问:
Threading in Python results in Globals setting to None
In a python 2.7 script of mine, I have discovered this issue where threads at random instances will see the global variables all as None type and throw an error.

In trying to narrow down the issue, I limited my number of threads to 1 (plus main thread for managing threads and what data to process).  Then in running my script which does not change global variables at all, they are static, I find at random instances during the execution it throwing then the following error:

```<code>'NoneType' object has no attribute '__getitem__'
</code>```

Then that error was what brought me to the view of all of my globals.  And agian to reiterate, in no where in the code am I setting these variables.  For example, jiraIDs is an import that is an array that is utilized, not ever set.

Let me know if any other information would be needed.

Main script:

```<code>from Jira import Jira, jiraIDs, getSearchQueryTemplate
import re, sys, time
import threading

restAPI = "JIRA URL"
validationTicket = "XYZ-01234"

def interactive():
    while(1):
        while(1):
            ticket = raw_input("Enter JIRA ID of ticket to flow EPIC Link down (eg. XYZ-XXXXX): ").strip().upper()
            if re.search('XYZ-[0-9]{5}', ticket):
                break
            print("Following is not a correct ID: {}".format(ticket))
        jira = Jira(restAPI, validationTicket)
        jira.randRequestDeley = 0
        epicFlowdownHelper(jira, ticket)
        raw_input("Finished.  Press ENTER to go again (Epic'ly)...")

def unattendedEpicflowdown():
    # For flowing down epics for the new standard of XY.BZ standard
    # filtering through epic links
    jira = Jira(restAPI,validationTicket)
    query = getSearchQueryTemplate()
    query["jql"] = 'project = "jql filter" and type = Epic and status != CLOSED'
    resp = jira.request_POST_search(query)
    epicLinks = []
    for issue in resp["issues"]:
        if  not re.search("[0-9]{1,2}\.B[1-8]|v6\.6\.1", issue["fields"]["summary"]):
            continue
        epicLinks.append(issue["key"])

    # get all WP's that are associated to epics in epicLinks and start the flowdown
    query["jql"] = 'project = "jql filter" and status != CLOSED and type = "Work Package" and "Epic Link" in (' + ','.join(epicLinks) + ')'
    resp = jira.request_POST_search(query)
    threads = []
    for issue in resp["issues"]:
        # epicFlowdownHelper(jira, issue['key'])
        while(len(threads) > 0):
            time.sleep(.2)
            for thread in threads:
                if( not thread.isAlive()):
                    threads.remove(thread)
        t = threading.Thread(target=epicFlowdownHelper, args=(jira, issue['key'], jiraIDs))
        threads.append(t)
        t.start()

def epicFlowdownHelper(jiraInstance, WorkPackage, jiraIDs):
    def updateEpicLink(jiraInstance, ticket, epicLink, resp):
        ttype = jiraIDs["type"](jiraInstance, resp).upper()
        if (ttype == "WORK ELEMENT" or ttype == "STORY") and \
                jiraIDs["status"](jiraInstance, resp).upper() != "CLOSED" and \
                jiraIDs["Epic Link"](jiraInstance, resp) != epicLink:
            print("Updating Epic for ticket: {}".format(ticket))
            data = {}
            jiraIDs["Epic Link"](jiraInstance, data, epicLink)
            jiraInstance.request_PUT(ticket, data)

    resp = jiraInstance.request_GET(WorkPackage)
    if jiraIDs["type"](jiraInstance, resp) != "Work Package":
        print("Following ticket is not a Work Package: {}".format(WorkPackage))
        return
    if jiraIDs["status"](jiraInstance,resp).upper() == "CLOSED":
        print("Following Work Package is Closed: {}".format(WorkPackage))
        return
    epicLink = jiraIDs["Epic Link"](jiraInstance, resp)
    print("Flowing down ticket Epic'ly: {}".format(WorkPackage))
    blockedByIDs = jiraIDs["is blocked by"](jiraInstance, resp)
    if not blockedByIDs:
        return
    blockedByIDs = blockedByIDs.split(',')
    for ticket in blockedByIDs:
        resp = jiraInstance.request_GET(ticket)
        if jiraIDs["type"](jiraInstance, resp).upper() not in ("WORK ELEMENT", "STORY"):
            continue
        updateEpicLink(jiraInstance, ticket, epicLink, resp)
        blockedByIDs = jiraIDs["is blocked by"](jiraInstance, resp)
        if not blockedByIDs or len(blockedByIDs) == 0:
            continue
        blockedByIDs = blockedByIDs.split(',')
        for ticket in blockedByIDs:
            resp = jiraInstance.request_GET(ticket)
            updateEpicLink(jiraInstance, ticket, epicLink, resp)

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1].upper() == "INTERACTIVE":
        interactive()
    else:
        unattendedEpicflowdown()
</code>```

Jira Script:

```<code>from urllib2 import Request, urlopen, HTTPError
from urllib import urlencode
from base64 import b64encode, b64decode
import getpass, json, os.path, copy, random, time

class Jira():

    randRequestDeley = 0

    def __init__(self, RESTuri, validationTicketID, auth=None):
        self.RESTuri = RESTuri
        self.validationTicketID = validationTicketID
        self.scriptPath = os.path.realpath(os.path.dirname(__file__))
        self.authenticationB64(auth)

    def authenticationB64(self, auth=None):
        if auth == None:
            uname = raw_input("User Name:").strip()
            passwd = getpass.getpass("Password:").strip()
        else:
            uname = auth["username"]
            passwd = auth["password"]
        self.b64Auth = b64encode(uname + ":" + passwd)
        self.request_GET(self.validationTicketID)

    def jiraIDsFuncHelper(self, data, location, value=None):
        tracker = data
        for i, key in enumerate(location):
            if i == len(location) - 1:
                if not value:
                    return tracker.get(key)
                tracker.update({key : value})
            else:
                temp = tracker.get(key)
                if not temp:
                    tracker.update({key : {}})
                    tracker = tracker.get(key)
                else:
                    tracker = temp
        return data

    def request_GET(self, ticket, forceCustomURL=None):
        headers = {
            "Authorization" : "Basic " + self.b64Auth,
            "Content-Type"  : "application/json"
        }
        if forceCustomURL:
            req = Request(forceCustomURL, headers=headers)
        else:
            time.sleep(float(random.randint(0,self.randRequestDeley))/10)
            req = Request(self.RESTuri + "issue/" + ticket, headers=headers)
        resp = urlopen(req)
        if resp.headers.dict["x-seraph-loginreason"].upper() != "OUT, OK":
            raise ValueError("Invalid Credentials")
        return json.loads(resp.read())

    def request_POST_search(self, query):
        headers = {
            "Authorization" : "Basic " + self.b64Auth,
            "Content-Type"  : "application/json"
        }
        time.sleep(float(random.randint(0,self.randRequestDeley))/10)
        req = Request(self.RESTuri + "search", data=json.dumps(query), headers=headers)
        resp = urlopen(req)
        respStr = resp.read()
        if respStr == '':
            return None
        return json.loads(respStr)

    def request_PUT(self, ticket, data):
        headers = {
            "Authorization" : "Basic " + self.b64Auth,
            "Content-Type"  : "application/json"
        }
        time.sleep(float(random.randint(0,self.randRequestDeley))/10)
        req = Request(self.RESTuri + "issue/" + ticket, data=json.dumps(data), headers=headers)
        req.get_method = lambda: "PUT"
        resp = urlopen(req)
        respStr = resp.read()
        if respStr == '':
            return None
        return json.loads(respStr)

jiraIDs = {
        "Epic Link"   : lambda jiraInstance,data,value=None: jiraInstance.jiraIDsFuncHelper(data,["fields","customfield_11913"],value=value),
        "is blocked by" : lambda jiraInstance,data,value=None: jiraInstance.jiraIDsFuncHelper(data,["fields","customfield_15802"],value=value),
        "type"        : lambda jiraInstance,data,value=None: jiraInstance.jiraIDsFuncHelper(data,["fields","issuetype","name"],value=value),
        "status"        : lambda jiraInstance,data,value=None: jiraInstance.jiraIDsFuncHelper(data,["fields","status","name"],value=value),
        "labels"        : lambda jiraInstance,data,value=None: jiraInstance.jiraIDsFuncHelper(data,["fields","labels"],value=value),
    }

getSearchQueryTemplate = lambda: copy.deepcopy({
                                                    "jql" : None,
                                                    "fields" : ["id", "key", "summary"],
                                                    "maxResults" : 1000000,
                                                })
</code>```

Body:
In a python 2.7 script of mine, I have discovered this issue where threads at random instances will see the global variables all as None type and throw an error.

In trying to narrow down the issue, I limited my number of threads to 1 (plus main thread for managing threads and what data to process).  Then in running my script which does not change global variables at all, they are static, I find at random instances during the execution it throwing then the following error:

'NoneType' object has no attribute '__getitem__'

Then that error was what brought me to the view of all of my globals.  And agian to reiterate, in no where in the code am I setting these variables.  For example, jiraIDs is an import that is an array that is utilized, not ever set.

Let me know if any other information would be needed.

Main script:

from Jira import Jira, jiraIDs, getSearchQueryTemplate
import re, sys, time
import threading

restAPI = "JIRA URL"
validationTicket = "XYZ-01234"

def interactive():
    while(1):
        while(1):
            ticket = raw_input("Enter JIRA ID of ticket to flow EPIC Link down (eg. XYZ-XXXXX): ").strip().upper()
            if re.search('XYZ-[0-9]{5}', ticket):
                break
            print("Following is not a correct ID: {}".format(ticket))
        jira = Jira(restAPI, validationTicket)
        jira.randRequestDeley = 0
        epicFlowdownHelper(jira, ticket)
        raw_input("Finished.  Press ENTER to go again (Epic'ly)...")

def unattendedEpicflowdown():
    # For flowing down epics for the new standard of XY.BZ standard
    # filtering through epic links
    jira = Jira(restAPI,validationTicket)
    query = getSearchQueryTemplate()
    query["jql"] = 'project = "jql filter" and type = Epic and status != CLOSED'
    resp = jira.request_POST_search(query)
    epicLinks = []
    for issue in resp["issues"]:
        if  not re.search("[0-9]{1,2}\.B[1-8]|v6\.6\.1", issue["fields"]["summary"]):
            continue
        epicLinks.append(issue["key"])

    # get all WP's that are associated to epics in epicLinks and start the flowdown
    query["jql"] = 'project = "jql filter" and status != CLOSED and type = "Work Package" and "Epic Link" in (' + ','.join(epicLinks) + ')'
    resp = jira.request_POST_search(query)
    threads = []
    for issue in resp["issues"]:
        # epicFlowdownHelper(jira, issue['key'])
        while(len(threads) > 0):
            time.sleep(.2)
            for thread in threads:
                if( not thread.isAlive()):
                    threads.remove(thread)
        t = threading.Thread(target=epicFlowdownHelper, args=(jira, issue['key'], jiraIDs))
        threads.append(t)
        t.start()

