问:
How do I connect my database to local SQL Server Express using nose js
I am using Express framework and trying to connect to my SQL Server Express database locally. I am getting error - connection failure. I need help with that, if you'd please.

Steps completed so far..

npm install mssql

var sql = require("mssql");

```<code>// config for your database
var config = {
    user: 'ImacamUser',
    password: '*****',
    server: 'localhost',
    database: 'InvoicingData'
};
</code>```

```<code> sql.connect(config, (err) => {
     if (err) console.log(err);

     // create Request object
     var request = new sql.Request();

     // query to the database and get the records
     request.query('select * from Customers', function (err, recordset) {
         if (err) console.log(err)
         // send records as a response
         res.send(recordset);
     });
 });
</code>```

The error I get from this code is:

ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)

at C:\Projects\RCN\Invoicing\node_modules\mssql\lib\tedious\connection-pool.js:70:17

at Connection.onConnect (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1012:9)

at Object.onceWrapper (node:events:510:26)

at Connection.emit (node:events:390:28)

at Connection.emit (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1040:18)

at Connection.socketError (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1395:12)

at C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1176:14

at processTicksAndRejections (node:internal/process/task_queues:78:11) {

code: 'ESOCKET',

originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)

at Connection.socketError (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1395:28)

at C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1176:14

at processTicksAndRejections (node:internal/process/task_queues:78:11) {

code: 'ESOCKET',

isTransient: undefined

}

Any help would be appreciated.

Body:
I am using Express framework and trying to connect to my SQL Server Express database locally. I am getting error - connection failure. I need help with that, if you'd please.

Steps completed so far..

npm install mssql

var sql = require("mssql");

// config for your database
var config = {
    user: 'ImacamUser',
    password: '*****',
    server: 'localhost',
    database: 'InvoicingData'
};

 sql.connect(config, (err) => {
     if (err) console.log(err);

     // create Request object
     var request = new sql.Request();

     // query to the database and get the records
     request.query('select * from Customers', function (err, recordset) {
         if (err) console.log(err)
         // send records as a response
         res.send(recordset);
     });
 });

The error I get from this code is:

ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)

at C:\Projects\RCN\Invoicing\node_modules\mssql\lib\tedious\connection-pool.js:70:17

at Connection.onConnect (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1012:9)

at Object.onceWrapper (node:events:510:26)

at Connection.emit (node:events:390:28)

at Connection.emit (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1040:18)

at Connection.socketError (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1395:12)

at C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1176:14

at processTicksAndRejections (node:internal/process/task_queues:78:11) {

code: 'ESOCKET',

originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)

at Connection.socketError (C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1395:28)

at C:\Projects\RCN\Invoicing\node_modules\tedious\lib\connection.js:1176:14

at processTicksAndRejections (node:internal/process/task_queues:78:11) {

code: 'ESOCKET',

isTransient: undefined

}

Any help would be appreciated.


来源: stackexchange

问:
Android: Send a Real Time Event from Activity To Fragment
I know that when I want to send a real time event from fragment to activity I use setFragmentResult() and it works fine, now I want to do the opposite.
I want to pass an event from the parent activity to the fragment and do some code based on that event. How do I do that?

ContentLicense: CC BY-SA 4.0


问:
stack ensemble model versus stack generalization ensemble model
Is there any difference between stack ensemble model and stack generalization ensemble model? I have read different resources and It seems they should be the same. However, when I summarize their algorithms, they do not seem equal.

Here is what I summarized from stack ensemble procedure.
The test data will not contribute to model training at all.

In contrast, when I summarize stack generalization algorithm, there is no test data. The cross-validation (CV) data (this time it is fold 1 to 10) and the main data will contribute to level 0 models, separately. We build the meta model (level 1 model) based on the predictions from CV data.

Using the built level 1 model, we calculate the main data predictions by feeding the level 0 predictions as the new data to level 1 model. The stack generalization algorithm is based on https://doi.org/10.1098/rsif.2017.0520 paper.

RF = random forest, GB: gradient boosting


问:
React beautiful DND with typescript react-beautiful-dndUnable to find draggable with id: 1
I am trying to make my list of stuff draggable, because it will be used to reorder a set of items retrieved from an API. All these items will have a prop named number, and with the drag and drop, I should change the order and the number in the visualization.

I followed along with some tutorials, the documentation, and many StackOverflow questions, but I have not been able to fix the problem. Each time I try to grab an element, in the console appears a warning message with the following content:

```<code>react_devtools_backend.js:4012
react-beautiful-dndUnable to find draggable with id: 1
This is a development-only message. It will be removed in production builds.
</code>```

Here is the code I am working on:

Categories.tsx file with all the logic:

```<code>// Global imports
import {DragDropContext,Droppable, DropResult} from "react-beautiful-dnd";

// Local imports
// Context
import { menuContext } from "../menu";
// Components
import CategoryItem from "./cateogory";
// Types
import Category from "../../types/category";

function Categories(){
    const {categories, setCategories} = useContext(menuContext);
    /*functions and logic*/
    const onDragEnd = (result:DropResult) => {
        const {destination, source} = result;
        if (!destination) return;

        const items = Array.from(categories);
        const [newOrder] = items.splice(source.index, 1);
        items.splice(destination.index, 0, newOrder);

        setCategories(items);
    }

    return (
        <div className="greyBox">
            <header className="header_menu">
                <p>All your categories</p>
                <div className="searchContainer">
                    <AiOutlineSearch className="searchIcon" />
                    <input type={"text"} placeholder={"Search"} className="searchBar" value={search}
                        onChange={(e) => handleModification(e)} />
                </div>
            </header>

            <DragDropContext onDragEnd={onDragEnd}>
                <Droppable droppableId="categories">
                    {(provided) =>
                        <div {...provided.droppableProps}
                            ref={provided.innerRef}
                            className="categoriesContainer" >

                        {filteredCategories.map((category: Category, idx: number) => {
                            return (
                                <CategoryItem  key={category.id} idx={idx} category={category}/>
                                )
                            })}

                    </div>}
                </Droppable>
            </DragDropContext>
            <button onClick={(e) => confirmChanges(e)} className="submitBTN bottomButton">Confirm changes</button>
        </div>
    )
}

export default Categories;
</code>```

Category.tsx File into I have the single Item:

```<code>// Global imports
import React, { useContext, useState } from "react";
import { Draggable } from "react-beautiful-dnd";

// Local imports
// Context
import { menuContext } from "../menu";
// Types
import Category from "../../types/category";

function CategoryItem(props:{category:Category, idx:number}) {
    const {categories, setCategories} = useContext(menuContext);
    const {selectedCategory, setSelectedCategory} = useContext(menuContext);

    /*Functions and various small things*/

    let category = categories.find((category:Category) => category.id === props.category.id);

    return (
        <Draggable key={props.category.id} draggableId={props.category.id.toString()} index={props.idx}>
            {(provided, snapshot) => (
                <div className={selectedCategory === category.id ? "category activeCategory":"category"}
                onClick={() => handleCategoryClick()}
                style={{backgroundColor: category.isActive ? "" : "#FF7B7B"}}
                ref={provided.innerRef}
                {...provided.draggableProps}
                {...provided.dragHandleProps}
                >

                    <div className="alwaysActiveCategory" style={{alignItems: props.category.id === selectedCategory ? "center" : "normal"}}>
                        <MdOutlineDragIndicator className="dragIcon" />
                        <p style={{display: props.category.id === selectedCategory ? "none" : "block" }}>{category.name}</p>
                    </div>

                    <aside style={{display: selectedCategory === category.id ? "flex": "none"}}>

                        <form className="modifyCategory" onClick={(e) => e.stopPropagation()} onSubmit={e => updateCategory(e)}>
                            <label htmlFor="categoryName">Category Name</label>
                            <p id="categoryProblem3">The name must be given</p>
                            <input value={name} onChange={(e) => changeName(e)} type="text" name="categoryName" id="categoryName" />
                            <label htmlFor="categoryDescription">Category Description</label>
                            <p id="categoryProblem4">The description must be given</p>
                            <textarea value={description} onChange={(e) => changeDescription(e)} name="categoryDescription" id="categoryDescription"
                                    style={{maxWidth: "85%"}} />
                            <button>Update Category</button>
                            <div className="manageCategory">
                                <button onClick={(e) => hideCategory(e) }> <BiHide className="hideIcon"
                                        style={{backgroundColor: categories.find((category: Category) => category.id === props.category.id).isActive ? "#FF7B7B" : "#76CB8E"}} />
                                    {category.isActive ? "Hide Category" : "Show Category"}
                                </button>
                                <button onClick={(e) => deleteCategory(e)}> <BsTrash className="deleteIcon" /> Delete Category</button>
                            </div>
                        </form>

                    </aside>
                </div>
            )}
        </Draggable>
    )
}

export default CategoryItem;
</code>```

They are pretty long, I tried to take away everything useless.

I don't know where the problem is in this script. It seems all fine to me, but there are some problems otherwise it wouldn't broke each time. If someone knows where my mistakes are, please tell me. Thank you a lot

Body:
I am trying to make my list of stuff draggable, because it will be used to reorder a set of items retrieved from an API. All these items will have a prop named number, and with the drag and drop, I should change the order and the number in the visualization.

I followed along with some tutorials, the documentation, and many StackOverflow questions, but I have not been able to fix the problem. Each time I try to grab an element, in the console appears a warning message with the following content:

react_devtools_backend.js:4012
react-beautiful-dndUnable to find draggable with id: 1
This is a development-only message. It will be removed in production builds.

