问:
How to tell if a STEAM ID is taken using nodejs
I am trying to make a function that can tell me information about a steam page that I can use to tell if the profile was found or not, and perform an action accordingly.

What I came up with is the function below. This tells me a bunch of information about the page and I was hoping that when the steam profile is not found the status would be 404, but there is no difference between a profile that is found and one that isnt.

```<code>//GETHTML
function getURLInfo(url) {

   (fetch(url))
                            .then(res => console.log(res))
                            .then(body => console.log(body))

      }
</code>```

THIS IS THE CONSOLE OUTPUT

```<code>Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: Gunzip {
      _writeState: [Uint32Array],
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 6,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: true,
      allowHalfOpen: true,
      _transformState: [Object],
      _hadError: false,
      bytesWritten: 0,
      _handle: [Zlib],
      _outBuffer: <Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0d 0a 3c 68 74 6d 6c 20 63 6c 61 73 73 3d 22 20 72 65 73 70 6f 6e 73 69 76 65 22 20 6c 61 6e 67 3d 22 65 ... 16334 more bytes>,
      _outOffset: 0,
      _chunkSize: 16384,
      _defaultFlushFlag: 2,
      _finishFlushFlag: 2,
      _defaultFullFlushFlag: 3,
      _info: undefined,
      _level: -1,
      _strategy: 0,
      [Symbol(kCapture)]: false
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://steamcommunity.com/id/cmm9/',
    status: 200,
    statusText: 'OK',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}
</code>```

What I thought about trying is creating a function that makes the HTML of the page a long string, and then if the string includes 'Specified profile could not be found.' perform an action, but I don't know how I would do that. I need help on how to do this.

答:
What you should really be using is the Steam Web API. You can register for a key here: https://steamcommunity.com/dev/apikey

Here's a valid request: https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key={KEYGOESHERE}&format=json&steamids=76561198036370701

```<code>{
    "response": {
        "players": [
            {
                "steamid": "76561198036370701",
                "communityvisibilitystate": 3,
                "profilestate": 1,
                "personaname": "Heavenanvil",
                "commentpermission": 1,
                "profileurl": "https://steamcommunity.com/id/heavenanvil/",
                "avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d9/d9838736a062d18eb6848ba8d5cc56d72c1cef80.jpg",
                "avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d9/d9838736a062d18eb6848ba8d5cc56d72c1cef80_medium.jpg",
                "avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d9/d9838736a062d18eb6848ba8d5cc56d72c1cef80_full.jpg",
                "avatarhash": "d9838736a062d18eb6848ba8d5cc56d72c1cef80",
                "personastate": 0,
                "realname": "Heaven",
                "primaryclanid": "103582791433464576",
                "timecreated": 1294227386,
                "personastateflags": 0,
                "loccountrycode": "RU",
                "locstatecode": "39",
                "loccityid": 40975
            }
        ]
    }
}
</code>```

And when there's no matching steamIds, you get an empty respoonse.

```<code>{
    "response": {
        "players": []
    }
}
</code>```

More documentation on the API can be found here: https://partner.steamgames.com/doc/webapi_overview

Edit: If you want to check to see if there are any players that were returned, just check the response.players array.

fetch(url)
    .then(res => res.json())
    .then(json => {
        const { response } = json;
        if (response.players && response.players.length > 0) {
            // There are players that were found. Do something.
        } else {
            // No players found, do something else.
        }
    });

If you want to check using their VanityURL, you can use this endpoint: http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key={KEYGOESHERE}&format=json&vanityurl=Eclyps19

Success Response:

```<code>{
    "response": {
        "steamid": "76561197960670951",
        "success": 1
    }
}
</code>```

Not Found Respoonse:

```<code>{
    "response": {
        "success": 42,
        "message": "No match"
    }
}
</code>```

To check this for a success:

```<code>fetch(url)
    .then(res => res.json())
    .then(json => {
        const { response } = json;
        if (response.success === 1) {
            // Player found. Do something.
        } else {
            // No player found, do something else.
        }
    });
</code>```

Body:
I am trying to make a function that can tell me information about a steam page that I can use to tell if the profile was found or not, and perform an action accordingly.

What I came up with is the function below. This tells me a bunch of information about the page and I was hoping that when the steam profile is not found the status would be 404, but there is no difference between a profile that is found and one that isnt.

//GETHTML
function getURLInfo(url) {

   (fetch(url))
                            .then(res => console.log(res))
                            .then(body => console.log(body))

      }