def epicFlowdownHelper(jiraInstance, WorkPackage, jiraIDs):
    def updateEpicLink(jiraInstance, ticket, epicLink, resp):
        ttype = jiraIDs["type"](jiraInstance, resp).upper()
        if (ttype == "WORK ELEMENT" or ttype == "STORY") and \
                jiraIDs["status"](jiraInstance, resp).upper() != "CLOSED" and \
                jiraIDs["Epic Link"](jiraInstance, resp) != epicLink:
            print("Updating Epic for ticket: {}".format(ticket))
            data = {}
            jiraIDs["Epic Link"](jiraInstance, data, epicLink)
            jiraInstance.request_PUT(ticket, data)

    resp = jiraInstance.request_GET(WorkPackage)
    if jiraIDs["type"](jiraInstance, resp) != "Work Package":
        print("Following ticket is not a Work Package: {}".format(WorkPackage))
        return
    if jiraIDs["status"](jiraInstance,resp).upper() == "CLOSED":
        print("Following Work Package is Closed: {}".format(WorkPackage))
        return
    epicLink = jiraIDs["Epic Link"](jiraInstance, resp)
    print("Flowing down ticket Epic'ly: {}".format(WorkPackage))
    blockedByIDs = jiraIDs["is blocked by"](jiraInstance, resp)
    if not blockedByIDs:
        return
    blockedByIDs = blockedByIDs.split(',')
    for ticket in blockedByIDs:
        resp = jiraInstance.request_GET(ticket)
        if jiraIDs["type"](jiraInstance, resp).upper() not in ("WORK ELEMENT", "STORY"):
            continue
        updateEpicLink(jiraInstance, ticket, epicLink, resp)
        blockedByIDs = jiraIDs["is blocked by"](jiraInstance, resp)
        if not blockedByIDs or len(blockedByIDs) == 0:
            continue
        blockedByIDs = blockedByIDs.split(',')
        for ticket in blockedByIDs:
            resp = jiraInstance.request_GET(ticket)
            updateEpicLink(jiraInstance, ticket, epicLink, resp)

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1].upper() == "INTERACTIVE":
        interactive()
    else:
        unattendedEpicflowdown()

Jira Script:

from urllib2 import Request, urlopen, HTTPError
from urllib import urlencode
from base64 import b64encode, b64decode
import getpass, json, os.path, copy, random, time

class Jira():

    randRequestDeley = 0

    def __init__(self, RESTuri, validationTicketID, auth=None):
        self.RESTuri = RESTuri
        self.validationTicketID = validationTicketID
        self.scriptPath = os.path.realpath(os.path.dirname(__file__))
        self.authenticationB64(auth)

    def authenticationB64(self, auth=None):
        if auth == None:
            uname = raw_input("User Name:").strip()
            passwd = getpass.getpass("Password:").strip()
        else:
            uname = auth["username"]
            passwd = auth["password"]
        self.b64Auth = b64encode(uname + ":" + passwd)
        self.request_GET(self.validationTicketID)

    def jiraIDsFuncHelper(self, data, location, value=None):
        tracker = data
        for i, key in enumerate(location):
            if i == len(location) - 1:
                if not value:
                    return tracker.get(key)
                tracker.update({key : value})
            else:
                temp = tracker.get(key)
                if not temp:
                    tracker.update({key : {}})
                    tracker = tracker.get(key)
                else:
                    tracker = temp
        return data

    def request_GET(self, ticket, forceCustomURL=None):
        headers = {
            "Authorization" : "Basic " + self.b64Auth,
            "Content-Type"  : "application/json"
        }
        if forceCustomURL:
            req = Request(forceCustomURL, headers=headers)
        else:
            time.sleep(float(random.randint(0,self.randRequestDeley))/10)
            req = Request(self.RESTuri + "issue/" + ticket, headers=headers)
        resp = urlopen(req)
        if resp.headers.dict["x-seraph-loginreason"].upper() != "OUT, OK":
            raise ValueError("Invalid Credentials")
        return json.loads(resp.read())

    def request_POST_search(self, query):
        headers = {
            "Authorization" : "Basic " + self.b64Auth,
            "Content-Type"  : "application/json"
        }
        time.sleep(float(random.randint(0,self.randRequestDeley))/10)
        req = Request(self.RESTuri + "search", data=json.dumps(query), headers=headers)
        resp = urlopen(req)
        respStr = resp.read()
        if respStr == '':
            return None
        return json.loads(respStr)

    def request_PUT(self, ticket, data):
        headers = {
            "Authorization" : "Basic " + self.b64Auth,
            "Content-Type"  : "application/json"
        }
        time.sleep(float(random.randint(0,self.randRequestDeley))/10)
        req = Request(self.RESTuri + "issue/" + ticket, data=json.dumps(data), headers=headers)
        req.get_method = lambda: "PUT"
        resp = urlopen(req)
        respStr = resp.read()
        if respStr == '':
            return None
        return json.loads(respStr)

jiraIDs = {
        "Epic Link"   : lambda jiraInstance,data,value=None: jiraInstance.jiraIDsFuncHelper(data,["fields","customfield_11913"],value=value),
        "is blocked by" : lambda jiraInstance,data,value=None: jiraInstance.jiraIDsFuncHelper(data,["fields","customfield_15802"],value=value),
        "type"        : lambda jiraInstance,data,value=None: jiraInstance.jiraIDsFuncHelper(data,["fields","issuetype","name"],value=value),
        "status"        : lambda jiraInstance,data,value=None: jiraInstance.jiraIDsFuncHelper(data,["fields","status","name"],value=value),
        "labels"        : lambda jiraInstance,data,value=None: jiraInstance.jiraIDsFuncHelper(data,["fields","labels"],value=value),
    }

getSearchQueryTemplate = lambda: copy.deepcopy({
                                                    "jql" : None,
                                                    "fields" : ["id", "key", "summary"],
                                                    "maxResults" : 1000000,
                                                })


来源: stackexchange

问:
derive secret "tls13 c hs traffic" how to derive?
can anyone tell me how the value (32 octets) was expanded ?
i mean how the client handshake traffic secret was expanded ?

```<code>{server}  derive secret "tls13 c hs traffic":

      PRK (32 octets):  1d c8 26 e9 36 06 aa 6f dc 0a ad c1 2f 74 1b 01
         04 6a a6 b9 9f 69 1e d2 21 a9 f0 ca 04 3f be ac

Thomson                       Informational                     [Page 5]
RFC 8448                     TLS 1.3 Traces                 January 2019

      hash (32 octets):  86 0c 06 ed c0 78 58 ee 8e 78 f0 e7 42 8c 58 ed
         d6 b4 3f 2c a3 e6 e9 5f 02 ed 06 3c f0 e1 ca d8

      info (54 octets):  00 20 12 74 6c 73 31 33 20 63 20 68 73 20 74 72
         61 66 66 69 63 20 86 0c 06 ed c0 78 58 ee 8e 78 f0 e7 42 8c 58
         ed d6 b4 3f 2c a3 e6 e9 5f 02 ed 06 3c f0 e1 ca d8

      expanded (32 octets):  b3 ed db 12 6e 06 7f 35 a7 80 b3 ab f4 5e
         2d 8f 3b 1a 95 07 38 f5 2e 96 00 74 6a 0e 27 a5 5a 21
</code>```

from RFC 8448 - Example Handshake Traces for TLS 1.3

I am trying to find how the (c hs traffic) was derived or expanded?
I expect that someone explain to me how the label , salt , PRK , hashing

ContentLicense: CC BY-SA 4.0

Body:
can anyone tell me how the value (32 octets) was expanded ?
i mean how the client handshake traffic secret was expanded ?

{server}  derive secret "tls13 c hs traffic":

      PRK (32 octets):  1d c8 26 e9 36 06 aa 6f dc 0a ad c1 2f 74 1b 01
         04 6a a6 b9 9f 69 1e d2 21 a9 f0 ca 04 3f be ac

Thomson                       Informational                     [Page 5]
RFC 8448                     TLS 1.3 Traces                 January 2019

      hash (32 octets):  86 0c 06 ed c0 78 58 ee 8e 78 f0 e7 42 8c 58 ed
         d6 b4 3f 2c a3 e6 e9 5f 02 ed 06 3c f0 e1 ca d8

      info (54 octets):  00 20 12 74 6c 73 31 33 20 63 20 68 73 20 74 72
         61 66 66 69 63 20 86 0c 06 ed c0 78 58 ee 8e 78 f0 e7 42 8c 58
         ed d6 b4 3f 2c a3 e6 e9 5f 02 ed 06 3c f0 e1 ca d8

      expanded (32 octets):  b3 ed db 12 6e 06 7f 35 a7 80 b3 ab f4 5e
         2d 8f 3b 1a 95 07 38 f5 2e 96 00 74 6a 0e 27 a5 5a 21

from RFC 8448 - Example Handshake Traces for TLS 1.3

I am trying to find how the (c hs traffic) was derived or expanded?
I expect that someone explain to me how the label , salt , PRK , hashing


问:
How to show an image in the view in Laravel using DataTables
I'm using DataTables and AdminLTE in Laravel. I want to show an image in the view, what is the way to do it? Is there a way to do it inside the EmployeesDataTable and somehow add img tag and some css to the column? Code inside EmployeesDataTable:

```<code>public function getColumns(): array
    {
        return [
            Column::make('image_path')->title('Photo'),
            Column::make('name'),
            Column::make('position_id')->title('Position'),
            Column::make('recruitment_date'),
            Column::make('phone_number'),
            Column::make('email'),
            Column::make('payment'),
            Column::computed('action')
            ->exportable(false)
            ->printable(false)
            ->width(60)
            ->addClass('text-center'),
        ];
    }
</code>```

View:

```<code>
@section('title', 'Dashboard')

@section('content_header')
    <h1>Dashboard</h1>
@stop

@section('content')
<div class="container">
    <div class="card">
        <div class="card-header">Manage Employees</div>
        <div class="card-body">
            {{ $dataTable->table() }}
        </div>
    </div>
</div>
@stop

@section('css')
    <link rel="stylesheet" href="/css/admin_custom.css">
@stop

@push('scripts')
    {{ $dataTable->scripts(attributes: ['type' => 'module']) }}
@endpush

@section('js')
@stack('scripts')
@stop

</code>```

