问:
Fastapi Captcha Sessions
I am testing captcha setups with Fastapi.  Currently, I am using an in-memory session (stored in a dictionary. Seems to not be a problem as there is no load balancing, etc...).

To fill out the contact form the frontend app makes a request to start a session (thus retrieving the captcha image and setting an opaque (really just a random UUID) session cookie (expiration. Of course, the id references the in-memory session that contains the captcha answer, which is checked at the time of submission.  If the captcha answer doesn't match the session's captcha is cleared and a new captcha is set in the user's session.

My question is this enough to mitigate automation attacks (I know you can pay for services etc... to get around captcha but I am trying to see what loop holes lie in this code)?

Here is my code thus far:

```<code>from captcha.image import ImageCaptcha
from fastapi import FastAPI, Request, Response, HTTPException, status

def captcha_generator(size: int):
    return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(size))

def generate_captcha():
    captcha: str = captcha_generator(5)
    image = ImageCaptcha()
    data = image.generate(captcha)
    data = base64.b64encode(data.getvalue())
    return {"data": data, "captcha": captcha}

@app.get('/')
def main(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.get('/start-session')
def start_session(request: Request):
    captcha = generate_captcha()
    request.session["captcha"] = captcha['captcha']
    captcha_image = captcha["data"].decode("utf-8")
    return StreamingResponse(io.BytesIO(base64.b64decode(captcha_image)), media_type="image/png")

@app.post('/contact-submission')
def submission(
     request: Request
    ,response: Response
    ,data # This includes the captcha answer provided by user
):

   if request.session.get("captcha", uuid.uuid4()) == data.captcha:
       return status.HTTP_200_OK
   else:
      request.session["captcha"] = str(uuid.uuid4())
      raise HTTPException(status.HTTP_403_FORBIDDEN, detail="Captcha Does not Match")

</code>```

Here is what the cookie looks like:

Session Cookie

答:
From your code layout:

```<code>def generate_captcha():
    captcha: str = captcha_generator(5)
    image = ImageCaptcha()
    data = image.generate(captcha)
    data = base64.b64encode(data.getvalue())
    return {"data": data, "captcha": captcha}
</code>```

and

```<code>if request.session.get("captcha", uuid.uuid4()) == data.captcha:
       return status.HTTP_200_OK
</code>```

you are storing the clue to the captcha in the cookies.
Sniffer/bot will eventually be able to read your cookies  even if it is encrypted. You are using encryption method base64 which can be decrypted easily.

You should implement a captcha validation service to avoid this security loopholes in which there should be no clue of the answer stored in any way in the users session. The captcha validation service should only return true or false.

Title: Fastapi Captcha Sessions

Body:
I am testing captcha setups with Fastapi.  Currently, I am using an in-memory session (stored in a dictionary. Seems to not be a problem as there is no load balancing, etc...).

To fill out the contact form the frontend app makes a request to start a session (thus retrieving the captcha image and setting an opaque (really just a random UUID) session cookie (expiration. Of course, the id references the in-memory session that contains the captcha answer, which is checked at the time of submission.  If the captcha answer doesn't match the session's captcha is cleared and a new captcha is set in the user's session.

My question is this enough to mitigate automation attacks (I know you can pay for services etc... to get around captcha but I am trying to see what loop holes lie in this code)?

Here is my code thus far:

from captcha.image import ImageCaptcha
from fastapi import FastAPI, Request, Response, HTTPException, status

def captcha_generator(size: int):
    return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(size))

def generate_captcha():
    captcha: str = captcha_generator(5)
    image = ImageCaptcha()
    data = image.generate(captcha)
    data = base64.b64encode(data.getvalue())
    return {"data": data, "captcha": captcha}

@app.get('/')
def main(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.get('/start-session')
def start_session(request: Request):
    captcha = generate_captcha()
    request.session["captcha"] = captcha['captcha']
    captcha_image = captcha["data"].decode("utf-8")
    return StreamingResponse(io.BytesIO(base64.b64decode(captcha_image)), media_type="image/png")

@app.post('/contact-submission')
def submission(
     request: Request
    ,response: Response
    ,data # This includes the captcha answer provided by user
):

   if request.session.get("captcha", uuid.uuid4()) == data.captcha:
       return status.HTTP_200_OK
   else:
      request.session["captcha"] = str(uuid.uuid4())
      raise HTTPException(status.HTTP_403_FORBIDDEN, detail="Captcha Does not Match")

Here is what the cookie looks like:

Session Cookie

Body:
From your code layout:

def generate_captcha():
    captcha: str = captcha_generator(5)
    image = ImageCaptcha()
    data = image.generate(captcha)
    data = base64.b64encode(data.getvalue())
    return {"data": data, "captcha": captcha}

and

if request.session.get("captcha", uuid.uuid4()) == data.captcha:
       return status.HTTP_200_OK

you are storing the clue to the captcha in the cookies.
Sniffer/bot will eventually be able to read your cookies  even if it is encrypted. You are using encryption method base64 which can be decrypted easily.

You should implement a captcha validation service to avoid this security loopholes in which there should be no clue of the answer stored in any way in the users session. The captcha validation service should only return true or false.


来源: stackexchange

问:
Test Suite for Actions on Google Smart Home Assertion Error
I'm implementing a Smart Home action, and while running tests on the Test Suite, I got the following error message during an OnOff trait test:

Ok Google. Turn on the WaterMoter
AssertionError: Expected state to include: {"on":true}, actual state: {"on":false,"online":true}: expected false to be true

Ok Google. Turn off the WaterMoter

But when we try with the Google Home app everything is working and the response is 200 OK with this data:

```<code>Apr 30 12:29:54 api.firewires.in node[277153]: Email: firewires.smart.home@gmail.com
Apr 30 12:29:54 api.firewires.in node[277153]: UUID: 6e5c0a41-e9db-4313-b550-f5674d500bf7
Apr 30 12:29:54 api.firewires.in node[277153]: Device: FW_246F28248118#switch_7
Apr 30 12:29:54 api.firewires.in node[277153]: Calling Home Graph
Apr 30 12:29:55 api.firewires.in node[277153]: HomeGraph Called without Error
Apr 30 12:29:55 api.firewires.in node[277153]: HomeGraph Response: {
Apr 30 12:29:55 api.firewires.in node[277153]: "requestId": "6e5c0a41-e9db-4313-b550-f5674d500bf7"
Apr 30 12:29:55 api.firewires.in node[277153]:
</code>```

In Smart Home Report State Dashboard devices showing state:

https://i.stack.imgur.com/hfORZ.png

答:
After looking at the question, it can be concluded that you’re not using the Report State API correctly. The Test Suite for Google Smart Home derives the state change data from the HomeGraph API and in order to do that a proper implementation of the Report State must be in place.
Please check if the Report State API has been set up and being called correctly. Visit https://developers.google.com/assistant/smarthome/develop/report-state for more information.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm implementing a Smart Home action, and while running tests on the Test Suite, I got the following error message during an OnOff trait test:

Ok Google. Turn on the WaterMoter
AssertionError: Expected state to include: {"on":true}, actual state: {"on":false,"online":true}: expected false to be true

Ok Google. Turn off the WaterMoter

But when we try with the Google Home app everything is working and the response is 200 OK with this data:

Apr 30 12:29:54 api.firewires.in node[277153]: Email: firewires.smart.home@gmail.com
Apr 30 12:29:54 api.firewires.in node[277153]: UUID: 6e5c0a41-e9db-4313-b550-f5674d500bf7
Apr 30 12:29:54 api.firewires.in node[277153]: Device: FW_246F28248118#switch_7
Apr 30 12:29:54 api.firewires.in node[277153]: Calling Home Graph
Apr 30 12:29:55 api.firewires.in node[277153]: HomeGraph Called without Error
Apr 30 12:29:55 api.firewires.in node[277153]: HomeGraph Response: {
Apr 30 12:29:55 api.firewires.in node[277153]: "requestId": "6e5c0a41-e9db-4313-b550-f5674d500bf7"
Apr 30 12:29:55 api.firewires.in node[277153]:

In Smart Home Report State Dashboard devices showing state:

https://i.stack.imgur.com/hfORZ.png


问:
How to draw dynamically draw units out of an array and pair them with a predefined number value?
So I'm working on a homework assignment where I'm supposed track the "how many points a sports team has earned in a season" by writing a function called getTotalPoints that accepts a string of letters and returns the total points earned. These letters would be any series of "w" (wins) "d" (draws) and/or "l"(losses).

The assignment includes a pre-defined number value to each letter (w = 3, d = 1, and l =0), a helper function to draw out these values getPointsFromResult, and the function with a string param passed, getTotalPoints('wwdl') to test the getTotalPoints function I wrote works properly.

I got as a far as turning the string into an array and then tried to iterate on that array. The correct answer should be 7, but I am getting a result of 16, because it seems that forEach loop is iterating everything x's 4 (4 being the length of the array) As a result of 4 sets of 3+1+0 (essentially 4 x 4).

I have no idea how to move forward from here and am completely stuck.

const RESULT_VALUES = {
  w: 3,
  d: 1,
  l: 0
}

/**
 * Takes a single result string and (one of 'w', 'l', or 'd')
 * and returns the point value
 *
 * @param {string} result
 * @returns {number} point value
 */

function getPointsFromResult(result) {
  return RESULT_VALUES[result];
}

// Create getTotalPoints function which accepts a string of results
// including wins, draws, and losses i.e. 'wwdlw'
// Returns total number of points won

let getTotalPoints = function(pointsString) {
  let pointsArray = Array.from(pointsString);
  console.log(pointsArray);

  let sum = 0

  pointsArray.forEach(function(result) {
    console.log(result)
    let wins = getPointsFromResult('w');
    let draws = getPointsFromResult('d');
    let losses = getPointsFromResult('l');

    console.log(wins);
    console.log(draws);
    console.log(losses);

    sum += wins;
    sum += draws;
    sum += losses;
  })

  return sum;

};

// Check getTotalPoints
console.log(getTotalPoints('wwdl')); // should equal 7```

答:
split() "wwdl" string into an array:

```<code>'wwdl'.split('') //['w', 'w', 'd', 'l']
</code>```

Then get each key of the object ('w', 'd', 'l') and get the value (3, 1, 0).

```<code> object['w'] // first iteration 3
 object['w'] // second iteration 3
 object['d'] // third iterayion 1
 object['l'] // fourth iteration 0
</code>```

.reduce() can add the values and return a sum:

```<code>  sum + current value
</code>```

In the example below log(data) is just a helper function to log to console easier.

const log = data => console.log(JSON.stringify(data));
const record = `wwdl`;

const totalScore = record => {
  const scoring = {
    w: 3,
    d: 1,
    l: 0
  };

  let recArr = record.split('');
  log('String as an Array:');
  log(recArr);

  return recArr.reduce((sum, cur) => {
    log('Current Key: ' + cur + ': return: ' + scoring[cur]);
    return sum + scoring[cur];
  }, 0);
};

log('Total Score: ' + totalScore(record));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-row::after {
  width: 0;
  font-size: 0;
}

.as-console-row-code {
  width: 100%;
  word-break: break-word;
}</code>```

Body:
split() "wwdl" string into an array:

'wwdl'.split('') //['w', 'w', 'd', 'l']

Then get each key of the object ('w', 'd', 'l') and get the value (3, 1, 0).

 object['w'] // first iteration 3
 object['w'] // second iteration 3
 object['d'] // third iterayion 1
 object['l'] // fourth iteration 0

.reduce() can add the values and return a sum:

  sum + current value

In the example below log(data) is just a helper function to log to console easier.

const log = data => console.log(JSON.stringify(data));
const record = `wwdl`;

const totalScore = record => {
  const scoring = {
    w: 3,
    d: 1,
    l: 0
  };

  let recArr = record.split('');
  log('String as an Array:');
  log(recArr);

  return recArr.reduce((sum, cur) => {
    log('Current Key: ' + cur + ': return: ' + scoring[cur]);
    return sum + scoring[cur];
  }, 0);
};

log('Total Score: ' + totalScore(record));

.as-console-row::after {
  width: 0;
  font-size: 0;
}

.as-console-row-code {
  width: 100%;
  word-break: break-word;
}


问:
Circular buffer in JavaScript
Has anyone already implemented a circular buffer in JavaScript? How would you do that without having pointers?</p>

答:
```<code>  /**
    example: [1,2,3].bPush(-1,'a')   //[1,2,3,'a']
                    .bPush(0,'b')    //[1,2,3,'a']
                    .bPush(-1,'c')   //[1,2,3,'a','c']
                    .bPush(3,'e')    //['a','c','e']
    bufferSize zero or undefined does nothing; returns array as is
    bufferSize negative is same as push
    bufferSize > 0 creates a circular buffer appending newest & overwriting oldest
  */
  Array.prototype.bPush = function (bufferSize, newItem) {
    if (!bufferSize) return this;
    if (bufferSize > 0 && this.length >= bufferSize) {
      while( this.length >= bufferSize) this.shift();
    }
    this.push(newItem);
    return this;
  }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Circular buffer in JavaScript


问:
Webkit (Safari and Chrome) zero width td with only bottom border is displayed as 1px wide
My problem is simple to explain but Webkit hard to resolve. Please read below:

I have a simple table with a single row and two cells but still the table is displayed differently in Safari/Chrome than in IE/Firefox.

The first cell in the single row of the table contains a div which is 150px wide and has a 1px blue border. The second cell in the same row has a red only bottom border 25px wide and contains a div which is 0px wide and has no border.

See the example at http://www.livenetlife.com/Tabletest.html:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
    </head>
    <body>
        <table cellpadding="0" cellspacing="0">
            <tr>
                <td>
                    <div style="border: 1px solid blue; width:150px; height:50px;"></div>
                </td>
                <td style="border-left: 0px; border-right:0px; border-top:0px; border-bottom: 25px solid red;">
                    <div style="width:0px; height:0px;"></div>
                </td>
            </tr>
        </table>

    </body>
</html>
</code>```

In Firefox and IE the second cell is not displayed as it is 0 px wide. Test by opening the link above with Firefox or IE and all you will notice is a single blue rectangle (the div in the first cell).

But in Webkit Browsers (Safari and Chrome) the second cell is displayed too because it is mysteriously 1px wide. Open the link above with Safari or Chrome and you will notice the vertical red line (25px wide bottom border of the second cell) displayed next to the blue rectangle.

What Webkit CSS am I missing to make the second cell disappear also in Safari and Chrome?

Any advice would really be appreciated.

PS: Please note that the table above is actually a simplification of the real problem described here. Therefore HTML modification is not possible. Please try to help me find a (Webkit) CSS solution for the mentioned problem.

答:
You can use display:inline; in the 2nd td of the table. Here is your code with my changes.

```<code><table cellpadding="0" cellspacing="0">
        <tbody><tr>
            <td>
                <div style="border: 1px solid blue; width:150px; height:50px;"></div>
            </td>
            <td style="border-left: 0px; border-right:0px; border-top:0px; border-bottom: 25px solid red; display: inline;">
                <div style="width:0px; height:0px;"></div>
            </td>
        </tr>
    </tbody></table>
</code>```

Body:
My problem is simple to explain but Webkit hard to resolve. Please read below:

I have a simple table with a single row and two cells but still the table is displayed differently in Safari/Chrome than in IE/Firefox.

The first cell in the single row of the table contains a div which is 150px wide and has a 1px blue border. The second cell in the same row has a red only bottom border 25px wide and contains a div which is 0px wide and has no border.

See the example at http://www.livenetlife.com/Tabletest.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

In Firefox and IE the second cell is not displayed as it is 0 px wide. Test by opening the link above with Firefox or IE and all you will notice is a single blue rectangle (the div in the first cell).

But in Webkit Browsers (Safari and Chrome) the second cell is displayed too because it is mysteriously 1px wide. Open the link above with Safari or Chrome and you will notice the vertical red line (25px wide bottom border of the second cell) displayed next to the blue rectangle.

What Webkit CSS am I missing to make the second cell disappear also in Safari and Chrome?

Any advice would really be appreciated.

PS: Please note that the table above is actually a simplification of the real problem described here. Therefore HTML modification is not possible. Please try to help me find a (Webkit) CSS solution for the mentioned problem.

Body:
You can use display:inline; in the 2nd td of the table. Here is your code with my changes.

<table cellpadding="0" cellspacing="0">
        <tbody><tr>
            <td>
                <div style="border: 1px solid blue; width:150px; height:50px;"></div>
            </td>
            <td style="border-left: 0px; border-right:0px; border-top:0px; border-bottom: 25px solid red; display: inline;">
                <div style="width:0px; height:0px;"></div>
            </td>
        </tr>
    </tbody></table>


问:
Why is it discouraged to include features.h?
I was reading the linux features test macro page and in the NOTES section it states that:

<features.h> is a Linux/glibc-specific header file.  Other
systems have an analogous file, but typically with a different
name.  This header file is automatically included by other header
files as required: it is not necessary to explicitly include it
in order to employ feature test macros.

I understand that other systems wouldn't have the same filename as features.h, and therefore you shouldn't include it directly. But then, if you don't include the header file, how do you know if you can use the features test macros?

答:
glibc guarantees that #defines of the documented feature selection macros (_POSIX_C_SOURCE, _XOPEN_SOURCE, _GNU_SOURCE, etc) will be honored as long as they take effect before the first inclusion of any public C library header.  For instance

```<code>/* file header comment */
#define _XOPEN_SOURCE 700 // first non-comment line of the file
#include <unistd.h>       // first #include in the file
// ... more code here ...
</code>```

is guaranteed to make unistd.h declare things that are part of POSIX.1-2008 including XSI extensions.

The implementation of this guarantee involves features.h, but features.h is not a public C library header.  Direct inclusion of features.h is not something you should ever need to do, and we (glibc devs) do not promise that this header will even continue to exist in the future.  (For instance, a future release might merge it into bits/libc-header-start.h.)

Body:
glibc guarantees that #defines of the documented feature selection macros (_POSIX_C_SOURCE, _XOPEN_SOURCE, _GNU_SOURCE, etc) will be honored as long as they take effect before the first inclusion of any public C library header.  For instance

/* file header comment */
#define _XOPEN_SOURCE 700 // first non-comment line of the file
#include <unistd.h>       // first #include in the file
// ... more code here ...

is guaranteed to make unistd.h declare things that are part of POSIX.1-2008 including XSI extensions.

The implementation of this guarantee involves features.h, but features.h is not a public C library header.  Direct inclusion of features.h is not something you should ever need to do, and we (glibc devs) do not promise that this header will even continue to exist in the future.  (For instance, a future release might merge it into bits/libc-header-start.h.)


问:
Minimize maximum time to complete tasks in parallel
Suppose there are n tasks to complete and k parallel processors that can complete the task.
Each processor can only run 1 task at a time and each processor takes a different amount of time to complete each task (we can represent the time it takes for each processor to complete each task in an n X k matrix)

What's the optimal algorithm to allocate the n tasks to the k processors to minimize the total time to complete all tasks?

Very similar to this problem:
Algorithm to find the most efficient way to distribute non-identical work tasks between workers

But with non-identical workers!

Thanks.

答: Ok after some more searching I learned this is integer linear programming problem.</p>


问:
How to scure my APIs on c#.net the best practice
I have built APIs on c#.Net

these APIs works fine, but they are not secure, which means anyone worldwide can use it

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.SqlClient;
using System.Data;

namespace CDAPIs.Controllers
{
    public class CallSPController : ApiController
    {

        [Route("api/CallSP")]
        public string Get(string SP = null, string Type = null, string Ps = null, string P0 = null, string P1 = null, string P2 = null, string P3 = null)
        {
            string sDBConn = Functions.GetConn();
            string[] Parms = Ps.Split(',');
            SqlConnection conn = new SqlConnection(sDBConn);
            SqlCommand cmd = new SqlCommand(SP, conn);
            cmd.CommandTimeout = 0;
            cmd.CommandType = CommandType.StoredProcedure;

            string P = "";
            for (int i = 0; i < Parms.Length; i++)
            {
                if (i == 0) { P = P0; }
                if (i == 1) { P = P1; }
                if (i == 2) { P = P2; }
                if (i == 3) { P = P3; }
                cmd.Parameters.Add(new SqlParameter("@" + Parms[i].Trim(), P));
            }

            try
            {
                conn.Open();

                if (Type.ToUpper().Trim() == "STRING")
                {
                    string st = cmd.ExecuteScalar().ToString();
                    conn.Close();
                    conn.Dispose();
                    return st;
                }
                else
                {
                    SqlDataReader rdr = cmd.ExecuteReader();
                    var dt = new DataTable();
                    dt.Load(rdr);
                    List<DataRow> result = dt.AsEnumerable().ToList();
                    rdr.Close();
                    conn.Close();
                    conn.Dispose();
                    string json = Functions.DataTableToJSON(dt);
                    //return Json(result, JsonRequestBehavior.AllowGet);
                    return json;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
</code>```

I want to protect these APIs and I would like to how to do that properly

I thought of adding UserID and Password to each API so the use send them as parameters

so it will be like this

```<code>    [Route("api/CallSP")]
    public string Get(string UserID, string Password, string SP = null, string Type = null, string Ps = null, string P0 = null, string P1 = null, string P2 = null, string P3 = null)
    {
</code>```

Is there a better solution?

答: No, you can't send secure data like passwords in the query as it could be easily stolen. In that case you should create an endpoint to authenticate the user and return to user secure string. This secure string is called JWT token. After that you put this token inside each request in the Authorization header. If API configured properly, and you used [Authorize] attribute, then you will automatically pass an authorization and step into your method. You can find the easiest code example (but post is in different language) here.

Body:
I have built APIs on c#.Net

these APIs works fine, but they are not secure, which means anyone worldwide can use it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.SqlClient;
using System.Data;

namespace CDAPIs.Controllers
{
    public class CallSPController : ApiController
    {

        [Route("api/CallSP")]
        public string Get(string SP = null, string Type = null, string Ps = null, string P0 = null, string P1 = null, string P2 = null, string P3 = null)
        {
            string sDBConn = Functions.GetConn();
            string[] Parms = Ps.Split(',');
            SqlConnection conn = new SqlConnection(sDBConn);
            SqlCommand cmd = new SqlCommand(SP, conn);
            cmd.CommandTimeout = 0;
            cmd.CommandType = CommandType.StoredProcedure;

            string P = "";
            for (int i = 0; i < Parms.Length; i++)
            {
                if (i == 0) { P = P0; }
                if (i == 1) { P = P1; }
                if (i == 2) { P = P2; }
                if (i == 3) { P = P3; }
                cmd.Parameters.Add(new SqlParameter("@" + Parms[i].Trim(), P));
            }

            try
            {
                conn.Open();

                if (Type.ToUpper().Trim() == "STRING")
                {
                    string st = cmd.ExecuteScalar().ToString();
                    conn.Close();
                    conn.Dispose();
                    return st;
                }
                else
                {
                    SqlDataReader rdr = cmd.ExecuteReader();
                    var dt = new DataTable();
                    dt.Load(rdr);
                    List<DataRow> result = dt.AsEnumerable().ToList();
                    rdr.Close();
                    conn.Close();
                    conn.Dispose();
                    string json = Functions.DataTableToJSON(dt);
                    //return Json(result, JsonRequestBehavior.AllowGet);
                    return json;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}

I want to protect these APIs and I would like to how to do that properly

I thought of adding UserID and Password to each API so the use send them as parameters

so it will be like this

    [Route("api/CallSP")]
    public string Get(string UserID, string Password, string SP = null, string Type = null, string Ps = null, string P0 = null, string P1 = null, string P2 = null, string P3 = null)
    {

Is there a better solution?


问:
How do git's built-in large file handling features deal with checksumming files?
It seems that the git team has been working on large binary file handling features that don't require git LFS - features like partial clone, and sparse checkout. That's great.

The one thing I'm not totally clear about is how these features are supposed to improve this issue:

Correct me if I'm wrong, but every time you run git status, git quickly does a checksum of all the files in your working directory, and compares that to the stored checksums in HEAD to see which files changed. This works great for text files, and is so common, and so fast an operation that many shells build the current branch, and whether or not your current working directory is clean into the shell prompt:

With large files however, doing a checksum can take multiple seconds, or even minutes. That means every time you type git status, or in a fancy shell with a custom, git-enabled prompt hit "enter", it can take several seconds to checksum the large files in your working directory to figure out if they've changed. That means that either your git status command will take several seconds/minutes to return, or worse, EVERY command will take several seconds/minutes to return while your current working directory is in the git repo, as the shell itself will try to figure out the repo's current status to show you the proper prompt.

This isn't theoretical - I've seen this happen with git LFS. If I have a large, modified file in my working directory, working in that git repo becomes a colossal pain. git status takes forever to return, and with a custom shell, every single command you type takes forever to return as the shell tries to generate your prompt text.

Is this meant to be addressed by sparse checkout, where you just don't checkout the large files? Or is there something else meant to address this?

答:
Git stores certain information in the index, which reflects things like the file size, device and inode numbers, modification and inode change times, and various other attributes.  If this information is changed, or is potentially stale, then Git will re-read the file to see if it's modified.  This is potentially expensive, as you've noticed, and Git's detection here is the reason that Git LFS has this same performance problem: Git is telling Git LFS to reprocess the file.

What you want to do is find out what's modifying the attributes of your files.  For example, if you have some sort of file monitoring or backup software, then that can cause this problem, or if you're using some sort of cloud syncing service (which you should avoid anyway because it will probably corrupt your repository).  This can also happen if you mount the repository into a container, since the container will have different device and inode numbers, and then each time you alternate in which environment you run git status, the entire repository must be re-read.

For example, on my systems, I don't have this problem and my system performs just fine.  However, if you really can't figure it out, you can try setting core.trustctime to false and/or core.checkstat to minimal (which you should try in that order).  That will put less data in the index, and then it's less likely to become stale when nothing's changed.  However, it also means that it's more likely that Git will fail to detect a legitimate change, so if you can avoid needing to do this, you should.


问:
Is it possible to have flexible decimal_places for a model in django?
I am working in a model that i would like to use for diferent kinds of investmensts. So i am wondering if is it possíble to have flexible decimals.

For example:

This is the class

```<code>class Asset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    shares_amount = models.DecimalField(max_digits=18, decimal_places=0, default=0)
    share_cost = models.DecimalField(max_digits=18, decimal_places=0, default=0)
</code>```

If i leave it blank i get the error: "DecimalFields must define a 'decimal_places' attribute."

Maybe what i am trying is not possíble, probably i need to find another solution. I am open to suggestions

I would like to know if is possíble to have this decimal places fleixible.

答:
I found out a solution that worked for what i was wondering to achieve.

I chaged the field to a FloatField type, instead of DecimalField. Than i got more flexibilie on how many decimals, without restrictions:

```<code>shares_amount = models.FloatField()
</code>```

As there where using some mathemathic operations, started to show this conflict error:

*unsupported operand type(s) for : 'float' and 'decimal.Decimal'

The solution was here on the forum:

unsupported operand type(s) for *: 'float' and 'Decimal'

So for the mathematics it was just do that:

```<code>decimal.Decimal(self.shares_amount) * self.share_cost

</code>```

Body:
I am working in a model that i would like to use for diferent kinds of investmensts. So i am wondering if is it possíble to have flexible decimals.

For example:

This is the class

class Asset(models.Model):
    portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    shares_amount = models.DecimalField(max_digits=18, decimal_places=0, default=0)
    share_cost = models.DecimalField(max_digits=18, decimal_places=0, default=0)

If i leave it blank i get the error: "DecimalFields must define a 'decimal_places' attribute."

Maybe what i am trying is not possíble, probably i need to find another solution. I am open to suggestions

I would like to know if is possíble to have this decimal places fleixible.

Body:
I found out a solution that worked for what i was wondering to achieve.

I chaged the field to a FloatField type, instead of DecimalField. Than i got more flexibilie on how many decimals, without restrictions:

shares_amount = models.FloatField()

As there where using some mathemathic operations, started to show this conflict error:

*unsupported operand type(s) for : 'float' and 'decimal.Decimal'

The solution was here on the forum:

unsupported operand type(s) for *: 'float' and 'Decimal'

So for the mathematics it was just do that:

decimal.Decimal(self.shares_amount) * self.share_cost


问:
Why is test >= 0 true when test is null?
Let's say I have the following javascript code:

const test = null

if ( test >= 0 ){
    console.log("Hello World")
}```
</div>
</div>
</p>
<p>This code will print <code>Hello World</code>... In my mind, it should work only if <code>test === null</code>. But all the times that I use the condition <code>test >= 0</code> the code falls on it. Is there any reason why it happens? I see it as a problem in some situations... For example on the next code:</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>const test = null

if ( test >= 0 ){
    console.log("1")
}
else if ( test === null ){
    console.log("Hello World")
}</code>```

In this case, the code is not doing what apparently it should be doing. The workaround to make it work would be having the habit of always putting the === null condition at first on if/else or switch/cases. Is that how I'm supposed to work with Javascript? Or is there a better way of doing it?

答:
Is there any reason why it happens?

Any value that is compared to a number will be coerced to a number1. Number(null) is 0, and 0 >= 0 is true. If you had used undefined on the other hand, you'd have gotten NaN >= 0 which is false.

1: In fact, the only non-numeric relational comparison is between two strings (or two objects that convert to strings).

The workaround to make it work would be having the habit of always putting the === null condition at first.

Yes, that's how to deal with variables that can have the value null.

Or is there a better way of doing it?

You might want to avoid having the value null at all in your variable. Depending on the application, whatever the value is representing, could also be expressed as 0 or -1 maybe? Those may not be much cleaner, but they would at least have predictable behaviour in >= 0.

Body:
Let's say I have the following javascript code:

const test = null

if ( test >= 0 ){
    console.log("Hello World")
}

This code will print Hello World... In my mind, it should work only if test === null. But all the times that I use the condition test >= 0 the code falls on it. Is there any reason why it happens? I see it as a problem in some situations... For example on the next code:

const test = null

if ( test >= 0 ){
    console.log("1")
}
else if ( test === null ){
    console.log("Hello World")
}

In this case, the code is not doing what apparently it should be doing. The workaround to make it work would be having the habit of always putting the === null condition at first on if/else or switch/cases. Is that how I'm supposed to work with Javascript? Or is there a better way of doing it?


问:
Segmentation fault occurred when providing incorrect HTTP_PROXY_OPTIONS in azure iot sdk c
I am developing a small application that uses the azure iot sdk in C (lts_07_2021). All my test cases worked well except for one that is related to the proxy. When providing a working/correct proxy server information, my application successfully connected without any problems. But when I provided a non-working proxy information, it produces a segfault. I expected that the SDK will provide some sort of error message but not the segfault.

It can also be reproduced using the example provided by azure in azure-iot-sdk-c/iothub_client/samples/iothub_ll_telemetry_sample
I just added the following options:

```<code>    HTTP_PROXY_OPTIONS proxy;
    memset(&proxy, 0, sizeof(HTTP_PROXY_OPTIONS));
    proxy.host_address = "x.x.x.x"; //non-working proxy server
    proxy.port = 3128;
    (void)IoTHubDeviceClient_LL_SetOption(device_ll_handle, OPTION_HTTP_PROXY,&proxy);
</code>```

Heres the terminal output when running iothub_ll_telemetry_sample provided by azure + INCORRECT PROXY:
https://github.com/Azure/azure-iot-sdk-c/blob/lts_07_2021/iothub_client/samples/iothub_ll_telemetry_sample/iothub_ll_telemetry_sample.c

```<code>[iothub_ll_telemetry_sample]$ ./iothub_ll_telemetry_sample
Creating IoTHub Device handle
Sending message 1 to IoTHub
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/adapters/socketio_berkeley.c Func:wait_for_connection Line:415 Failure: select failure.
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/adapters/socketio_berkeley.c Func:socketio_open Line:833 wait_for_connection failed
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/src/http_proxy_io.c Func:on_underlying_io_open_complete Line:280 Underlying IO open failed
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/umqtt/src/mqtt_client.c Func:onOpenComplete Line:454 Error: failure opening connection to endpoint
The device client has been disconnected
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/adapters/tlsio_openssl.c Func:on_underlying_io_open_complete Line:849 Invalid tlsio_state. Expected state is TLSIO_STATE_OPENING_UNDERLYING_IO.
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/src/http_proxy_io.c Func:http_proxy_io_open Line:749 Cannot open the underlying IO.
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/adapters/tlsio_openssl.c Func:tlsio_openssl_open Line:1437 Failed opening the underlying I/O.
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/src/uws_client.c Func:uws_client_open_async Line:1700 Opening the underlying IO failed
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/src/wsio.c Func:wsio_open Line:519 Opening the uws instance failed.
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/umqtt/src/mqtt_client.c Func:mqtt_client_connect Line:1118 Error: io_open failed
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/iothub_client/src/iothubtransport_mqtt_common.c Func:SendMqttConnectMsg Line:2696 failure connecting to address xxxxxxxxxx.azure-devices.net.
Sending message 2 to IoTHub
Segmentation fault (core dumped)
</code>```

Here's the backtrace:
It seems like the stack frames goes on and on... repeating

```<code>#0  0x00000000004383c7 in OptionHandler_Destroy ()
#1  0x00000000004403c1 in http_proxy_io_destroy_option ()
#2  0x0000000000437ea3 in DestroyInternal ()
#3  0x00000000004383cc in OptionHandler_Destroy ()
#4  0x00000000004403c1 in http_proxy_io_destroy_option ()
#5  0x0000000000437ea3 in DestroyInternal ()
#6  0x00000000004383cc in OptionHandler_Destroy ()
#7  0x00000000004403c1 in http_proxy_io_destroy_option ()
#8  0x0000000000437ea3 in DestroyInternal ()
#9  0x00000000004383cc in OptionHandler_Destroy ()
#10 0x00000000004403c1 in http_proxy_io_destroy_option ()
#11 0x0000000000437ea3 in DestroyInternal ()
#12 0x00000000004383cc in OptionHandler_Destroy ()
#13 0x00000000004403c1 in http_proxy_io_destroy_option ()
#14 0x0000000000437ea3 in DestroyInternal ()
#15 0x00000000004383cc in OptionHandler_Destroy ()
#16 0x00000000004403c1 in http_proxy_io_destroy_option ()
#17 0x0000000000437ea3 in DestroyInternal ()
#18 0x00000000004383cc in OptionHandler_Destroy ()
#19 0x00000000004403c1 in http_proxy_io_destroy_option ()
#20 0x0000000000437ea3 in DestroyInternal ()
#21 0x00000000004383cc in OptionHandler_Destroy ()
#22 0x00000000004403c1 in http_proxy_io_destroy_option ()
#23 0x0000000000437ea3 in DestroyInternal ()
#24 0x00000000004383cc in OptionHandler_Destroy ()
#25 0x00000000004403c1 in http_proxy_io_destroy_option ()
#26 0x0000000000437ea3 in DestroyInternal ()
#27 0x00000000004383cc in OptionHandler_Destroy ()
#28 0x00000000004403c1 in http_proxy_io_destroy_option ()
#29 0x0000000000437ea3 in DestroyInternal ()
#30 0x00000000004383cc in OptionHandler_Destroy ()
#31 0x00000000004403c1 in http_proxy_io_destroy_option ()
#32 0x0000000000437ea3 in DestroyInternal ()
#33 0x00000000004383cc in OptionHandler_Destroy ()
#34 0x00000000004403c1 in http_proxy_io_destroy_option ()
#35 0x0000000000437ea3 in DestroyInternal ()
#36 0x00000000004383cc in OptionHandler_Destroy ()
#37 0x00000000004403c1 in http_proxy_io_destroy_option ()
#38 0x0000000000437ea3 in DestroyInternal ()
#39 0x00000000004383cc in OptionHandler_Destroy ()
#40 0x00000000004403c1 in http_proxy_io_destroy_option ()
#41 0x0000000000437ea3 in DestroyInternal ()
#42 0x00000000004383cc in OptionHandler_Destroy ()
#43 0x00000000004403c1 in http_proxy_io_destroy_option ()
#44 0x0000000000437ea3 in DestroyInternal ()
#45 0x00000000004383cc in OptionHandler_Destroy ()
#46 0x00000000004403c1 in http_proxy_io_destroy_option ()
#47 0x0000000000437ea3 in DestroyInternal ()
#48 0x00000000004383cc in OptionHandler_Destroy ()
#49 0x00000000004403c1 in http_proxy_io_destroy_option ()
#50 0x0000000000437ea3 in DestroyInternal ()
#51 0x00000000004383cc in OptionHandler_Destroy ()
#52 0x00000000004403c1 in http_proxy_io_destroy_option ()
#53 0x0000000000437ea3 in DestroyInternal ()
#54 0x00000000004383cc in OptionHandler_Destroy ()
#55 0x00000000004403c1 in http_proxy_io_destroy_option ()
.
.
.
.
.
.#xxxxx repeatedly goes on and on
</code>```

System information:
CentOS-7
cURL7.29
openssl1.0.2k

答:
This issue was fixed by https://github.com/Azure/azure-c-shared-utility/commit/2d74785c2b475ca94321114a23f8007094bdac11

Updating to the latest lts_01_2022 solved this problem.

Thanks!

Body:
I am developing a small application that uses the azure iot sdk in C (lts_07_2021). All my test cases worked well except for one that is related to the proxy. When providing a working/correct proxy server information, my application successfully connected without any problems. But when I provided a non-working proxy information, it produces a segfault. I expected that the SDK will provide some sort of error message but not the segfault.

It can also be reproduced using the example provided by azure in azure-iot-sdk-c/iothub_client/samples/iothub_ll_telemetry_sample
I just added the following options:

    HTTP_PROXY_OPTIONS proxy;
    memset(&proxy, 0, sizeof(HTTP_PROXY_OPTIONS));
    proxy.host_address = "x.x.x.x"; //non-working proxy server
    proxy.port = 3128;
    (void)IoTHubDeviceClient_LL_SetOption(device_ll_handle, OPTION_HTTP_PROXY,&proxy);

Heres the terminal output when running iothub_ll_telemetry_sample provided by azure + INCORRECT PROXY:
https://github.com/Azure/azure-iot-sdk-c/blob/lts_07_2021/iothub_client/samples/iothub_ll_telemetry_sample/iothub_ll_telemetry_sample.c

[iothub_ll_telemetry_sample]$ ./iothub_ll_telemetry_sample
Creating IoTHub Device handle
Sending message 1 to IoTHub
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/adapters/socketio_berkeley.c Func:wait_for_connection Line:415 Failure: select failure.
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/adapters/socketio_berkeley.c Func:socketio_open Line:833 wait_for_connection failed
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/src/http_proxy_io.c Func:on_underlying_io_open_complete Line:280 Underlying IO open failed
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/umqtt/src/mqtt_client.c Func:onOpenComplete Line:454 Error: failure opening connection to endpoint
The device client has been disconnected
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/adapters/tlsio_openssl.c Func:on_underlying_io_open_complete Line:849 Invalid tlsio_state. Expected state is TLSIO_STATE_OPENING_UNDERLYING_IO.
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/src/http_proxy_io.c Func:http_proxy_io_open Line:749 Cannot open the underlying IO.
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/adapters/tlsio_openssl.c Func:tlsio_openssl_open Line:1437 Failed opening the underlying I/O.
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/src/uws_client.c Func:uws_client_open_async Line:1700 Opening the underlying IO failed
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/c-utility/src/wsio.c Func:wsio_open Line:519 Opening the uws instance failed.
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/umqtt/src/mqtt_client.c Func:mqtt_client_connect Line:1118 Error: io_open failed
Error: Time:Tue Feb  8 13:14:51 2022 File:/isolated/azure-iot-sdk-c/iothub_client/src/iothubtransport_mqtt_common.c Func:SendMqttConnectMsg Line:2696 failure connecting to address xxxxxxxxxx.azure-devices.net.
Sending message 2 to IoTHub
Segmentation fault (core dumped)

Here's the backtrace:
It seems like the stack frames goes on and on... repeating

#0  0x00000000004383c7 in OptionHandler_Destroy ()
#1  0x00000000004403c1 in http_proxy_io_destroy_option ()
#2  0x0000000000437ea3 in DestroyInternal ()
#3  0x00000000004383cc in OptionHandler_Destroy ()
#4  0x00000000004403c1 in http_proxy_io_destroy_option ()
#5  0x0000000000437ea3 in DestroyInternal ()
#6  0x00000000004383cc in OptionHandler_Destroy ()
#7  0x00000000004403c1 in http_proxy_io_destroy_option ()
#8  0x0000000000437ea3 in DestroyInternal ()
#9  0x00000000004383cc in OptionHandler_Destroy ()
#10 0x00000000004403c1 in http_proxy_io_destroy_option ()
#11 0x0000000000437ea3 in DestroyInternal ()
#12 0x00000000004383cc in OptionHandler_Destroy ()
#13 0x00000000004403c1 in http_proxy_io_destroy_option ()
#14 0x0000000000437ea3 in DestroyInternal ()
#15 0x00000000004383cc in OptionHandler_Destroy ()
#16 0x00000000004403c1 in http_proxy_io_destroy_option ()
#17 0x0000000000437ea3 in DestroyInternal ()
#18 0x00000000004383cc in OptionHandler_Destroy ()
#19 0x00000000004403c1 in http_proxy_io_destroy_option ()
#20 0x0000000000437ea3 in DestroyInternal ()
#21 0x00000000004383cc in OptionHandler_Destroy ()
#22 0x00000000004403c1 in http_proxy_io_destroy_option ()
#23 0x0000000000437ea3 in DestroyInternal ()
#24 0x00000000004383cc in OptionHandler_Destroy ()
#25 0x00000000004403c1 in http_proxy_io_destroy_option ()
#26 0x0000000000437ea3 in DestroyInternal ()
#27 0x00000000004383cc in OptionHandler_Destroy ()
#28 0x00000000004403c1 in http_proxy_io_destroy_option ()
#29 0x0000000000437ea3 in DestroyInternal ()
#30 0x00000000004383cc in OptionHandler_Destroy ()
#31 0x00000000004403c1 in http_proxy_io_destroy_option ()
#32 0x0000000000437ea3 in DestroyInternal ()
#33 0x00000000004383cc in OptionHandler_Destroy ()
#34 0x00000000004403c1 in http_proxy_io_destroy_option ()
#35 0x0000000000437ea3 in DestroyInternal ()
#36 0x00000000004383cc in OptionHandler_Destroy ()
#37 0x00000000004403c1 in http_proxy_io_destroy_option ()
#38 0x0000000000437ea3 in DestroyInternal ()
#39 0x00000000004383cc in OptionHandler_Destroy ()
#40 0x00000000004403c1 in http_proxy_io_destroy_option ()
#41 0x0000000000437ea3 in DestroyInternal ()
#42 0x00000000004383cc in OptionHandler_Destroy ()
#43 0x00000000004403c1 in http_proxy_io_destroy_option ()
#44 0x0000000000437ea3 in DestroyInternal ()
#45 0x00000000004383cc in OptionHandler_Destroy ()
#46 0x00000000004403c1 in http_proxy_io_destroy_option ()
#47 0x0000000000437ea3 in DestroyInternal ()
#48 0x00000000004383cc in OptionHandler_Destroy ()
#49 0x00000000004403c1 in http_proxy_io_destroy_option ()
#50 0x0000000000437ea3 in DestroyInternal ()
#51 0x00000000004383cc in OptionHandler_Destroy ()
#52 0x00000000004403c1 in http_proxy_io_destroy_option ()
#53 0x0000000000437ea3 in DestroyInternal ()
#54 0x00000000004383cc in OptionHandler_Destroy ()
#55 0x00000000004403c1 in http_proxy_io_destroy_option ()
.
.
.
.
.
.#xxxxx repeatedly goes on and on

System information:
CentOS-7
cURL7.29
openssl1.0.2k


问:
How do I update multiple columns with a subquery in a single statement?
I am attempting to update a temp table from a source table:

```<code>    UPDATE #DETAIL
        SET EXCD_ID, CDOR_OR_AMT, CDOR_OR_VALUE
        (SELECT
            CDID_ADDL_DATA_1, CDID_ADDL_DATA, CDID_VALUE_STRING
        FROM
            CMC_CDID_DATA CDID
        WHERE
            CDID.CLCL_ID = DTL.CLCL_ID AND
            CDID.CDML_SEQ_NO = DTL.CDML_SEQ_NO AND
            CDID_TYPE = 'NDC'
    )
    FROM #DETAIL DTL
    WHERE DTL.CDOR_OR_ID = 'XS'
</code>```

Unfortunately it complains

```<code>Incorrect syntax near ',' (on the '(SELECT' line)
Incorrect syntax near 'FROM' (the second one)
</code>```

答:
I just tried this out and it worked (on Oracle)

```<code>update dstTable T
    set (T.field1, T.field2, T.field3) =
           (select S.value1, S.value2, S.value3
            from srcTable S
             where S.key = T.Key);
</code>```

This, unfortunately is Oracle specific syntax.

Caveat: Note that the update above has no where clause.  It updates the entire table.  If the subquery return no rows then the target fields are set to NULL.  Also, it's an error if the subquery returns more than one row.

Body:
I am attempting to update a temp table from a source table:

    UPDATE #DETAIL
        SET EXCD_ID, CDOR_OR_AMT, CDOR_OR_VALUE
        (SELECT
            CDID_ADDL_DATA_1, CDID_ADDL_DATA, CDID_VALUE_STRING
        FROM
            CMC_CDID_DATA CDID
        WHERE
            CDID.CLCL_ID = DTL.CLCL_ID AND
            CDID.CDML_SEQ_NO = DTL.CDML_SEQ_NO AND
            CDID_TYPE = 'NDC'
    )
    FROM #DETAIL DTL
    WHERE DTL.CDOR_OR_ID = 'XS'

Unfortunately it complains

Incorrect syntax near ',' (on the '(SELECT' line)
Incorrect syntax near 'FROM' (the second one)

Body:
I just tried this out and it worked (on Oracle)

update dstTable T
    set (T.field1, T.field2, T.field3) =
           (select S.value1, S.value2, S.value3
            from srcTable S
             where S.key = T.Key);

This, unfortunately is Oracle specific syntax.

Caveat: Note that the update above has no where clause.  It updates the entire table.  If the subquery return no rows then the target fields are set to NULL.  Also, it's an error if the subquery returns more than one row.


问:
OSX - How to auto Close Terminal window after the "exit" command executed.
When I'm done with Terminal, I want to exit it. Right now, I have three options:

killall Terminal. It will end the process, but rather abruptly. I don't think this is the best idea.

Call exit. I've changed the settings so exit closes Terminal. The app still appears open in the Dock though, and doesn't do what I want it to do.

Right click>Quit. However, this isn't a Terminal command to exit it.

So now, what is the way I should exit and close Terminal? I've heard something about osascript but I'm not too sure. I want to exit and close, so that Terminal is no longer open, both as a window and as a process.

答:
This is what I did for a command I just wrote. I wanted to be able to create a "shortcut" to the Backup directory for Apple Configurator that worked on different computers, but since it's relative to the user's home directory, I needed to make it a .command file. Here are the contents:

#!/usr/bin/env bash

open "${HOME}/Library/Application Support/MobileSync/Backup"
(sleep 0.1 ; osascript -e 'tell application "Terminal" to quit') &
```


问:
How do I add a hyperlink in my text using JavaScript?
I'm really new to JS and I tried googling but it did not help. All I'm trying to do is add the medium Post link into my text as a hyperlink. I'm pretty sure I'm half way there but I can't figure it out:

_$ = document.querySelector.bind(document) ;
var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
var a = document.createElement('a');
a.text = "Medium Post";
a.href = "https://medium.com/@FundsFi/fundsfi-presale-terms-are-here-whitelisting-requirements-fc798d85b284";

// AppendLinkHere.appendChild(a)
// a.title = 'Well well ...
// a.setAttribute('title', 'Well well that\'s a link');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><s.TextDescription style={{ textAlign: "center", color: "var(--primary-text)", }}>
  blah blah blah blah blah blah blah blah blah blah  Medium Post.
</s.TextDescription></code>```

All I want to do is make it so that when people click on the word Medium Post it takes them to a new tab with the medium link. Also, I got the code from this post while searching for an answer: How do I create a link using javascript? And then I realized that I need to added a CSS selector which I can't figure out how to do. So far I've found this post about: How do you add CSS with Javascript?

答:
From what I understand you want an HTML page to include a text that a user can click to go to a new lab that has your link, well there is a lot of ways you can do this including writing in in HTML code instead of javascript so it'll be
medium and that will show a hyperlink text on the page that when clicked would take you to a new page or if you want to use javascript you can use the document.querySelector("id here").innerHTML = 'medium'; and that would allow you to show the link inside the page and link on an event if set up with document.addEventListener but keep in mind that it will remove all the code, text and tags inside the selected tag and put the link.
Sorry if I got something wrong, I'm still kinda new :D

Body:
I'm really new to JS and I tried googling but it did not help. All I'm trying to do is add the medium Post link into my text as a hyperlink. I'm pretty sure I'm half way there but I can't figure it out:

_$ = document.querySelector.bind(document) ;
var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
var a = document.createElement('a');
a.text = "Medium Post";
a.href = "https://medium.com/@FundsFi/fundsfi-presale-terms-are-here-whitelisting-requirements-fc798d85b284";

// AppendLinkHere.appendChild(a)
// a.title = 'Well well ...
// a.setAttribute('title', 'Well well that\'s a link');

<s.TextDescription style={{ textAlign: "center", color: "var(--primary-text)", }}>
  blah blah blah blah blah blah blah blah blah blah  Medium Post.
</s.TextDescription>

All I want to do is make it so that when people click on the word Medium Post it takes them to a new tab with the medium link. Also, I got the code from this post while searching for an answer: How do I create a link using javascript? And then I realized that I need to added a CSS selector which I can't figure out how to do. So far I've found this post about: How do you add CSS with Javascript?

Body:
From what I understand you want an HTML page to include a text that a user can click to go to a new lab that has your link, well there is a lot of ways you can do this including writing in in HTML code instead of javascript so it'll be
<a href="link here" target="_blank">medium</a> and that will show a hyperlink text on the page that when clicked would take you to a new page or if you want to use javascript you can use the document.querySelector("id here").innerHTML = '<a href="link here" target="_blank">medium</a>'; and that would allow you to show the link inside the page and link on an event if set up with document.addEventListener but keep in mind that it will remove all the code, text and tags inside the selected tag and put the link.
Sorry if I got something wrong, I'm still kinda new :D


问:
Clear contents of cells E through AN if cell E has contents
I am trying to clear all of the contents from columns E through AN for only the rows that have data in Column E (and not continue through the rest of the sheet). I would like the formulas in the cells to stay intact.

Any help greatly appreciated!

```<code>Sub ClearJEdetails()

    Dim rng As Range

    Set rng = Range("e12:AI1048530")

    'Selecting only hardcoded data
      rng.SpecialCells(xlCellTypeConstants).Select

    Selection.ClearContents

End Sub

Sub ClearJEformulas()

    Dim rng As Range

    Set rng = Range("aj13:Ak1048530")

    'Selecting only formulas
      rng.SpecialCells(xlCellTypeFormulas).Select

    Selection.ClearContents

End Sub
</code>```

答:
Clear Contents of Filtered Rows in Certain Columns

Adjust the values in the constants section.

Option Explicit

Sub DeleteFilteredEntireRows()

    Const wsName As String = "Sheet1"
    Const hRow As Long = 1
    Const lrCol As String = "E"
    Const Cols As String = "E:AN"
    Const Criteria As String = "<>" ' non-blanks

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
    If ws.AutoFilterMode Then ws.AutoFilterMode = False
    Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, lrCol).End(xlUp).Row
    Dim rCount As Long: rCount = lRow - hRow + 1
    Dim scrg As Range: Set scrg = ws.Cells(hRow, lrCol).Resize(rCount)
    Dim scdrg As Range: Set scdrg = scrg.Resize(rCount - 1).Offset(1)

    scrg.AutoFilter 1, Criteria
    Dim vcdrg As Range
    On Error Resume Next
        Set vcdrg = scdrg.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    ws.AutoFilterMode = False

    If vcdrg Is Nothing Then Exit Sub

    Dim drg As Range: Set drg = Intersect(vcdrg.EntireRow, ws.Columns(Cols))

    drg.ClearContents

End Sub
```

Body:
I am trying to clear all of the contents from columns E through AN for only the rows that have data in Column E (and not continue through the rest of the sheet). I would like the formulas in the cells to stay intact.

Any help greatly appreciated!

Sub ClearJEdetails()

    Dim rng As Range

    Set rng = Range("e12:AI1048530")

    'Selecting only hardcoded data
      rng.SpecialCells(xlCellTypeConstants).Select

    Selection.ClearContents

End Sub

Sub ClearJEformulas()

    Dim rng As Range

    Set rng = Range("aj13:Ak1048530")

    'Selecting only formulas
      rng.SpecialCells(xlCellTypeFormulas).Select

    Selection.ClearContents

End Sub


问:
How to retrieve View definition on Synapse (Azure SQL DW)?
I am new to Synapse (Azure SQL DW). Currently, the DW has lots of views and I need to modify a handful of them. The issue is that I do not know how the views were created.
Is there a query to check the view definition in Synapse or more specifically, the SELECT statement was used to create the view ?

Kind regards,
Ken

答:
OBJECT_DEFINITION is definitely the way to go.
See the MS docs.

For example, if you want to find out the create statement for a view called dbo.example, you would do the following:

select object_definition(object_id(N'dbo.example')) as [Trigger Definition];
```

That's it!

Body:
OBJECT_DEFINITION is definitely the way to go.
See the MS docs.

For example, if you want to find out the create statement for a view called dbo.example, you would do the following:

select object_definition(object_id(N'dbo.example')) as [Trigger Definition];

That's it!


问:
How can I left join a subquery in hibernate with criteria?
I want to be able to left join a subquery in hibernate with criteria.

Here is sample query:

```<code>Select * From Order o
Left Join (Select * From Product p Where p.accountId = 3) p
On p.id = o.productId
Where (p.category is not null and p.category = 'clothes') or
(p.category is null and o.category = 'clothes')
</code>```

Note this is a sample query, mine is more complex and I need to be able to left join a subquery.

How could you generate this query with the hibernate criteria syntax?

I would like to do something similar to this:

```<code>Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(Order.class);

DetachedCriteria productCriteria = DetachedCriteria.forClass(Product.class);
productCriteria.add(Restrictions.eq("accountId", 3));

criteria.createAlias("productCriteria", "p", JoinType.LEFT_OUTER_JOIN, productCriteria);

criteria.add(Restrictions.or(
        Restrictions.and(Restrictions.isNotNull("p.category"), Restrictions.eq("p.category", "clothes")),
   Restrictions.and(Restrictions.isNull("p.category"), Restrictions.eq("category", "clothes"))
));

List list = criteria.list();
</code>```

Edit

In my real problem the subquery consists of two tables.

答:
You can use the following Criteria method to use subquery in joins.

```<code>public Criteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException;
</code>```

and a Criterion parameter, which you can create with the Subqueries factory class, will generate a subquery in the join condition.

You will end up with something like this:

```<code>Criteria criteria = session.createCriteria(Order.class);

DetachedCriteria productCriteria = DetachedCriteria.forClass(Product.class)
                .setProjection(property("id"))
                .add(Restrictions.eq("accountId", 3));

criteria.createAlias("product", "p", JoinType.LEFT_OUTER_JOIN, Subqueries.propertyEq("id", productCriteria));
...
</code>```

Body:
I want to be able to left join a subquery in hibernate with criteria.

Here is sample query:

Select * From Order o
Left Join (Select * From Product p Where p.accountId = 3) p
On p.id = o.productId
Where (p.category is not null and p.category = 'clothes') or
(p.category is null and o.category = 'clothes')

Note this is a sample query, mine is more complex and I need to be able to left join a subquery.

How could you generate this query with the hibernate criteria syntax?

I would like to do something similar to this:

Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(Order.class);

DetachedCriteria productCriteria = DetachedCriteria.forClass(Product.class);
productCriteria.add(Restrictions.eq("accountId", 3));

criteria.createAlias("productCriteria", "p", JoinType.LEFT_OUTER_JOIN, productCriteria);

criteria.add(Restrictions.or(
        Restrictions.and(Restrictions.isNotNull("p.category"), Restrictions.eq("p.category", "clothes")),
   Restrictions.and(Restrictions.isNull("p.category"), Restrictions.eq("category", "clothes"))
));

List list = criteria.list();

Edit

In my real problem the subquery consists of two tables.

Body:
You can use the following Criteria method to use subquery in joins.

public Criteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException;

and a Criterion parameter, which you can create with the Subqueries factory class, will generate a subquery in the join condition.

You will end up with something like this:

Criteria criteria = session.createCriteria(Order.class);

DetachedCriteria productCriteria = DetachedCriteria.forClass(Product.class)
                .setProjection(property("id"))
                .add(Restrictions.eq("accountId", 3));

criteria.createAlias("product", "p", JoinType.LEFT_OUTER_JOIN, Subqueries.propertyEq("id", productCriteria));
...


问:
Terraform auth problem with the google_firebase_project resource
I've imported my firebase project as a terraform resource, but got this when ran terraform plan:

```<code>│ Error: Error when reading or editing FirebaseProject "projects/myproject": googleapi: Error 403: Your application has authenticated using end user credentials from the Google Cloud SDK or Google Cloud Shell which are not supported by the firebase.googleapis.com. We recommend configuring the billing/quota_project setting in gcloud or using a service account through the auth/impersonate_service_account setting. For more information about service accounts and how to use them in your application, see https://cloud.google.com/docs/authentication/. If you are getting this error with curl or similar tools, you may need to specify 'X-Goog-User-Project' HTTP header for quota and billing purposes. For more information regarding 'X-Goog-User-Project' header, please check https://cloud.google.com/apis/docs/system-parameters.
│ Details:
│ [
│   {
│     "@type": "type.googleapis.com/google.rpc.ErrorInfo",
│     "domain": "googleapis.com",
│     "metadata": {
│       "consumer": "projects/774686551450",
│       "service": "firebase.googleapis.com"
│     },
│     "reason": "SERVICE_DISABLED"
│   }
│ ]
│
│   with google_firebase_project.default,
│   on main.tf line 27, in resource "google_firebase_project" "default":
│   27: resource "google_firebase_project" "default" {
</code>```

If I set the GOOGLE_APPLICATION_CREDENTIALS env var to a service account of that project, it seems to work, but I'd like to avoid it as it is required to re-export that variable each time I'm changing environment.

I've authenticated to gcloud via my user, which is admin for all the relevant project.

答:
As an external tool, terraform requires some method of authenticating with GCP. You have only two options:

A service account with the required permissions.

A GSuite user or group with the required permissions.

One service or group or user account can be granted permissions on multiple projects, although this has security implications (blast radius mainly) and I wouldn't recommend it.

Switching accounts when working with different projects might be annoying, but is currently the best way.

If you're working with GKE, you may be able to leverage their workload identity feature. I'm not exactly sure about how this works, but I believe it enables automatic switching to the correct service account depending on the workload. Ultimately, separate service accounts are still required.

Body:
I've imported my firebase project as a terraform resource, but got this when ran terraform plan:

│ Error: Error when reading or editing FirebaseProject "projects/myproject": googleapi: Error 403: Your application has authenticated using end user credentials from the Google Cloud SDK or Google Cloud Shell which are not supported by the firebase.googleapis.com. We recommend configuring the billing/quota_project setting in gcloud or using a service account through the auth/impersonate_service_account setting. For more information about service accounts and how to use them in your application, see https://cloud.google.com/docs/authentication/. If you are getting this error with curl or similar tools, you may need to specify 'X-Goog-User-Project' HTTP header for quota and billing purposes. For more information regarding 'X-Goog-User-Project' header, please check https://cloud.google.com/apis/docs/system-parameters.
│ Details:
│ [
│   {
│     "@type": "type.googleapis.com/google.rpc.ErrorInfo",
│     "domain": "googleapis.com",
│     "metadata": {
│       "consumer": "projects/774686551450",
│       "service": "firebase.googleapis.com"
│     },
│     "reason": "SERVICE_DISABLED"
│   }
│ ]
│
│   with google_firebase_project.default,
│   on main.tf line 27, in resource "google_firebase_project" "default":
│   27: resource "google_firebase_project" "default" {

If I set the GOOGLE_APPLICATION_CREDENTIALS env var to a service account of that project, it seems to work, but I'd like to avoid it as it is required to re-export that variable each time I'm changing environment.

I've authenticated to gcloud via my user, which is admin for all the relevant project.


问:
Puppeteer error: Navigation failed because browser has disconnected
I am using puppeteer on Google App Engine with Node.JS

whenever I run puppeteer on app engine, I encounter an error saying

Navigation failed because browser has disconnected!

This works fine in local environment, so I am guessing it is a problem with app engine.

```<code>const browser = await puppeteer.launch({
    ignoreHTTPSErrors: true,
    headless: true,
    args: ["--disable-setuid-sandbox", "--no-sandbox"],
});
</code>```

This is my app engine's app.yaml file

```<code>runtime: nodejs12

env: standard

handlers:
  - url: /.*
    secure: always
    script: auto
</code>```

-- EDIT--

It works when I add --disable-dev-shm-usage argument, but then it always timeouts. Here are my codes.

```<code>const browser = await puppeteer.launch({
  ignoreHTTPSErrors: true,
  headless: true,
  args: [
    "--disable-gpu",
    "--disable-dev-shm-usage",
    "--no-sandbox",
    "--disable-setuid-sandbox",
    "--no-first-run",
    "--no-zygote",
    "--single-process",
  ],
});
const page = await browser.newPage();

try {
  const url = "https://seekingalpha.com/market-news/1";
  const pageOption = {
    waitUntil: "networkidle2",
    timeout: 20000,
  };

  await page.goto(url, pageOption);
} catch (e) {
  console.log(e);
  await page.close();
  await browser.close();
  return resolve("error at 1");
}

try {
  const ulSelector = "#latest-news-list";
  await page.waitForSelector(ulSelector, { timeout: 30000 });
} catch (e) {
  // ALWAYS TIMEOUTS HERE!
  console.log(e);
  await page.close();
  await browser.close();
  return resolve("error at 2");
}
...
</code>```

答:
For me the error was solved when I stopped using the --use-gl=swiftshader arg.

It is used by default if you use args: chromium.args from chrome-aws-lambda

Body:
I am using puppeteer on Google App Engine with Node.JS

whenever I run puppeteer on app engine, I encounter an error saying

Navigation failed because browser has disconnected!

This works fine in local environment, so I am guessing it is a problem with app engine.

const browser = await puppeteer.launch({
    ignoreHTTPSErrors: true,
    headless: true,
    args: ["--disable-setuid-sandbox", "--no-sandbox"],
});

This is my app engine's app.yaml file

runtime: nodejs12

env: standard

handlers:
  - url: /.*
    secure: always
    script: auto

-- EDIT--

It works when I add --disable-dev-shm-usage argument, but then it always timeouts. Here are my codes.

const browser = await puppeteer.launch({
  ignoreHTTPSErrors: true,
  headless: true,
  args: [
    "--disable-gpu",
    "--disable-dev-shm-usage",
    "--no-sandbox",
    "--disable-setuid-sandbox",
    "--no-first-run",
    "--no-zygote",
    "--single-process",
  ],
});
const page = await browser.newPage();

try {
  const url = "https://seekingalpha.com/market-news/1";
  const pageOption = {
    waitUntil: "networkidle2",
    timeout: 20000,
  };

  await page.goto(url, pageOption);
} catch (e) {
  console.log(e);
  await page.close();
  await browser.close();
  return resolve("error at 1");
}

try {
  const ulSelector = "#latest-news-list";
  await page.waitForSelector(ulSelector, { timeout: 30000 });
} catch (e) {
  // ALWAYS TIMEOUTS HERE!
  console.log(e);
  await page.close();
  await browser.close();
  return resolve("error at 2");
}
...


问:
Visual Studio Code Using wrong Python Version--correct version does not show up
I'm running VSCode on a Linux machine. In the terminal, my Python version is 3.10.1, with the path /usr/bin/python.

However, in VSCode, it only shows Python 3.9.9, but with the same path.

Indeed, VSCode's built-in terminal also uses Python 3.9.9.

I have not yet found a way to fix this, such that Python 3.10.1 is available for use in VSCode.

答:
I've been having the exact same problem. Fortunately, as I am currently using Fedora, the easy solution (the only one I've found) was to install the rpm package, as it is officially provided.

That's too bad! Specially because I try to use flatpaks whenever possible.

The only relevant source of information I've found was this discussion in Zorin's forum.

So If anyone in the future comes across this problem and reads this SO question, my advice up to now is (unfortunately) to just try another package format.


问:
Why does my Fewest Clicks modal open when I click the button but none of my other ones open?
I use modals with buttons. I don't know why only one works when I click the button. The code is the same for all of them I think. Can someone help?

All the code is below  I have no idea how to fix this. I just started using JavaScript so there is probably something that I missed or didn't add. Also any tips that I could do better next time?

```<code><html>
<title> Singleplayer | WikiRun </title>
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<img src="/logo.png" alt="The WikiRuns Logo"style="margin-left:542;">

<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg=="
     crossorigin="anonymous" referrerpolicy="no-referrer" />

</head>
<style>
    /* Style buttons */
    .btn {
        background-color: DodgerBlue;
        /* Blue background */
        border: none;
        /* Remove borders */
        color: white;
        /* White text */
        padding: 11px 12px;
        /* Some padding */
        font-size: 16px;
        /* Set a font size */
        cursor: pointer;
        /* Mouse pointer on hover */
        border-radius: 16px;
        width: 32em;
        height: 3.5em;
        margin: 12;
        margin-left: 400;
        margin-top: 50;
        text-anchor: middle;

    }

    /* Darker background on mouse-over */
    .btn:hover {
        background-color: RoyalBlue;
    }

    /*so that the link does not have a different color*/
    a:link:active,
    a:visited:active {
        color: black;
    }

    a:link,
    a:visited {
        color: black;
        text-decoration: 0;
        cursor: pointer;
    }

    /*paragraph*/
    p {
        color: black;
        text-align-last: top;
        margin-left: 370;
        margin-top: 50;
        margin: 12;
    }
</style>
<link rel="stylesheet" href="/css/singleply.css">
<a href="/index.html"><button class="btn"><i class="fa fa-house"></i></button> </a>
<button id="golfButton" class="btn"><i class="fa fa-solid fa-golf-ball-tee"></i>  Wiki Golf</button>
<button id="clicksButton" class="btn"><i class="fa fa-solid fa-arrow-pointer"></i> Fewest Clicks</button>

<button id="timed" class="btn"><i class="fa-solid fa-hourglass"></i> Timed</button>

<!-- MODALS -->

<!--Wiki Golf-->
<script>
  // Get the modal
var modalGolf = document.getElementById("golfModal");

// Get the button that opens the modal
var btnGolf = document.getElementById("golfButton");

// Get the <span> element that closes the modal
var spanGolf = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btnGolf.onclick = function() {
  modalGolf.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
spanGolf.onclick = function() {
  modalGolf.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modalGolf) {
    modalGolf.style.display = "none";
  }
}
</script>
<!-- The Modal -->
<div id="golfModal" class="modalGolf">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    </div>
    <!-- Modal content -->
<div class="modal-content">
  <div class="modal-header">
    <span class="close">×</span>
    <h2>Wiki Golf</h2>
  </div>
  <div class="modal-body">
    <p>Wiki Golf is a good Choice!</p>
    <p>The goal of Wiki Golf is to get to the page "Jesus" in under 5 moves. For more information, click <a href="/howto/howto.html"> here. </a>
      <br>

    </p>
  </div>
  <div class="modal-footer">
    <h3> <a href="/game/wikigolf.html">Start </a></h3>
  </div>
</div>
  </div>

</div>

<!-- END OF WIKI GOLF MODAL -->

<!-- TIMED MODAL -->

<div id="timed" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    </div>
    <!-- Modal content -->
<div class="modal-content">
  <div class="modal-header">
    <span class="close">×</span>
    <h2>Timed Mode</h2>
  </div>
  <div class="modal-body">
    <p>Same Rules as other versions of Wiki Run</p>
    <p>When you are ready, click start below. Before you start your game, start the stop watch that is below the wiki article. Before you start, choose a end page. A random one will automatically load when you click start. It will be small and on the bottom right of your screen. Before starting the timer, scroll around the page and look for the title. If you want to try to reach one you chose yourself, completly disregard the random one. Then, click start below and start your timer!
      <br>

    </p>
  </div>
  <div class="modal-footer">
    <h3> <a href="/game/timed.html">Start </a></h3>
  </div>
</div>
  </div>

</div>

<script>
  // Get the modal
var modalTimed = document.getElementById("timed");

// Get the button that opens the modal
var btnTimed = document.getElementById("timed");

// Get the <span> element that closes the modal
var spanTimed = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btnTimed.onclick = function() {
  modalTimed.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
spanTimed.onclick = function() {
  modalTimed.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modalClicks) {
    modalTimed.style.display = "none";
  }
}
</script>

<!-- END OF TIMED MODAL -->

<!-- FEWEST CLICKS MODAL-->

<!-- The Modal -->
<div id="clicksModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    </div>
    <!-- Modal content -->
<div class="modal-content">
  <div class="modal-header">
    <span class="close">×</span>
    <h2>Fewest Clicks</h2>
  </div>
  <div class="modal-body">
    <p>Same Rules as other versions of Wiki Run</p>
    <p>This Mode is just timed but instead of timed, it scores based on your click count. If you need help or want to learn how to play click <a href="/howto/howto.html"> here </a>
      <br>

    </p>
  </div>
  <div class="modal-footer">
    <h3> <a href="/game/fewestclicks.html">Start </a></h3>
  </div>
</div>
  </div>

</div>

<script>
  // Get the modal
var modalClicks = document.getElementById("clicksModal");

// Get the button that opens the modal
var btnClicks = document.getElementById("clicksButton");

// Get the <span> element that closes the modal
var spanClicks = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btnClicks.onclick = function() {
  modalClicks.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
spanClicks.onclick = function() {
  modalClicks.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modalClicks) {
    modalClicks.style.display = "none";
  }
}
</script>

<!-- END OF FEWEST CLICKS MODAL -->

<!-- STYLE FOR ALL MODALS -->

<style>
/* The Modal (background) */
.modalGolf {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color:rgb(255,0,0) ;/* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 15% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
/* Modal Header */
.modal-header {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}

/* Modal Body */
.modal-body {padding: 2px 16px;}

/* Modal Footer */
.modal-footer {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}

/* Modal Content */
.modal-content {
  position: relative;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  border: 1px solid #888;
  width: 80%;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
  animation-name: animatetop;
  animation-duration: 0.7s
}
/* Add Animation */
@keyframes animatetop {
  from {top: -300px; opacity: 0}
  to {top: 0px; opacity: 1}
}

</style>
<style>
/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color:rgb(255,0,0) ;/* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 15% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
/* Modal Header */
.modal-header {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}

/* Modal Body */
.modal-body {padding: 2px 16px;}

/* Modal Footer */
.modal-footer {
  padding: 2px 16px;
  background-color: #5cb85c;
  color: white;
}

/* Modal Content */
.modal-content {
  position: relative;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  border: 1px solid #888;
  width: 80%;
  box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
  animation-name: animatetop;
  animation-duration: 0.7s
}
/* Add Animation */
@keyframes animatetop {
  from {top: -300px; opacity: 0}
  to {top: 0px; opacity: 1}
}

</style>
<!-- END OF STYLE FOR ALL MODALS -->
</code>```

答:
<button id="timed" and <div id="timed" have same ID. ID should be unique for all HTML elements. JavaScript finds by ID only first occurrence of an element. var modalTimed and btnTimed are assigned to the same element because their IDs are identic. Change these.

var modalGolf defined before the HTML element that matches it. When you want to get an HTML element with JS, you should write that JS after an appropriate HTML is rendered. It's because code is executed line by line from top to bottom. JS at the top can't access HTML at the bottom. Other code that references to var modalGolf will not work. var spanGolf will not work, a reason is same.

Write all of your JS at the bottom of body tag. This will make your code cleaner and more understandable. Remember, JS blocks the code that after it from rendering/execution until it's done. So write your JS at the top of the page if you really need it

Correct HTML document structure:

```<code><html>
   <head>
       here you put link tags, style
       tags, script tags, title tag
   </head>
   <body>
       here is a visible part of your
       page. May include scripts at the
       bottom of this tag
   </body>
</html>
</code>```

Body:
I use modals with buttons. I don't know why only one works when I click the button. The code is the same for all of them I think. Can someone help?

All the code is below  I have no idea how to fix this. I just started using JavaScript so there is probably something that I missed or didn't add. Also any tips that I could do better next time?

<title> Singleplayer | WikiRun </title>
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg=="
     crossorigin="anonymous" referrerpolicy="no-referrer" />

<link rel="stylesheet" href="/css/singleply.css">
<button class="btn"></button>
<button id="golfButton" class="btn">  Wiki Golf</button>
<button id="clicksButton" class="btn"> Fewest Clicks</button>

<button id="timed" class="btn"> Timed</button>

    ×

    ×

Wiki Golf

Wiki Golf is a good Choice!

The goal of Wiki Golf is to get to the page "Jesus" in under 5 moves. For more information, click  here.

 Start

    ×

    ×

Timed Mode

Same Rules as other versions of Wiki Run

When you are ready, click start below. Before you start your game, start the stop watch that is below the wiki article. Before you start, choose a end page. A random one will automatically load when you click start. It will be small and on the bottom right of your screen. Before starting the timer, scroll around the page and look for the title. If you want to try to reach one you chose yourself, completly disregard the random one. Then, click start below and start your timer!

 Start

    ×

    ×

Fewest Clicks

Same Rules as other versions of Wiki Run

This Mode is just timed but instead of timed, it scores based on your click count. If you need help or want to learn how to play click  here

 Start

Body:
<button id="timed" and <div id="timed" have same ID. ID should be unique for all HTML elements. JavaScript finds by ID only first occurrence of an element. var modalTimed and btnTimed are assigned to the same element because their IDs are identic. Change these.

var modalGolf defined before the HTML element that matches it. When you want to get an HTML element with JS, you should write that JS after an appropriate HTML is rendered. It's because code is executed line by line from top to bottom. JS at the top can't access HTML at the bottom. Other code that references to var modalGolf will not work. var spanGolf will not work, a reason is same.

Write all of your JS at the bottom of body tag. This will make your code cleaner and more understandable. Remember, JS blocks the code that after it from rendering/execution until it's done. So write your JS at the top of the page if you really need it

Correct HTML document structure:

<html>
   <head>
       here you put link tags, style
       tags, script tags, title tag
   </head>
   <body>
       here is a visible part of your
       page. May include scripts at the
       bottom of this tag
   </body>
</html>


问:
How to configure freeradius to allow whitespaces in username
We got some usernames with whitespaces at the end and they are getting rejected by freeradius. Does anyone know how to configure it so that these username don't get rejected?

Thanks

答:
The default virtual server in raddb/sites-enabled/default contains a call to the filter_username policy (see the top of the authorize section).

This policy is defined in raddb/policy.d/filter, and makes several checks to ensure the username is sane. The first of which ensures no spaces.

You can:

Remove the call to filter_username entirely from the virtual server; or

Alter the policy so that it doesn't check for spaces; or

Fix the devices so that the username is correct.

The last option is the correct one. You will likely find that if you permit usernames with spaces then they will fail to authenticate anyway (they are not valid usernames) - so it will be the same outcome, yet wasting more server resources in the process. The filter tests are there for a reason.


问:
Can't get image resizing to work with jQuery File Upload
I am trying to utilize the client-side image resizing available in the jQuery File Upload plugin, developed by blueimp: https://github.com/blueimp/jQuery-File-Upload

Unfortunately, I cannot get the image resizing to work. The upload itself works perfectly.

```<code>this.$('.fileupload').fileupload({
    url: websiteUrl + 'deed/uploadimage',
    dataType: 'json',
    previewMaxWidth: 90,
    previewMaxHeight: 90,
    previewCrop: true,
    imageOrientation: true,
    disableImageResize: false,
    add: function($, data) {
        _.each(data.files, function(file){
            file.model = self.addImagePreview();
        });
        _.defer(_.bind(data.submit, data));
    },
    done: function($, data) {
        // Quirky shit. Iterate over data.files array while we know that
        // only one file are uploaded at a time...
        _.each(data.files, function(file){
            file.model.set({
                "uploading": false,
                "src": data.response().result.image,
                "preview": data.response().result.cropped
            });
        });
    }
});
</code>```

I have tried putting a breakpoint in the resizeImage method to see if it for some reason broke on one of the conditions, but the method is never invoked.

All dependencies are loaded in this order:

```<code>load-image.min.js
canvas-to-blob.js
jquery.ui.widget.js
jquery.fileupload.js
jquery.fileupload-process.js
jquery.fileupload-image.js
jquery.iframe-transport.js
</code>```

Am I missing something here?

答:
html

```<code><input type="file" name="image" id="upload-image">
    <br>
<img src="" id="Logo">
</code>```

js | jquery

```<code><script type="text/javascript">
$(document).ready(function() {

    $('#upload-image').on('change', function (e) {
        e.preventDefault();

        var imageFile = e.target.files[0];
        var reader    = new FileReader();
        reader.onload = imageIsLoaded;
        reader.readAsDataURL(this.files[0]);

        function imageIsLoaded(e) {

            var image = new Image();

            image.src = e.target.result;

            image.onload = function() {

                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                    ctx.drawImage(image,0, 0, 300, 300);// new width and height | resize

                var newImage= canvas.toDataURL("image/jpeg");

                $('#Logo').attr('src', newImage);

            }; //end of function onload image

        }; //end of function imageIsLoaded

    });//end of change image

});//end of redy fun
</script>
</code>```

Body:
I am trying to utilize the client-side image resizing available in the jQuery File Upload plugin, developed by blueimp: https://github.com/blueimp/jQuery-File-Upload

Unfortunately, I cannot get the image resizing to work. The upload itself works perfectly.

this.$('.fileupload').fileupload({
    url: websiteUrl + 'deed/uploadimage',
    dataType: 'json',
    previewMaxWidth: 90,
    previewMaxHeight: 90,
    previewCrop: true,
    imageOrientation: true,
    disableImageResize: false,
    add: function($, data) {
        _.each(data.files, function(file){
            file.model = self.addImagePreview();
        });
        _.defer(_.bind(data.submit, data));
    },
    done: function($, data) {
        // Quirky shit. Iterate over data.files array while we know that
        // only one file are uploaded at a time...
        _.each(data.files, function(file){
            file.model.set({
                "uploading": false,
                "src": data.response().result.image,
                "preview": data.response().result.cropped
            });
        });
    }
});

I have tried putting a breakpoint in the resizeImage method to see if it for some reason broke on one of the conditions, but the method is never invoked.

All dependencies are loaded in this order:

load-image.min.js
canvas-to-blob.js
jquery.ui.widget.js
jquery.fileupload.js
jquery.fileupload-process.js
jquery.fileupload-image.js
jquery.iframe-transport.js

Am I missing something here?

Body:
html

<input type="file" name="image" id="upload-image">
    <br>
<img src="" id="Logo">

js | jquery

<script type="text/javascript">
$(document).ready(function() {

    $('#upload-image').on('change', function (e) {
        e.preventDefault();

        var imageFile = e.target.files[0];
        var reader    = new FileReader();
        reader.onload = imageIsLoaded;
        reader.readAsDataURL(this.files[0]);

        function imageIsLoaded(e) {

            var image = new Image();

            image.src = e.target.result;

            image.onload = function() {

                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                    ctx.drawImage(image,0, 0, 300, 300);// new width and height | resize

                var newImage= canvas.toDataURL("image/jpeg");

                $('#Logo').attr('src', newImage);

            }; //end of function onload image

        }; //end of function imageIsLoaded

    });//end of change image

});//end of redy fun
</script>


问:
How to make a dynamic key optional with typescript
I would like to make the dynamic key item optional. Adding ? creates an error.

type Example = {
  name?: string;
  [item: string]?: unknown; // error: TS1131: Property or signature expected.
};
```

答:
You can use the type utilities Partial and Record to create the type you want:

TS Playground

type Example = Partial<Record<string, unknown>> & { name?: string };

declare const example: Example;
example.name; // string | undefined
example.anyOtherProperty; // unknown

```


问:
R with dplyr rename, avoid error if column doesn't exist AND create new column with NAs
We are looking to rename columns in a dataframe in R, however the columns may be missing and this throws an error:

```<code>my_df <- data.frame(a = c(1,2,3), b = c(4,5,6))
my_df %>% dplyr::rename(aa = a, bb = b, cc = c)

Error: Can't rename columns that don't exist.
x Column `c` doesn't exist.
</code>```

our desired output is this, which creates a new column with NA values if the original column does not exist:

```<code>> my_df
  aa bb  c
1  1  4 NA
2  2  5 NA
3  3  6 NA
</code>```

答:
Here is a solution using the data.table function setnames. I've added a second "missing" column "d" to demonstrate generality.</p>
```<code>library(tidyverse)
library(data.table)
my_df <- data.frame(a = c(1,2,3), b = c(4,5,6))
curr <-  names(my_df)
cols <- data.frame(new=c("aa","bb","cc","dd"), old = c("a", "b", "c","d"))     %>%
mutate(exist = old %in% curr)
foo <- filter(cols, exist)
bar <- filter(cols, !exist)
setnames(my_df, new = foo$new)
my_df[, bar$old] <- NA
my_df

#> my_df
#  aa bb  c  d
#1  1  4 NA NA
#2  2  5 NA NA
#3  3  6 NA NA
</code>```

Body:
We are looking to rename columns in a dataframe in R, however the columns may be missing and this throws an error:

my_df <- data.frame(a = c(1,2,3), b = c(4,5,6))
my_df %>% dplyr::rename(aa = a, bb = b, cc = c)

Error: Can't rename columns that don't exist.
x Column `c` doesn't exist.

our desired output is this, which creates a new column with NA values if the original column does not exist:

> my_df
  aa bb  c
1  1  4 NA
2  2  5 NA
3  3  6 NA

Body:
Here is a solution using the data.table function setnames. I've added a second "missing" column "d" to demonstrate generality.

library(tidyverse)
library(data.table)
my_df <- data.frame(a = c(1,2,3), b = c(4,5,6))
curr <-  names(my_df)
cols <- data.frame(new=c("aa","bb","cc","dd"), old = c("a", "b", "c","d"))     %>%
mutate(exist = old %in% curr)
foo <- filter(cols, exist)
bar <- filter(cols, !exist)
setnames(my_df, new = foo$new)
my_df[, bar$old] <- NA
my_df

#> my_df
#  aa bb  c  d
#1  1  4 NA NA
#2  2  5 NA NA
#3  3  6 NA NA