THIS IS THE CONSOLE OUTPUT

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: Gunzip {
      _writeState: [Uint32Array],
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 6,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: true,
      allowHalfOpen: true,
      _transformState: [Object],
      _hadError: false,
      bytesWritten: 0,
      _handle: [Zlib],
      _outBuffer: <Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0d 0a 3c 68 74 6d 6c 20 63 6c 61 73 73 3d 22 20 72 65 73 70 6f 6e 73 69 76 65 22 20 6c 61 6e 67 3d 22 65 ... 16334 more bytes>,
      _outOffset: 0,
      _chunkSize: 16384,
      _defaultFlushFlag: 2,
      _finishFlushFlag: 2,
      _defaultFullFlushFlag: 3,
      _info: undefined,
      _level: -1,
      _strategy: 0,
      [Symbol(kCapture)]: false
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://steamcommunity.com/id/cmm9/',
    status: 200,
    statusText: 'OK',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

What I thought about trying is creating a function that makes the HTML of the page a long string, and then if the string includes 'Specified profile could not be found.' perform an action, but I don't know how I would do that. I need help on how to do this.

Body:
What you should really be using is the Steam Web API. You can register for a key here: https://steamcommunity.com/dev/apikey

Here's a valid request: https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key={KEYGOESHERE}&format=json&steamids=76561198036370701

{
    "response": {
        "players": [
            {
                "steamid": "76561198036370701",
                "communityvisibilitystate": 3,
                "profilestate": 1,
                "personaname": "Heavenanvil",
                "commentpermission": 1,
                "profileurl": "https://steamcommunity.com/id/heavenanvil/",
                "avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d9/d9838736a062d18eb6848ba8d5cc56d72c1cef80.jpg",
                "avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d9/d9838736a062d18eb6848ba8d5cc56d72c1cef80_medium.jpg",
                "avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d9/d9838736a062d18eb6848ba8d5cc56d72c1cef80_full.jpg",
                "avatarhash": "d9838736a062d18eb6848ba8d5cc56d72c1cef80",
                "personastate": 0,
                "realname": "Heaven",
                "primaryclanid": "103582791433464576",
                "timecreated": 1294227386,
                "personastateflags": 0,
                "loccountrycode": "RU",
                "locstatecode": "39",
                "loccityid": 40975
            }
        ]
    }
}

And when there's no matching steamIds, you get an empty respoonse.

{
    "response": {
        "players": []
    }
}

More documentation on the API can be found here: https://partner.steamgames.com/doc/webapi_overview

Edit: If you want to check to see if there are any players that were returned, just check the response.players array.

fetch(url)
    .then(res => res.json())
    .then(json => {
        const { response } = json;
        if (response.players && response.players.length > 0) {
            // There are players that were found. Do something.
        } else {
            // No players found, do something else.
        }
    });

If you want to check using their VanityURL, you can use this endpoint: http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key={KEYGOESHERE}&format=json&vanityurl=Eclyps19

Success Response:

{
    "response": {
        "steamid": "76561197960670951",
        "success": 1
    }
}

Not Found Respoonse:

{
    "response": {
        "success": 42,
        "message": "No match"
    }
}

To check this for a success:

fetch(url)
    .then(res => res.json())
    .then(json => {
        const { response } = json;
        if (response.success === 1) {
            // Player found. Do something.
        } else {
            // No player found, do something else.
        }
    });


来源: stackexchange

问:
What is the difference between np.linspace and np.arange?
I have always used np.arange. I recently came across np.linspace. I am wondering what exactly is the difference between them... Looking at their documentation:

np.arange:

Return evenly spaced values within a given interval.

np.linspace:

Return evenly spaced numbers over a specified interval.

The only difference I can see is linspace having more options... Like choosing to include the last element.

Which one of these two would you recommend and why? And in which cases is np.linspace superior?

答:
np.linspace allows you to define how many values you get including the specified min and max value. It infers the stepsize:

>>> np.linspace(0,1,11)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
```
<p><code>np.arange</code> allows you to define the stepsize and infers the number of steps(the number of values you get).</p>
<pre class="lang-py prettyprint-override"><code>>>> np.arange(0,1,.1)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
</code>```

contributions from user2357112:

np.arange excludes the maximum value unless rounding error makes it do otherwise.

For example, the following results occur due to rounding error:

>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
```
<p>You can exclude the <code>stop</code> value (in our case 1.3) using <code>endpoint=False</code>:</p>
<pre class="lang-py prettyprint-override"><code>>>> numpy.linspace(1, 1.3, 3, endpoint=False)
array([1. , 1.1, 1.2])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
np.linspace allows you to define how many values you get including the specified min and max value. It infers the stepsize:

>>> np.linspace(0,1,11)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])

np.arange allows you to define the stepsize and infers the number of steps(the number of values you get).

>>> np.arange(0,1,.1)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])

contributions from user2357112:

np.arange excludes the maximum value unless rounding error makes it do otherwise.

For example, the following results occur due to rounding error:

>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])

You can exclude the stop value (in our case 1.3) using endpoint=False:

>>> numpy.linspace(1, 1.3, 3, endpoint=False)
array([1. , 1.1, 1.2])


问:
Problem on installing metview package on Anaconda
I am trying to install Metview package through its installation page:

https://anaconda.org/conda-forge/metview

using the code: conda install -c conda-forge metview

I encounter this problem:

```<code>(base) C:\Users\Saeed>conda install -c conda-forge metview
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

  - metview

Current channels:

      - https://conda.anaconda.org/conda-forge/win-64
      - https://conda.anaconda.org/conda-forge/noarch
      - https://repo.anaconda.com/pkgs/main/win-64
      - https://repo.anaconda.com/pkgs/main/noarch
      - https://repo.anaconda.com/pkgs/r/win-64
      - https://repo.anaconda.com/pkgs/r/noarch
      - https://repo.anaconda.com/pkgs/msys2/win-64
      - https://repo.anaconda.com/pkgs/msys2/noarch
      - https://conda.anaconda.org/conda-canary/win-64

  - https://conda.anaconda.org/conda-canary/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.
</code>```

I am using Anaconda and tried to use the Anaconda prompt.

Thank you in advance for your help.

答: The metview package at conda-forge is only built for osx-64 and linux-64. Looks like you're on win-64 system. Try installing with pip install metview. If unsuccessful you'll have to build from source.

Body:
I am trying to install Metview package through its installation page:

https://anaconda.org/conda-forge/metview

using the code: conda install -c conda-forge metview

I encounter this problem:

(base) C:\Users\Saeed>conda install -c conda-forge metview
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

PackagesNotFoundError: The following packages are not available from current channels:

  - metview

Current channels:

      - https://conda.anaconda.org/conda-forge/win-64
      - https://conda.anaconda.org/conda-forge/noarch
      - https://repo.anaconda.com/pkgs/main/win-64
      - https://repo.anaconda.com/pkgs/main/noarch
      - https://repo.anaconda.com/pkgs/r/win-64
      - https://repo.anaconda.com/pkgs/r/noarch
      - https://repo.anaconda.com/pkgs/msys2/win-64
      - https://repo.anaconda.com/pkgs/msys2/noarch
      - https://conda.anaconda.org/conda-canary/win-64

  - https://conda.anaconda.org/conda-canary/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

I am using Anaconda and tried to use the Anaconda prompt.

Thank you in advance for your help.


问:
Validate Regex: min/max characters, one hypen and start/finish conditions
I am trying to create a validation function for usernames.  It must be:

Min six characters / Max 16 characters

Only letters, numbers and, at the most, one hyphen

It must start with a letter and no end with a hyphen

I came up with this regular expression:

```<code>^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$
</code>```

Which does everything but the maximum number of characters.  What am I missing?

You may wonder why I am using 4 to 14: it is because the first and last characters are already defined by the other conditions, so I need the rest to be at least 4 (to make it to six) and at most 14 characters (to make it to 16).

This is a simple validation function in Python:

```<code># Username validation
import re

def validate(username):
    regex = re.compile('^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$', re.I)
    match = regex.match(str(username))
    return bool(match)

print(validate("PeterParker")) #Valid username
print(validate("Peter-Parker")) #Valid username
print(validate("Peter-P-arker")) #Invalid username
print(validate("Peter")) #Invalid username
print(validate("PeterParker-")) #Invalid username
print(validate("-PeterParker")) #Invalid username
print(validate("1PeterParker")) #Invalid username
print(validate("Peter Parker")) #Invalid username
print(validate("PeterParkerSpiderMan")) #Invalid username
</code>```

Thanks very much for any suggestion.

答:
I used for loops to build the entire hypen and alphabet combinations, pretty brute force. I'd say using a length check in code is much cleaner. If you want the expression you can use just print it before compiling.

```<code># Username validation
import re

def validate(username):
    print(username)
    hypen = []
    for length in range(4,14+1):
        for i in range(length):
            hypen.append("[A-Za-z]{{{}}}-[A-Za-z]{{{}}}".format(i,length-i-1))
    expression = '^([A-Za-z]([A-Za-z]{{4,14}}|{})[A-Za-z0-9])$'.format("|".join(hypen))
    regex = re.compile(expression, re.I)
    match = regex.match(str(username))
    return bool(match)

print(validate("PeterParker")) #Valid username
print(validate("Peter-Parker")) #Valid username
print(validate("Peter-P-arker")) #Invalid username
print(validate("Peter")) #Invalid username
print(validate("PeterParker-")) #Valid username
print(validate("-PeterParker")) #Invalid username
print(validate("1PeterParker")) #Invalid username
print(validate("Peter Parker")) #Invalid username
print(validate("PeterParkerSpiderMan")) #Invalid username
</code>```

OUTPUT

```<code>PeterParker
True
Peter-Parker
True
Peter-P-arker
False
Peter
False
PeterParker-
False
-PeterParker
False
1PeterParker
False
Peter Parker
False
PeterParkerSpiderMan
False
</code>```

Body:
I am trying to create a validation function for usernames.  It must be:

Min six characters / Max 16 characters

Only letters, numbers and, at the most, one hyphen

It must start with a letter and no end with a hyphen

I came up with this regular expression:

^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$

Which does everything but the maximum number of characters.  What am I missing?

You may wonder why I am using 4 to 14: it is because the first and last characters are already defined by the other conditions, so I need the rest to be at least 4 (to make it to six) and at most 14 characters (to make it to 16).

This is a simple validation function in Python:

# Username validation
import re

def validate(username):
    regex = re.compile('^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$', re.I)
    match = regex.match(str(username))
    return bool(match)

print(validate("PeterParker")) #Valid username
print(validate("Peter-Parker")) #Valid username
print(validate("Peter-P-arker")) #Invalid username
print(validate("Peter")) #Invalid username
print(validate("PeterParker-")) #Invalid username
print(validate("-PeterParker")) #Invalid username
print(validate("1PeterParker")) #Invalid username
print(validate("Peter Parker")) #Invalid username
print(validate("PeterParkerSpiderMan")) #Invalid username

Thanks very much for any suggestion.

Body:
I used for loops to build the entire hypen and alphabet combinations, pretty brute force. I'd say using a length check in code is much cleaner. If you want the expression you can use just print it before compiling.

# Username validation
import re

def validate(username):
    print(username)
    hypen = []
    for length in range(4,14+1):
        for i in range(length):
            hypen.append("[A-Za-z]{{{}}}-[A-Za-z]{{{}}}".format(i,length-i-1))
    expression = '^([A-Za-z]([A-Za-z]{{4,14}}|{})[A-Za-z0-9])$'.format("|".join(hypen))
    regex = re.compile(expression, re.I)
    match = regex.match(str(username))
    return bool(match)

print(validate("PeterParker")) #Valid username
print(validate("Peter-Parker")) #Valid username
print(validate("Peter-P-arker")) #Invalid username
print(validate("Peter")) #Invalid username
print(validate("PeterParker-")) #Valid username
print(validate("-PeterParker")) #Invalid username
print(validate("1PeterParker")) #Invalid username
print(validate("Peter Parker")) #Invalid username
print(validate("PeterParkerSpiderMan")) #Invalid username

OUTPUT

PeterParker
True
Peter-Parker
True
Peter-P-arker
False
Peter
False
PeterParker-
False
-PeterParker
False
1PeterParker
False
Peter Parker
False
PeterParkerSpiderMan
False


问:
Any way to produce route values instead of query arguments when submitting a form?
I have the following form.

```<code><form method="get">
    <div class="row">
        <div class="col-md-4">
            <div class="form-group">
                <select asp-for="@Model.MonthCode" asp-items="@Model.InvoiceDates" class="form-control">
                </select>
            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                <button type="submit" class="btn btn-success">Update</button>
            </div>
        </div>
    </div>
</form>
</code>```

I'm using the get method (instead of post) because I don't want to have to duplicate all my OnGetAsync() logic in OnPostAsync(). The two methods would do exactly the same thing. This way, I don't need OnPostAsync().

However, the downside is that the data is passed as a query argument.

```<code>https://localhost:44322/Invoices?MonthCode=24243
</code>```

And I would much prefer the URL:

```<code>https://localhost:44322/Invoices/24243
</code>```

Is there any way to have this code produce the second URL? I prefer my users don't get a description of what the arguments are.

答:
It feels like the cleaner solution might be to extract the code from OnGetAsync() into a helper method and then just call that method from OnPostAsync().

Unless the implementation of OnGetAsync() is trivially small, Id generally avoid putting too much logic into the pages. (We tried that back in the day with web forms (.aspx pages) and it did not end well! ;-))

Body:
I have the following form.

<form method="get">

                <select asp-for="@Model.MonthCode" asp-items="@Model.InvoiceDates" class="form-control">
                </select>

                <button type="submit" class="btn btn-success">Update</button>

</form>

I'm using the get method (instead of post) because I don't want to have to duplicate all my OnGetAsync() logic in OnPostAsync(). The two methods would do exactly the same thing. This way, I don't need OnPostAsync().

However, the downside is that the data is passed as a query argument.

https://localhost:44322/Invoices?MonthCode=24243

And I would much prefer the URL:

https://localhost:44322/Invoices/24243

Is there any way to have this code produce the second URL? I prefer my users don't get a description of what the arguments are.


问:
How to Retrieve data from selected ListBox?
In C#.Net ,I'm trying to retrieve data from selected ListBox.

Eg. First I displayed many data in ListBox that retrieved from MSSQL 2008 Database.
    When i select single data from that listbox , i want to show that selected data into textbox...
How can i do that?
I need yours answers because i'm just beginner ,
Please answer me if you know..
Thanks

答:
Trap the ListBox SelectedIndexChanged event, for example you can do,

```<code>private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    textBox1.Text = listBox1.SelectedItem.ToString(); //let textBox1 be your TextBox name and listBox1 be your ListBox name
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Trap the ListBox SelectedIndexChanged event, for example you can do,

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    textBox1.Text = listBox1.SelectedItem.ToString(); //let textBox1 be your TextBox name and listBox1 be your ListBox name
}


问:
Longest subset of five-positions five-elements permutations, only one-element-position in common
I am trying to get the longest list of a set of five ordered position, 1 to 5 each, satisfying the condition that any two members of the list cannot share more than one identical position (index). I.e., 11111 and 12222 is permitted (only the 1 at index 0 is shared), but 11111 and 11222 is not permitted (same value at index 0 and 1).

I have tried a brute-force attack, starting with the complete list of permutations, 3125 members, and walking through the list element by element, rejecting the ones that do not match the criteria, in several steps:

step one: testing elements 2 to 3125 against element 1, getting a new shorter list L'

step one: testing elements 3 to N' against element 2', getting a shorter list yet L'',

and so on.

I get a 17 members solution, perfectly valid. The problem is that:

I know there are, at least, two 25-member valid solution found by a matter of good luck,

The solution by this brute-force method depends strongly on the initial order of the 3125 members list, so I have been able to find from 12- to 21-member solutions, shuffling the L0 list, but I have never hit the 25-member solutions.

Could anyone please put light on the problem? Thank you.

This is my approach so far

```<code>import csv, random

maxv = 0
soln=0

for p in range(0,1): #Intended to run multiple times

    z = -1

    while True:

        z = z + 1

        file1 = 'Step' + "%02d" % (z+0) + '.csv'
        file2 = 'Step' + "%02d" % (z+1) + '.csv'

        nextdata=[]

        with open(file1, 'r') as csv_file:
            data = list(csv.reader(csv_file))

        #if file1 == 'Step00.csv':  # related to p loop
        #    random.shuffle(data)

        i = 0
        while i <= z:
            nextdata.append(data[i])
            i = i + 1

        for j in range(z, len(data)):

            sum=0
            for k in range(0,5):

                if (data[z][k] == data[j][k]):
                    sum = sum + 1

            if sum < 2:
                nextdata.append(data[j])

        ofile = open(file2, 'wb')
        writer = csv.writer(ofile)
        writer.writerows(nextdata)
        ofile.close()

        if (len(nextdata) < z + 1 + 1):
            if (z+1)>= maxv:
                maxv = z+1
                print maxv
                ofile = open("Solution"+"%02d" % soln + '.csv', 'wb')
                writer = csv.writer(ofile)
                writer.writerows(nextdata)
                ofile.close()
            soln = soln + 1
            break
</code>```

