How to pass search parameter to datatables Search field

I have successfully setup datatables (with no search text by default). I want to be able to pass a search parameter to my datatbles table via URL. for example if my default datatables page is abc.html. I want to add search text “test” via url abc.html?search.search=test

I am not sure how I can do this. Please see the code I have on the datatables page below.

http://live.datatables.net/peticimu/1/edit

Prevent multiple versions of React (while creating npm package)

I intend to create an npm package (recharts-candlestick). The only dependency my package has is Recharts. I have created the package, used Webpack to build it and tested the package locally using npm link. This works when I do NOT use Recharts, but as soon as I have Recharts as a peer dependency I get an error message (https://reactjs.org/docs/error-decoder.html/?invariant=321). I think I am having this issue because I have multiple versions of react:

$ npm ls react
[email protected] C:path_to_project
├─┬ [email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected] deduped
├── [email protected]
└─┬ [email protected]
  ├── [email protected] deduped
  └─┬ [email protected]
    ├─┬ [email protected]
    │ └── [email protected] deduped
    ├─┬ [email protected]
    │ ├─┬ [email protected]
    │ │ └── [email protected] deduped
    │ └── [email protected] deduped
    └── [email protected] deduped

I have tried fixing the duplicate react packages locally by linking the react version in the package to the react package of the project I am testing the package in (https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react). I would however suspect that with the current setup there would not be any errors anyway because the other react versions are all deduped. The source code for the package can be found here: https://github.com/jobdenotter/candlestick-chart. The package.json of the package code is:

  "name": "my-package",
  "version": "1.0.0",
  "description": "",
  "main": "build/index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "webpack",
    "start": "webpack --watch"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.16.7",
    "webpack": "^5.72.0"
  },
  "peerDependencies": {
    "react": "^17.0.0",
    "react-dom": "^17.0.0",
    "recharts": "^2.1.9"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.2.4",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-plugin-transform-react-jsx": "^6.24.1",
    "babel-preset-env": "^1.7.0",
    "webpack-cli": "^4.9.2"
  }
}

How to submit modal form from another form using python flask bootstrap

I have a form that works fine to select a customer from a drop down. I am trying to add a modal that will allow the user to add a new customer name if the customer is not already in the drop down. Everything works well except I believe when I submit the new customer name via modal, both the modal submit and the original submit are being activated. I am simply trying to add a customer to a sql table from the modal from inside a form. Thank you, and yes, I am a beginner.

Here is the form with the modal as well.

{% extends "layout.html" %}

{% block title %}
Request
{% endblock %}

{% block main %}
<!--Nav Tabs-->
<ul class="nav nav-tabs" id="myTab" role="tablist">
    <li class="nav-item" role="presentation">
      <button class="nav-link active" id="company-tab" data-bs-toggle="tab" data-bs-target="#company" type="button" role="tab" aria-controls="company" aria-selected="true">Company</button>
    </li>
    <li class="nav-item" role="presentation">
      <button class="nav-link disabled" id="address-tab" data-bs-toggle="tab" type="button" role="tab" aria-controls="address" aria-selected="false">Address</button>
    </li>
    <li class="nav-item" role="presentation">
      <button class="nav-link disabled" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" type="button" role="tab" aria-controls="contact" aria-selected="false">Contact</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link disabled" id="development-tab" data-bs-toggle="tab" data-bs-target="#development" type="button" role="tab" aria-controls="development" aria-selected="false">Development</button>
      </li>
  </ul>

<!--Nav Tab-->
  <div class="tab-content" id="myTabContent">
    <div class="tab-pane fade show active" id="company" role="tabpanel" aria-labelledby="company-tab">
      <h4 class="mt-2">Company</h4>
      <p>Please select a company from the dropdown or add new.</p>
        <form action="/request_exp" method="POST">
            <div class="mb-3">
                <select class="form-select w-auto mx-auto" name="company">
                    <option disabled selected>Company...</option>
                    {% for row in company_list %}
                    <option value="{{  row.id  }}">{{ row.company }}</option>
                    {% endfor %}
                </select>
            </div>
            <!--Select customer from drop down list-->
            <button class="btn btn-primary btn-space" type="submit">Select</button>
      </div>
      <!-- Button trigger modal -->
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addcompmodal">
          Add New Company
        </button>

        <!-- Modal -->
        <div class="modal fade" id="addcompmodal" tabindex="-1" aria-labelledby="addcompmodalLabel" aria-hidden="true">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="addcompmodalLabel">New Customer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <div class="modal-body">

                  <form id="loadcustomerform">
                    <input autocomplete="off" class="form-control mx-auto w-auto" id="company" type="text" placeholder="Customer Name">
                    <button class="btn btn-primary btn-space" onclick="onLoadCustomerPress(this)">Submit</button>
                  </form>

              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
              </div>
            </div>
          </div>
        </div>
       </div>
        {% endblock %}