Here is the code I am working on:

Categories.tsx file with all the logic:

// Global imports
import {DragDropContext,Droppable, DropResult} from "react-beautiful-dnd";

// Local imports
// Context
import { menuContext } from "../menu";
// Components
import CategoryItem from "./cateogory";
// Types
import Category from "../../types/category";

function Categories(){
    const {categories, setCategories} = useContext(menuContext);
    /*functions and logic*/
    const onDragEnd = (result:DropResult) => {
        const {destination, source} = result;
        if (!destination) return;

        const items = Array.from(categories);
        const [newOrder] = items.splice(source.index, 1);
        items.splice(destination.index, 0, newOrder);

        setCategories(items);
    }

    return (

All your categories

                    <AiOutlineSearch className="searchIcon" />
                    <input type={"text"} placeholder={"Search"} className="searchBar" value={search}
                        onChange={(e) => handleModification(e)} />

            <DragDropContext onDragEnd={onDragEnd}>
                <Droppable droppableId="categories">
                    {(provided) =>

                        {filteredCategories.map((category: Category, idx: number) => {
                            return (
                                <CategoryItem  key={category.id} idx={idx} category={category}/>
                                )
                            })}

}
                </Droppable>
            </DragDropContext>
            <button onClick={(e) => confirmChanges(e)} className="submitBTN bottomButton">Confirm changes</button>

    )
}

export default Categories;

Category.tsx File into I have the single Item:

// Global imports
import React, { useContext, useState } from "react";
import { Draggable } from "react-beautiful-dnd";

// Local imports
// Context
import { menuContext } from "../menu";
// Types
import Category from "../../types/category";

function CategoryItem(props:{category:Category, idx:number}) {
    const {categories, setCategories} = useContext(menuContext);
    const {selectedCategory, setSelectedCategory} = useContext(menuContext);

    /*Functions and various small things*/

    let category = categories.find((category:Category) => category.id === props.category.id);

    return (
        <Draggable key={props.category.id} draggableId={props.category.id.toString()} index={props.idx}>
            {(provided, snapshot) => (

 handleCategoryClick()}
                style={{backgroundColor: category.isActive ? "" : "#FF7B7B"}}
                ref={provided.innerRef}
                {...provided.draggableProps}
                {...provided.dragHandleProps}
                >

                        <MdOutlineDragIndicator className="dragIcon" />

{category.name}

                        <form className="modifyCategory" onClick={(e) => e.stopPropagation()} onSubmit={e => updateCategory(e)}>
                            Category Name

The name must be given

                            <input value={name} onChange={(e) => changeName(e)} type="text" name="categoryName" id="categoryName" />
                            Category Description

The description must be given

                            <textarea value={description} onChange={(e) => changeDescription(e)} name="categoryDescription" id="categoryDescription"
                                    style={{maxWidth: "85%"}} />
                            <button>Update Category</button>

                                <button onClick={(e) => hideCategory(e) }> <BiHide className="hideIcon"
                                        style={{backgroundColor: categories.find((category: Category) => category.id === props.category.id).isActive ? "#FF7B7B" : "#76CB8E"}} />
                                    {category.isActive ? "Hide Category" : "Show Category"}
                                </button>
                                <button onClick={(e) => deleteCategory(e)}> <BsTrash className="deleteIcon" /> Delete Category</button>

                        </form>

            )}
        </Draggable>
    )
}

export default CategoryItem;

They are pretty long, I tried to take away everything useless.

I don't know where the problem is in this script. It seems all fine to me, but there are some problems otherwise it wouldn't broke each time. If someone knows where my mistakes are, please tell me. Thank you a lot


问:
aws ses email sending limit
AWS ses in my account has production access. I have also setup automation for pausing domain/email addresses if bounce/complaint rate is high. I am looking to limit emails sending per domain. I mean any domain/email address in my account will be allowed to send only 100 emails per day. can someone please suggest me how can I do this? I have looked at various AWS docs but couldn't come up with any solution.</p>

Title: aws ses email sending limit


问:
Why the hitbox of the CheckBox so small?
Im making a multiple option checkbox with a tittle of what clicking that checkbox does, the problem is that I cant check them and after struggling I found that some checkbox have like 2 or 3 pixels in which they can be clicked.

```<code>from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.core.window import Window

Window.size = (300, 500)

navigation_helper = """

MDScreen:
    name: 'user_screen'

    MDBoxLayout:
        orientation: "vertical"
        pos_hint: {"top": 1}
        adaptive_height: True
        padding: (0, "100dp" , 0, 0)

        MDGridLayout:
            cols:2
            size_hint: (0.9,1)
            pos_hint: {"center_x":0.5, "center_y": 0.5}
            padding: (0,"200dp",0,0)
            spacing: ("-80dp","40dp")

            MDLabel:
                text: "Ejercicio Semanal"
                bold: True
                pos_hint: {"left": 1, "top": 1}
                size_hint: (None,1)
                width: "128dp"

           Widget:

            BoxLayout:
                orientation:"horizontal"
                spacing: "-90dp"
                MDLabel:
                    text: "Sedentario"
                    size_hint: (None,1)
                    width: "110dp"

                MDCheckbox:
                    id: "sedentary_cb"
                    group: "exercise_cb"
                    size: "100dp", "100dp"

            BoxLayout:
                orientation:"horizontal"
                MDLabel:
                    text: "Bajo(1-3)"
                    size_hint: (None,1)
                    width: "70dp"
                MDCheckbox:
                    id: "low_cb"
                    group: "exercise_cb"

            BoxLayout:
                orientation:"horizontal"
                spacing: "-90dp"
                MDLabel:
                    text: "Moderado (3-5)"
                    size_hint: (None,1)
                    width: "110dp"
                MDCheckbox:
                    id: "moderated_cb"
                    group: "exercise_cb"

            BoxLayout:
                orientation:"horizontal"
                MDLabel:
                    text: "Alto (6-7)"
                    size_hint: (None,1)
                    width: "70dp"
                MDCheckbox:
                    id: "high_cb"
                    group: "exercise_cb"

            BoxLayout:
                orientation:"horizontal"
                spacing: "-90dp"
                MDLabel:
                    text: "Pro (2 por día)"
                    size_hint: (None,1)
                    width: "110dp"
                MDCheckbox:
                    id: "pro_cb"
                    group: "exercise_cb"

"""

class DemoApp(MDApp):
    def build(self):
        self.theme_cls.theme_style = ("Dark")
        screen = Builder.load_string(navigation_helper)
        return screen

DemoApp().run()`

</code>```

I tried enabling all checkbox, but the found out it is something with the hitbox

Body:
Im making a multiple option checkbox with a tittle of what clicking that checkbox does, the problem is that I cant check them and after struggling I found that some checkbox have like 2 or 3 pixels in which they can be clicked.

from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.core.window import Window

Window.size = (300, 500)

navigation_helper = """

MDScreen:
    name: 'user_screen'

    MDBoxLayout:
        orientation: "vertical"
        pos_hint: {"top": 1}
        adaptive_height: True
        padding: (0, "100dp" , 0, 0)

        MDGridLayout:
            cols:2
            size_hint: (0.9,1)
            pos_hint: {"center_x":0.5, "center_y": 0.5}
            padding: (0,"200dp",0,0)
            spacing: ("-80dp","40dp")

            MDLabel:
                text: "Ejercicio Semanal"
                bold: True
                pos_hint: {"left": 1, "top": 1}
                size_hint: (None,1)
                width: "128dp"

           Widget:

            BoxLayout:
                orientation:"horizontal"
                spacing: "-90dp"
                MDLabel:
                    text: "Sedentario"
                    size_hint: (None,1)
                    width: "110dp"

                MDCheckbox:
                    id: "sedentary_cb"
                    group: "exercise_cb"
                    size: "100dp", "100dp"

            BoxLayout:
                orientation:"horizontal"
                MDLabel:
                    text: "Bajo(1-3)"
                    size_hint: (None,1)
                    width: "70dp"
                MDCheckbox:
                    id: "low_cb"
                    group: "exercise_cb"

            BoxLayout:
                orientation:"horizontal"
                spacing: "-90dp"
                MDLabel:
                    text: "Moderado (3-5)"
                    size_hint: (None,1)
                    width: "110dp"
                MDCheckbox:
                    id: "moderated_cb"
                    group: "exercise_cb"

            BoxLayout:
                orientation:"horizontal"
                MDLabel:
                    text: "Alto (6-7)"
                    size_hint: (None,1)
                    width: "70dp"
                MDCheckbox:
                    id: "high_cb"
                    group: "exercise_cb"

            BoxLayout:
                orientation:"horizontal"
                spacing: "-90dp"
                MDLabel:
                    text: "Pro (2 por día)"
                    size_hint: (None,1)
                    width: "110dp"
                MDCheckbox:
                    id: "pro_cb"
                    group: "exercise_cb"

"""

class DemoApp(MDApp):
    def build(self):
        self.theme_cls.theme_style = ("Dark")
        screen = Builder.load_string(navigation_helper)
        return screen

DemoApp().run()`

I tried enabling all checkbox, but the found out it is something with the hitbox


问:
Deterministic runs in Carla
I'd like to be able to run the exact same run, given I didn't change any parameters of the simulation, in the autonomous driving simulator Carla. Before I paste my code, my logic is that I have to set a specific seed for any Random operation to be repeatable, set a specific seed for the traffic manager, and in general to work in synchronous_mode=True so the lag in my computer won't interrupt(?). As you'll see, I log the x,y,z location of the ego vehicle, and run the simulation twice. It is similar, but not the same. What can I do to make it repeatable (not in recording mode, actual live runs)?