答:
Here is a Picat model for the problem (as I understand it): http://hakank.org/picat/longest_subset_of_five_positions.pi It use constraint modelling and SAT solver.

Edit: Here is a MiniZinc model: http://hakank.org/minizinc/longest_subset_of_five_positions.mzn

The model (predicate go/0) check lengths of 2 to 100. All lengths between 2 and 25 has at least one solution (probably at lot more). So 25 is the longest sub sequence. Here is one 25 length solution:

```<code>{1,1,1,3,4}
{1,2,5,1,5}
{1,3,4,4,1}
{1,4,2,2,2}
{1,5,3,5,3}
{2,1,3,2,1}
{2,2,4,5,4}
{2,3,2,1,3}
{2,4,1,4,5}
{2,5,5,3,2}
{3,1,2,5,5}
{3,2,3,4,2}
{3,3,5,2,4}
{3,4,4,3,3}
{3,5,1,1,1}
{4,1,4,1,2}
{4,2,1,2,3}
{4,3,3,3,5}
{4,4,5,5,1}
{4,5,2,4,4}
{5,1,5,4,3}
{5,2,2,3,1}
{5,3,1,5,2}
{5,4,3,1,4}
{5,5,4,2,5}
</code>```

There is a lot of different 25 lengths solutions (the predicate go2/0 checks that).

Here is the complete model (edited from the file above):

```<code>import sat.
main => go.

%
% Test all lengths from 2..100.
% 25 is the longest.
%
go ?=>
  nolog,
  foreach(M in 2..100)
  println(check=M),
  if once(check(M,_X)) then
    println(M=ok)
  else
    println(M=not_ok)
  end,
  nl
end,
nl.

go => true.

%
% Check if there is a solution with M numbers
%
check(M, X) =>
  N = 5,
  X = new_array(M,N),
  X :: 1..5,

  foreach(I in 1..M, J in I+1..M)
    % at most 1 same number in the same position
    sum([X[I,K] #= X[J,K] : K in 1..N]) #<= 1,
    % symmetry breaking: sort the sub sequence
    lex_lt(X[I],X[J])
  end,

 solve([ff,split],X),

 foreach(Row in X)
   println(Row)
 end,
 nl.
</code>```

Body:
I am trying to get the longest list of a set of five ordered position, 1 to 5 each, satisfying the condition that any two members of the list cannot share more than one identical position (index). I.e., 11111 and 12222 is permitted (only the 1 at index 0 is shared), but 11111 and 11222 is not permitted (same value at index 0 and 1).

I have tried a brute-force attack, starting with the complete list of permutations, 3125 members, and walking through the list element by element, rejecting the ones that do not match the criteria, in several steps:

step one: testing elements 2 to 3125 against element 1, getting a new shorter list L'

step one: testing elements 3 to N' against element 2', getting a shorter list yet L'',

and so on.

I get a 17 members solution, perfectly valid. The problem is that:

I know there are, at least, two 25-member valid solution found by a matter of good luck,

The solution by this brute-force method depends strongly on the initial order of the 3125 members list, so I have been able to find from 12- to 21-member solutions, shuffling the L0 list, but I have never hit the 25-member solutions.

Could anyone please put light on the problem? Thank you.

This is my approach so far

import csv, random

maxv = 0
soln=0

for p in range(0,1): #Intended to run multiple times

    z = -1

    while True:

        z = z + 1

        file1 = 'Step' + "%02d" % (z+0) + '.csv'
        file2 = 'Step' + "%02d" % (z+1) + '.csv'

        nextdata=[]

        with open(file1, 'r') as csv_file:
            data = list(csv.reader(csv_file))

        #if file1 == 'Step00.csv':  # related to p loop
        #    random.shuffle(data)

        i = 0
        while i <= z:
            nextdata.append(data[i])
            i = i + 1

        for j in range(z, len(data)):

            sum=0
            for k in range(0,5):

                if (data[z][k] == data[j][k]):
                    sum = sum + 1

            if sum < 2:
                nextdata.append(data[j])

        ofile = open(file2, 'wb')
        writer = csv.writer(ofile)
        writer.writerows(nextdata)
        ofile.close()

        if (len(nextdata) < z + 1 + 1):
            if (z+1)>= maxv:
                maxv = z+1
                print maxv
                ofile = open("Solution"+"%02d" % soln + '.csv', 'wb')
                writer = csv.writer(ofile)
                writer.writerows(nextdata)
                ofile.close()
            soln = soln + 1
            break

Body:
Here is a Picat model for the problem (as I understand it): http://hakank.org/picat/longest_subset_of_five_positions.pi It use constraint modelling and SAT solver.

Edit: Here is a MiniZinc model: http://hakank.org/minizinc/longest_subset_of_five_positions.mzn

The model (predicate go/0) check lengths of 2 to 100. All lengths between 2 and 25 has at least one solution (probably at lot more). So 25 is the longest sub sequence. Here is one 25 length solution:

{1,1,1,3,4}
{1,2,5,1,5}
{1,3,4,4,1}
{1,4,2,2,2}
{1,5,3,5,3}
{2,1,3,2,1}
{2,2,4,5,4}
{2,3,2,1,3}
{2,4,1,4,5}
{2,5,5,3,2}
{3,1,2,5,5}
{3,2,3,4,2}
{3,3,5,2,4}
{3,4,4,3,3}
{3,5,1,1,1}
{4,1,4,1,2}
{4,2,1,2,3}
{4,3,3,3,5}
{4,4,5,5,1}
{4,5,2,4,4}
{5,1,5,4,3}
{5,2,2,3,1}
{5,3,1,5,2}
{5,4,3,1,4}
{5,5,4,2,5}

There is a lot of different 25 lengths solutions (the predicate go2/0 checks that).

Here is the complete model (edited from the file above):

import sat.
main => go.

%
% Test all lengths from 2..100.
% 25 is the longest.
%
go ?=>
  nolog,
  foreach(M in 2..100)
  println(check=M),
  if once(check(M,_X)) then
    println(M=ok)
  else
    println(M=not_ok)
  end,
  nl
end,
nl.

go => true.