Here is the python code for both routes. The first is for the main form. The second is for the modal.

 @app.route("/request_exp", methods=["GET", "POST"])
@login_required
def request_exp():
    """Request a development - customer facing"""
    if request.method == "POST":

        # Get company name from request_ext
        cust_id = request.form.get("company")

        # Get company ID to set session
        rows = db.execute("SELECT * FROM customers WHERE id = ?;", cust_id)
        session["cust_id"] = rows[0]["id"]

        # Move on to address request page
        return redirect("request_exp2")

    else:
        # TODO - Clear any previous company sessions
        # If request.method == "GET":
        company_list = db.execute("SELECT id, company FROM customers ORDER BY company;")
        return render_template("request_exp.html", company_list=company_list)

    @app.route("/add_cust", methods=['POST'])
def capture_userinput():
    req_data = request.get_json()
    recd_data = req_data['toSend']

    #Add into database
    db.execute("INSERT INTO customers (company) VALUES(?);", recd_data)

Lastly, here is the javascript

//Add a new customer from the modal
function onLoadCustomerPress(e) {
    //FIRST WE CAPTURE THE VALUE THAT THE USER INPUTS
    let userInput = {toSend: e.currentTarget.previousElementSibling.value}

    //THEN WE SEND IT TO THE FLASK BACKEND USING AJAX (Fetch API)
    fetch("/add_cust", {
    method: 'POST',
    headers: {
    "Content-Type": "application/json",
    },
    body: JSON.stringify(userInput)
    }
}

How do I return all results of an inner join when filtering by an attribute of a joined table

I have a SQL query that filters logs by what kind of tags they have. Sometimes the logs have multiple tags. The issue is that when I filter by a tag, the returned logs only include the tag that I’ve filtered with. When filtering by a tag, I would like to get all logs with that tag, with all of their tags.

i.e. When filtering by “a pink tag” I would like to have…
enter image description here

But instead I’m getting this…
enter image description here

Below is my SQL query

        var logsQuery = `PREPARE LogQuery (text) AS
            SELECT trackerlogs.*,
            trackers.serialnumber,
            trackers.active,
            trackers.actdate,
            trackers.deactdate,
            trackerclaims.devicename,
            trackerclaims.claimtype,
            t.id AS tagid,
            t.tagname,
            t.color
            FROM trackerlogs INNER JOIN
            trackers ON trackerlogs.deviceid = trackers.id
            INNER JOIN trackerclaims ON trackerclaims.deviceid = trackers.id
            LEFT JOIN
            (SELECT tags.*, trlogtags.logid AS logid from tags
            INNER JOIN trlogtags ON trlogtags.tagid = tags.id
            ${tags.length > 0 ? `AND t.id IN (${tags.join()})` : ""}
            EXECUTE LogQuery('${search === "" ? "%" : "%" + search + "%"}');`;

I believe the relevant part of the query is:

${tags.length > 0 ? `AND t.id IN (${tags.join()})` : ""}

However every time I try to change this, I’m not able to filter by tags anymore.

Any help is greatly appreciated. Please let me know if the explanation isn’t clear, additional context is needed, or if the answer is somewhere else on StackOverflow and I’m blind.

Angular component Inputs might be null error

I’m new to Angular and trying to figure things out, and between typescript and angular, I’m noticing an annoyance. VS Code complains and the TS compiler complains when I have things marked as @Input might be null. I’d rather it throw if not provided”, but the advice from TS is that “It might be null, and I have “?”s and “!”s all over my code (which I don’t like, I why can’t an @Input simply be required?).

However, now my code is throwing errors. The page is rendering correctly, but my guess is at some point in the render the value isn’t provided. I’m trying to pass the 0 value from an array into a component, because the serverside decided to create an array that would only have one value. And that’s the complaint.

ERROR TypeError: Cannot read properties of null (reading ‘0’)

What am I missing about Angular and Typescript, @Inputs and potential nulls/anys?

Simple peer ice connection failure randomly after connection is established

I am using simple-peer to connect clients to my server. Connection gets established, data get transferred, everything works fine, but an errors occurs and crashes the server randomly while running. I have not been able to find anyway to reproduce it. Sometimes it works fine over night, sometimes it crashes within few seconds. More often though it happens within like 10 or so minutes.

I suspect it happens within few seconds of a disconnection, but I cant be sure since its fine in most of the disconnections.

One thing to note is that the error comes up only on the server side, which is on node.js, and using wrtc. Not once did this happen client/browser side.

Let me know what more details can I provide in the comments. Error is attached below.

enter image description here

How can I override tabBarOptions and change the color of the navigation icons?

How can I change the colors of the icons that are active by removing the ‘tabBarOptions’ part and everything still works?

Going through an app I made some time ago in a tutorial, I came across this warning in the console:

Bottom Tab Navigator: 'tabBarOptions' is deprecated. Migrate the options to 'screenOptions' instead.
Place the following in ‘screenOptions’ in your code to keep current behavior:

Reading the information that React Navigation offers about Bottom Tabs Navigation, I have managed to solve the error in the following way.

<Tab.Screen
          name="restaurants"
          component={RestaurantsStack}
          options={{
            title: "Restaurants",
            headerShown: false,
            tabBarIcon: ({ color, size }) => (
              <MaterialCommunityIcons
                name="magnify"
                color={color}
                size={size}
              />
            ),
          }}
        />

However, in my application, I want to change the color of the buttons when we navigate through the screens, the icon of the screen we are on is shown in a different color, and at the time the code was the one shown below, and it is That’s why it shows me the warning.
The problem is that I don’t know how I can correct this

This is the full code of my file

const Tab = createBottomTabNavigator()

export default function Navigation() {
  const screenOptions = (route, color) => {
    let iconName
    switch (route.name) {
      case "tiendas":
        iconName = "compass-outline"
        break;
      case "favorites":
        iconName = "heart-outline"
        break;
      case "top-tiendas":
        iconName = "star-outline"
        break;
      case "search":
        iconName = "magnify"
        break;
      case "account":
        iconName = "home-outline"
        break;
    }

    return (
      <Icon
        type="material-community"
        name={iconName}
        size={22}
        color={color}
      />
    )
  }

  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName="tiendas"
        tabBarOptions={{
          inactiveTintColor: "#f48b28",
          activeTintColor: "#633204"
        }}
        screenOptions={({ route }) => ({
          tabBarIcon: ({ color }) => screenOptions(route, color)
        })}
      >
        <Tab.Screen
          name="tiendas"
          component={tiendasStack}
          options={{
            title: "Tiendas",
            headerShown: false
          }}
        />
        <Tab.Screen
          name="favorites"
          component={FavoritesStack}
          options={{
            title: "Favoritos",
            headerShown: false
          }}
        />
        <Tab.Screen
          name="top-tiendas"
          component={ToptiendasStack}
          options={{
            title: "Top 10",
            headerShown: false,
          }}
        />
        <Tab.Screen
          name="search"
          component={SearchStack}
          options={{
            title: "Buscar",
            headerShown: false,
          }}
        />
        <Tab.Screen
          name="account"
          component={AccountStack}
          options={{
            title: "Cuenta",
            headerShown: false,
          }}
        />
      </Tab.Navigator>
    </NavigationContainer>
  )
}