Additional info: Carla 0.9.14 on Ubuntu 20.04, Python 3.8.

import random
import numpy as np
import sys
import os
try:
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/carla')
except IndexError:
    pass

import carla
from agents.navigation.behavior_agent import BehaviorAgent  # pylint: disable=import-error

seed = 123
N_vehicles = 50
camera = None
telemetry = []

random.seed(seed)

try:
    # Connect the client and set up bp library and spawn points
    client = carla.Client('localhost', 2000)
    client.set_timeout(60.0)

    world = client.get_world()
    bp_lib = world.get_blueprint_library()
    spawn_points = world.get_map().get_spawn_points()

    settings = world.get_settings()
    settings.synchronous_mode = True
    settings.fixed_delta_seconds = 0.10
    world.apply_settings(settings)

    traffic_manager = client.get_trafficmanager()
    traffic_manager.set_random_device_seed(seed)
    traffic_manager.set_synchronous_mode(True)

    # Spawn ego vehicle
    vehicle_bp = bp_lib.find('vehicle.audi.a2')
    # breakpoint()
    vehicle = world.try_spawn_actor(vehicle_bp, random.choice(spawn_points))

    # Move spectator behind vehicle to motion
    spectator = world.get_spectator()
    transform = carla.Transform(vehicle.get_transform().transform(carla.Location(x=-6,z=2.5)),vehicle.get_transform().rotation)
    spectator.set_transform(transform)
    world.tick()

    # set the car's controls
    agent = BehaviorAgent(vehicle, behavior="normal")
    destination = random.choice(spawn_points).location
    agent.set_destination(destination)
    print('destination:')
    print(destination)
    print('current location:')
    print(vehicle.get_location())

    #Iterate this cell to find desired camera location
    camera_bp = bp_lib.find('sensor.camera.rgb')

    # Spawn camera
    camera_init_trans = carla.Transform(carla.Location(z=2))
    camera = world.spawn_actor(camera_bp, camera_init_trans, attach_to=vehicle)

    # Callback stores sensor data in a dictionary for use outside callback
    def camera_callback(image, data_dict):
        data_dict['image'] = np.reshape(np.copy(image.raw_data), (image.height, image.width, 4))

    # Get gamera dimensions and initialise dictionary
    image_w = camera_bp.get_attribute("image_size_x").as_int()
    image_h = camera_bp.get_attribute("image_size_y").as_int()
    camera_data = {'image': np.zeros((image_h, image_w, 4))}

    # Start camera recording
    camera.listen(lambda image: camera_callback(image, camera_data))

    # Add traffic to the simulation
    SpawnActor = carla.command.SpawnActor
    SetAutopilot = carla.command.SetAutopilot
    FutureActor = carla.command.FutureActor

    vehicles_list, batch = [], []
    for i in range(N_vehicles):
        ovehicle_bp = random.choice(bp_lib.filter('vehicle'))
        npc = world.try_spawn_actor(ovehicle_bp, random.choice(spawn_points))
        # add it if it was successful
        if(npc):
           vehicles_list.append(npc)
    print(f'only {len(vehicles_list)} cars were spawned')
    world.tick()
    # Set the all vehicles in motion using the Traffic Manager
    for idx, v in enumerate(vehicles_list):
        try:
            v.set_autopilot(True)
        except:
            pass

    # Game loop
    while True:
        world.tick()
        pose = vehicle.get_location()
        telemetry.append([pose.x, pose.y, pose.z])

        # keep following the car
        transform = carla.Transform(vehicle.get_transform().transform(carla.Location(x=-6,z=2.5)),vehicle.get_transform().rotation)
        spectator.set_transform(transform)

        if agent.done():
            print("The target has been reached, stopping the simulation")
            break

        control = agent.run_step()
        control.manual_gear_shift = False
        vehicle.apply_control(control)

finally:
    # Stop the camera when we've recorded enough data
    if(camera):
        camera.stop()
        camera.destroy()
    settings = world.get_settings()
    settings.synchronous_mode = False
    settings.fixed_delta_seconds = None
    world.apply_settings(settings)
    traffic_manager.set_synchronous_mode(True)

    if(vehicles_list):
        client.apply_batch([carla.command.DestroyActor(v) for v in vehicles_list])
    vehicle.destroy()

    np.savetxt('telemetry.txt', np.array(telemetry), delimiter=',')
```

y-axis is the error between two runs, x-axis is the time index of the run

Title: Deterministic runs in Carla

Body:
I'd like to be able to run the exact same run, given I didn't change any parameters of the simulation, in the autonomous driving simulator Carla. Before I paste my code, my logic is that I have to set a specific seed for any Random operation to be repeatable, set a specific seed for the traffic manager, and in general to work in synchronous_mode=True so the lag in my computer won't interrupt(?). As you'll see, I log the x,y,z location of the ego vehicle, and run the simulation twice. It is similar, but not the same. What can I do to make it repeatable (not in recording mode, actual live runs)?

Additional info: Carla 0.9.14 on Ubuntu 20.04, Python 3.8.

import random
import numpy as np
import sys
import os
try:
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/carla')
except IndexError:
    pass

import carla
from agents.navigation.behavior_agent import BehaviorAgent  # pylint: disable=import-error

seed = 123
N_vehicles = 50
camera = None
telemetry = []

random.seed(seed)

try:
    # Connect the client and set up bp library and spawn points
    client = carla.Client('localhost', 2000)
    client.set_timeout(60.0)

    world = client.get_world()
    bp_lib = world.get_blueprint_library()
    spawn_points = world.get_map().get_spawn_points()

    settings = world.get_settings()
    settings.synchronous_mode = True
    settings.fixed_delta_seconds = 0.10
    world.apply_settings(settings)

    traffic_manager = client.get_trafficmanager()
    traffic_manager.set_random_device_seed(seed)
    traffic_manager.set_synchronous_mode(True)

    # Spawn ego vehicle
    vehicle_bp = bp_lib.find('vehicle.audi.a2')
    # breakpoint()
    vehicle = world.try_spawn_actor(vehicle_bp, random.choice(spawn_points))

    # Move spectator behind vehicle to motion
    spectator = world.get_spectator()
    transform = carla.Transform(vehicle.get_transform().transform(carla.Location(x=-6,z=2.5)),vehicle.get_transform().rotation)
    spectator.set_transform(transform)
    world.tick()

    # set the car's controls
    agent = BehaviorAgent(vehicle, behavior="normal")
    destination = random.choice(spawn_points).location
    agent.set_destination(destination)
    print('destination:')
    print(destination)
    print('current location:')
    print(vehicle.get_location())

    #Iterate this cell to find desired camera location
    camera_bp = bp_lib.find('sensor.camera.rgb')

    # Spawn camera
    camera_init_trans = carla.Transform(carla.Location(z=2))
    camera = world.spawn_actor(camera_bp, camera_init_trans, attach_to=vehicle)

    # Callback stores sensor data in a dictionary for use outside callback
    def camera_callback(image, data_dict):
        data_dict['image'] = np.reshape(np.copy(image.raw_data), (image.height, image.width, 4))

    # Get gamera dimensions and initialise dictionary
    image_w = camera_bp.get_attribute("image_size_x").as_int()
    image_h = camera_bp.get_attribute("image_size_y").as_int()
    camera_data = {'image': np.zeros((image_h, image_w, 4))}

    # Start camera recording
    camera.listen(lambda image: camera_callback(image, camera_data))

    # Add traffic to the simulation
    SpawnActor = carla.command.SpawnActor
    SetAutopilot = carla.command.SetAutopilot
    FutureActor = carla.command.FutureActor

    vehicles_list, batch = [], []
    for i in range(N_vehicles):
        ovehicle_bp = random.choice(bp_lib.filter('vehicle'))
        npc = world.try_spawn_actor(ovehicle_bp, random.choice(spawn_points))
        # add it if it was successful
        if(npc):
           vehicles_list.append(npc)
    print(f'only {len(vehicles_list)} cars were spawned')
    world.tick()
    # Set the all vehicles in motion using the Traffic Manager
    for idx, v in enumerate(vehicles_list):
        try:
            v.set_autopilot(True)
        except:
            pass

    # Game loop
    while True:
        world.tick()
        pose = vehicle.get_location()
        telemetry.append([pose.x, pose.y, pose.z])

        # keep following the car
        transform = carla.Transform(vehicle.get_transform().transform(carla.Location(x=-6,z=2.5)),vehicle.get_transform().rotation)
        spectator.set_transform(transform)

        if agent.done():
            print("The target has been reached, stopping the simulation")
            break

        control = agent.run_step()
        control.manual_gear_shift = False
        vehicle.apply_control(control)

finally:
    # Stop the camera when we've recorded enough data
    if(camera):
        camera.stop()
        camera.destroy()
    settings = world.get_settings()
    settings.synchronous_mode = False
    settings.fixed_delta_seconds = None
    world.apply_settings(settings)
    traffic_manager.set_synchronous_mode(True)

    if(vehicles_list):
        client.apply_batch([carla.command.DestroyActor(v) for v in vehicles_list])
    vehicle.destroy()

    np.savetxt('telemetry.txt', np.array(telemetry), delimiter=',')

y-axis is the error between two runs, x-axis is the time index of the run


问:
R code for making a column indicating which other column a value comes from
I have a dataframe with a multiple values, and one column with the largest of these values. I do not know, however, which of the columns the largest value came from. I would like to be able to create a variable stating which of the columns is an exact match. This is likely best explained with an example.

VALUEONE
VALUETWO
VALUETHREE
VALUEFOUR
LARGEST

6.76
3.29
4.66
6.777
6.777

1.2
4.3
5.6
1.9
5.6

10
3.99
7.9
2.1
10

In this example the largest in the first row is 6.77 from VALUEFOUR, 5.6 from VALUETHREE in the second row and 10 from VALUEONE in the third row. I would like to be able to code to create a variable that will say this, for instance to create the dataframe below.

VALUEONE
VALUETWO
VALUETHREE
VALUEFOUR
LARGEST
WHICH_VALUE_LARGEST

6.76
3.29
4.66
6.777
6.777
VALUEFOUR

1.2
4.3
5.6
1.9
5.6
VALUETHREE

10
3.99
7.9
2.1
10
VALUEONE

I was wondering if anyone might be able to help?


问:
How can I get my table to be fixed at the center?
I am still trying to get the hang on designing such stuff so please go easy on me. I am trying to design a table but the problem is that every time a new entry (a new row) is added, the table as a whole climbs up the page and the upper parts of it are no longer visible. I will leave my codes down below. Please let me know what I can do to make the table fixed at the middle and then to see the rest of the table, I can scroll down the website or maybe scroll down the table itself to see the rest of the content instead of the whole table just flying up

```<code> <div className="container">
            <div className="myTable">
                <table>
                    <tr>
                        <th>Decision</th>
                        <th>Federation Approval</th>
                        <th>Offer From</th>
                        <th>Transfer Type</th>
                        <th>Offer For</th>
                        <th>Player Current Club</th>
                        <th>Fee Offered in Millions</th>
                        <th>Action</th>

                    </tr>
                    {data.map((offer, key) => {
                        return (
                            <tr key={key}>
                                <td>{offer.decision}</td>
                                <td>{offer.fedApproval}</td>
                                <td>{offer.buyingClub}</td>
                                <td>{offer.transferType}</td>
                                <td>{offer.player}</td>
                                <td>{offer.sellingClub}</td>
                                <td>{offer.fee}</td>

                                <button className="approve" disabled={offer.fedApproval != "AWAITING       APPROVAL"} onClick={(e) => { handleApprove(e, offer.fedApproval, offer.buyingClub, offer.player) }}> Approve Offer</button>
                                <button className="disapprove" disabled={offer.fedApproval != "AWAITING APPROVAL"} onClick={(e) => { handleDisapprove(e, offer.fedApproval, offer.buyingClub, offer.player) }}> Disapprove Offer </button>
                                <Link to="/clubffpstatus" style={{ textDecoration: "none" }}>
                                 <button className="checkStatus"> Check Club FFP Status</button>
                                </Link>

                            </tr>
                        )
                    })}
                </table>
            </div>
            </div>