%
% Check if there is a solution with M numbers
%
check(M, X) =>
  N = 5,
  X = new_array(M,N),
  X :: 1..5,

  foreach(I in 1..M, J in I+1..M)
    % at most 1 same number in the same position
    sum([X[I,K] #= X[J,K] : K in 1..N]) #<= 1,
    % symmetry breaking: sort the sub sequence
    lex_lt(X[I],X[J])
  end,

 solve([ff,split],X),

 foreach(Row in X)
   println(Row)
 end,
 nl.


问:
App crashes and failed to bind $PORT 60 seconds
I have the problem of my app in Heroku, my set up is Nginx, Docker and Php, and a simple Php script. after issuing release command in Heroku CLI and open the app, my app launches in browser but it crashes.

here is the log.

```<code>2020-05-30T15:46:38.733789+00:00 heroku[web.1]: State changed from crashed to starting
2020-05-30T15:46:51.620126+00:00 heroku[web.1]: Starting process with command `nginx -g daemon\ off\;`
2020-05-30T15:47:52.178537+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2020-05-30T15:47:52.210903+00:00 heroku[web.1]: Stopping process with SIGKILL
2020-05-30T15:47:52.317640+00:00 heroku[web.1]: Process exited with status 137
2020-05-30T15:47:52.373907+00:00 heroku[web.1]: State changed from starting to crashed
</code>```

Dockerfile

```<code>FROM  ubuntu:latest

RUN apt-get update \
    && apt-get install -y curl zip unzip  \
            php7.4 php7.4-fpm \
            nginx

COPY ./webapp /var/www/myapp

WORKDIR /var/www/myapp

# ADD default.conf /etc/nginx/conf.d/default.conf

COPY default.conf.template /etc/nginx/conf.d/default.conf.template
COPY nginx.conf /etc/nginx/nginx.conf

# for ubuntu
RUN useradd -m myuser
USER myuser

CMD /bin/bash -c "envsubst '\$PORT' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'
</code>```

UPDATE

After adding port as what suggested in the comment, now new error occurs

/bin/bash: envsubst: command not found

答:
As mentioned in your Dockerfile for CMD, you are $PORT and you have to pass that environment variable in your Dockerfile or while running the container.

```<code>CMD /bin/bash -c "envsubst '\$PORT' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'
</code>```

If you want to supply in Dockerfile,

```<code>FROM  ubuntu:latest
ENV PORT=80 # Add this line
...
...
CMD /bin/bash -c "envsubst '\$PORT' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'
</code>```

or If you want to override at runtime, pass it with docker run command

```<code>docker run -e PORT=8008 imageName
</code>```

Body:
I have the problem of my app in Heroku, my set up is Nginx, Docker and Php, and a simple Php script. after issuing release command in Heroku CLI and open the app, my app launches in browser but it crashes.

here is the log.

2020-05-30T15:46:38.733789+00:00 heroku[web.1]: State changed from crashed to starting
2020-05-30T15:46:51.620126+00:00 heroku[web.1]: Starting process with command `nginx -g daemon\ off\;`
2020-05-30T15:47:52.178537+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2020-05-30T15:47:52.210903+00:00 heroku[web.1]: Stopping process with SIGKILL
2020-05-30T15:47:52.317640+00:00 heroku[web.1]: Process exited with status 137
2020-05-30T15:47:52.373907+00:00 heroku[web.1]: State changed from starting to crashed

Dockerfile

FROM  ubuntu:latest

RUN apt-get update \
    && apt-get install -y curl zip unzip  \
            php7.4 php7.4-fpm \
            nginx

COPY ./webapp /var/www/myapp

WORKDIR /var/www/myapp

# ADD default.conf /etc/nginx/conf.d/default.conf

COPY default.conf.template /etc/nginx/conf.d/default.conf.template
COPY nginx.conf /etc/nginx/nginx.conf

# for ubuntu
RUN useradd -m myuser
USER myuser

CMD /bin/bash -c "envsubst '\$PORT' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'

UPDATE

After adding port as what suggested in the comment, now new error occurs

/bin/bash: envsubst: command not found

Body:
As mentioned in your Dockerfile for CMD, you are $PORT and you have to pass that environment variable in your Dockerfile or while running the container.

CMD /bin/bash -c "envsubst '\$PORT' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'

If you want to supply in Dockerfile,

FROM  ubuntu:latest
ENV PORT=80 # Add this line
...
...
CMD /bin/bash -c "envsubst '\$PORT' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'

or If you want to override at runtime, pass it with docker run command

docker run -e PORT=8008 imageName


问:
How to remove text content of span when ajax response is same for 5 seconds
I have written ajax which gets called every second using setInterval() function.

I want to use the ajax response to set text content of a span using innerText.

ajax is getting called every second and is receiving response data from URL.

When data from response remains unchanged for 5 seconds, I want the text content of span tag to be removed.

How can I put condition in ajax call to check if data from response is unchanged for 5 seconds?

```<code>setInterval(function() {
      $.ajax({
          type: "POST",

          url: "/data",  // URL to your view that serves new info

      })
      .done(function(data) {
         console.log(data);
      });
}, 1000)
</code>```

Any suggestion will be appreciated.
Thank you in advance.

答:
Try something like this:</p>

```<code>var i = 0;
var prevValue = null;

setInterval(function() {
      $.ajax({
          type: "POST",

          url: "/data",  // URL to your view that serves new info

      })
      .done(function(data) {
         console.log(data);
         if (prevValue === null) {
             prevValue = data;       //set initial value on first call
         } else {
            if (data == prevValue) {      //check if data is the same
                i++;                      //add 1 to counter
                if(i == 5) {              //if counter reaches 5
                    $('span').text('');   //hide span text
                }
            } else {                      //if data is not same
                i = 0;                    //reset counter
            }
         }
      });
}, 1000)
</code>```

Body:
I have written ajax which gets called every second using setInterval() function.

I want to use the ajax response to set text content of a span using innerText.

ajax is getting called every second and is receiving response data from URL.

When data from response remains unchanged for 5 seconds, I want the text content of span tag to be removed.

How can I put condition in ajax call to check if data from response is unchanged for 5 seconds?

setInterval(function() {
      $.ajax({
          type: "POST",

          url: "/data",  // URL to your view that serves new info

      })
      .done(function(data) {
         console.log(data);
      });
}, 1000)

Any suggestion will be appreciated.
Thank you in advance.

Body:
Try something like this:

var i = 0;
var prevValue = null;

setInterval(function() {
      $.ajax({
          type: "POST",

          url: "/data",  // URL to your view that serves new info

      })
      .done(function(data) {
         console.log(data);
         if (prevValue === null) {
             prevValue = data;       //set initial value on first call
         } else {
            if (data == prevValue) {      //check if data is the same
                i++;                      //add 1 to counter
                if(i == 5) {              //if counter reaches 5
                    $('span').text('');   //hide span text
                }
            } else {                      //if data is not same
                i = 0;                    //reset counter
            }
         }
      });
}, 1000)


问:
Sum of numbers in array, not counting 13 and number directly after it (CodingBat puzzle)
The Question:

Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.

My Code:

```<code>def sum13(nums):
  l = len(nums)
  tot = 0

  if l==0:
    return 0

  for x in range(l):
    if nums[x]!=13:
      if nums[x-1]!=13:
        tot+=nums[x]

  return tot
</code>```

Where It's Failing:

```<code>sum13([1, 2, 2, 1, 13]) should → 6, but my code is outputting 5
sum13([1, 2, 13, 2, 1, 13]) should → 4, but my code is outputting 3
</code>```

答:
```<code>def sum13(nums):
    li=[]
    if nums[-1]==13:
        li.append(13)
    for i in range(len(nums)-1):
        if nums[i]==13:
            li.append(nums[i])
            li.append(nums[i+1])
    n=sum(nums)
    return (n-sum(li))
</code>```

Body:
The Question:

Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.

My Code:

def sum13(nums):
  l = len(nums)
  tot = 0

  if l==0:
    return 0

  for x in range(l):
    if nums[x]!=13:
      if nums[x-1]!=13:
        tot+=nums[x]

  return tot

Where It's Failing:

sum13([1, 2, 2, 1, 13]) should → 6, but my code is outputting 5
sum13([1, 2, 13, 2, 1, 13]) should → 4, but my code is outputting 3


问:
How to create red header while recording in an app
In the default Voice Recording app on the iPhone, starting to record turns the iPhone header red and starts a timer.  Is this something that we can reproduce in an app, or perhaps this is behavior that always happens when recording sound?</p>

答:
Also, try this one....

Tweetbot-Like Alert Panels (Blog), and the repository is MKInfoPanelDemo at Github.

ContentLicense: CC BY-SA 2.5


问:
How does the clip-path: ellipse property work?
In this documentation:

https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path

The clip-path property used like

clip-path: ellipse(150px 160px at 100px 200px)

does work to cut an ellipse at the bottom of the div, but I want to cut an ellipse at the top of the div. How can I do that? And what if I want to cut a concave ellipse and not a convex one?

答:
to make short : placement is set from the middle of the shape

and values can be seen like :

```<code>clip-path: ellipse(width height at left top )
</code>```

If you set a shape at 0 0 you will only see a quart of it the bottom and right part of it from the center of the shape .

html {
  background:white;
}
body {
  background:black;
  height:100vh;
  clip-path: ellipse(150px 160px at 0 0);
}```
</div>
</div>
</p>

<p>with vh/vw value you can do   something alike :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  background:white;
}
body {
  background:black;
  height:100vh;
  clip-path: ellipse(25vw 25vh at 50vw 50vh );
}</code>```

Does this make it easier ?

Body:
to make short : placement is set from the middle of the shape

and values can be seen like :

clip-path: ellipse(width height at left top )

If you set a shape at 0 0 you will only see a quart of it the bottom and right part of it from the center of the shape .

html {
  background:white;
}
body {
  background:black;
  height:100vh;
  clip-path: ellipse(150px 160px at 0 0);
}

with vh/vw value you can do   something alike :

html {
  background:white;
}
body {
  background:black;
  height:100vh;
  clip-path: ellipse(25vw 25vh at 50vw 50vh );
}

Does this make it easier ?


答:
Record the time and the data whenever the data changes.

let dataRecord = {
  time: 0,
  data: null
};

...

let dataChanged = (d1, d2) => {
    /* compare d1 & d2, return true if different */
}

.done(function(data) {
  let nowTime = new Date().getTime();

  if (dataChanged(data, dataRecord.data)) {
    dataRecord = {
      time: nowTime,
      data
    };

    // update your span content here

  } else if (nowTime - dataRecord.time > 5000) {

    // remove your span content here

  }
});
```

Title: How to remove text content of span when ajax response is same for 5 seconds


问:
Processing errorsmessages
I want to create a Javacode in processing with a simple square who can be moved by pressing A,W,S and D so i wrote a code to do so but I keep getting errormessages. I was wondering if i could get help to fix the errors.

```<code>public void setup() {

  k = new karaktar();

  background (#F5CD0C);
  size( 800, 800 );
  strokeWeight( 20 );
  frameRate( 24 );

}

int lastKey = 0;
int lastKey2 =0;
void keyPressed() {
  if (lastKey != key) {
    lastKey = key;
    k.move();

  }
}

boolean start = false;
//draw
void draw() {
      start = true;

}

</code>```

```<code>class karaktar {

  float x = 400;
  float y = 500;

  boolean alreadypressed = false;

  float xF = x;
  float yF = y-100;
  float xFF = 0;
  float yFF = 0;

  int h1 = 50;
  int w1 = 50;
  int hF = h1;
  int wF = w1;
  float wFF = 0;
  float hFF = 0;

  }

  void move() {

    if (keyPressed) {
       if (key == 'w' || key == 'W') {

        y -= 50;
        yF -=50;
      }
    }
    if (keyPressed) {
      if (key == 'a' || key == 'A') {

        x -= 50;
        xF -= 50;
      }
    }
    if (keyPressed) {
      if (key == 's' || key == 'S') {

        y += 50;
        yF += 50;
      }
    }
    if (keyPressed) {
      if (key == 'd' || key == 'D') {

        x += 50;
        xF +=50;
      }
    }

}

</code>```

The first code is meant to be the playingfield and the second is for the moving square.

答:
Looking at what you've posted, you're likely referencing something somewhere that doesn't exist:

k = new karaktar(); only works if the variable k is declared somewhere with a line like karaktar k;.

background(#F5CD0C); the method background must exist, and it looks like you are trying to pass in a hexadecimal number.  In Java, hex numbers are identified by 0x, not #.  I imagine that line should be background(0xF5CD0C);

size(800, 800); The method size also has to exist.

strokeWeight(20); ditto, must exist somewhere.

frameRate(24); ditto

if (lastKey != key) { variable key must be declared somewhere, presumably an int to compare to lastKey.

k.move(); again, k must be declared somewhere.

In your class karaktar, variables keyPressed and key were not declared, and you had unbalanced curly braces.  Below I have fixed the curly braces, but not the variable declarations (in case you aren't showing the code where they are defined):

```<code>class karaktar {
  float x = 400;
  float y = 500;

  boolean alreadypressed = false;

  float xF = x;
  float yF = y-100;
  float xFF = 0;
  float yFF = 0;

  int h1 = 50;
  int w1 = 50;
  int hF = h1;
  int wF = w1;
  float wFF = 0;
  float hFF = 0;

  void move() {
    if (keyPressed) {
       if (key == 'w' || key == 'W') {

        y -= 50;
        yF -=50;
      }
    }

    if (keyPressed) {
      if (key == 'a' || key == 'A') {

        x -= 50;
        xF -= 50;
      }
    }

    if (keyPressed) {
      if (key == 's' || key == 'S') {

        y += 50;
        yF += 50;
      }
    }

    if (keyPressed) {
      if (key == 'd' || key == 'D') {

        x += 50;
        xF +=50;
      }
    }
  }
}
</code>```

Title: Processing errorsmessages

Body:
I want to create a Javacode in processing with a simple square who can be moved by pressing A,W,S and D so i wrote a code to do so but I keep getting errormessages. I was wondering if i could get help to fix the errors.

public void setup() {

  k = new karaktar();

  background (#F5CD0C);
  size( 800, 800 );
  strokeWeight( 20 );
  frameRate( 24 );

}

int lastKey = 0;
int lastKey2 =0;
void keyPressed() {
  if (lastKey != key) {
    lastKey = key;
    k.move();

  }
}

boolean start = false;
//draw
void draw() {
      start = true;

}

class karaktar {

  float x = 400;
  float y = 500;

  boolean alreadypressed = false;

  float xF = x;
  float yF = y-100;
  float xFF = 0;
  float yFF = 0;

  int h1 = 50;
  int w1 = 50;
  int hF = h1;
  int wF = w1;
  float wFF = 0;
  float hFF = 0;

  }

  void move() {

    if (keyPressed) {
       if (key == 'w' || key == 'W') {

        y -= 50;
        yF -=50;
      }
    }
    if (keyPressed) {
      if (key == 'a' || key == 'A') {

        x -= 50;
        xF -= 50;
      }
    }
    if (keyPressed) {
      if (key == 's' || key == 'S') {

        y += 50;
        yF += 50;
      }
    }
    if (keyPressed) {
      if (key == 'd' || key == 'D') {

        x += 50;
        xF +=50;
      }
    }

}

The first code is meant to be the playingfield and the second is for the moving square.

Body:
Looking at what you've posted, you're likely referencing something somewhere that doesn't exist:

k = new karaktar(); only works if the variable k is declared somewhere with a line like karaktar k;.

background(#F5CD0C); the method background must exist, and it looks like you are trying to pass in a hexadecimal number.  In Java, hex numbers are identified by 0x, not #.  I imagine that line should be background(0xF5CD0C);

size(800, 800); The method size also has to exist.

strokeWeight(20); ditto, must exist somewhere.

frameRate(24); ditto

if (lastKey != key) { variable key must be declared somewhere, presumably an int to compare to lastKey.

k.move(); again, k must be declared somewhere.

In your class karaktar, variables keyPressed and key were not declared, and you had unbalanced curly braces.  Below I have fixed the curly braces, but not the variable declarations (in case you aren't showing the code where they are defined):

class karaktar {
  float x = 400;
  float y = 500;

  boolean alreadypressed = false;

  float xF = x;
  float yF = y-100;
  float xFF = 0;
  float yFF = 0;

  int h1 = 50;
  int w1 = 50;
  int hF = h1;
  int wF = w1;
  float wFF = 0;
  float hFF = 0;

  void move() {
    if (keyPressed) {
       if (key == 'w' || key == 'W') {

        y -= 50;
        yF -=50;
      }
    }

    if (keyPressed) {
      if (key == 'a' || key == 'A') {

        x -= 50;
        xF -= 50;
      }
    }

    if (keyPressed) {
      if (key == 's' || key == 'S') {

        y += 50;
        yF += 50;
      }
    }

    if (keyPressed) {
      if (key == 'd' || key == 'D') {

        x += 50;
        xF +=50;
      }
    }
  }
}


问:
Hackerearth policeman and theives problem
I am trying to solve the Policeman and Theives problem in Hackeearth website. I am able to reduce the time complexity but three test cases are failing. There seems to be a bug in the solution which causes a small mismatch. I am struggling to find the error for weeks. Below are the problem statement and my code,

Policeman and Thieves Problem statement:

You are given a grid of size  that has the following specifications:

Each cell in the grid contains either a policeman or a thief.

A policeman can only catch a thief if both of them are in the same row.

Each policeman can only catch one thief.

A policeman cannot catch a thief who is more than K units away from the policeman.
Write a program to find the maximum number of thieves that can be caught in the grid.

Input format

First line: T (number of test cases)

For each test case,

First-line contains Two space-separated integers N and K

Next N lines contain N space-separated characters (denoting each cell in the grid)

Output format

For each test case, print the maximum number of thieves that can be caught in the grid.

My code:

```<code>import java.io.*;
import java.util.*;

public class TestClass {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wr = new PrintWriter(System.out);
        int T = Integer.parseInt(br.readLine().trim());
        for(int t_i=0; t_i<T; t_i++)
        {
            String[] line = br.readLine().split(" ");
            int N = Integer.parseInt(line[0]);
            int K = Integer.parseInt(line[1]);
            char[][] A = new char[N][N];
            for(int i_A=0; i_A<N; i_A++)
            {
                String[] arr_A = br.readLine().split(" ");
                for(int j_A=0; j_A<arr_A.length; j_A++)
                {
                    A[i_A][j_A] = arr_A[j_A].charAt(0);
                }
            }

            int out_ = solution(A, K);
            System.out.println(out_);
            System.out.println("");
        }

        wr.close();
        br.close();
    }
    static int solution(char[][] A, int K){
        int count = 0;
        for(int i=0;i<A.length;i++){
            for(int j=0;j<A[i].length;j++){
                if(A[i][j]=='P'){
                    boolean thiefCaptured = false;
                    int x;
                    if(j-K >0){
                        x = j-K;
                    }else {
                        x = 0;
                    }
                    for(;x<j;x++) {
                        if (A[i][x] == 'T') {
                            A[i][x] = 'X';
                            A[i][j] = 'X';
                            count++;
                            thiefCaptured = true;
                            break;
                        }
                    }
                    int y;
                    if(j+K < A[i].length){
                        y = j+K;
                    }else{
                        y = A[i].length - 1;
                    }
                    for(;(y>j) && (thiefCaptured == false);y--){
                        if(A[i][y]=='T'){
                            A[i][y] = 'X';
                            A[i][j] = 'X';
                            count++;
                            break;
                        }
                    }
                }
            }
        }
        return count;
    }
}
</code>```

My Logic
If an element is considered as the center of our search, then I am first looking for the thieves from the farthest left(by k units) and iterating towards the center. If the thief is not found, then I am looking for the thief from the farthest right(by k units) towards the center.

Failing test case input:

```<code>1
18 2
P P T T T P T P P T T P P P T P P T
P P P P T P P T P P T P P P T P T P
P P P T T T T T P P T P T P T T P T
P P P P P P T P P P T T T P T T T P
P P T P P T P P P T T P P T P P P T
P T P P P P P P P P P P T T P T P P
T P T T T P P P P T P T T T T P T P
T T P T P P P P P P P T T T P T P P
P T T T T P T T P T P P P P T T P T
P T P P T T P P P P P T T P T P P P
P T P T T P T P T P T P P P P P P T
P T P P T P T P T P T P T T T P P P
T T P T P P P P P P T T T P T P T P
P T T P P P P P T P T P T P T P P T
P T P T T P T P T P P P P T P T P P
T P P P T P T P P P P P T T P P P P
P P T P P P P P P P P T T T P P T P
T T T P T P T P T P P T P P T P P P
</code>```

Expected Ouput
113

Actual Output
112

Can you guys help me to figure out where I am going wrong? I am actually trying to figure out the solution for weeks but not able to progress. I know there is a different solution out there for the same question. But the thing is I would like to figure out the issue or the hole in my logic. Please help me out.

Link: Policemen and thieves on hackerearth

答:
Your bug manifests in the line of i 11 (the 12th line if you count naturally/1-based).

```<code>P T P P T P T P T P T P T T T P P P
</code>```

There are 8 thieves in this row. They can all be caught. In the following line a + indicates a policeman or policewoman successful of catching a thief, whereas - means one who doesn’t catch any.

```<code>+ T - + T + T + T + T + T T T + + -
</code>```

(The first thief can be caught by either the police officer on the left or the right, it makes no difference to the count. There are yet more possible variations on who catches the first two thieves.)

Your program “catches” only 7 of the 8 thieves. Before this row you have a count of 68, which I believe is correct. After the row your count is 75, it should be 76.

In the row the first 5 thieves are caught as they should. Now what does the police officer at index 11 do? The thief to the left has already been caught. To the right are three thieves. Your second innermost loop counts down from y = j+K = 11 + 2 = 13, so catches the thief at index 13, leaving the thief at index 12 uncaught. The next police officer is at index 15.When K is 2, s/he cannot catch the thief at index 12, the distance is too great.

Edit: my idea for a solution. Since you have posted your solution, I think I can post mine without spoiling anything. My idea is for each thief to search left to right for a police officer who can catch that thief. I will start the search where the previous search left off. This ensures that each police officer catches only one thief.

```<code>    char[] row = { 'P', 'T', 'P', 'P', 'T', 'P', 'T', 'P', 'T',
            'P', 'T', 'P', 'T', 'T', 'T', 'P', 'P', 'P' };
    int k = 2; // The uppercase K from the problem

    int count = 0;
    // Index from where to search for the next police officer to catch a thief
    int pix = 0;
    for (int ix = 0; ix < row.length; ix++) {
        if (row[ix] == 'T') {
            if (pix < ix - k) {
                pix = ix - k;
            }
            int searchLimit = Math.min(row.length, ix + k + 1);
            while (pix < searchLimit && row[pix] != 'P') {
                pix++;
            }
            if (pix < searchLimit) { // Found
                count++;
                pix++;
            }
        }
    }

    System.out.println(count);
</code>```

Output:

8

I am not using any auxiliary data structures, and I am not modifying the input array. I believe that this algorithm is efficient (I have not tried it on hackerearth).

The problem is symmetrical in police officers and thieves, so one may do it the other way around, for each police officer search for at thief to catch, it will work the same.

If the Math.min() call feels unusual, instead use either the ? : ternary operator or an if-else construct.

PS Maybe on hackerearth it would have been more appropriate to have P for police officer and H for hacker and ask how many hackers got away without being caught by police. Just joking.

Body:
I am trying to solve the Policeman and Theives problem in Hackeearth website. I am able to reduce the time complexity but three test cases are failing. There seems to be a bug in the solution which causes a small mismatch. I am struggling to find the error for weeks. Below are the problem statement and my code,

Policeman and Thieves Problem statement:

You are given a grid of size  that has the following specifications:

Each cell in the grid contains either a policeman or a thief.

A policeman can only catch a thief if both of them are in the same row.

Each policeman can only catch one thief.

A policeman cannot catch a thief who is more than K units away from the policeman.
Write a program to find the maximum number of thieves that can be caught in the grid.

Input format

First line: T (number of test cases)

For each test case,

First-line contains Two space-separated integers N and K

Next N lines contain N space-separated characters (denoting each cell in the grid)

Output format

For each test case, print the maximum number of thieves that can be caught in the grid.

My code:

import java.io.*;
import java.util.*;

public class TestClass {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wr = new PrintWriter(System.out);
        int T = Integer.parseInt(br.readLine().trim());
        for(int t_i=0; t_i<T; t_i++)
        {
            String[] line = br.readLine().split(" ");
            int N = Integer.parseInt(line[0]);
            int K = Integer.parseInt(line[1]);
            char[][] A = new char[N][N];
            for(int i_A=0; i_A<N; i_A++)
            {
                String[] arr_A = br.readLine().split(" ");
                for(int j_A=0; j_A<arr_A.length; j_A++)
                {
                    A[i_A][j_A] = arr_A[j_A].charAt(0);
                }
            }

            int out_ = solution(A, K);
            System.out.println(out_);
            System.out.println("");
        }

        wr.close();
        br.close();
    }
    static int solution(char[][] A, int K){
        int count = 0;
        for(int i=0;i<A.length;i++){
            for(int j=0;j0){
                        x = j-K;
                    }else {
                        x = 0;
                    }
                    for(;x<j;x++) {
                        if (A[i][x] == 'T') {
                            A[i][x] = 'X';
                            A[i][j] = 'X';
                            count++;
                            thiefCaptured = true;
                            break;
                        }
                    }
                    int y;
                    if(j+K j) && (thiefCaptured == false);y--){
                        if(A[i][y]=='T'){
                            A[i][y] = 'X';
                            A[i][j] = 'X';
                            count++;
                            break;
                        }
                    }
                }
            }
        }
        return count;
    }
}

My Logic
If an element is considered as the center of our search, then I am first looking for the thieves from the farthest left(by k units) and iterating towards the center. If the thief is not found, then I am looking for the thief from the farthest right(by k units) towards the center.

Failing test case input:

1
18 2
P P T T T P T P P T T P P P T P P T
P P P P T P P T P P T P P P T P T P
P P P T T T T T P P T P T P T T P T
P P P P P P T P P P T T T P T T T P
P P T P P T P P P T T P P T P P P T
P T P P P P P P P P P P T T P T P P
T P T T T P P P P T P T T T T P T P
T T P T P P P P P P P T T T P T P P
P T T T T P T T P T P P P P T T P T
P T P P T T P P P P P T T P T P P P
P T P T T P T P T P T P P P P P P T
P T P P T P T P T P T P T T T P P P
T T P T P P P P P P T T T P T P T P
P T T P P P P P T P T P T P T P P T
P T P T T P T P T P P P P T P T P P
T P P P T P T P P P P P T T P P P P
P P T P P P P P P P P T T T P P T P
T T T P T P T P T P P T P P T P P P

Expected Ouput
113

Actual Output
112

Can you guys help me to figure out where I am going wrong? I am actually trying to figure out the solution for weeks but not able to progress. I know there is a different solution out there for the same question. But the thing is I would like to figure out the issue or the hole in my logic. Please help me out.

Link: Policemen and thieves on hackerearth

Body:
Your bug manifests in the line of i 11 (the 12th line if you count naturally/1-based).

P T P P T P T P T P T P T T T P P P

There are 8 thieves in this row. They can all be caught. In the following line a + indicates a policeman or policewoman successful of catching a thief, whereas - means one who doesn’t catch any.

+ T - + T + T + T + T + T T T + + -

(The first thief can be caught by either the police officer on the left or the right, it makes no difference to the count. There are yet more possible variations on who catches the first two thieves.)

Your program “catches” only 7 of the 8 thieves. Before this row you have a count of 68, which I believe is correct. After the row your count is 75, it should be 76.

In the row the first 5 thieves are caught as they should. Now what does the police officer at index 11 do? The thief to the left has already been caught. To the right are three thieves. Your second innermost loop counts down from y = j+K = 11 + 2 = 13, so catches the thief at index 13, leaving the thief at index 12 uncaught. The next police officer is at index 15.When K is 2, s/he cannot catch the thief at index 12, the distance is too great.

Edit: my idea for a solution. Since you have posted your solution, I think I can post mine without spoiling anything. My idea is for each thief to search left to right for a police officer who can catch that thief. I will start the search where the previous search left off. This ensures that each police officer catches only one thief.

    char[] row = { 'P', 'T', 'P', 'P', 'T', 'P', 'T', 'P', 'T',
            'P', 'T', 'P', 'T', 'T', 'T', 'P', 'P', 'P' };
    int k = 2; // The uppercase K from the problem

    int count = 0;
    // Index from where to search for the next police officer to catch a thief
    int pix = 0;
    for (int ix = 0; ix < row.length; ix++) {
        if (row[ix] == 'T') {
            if (pix < ix - k) {
                pix = ix - k;
            }
            int searchLimit = Math.min(row.length, ix + k + 1);
            while (pix < searchLimit && row[pix] != 'P') {
                pix++;
            }
            if (pix < searchLimit) { // Found
                count++;
                pix++;
            }
        }
    }

    System.out.println(count);

Output:

8

I am not using any auxiliary data structures, and I am not modifying the input array. I believe that this algorithm is efficient (I have not tried it on hackerearth).

The problem is symmetrical in police officers and thieves, so one may do it the other way around, for each police officer search for at thief to catch, it will work the same.

If the Math.min() call feels unusual, instead use either the ? : ternary operator or an if-else construct.

PS Maybe on hackerearth it would have been more appropriate to have P for police officer and H for hacker and ask how many hackers got away without being caught by police. Just joking.


问:
Django migrations/South: New column take default value another value from the same record
I want to add a new column to an already existing table, but I want to give it a default value dependent on already existing data:

e.g. Each record has a start_date. Now I want to add an open_until column, and I want to fill it with the value for start_date of each existing record. (the upcoming records will be able to pick different value)

Is there a friendly way to do this?

答:
In Python 3.8 I first add fields to MyApp models file and it looks like:

```<code>from django.db import models
import datetime

class MyModel(models.Model):
    start_date = models.DateField(),
    open_until = models.DateField(default=datetime.date.today),
</code>```

Then, after running manage.py makemigrations add this lines to new migrations file is created:

```<code>def forward(apps, schema_editor):
    my_model_objects = apps.get_model('MyApp', 'MyModel').objects.all()
    for t in my_model_objects:
        t.open_until = t.start_date
        t.save()

def reverse(apps, schema_editor):
    pass

class Migration(migrations.Migration):
    operations = [
        " the base operations is here " ,
        migrations.RunPython(forward, reverse),
    ]
</code>```

Body:
In Python 3.8 I first add fields to MyApp models file and it looks like:

from django.db import models
import datetime

class MyModel(models.Model):
    start_date = models.DateField(),
    open_until = models.DateField(default=datetime.date.today),

Then, after running manage.py makemigrations add this lines to new migrations file is created:

def forward(apps, schema_editor):
    my_model_objects = apps.get_model('MyApp', 'MyModel').objects.all()
    for t in my_model_objects:
        t.open_until = t.start_date
        t.save()

def reverse(apps, schema_editor):
    pass

class Migration(migrations.Migration):
    operations = [
        " the base operations is here " ,
        migrations.RunPython(forward, reverse),
    ]


问:
Using the continue statement in a for loop
Why does the continue statement print even numbers, but will print odd numbers if replaced by console.log() in the following?

// print even numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) != 0) {
    continue;
  }
  console.log(i);
}

//print odd numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) != 0) {
    console.log(i);
  }
}```

答:
In the first example, the loop continues with the next iteration if the number is odd (and therefore the program does not reach console.log()). In this next iteration the number is even and will be printed.

The second example is quite trivial: you only print the number if it is odd.


问:
Error: You cannot call webbrowser methods until it is in the visual tree
I started using a Google AdMob control in WP7 application and getting an exception thrown. I believe the control uses a webbrowser inside it.  I am getting this following error on my page now.  Any suggestions on how to resolve this.

```<code>System.InvalidOperationException was unhandled
  Message=You cannot call WebBrowser methods until it is in the visual tree.
  StackTrace:
   at Microsoft.Phone.Controls.WebBrowserDisconnected.NavigateToString(String pszHtml)
   at Microsoft.Phone.Controls.WebBrowser.NavigateToString(String html)
   at Google.AdMob.Ads.WindowsPhone7.WPF.DisplayAdBase.<.ctor>b__7(Object , RoutedEventArgs )
   at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)
</code>```

I am using WP7 Navigation recipe in the app -
http://create.msdn.com/en-us/education/catalog/article/nln-serv-wp7

I believe Google AdMob control is throwing the error during the back navigation of the page stack.  so, if you navigate to page 1, page 2 (has Google AdMob control), page 3 and then press a home button to come back to page 1, the error gets thrown by page 2 during the back navigation.

I don't know how to resolve this as the webbrowser control is within the google ad control.  Anyone else running into this issue?

答:
a quick solution:
on your app.xaml.cs is this event...
paste the exception of ADMOB... </p>

```<code>// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
    if (System.Diagnostics.Debugger.IsAttached)
    {
        // An unhandled exception has occurred; break into the debugger
        System.Diagnostics.Debugger.Break();
    }

    else
    {
        //this is the ADMOB exception
        if (e.ExceptionObject.Message == "You cannot call WebBrowser methods until it is in the visual tree.")
            e.Handled = true;

        else
             MessageBox.Show(e.ExceptionObject.Message, "007", MessageBoxButton.OK);
    }
}
</code>```

Body:
I started using a Google AdMob control in WP7 application and getting an exception thrown. I believe the control uses a webbrowser inside it.  I am getting this following error on my page now.  Any suggestions on how to resolve this.

System.InvalidOperationException was unhandled
  Message=You cannot call WebBrowser methods until it is in the visual tree.
  StackTrace:
   at Microsoft.Phone.Controls.WebBrowserDisconnected.NavigateToString(String pszHtml)
   at Microsoft.Phone.Controls.WebBrowser.NavigateToString(String html)
   at Google.AdMob.Ads.WindowsPhone7.WPF.DisplayAdBase.<.ctor>b__7(Object , RoutedEventArgs )
   at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)

I am using WP7 Navigation recipe in the app -
http://create.msdn.com/en-us/education/catalog/article/nln-serv-wp7

I believe Google AdMob control is throwing the error during the back navigation of the page stack.  so, if you navigate to page 1, page 2 (has Google AdMob control), page 3 and then press a home button to come back to page 1, the error gets thrown by page 2 during the back navigation.

I don't know how to resolve this as the webbrowser control is within the google ad control.  Anyone else running into this issue?

Body:
a quick solution:
on your app.xaml.cs is this event...
paste the exception of ADMOB...

// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
    if (System.Diagnostics.Debugger.IsAttached)
    {
        // An unhandled exception has occurred; break into the debugger
        System.Diagnostics.Debugger.Break();
    }

    else
    {
        //this is the ADMOB exception
        if (e.ExceptionObject.Message == "You cannot call WebBrowser methods until it is in the visual tree.")
            e.Handled = true;

        else
             MessageBox.Show(e.ExceptionObject.Message, "007", MessageBoxButton.OK);
    }
}