As I already said, I could solve it in the following way, but I don’t know how to add the desired color and how to make it change when the icon is active:

This removes the warning, but I can’t change the colors:
How can I change the colors of the icons that are active by removing the 'tabBarOptions' part and everything still works?

const Tab = createBottomTabNavigator()

export default function Navigation() {

  // Navigation buttons
  return (
    <NavigationContainer>
      <Tab.Navigator >
        <Tab.Screen
          name="tiendas"
          component={TiendasStack}
          options={{
            title: "Tiendas",
            headerShown: false,
            tabBarIcon: ({ color, size }) => (
              <MaterialCommunityIcons
                name="magnify"
                color={color}
                size={size}
              />
            ),
          }}
        />
        <Tab.Screen
          name="favorites"
          component={FavoritesStack}
          options={{
            title: "Favoritos",
            headerShown: false,
            tabBarIcon: ({ color, size }) => (
              <MaterialCommunityIcons
                name="heart-outline"
                color={color}
                size={size}
              />
            ),
          }}

        />
        <Tab.Screen
          name="top-tiendas"
          component={TopTiendasStack}
          options={{
            title: "Top 5",
            headerShown: false,
            tabBarIcon: ({ color, size }) => (
              <MaterialCommunityIcons
                name="star-outline"
                color={color}
                size={size}
              />
            ),
          }}
        />
        <Tab.Screen
          name="search"
          component={SearchStack}
          options={{
            title: "Buscar",
            headerShown: false,
            tabBarIcon: ({ color, size }) => (
               <MaterialCommunityIcons
                 name="magnify"
                 color={color}
                 size={size}
               />
             ),
          }}
        />
        <Tab.Screen
          name="account"
          component={AccountStack}
          options={{
            title: "Cuenta",
            headerShown: false,
            tabBarIcon: ({ color, size }) => (
              <MaterialCommunityIcons
                name="home-outline"
                color={color}
                size={size}
              />
            ),
          }}
        />
      </Tab.Navigator>
    </NavigationContainer>
  )
}