Controller:

```<code>  public function index(EmployeesDataTable $dataTable)
    {

        return $dataTable->render('admin.employees.index');
    }
</code>```

Body:
I'm using DataTables and AdminLTE in Laravel. I want to show an image in the view, what is the way to do it? Is there a way to do it inside the EmployeesDataTable and somehow add img tag and some css to the column? Code inside EmployeesDataTable:

public function getColumns(): array
    {
        return [
            Column::make('image_path')->title('Photo'),
            Column::make('name'),
            Column::make('position_id')->title('Position'),
            Column::make('recruitment_date'),
            Column::make('phone_number'),
            Column::make('email'),
            Column::make('payment'),
            Column::computed('action')
            ->exportable(false)
            ->printable(false)
            ->width(60)
            ->addClass('text-center'),
        ];
    }

View:

@section('title', 'Dashboard')

@section('content_header')

Dashboard

@stop

@section('content')

Manage Employees

            {{ $dataTable->table() }}

@stop

@section('css')
    <link rel="stylesheet" href="/css/admin_custom.css">
@stop

@push('scripts')
    {{ $dataTable->scripts(attributes: ['type' => 'module']) }}
@endpush

@section('js')
@stack('scripts')
@stop

Controller:

  public function index(EmployeesDataTable $dataTable)
    {

        return $dataTable->render('admin.employees.index');
    }


问:
upload jpg to the server of an MVC .net 6 application
Good afternoon, I currently have the problem of uploading a jpg to the server of my application, it returns it to me in this way, there are times that it is displayed well but there are others that it shows me cropped, I leave an image so that you understand what it is going

Bug

What I was trying to do is get the path of the image that saves it to a folder and extract the name of the file from that path to finally upload it to the server with httpclient, this is my code so far

```<code>public async void DownloadFile(DownloadInfo Info, string directory, string cameraName, string cameraIndex, double latitude, double longitude, string barcode, string imageUrl, string watermarkText)
        {
            CheckState();
            if (Info == null) throw new ArgumentNullException(nameof(Info));
            if (directory == null || string.IsNullOrEmpty(directory.Trim())) directory = ".";

            string dateCapture = DateTime.Now.ToString("ddMMyyyy");
            string timeCapture = DateTime.Now.ToString("hhmmss");
            string currentFileName = $"{cameraName}{cameraIndex}-{dateCapture}{timeCapture}.jpg";
            string currentFilePath = Path.Combine(directory, Info.FileName = currentFileName);
            string baseFolder = $"{directory}/{DeviceName}";
            string demoFolder = $"{directory}/{DeviceName}/Demo";
            //string definitiveFolder = $"{directory}/{DeviceName}/Definitive";

            CreateFolderIfNotExist(directory);
            CreateFolderIfNotExist(baseFolder);
            CreateFolderIfNotExist(demoFolder);
            //CreateFolderIfNotExist(definitiveFolder);

            DownloadToFile(Info, currentFilePath);

            await SendPhoto(currentFilePath, Reserved, DeviceName, Info.FileName);

            using (var bitmap = GetBitmap(currentFilePath))
            {
                Image watermarkImage = Image.FromFile(imageUrl);
                var folderSaveFilePath = Path.Combine(baseFolder, currentFileName);
                AddImageWatermark(bitmap, folderSaveFilePath, watermarkImage);
                AddMetadata(folderSaveFilePath, bitmap, latitude, longitude, barcode);
                var fileName = Path.GetFileName(folderSaveFilePath);
                await UploadFile(folderSaveFilePath, barcode, fileName);
            }

            using (var bitmap = GetBitmap(currentFilePath))
            {
                var folderSaveFilePath = Path.Combine(demoFolder, currentFileName);
                AddFontWatermark(bitmap, folderSaveFilePath, watermarkText);
                AddMetadata(folderSaveFilePath, bitmap, latitude, longitude, barcode);
            }

            File.Delete(currentFilePath);
        }

        public async Task<string> UploadFile(string filePath, string barcode, string photo)
        {
            var stringResponse = string.Empty;

            try
            {
                using (var httpClient = new HttpClient())
                {
                    using (var multipartFormContent = new MultipartFormDataContent())
                    {
                        //Add other fields
                        multipartFormContent.Add(new StringContent(barcode), name: "barcode");

                        //Add the file
                        var fileStreamContent = new StreamContent(File.OpenRead(filePath));
                        fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
                        multipartFormContent.Add(fileStreamContent, name: "photo", fileName: photo);

                        //Send it
                        var response = await httpClient.PostAsync("https://localhost:7288/api/zip", multipartFormContent);
                        response.EnsureSuccessStatusCode();

                        if (response.IsSuccessStatusCode)
                            stringResponse = await response.Content.ReadAsStringAsync();
                        else
                            stringResponse = response.StatusCode.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                var error = ex.Message;
            }

            return stringResponse;
        }

public class ZipFileHelper : IZipFileHelper
    {
        private double _currentArchiveSize = 0;
        private readonly IWebHostEnvironment _env;
        private double _maxArchiveSize = 104857600; //100mb
        private List<string> _archives = new();
        private List<string> _filesInCurrentArchive = new();
        ZipFile _zip = null;

        public ZipFileHelper(IWebHostEnvironment env)
        {
            _env = env;
        }

        public async Task UploadPhoto(IFormFile photo, string barcode)
        {
            string folder = Path.Combine(_env.ContentRootPath, $"Uploads/{barcode}");

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            string path = Path.Combine(folder, photo.FileName);

            using (FileStream fileStream = File.Create(path))
            {
                await photo.OpenReadStream().CopyToAsync(fileStream);
            }
        }
    }
</code>```

Body:
Good afternoon, I currently have the problem of uploading a jpg to the server of my application, it returns it to me in this way, there are times that it is displayed well but there are others that it shows me cropped, I leave an image so that you understand what it is going

Bug

What I was trying to do is get the path of the image that saves it to a folder and extract the name of the file from that path to finally upload it to the server with httpclient, this is my code so far