问:
python: can't open file 'manage.py
i just finishing running the makemigration & migrate command
it's OK
but when i run python manage.py createsuperuser

i receive this message :
python: can't open file 'manage.py': [Errno 2] No such file or directory

i did not know what is my mistake

this is my python file:

```<code>#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oasisconsuting.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()
</code>```

maybe (i'm not sure) i change some code or anything

答:
your manage.py should be located in root of the project . you need to be in the directory where manage.py exits .
So, if you cd in your project root directory you should be able to run it.</p>

Title: python: can't open file 'manage.py

Body:
i just finishing running the makemigration & migrate command
it's OK
but when i run python manage.py createsuperuser

i receive this message :
python: can't open file 'manage.py': [Errno 2] No such file or directory

i did not know what is my mistake

this is my python file:

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oasisconsuting.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()

maybe (i'm not sure) i change some code or anything


问:
Decode case class, String or Int in circe
I use some Rest API responding with json containing a sort of "mixed" field. By mixed I mean that it can take values of a different type. In my case Object, String and Int are allowed. The Object itself consists of 1 Int and 1 String.

The object I need to decode looks as:

I

```<code>{
   field1: 32,
   ...
   value: {
      id: 23,
      text: "text"
   }
}
</code>```

II

```<code>{
   field1: 32,
   ...
   value: 21
}
</code>```

III

```<code>{
   field1: 32,
   ...
   value: "value"
}
</code>```

How to deal with such objects in circe?

答:
A similar approach to what @SomeName created, but with a decoder not requiring HCursor:

```<code>sealed trait Value
object Value {
  final case class Values(id: Int, text: String) extends Value
  final case class IntValue(i: Int) extends Value
  final case class StringValue(s: String) extends Value

  implicit val valueDecoder: Decoder[Value] = Decoder[String]
    .map[Value](StringValue)
    .or(Decoder[Int].map[Value](IntValue))
    .or(Decoder.forProduct2("id", "text")(Values.apply).map[Value](identity))
}
</code>```

And the enclosing object:

```<code>final case class Example(field1: Int, value: Value)
object Example {
  implicit val exampDecoder: Decoder[Example] =
    Decoder.forProduct2("field1", "value")(Example.apply)
}
</code>```

Run it:

```<code>import io.circe.Decoder
import io.circe.parser._

def main(args: Array[String]): Unit = {
  val fst =
    """
      |{
      |   "field1": 32,
      |   "value": {
      |      "id": 23,
      |      "text": "text"
      |   }
      |}""".stripMargin

  val snd =
    """
      |{
      |   "field1": 32,
      |   "value": 21
      |}
      |""".stripMargin

  val third =
    """{
      |   "field1": 32,
      |   "value": "value"
      |}
      |""".stripMargin

  println(decode[Example](fst))
  println(decode[Example](snd))
  println(decode[Example](third))
}
</code>```

Results:

```<code>Right(Example(32,Values(23,text)))
Right(Example(32,IntValue(21)))
Right(Example(32,StringValue(value)))
</code>```

Body:
I use some Rest API responding with json containing a sort of "mixed" field. By mixed I mean that it can take values of a different type. In my case Object, String and Int are allowed. The Object itself consists of 1 Int and 1 String.

The object I need to decode looks as:

I

{
   field1: 32,
   ...
   value: {
      id: 23,
      text: "text"
   }
}

II

{
   field1: 32,
   ...
   value: 21
}

III

{
   field1: 32,
   ...
   value: "value"
}

How to deal with such objects in circe?

Body:
A similar approach to what @SomeName created, but with a decoder not requiring HCursor:

sealed trait Value
object Value {
  final case class Values(id: Int, text: String) extends Value
  final case class IntValue(i: Int) extends Value
  final case class StringValue(s: String) extends Value

  implicit val valueDecoder: Decoder[Value] = Decoder[String]
    .map[Value](StringValue)
    .or(Decoder[Int].map[Value](IntValue))
    .or(Decoder.forProduct2("id", "text")(Values.apply).map[Value](identity))
}

And the enclosing object:

final case class Example(field1: Int, value: Value)
object Example {
  implicit val exampDecoder: Decoder[Example] =
    Decoder.forProduct2("field1", "value")(Example.apply)
}

Run it:

import io.circe.Decoder
import io.circe.parser._

def main(args: Array[String]): Unit = {
  val fst =
    """
      |{
      |   "field1": 32,
      |   "value": {
      |      "id": 23,
      |      "text": "text"
      |   }
      |}""".stripMargin

  val snd =
    """
      |{
      |   "field1": 32,
      |   "value": 21
      |}
      |""".stripMargin

  val third =
    """{
      |   "field1": 32,
      |   "value": "value"
      |}
      |""".stripMargin

  println(decode[Example](fst))
  println(decode[Example](snd))
  println(decode[Example](third))
}

Results:

Right(Example(32,Values(23,text)))
Right(Example(32,IntValue(21)))
Right(Example(32,StringValue(value)))


答:
When the continue statement is executed, the rest of the contents of the loop body are skipped and execution returns to the top of the loop, to start the next iteration of the loop. So this:

```<code>if ((i % 2) != 0) {
  continue;
}
</code>```

means "If i is odd, skip back to the top of the loop, don't execute the rest of the loop body." That means the odd number isn't printed.

In your second example, you're only outputting when the condition is true, so you've ended up doing the opposite output, but in a different way: Only calling console.log when the number is odd.

You can make the first one output only even numbers by removing the continue, changing the condition, and moving console.log into the if body:

// print even numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) === 0) { // *** Changed condition
    console.log(i);    // *** Moved `console.log`
  }
}```
</div>
</div>
</p>

<p>That does even numbers in the same basic way the second one did odd numbers.</p>

<p>Or you can change the second one work like the first one, but in general it's best to avoid using <code>continue</code> (there are probably exceptions to that general rule):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// print odd numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) == 0) { // *** Changed condition
    continue;
  }
  console.log(i);
}</code>```