getting same entered data automatically into new input React Redux adding 2 useState together

I am creating an application so first started creating in a simple way so i can cover all the topics then after that will combine everything together. So, here taking user data using useState and using Redux for getting the data into other components.

There are two use States one for workData and another one for skillData.
Work section contains both workData and skilldata in same div.
Now the issue what am facing is that when am adding skills into the inputs and then creating another workData, the older entered skillData coming automatically with it in the inputs.

Adding Code Below:

const Work = () => {
    const dispatch=useDispatch();
    const [workData,setWorkData]=useState([{
        firstname:"",
        lastname:""
    }])
    function handleChange(event,index){
        const {name,value}=event.target;
        const data=[...workData];
        data[index][name]=value;
        setWorkData(data);
    }
    function handleAddInput(){
        setWorkData([...workData,{firstname:"",lastname:""}]);
    }
    function handleDeleteInput(index){
        const data=[...workData];
        data.splice(index,1);
        setWorkData(data);
    }

    const [skillsData,setSkillsData]=useState([{skillname:""}]);
    
    function handleSkillChange(e,index){
        const {name,value}=e.target;
        const SkillList=[...skillsData];
        SkillList[index][name] = value;
        setSkillsData(SkillList);
    }
    function handleSkillAdd(){
        setSkillsData([...skillsData,{skillname:""}])
    }
    function handleSkillDelete(index){
        const SkillList=[...skillsData];
        SkillList.splice(index,1)
        setSkillsData(SkillList);
    }


    useEffect(()=>{
        const finalWorkData={
            workData,
            skillsData
        };
        dispatch(WorkAction(finalWorkData))
    },[workData,skillsData,dispatch])


  return (
    <>
        {workData.map((data,index)=>{
            return (
            <div key={index}>
                <input type="text" name="firstname" placeholder='firstname' value={data.firstname} onChange={event=>handleChange(event,index)} />
                <input type="text" name="lastname" placeholder='lastname' value={data.lastname} onChange={event=>handleChange(event,index)} />
                {skillsData.map((skill,index)=>(
                    <div key={index}>
                        <input type="text" name="skillname" placeholder='e.g., java,python,react' value={skill.skillname} onChange={(e)=>handleSkillChange(e,index)} />
                        {skillsData.length -1 === index && skillsData.length < 10 && <button className="add" onClick={handleSkillAdd}>Add</button>}
                        {skillsData.length > 1 && <button className="remove" onClick={handleSkillDelete}>remove</button>}
                    </div>
                ))}
                {workData.length -1 === index &&  <button onClick={handleAddInput}>Add</button>}
                {workData.length !== 1 &&  <button onClick={()=>handleDeleteInput(index)}>Delete</button>}
            </div>
            )
        })}

    </>
  )
}

export default Work

Here is the Screen Shot of Issue am facing

Help me in resolving this issue Thanks.

How to find all combinations of if conditions by effective way?

I would like to find by effective way, because of code nesting

if (price && car.price < price.value) {
    return car
}
if (tachometer && car.tachometer < tachometer.value) {
    return car
}
if (cars.length > 0 && cars.includes(car.name.split(' ')[0])) {
    return car
}
if (colors.length > 0 && colors.includes(car.color)) {
    return car
}
if (fuel && car.fuel === fuel.text) {
    return car
}