</code>```

scss file:

```<code>.container {
        align-items: center;
        justify-items: center;
    .myTable {
        width: 100%;
        height: 50vh;
        display: flex;
        justify-content: center;
        align-items: center;
        justify-items: center;
        //overflow-y: scroll;
        margin: 0 auto;
        margin-top: 0 auto;

        button {
          display: flex;
          flex-direction: row;
          margin: 5px;
          cursor: pointer;
        }

        .approve {
          color: green;
          background-color: white;
          border-color: green;
          border-radius: 8px;
        }

        .approve:hover{
          transform:scale(1.1);
        }

        .approve:disabled{
          color: lightgray;
          border-color: lightgray;
          transform: none;
          cursor: default;
        }

        .disapprove {
          color: red;
          background-color: white;
          border-color: red;
          border-radius: 8px;
        }

        .disapprove:hover{
          transform:scale(1.1);
        }

        .disapprove:disabled{
          color: lightgray;
          border-color: lightgray;
          transform: none;
          cursor: default;
        }

        table {
          border: 2px solid blue;
          width: 800px;
          height: 200px;
          align-items: center;
          justify-items: center;
        }

        th {
          border-bottom: 1px solid black;
          gap: 0px;
        }

        td {
          text-align: center;
          border-bottom: 1px solid black;
        }
      }

    }

</code>```

I tried to make a table in which I can see all the information and expected to be able to scroll down the website to see other entries when they are not visible but that did not happen the table would go up the page and eventually the upper entries no longer appear on the screen and I cannot scroll anywhere to see them

Body:
I am still trying to get the hang on designing such stuff so please go easy on me. I am trying to design a table but the problem is that every time a new entry (a new row) is added, the table as a whole climbs up the page and the upper parts of it are no longer visible. I will leave my codes down below. Please let me know what I can do to make the table fixed at the middle and then to see the rest of the table, I can scroll down the website or maybe scroll down the table itself to see the rest of the content instead of the whole table just flying up

                        Decision
                        Federation Approval
                        Offer From
                        Transfer Type
                        Offer For
                        Player Current Club
                        Fee Offered in Millions
                        Action

                    {data.map((offer, key) => {
                        return (

                                {offer.decision}
                                {offer.fedApproval}
                                {offer.buyingClub}
                                {offer.transferType}
                                {offer.player}
                                {offer.sellingClub}
                                {offer.fee}

                                <button className="approve" disabled={offer.fedApproval != "AWAITING       APPROVAL"} onClick={(e) => { handleApprove(e, offer.fedApproval, offer.buyingClub, offer.player) }}> Approve Offer</button>
                                <button className="disapprove" disabled={offer.fedApproval != "AWAITING APPROVAL"} onClick={(e) => { handleDisapprove(e, offer.fedApproval, offer.buyingClub, offer.player) }}> Disapprove Offer </button>
                                <Link to="/clubffpstatus" style={{ textDecoration: "none" }}>
                                 <button className="checkStatus"> Check Club FFP Status</button>
                                </Link>

                        )
                    })}

scss file:

.container {
        align-items: center;
        justify-items: center;
    .myTable {
        width: 100%;
        height: 50vh;
        display: flex;
        justify-content: center;
        align-items: center;
        justify-items: center;
        //overflow-y: scroll;
        margin: 0 auto;
        margin-top: 0 auto;

        button {
          display: flex;
          flex-direction: row;
          margin: 5px;
          cursor: pointer;
        }

        .approve {
          color: green;
          background-color: white;
          border-color: green;
          border-radius: 8px;
        }

        .approve:hover{
          transform:scale(1.1);
        }

        .approve:disabled{
          color: lightgray;
          border-color: lightgray;
          transform: none;
          cursor: default;
        }

        .disapprove {
          color: red;
          background-color: white;
          border-color: red;
          border-radius: 8px;
        }

        .disapprove:hover{
          transform:scale(1.1);
        }

        .disapprove:disabled{
          color: lightgray;
          border-color: lightgray;
          transform: none;
          cursor: default;
        }

        table {
          border: 2px solid blue;
          width: 800px;
          height: 200px;
          align-items: center;
          justify-items: center;
        }

        th {
          border-bottom: 1px solid black;
          gap: 0px;
        }

        td {
          text-align: center;
          border-bottom: 1px solid black;
        }
      }

    }

I tried to make a table in which I can see all the information and expected to be able to scroll down the website to see other entries when they are not visible but that did not happen the table would go up the page and eventually the upper entries no longer appear on the screen and I cannot scroll anywhere to see them


问:
Error Adding Excel Hyperlink Dynamically to Shapes
The below macro ran successfully until I tried adding hyperlinks to it.
I can't seem to define the Anchor correctly.

Any suggestions are appreciated.

```<code>For shapesloop = 1 To 3
Dim shapes As Shape
Set shapes = SilSelection.shapes.AddShape(msoShapeRoundedRectangle, x, y, 370, 30)

    shapes.Name = "S1"

    Set HLShape = SilSelection.shapes("S1")

    SilSelection.Hyperlinks.Add Anchor:=HLShape, Address:="", SubAddress:=namesheet.Cells(names, 8), ScreenTip:="Please Click"

</code>```

Here is image of cells i'm using to reference the sheet names:

Image of one of the sheets I want button linked to (A1 could be used as cell to link to if needed)

Body:
The below macro ran successfully until I tried adding hyperlinks to it.
I can't seem to define the Anchor correctly.

Any suggestions are appreciated.

For shapesloop = 1 To 3
Dim shapes As Shape
Set shapes = SilSelection.shapes.AddShape(msoShapeRoundedRectangle, x, y, 370, 30)

    shapes.Name = "S1"

    Set HLShape = SilSelection.shapes("S1")

    SilSelection.Hyperlinks.Add Anchor:=HLShape, Address:="", SubAddress:=namesheet.Cells(names, 8), ScreenTip:="Please Click"

Here is image of cells i'm using to reference the sheet names:

Image of one of the sheets I want button linked to (A1 could be used as cell to link to if needed)


问:
micropython temp sensor gives CRC error when in larger code file
I have a temp sensor taht i need to use for a school project it works perfectly when i dont put it together with the rest of the code but when I do it gives a CRC error after giving me the temp 3 or 4 times.

```<code>import onewire
import time, ds18x20
from machine import Pin

ow = onewire.OneWire(Pin(26))
ds = ds18x20.DS18X20(ow)
roms = ds.scan()

print("roms=",roms)  # roms= [bytearray(b'(\x19\x1e\xbf\x0b\x00\x00\xc7'), bytearray(b'(\xd2*y\x97\x13\x03\xc3')]