Title: Using the continue statement in a for loop

Body:
Why does the continue statement print even numbers, but will print odd numbers if replaced by console.log() in the following?

// print even numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) != 0) {
    continue;
  }
  console.log(i);
}

//print odd numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) != 0) {
    console.log(i);
  }
}

Body:
When the continue statement is executed, the rest of the contents of the loop body are skipped and execution returns to the top of the loop, to start the next iteration of the loop. So this:

if ((i % 2) != 0) {
  continue;
}

means "If i is odd, skip back to the top of the loop, don't execute the rest of the loop body." That means the odd number isn't printed.

In your second example, you're only outputting when the condition is true, so you've ended up doing the opposite output, but in a different way: Only calling console.log when the number is odd.

You can make the first one output only even numbers by removing the continue, changing the condition, and moving console.log into the if body:

// print even numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) === 0) { // *** Changed condition
    console.log(i);    // *** Moved `console.log`
  }
}

That does even numbers in the same basic way the second one did odd numbers.

Or you can change the second one work like the first one, but in general it's best to avoid using continue (there are probably exceptions to that general rule):

// print odd numbers
for (var i = 1; i <= 10; i++) {
  if ((i % 2) == 0) { // *** Changed condition
    continue;
  }
  console.log(i);
}


问:
Functional construction of a List from Pair-s
I try to construct a list from a primitive Pair data (see implementation for full implementation)
The constructor function uses recursion and is affected by stack space limitation for this reason. One possible solution is pass the (array, decrementing array index, incremental list) and keep state as part of the recursive call, but this still uses space at runtime.