turn into all posible conditions

if (price && car.price < price.value) {
    if (tachometer && car.tachometer < tachometer.value) {
        if (...
        
    }
}

Move focus from Taskpane to Sheet with Excel Javascript API

I am working on an Excel Add in using Excel Javascript API.

https://docs.microsoft.com/en-us/office/dev/add-ins/reference/overview/excel-add-ins-reference-overview

Is there a way to switch focus from taskpane to the sheet? Now if user clicks on an element on the taskpane she cannot use the the arrow keys to navigate the excel sheet until she has clicked the sheet area again with the mouse.

Use case
It would be nice to have a button on the taskpane that would paste text to a certain range on the sheet and would also move the focus to the sheet, so the user could start navigating with arrow keys immediately after pressing the button.

Pasting the text to the range and setting the selection are working fine, but I cannot find a way to move focus from the taskpane to the sheet with JS API.

Any help is very much appreciated,
Thank you!

The problem with passing callback functions, writes an error props.me is not a function, I can only show part of the code

There is a parent and a child (component) I want to get the values ​​from the child to the parent, I throw the functions themselves into the component, in the child I wrote the return target of the value from the input

parent

const [m, setM] = useState("")
    const me = (m) => {
        setM(m)
        console.log(m)
    }

    const [dey, setD] = useState("")
    const de = (dey) => {
        setD(dey)
    }

    const [y, setY] = useState("")
    const ye = (y) => {
        setY(y)
    }

its companent connect in jsx

<CustomSelect
    className="flex-1"
    btnClass="inp"
    checkedOpt={dey}
    options={d}
    de={de}
/>
<CustomSelect
    className="flex-1 ms-2 ms-xxl-4"
    btnClass="inp"
    checkedOpt={m}
    options={month}
    me={me}
/>
<CustomSelect
    className="flex-1 ms-2 ms-xxl-4"
    btnClass="inp"
    checkedOpt={y}
    options={years}
    ye={ye}
/>

child

 const handleChange = (e) => {
        props.de(e.target.value);
        props.me(e.target.value);
        props.ye(e.target.value);
    }

jsx

<input
    type="radio"
    name="type"
    value={item}
    checked={(item === props.checkedOpt)}
    onChange={handleChange}
/>

Change a string text if another contains a certain value

I got this html code:

<p class="day-left"><span style="color: #000" id="countdown2"></span> <span id="days">days</span> to <strong>the EVENT</strong>!</p> 

The output is:

3 day to the EVENT.

The countdown 2 is running a function that calculate the days left.

I want when the span countdown2 is = 1, the text of span days change to “day”, not “days”.

I tryed this code, but not worked:

if ($('span#countdown2:contains("<span style="color: #000" id="countdown2">1</span>")').length > 0) {
            $("#days").write("day");
        }

Any idea?

to get the values of the key ‘a’ using X variable?

I am a beginner in javaScript, I have this code and i want to get the values of the key ‘a’ in the object MyGraph using the “currentVertex” variable which is in this situation has the value ‘a’. how to fix this instruction: console.log(Object.values(MyGraph.currentVertex));
My code :

let unvisitedVertices={ 'a' :0, 'b':Infinity, 'c':Infinity, 'd':Infinity, 'e':Infinity, 'f':Infinity};

const MyGraph = {
    a: { b: 5, c: 2 },
    b: { a: 5, c: 7, d: 8 },
    c: { a: 2, b: 7, d: 4, e: 8 },
    d: { b: 8, c: 4, e: 6, f: 4 },
    e: { c: 8, d: 6, f: 3 },
    f: { e: 3, d: 4 },
};

const minDistance =Math.min.apply(Math,Object.values(unvisitedVertices));
function calcDistance() {     
}

function getKeyByValue(object, value) {
    return Object.keys(object).find(key => object[key] === value);
}

const currentVertex = getKeyByValue(unvisitedVertices,minDistance);
console.log(currentVertex);
console.log(minDistance);
console.log(Object.values(MyGraph.currentVertex));

After execution :

 console.log(Object.values(MyGraph.currentVertex));

TypeError: Cannot convert undefined or null to object
    at Function.values (<anonymous>)
    at Object.<anonymous> (c:UsersInspiron15DesktopsummerjavaScripttest.js:25:21)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 ```