public async void DownloadFile(DownloadInfo Info, string directory, string cameraName, string cameraIndex, double latitude, double longitude, string barcode, string imageUrl, string watermarkText)
        {
            CheckState();
            if (Info == null) throw new ArgumentNullException(nameof(Info));
            if (directory == null || string.IsNullOrEmpty(directory.Trim())) directory = ".";

            string dateCapture = DateTime.Now.ToString("ddMMyyyy");
            string timeCapture = DateTime.Now.ToString("hhmmss");
            string currentFileName = $"{cameraName}{cameraIndex}-{dateCapture}{timeCapture}.jpg";
            string currentFilePath = Path.Combine(directory, Info.FileName = currentFileName);
            string baseFolder = $"{directory}/{DeviceName}";
            string demoFolder = $"{directory}/{DeviceName}/Demo";
            //string definitiveFolder = $"{directory}/{DeviceName}/Definitive";

            CreateFolderIfNotExist(directory);
            CreateFolderIfNotExist(baseFolder);
            CreateFolderIfNotExist(demoFolder);
            //CreateFolderIfNotExist(definitiveFolder);

            DownloadToFile(Info, currentFilePath);

            await SendPhoto(currentFilePath, Reserved, DeviceName, Info.FileName);

            using (var bitmap = GetBitmap(currentFilePath))
            {
                Image watermarkImage = Image.FromFile(imageUrl);
                var folderSaveFilePath = Path.Combine(baseFolder, currentFileName);
                AddImageWatermark(bitmap, folderSaveFilePath, watermarkImage);
                AddMetadata(folderSaveFilePath, bitmap, latitude, longitude, barcode);
                var fileName = Path.GetFileName(folderSaveFilePath);
                await UploadFile(folderSaveFilePath, barcode, fileName);
            }

            using (var bitmap = GetBitmap(currentFilePath))
            {
                var folderSaveFilePath = Path.Combine(demoFolder, currentFileName);
                AddFontWatermark(bitmap, folderSaveFilePath, watermarkText);
                AddMetadata(folderSaveFilePath, bitmap, latitude, longitude, barcode);
            }

            File.Delete(currentFilePath);
        }

        public async Task<string> UploadFile(string filePath, string barcode, string photo)
        {
            var stringResponse = string.Empty;

            try
            {
                using (var httpClient = new HttpClient())
                {
                    using (var multipartFormContent = new MultipartFormDataContent())
                    {
                        //Add other fields
                        multipartFormContent.Add(new StringContent(barcode), name: "barcode");

                        //Add the file
                        var fileStreamContent = new StreamContent(File.OpenRead(filePath));
                        fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
                        multipartFormContent.Add(fileStreamContent, name: "photo", fileName: photo);

                        //Send it
                        var response = await httpClient.PostAsync("https://localhost:7288/api/zip", multipartFormContent);
                        response.EnsureSuccessStatusCode();

                        if (response.IsSuccessStatusCode)
                            stringResponse = await response.Content.ReadAsStringAsync();
                        else
                            stringResponse = response.StatusCode.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                var error = ex.Message;
            }

            return stringResponse;
        }

public class ZipFileHelper : IZipFileHelper
    {
        private double _currentArchiveSize = 0;
        private readonly IWebHostEnvironment _env;
        private double _maxArchiveSize = 104857600; //100mb
        private List<string> _archives = new();
        private List<string> _filesInCurrentArchive = new();
        ZipFile _zip = null;

        public ZipFileHelper(IWebHostEnvironment env)
        {
            _env = env;
        }

        public async Task UploadPhoto(IFormFile photo, string barcode)
        {
            string folder = Path.Combine(_env.ContentRootPath, $"Uploads/{barcode}");

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            string path = Path.Combine(folder, photo.FileName);

            using (FileStream fileStream = File.Create(path))
            {
                await photo.OpenReadStream().CopyToAsync(fileStream);
            }
        }
    }


问:
docker-compose not building las stage in dockerfile
I have the below multi-stage docker file.

```<code>FROM node:19-slim as base
RUN npm i npm@latest -g
RUN mkdir /app && chown -R node:node /app
WORKDIR /app
USER node
COPY --chown=node:node package.json package-lock*.json ./
RUN npm install --legacy-peer-deps && npm cache clean --force
ENV PATH /app/node_modules/.bin:$PATH
# check every 30s to ensure this service returns HTTP 200

FROM base as source
COPY --chown=node:node . .

FROM source as dev
ENV NODE_ENV=development
RUN npm install --legacy-peer-deps --only=development
RUN npm run build

FROM source as prod
RUN npm run build

FROM nginx:latest
COPY --from=dev /app/nginx/default.conf /etc/nginx/conf.d/default.conf

## Remove default nginx index page
RUN rm -rf /usr/share/nginx/html/*

# Copy from the stahg 1
COPY --from=dev /app/build /usr/share/nginx/html

EXPOSE 3001

ENTRYPOINT ["nginx", "-g", "daemon off;"]

</code>```

In the first stage, the node base image is used to install the latest version of npm, create the /app directory, and install the dependencies for the app. The second stage, called source, copies the source code of the app into the image.

The third and fourth stages, called dev and prod, respectively, are used to build the app in development and production mode. The dev stage also installs additional development dependencies and copies the nginx.conf file for the app. The prod stage builds the app without installing any other dependencies.

Finally, the fifth stage uses the nginx base image to serve the built app. It copies the nginx.conf file and the built app from the dev stage and exposes port 3001 for the app.

When I build Dockerfile using docker, it also builds FROM nginx:latest stage.
But, I use docke-compose to build it, it just ignore the las step.

Here is docker-compose file:

```<code>version: '3'
services:
  postgres:
    image: 'postgres:latest'
    environment:
      - POSTGRES_PASSWORD=postgres_password
  nginx:
    depends_on:
      - api
      - client
    restart: always
    build:
      dockerfile: Dockerfile
      context: ./nginx
    ports:
      - '3050:80'
  api:
    build:
      dockerfile: Dockerfile
      context: './backend'
      target: dev
    environment:
      - PGUSER=postgres
      - PGHOST=postgres
      - PGDATABASE=postgres
      - PGPASSWORD=postgres_password
      - PGPORT=5432
  client:
    stdin_open: true
    build:
      dockerfile: Dockerfile
      context: ./frontend
      target: dev
</code>```
```<code>Building client
[+] Building 0.9s (13/13) FINISHED
 => [internal] load build definition from Dockerfile                                                                                0.0s
 => => transferring dockerfile: 874B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 34B                                                                                0.0s
 => [internal] load metadata for docker.io/library/node:14.5.0-alpine3.10                                                                          0.8s
 => [base 1/5] FROM docker.io/library/node:14.5.0-alpine3.10@sha256:7fb1e608dc4081c25930db83cb4a5df884b6a3f6e4e9f5fa2df08f22778fcfad               0.0s
 => [internal] load build context                                                                                0.0s
 => => transferring context: 4.79kB                                                                                0.0s
 => CACHED [base 2/5] RUN mkdir /app && chown -R node:node /app                                                                                0.0s
 => CACHED [base 3/5] WORKDIR /app                                                                                0.0s
 => CACHED [base 4/5] COPY --chown=node:node package.json package-lock*.json ./                                                                    0.0s
 => CACHED [base 5/5] RUN npm install --legacy-peer-deps && npm cache clean --force                                                                0.0s
 => CACHED [source 1/1] COPY --chown=node:node . .                                                                                0.0s
 => CACHED [dev 1/2] RUN npm install --legacy-peer-deps --only=development                                                                         0.0s
 => CACHED [dev 2/2] RUN npm run build                                                                                0.0s
 => exporting to image                                                                                0.0s
 => => exporting layers                                                                                0.0s
 => => writing image sha256:b82b488fc6b4bda36f2bc60c66474ef4ac74d6db1345758acd5f2e01e48b5639                                                       0.0s
 => => naming to docker.io/library/client
</code>```

Body:
I have the below multi-stage docker file.

FROM node:19-slim as base
RUN npm i npm@latest -g
RUN mkdir /app && chown -R node:node /app
WORKDIR /app
USER node
COPY --chown=node:node package.json package-lock*.json ./
RUN npm install --legacy-peer-deps && npm cache clean --force
ENV PATH /app/node_modules/.bin:$PATH
# check every 30s to ensure this service returns HTTP 200

FROM base as source
COPY --chown=node:node . .

FROM source as dev
ENV NODE_ENV=development
RUN npm install --legacy-peer-deps --only=development
RUN npm run build

FROM source as prod
RUN npm run build

FROM nginx:latest
COPY --from=dev /app/nginx/default.conf /etc/nginx/conf.d/default.conf

## Remove default nginx index page
RUN rm -rf /usr/share/nginx/html/*

# Copy from the stahg 1
COPY --from=dev /app/build /usr/share/nginx/html

EXPOSE 3001

ENTRYPOINT ["nginx", "-g", "daemon off;"]

In the first stage, the node base image is used to install the latest version of npm, create the /app directory, and install the dependencies for the app. The second stage, called source, copies the source code of the app into the image.

The third and fourth stages, called dev and prod, respectively, are used to build the app in development and production mode. The dev stage also installs additional development dependencies and copies the nginx.conf file for the app. The prod stage builds the app without installing any other dependencies.

Finally, the fifth stage uses the nginx base image to serve the built app. It copies the nginx.conf file and the built app from the dev stage and exposes port 3001 for the app.

When I build Dockerfile using docker, it also builds FROM nginx:latest stage.
But, I use docke-compose to build it, it just ignore the las step.

Here is docker-compose file:

version: '3'
services:
  postgres:
    image: 'postgres:latest'
    environment:
      - POSTGRES_PASSWORD=postgres_password
  nginx:
    depends_on:
      - api
      - client
    restart: always
    build:
      dockerfile: Dockerfile
      context: ./nginx
    ports:
      - '3050:80'
  api:
    build:
      dockerfile: Dockerfile
      context: './backend'
      target: dev
    environment:
      - PGUSER=postgres
      - PGHOST=postgres
      - PGDATABASE=postgres
      - PGPASSWORD=postgres_password
      - PGPORT=5432
  client:
    stdin_open: true
    build:
      dockerfile: Dockerfile
      context: ./frontend
      target: dev

Building client
[+] Building 0.9s (13/13) FINISHED
 => [internal] load build definition from Dockerfile                                                                                0.0s
 => => transferring dockerfile: 874B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 34B                                                                                0.0s
 => [internal] load metadata for docker.io/library/node:14.5.0-alpine3.10                                                                          0.8s
 => [base 1/5] FROM docker.io/library/node:14.5.0-alpine3.10@sha256:7fb1e608dc4081c25930db83cb4a5df884b6a3f6e4e9f5fa2df08f22778fcfad               0.0s
 => [internal] load build context                                                                                0.0s
 => => transferring context: 4.79kB                                                                                0.0s
 => CACHED [base 2/5] RUN mkdir /app && chown -R node:node /app                                                                                0.0s
 => CACHED [base 3/5] WORKDIR /app                                                                                0.0s
 => CACHED [base 4/5] COPY --chown=node:node package.json package-lock*.json ./                                                                    0.0s
 => CACHED [base 5/5] RUN npm install --legacy-peer-deps && npm cache clean --force                                                                0.0s
 => CACHED [source 1/1] COPY --chown=node:node . .                                                                                0.0s
 => CACHED [dev 1/2] RUN npm install --legacy-peer-deps --only=development                                                                         0.0s
 => CACHED [dev 2/2] RUN npm run build                                                                                0.0s
 => exporting to image                                                                                0.0s
 => => exporting layers                                                                                0.0s
 => => writing image sha256:b82b488fc6b4bda36f2bc60c66474ef4ac74d6db1345758acd5f2e01e48b5639                                                       0.0s
 => => naming to docker.io/library/client


问:
How to switch the factor level for the outcome used for in caret
This is somewhat tough to explain, but essentially, I developed an XGBoost model in caret for a set of data (I am trying to detect cancer based on a certain number of explanatory features). The outcome variables is the presence of cancer (Yes/No) and it a factor variable. The problem that arose was when I tried to do some analysis with SHAP. I used the fastshap package to calculate shap values for the test dataset and shapviz to plot beeswarm plots and dependency plots. The problem is that the relationships between explanatory variables and the outcome are the complete opposite of what domain knowledge says should be right. For example, a shap dependency plot showed that increasing age had a negative correlation with the cancer outcome, when it should be the opposite (older age increases cancer risk). The fact is that every relationship in the shap analysis has an inverted relationship like this suggests to me that maybe the XGBoost model is trying to identify, as it's outcome, the absence of cancer (presence of cancer=No instead of presence of cancer=Yes), and this may be why every relationship is inverted. Is there anyway in caret I can select the factor level that the xgboost model uses for outcome identification?

I honestly have no idea how to switch the factor level that is used for outcome identification in caret (usign xgbTree as the method).


问:
Why can't I access past index 199 on the google books API
`I'm building a discord bot in python.
Every time a user types a command such as "fantasy 10" the bot will give the user a list of 10 books from that genre.

```<code>import discord
import requests
import random
from discord.ext import commands

base_url = "https://www.googleapis.com/books/v1/volumes"

client = commands.Bot(command_prefix="=",intents=discord.Intents.all())

books_list = []

@client.command()
async def recommend(cxt,subject:str, num_books:int):

        create_book_list(subject)

        randomizer = random.randint(0,len(books_list) - num_books)

        for i in range(num_books):

            await cxt.channel.send(books_list[i + randomizer]["volumeInfo"]["title"])

def create_book_list(subject):

        start_index = 0

        num_loops = 15

        for i in range(num_loops):

            params = {
            "q": f"subject:{subject}",
            "maxResults": 14,
            "startIndex": start_index,
            "printType": "books",
        }
            start_index = start_index + 14
            response = requests.get(base_url,params=params)

            if response.status_code == 200:

                books = response.json()["items"]

                for book in books:
                    books_list.append(book);

client.run("")
</code>```

I tried many ways  to loop through all the books in a genre as you can see but basically I can't access index past 200.
if startingIndex is more than 200 code breaks

`I'm just wondering why I can't access  indexes past 200  as there should be more than 200 books in a specified genre.

I'm trying to access the books past index 200 so I can give the users more diversity when recommending books.

Body:
`I'm building a discord bot in python.
Every time a user types a command such as "fantasy 10" the bot will give the user a list of 10 books from that genre.

import discord
import requests
import random
from discord.ext import commands

base_url = "https://www.googleapis.com/books/v1/volumes"

client = commands.Bot(command_prefix="=",intents=discord.Intents.all())

books_list = []

@client.command()
async def recommend(cxt,subject:str, num_books:int):

        create_book_list(subject)

        randomizer = random.randint(0,len(books_list) - num_books)

        for i in range(num_books):

            await cxt.channel.send(books_list[i + randomizer]["volumeInfo"]["title"])

def create_book_list(subject):

        start_index = 0

        num_loops = 15

        for i in range(num_loops):

            params = {
            "q": f"subject:{subject}",
            "maxResults": 14,
            "startIndex": start_index,
            "printType": "books",
        }
            start_index = start_index + 14
            response = requests.get(base_url,params=params)

            if response.status_code == 200:

                books = response.json()["items"]

                for book in books:
                    books_list.append(book);

client.run("")

I tried many ways  to loop through all the books in a genre as you can see but basically I can't access index past 200.
if startingIndex is more than 200 code breaks

`I'm just wondering why I can't access  indexes past 200  as there should be more than 200 books in a specified genre.

I'm trying to access the books past index 200 so I can give the users more diversity when recommending books.


问:
Newly added Intent is not working Dialogflow
I am trying to add new intent and the response is custom payload but it is not working in my android app.
I have also tried to use the same response of intent which is working but still, I am not getting a response.</p>


问:
getCookies from superagent
I'm using superagent with cookies to run several requests.
At the end of the run of all requests, I would like to receive the latest cookies

I tried the following code

const superagent = require("superagent")
const {CookieAccessInfo} = require('cookiejar')
const request = superagent.agent();
await request.post('https://my-domain/set-cookies');
await request.post('https://my-domain/set-cookies2');
const access = new CookieAccessInfo('my-domain', '/', true);
request.jar.getCookies(access)
```
<p>So far so good.
The problem is that if I try to get the cookies from <code>Google.com</code> domain I will also get the same output (the cookies from <code>my-domain</code>).</p>
<pre class="lang-js prettyprint-override"><code>const access = new CookieAccessInfo('google.com', '/', true);
request.jar.getCookies(access)
</code>```

This code will return the same cookies as before...
According to this, I understand that I am not extracting the cookies correctly.
I would appreciate help on how to use getCookies correctly per specific domain. I don't want to use  set-cookies header to get this information.

Title: getCookies from superagent

Body:
I'm using superagent with cookies to run several requests.
At the end of the run of all requests, I would like to receive the latest cookies

I tried the following code

const superagent = require("superagent")
const {CookieAccessInfo} = require('cookiejar')
const request = superagent.agent();
await request.post('https://my-domain/set-cookies');
await request.post('https://my-domain/set-cookies2');
const access = new CookieAccessInfo('my-domain', '/', true);
request.jar.getCookies(access)

So far so good.
The problem is that if I try to get the cookies from Google.com domain I will also get the same output (the cookies from my-domain).

const access = new CookieAccessInfo('google.com', '/', true);
request.jar.getCookies(access)

This code will return the same cookies as before...
According to this, I understand that I am not extracting the cookies correctly.
I would appreciate help on how to use getCookies correctly per specific domain. I don't want to use  set-cookies header to get this information.


问:
Sum with multiple conditions and GROUP BY
I have these 3 tables :

order_details

id
date

5
15/12/2022

6
15/12/2022

7
16/12/2022

order_items

id
orderId
productId
quantity

7
5
5
10

8
5
6
5

9
5
7
2

10
6
5
10

11
6
6
5

12
6
7
2

13
7
5
7

14
7
6
3

products

id
name

5
productOne

6
productTwo

7
productThree

I want to join these 3 tables and have a list of products associated with their date and sum of the quantities

For example for these tables I want this:

date
product_name
quantity

15/12/2022
productOne
20

15/12/2022
productTwo
10

15/12/2022
productThree
4

15/12/2022
productOne
20

15/12/2022
productTwo
10

15/12/2022
productThree
4

16/12/2022
productOne
7

16/12/2022
productTwo
3

If someone can help me it would be so beautiful...

Here is my work on my side ->

```<code>SELECT *
  FROM order_details
  JOIN (SELECT order_items.orderId,
               order_items.productId,
               order_items.quantity,
               products.name,
               SUM(order_items.quantity)
          FROM order_items
         INNER JOIN products
            ON order_items.productId = products.id
         GROUP BY order_items.productId) AS items
 GROUP BY order_details.date, items.productId
</code>```

Body:
I have these 3 tables :

order_details

id
date

5
15/12/2022

6
15/12/2022

7
16/12/2022

order_items

id
orderId
productId
quantity

7
5
5
10

8
5
6
5

9
5
7
2

10
6
5
10

11
6
6
5

12
6
7
2

13
7
5
7

14
7
6
3

products

id
name

5
productOne

6
productTwo

7
productThree

I want to join these 3 tables and have a list of products associated with their date and sum of the quantities

For example for these tables I want this:

date
product_name
quantity

15/12/2022
productOne
20

15/12/2022
productTwo
10

15/12/2022
productThree
4

15/12/2022
productOne
20

15/12/2022
productTwo
10

15/12/2022
productThree
4

16/12/2022
productOne
7

16/12/2022
productTwo
3

If someone can help me it would be so beautiful...

Here is my work on my side ->

SELECT *
  FROM order_details
  JOIN (SELECT order_items.orderId,
               order_items.productId,
               order_items.quantity,
               products.name,
               SUM(order_items.quantity)
          FROM order_items
         INNER JOIN products
            ON order_items.productId = products.id
         GROUP BY order_items.productId) AS items
 GROUP BY order_details.date, items.productId


问:
How do I access an internal link with Selenium that seems restricted
I am trying to fetch data from nj.58.com using selenium. I can access the homepapage and some internal links. While navigating through the links, I noticed that the website sees me as a web crawler when I visit a specific url; even if I interact with the links as a human.

I have built my selenium script to a point but I'm stock because the sites throws antibot response back at me.

Here is what I've done:

```<code>
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import Select
import undetected_chromedriver as uc
import time
import pandas as pd

driver = uc.Chrome()
website = 'https://nj.58.com/'

driver.get(website)
driver.implicitly_wait(4)
wait = WebDriverWait(driver, 10)
driver.maximize_window()

switch_city = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#commonTopbar_ipconfig > a"))).click()

city_location = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#selector-search-input')))

city_location.clear()
city_location.send_keys('南京' + Keys.RETURN)

keyword = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#keyword')))

keyword.clear()
keyword.send_keys('"废纸回收"')
time.sleep(2)

search_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#searchbtn')))
search_btn.click()
</code>```

When I click on search_btn, I'm expecting to see a list of items that I'm interested in. But instead it sees me as a web crawler at this variable position (search_btn) even before using the selenium.

How can I bypass this antibot/antihuman detection at point when I click on search_btn?

Body:
I am trying to fetch data from nj.58.com using selenium. I can access the homepapage and some internal links. While navigating through the links, I noticed that the website sees me as a web crawler when I visit a specific url; even if I interact with the links as a human.

I have built my selenium script to a point but I'm stock because the sites throws antibot response back at me.

Here is what I've done:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import Select
import undetected_chromedriver as uc
import time
import pandas as pd

driver = uc.Chrome()
website = 'https://nj.58.com/'

driver.get(website)
driver.implicitly_wait(4)
wait = WebDriverWait(driver, 10)
driver.maximize_window()

switch_city = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#commonTopbar_ipconfig > a"))).click()

city_location = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#selector-search-input')))

city_location.clear()
city_location.send_keys('南京' + Keys.RETURN)

keyword = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#keyword')))

keyword.clear()
keyword.send_keys('"废纸回收"')
time.sleep(2)

search_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#searchbtn')))
search_btn.click()

When I click on search_btn, I'm expecting to see a list of items that I'm interested in. But instead it sees me as a web crawler at this variable position (search_btn) even before using the selenium.

How can I bypass this antibot/antihuman detection at point when I click on search_btn?


问:
Download Nuget Package using Nuget.exe
Im working on an automation solution for transfering nuget packages from nuget.org to a private nuget feed. Is it possible to download nuget packages using nuget.exe? If i run the following command, it fails because it tries to install it to the directory, but i dont need to install the package i just need to download it.

```<code>.\nuget.exe install Microsoft.AspNetCore.App.Runtime.linux-x64 -source nuget.org -force
</code>```

This throws the following error:

```<code>Error NU5000: Package 'Microsoft.AspNetCore.App.Runtime.linux-x64 7.0.1' has a package type 'DotnetPlatform' that is not supported by project 'C:\foo'.
</code>```

I am looking for something like a -force option, so that i can just download the package without installing it.

Title: Download Nuget Package using Nuget.exe

Body:
Im working on an automation solution for transfering nuget packages from nuget.org to a private nuget feed. Is it possible to download nuget packages using nuget.exe? If i run the following command, it fails because it tries to install it to the directory, but i dont need to install the package i just need to download it.

.\nuget.exe install Microsoft.AspNetCore.App.Runtime.linux-x64 -source nuget.org -force

This throws the following error:

Error NU5000: Package 'Microsoft.AspNetCore.App.Runtime.linux-x64 7.0.1' has a package type 'DotnetPlatform' that is not supported by project 'C:\foo'.

I am looking for something like a -force option, so that i can just download the package without installing it.


问:
Drawing box-plot only white max and min in python
I would like to draw box-plot for below data set but I don't need tails . I need a tip whit  max and min on edges Only like in the picture  .

Please help.

Thank you.

I try using libre office Excel but didn't work


问:
How to avoid re renders when using rtk query in react native
I am using rtk query with below logic

```<code> if(isSuccess){
    console.log("success")
     storeToken(data.token)
    dispatch(login())
}
</code>```

But this code causing too many re renders causing error in react native

Body:
I am using rtk query with below logic

 if(isSuccess){
    console.log("success")
     storeToken(data.token)
    dispatch(login())
}

But this code causing too many re renders causing error in react native


问:
Spring Boot Data JPA "Cannot instantiate abstract class or interface" with abstract class
I have this abstract class

```<code>abstract class EventContext(
    protected var name: String
)

</code>```

That is extended by:

```<code>@Embeddable
class GameEventContext : EventContext("game")

</code>```

The whole is hold by:

```<code>@Entity
class GameEvent(
    @Id
    val id: String = UUID.randomUUID().toString(),
    @Embedded
    val context: EventContext,
    @Embedded
    val message: EventMessage
)

</code>```

and instantiated by:

```<code>object GameEventFactory {

    fun test() = GameEvent(
        id = UUID.randomUUID().toString(),
        context = GameEventContext(),
        message = EventMessage("game", "foo message"),
    )
}

</code>```

Now when running my @DataJpaTest:

```<code>@DataJpaTest
class GameEventRepositoryTest {
    @Autowired
    private lateinit var gameEventRepository: GameEventRepository

    @Test
    fun `should save game event`() {
        val gameEvent = GameEventFactory.test()
        gameEventRepository.save(gameEvent)
    }
}

</code>```

The following exception is thrown:

```<code>Cannot instantiate abstract class or interface:  : com.barbarus.gameserver.event.EventContext; nested exception is org.hibernate.InstantiationException: Cannot instantiate abstract class or interface:  : com.barbarus.gameserver.event.EventContext
org.springframework.orm.jpa.JpaSystemException: Cannot instantiate abstract class or interface:  : com.barbarus.gameserver.event.EventContext; nested exception is org.hibernate.InstantiationException: Cannot instantiate abstract class or interface:  : com.barbarus.gameserver.event.EventContext
    at app//org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:331)
    at app//org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)
    at app//org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)
    at app//org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at app//org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at app//org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)
    at app//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at app//org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174)
    at app//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at app//org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
    at app//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at app//org.springframework.data.repository.core.support.MethodInvocationValidator.invoke(MethodInvocationValidator.java:99)
    at app//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at app//org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
    at app/jdk.proxy3/jdk.proxy3.$Proxy142.save(Unknown Source)
    at app//com.barbarus.gameserver.event.GameEventRepositoryTest.should save game event(GameEventRepositoryTest.kt:17)
</code>```

I do understand the problem but I have no idea how to work around it properly?

Body:
I have this abstract class

abstract class EventContext(
    protected var name: String
)

That is extended by:

@Embeddable
class GameEventContext : EventContext("game")

The whole is hold by:

@Entity
class GameEvent(
    @Id
    val id: String = UUID.randomUUID().toString(),
    @Embedded
    val context: EventContext,
    @Embedded
    val message: EventMessage
)

and instantiated by:

object GameEventFactory {

    fun test() = GameEvent(
        id = UUID.randomUUID().toString(),
        context = GameEventContext(),
        message = EventMessage("game", "foo message"),
    )
}

Now when running my @DataJpaTest:

@DataJpaTest
class GameEventRepositoryTest {
    @Autowired
    private lateinit var gameEventRepository: GameEventRepository

    @Test
    fun `should save game event`() {
        val gameEvent = GameEventFactory.test()
        gameEventRepository.save(gameEvent)
    }
}

The following exception is thrown:

Cannot instantiate abstract class or interface:  : com.barbarus.gameserver.event.EventContext; nested exception is org.hibernate.InstantiationException: Cannot instantiate abstract class or interface:  : com.barbarus.gameserver.event.EventContext
org.springframework.orm.jpa.JpaSystemException: Cannot instantiate abstract class or interface:  : com.barbarus.gameserver.event.EventContext; nested exception is org.hibernate.InstantiationException: Cannot instantiate abstract class or interface:  : com.barbarus.gameserver.event.EventContext
    at app//org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:331)
    at app//org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)
    at app//org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)
    at app//org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at app//org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at app//org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)
    at app//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at app//org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174)
    at app//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at app//org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
    at app//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at app//org.springframework.data.repository.core.support.MethodInvocationValidator.invoke(MethodInvocationValidator.java:99)
    at app//org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at app//org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
    at app/jdk.proxy3/jdk.proxy3.$Proxy142.save(Unknown Source)
    at app//com.barbarus.gameserver.event.GameEventRepositoryTest.should save game event(GameEventRepositoryTest.kt:17)

I do understand the problem but I have no idea how to work around it properly?


问:
Tailwind ignoring darkMode: "class", not paying attention to class="dark" on html tag
Using tailwind and react, I am using a config file as follows:

```<code>/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{html,js,jsx,ts,tsx}"],
  darkMode: "class",
  important: "#app",
  theme: {
    colors: {
      ...
    },
    fontFamily: {
      ...
    },
    extend: {},
  },
  plugins: [],
  corePlugins: {
    preflight: false,
  },
};

</code>```

and setting the class as follows

```<code>darkMode
      ? document.documentElement.classList.add("dark")
      : document.documentElement.classList.remove("dark");
</code>```

Inspecting the top element, it is indeed adding and removing a class="dark" to the top element. However, two elements like

```<code>text-grey-300 dark:text-grey-700
</code>```

aren't changing when the class changes, at all. When the darkMode: Class is removed, it accurately follows OS preference however. Whats going on?

I have tried changing the class selector manually, tried placing the dark on other elements, moving the declaration around in my config file, none of it seems to help.

Body:
Using tailwind and react, I am using a config file as follows:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{html,js,jsx,ts,tsx}"],
  darkMode: "class",
  important: "#app",
  theme: {
    colors: {
      ...
    },
    fontFamily: {
      ...
    },
    extend: {},
  },
  plugins: [],
  corePlugins: {
    preflight: false,
  },
};

and setting the class as follows

darkMode
      ? document.documentElement.classList.add("dark")
      : document.documentElement.classList.remove("dark");

Inspecting the top element, it is indeed adding and removing a class="dark" to the top element. However, two elements like

text-grey-300 dark:text-grey-700

aren't changing when the class changes, at all. When the darkMode: Class is removed, it accurately follows OS preference however. Whats going on?

I have tried changing the class selector manually, tried placing the dark on other elements, moving the declaration around in my config file, none of it seems to help.


问:
What is the best way to validate a large json file before reading it into a pyspark dataframe?
I have to read a large (roughly 1500 lines) json file into a pyspark data frame, and take into account incomplete json objects and unexpected line endings. The file has one json object per line, and looks like this:

```<code>{"place":{"place_name":"Chicago","place_id": 23654},"category":"city","population":8000000}...}
{"place":{"place_name":"New York","place_id": 23754},"category":"city","population":10000000}...}
</code>```

I found an example of how to fix broken json objects, but that would require me to iterate over the file line by line (accepted answer here: Complete a json string from incomplete HTTP JSON response). Is it a good strategy to do this and to rewrite any broken lines in the file before reading it into the pyspark dataframe?

Also, would a simple regex replace operation be enough to remove the unexpected line endings in the middle of the objects?

Any help would be much appreciated.

Body:
I have to read a large (roughly 1500 lines) json file into a pyspark data frame, and take into account incomplete json objects and unexpected line endings. The file has one json object per line, and looks like this:

{"place":{"place_name":"Chicago","place_id": 23654},"category":"city","population":8000000}...}
{"place":{"place_name":"New York","place_id": 23754},"category":"city","population":10000000}...}

I found an example of how to fix broken json objects, but that would require me to iterate over the file line by line (accepted answer here: Complete a json string from incomplete HTTP JSON response). Is it a good strategy to do this and to rewrite any broken lines in the file before reading it into the pyspark dataframe?

Also, would a simple regex replace operation be enough to remove the unexpected line endings in the middle of the objects?

Any help would be much appreciated.


问:
I am trying to make two different cubes in WebGL using jsbin
I am trying to draw two different cubes in jsbin using WebGL. There is only one cube showing even though I have two different sets of points for normals, vertices and etc. I also set up additional buffers for the second object but its not letting me draw a second object. I am not entirely sure what I am doing wrong but here is my current code. I would appreciaite it if someone could explain whats wrong and how to fix it so I dont make the same mistake again.

```<code><!DOCTYPE html>
<!--
Created using JS Bin
http://jsbin.com

Copyright (c) 2022 by anonymous (http://jsbin.com/jixoqosoxo/1/edit)

Released under the MIT license: http://jsbin.mit-license.org
-->
<meta name="robots" content="noindex">
<html>
  <head>
    <title>WebGL cube drawn with indexed vertex list</title>
  </head>

  <body>
    <script id="vertexShader" type="not-js">
      attribute vec3 vPosition;
      attribute vec3 vNormal;
      attribute vec3 vColor;
      attribute vec2 vTexCoord;
      varying vec3 fPosition;
      varying vec3 fColor;
      varying vec3 fNormal;
      varying vec2 fTexCoord;
      uniform mat4 uMV;
      uniform mat4 uMVP;

      void main(void) {
        gl_Position = uMVP * vec4(vPosition, 1.0);
        fPosition = (uMV * vec4(vPosition, 1.0)).xyz; // In camera coordinates
        fColor = vColor;
        fNormal = vNormal;                            // In local coordinates
        fTexCoord = vTexCoord;
     }
    </script>

    <script id="fragmentShader" type="not-js">
      precision highp float;
      varying vec3 fPosition;
      varying vec3 fColor;
      varying vec3 fNormal;
      varying vec2 fTexCoord;
      uniform mat4 uMV;
      uniform mat3 uMVn;
      uniform sampler2D texSampler1;
      uniform sampler2D texSampler2;

      const vec3  lightV    = vec3(0.0,-0.3,1.0);
      const float lightI    = 1.0;               // only for diffuse component
      const float ambientC  = 0.5;
      const float diffuseC  = 0.4;
      const float specularC = 0.3;
      const float specularE = 32.0;
      const vec3  lightCol  = vec3(1.0,1.0,1.0);
      const vec3  objectCol = vec3(1.0,0.6,0.0); // yellow-ish orange
      vec2 blinnPhongDir(vec3 lightDir, vec3 n, float lightInt, float Ka,
        float Kd, float Ks, float shininess) {
        vec3 s = normalize(lightDir);
        vec3 v = normalize(-fPosition);
        vec3 h = normalize(v+s);
        float diffuse = Ka + Kd * lightInt * max(0.0, dot(n, s));
        float spec =  Ks * pow(max(0.0, dot(n,h)), shininess);
        return vec2(diffuse, spec);
      }

      void main(void) {
        vec3 texColor=texture2D(texSampler1,fTexCoord).xyz;
        vec3 n = normalize(uMVn * fNormal);
        vec3 ColorS  = blinnPhongDir(lightV,n,0.0   ,0.0,     0.0,     specularC,specularE).y*lightCol;
        vec3 ColorAD = blinnPhongDir(lightV,n,lightI,ambientC,diffuseC,0.0,      1.0      ).x*texColor;
        gl_FragColor = vec4(ColorAD+ColorS,1.0);
      }
    </script>

    <canvas id="mycanvas" width="500" height="500"></canvas>
    <br>
    <input id="slider1" type="range" min="-100" max="100" />
    <input id="slider2" type="range" min="-100" max="100" />

    <script type="text/javascript">
     //Have long code here had to remove so I could post this question
    </script>
  <script id="jsbin-javascript">
function start() {

    // Get canvas, WebGL context, twgl.m4
    var canvas = document.getElementById("mycanvas");
    var gl = canvas.getContext("webgl", {preserveDrawingBuffer: true});

    // Sliders at center
    var slider1 = document.getElementById('slider1');
    slider1.value = 0;
    var slider2 = document.getElementById('slider2');
    slider2.value = 0;

    // Read shader source
    var vertexSource = document.getElementById("vertexShader").text;
    var fragmentSource = document.getElementById("fragmentShader").text;

    // Compile vertex shader
    var vertexShader = gl.createShader(gl.VERTEX_SHADER);
    gl.shaderSource(vertexShader,vertexSource);
    gl.compileShader(vertexShader);
    if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
      alert(gl.getShaderInfoLog(vertexShader)); return null; }

    // Compile fragment shader
    var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
    gl.shaderSource(fragmentShader,fragmentSource);
    gl.compileShader(fragmentShader);
    if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
      alert(gl.getShaderInfoLog(fragmentShader)); return null; }

    // Attach the shaders and link
    var shaderProgram = gl.createProgram();
    gl.attachShader(shaderProgram, vertexShader);
    gl.attachShader(shaderProgram, fragmentShader);
    gl.linkProgram(shaderProgram);
    if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
      alert("Could not initialize shaders"); }
    gl.useProgram(shaderProgram);

    // with the vertex shader, we need to pass it positions
    // as an attribute - so set up that communication
    shaderProgram.PositionAttribute = gl.getAttribLocation(shaderProgram, "vPosition");
    gl.enableVertexAttribArray(shaderProgram.PositionAttribute);

    shaderProgram.NormalAttribute = gl.getAttribLocation(shaderProgram, "vNormal");
    gl.enableVertexAttribArray(shaderProgram.NormalAttribute);

    shaderProgram.ColorAttribute = gl.getAttribLocation(shaderProgram, "vColor");
    gl.enableVertexAttribArray(shaderProgram.ColorAttribute);

    shaderProgram.texcoordAttribute = gl.getAttribLocation(shaderProgram, "vTexCoord");
    gl.enableVertexAttribArray(shaderProgram.texcoordAttribute);

    // this gives us access to the matrix uniform
    shaderProgram.MVmatrix = gl.getUniformLocation(shaderProgram,"uMV");
    shaderProgram.MVNormalmatrix = gl.getUniformLocation(shaderProgram,"uMVn");
    shaderProgram.MVPmatrix = gl.getUniformLocation(shaderProgram,"uMVP");

    // Attach samplers to texture units
    shaderProgram.texSampler1 = gl.getUniformLocation(shaderProgram, "texSampler1");
    gl.uniform1i(shaderProgram.texSampler1, 0);
    shaderProgram.texSampler2 = gl.getUniformLocation(shaderProgram, "texSampler2");
    gl.uniform1i(shaderProgram.texSampler2, 1);

    // Data ...

    // vertex positions
    var vertexPos = new Float32Array(
        [  1, 1, 1,  -1, 1, 1,  -1,-1, 1,   1,-1, 1,
           1, 1, 1,   1,-1, 1,   1,-1,-1,   1, 1,-1,
           1, 1, 1,   1, 1,-1,  -1, 1,-1,  -1, 1, 1,
          -1, 1, 1,  -1, 1,-1,  -1,-1,-1,  -1,-1, 1,
          -1,-1,-1,   1,-1,-1,   1,-1, 1,  -1,-1, 1,
           1,-1,-1,  -1,-1,-1,  -1, 1,-1,   1, 1,-1 ]);

    // vertex normals
    var vertexNormals = new Float32Array(
        [  0, 0, 1,   0, 0, 1,   0, 0, 1,   0, 0, 1,
           1, 0, 0,   1, 0, 0,   1, 0, 0,   1, 0, 0,
           0, 1, 0,   0, 1, 0,   0, 1, 0,   0, 1, 0,
          -1, 0, 0,  -1, 0, 0,  -1, 0, 0,  -1, 0, 0,
           0,-1, 0,   0,-1, 0,   0,-1, 0,   0,-1, 0,
           0, 0,-1,   0, 0,-1,   0, 0,-1,   0, 0,-1  ]);

    // vertex colors
    var vertexColors = new Float32Array(
        [  0, 0, 1,   0, 0, 1,   0, 0, 1,   0, 0, 1,
           1, 0, 0,   1, 0, 0,   1, 0, 0,   1, 0, 0,
           0, 1, 0,   0, 1, 0,   0, 1, 0,   0, 1, 0,
           1, 1, 0,   1, 1, 0,   1, 1, 0,   1, 1, 0,
           1, 0, 1,   1, 0, 1,   1, 0, 1,   1, 0, 1,
           0, 1, 1,   0, 1, 1,   0, 1, 1,   0, 1, 1 ]);

    // vertex texture coordinates
    var vertexTextureCoords = new Float32Array(
        [  0, 0,   1, 0,   1, 1,   0, 1,
           1, 0,   1, 1,   0, 1,   0, 0,
           0, 1,   0, 0,   1, 0,   1, 1,
           0, 0,   1, 0,   1, 1,   0, 1,
           1, 1,   0, 1,   0, 0,   1, 0,
           1, 1,   0, 1,   0, 0,   1, 0 ]);

    // element index array
    var triangleIndices = new Uint8Array(
        [  0, 1, 2,   0, 2, 3,    // front
           4, 5, 6,   4, 6, 7,    // right
           8, 9,10,   8,10,11,    // top
          12,13,14,  12,14,15,    // left
          16,17,18,  16,18,19,    // bottom
          20,21,22,  20,22,23 ]); // back

    // we need to put the vertices into a buffer so we can
    // block transfer them to the graphics hardware
    var trianglePosBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertexPos, gl.STATIC_DRAW);
    trianglePosBuffer.itemSize = 3;
    trianglePosBuffer.numItems = 24;

    // a buffer for normals
    var triangleNormalBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, triangleNormalBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertexNormals, gl.STATIC_DRAW);
    triangleNormalBuffer.itemSize = 3;
    triangleNormalBuffer.numItems = 24;

    // a buffer for colors
    var colorBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertexColors, gl.STATIC_DRAW);
    colorBuffer.itemSize = 3;
    colorBuffer.numItems = 24;

    // a buffer for textures
    var textureBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, textureBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertexTextureCoords, gl.STATIC_DRAW);
    textureBuffer.itemSize = 2;
    textureBuffer.numItems = 24;

    // a buffer for indices
    var indexBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, triangleIndices, gl.STATIC_DRAW);

  var vertexPos2 = new Float32Array(
        [  1, 3, 1,   3, 3, 3,   1, 1, 3,   3, 1, 3,
           3, 3, 3,   3, 1, 3,   3, 1, 1,   3, 3, 1,
           3, 3, 3,   3, 3, 1,   1, 3, 1,   1, 3, 3,
           1, 3, 3,   1, 3, 1,   1, 1, 1,   1, 1, 3,
           1, 1, 1,   3, 1, 1,   3, 1, 3,   1, 1, 3,
           3, 1, 1,   1, 1, 1,   1, 3, 1,   3, 3, 1 ]);

    // vertex normals
    var vertexNormals2 = new Float32Array(
        [  0, 0, 1,   0, 0, 1,   0, 0, 1,   0, 0, 1,
           1, 0, 0,   1, 0, 0,   1, 0, 0,   1, 0, 0,
           0, 1, 0,   0, 1, 0,   0, 1, 0,   0, 1, 0,
          -1, 0, 0,  -1, 0, 0,  -1, 0, 0,  -1, 0, 0,
           0,-1, 0,   0,-1, 0,   0,-1, 0,   0,-1, 0,
           0, 0,-1,   0, 0,-1,   0, 0,-1,   0, 0,-1  ]);

    // vertex colors
    var vertexColors2 = new Float32Array(
        [  1, 0, 1,   0, 0, 1,   0, 0, 1,   0, 0, 1,
           1, 0, 0,   1, 0, 0,   1, 0, 0,   1, 0, 0,
           0, 1, 0,   0, 1, 0,   0, 1, 0,   0, 1, 0,
           1, 1, 0,   1, 1, 0,   1, 1, 0,   1, 1, 0,
           1, 0, 1,   1, 0, 1,   1, 0, 1,   1, 0, 1,
           0, 1, 1,   1, 1, 1,   0, 1, 1,   0, 0, 1 ]);

    // vertex texture coordinates
    var vertexTextureCoords2 = new Float32Array(
        [  0, 0,   1, 0,   1, 1,   0, 1,
           1, 0,   1, 1,   0, 1,   0, 0,
           0, 1,   0, 0,   1, 0,   1, 1,
           0, 0,   1, 0,   1, 1,   0, 1,
           1, 1,   0, 1,   0, 0,   1, 0,
           1, 1,   0, 1,   0, 0,   1, 0 ]);

    // element index array
    var triangleIndices2 = new Uint8Array(
        [  0, 1, 2,   0, 2, 3,    // front
           4, 5, 6,   4, 6, 7,    // right
           8, 9,10,   8,10,11,    // top
          12,13,14,  12,14,15,    // left
          16,17,18,  16,18,19,    // bottom
          20,21,22,  20,22,23 ]); // back

    // we need to put the vertices into a buffer so we can
    // block transfer them to the graphics hardware
    var trianglePosBuffer2 = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBuffer2);
    gl.bufferData(gl.ARRAY_BUFFER, vertexPos2, gl.STATIC_DRAW);
    trianglePosBuffer2.itemSize = 3;
    trianglePosBuffer2.numItems = 24;

    // a buffer for normals
    var triangleNormalBuffer2 = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, triangleNormalBuffer2);
    gl.bufferData(gl.ARRAY_BUFFER, vertexNormals2, gl.STATIC_DRAW);
    triangleNormalBuffer2.itemSize = 3;
    triangleNormalBuffer2.numItems = 24;

    // a buffer for colors
    var colorBuffer2 = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer2);
    gl.bufferData(gl.ARRAY_BUFFER, vertexColors2, gl.STATIC_DRAW);
    colorBuffer2.itemSize = 3;
    colorBuffer2.numItems = 24;

    // a buffer for textures
    var textureBuffer2 = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, textureBuffer2);
    gl.bufferData(gl.ARRAY_BUFFER, vertexTextureCoords2, gl.STATIC_DRAW);
    textureBuffer2.itemSize = 2;
    textureBuffer2.numItems = 24;

    // a buffer for indices
    var indexBuffer2 = gl.createBuffer();
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer2);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, triangleIndices2, gl.STATIC_DRAW);

    // Set up texture
    var texture1 = gl.createTexture();
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, texture1);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
    var image1 = new Image();

    var texture2 = gl.createTexture();
    gl.activeTexture(gl.TEXTURE1);
    gl.bindTexture(gl.TEXTURE_2D, texture2);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
    var image2 = new Image();

    function initTextureThenDraw()
    {
      image1.onload = function() { loadTexture(image1,texture1); };
      image1.crossOrigin = "anonymous";
      image1.src = "https://live.staticflickr.com/65535/50641871583_78566f4fbb_o.jpg";

      image2.onload = function() { loadTexture(image2,texture2); };
      image2.crossOrigin = "anonymous";
      image2.src = "https://live.staticflickr.com/65535/50641871583_78566f4fbb_o.jpg";

      window.setTimeout(draw,200);
    }

    function loadTexture(image,texture)
    {
      gl.bindTexture(gl.TEXTURE_2D, texture);
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);

      // Option 1 : Use mipmap, select interpolation mode
      gl.generateMipmap(gl.TEXTURE_2D);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);

      // Option 2: At least use linear filters
      // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
      // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

      // Optional ... if your shader & texture coordinates go outside the [0,1] range
      // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    }

     // Scene (re-)draw routine
     function draw() {

        // Translate slider values to angles in the [-pi,pi] interval
        var angle1 = slider1.value*0.01*Math.PI;
        var angle2 = slider2.value*0.01*Math.PI;

        // Circle around the y-axis
        var eye = [400*Math.sin(angle1),180.0,400.0*Math.cos(angle1)];
        var target = [0,0,0];
        var up = [0,1,0];

        var tModel = mat4.create();
        mat4.fromScaling(tModel,[50,50,50]);
        mat4.rotate(tModel,tModel,angle2,[1,1,1]);

        var tModel2 = mat4.create();
        mat4.fromScaling(tModel2, [50,50,50]);
        mat4.rotate(tModel2,tModel2,angle2,[1,0,1]);

        var tCamera = mat4.create();
        mat4.lookAt(tCamera, eye, target, up);

        var tProjection = mat4.create();
        mat4.perspective(tProjection,Math.PI/4,1,10,1000);

        var tMV = mat4.create();
        var tMVn = mat3.create();
        var tMVP = mat4.create();
        mat4.multiply(tMV,tCamera,tModel); // "modelView" matrix
        mat3.normalFromMat4(tMVn,tMV);
        mat4.multiply(tMVP,tProjection,tMV);

        var tMV2 = mat4.create();
        var tMVn2 = mat3.create();
        var tMVP2 = mat4.create();
        mat4.multiply(tMV2,tCamera,tModel2); // "modelView" matrix
        mat3.normalFromMat4(tMVn2,tMV2);
        mat4.multiply(tMVP2,tProjection,tMV2);

        // Clear screen, prepare for rendering
        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        gl.enable(gl.DEPTH_TEST);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        // Set up uniforms & attributes
        gl.uniformMatrix4fv(shaderProgram.MVmatrix,false,tMV);
        gl.uniformMatrix3fv(shaderProgram.MVNormalmatrix,false,tMVn);
        gl.uniformMatrix4fv(shaderProgram.MVPmatrix,false,tMVP);

        gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBuffer);
        gl.vertexAttribPointer(shaderProgram.PositionAttribute, trianglePosBuffer.itemSize,
          gl.FLOAT, false, 0, 0);
        gl.bindBuffer(gl.ARRAY_BUFFER, triangleNormalBuffer);
        gl.vertexAttribPointer(shaderProgram.NormalAttribute, triangleNormalBuffer.itemSize,
          gl.FLOAT, false, 0, 0);
        gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
        gl.vertexAttribPointer(shaderProgram.ColorAttribute, colorBuffer.itemSize,
          gl.FLOAT,false, 0, 0);
        gl.bindBuffer(gl.ARRAY_BUFFER, textureBuffer);
        gl.vertexAttribPointer(shaderProgram.texcoordAttribute, textureBuffer.itemSize,
          gl.FLOAT, false, 0, 0);

        // Bind texture
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, texture1);
        gl.activeTexture(gl.TEXTURE1);
        gl.bindTexture(gl.TEXTURE_2D, texture2);

        // Do the drawing
        gl.drawElements(gl.TRIANGLES, triangleIndices.length, gl.UNSIGNED_BYTE, 0);

        //Second Object

        gl.uniformMatrix4fv(shaderProgram.MVmatrix,false,tMV2);
        gl.uniformMatrix3fv(shaderProgram.MVNormalmatrix,false,tMVn2);
        gl.uniformMatrix4fv(shaderProgram.MVPmatrix,false,tMVP2);

        gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBuffer2);
        gl.vertexAttribPointer(shaderProgram.PositionAttribute, trianglePosBuffer2.itemSize,
          gl.FLOAT, false, 0, 0);
        gl.bindBuffer(gl.ARRAY_BUFFER, triangleNormalBuffer2);
        gl.vertexAttribPointer(shaderProgram.NormalAttribute, triangleNormalBuffer2.itemSize,
          gl.FLOAT, false, 0, 0);
        gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer2);
        gl.vertexAttribPointer(shaderProgram.ColorAttribute, colorBuffer2.itemSize,
          gl.FLOAT,false, 0, 0);
        gl.bindBuffer(gl.ARRAY_BUFFER, textureBuffer2);
        gl.vertexAttribPointer(shaderProgram.texcoordAttribute, textureBuffer2.itemSize,
          gl.FLOAT, false, 0, 0);
    }

    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, texture1);
    gl.activeTexture(gl.TEXTURE1);
    gl.bindTexture(gl.TEXTURE_2D, texture2);

    gl.drawElements(gl.TRIANGLES, triangleIndices2.length, gl.UNSIGNED_BYTE, 0);

    slider1.addEventListener("input",draw);
    slider2.addEventListener("input",draw);
    initTextureThenDraw();
}

window.onload = start;

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

I tried adding new buffers for the new object, binding and compiling but nothing is working. I also am trying to wrap the texture around multiple faces of the cubes instead of just having each face have its own image but I am not sure on how to do that as well.

Body:
I am trying to draw two different cubes in jsbin using WebGL. There is only one cube showing even though I have two different sets of points for normals, vertices and etc. I also set up additional buffers for the second object but its not letting me draw a second object. I am not entirely sure what I am doing wrong but here is my current code. I would appreciaite it if someone could explain whats wrong and how to fix it so I dont make the same mistake again.

<!DOCTYPE html>

<meta name="robots" content="noindex">

    <title>WebGL cube drawn with indexed vertex list</title>

    <canvas id="mycanvas" width="500" height="500"></canvas>

    <input id="slider1" type="range" min="-100" max="100" />
    <input id="slider2" type="range" min="-100" max="100" />

I tried adding new buffers for the new object, binding and compiling but nothing is working. I also am trying to wrap the texture around multiple faces of the cubes instead of just having each face have its own image but I am not sure on how to do that as well.


问:
Update column sequentially in Snowflake on historic data
I have table t1 which includes date column let say t1_date and a numeric column which is set to zero for all historic dates

Another table t2 includes a 2 dates column start_date and end_date

the sample data in t1 can be represented as :

t1_date
mo_sequqnce

2019-01-01
0

2019-01-02
0

2019-01-03
0

sample data in t2 can be represented as :

start_date
start_date

2019-01-01
2019-01-11

2019-02-01
2019-02-11

2019-03-01
2019-03-11

I have to sequentially increment mo_sequence column as per below query :

```<code>select t1.t1_date,
    t2.start_date,
    t2.end_date,t1.mo_sequence + ROW_NUMBER() OVER(ORDER BY SEQ8())
    from t1
   inner join t1 on t2.start_date = t1.t1_date
   where t1.t1_date = t2.start_date  and t1.t1_date between
   t2.start_date and t2.end_date
</code>```

t1_date
mo_sequnece

2019-01-01
1

2019-02-01
2

2019-03-01
3

But when I am updating it, I am not getting it sequentially.

```<code>update t1 set t1.mo_sequence = t3.sequen from
(select t1.t1_date,
    t2.start_date,
    t2.end_date,t1.mo_sequence + ROW_NUMBER() OVER(ORDER BY SEQ8())  as sequen
    from t1
   inner join t2  on t2.start_date = t1.t1_date
   where t1.t1_date = t2.start_date  and t1.t1_date between t2.start_date and
  t2.end_date) t3
</code>```

Body:
I have table t1 which includes date column let say t1_date and a numeric column which is set to zero for all historic dates

Another table t2 includes a 2 dates column start_date and end_date

the sample data in t1 can be represented as :

t1_date
mo_sequqnce

2019-01-01
0

2019-01-02
0

2019-01-03
0

sample data in t2 can be represented as :

start_date
start_date

2019-01-01
2019-01-11

2019-02-01
2019-02-11

2019-03-01
2019-03-11

I have to sequentially increment mo_sequence column as per below query :

select t1.t1_date,
    t2.start_date,
    t2.end_date,t1.mo_sequence + ROW_NUMBER() OVER(ORDER BY SEQ8())
    from t1
   inner join t1 on t2.start_date = t1.t1_date
   where t1.t1_date = t2.start_date  and t1.t1_date between
   t2.start_date and t2.end_date

t1_date
mo_sequnece

2019-01-01
1

2019-02-01
2

2019-03-01
3

But when I am updating it, I am not getting it sequentially.

update t1 set t1.mo_sequence = t3.sequen from
(select t1.t1_date,
    t2.start_date,
    t2.end_date,t1.mo_sequence + ROW_NUMBER() OVER(ORDER BY SEQ8())  as sequen
    from t1
   inner join t2  on t2.start_date = t1.t1_date
   where t1.t1_date = t2.start_date  and t1.t1_date between t2.start_date and
  t2.end_date) t3


问:
How to change sandbox attribute using Javascript
I don't know where I am going wrong I tried to add a value in sandbox attribute using javascript but it's not working as expected.

I was trying to add a value in sandbox of an iframe using javascript but it didn't work as expected
Here's the code

```<code><!DOCTYPE html>
<html>
<body onload="hello()">

<h1>The iframe sandbox attribute</h1>

<iframe id='ikea' src="demo_iframe_sandbox_form.htm" sandbox="">
  <p>Your browser does not support iframes.</p>
</iframe>

<p>The "Submit" button will submit the form in the inline frame.</p>
<p>Since the sandbox attribute is set to an empty string (""), the submission of the form in the inline frame will be blocked.</p>
<p>Add "allow-forms" to the sandbox attribute, to allow form submission.</p>

</body>
<script>
function hello(){
const iframes = document.getElementsByTagName('iframe');

for (var i = 0; i < iframes.length; i++) {
    iframes[i].setAttribute('sandbox', 'allow-forms');
}
}
</script>
</html>

</code>```

Body:
I don't know where I am going wrong I tried to add a value in sandbox attribute using javascript but it's not working as expected.

I was trying to add a value in sandbox of an iframe using javascript but it didn't work as expected
Here's the code

<!DOCTYPE html>

The iframe sandbox attribute

Your browser does not support iframes.

The "Submit" button will submit the form in the inline frame.

Since the sandbox attribute is set to an empty string (""), the submission of the form in the inline frame will be blocked.

Add "allow-forms" to the sandbox attribute, to allow form submission.