Is there a way to implement this tail recursive  ? I run this in Node.

```<code>// listIter::[xs] -> List[xs]
export function listIter(xs) {
    const construct = (list, index) => {
        return (index === -1) ?
            list :
            construct(pair(xs[index], list), index - 1);
    }

    return construct(Pair.empty(), xs.length - 1);
}
</code>```

答:
SICP is a wonderful text. The code here should be fairly self-explanatory. I'm short on time at the moment but I'll follow up later today to add some details and answer potential follow-up questions -

main.js

// main.js
import { of, fromArray, toString } from './list'

toString(of(999))
// 999->Empty.

toString(fromArray([]))
// Empty.

toString(fromArray([1]))
// 1->Empty.

toString(fromArray([1,2,3,4]))
// 1->2->3->4->Empty.

const big =
  Array.from(Array(100000), (_, x) => x)

toString(fromArray(big))
// 0->1->2->3->...99999->Empty.
```

<hr>

<p><strong>list.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import { loop, recur } from './function'

const empty =                      // <-- empty list
  Symbol()                         // <-- any sentinel value

const pair = (left, right) =>      // <-- pair constructor
  ({ pair, left, right })          // <-- plain object

const of = (x = null) =>           // <-- "of" constructor
  pair(x, empty)                   // <-- singleton list

const fromArray = (xs = []) =>
  loop                             // <-- begin loop
    ( ( r = empty                  // <-- init r
      , i = 0                      // <-- init i
      ) =>                         // <-- loop body
        i >= xs.length             // <-- exit condition
          ? reverse(r)             // <-- tail; return
          : recur                  // <-- tail; recur
              ( pair(xs[i], r)     // <-- next r
              , i + 1              // <-- next i
              )
    )

const reverse = (node = empty) =>
  loop                             // <-- begin loop
    ( ( r = empty                  // <-- init r
      , t = node                   // <-- init t
      ) =>                         // <-- loop body
        t === empty                // <-- exit condition
          ? r                      // <-- tail; return
          : recur                  // <-- tail; recur
              ( pair(t.left, r)    // <-- next r
              , t.right            // <-- next t
              )
    )

const toString = (node = empty) =>
  loop                             // <-- begin loop
    ( ( r = "Empty."               // <-- init r
      , t = reverse(node)          // <-- init t
      ) =>                         // <-- loop body
      t === empty                  // <-- exit condition
        ? r                        // <-- tail; return
        : recur                    // <-- tail; recur
            ( t.left + "->" + r    // <-- next r
            , t.right              // <-- next t
            )
    )

// "pair" is not exported
// it is an implementation detail of our list module
export { empty, of, fromArray, reverse, toString }
</code>```

function.js

const identity = x => x

const recur = (...v) =>
  ({ recur, [Symbol.iterator]: _ => v.values() })

const loop = (f = identity, ...init) =>
  whileTrue               // <-- functional while
    ( r => r && r.recur   // <-- while condition
    , r => f(...r)        // <-- next r
    , f(...init)          // <-- init r
    )

const whileTrue = (test = identity, next = identity, r = null) =>
{ while(Boolean(test(r))) // <-- while test(r) is true
    r = next(r)           // <-- nexr r
  return r                // <-- return r
}

export { identity, loop, recur, whileTrue }
```

<hr>

<p><strong>demo</strong></p>

<p>Expand the snippet below to verify the result in your browser -</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// function.js -------
const identity = x => x

const recur = (...v) =>
  ({ recur, [Symbol.iterator]: _ => v.values() })

const loop = (f = identity, ...init) =>
  whileTrue
    ( r => r && r.recur
    , r => f(...r)
    , f(...init)
    )

const whileTrue = (test = identity, next = identity, r = null) =>
{ while(Boolean(test(r)))
    r = next(r)
  return r
}

// list.js -------
const empty =
  Symbol()

const pair = (left, right) =>
  ({ pair, left, right })

const of = (x = null) =>
  pair(x, empty)

const fromArray = (xs = []) =>
  loop
    ( ( r = empty
      , i = 0
      ) =>
        i >= xs.length
          ? reverse(r)
          : recur
              ( pair(xs[i], r)
              , i + 1
              )
    )

const reverse = (node = empty) =>
  loop
    ( ( r = empty
      , t = node
      ) =>
        t === empty
          ? r
          : recur
              ( pair(t.left, r)
              , t.right
              )
    )

const toString = (node = empty) =>
  loop
    ( ( r = "Empty."
      , t = reverse(node)
      ) =>
      t === empty
        ? r
        : recur
            ( t.left + "->" + r
            , t.right
            )
    )

// main.js -------
console.log(toString(of(999)))
// 999->Empty.

console.log(toString(fromArray([])))
// Empty.

console.log(toString(fromArray([1])))
// 1->Empty.

console.log(toString(fromArray([1,2,3,4])))
// 1->2->3->4->Empty.

const big =
  Array.from(Array(100000), (_, x) => x)

console.log(toString(fromArray(big)))
// 0->1->2->3->...99999->Empty.</code>```