# https://web.alfredstate.edu/faculty/weimandn/miscellaneous/ascii/ascii_index.html

last_reading_time = 0

while(1):

    ds.convert_temp()

    for rom in roms:

        temp=ds.read_temp(rom)
        current_time = time.time()  # get the current time
        if current_time - last_reading_time >= 10:
            last_reading_time = current_time
            print(temp)
</code>```

this works without a problem.

```<code>from wifi import ssid, password, mqtt_server, client_id
from machine import Pin, I2C
from time import sleep, ticks_ms
from sh1106 import SH1106_I2C
import utime
import machine
import network
from umqttsimple import MQTTClient
from var import *
import time
import urequests
import json
from Pins import *
import onewire
import time, ds18x20

buzzer.freq(500)
buzzer.duty(0)

ow = onewire.OneWire(Pin(26))
ds = ds18x20.DS18X20(ow)
roms = ds.scan()

print("roms=",roms)

topic_sub = b'CVOFOCUS/RP3/*******'
topic_pub = b'CVOFOCUS/RP3/*******'
topic_pub2 = b'CVOFOCUS/RP3/******'

station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

print('Connection successful')
print(station.ifconfig())

WIDTH  = 128
HEIGHT = 64

i2c = I2C(scl=Pin(22), sda=Pin(27)) #Init i2c
oled= SH1106_I2C(128, 64, i2c)

# CONSTANTS
KEY_UP   = const(0)
KEY_DOWN = const(1)

gewenste_code = "7ADC"
ingegeven_code = ""

keys = [['1', '2', '3', 'A'], ['4', '5', '6', 'B'], ['7', '8', '9', 'C'], ['*', '0', '#', 'D']]

# Pin names for Pico
cols = [19,16,15,23]
rows = [2,4,5,18]

# set pins for rows as outputs
row_pins = [Pin(pin_name, mode=Pin.OUT) for pin_name in rows]

# set pins for cols as inputs
col_pins = [Pin(pin_name, mode=Pin.IN, pull=Pin.PULL_DOWN) for pin_name in cols]

def init():
    for row in range(0,4):
        for col in range(0,4):
            row_pins[row].value(0)

def scan(row, col):
    """ scan the keypad """

    # set the current column to high
    row_pins[row].value(1)
    key = None

    # check for keypressed events
    if col_pins[col].value() == KEY_DOWN:
        key = KEY_DOWN
    if col_pins[col].value() == KEY_UP:
        key = KEY_UP
    row_pins[row].value(0)

    # return the key state
    return key

print("starting")

# set all the columns to low
init()

def oled_text(text):
    oled.fill(0)
    oled.text(text, 10, 10)
    oled.show()

def trigger_alarm(trig_by = ""):
    global is_alarm_on, is_alarm_trigered, alarm_timer
    if is_alarm_on and not is_alarm_trigered:
        print("Alarm trigered by", trig_by)
        is_alarm_trigered = 1
        alarm_timer = ticks_ms()

def subscribe_callback(topic, msg):  #b'cvofocus/wimverlinden/msg_for_esp'
      print((topic, msg))
      global is_alarm_on
      if topic == b'CVOFOCUS/RP3/Matteo_Alarm':
          if msg== b'Alarm aan':
                if is_alarm_on == 0:
                    is_alarm_on = not is_alarm_on
                print("alarm_on =" , str(is_alarm_on))
                msg = b'Alarm aan'
                client.publish(topic_pub, msg)
                oled.text('van afstand', 10, 30)
                oled.text('bediend', 10, 38)
                oled.show()
          elif msg ==b'Alarm off':
                    print("correct")
                    if is_alarm_on == 1:
                            is_alarm_on = not is_alarm_on
                    print("alarm_on =" , str(is_alarm_on))
                    if is_alarm_on == 0:
                        # alles uitschakelen
                        is_alarm_trigered = 0
                        led_red.value(0)
                        buzzer.duty(0)
                    oled.text('van afstand', 10, 30)
                    oled.text('bediend', 10, 38)
                    oled.show()
                    msg = b'Alarm uit'
                    client.publish(topic_pub, msg)
                    led_green.value(1)
                    sleep(0.2)
                    led_green.value(0)
                    sleep(0.2)
                    led_green.value(1)
                    sleep(0.2)
                    led_green.value(0)
                    ingegeven_code = ""

def connect_and_subscribe():
  global client_id, mqtt_server, topic_sub
  client = MQTTClient(client_id, mqtt_server)
  client.set_callback(subscribe_callback)
  client.connect()
  client.subscribe(topic_sub)
  print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
  return client

def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  time.sleep(10)
  machine.reset()

try:
    client = connect_and_subscribe()
except OSError as e:
    restart_and_reconnect()
###############################

###############################
while True:

    ds.convert_temp()

    for rom in roms:

        temp= ds.read_temp(rom)
        current_time = time.time()  # get the current time
        if current_time - last_reading_time >= 60:
            last_reading_time = current_time
            msg = b"%d" % temp
            client.publish(topic_pub2, msg)
            print(f"temp send ({temp})")

    try:
        client.check_msg() # needed in loop?
        status_button2 = button2.value()
        if status_button_before2 != status_button2:
            status_button_before2 = status_button2
            if status_button2 == 0:
                msg = b'PANIC PANIC PANIC PANIC!'
                client.publish(topic_pub, msg)
                response = urequests.post(api_endpoint, data=json.dumps({
                    "token": app_token,
                    "user": user_key,
                    "message": message,
                    "sound": sound,
                    "priority": priority,
                    "retry": retry,
                    "expire": expire,
                }), headers={"Content-type": "application/json"})
                print(response.text)

    except OSError as e:
        restart_and_reconnect()

    status_button = button.value()
    if status_button_before != status_button:
        status_button_before = status_button
        if status_button == 0:
            if is_alarm_on == 0:
                is_alarm_on = not is_alarm_on
            print("alarm_on =" , str(is_alarm_on))
            msg = b'Alarm aan'
            client.publish(topic_pub, msg)
        sleep(0.05)

    if is_alarm_on:
        if ticks_ms() - timestamp_led > 200:
            timestamp_led = ticks_ms()
            is_led_on = not is_led_on
            #print("is_led_on", is_led_on)

    pir_status = pir.value()
    if pir_status != status_pir_before:
        status_pir_before = pir_status
        print("PIR=" , pir_status)
        if pir_status == 1:
            trigger_alarm("PIR")

    if is_alarm_trigered:

        if ticks_ms() - timestamp_buzzer > 500:
            timestamp_buzzer = ticks_ms()
            is_buzzer_on = not is_buzzer_on
            #print("is_buzzer_on", is_buzzer_on)
            buzzer.duty(512 * is_buzzer_on)

    if is_alarm_on == True:
        led_red.value(1)

    oled.fill(0)
    for row in range(4):
        for col in range(4):
            key = scan(row, col)
            if key == KEY_DOWN:
                oled.text("Key Pressed: ",10,0)
                print("Key Pressed", keys[row][col])
                oled.text(keys[row][col], 55, 30)
                oled.show()
                ##MATTEO
                ingegeven_code += keys[row][col]
                print(ingegeven_code)
                if len(ingegeven_code) > 3:
                    oled.fill(0)
                    oled.show()
                    if ingegeven_code == gewenste_code:
                        oled.text("correct",35,0)
                        print("correct")
                        if is_alarm_on == 1:
                            is_alarm_on = not is_alarm_on
                        print("alarm_on =" , str(is_alarm_on))
                        if is_alarm_on == 0:
                            # alles uitschakelen
                            is_alarm_trigered = 0
                            led_red.value(0)
                            buzzer.duty(0)
                        oled.text(ingegeven_code, 45, 30)
                        oled.show()
                        led_green.value(1)
                        sleep(0.2)
                        led_green.value(0)
                        sleep(0.2)
                        led_green.value(1)
                        sleep(0.2)
                        led_green.value(0)
                        msg = b'Alarm uit'
                        client.publish(topic_pub, msg)
                        oled.fill(0)
                        oled.show()
                        ingegeven_code = ""
                    else:
                        oled.text("incorrect", 29,0)
                        print("incorrect")
                        oled.text(ingegeven_code, 45, 30)
                        oled.show()
                        oled.show()
                        ingegeven_code = ""
                sleep(0.3)
                last_key_press = keys[row][col]
</code>```

And here it doesn't.

(I know some of the code might be mesy but the stuf about the temp sensor is on line 20-24 and 165-175)

```<code>Traceback (most recent call last):
  File "main.py", line 169, in <module>
  File "ds18x20.py", line 40, in read_temp
  File "ds18x20.py", line 30, in read_scratch