further abstraction

With more time earlier I probably would've written pair as its own module -

// pair.js
import { raise } from './function'

const empty =
  Symbol()

const pair = (left, right) =>
  ({ pair, left, right })

const left = (t = empty) =>
  t === empty
    ? raise(`cannot read value from empty`)
    : t.left

const right = (t = empty) =>
  t === empty
    ? raise(`cannot read value from empty`)
    : t.right

const of = ([ left, right ]) =>
  pair(left, right)

export { empty, pair, left, right, of }
```

<p>Adding <code>raise</code> to <code>function</code> module -</p>

<pre class="lang-js prettyprint-override"><code>// function.js
const identity = //

const recur = //

const loop = //

const whileTrue = //

const raise = (msg = "") => // functional throw
  { throw Error(msg) }

export { identity, loop, recur, whileTrue, raise }
</code>```

Creating a better abstraction barrier between list module and pair module -

// list.js
import { loop, recur } from './function'
import { empty, pair, left, right } from './pair'

const of = (x = null) =>
  pair(x, empty)                   // <-- pair, empty

const fromArray = (xs = []) =>
  loop
    ( ( r = empty                  // <-- empty
      , i = 0
      ) =>
        i >= xs.length
          ? reverse(r)
          : recur
              ( pair(xs[i], r)     // <-- pair
              , i + 1              //
              )
    )

const reverse = (node = empty) =>
  loop
    ( ( r = empty                  // <-- empty
      , t = node
      ) =>
        t === empty                // <-- empty
          ? r
          : recur
              ( pair(left(t), r)   // <-- pair, left
              , right(t)           // <-- right
              )
    )

const toString = (node = empty) =>
  loop
    ( ( r = "Empty."
      , t = reverse(node)
      ) =>
      t === empty                  // <-- empty
        ? r
        : recur
            ( left(t) + "->" + r   // <-- left
            , right(t)             // <-- right
            )
    )

// re-export empty
// it's okay that List.empty and Pair.empty are
// represented using the same sentinel value
export { empty, of, fromArray, reverse, toString }
```

It's nice to see writing pair as a separate step because it shows us how to break apart modules when data structures become too entangled.

Body:
I try to construct a list from a primitive Pair data (see implementation for full implementation)
The constructor function uses recursion and is affected by stack space limitation for this reason. One possible solution is pass the (array, decrementing array index, incremental list) and keep state as part of the recursive call, but this still uses space at runtime.

Is there a way to implement this tail recursive  ? I run this in Node.

// listIter::[xs] -> List[xs]
export function listIter(xs) {
    const construct = (list, index) => {
        return (index === -1) ?
            list :
            construct(pair(xs[index], list), index - 1);
    }

    return construct(Pair.empty(), xs.length - 1);
}

Body:
SICP is a wonderful text. The code here should be fairly self-explanatory. I'm short on time at the moment but I'll follow up later today to add some details and answer potential follow-up questions -

main.js

// main.js
import { of, fromArray, toString } from './list'

toString(of(999))
// 999->Empty.

toString(fromArray([]))
// Empty.

toString(fromArray([1]))
// 1->Empty.

toString(fromArray([1,2,3,4]))
// 1->2->3->4->Empty.

const big =
  Array.from(Array(100000), (_, x) => x)

toString(fromArray(big))
// 0->1->2->3->...99999->Empty.

list.js

import { loop, recur } from './function'

const empty =                      // <-- empty list
  Symbol()                         // <-- any sentinel value

const pair = (left, right) =>      // <-- pair constructor
  ({ pair, left, right })          // <-- plain object

const of = (x = null) =>           // <-- "of" constructor
  pair(x, empty)                   // <-- singleton list

const fromArray = (xs = []) =>
  loop                             // <-- begin loop
    ( ( r = empty                  // <-- init r
      , i = 0                      // <-- init i
      ) =>                         // <-- loop body
        i >= xs.length             // <-- exit condition
          ? reverse(r)             // <-- tail; return
          : recur                  // <-- tail; recur
              ( pair(xs[i], r)     // <-- next r
              , i + 1              // <-- next i
              )
    )

const reverse = (node = empty) =>
  loop                             // <-- begin loop
    ( ( r = empty                  // <-- init r
      , t = node                   // <-- init t
      ) =>                         // <-- loop body
        t === empty                // <-- exit condition
          ? r                      // <-- tail; return
          : recur                  // <-- tail; recur
              ( pair(t.left, r)    // <-- next r
              , t.right            // <-- next t
              )
    )

const toString = (node = empty) =>
  loop                             // <-- begin loop
    ( ( r = "Empty."               // <-- init r
      , t = reverse(node)          // <-- init t
      ) =>                         // <-- loop body
      t === empty                  // <-- exit condition
        ? r                        // <-- tail; return
        : recur                    // <-- tail; recur
            ( t.left + "->" + r    // <-- next r
            , t.right              // <-- next t
            )
    )

// "pair" is not exported
// it is an implementation detail of our list module
export { empty, of, fromArray, reverse, toString }

function.js

const identity = x => x

const recur = (...v) =>
  ({ recur, [Symbol.iterator]: _ => v.values() })

const loop = (f = identity, ...init) =>
  whileTrue               // <-- functional while
    ( r => r && r.recur   // <-- while condition
    , r => f(...r)        // <-- next r
    , f(...init)          // <-- init r
    )

const whileTrue = (test = identity, next = identity, r = null) =>
{ while(Boolean(test(r))) // <-- while test(r) is true
    r = next(r)           // <-- nexr r
  return r                // <-- return r
}

export { identity, loop, recur, whileTrue }

demo

Expand the snippet below to verify the result in your browser -

// function.js -------
const identity = x => x

const recur = (...v) =>
  ({ recur, [Symbol.iterator]: _ => v.values() })

const loop = (f = identity, ...init) =>
  whileTrue
    ( r => r && r.recur
    , r => f(...r)
    , f(...init)
    )

const whileTrue = (test = identity, next = identity, r = null) =>
{ while(Boolean(test(r)))
    r = next(r)
  return r
}

// list.js -------
const empty =
  Symbol()

const pair = (left, right) =>
  ({ pair, left, right })

const of = (x = null) =>
  pair(x, empty)

const fromArray = (xs = []) =>
  loop
    ( ( r = empty
      , i = 0
      ) =>
        i >= xs.length
          ? reverse(r)
          : recur
              ( pair(xs[i], r)
              , i + 1
              )
    )

const reverse = (node = empty) =>
  loop
    ( ( r = empty
      , t = node
      ) =>
        t === empty
          ? r
          : recur
              ( pair(t.left, r)
              , t.right
              )
    )

const toString = (node = empty) =>
  loop
    ( ( r = "Empty."
      , t = reverse(node)
      ) =>
      t === empty
        ? r
        : recur
            ( t.left + "->" + r
            , t.right
            )
    )

// main.js -------
console.log(toString(of(999)))
// 999->Empty.

console.log(toString(fromArray([])))
// Empty.

console.log(toString(fromArray([1])))
// 1->Empty.

console.log(toString(fromArray([1,2,3,4])))
// 1->2->3->4->Empty.

const big =
  Array.from(Array(100000), (_, x) => x)

console.log(toString(fromArray(big)))
// 0->1->2->3->...99999->Empty.

further abstraction

With more time earlier I probably would've written pair as its own module -

// pair.js
import { raise } from './function'

const empty =
  Symbol()

const pair = (left, right) =>
  ({ pair, left, right })

const left = (t = empty) =>
  t === empty
    ? raise(`cannot read value from empty`)
    : t.left

const right = (t = empty) =>
  t === empty
    ? raise(`cannot read value from empty`)
    : t.right

const of = ([ left, right ]) =>
  pair(left, right)

export { empty, pair, left, right, of }

Adding raise to function module -

// function.js
const identity = //

const recur = //

const loop = //

const whileTrue = //

const raise = (msg = "") => // functional throw
  { throw Error(msg) }

export { identity, loop, recur, whileTrue, raise }

Creating a better abstraction barrier between list module and pair module -

// list.js
import { loop, recur } from './function'
import { empty, pair, left, right } from './pair'

const of = (x = null) =>
  pair(x, empty)                   // <-- pair, empty

const fromArray = (xs = []) =>
  loop
    ( ( r = empty                  // <-- empty
      , i = 0
      ) =>
        i >= xs.length
          ? reverse(r)
          : recur
              ( pair(xs[i], r)     // <-- pair
              , i + 1              //
              )
    )

const reverse = (node = empty) =>
  loop
    ( ( r = empty                  // <-- empty
      , t = node
      ) =>
        t === empty                // <-- empty
          ? r
          : recur
              ( pair(left(t), r)   // <-- pair, left
              , right(t)           // <-- right
              )
    )

const toString = (node = empty) =>
  loop
    ( ( r = "Empty."
      , t = reverse(node)
      ) =>
      t === empty                  // <-- empty
        ? r
        : recur
            ( left(t) + "->" + r   // <-- left
            , right(t)             // <-- right
            )
    )

// re-export empty
// it's okay that List.empty and Pair.empty are
// represented using the same sentinel value
export { empty, of, fromArray, reverse, toString }

It's nice to see writing pair as a separate step because it shows us how to break apart modules when data structures become too entangled.


问:
unexpected result with numpy any()
most probably I'm missing something on the any()function, it says:
Returns True if any of the elements of a evaluate to True.

So in my case below, I would expect true as an output, as one element count[0]
is larger than 2. However, the output is FALSE.

What stupid mistake am I doing?!

minimal example:

```<code>count = np.zeros(10)
count[0] += 4
count[5] += 1
print(np.any(count,axis=0) > 2)
</code>```

答:
```<code># parentheses:

np.any(count,axis=0)
#output: True

np.any(count, axis=0)>2
# is a boolean expression. It evaluates to False, because True is not larger than 2.

# So:
np.any(count>2, axis=0)

# should do what you want
</code>```

Title: unexpected result with numpy any()

Body:
most probably I'm missing something on the any()function, it says:
Returns True if any of the elements of a evaluate to True.

So in my case below, I would expect true as an output, as one element count[0]
is larger than 2. However, the output is FALSE.

What stupid mistake am I doing?!

minimal example:

count = np.zeros(10)
count[0] += 4
count[5] += 1
print(np.any(count,axis=0) > 2)