Exception: CRC error
</code>```

and this is the error i get.

i have tried connecting it to a different ESP32 and it gives the same.
I'm mostly confused beacouse it does work apart but not toggeter with the rest of my code.

Body:
I have a temp sensor taht i need to use for a school project it works perfectly when i dont put it together with the rest of the code but when I do it gives a CRC error after giving me the temp 3 or 4 times.

import onewire
import time, ds18x20
from machine import Pin

ow = onewire.OneWire(Pin(26))
ds = ds18x20.DS18X20(ow)
roms = ds.scan()

print("roms=",roms)  # roms= [bytearray(b'(\x19\x1e\xbf\x0b\x00\x00\xc7'), bytearray(b'(\xd2*y\x97\x13\x03\xc3')]

# https://web.alfredstate.edu/faculty/weimandn/miscellaneous/ascii/ascii_index.html

last_reading_time = 0

while(1):

    ds.convert_temp()

    for rom in roms:

        temp=ds.read_temp(rom)
        current_time = time.time()  # get the current time
        if current_time - last_reading_time >= 10:
            last_reading_time = current_time
            print(temp)

this works without a problem.

from wifi import ssid, password, mqtt_server, client_id
from machine import Pin, I2C
from time import sleep, ticks_ms
from sh1106 import SH1106_I2C
import utime
import machine
import network
from umqttsimple import MQTTClient
from var import *
import time
import urequests
import json
from Pins import *
import onewire
import time, ds18x20

buzzer.freq(500)
buzzer.duty(0)

ow = onewire.OneWire(Pin(26))
ds = ds18x20.DS18X20(ow)
roms = ds.scan()

print("roms=",roms)

topic_sub = b'CVOFOCUS/RP3/*******'
topic_pub = b'CVOFOCUS/RP3/*******'
topic_pub2 = b'CVOFOCUS/RP3/******'

station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

print('Connection successful')
print(station.ifconfig())

WIDTH  = 128
HEIGHT = 64

i2c = I2C(scl=Pin(22), sda=Pin(27)) #Init i2c
oled= SH1106_I2C(128, 64, i2c)

# CONSTANTS
KEY_UP   = const(0)
KEY_DOWN = const(1)

gewenste_code = "7ADC"
ingegeven_code = ""

keys = [['1', '2', '3', 'A'], ['4', '5', '6', 'B'], ['7', '8', '9', 'C'], ['*', '0', '#', 'D']]

# Pin names for Pico
cols = [19,16,15,23]
rows = [2,4,5,18]

# set pins for rows as outputs
row_pins = [Pin(pin_name, mode=Pin.OUT) for pin_name in rows]

# set pins for cols as inputs
col_pins = [Pin(pin_name, mode=Pin.IN, pull=Pin.PULL_DOWN) for pin_name in cols]

def init():
    for row in range(0,4):
        for col in range(0,4):
            row_pins[row].value(0)

def scan(row, col):
    """ scan the keypad """

    # set the current column to high
    row_pins[row].value(1)
    key = None

    # check for keypressed events
    if col_pins[col].value() == KEY_DOWN:
        key = KEY_DOWN
    if col_pins[col].value() == KEY_UP:
        key = KEY_UP
    row_pins[row].value(0)

    # return the key state
    return key

print("starting")

# set all the columns to low
init()

def oled_text(text):
    oled.fill(0)
    oled.text(text, 10, 10)
    oled.show()

def trigger_alarm(trig_by = ""):
    global is_alarm_on, is_alarm_trigered, alarm_timer
    if is_alarm_on and not is_alarm_trigered:
        print("Alarm trigered by", trig_by)
        is_alarm_trigered = 1
        alarm_timer = ticks_ms()

def subscribe_callback(topic, msg):  #b'cvofocus/wimverlinden/msg_for_esp'
      print((topic, msg))
      global is_alarm_on
      if topic == b'CVOFOCUS/RP3/Matteo_Alarm':
          if msg== b'Alarm aan':
                if is_alarm_on == 0:
                    is_alarm_on = not is_alarm_on
                print("alarm_on =" , str(is_alarm_on))
                msg = b'Alarm aan'
                client.publish(topic_pub, msg)
                oled.text('van afstand', 10, 30)
                oled.text('bediend', 10, 38)
                oled.show()
          elif msg ==b'Alarm off':
                    print("correct")
                    if is_alarm_on == 1:
                            is_alarm_on = not is_alarm_on
                    print("alarm_on =" , str(is_alarm_on))
                    if is_alarm_on == 0:
                        # alles uitschakelen
                        is_alarm_trigered = 0
                        led_red.value(0)
                        buzzer.duty(0)
                    oled.text('van afstand', 10, 30)
                    oled.text('bediend', 10, 38)
                    oled.show()
                    msg = b'Alarm uit'
                    client.publish(topic_pub, msg)
                    led_green.value(1)
                    sleep(0.2)
                    led_green.value(0)
                    sleep(0.2)
                    led_green.value(1)
                    sleep(0.2)
                    led_green.value(0)
                    ingegeven_code = ""

def connect_and_subscribe():
  global client_id, mqtt_server, topic_sub
  client = MQTTClient(client_id, mqtt_server)
  client.set_callback(subscribe_callback)
  client.connect()
  client.subscribe(topic_sub)
  print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
  return client

def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  time.sleep(10)
  machine.reset()

try:
    client = connect_and_subscribe()
except OSError as e:
    restart_and_reconnect()
###############################

###############################
while True:

    ds.convert_temp()

    for rom in roms:

        temp= ds.read_temp(rom)
        current_time = time.time()  # get the current time
        if current_time - last_reading_time >= 60:
            last_reading_time = current_time
            msg = b"%d" % temp
            client.publish(topic_pub2, msg)
            print(f"temp send ({temp})")

    try:
        client.check_msg() # needed in loop?
        status_button2 = button2.value()
        if status_button_before2 != status_button2:
            status_button_before2 = status_button2
            if status_button2 == 0:
                msg = b'PANIC PANIC PANIC PANIC!'
                client.publish(topic_pub, msg)
                response = urequests.post(api_endpoint, data=json.dumps({
                    "token": app_token,
                    "user": user_key,
                    "message": message,
                    "sound": sound,
                    "priority": priority,
                    "retry": retry,
                    "expire": expire,
                }), headers={"Content-type": "application/json"})
                print(response.text)

    except OSError as e:
        restart_and_reconnect()

    status_button = button.value()
    if status_button_before != status_button:
        status_button_before = status_button
        if status_button == 0:
            if is_alarm_on == 0:
                is_alarm_on = not is_alarm_on
            print("alarm_on =" , str(is_alarm_on))
            msg = b'Alarm aan'
            client.publish(topic_pub, msg)
        sleep(0.05)

    if is_alarm_on:
        if ticks_ms() - timestamp_led > 200:
            timestamp_led = ticks_ms()
            is_led_on = not is_led_on
            #print("is_led_on", is_led_on)

    pir_status = pir.value()
    if pir_status != status_pir_before:
        status_pir_before = pir_status
        print("PIR=" , pir_status)
        if pir_status == 1:
            trigger_alarm("PIR")

    if is_alarm_trigered:

        if ticks_ms() - timestamp_buzzer > 500:
            timestamp_buzzer = ticks_ms()
            is_buzzer_on = not is_buzzer_on
            #print("is_buzzer_on", is_buzzer_on)
            buzzer.duty(512 * is_buzzer_on)

    if is_alarm_on == True:
        led_red.value(1)

    oled.fill(0)
    for row in range(4):
        for col in range(4):
            key = scan(row, col)
            if key == KEY_DOWN:
                oled.text("Key Pressed: ",10,0)
                print("Key Pressed", keys[row][col])
                oled.text(keys[row][col], 55, 30)
                oled.show()
                ##MATTEO
                ingegeven_code += keys[row][col]
                print(ingegeven_code)
                if len(ingegeven_code) > 3:
                    oled.fill(0)
                    oled.show()
                    if ingegeven_code == gewenste_code:
                        oled.text("correct",35,0)
                        print("correct")
                        if is_alarm_on == 1:
                            is_alarm_on = not is_alarm_on
                        print("alarm_on =" , str(is_alarm_on))
                        if is_alarm_on == 0:
                            # alles uitschakelen
                            is_alarm_trigered = 0
                            led_red.value(0)
                            buzzer.duty(0)
                        oled.text(ingegeven_code, 45, 30)
                        oled.show()
                        led_green.value(1)
                        sleep(0.2)
                        led_green.value(0)
                        sleep(0.2)
                        led_green.value(1)
                        sleep(0.2)
                        led_green.value(0)
                        msg = b'Alarm uit'
                        client.publish(topic_pub, msg)
                        oled.fill(0)
                        oled.show()
                        ingegeven_code = ""
                    else:
                        oled.text("incorrect", 29,0)
                        print("incorrect")
                        oled.text(ingegeven_code, 45, 30)
                        oled.show()
                        oled.show()
                        ingegeven_code = ""
                sleep(0.3)
                last_key_press = keys[row][col]

And here it doesn't.

(I know some of the code might be mesy but the stuf about the temp sensor is on line 20-24 and 165-175)

Traceback (most recent call last):
  File "main.py", line 169, in <module>
  File "ds18x20.py", line 40, in read_temp
  File "ds18x20.py", line 30, in read_scratch
Exception: CRC error

and this is the error i get.

i have tried connecting it to a different ESP32 and it gives the same.
I'm mostly confused beacouse it does work apart but not toggeter with the rest of my code.


问:
The form fields in PDF become empty when it is signed by docusign
I am trying to fix a bug in which the date field is not populated when the PDF is signed using docusign , but it works fine when it is done via Adobe sign.

When I debug this issue , I see the form fields are not at all coming when the PDF is signed using docusign

```<code>       PDDocument agreementDocument = PDDocument.load(file);

        PDAcroForm acroForm = agreementDocument.getDocumentCatalog().getAcroForm();

        if (acroForm != null) {
            PDTextField printName = (PDTextField) acroForm.getField("date");
            if (printName != null) {
                printName.setReadOnly(true);
                printName.setValue(new SimpleDateFormat(MM_DD_YYYY).format(date));
            }
</code>```

Here I see that the printName is coming as null when the pdf is signed by docusign , but it works fine when it is done by Adobe sign. I have tried with this Empty Adobe PDF fields stripped from document when returned from DocuSign
and this DocuSign: listing Document Custom fields → Empty JSON response

but I seem to be getting lost :( , any help will be greatly appreciated.

Body:
I am trying to fix a bug in which the date field is not populated when the PDF is signed using docusign , but it works fine when it is done via Adobe sign.

When I debug this issue , I see the form fields are not at all coming when the PDF is signed using docusign

       PDDocument agreementDocument = PDDocument.load(file);

        PDAcroForm acroForm = agreementDocument.getDocumentCatalog().getAcroForm();

        if (acroForm != null) {
            PDTextField printName = (PDTextField) acroForm.getField("date");
            if (printName != null) {
                printName.setReadOnly(true);
                printName.setValue(new SimpleDateFormat(MM_DD_YYYY).format(date));
            }

Here I see that the printName is coming as null when the pdf is signed by docusign , but it works fine when it is done by Adobe sign. I have tried with this Empty Adobe PDF fields stripped from document when returned from DocuSign
and this DocuSign: listing Document Custom fields → Empty JSON response

but I seem to be getting lost :( , any help will be greatly appreciated.


问:
What does the following assembly instruction mean "mov rax,qword ptr gs:[20h]"
Could someone please explain what the following assembly instruction means ?

```<code>mov rax,qword ptr gs:[20h]
</code>```

I found the following article here which is really helpful in explaining some things with respect to the segment override but I still do not understand what exactly is gs:[20h] is pointing at. Would the gs prefix segment override be pointing at a TEB or the PEB structure in 64 bit mode ?

Body:
Could someone please explain what the following assembly instruction means ?

mov rax,qword ptr gs:[20h]

I found the following article here which is really helpful in explaining some things with respect to the segment override but I still do not understand what exactly is gs:[20h] is pointing at. Would the gs prefix segment override be pointing at a TEB or the PEB structure in 64 bit mode ?


问:
Efficient way to find all matching array entries in another array (of structs) regardless of order
Hard to explain title.
I have an array like so

    var a = [][2]int{
        {18, 13},
        {13, 7},
    }
```
<p>I then have a 2D array of <code>Change</code> type (a From and to pair, of ints)</p>
<pre class="lang-golang prettyprint-override"><code>    var b = [][]Change{
        {   {From: 6, To: 5},
            {From: 14, To: 8},
        },
        {   {From: 13, To: 7},
            {From: 18, To: 13},
        },
    }
</code>```

I want to find if a exists in b, regardless of order, so in this example, a 'matches' the second entry in b.

I am wondering if its best to do a sort on the entries first so that they all are definiately in the right order, which would turn the entry in b of

        {   {From: 13, To: 7},
            {From: 18, To: 13},
        },
```
<p>into</p>
<pre class="lang-golang prettyprint-override"><code>        {   {From: 18, To: 13},
            {From: 13, To: 7},
        },
</code>```

but that feels like it the wrong way to go as there would be lots of rearranging before searching....
Any standard way to do this, or is it really a case of looping loads and loads to find it? I have tried writing loops to get it out but because of the order issue, i keep getting stuck pretty early in proceedings.

One note, the length of a will have to match the length of the entries in each array position of b, so that will cut out some looping.

Body:
Hard to explain title.
I have an array like so

    var a = [][2]int{
        {18, 13},
        {13, 7},
    }

I then have a 2D array of Change type (a From and to pair, of ints)

    var b = [][]Change{
        {   {From: 6, To: 5},
            {From: 14, To: 8},
        },
        {   {From: 13, To: 7},
            {From: 18, To: 13},
        },
    }

I want to find if a exists in b, regardless of order, so in this example, a 'matches' the second entry in b.

I am wondering if its best to do a sort on the entries first so that they all are definiately in the right order, which would turn the entry in b of

        {   {From: 13, To: 7},
            {From: 18, To: 13},
        },

into

        {   {From: 18, To: 13},
            {From: 13, To: 7},
        },

but that feels like it the wrong way to go as there would be lots of rearranging before searching....
Any standard way to do this, or is it really a case of looping loads and loads to find it? I have tried writing loops to get it out but because of the order issue, i keep getting stuck pretty early in proceedings.

One note, the length of a will have to match the length of the entries in each array position of b, so that will cut out some looping.


问:
Use Cookie ID for XHR Requests on Android Cordova
I recently had to migrate Cordova Android from version 8 to 10.
It turns out that there were many changes in the security of the WebViews and with that, my app no longer stores the Cookie ID for authenticating sessions on my backend server.
With each XHR request (GET/POST), it always receives a new session ID, as it did not send any.

How can I get the cookie ID and send it in other requests?


问:
Converting .csv to .TextGrid, nested .json format for transcripts
I am facing the (quite interesting) following problem : in the context of training a multi-modal deep learning model for a classification task, for a research project for my lab detailed below for those interested, I am using a text transcript of recorded videos, of two people speaking to each other, along with hand-made annotations.

The data

The text transcript is as utterance-level (i.e. each line is a turn of speak), saved as a .csv file, and looks like this :

```<code>Person_1 (string or NaN) | Person_2 (string or NaN) | Timestamp_begin (timestamp) | Timestamp_end (timestamp) | Duration (timestamp) | Label1 (1 or 0) | ... | Label8 (1 or 0)
</code>```

Person_1/Person_2 contains the sentence spoken by the respective person, and contains nothing when it is the other person speaking.

A thorough check of words has already been made, so I am quite sure that the words are the correct ones spoken.

I have the full videos of the interaction, and intend to use video and audio features extraction from those videos.

The problem :

I would like to check if the transcript is correctly aligned on the video, to coordinate the sentences and the features extracted from the videos : hence the need for correct alignement, face-tracking the speaking subject 20 seconds prior to when the sentence is spoken would be dumb. The language spoken is US English. Sadly, most techniques of forced alignement require the use of a specific transcript format, often used in psycholinguistics, the infamous .TextGrid files.

.TextGrid files seem to be a nested .json format, with phoeneme/word level annotations, with an exemple to be found here extracted from the following GitHub repo.

I would then like to know if someone :

Already had success converting a .csv text transcript to a .TextGrid text transcript
OR

Already worked on multi-speaker forced alignement directly on .csv transcripts, and could give me hand on how to achieve so.

I already looked at :

Montreal Forced Aligner
Berkeley Phonetics Machine
Most starred repos on forced alignement
The relabel_clean.py of this repo, considering to do .csv -> .lab -> .TextGrid, but had no success.

And did not find approaches allowing .txt/.csv files to be used, nor an approach allowing their conversion to .TextGrid format.

Body:
I am facing the (quite interesting) following problem : in the context of training a multi-modal deep learning model for a classification task, for a research project for my lab detailed below for those interested, I am using a text transcript of recorded videos, of two people speaking to each other, along with hand-made annotations.

The data

The text transcript is as utterance-level (i.e. each line is a turn of speak), saved as a .csv file, and looks like this :

Person_1 (string or NaN) | Person_2 (string or NaN) | Timestamp_begin (timestamp) | Timestamp_end (timestamp) | Duration (timestamp) | Label1 (1 or 0) | ... | Label8 (1 or 0)

Person_1/Person_2 contains the sentence spoken by the respective person, and contains nothing when it is the other person speaking.

A thorough check of words has already been made, so I am quite sure that the words are the correct ones spoken.

I have the full videos of the interaction, and intend to use video and audio features extraction from those videos.

The problem :

I would like to check if the transcript is correctly aligned on the video, to coordinate the sentences and the features extracted from the videos : hence the need for correct alignement, face-tracking the speaking subject 20 seconds prior to when the sentence is spoken would be dumb. The language spoken is US English. Sadly, most techniques of forced alignement require the use of a specific transcript format, often used in psycholinguistics, the infamous .TextGrid files.

.TextGrid files seem to be a nested .json format, with phoeneme/word level annotations, with an exemple to be found here extracted from the following GitHub repo.

I would then like to know if someone :

Already had success converting a .csv text transcript to a .TextGrid text transcript
OR

Already worked on multi-speaker forced alignement directly on .csv transcripts, and could give me hand on how to achieve so.

I already looked at :

Montreal Forced Aligner
Berkeley Phonetics Machine
Most starred repos on forced alignement
The relabel_clean.py of this repo, considering to do .csv -> .lab -> .TextGrid, but had no success.

And did not find approaches allowing .txt/.csv files to be used, nor an approach allowing their conversion to .TextGrid format.


问:
Individually change element inside of a class through their ID
I'm making a drawing board and as such need a color selector.

With the HTML I do plan to make them all different IDs. Right now all they do is change every single color, I just need it to change 1.

$("#colour").change(function(event) {
  console.log($(this).val());
  $(".color_front").css('background-color', $(this).val());
});

$(".color_front").click(function(event) {
  $("#colour").click();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  height: 100%;
  width: 100%;
}

.color_div {
  border: 2px solid black;
  width: 20px;
  height: 20px;
  border-radius: 50px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}

input[type=color] {
  display: none;
}

span {
  border-radius: 50%;
  width: 14px;
  height: 14px;
  background-color: black;
  display: block;
}

.color_box {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  gap: 5px;
  max-width: 290px;
  margin: 0 auto;
  padding: 20px 10px;
}</code>```

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

```

Body:
I'm making a drawing board and as such need a color selector.

With the HTML I do plan to make them all different IDs. Right now all they do is change every single color, I just need it to change 1.

$("#colour").change(function(event) {
  console.log($(this).val());
  $(".color_front").css('background-color', $(this).val());
});

$(".color_front").click(function(event) {
  $("#colour").click();
});

html,
body {
  height: 100%;
  width: 100%;
}

.color_div {
  border: 2px solid black;
  width: 20px;
  height: 20px;
  border-radius: 50px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}

input[type=color] {
  display: none;
}

span {
  border-radius: 50%;
  width: 14px;
  height: 14px;
  background-color: black;
  display: block;
}

.color_box {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  gap: 5px;
  max-width: 290px;
  margin: 0 auto;
  padding: 20px 10px;
}

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">

    <input type='color' value='#000000' class='bar' id="colour">


问:
Will using an explicit del matter for containers that are not needed anymore in the program?
Multiple sources lead me to believe that using a del statement is rarely necessary. However, I am working on a program that needs to read in huge files ( 6 GB) with filename getting picked up from from a list, do some transformation, write them to a datastore and pick up the next file.

For instance the reference variables buffer and processed will get overwritten with every iteration of loop - is there a point to deleting them explicitly?

```<code>files = list() # contains 1000 filenames
for file in files:
    buffer = read_from_s3(file)
    processed = process_data(buffer)
    del buffer # needed?
    write_to_another_s3(processed)
    del processed # needed?
</code>```

Body:
Multiple sources lead me to believe that using a del statement is rarely necessary. However, I am working on a program that needs to read in huge files ( 6 GB) with filename getting picked up from from a list, do some transformation, write them to a datastore and pick up the next file.

For instance the reference variables buffer and processed will get overwritten with every iteration of loop - is there a point to deleting them explicitly?

files = list() # contains 1000 filenames
for file in files:
    buffer = read_from_s3(file)
    processed = process_data(buffer)
    del buffer # needed?
    write_to_another_s3(processed)
    del processed # needed?


问:
Why when I send my node.js app to server the cookie is not created?
I have a small node.js app. It contains login and logout routes:

```<code>const createToken = (id) => {
  return jsonwebtoken.sign({ id }, 'a secret phrase', {
    expiresIn: maxAge
  })
}

router.post('/signup', async (req, res) => {
  const { email, password } = req.body

  try {
    const user = await User.create({ email, password })
    const token = createToken( user._id )
    console.log(token);
    res.cookie('jwt', token, {
      httpOnly: true,
      maxAge: maxAge * 1000
    })
    res.status(201).json(user._id)
  } catch(err) {
    const errors = { email: '', password: '' }
    if (err.code === 11000) {
      res.status(400).json({ errors: { email: 'This email is already taken' } })
    } else {
      Object.keys(err.errors).forEach( key => {
        errors[key] = err.errors[key].properties.message
      })
      res.status(400).json({ errors })
    }
  }
})

router.post('/login', async (req, res) => {
  console.log('i just entered login route');
  const { email, password } = req.body
  try {
    const user = await User.login(email, password)
    const maxAge = 3 * 24 * 60 * 60
    const token = jsonwebtoken.sign({ id: user._id }, 'a secret phrase', {
      expiresIn: maxAge
    })
    res.cookie('jwt', token, {
      httpOnly: true,
      maxAge: maxAge * 1000
    })
    res.status(201).json(user._id)
  } catch(err) {
    const errors = { email: '', password: '' }
    if (err.message === 'Email incorrect') {
      errors.email = err.message
    } else if (err.message === 'Incorrect password') {
      errors.password = err.message
    } else {
      errors.email = err.message
    }
    res.status(400).json({ errors })
  }
})
</code>```

This app works fine when I run it on localhost with nodemon. But after I send it to server and try to signup or login, problems start to emerge.

In each browser I'm getting an error 'use not logged in' which comes from my route guard (i'm pushing to protected routes after login and signup) and simply means there is either no token or user is not present in db. The first option seems to be the case here as I can see in my db that the user is created. And I can't see the cookie created in dev tools of ANY browser like I used to see when I ran the server from localhost.

And now it gets really weird: authentication works in Firefox anyway. Firefox dev tools can't see the cookie like other browser's dev tools, but Firefox behaves like it's there: login, signup and route guards work.

Can anybody please shed some light on what might be happening here? I'm totally lost and I don't have much experience in node.js.

edit: also works in opera

edit 2: when I add a sameSite attibute, then I can't log in in any browser including FF and Opera

Body:
I have a small node.js app. It contains login and logout routes:

const createToken = (id) => {
  return jsonwebtoken.sign({ id }, 'a secret phrase', {
    expiresIn: maxAge
  })
}

router.post('/signup', async (req, res) => {
  const { email, password } = req.body

  try {
    const user = await User.create({ email, password })
    const token = createToken( user._id )
    console.log(token);
    res.cookie('jwt', token, {
      httpOnly: true,
      maxAge: maxAge * 1000
    })
    res.status(201).json(user._id)
  } catch(err) {
    const errors = { email: '', password: '' }
    if (err.code === 11000) {
      res.status(400).json({ errors: { email: 'This email is already taken' } })
    } else {
      Object.keys(err.errors).forEach( key => {
        errors[key] = err.errors[key].properties.message
      })
      res.status(400).json({ errors })
    }
  }
})

router.post('/login', async (req, res) => {
  console.log('i just entered login route');
  const { email, password } = req.body
  try {
    const user = await User.login(email, password)
    const maxAge = 3 * 24 * 60 * 60
    const token = jsonwebtoken.sign({ id: user._id }, 'a secret phrase', {
      expiresIn: maxAge
    })
    res.cookie('jwt', token, {
      httpOnly: true,
      maxAge: maxAge * 1000
    })
    res.status(201).json(user._id)
  } catch(err) {
    const errors = { email: '', password: '' }
    if (err.message === 'Email incorrect') {
      errors.email = err.message
    } else if (err.message === 'Incorrect password') {
      errors.password = err.message
    } else {
      errors.email = err.message
    }
    res.status(400).json({ errors })
  }
})

This app works fine when I run it on localhost with nodemon. But after I send it to server and try to signup or login, problems start to emerge.

In each browser I'm getting an error 'use not logged in' which comes from my route guard (i'm pushing to protected routes after login and signup) and simply means there is either no token or user is not present in db. The first option seems to be the case here as I can see in my db that the user is created. And I can't see the cookie created in dev tools of ANY browser like I used to see when I ran the server from localhost.

And now it gets really weird: authentication works in Firefox anyway. Firefox dev tools can't see the cookie like other browser's dev tools, but Firefox behaves like it's there: login, signup and route guards work.

Can anybody please shed some light on what might be happening here? I'm totally lost and I don't have much experience in node.js.

edit: also works in opera

edit 2: when I add a sameSite attibute, then I can't log in in any browser including FF and Opera


问:
How to create Chromosomes and Fitness function for this NP-Hard Genetic algorithm problem
Hi i am very new to genetic algorithm and i am stuck with this problem:

A move is provided for a student. He has to store his things in small plastic boxes in a cardboard box with a capacity of 2 cubic meters. Knowing that the small plastic boxes have the following capacities 20 cubic centimeters, 35 cubic centimeters and 60 cubic centimeters. In this genetic algorithm problem we need to find the maximum number of plastic boxes stored in this cardboard box.

Thanks in advance.

I tried to use the knapsack problem as inspiration but it didn't really work.


问:
Why the shebang with `sudo` doesn't work as needed?
I have a simple python code should be run as root. sudo --preserve-env=HOME python3 <file_name> works perfect for me, but, in order not to write this every time, I made the shebang in my code: #!/usr/bin/sudo --preserve-env=HOME python3 — and started it as an usual executable file.

I have made a sudo-shebangs so I didn't expect something to be wrong, but when I started it, it didn't run, but it started to eat RAM. Even the first logging string of code (even before imports) wasn't executed, when it has already eat all the RAM.

Then I remade the shebang to #!/usr/bin/env sudo --preserve-env=HOME python3 (env was added). But then something weird started. This doesn't eat RAM anymore, but CPU... Two cores started some weird dance: the first core is overloaded, the second is resting, then they are being swapped. This repeats regularly and cadencially. Sometimes the second core can be shifted by another one.

What can be the reason of the behavior?


问:
Interacting with SVG file to change color on tap
I have an SVG file, how can i interact with it and change color of different portions of SVG file.

I am trying this thing very first time, and i am confused how to achieve it. Any possible and step by step solutions?
TIA


问:
Website doesn't work without www in Chrome
My friend created static website using a third party software. He's hosting it on bluehost.com The website works, if you type www.example.cz. Without the www it doesn't work. I tried it both in Chrome and Safari and suprisingly it works in Safari without www but doesn't work in Chrome.
I followed a Bluehost tutorial and changed .htaccess file with this code:

```<code>RewriteEngine On
            RewriteCond %{HTTP_HOST} !^www.example.cz$ [NC]
            RewriteRule ^(.*)$ http://www.example.cz/$1 [L,R=301]
</code>```

The result is the same. Is there something else I can do?

Body:
My friend created static website using a third party software. He's hosting it on bluehost.com The website works, if you type www.example.cz. Without the www it doesn't work. I tried it both in Chrome and Safari and suprisingly it works in Safari without www but doesn't work in Chrome.
I followed a Bluehost tutorial and changed .htaccess file with this code:

RewriteEngine On
            RewriteCond %{HTTP_HOST} !^www.example.cz$ [NC]
            RewriteRule ^(.*)$ http://www.example.cz/$1 [L,R=301]

The result is the same. Is there something else I can do?