Connect to Multiple Databases on one Server Using MSSQL NPM Package

I have a server set up and I am using “mssql” npm package to set up the database connections for my query routes. I want just one route in the whole server to be using a different database that is at a different IP address than the rest of the routes.

I have two different configs, configA and configB. This is my route set up:

router.get("/:code", function (req, res) {
  var sql = require("mssql");

    sql.connect(configA/B, function (err) {
      if (err) console.log(err);

      var request = new sql.Request();

      request.query("some query",
        function (err, recordset) {
          if (err) console.log(err);

          res.send(JSON.stringify(recordset));
        }
      );

    });

});

However, if I go to a page that uses a route with configA and then navigate to a page that uses a route with configB, configA just remains as the config, if that makes sense. I really just want to be able to use configA for routes 1, 2, and 3, and configB for route 4, but I am not able to as it always takes the already existing config.

How to use DELETE on custom route when using json-server

I’m having a couple of issues when calling DELETE on some custom endpoints defined in my routes.json

I have some data that looks like this –

{
  "apps": [
    {
      "creation_time": "2018-06-07 15:56:01",
      "description": "Test App",
      "id": "2",
      "name": "Test",
      "update_time": "2018-06-07 15:56:01"
    },
  ],
  "account_types": [
    {
      "app": {
        "description": "Test app",
        "id": "2",
        "name": "Test",
        "user_id": "337"
      },
      "creation_time": "2018-06-07 16:00:31",
      "description": "Regular Test account type",
      "id": "2",
      "max": "None",
      "name": "BASIC",
      "update_time": "2018-06-07 16:00:31"
    },
    {
      "app": {
        "description": "Test app",
        "id": "2",
        "name": "Test",
        "user_id": "337"
      },
      "creation_time": "2018-08-02 13:48:45",
      "description": "Premium Test account type",
      "id": "8",
      "max": "None",
      "name": "PREMIUM",
      "update_time": "2018-08-02 13:48:45"
    }
  ]
}

And this is my routes.json

{
    "/test/:app_id/accounts/type": "/account_types?app.id=:app_id",
    "/test/:app_id/accounts/type/:type_id": "/account_types?app.id=:app_id&id=:type_id"
}

When I call GET on these two endpoints, I retrieve the correct info but when I call DELETE on them I receive status code 404, is there something I am doing wrong or is this a known issue?

Any help would be appreciated

User Prompt Array Question for Javascript

I’m in a JavaScript class, and I am stuck on this portion of my homework assignment. Basically, we are creating a pizza ordering system where a user would fill out if they want thin/thick/pan crust, which toppings they want, if they want extra cheese and finally if they want delivery.

I have everything except the pizza toppings part. This is the information for this section (including the comments the teacher gave us as “hints”) along with what I’ve been trying to make work. I’ve cut out all the sections I’ve already finished.

function getPizzaOrder() {
  var extraCheeseUpcharge = 1.5
  var thickCrustUpcharge = 2
  var deliveryFee = 3.5
  var toppingsFee = 1.5
  var basePrice = 10

  var toppings = prompt("Please enter additional toppings (comma separated)")
      // HINT: prompt() will return an empty string "" if the user presses 'OK' without entering a value
      // if the user enters toppings, use .split(",") to separate toppings into an array
      // if no toppings are given, make sure pizza.toppings is set to []
      // if the user has added toppings, add toppingsFee multiplied by
      // the number of toppings added to pizza.cost
      // YOUR CODE HERE
    
      pizza.toppings = [];
      pizza.toppings = toppings.split(',');
      for (let i = 0; i < pizza.toppings.length; i++){
       pizza.cost =+ pizza.toppings * toppingsFee;
      }
      console.log(pizza.toppings);



  return pizza
}

My Error Message. The bane of my existence. Error Message not working and it might be due to a multitude of things

$(document).ready(function (e) {



    $("#reg-form").submit(function (event) {
        let $password = $("#password");
        let $confirm = $("#confirm_pwd");
        let $error = $("#confirm_error");
        if($password.val() === $confirm.val()){
            return true;
        }else{
            $error.text("Password not Match");
            event.preventDefault();
        }
    });



});

This is my Js code and here’s my HTML

                        <div class="form-row">
                            <div class="col">
                                <input type="text" required name="FirstName" id="FirstName" class="form-control rounded-pill" placeholder="First name*">
                            </div>
                            <div class="col">
                                <input type="text" name="LastName" id="LastName" class="form-control rounded-pill" placeholder="Last name">
                            </div>
                        </div>
                        
                        <div class="form-row-my-4">
                            <div class="col">
                                <input type="text" required name="UserName" id="UserName" class="form-control rounded-pill" placeholder="Username*">
                            </div>
                        </div>

                        <div class="form-row-my-4">
                            <div class="col">
                                <input type="email" required name="email" id="email" class="form-control rounded-pill" placeholder="Email*">
                            </div>
                        </div>

                        <div class="form-row-my-4">
                            <div class="col">
                                <input type="password" required name="password" id="password" class="form-control rounded-pill" placeholder="Password*">
                            </div>
                        </div>

                        <div class="form-row-my-4">
                            <div class="col">
                                <input type="password" required name="confirm_pwd" id="confirm_pwd" class="form-control rounded-pill" placeholder="Confirm Password*">
                                <small id="confirm_error" class="text-danger"></small>
                            </div>
                        </div>
                        <br>
                        <div class="form-check form-check-inline">
                            <input type="checkbox" name="agreement" class="form-check-input" required>
                            <label for="agreement" class="form-check-label font-ubuntu text-black-50">I agree <a href="#">terms, conditions and policy</a>*</label>
                        </div>
                        
                        <div class="submit-btn text-center my-5">
                            <button type="submit" class="btn btn-light rounded-pill text-dark px-5">Continue</button>
                        </div>
                    </form> 
                </div>
            </div>
        </div>
        <br>
    </section>

My aim is to make a small error message, in the text below, when the password and confirm_pwd don’t match.

I tried crossing my fingers and touching wood, then I thought I might have to think about it all night but I decided to post here instead :).

But this does not seem to be working and I tried every solution my small brain can come up with from the text boxes are not sending things (most likely) to the continue button does not work.

<small id="confirm_error" class="text-danger"></small>

Tell me what too do as I’ve been stuck for a while.

“Thank you kindly”

Export react table as csv

Hi guys I’m trying to export my atlassian dynamic react table as a csv file but the table I’m getting in the file is not really looking as I expected… I tried using the react-csv library but I’m getting this. My dynamic table looks like this on my browserthis. The Columns are in {shareFilterHead} and the rows are {shareFilterRows} . Is there any other way to download this table in React as a csv file?

import React, {Component} from "react";
import DynamicTable from '@atlaskit/dynamic-table';
import styled from 'styled-components';
import { CSVLink, CSVDownload } from "react-csv";
export const createHead = (withWidth) => {
return {
  cells: [
    {
  
      key: 'filterID',
      content: 'Filter ID',
      isSortable: true,
      width: withWidth ? 25 : undefined,
  fontSize: 30,
    },
    {
      key: 'author',
      content: 'Author',
      shouldTruncate: true,
      isSortable: true,
      width: withWidth ? 25 : undefined,
  fontSize: 30,
    },
    {
      key: 'filtername',
      content: 'Filter Name',
      shouldTruncate: true,
      isSortable: true,
      width: withWidth ? 25 : undefined,
  fontSize: 30,
    },
    {
      key: 'jql',
      content: 'JQL',
      shouldTruncate: true,
  isSortable: true,
  width: withWidth ? 25 : undefined,
  fontSize: 30,
    },
  ],
   };
 };

export const shareFilterHead = createHead(true);

export default class ShareFilter extends Component {

constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      shareFilterRows: []
    };
  }

componentDidMount() {
    fetch(AJS.contextPath() + "/rest/securityrestresource/1.0/results?check=ShareFilter")
    .then((res)=>{
        if(res.ok) {
            return res.json();
        }
    }).then((res)=>{
  this.setState({
    isLoaded: true,
    shareFilterRows: res.map((row, index) => ({
      key: `row-${index}-${row.filterID}`,
      cells: [{
        key: `${row.filterID}`,
        content: row.filterID,
        },
        {
        key: `${row.author}`,
        content: row.author,
        },
        {
        key: `${row.filtername}`,
        content: row.filtername,
        },
        {
        key: `${row.jql}`,
        content: row.jql,
        },]}))
  })
  })
  }

render() {
const { error, isLoaded, shareFilterRows } = this.state;
if (error) {
  return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
  return <div>Loading Shared Filters...</div>;
} else {
  return ( 
  <Wrapper>
    <div>
    <DynamicTable
      head={shareFilterHead}
      rows={shareFilterRows}
      rowsPerPage={10}
      defaultPage={1}
      loadingSpinnerSize="large"
      isLoading={false}
      isFixedSize
      defaultSortKey="filterID"
      defaultSortOrder="ASC"
      onSort={() => console.log('onSort')}
      onSetPage={() => console.log('onSetPage')}
      />
      <CSVDownload data={shareFilterRows} target="_blank" />;
  </div>

  </Wrapper>

  
  );
  }
}

}

Add days to event.getTime() in angular

I am trying to add days selected from dropdown. But the dates coming up after adding is way back in 1700s. What am I doing wrong here?

  selectedDays: number = 0;
  //event handler for the select element's change event
  selectDaystoadd (event: any) {
    //update the ui
    this.selectedDays = event.target.value;
    console.log(this.selectedDays);
  }

  formatDateField(event: Date, formControl: string) {
    this.form
      .get(formControl)
      .patchValue(
        this.datePipe.transform(event.getTime() + this.selectedDays, "yyyy-MM-dd'T'HH:mm:ss")
      );
      console.log(event);
  }

HTML code..

     <label>Date</label>
        <input id="input--payout-date"
          class="form-control"
          formControlName="payoutDate"
          [owlDateTime]="payoutDate"
          (dateTimeInput)="formatDateField($event.value, 'payoutDate')"
          [owlDateTimeTrigger]="payoutDate"
        />
        <owl-date-time [pickerType]="'calendar'" #payoutDate></owl-date-time>
        <label>Add days to date</label>
        <select (change)="selectDaystoadd($event)">
          <option value="0">0</option>
          <option value="20">+20</option>
          <option value="50">+30</option>
          <option value="90">+90</option>
        </select>

Dittofi is not saving updates made in the design studio. How do I fix this?

We have been working within the Dittofi platform on a few simple tasks for hours now, as Dittofi is responding very slowly to the changes made in design studio.

When we complete the changes and build the application, it’s not showing all the changes in the app preview output – only partial changes are seen at times. In design studio all the changes can be seen, but not in the output.

Additionally, there is no log in the history. If we refresh the design studio, the changes just made and displayed in the design studio disappear and we have to redo the work again, causing 2x, 3x the amount of work we would spend if we just had coded the app from scratch.

Video that Dittofi is responding slowly to the changes:
https://www.loom.com/share/72ce0b3b804a4673a4e6d58cd706f4f9

Video that all the changes are seen in design studio but not in output:
https://www.loom.com/share/3ea5155b838c4788a671aaa57b9e5c8a

Another video showing issues:
https://www.loom.com/share/bdde1cc5d19b48beaf0468967faa6382

This has been happening randomly for about a week.

I was told by Dittofi to post platform issue support tickets here.

Checking if multiple elements are rendering using jasmine

it('should check if all div are appearing which are dependent on a common condition', () => {
  component.someCommonCondition = true;
  fixture.detectChanges();
  // now the prob lies in line below since it only gets the first element of the mentioned class
  const contentCheck = fixture.debugElement.query(By.css('.someClass'))
  expect() // what to write here to check all 3 divs are getting rendered
})
<div *ngif="someCommonCondition" class="someClass"></div>
<div *ngif="someCommonCondition" class="someClass"></div>
<div *ngif="someCommonCondition" class="someClass"></div>

Greetings, I am trying to write a unit test where i can test if multiple divs are getting rendered which depend on a common condition. I want to know if there is a way to do it in one test rather than writing a test for each of them individually since they all dependent on a common condition. That is, either none of them appear or all of them should.

Where to write the logic for drag and drop functionality in React?

I am writing an application similar to Trello for project management. I want to implement the drag and drop functionality from scratch. ( I know there are other libraries already made for this but I want to customize the behavior )

My simplified components look something like this:

import React, { useState } from "react";

const ListsContainer = () => {
  const [data, setData] = useState([]);

  //fetch data and do stuff on it

  return (
    <div className="lists-container">
      {data.forEach((element) => {
        return <List element={element}/>;
      })}
    </div>
  );
};

export default ListsContainer;
import React from "react";

const List = ({ element }) => {
  //display stuff about the list
  return <div className="list"></div>;
};

export default List;

What I want to do is to be able to click on a List, drag it around inside the ListContainer and drop it in place of another. The problem is that I am unsure of where should I write the logic for this functionality. Right now I see 2 possibilities:

  1. Have the logic in the ListContainer component. The List component would be wrapped using React.forwardRef() and the container would have the references to all the List components. This makes sense because the data is part of this component and the <div className = "lists-container"></div> is needed in order to calculate if I dropped a List in a different spot and the order between them needs to change.
  2. Have the logic in the List component. This just feels more natural. The “drag and drop” functionality is specific to the List and it feels like this is the place where the logic should stay. The problem here would be the fact that I have to pass the data as well as a ref to <div className = "lists-container"></div> from ListContainer down to each List in order to determine from inside the List itself whether or not I dropped it in place of another.

There is also most likely a third option to do a combination of these two but I am not 100% sure how to go about it.

So what do you think the best approach is?

Exception in NodeWeb Kit for Canvas

I am trying to convert my nodejs application into an .exe file. I am stuck with the canvas module(npm install @tensorflow/tfjs canvas). For some reason,nw.js is not able to load this module.

This is the line for which I am getting the error :

const canvas = require("canvas");

And this is the error :

enter image description here

I did go through this but unfortunately it didn’t help.
My node version is : 16.10.10 and nw.js version is : 0.57.1. Using Windows10.

Is there any way in which this can be solved ? Thanks.

Integrating Google’s reCaptcha v3 with Recurly’s JavaSript API

I am using Recurly’s JavaScript API to process subscriptions payments.
I want to implement Google’s reCaptcha V3 API to the Recurly’s self-hosted page.

<script src="https://js.recurly.com/v4/recurly.js"></script>

recurly.configure({
    publicKey : 'xxx-xxx',
    required  : ['cvv', 'address1', 'city', 'state', 'country', 'postal_code'], 
});

// When a customer hits their 'enter' key while in a field
recurly.on('field:submit', function (event) {
    $('form').submit();        
});

// On form submit, we stop submission to go get the token
$('form').on('submit', function (event) {
    // Prevent the form from submitting while we retrieve the token from Recurly
    event.preventDefault();
    // Reset the errors display
    $('#errors').text('');
    $('input').removeClass('error');
    // Disable the submit button
    $('button').prop('disabled', true);
    var form = this;
    // Now we call recurly.token with the form. It goes to Recurly servers
    // to tokenize the credit card information, then injects the token into the
    // data-recurly="token" field above
    recurly.token(form, function (err, token) {
        // send any errors to the error function below
        if (err) error(err);
        // Otherwise we continue with the form submission
        else form.submit();
    });
});

Things is, Google’s API implementation is something like this :

<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
<button type="submit" id="btn-submit" class="g-recaptcha" data-sitekey="xxxxxxxxx" data-callback='onSubmit' data-action='submit'>Submit</button>

<script>
function onSubmit(token)
{
    document.getElementById("recaptchaResponse").value = token;
    document.getElementById("frm-subscribe").submit();
}
</script>

Both have their own version of onSubmit. How do I include Google’s one into Recurly’s ?

How to accept a form from the client side to the server?

I am creating a chat (on nodeJS), I wanted to send data from the form to the server from the registration page, so that the next page (the chat itself) displays the username. I was able to do this through localStorage, but as soon as I started connecting the database, I realized that I couldn’t do without sending it to the server. I was able to do this, but it only passes the value to app.post (that is, the scope is only this method call). I need to get it into a global variable in order to perform checks and send it to the client side. And how to make it so that when the send button is opened, another html page (the chat itself) opens.

index.html

<body>
<a href = "client/chat.html">Тык</a>
    <form action="/index" method="post" class="FORM">
        <label>Username</label><br>
        <input type="TEXT" class="CHECK" autocomplete="off" name="Username"/>
        <button type="submit" onclick="redirect()" class="BTN">Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src = "client/register.js"></script>
</body>

index.js(server)

const express = require('express');
const app = express();
const db = require('./database/database'); // подключаемся к бд
const bodyParser = require('body-parser');
const http = require('http');
const server = http.createServer(app);
const {Server} = require('socket.io');
const io = new Server(server);

const port = 3000;
let id = 0;
let users = {};
const urlencodedParser = bodyParser.urlencoded({
    extended: false,
})   

app.use(express.static(__dirname));
app.get('/index', (request, response ) => {
    response.sendFile(__dirname + '/index.html');
});
app.post('/index', urlencodedParser, function (request,response) {
    if (!request.body) return response.sendStatus(400)
    console.log(request.body.Username) // мне надо чтобы значение Username было в глобальное переменной
})
io.on('connection', (socket) => {
    socket.on('chat message', (msg) => { // событие "сообщение чата"
.....

React Collapsible triggerSibling property gives invalid element type error

I am working on a SharePoint webpart and need to have a collapsible element that I can add a clickable element to. I have a complex class, so for simplicity’s sake, I have created this example webpart that shows the issue. I have tried a number of different things, including things such as creating a component and then setting the triggerSibling property to that, setting it to just a string and adding the content of the const to the triggerSibling property directly. Here is my class.

import * as React from 'react';
import { IHelloWorldProps } from './IHelloWorldProps';
import Collapsible from 'react-collapsible';

export default class HelloWorld extends React.Component<IHelloWorldProps, {}> {
  public render(): React.ReactElement<IHelloWorldProps> {
    const siblingContent = <div><a href="https://www.google.com" target="_blank">Clickable sibling content</a></div>;

    return (
      <Collapsible trigger="Collapsible example" triggerSibling={siblingContent}>
        <p>Some collapsible content</p>
      </Collapsible>
    );
  }
}

I get the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Am I doing something wrong? Or is there a better route I should consider for what I need to do?

React You likely forgot to export your component from the file it’s defined in app.js when rendering functional component

I am trying to render the StockPopup function component in App.js, but I am getting this error:

Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a 

class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check your code at StockPopup.js:10.
    at StockPopup

At StockPopup line 10 is this line:

<Alert.Heading>Warnings</Alert.Heading>

And I’m not sure if this is an error with this line or with importing/exporting. I got the code for the component from the React docs.

App.js

   import './App.css';
    import StockPopup from "./StockPopup";


function App() {
  return (
    <div className="App">
        <StockPopup />
    </div>
  );
}

export default App;

StockPopup.js

import {Alert, Button} from "reactstrap";
import {useState} from "react";

function StockPopup() {
    const [show, setShow] = useState(true);

    if (show) {
        return (
            <Alert variant="danger" onClose={() => setShow(false)} dismissible>
                <Alert.Heading>Warnings</Alert.Heading>
                <p>
                    Low level warnings.
                </p>
            </Alert>
        );
    }
    return <Button onClick={() => setShow(true)}>Dismiss Alert</Button>;
}
export default StockPopup;

Thanks for your help

Why this React child component seems can’t retrieve data from the state? [closed]

I am very new in React.js and I have the following problem trying to implement the following example from a Udemy course.

Fist of all I have this index.html main page:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/style/style.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css">
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAq06l5RUVfib62IYRQacLc-KAy0XIWAVs"></script>
  </head>
  <body>
    <div class="container"></div>
  </body>
  <script src="/bundle.js"></script>
</html>

then I have the related index.js file:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';

import SearchBar from './components/search_bar';
import VideoList from './components/video_list';

const API_KEY = 'MY-YOUTUBE-API-KEY';

class App extends Component {

    constructor(props) {
        super(props);

        this.state = { videos: [] };

        YTSearch({key: API_KEY, term: 'surfboards'}, (videos) => {
            console.log(videos);
            //this.setState({ videos: videos});
            this.setState({ videos });  // if have the 2 variables have the same name can be condensed
            
        })
    }

    render() {
        return  (
            <div>
                <SearchBar />
                <VideoList videos={this.state.videos} />
            </div>
        );
    }

}



// Take this component's generated HTML and put it on the page (in the DOM):
ReactDOM.render(<App />, document.querySelector('.container'));    // This <App /> is an instancve of the App class returned by the function

NOTE: this is preloading some videos calling the YTSearch() and infact the console.log() is showing an array of 5 objects that will be put into the state.

As you can see the previos code contains this render() method:

render() {
    return  (
        <div>
            <SearchBar />
            <VideoList videos={this.state.videos} />
        </div>
    );
}

that renders two sub components that are:

SearchBar: used to search and retrieve videos from Youtube:

import React, {Component} from 'react';

class SearchBar extends Component {

    constructor(props) {
        super(props);

        this.state = { term: 'Starting value' };

    }

    render() {
        return (
            <div>          
                <input 
                    value={this.state.term}
                    onChange={event => this.setState({ term: event.target.value })} />

                Value of the input: {this.state.term}         
            </div>
        );
    }
}

export default SearchBar;

As you can see it put the sarched temes into the React state.

Then I have the VideoList component that should show the list of the retrieved videos, at the moment I have something very minimalist like this:

import React from 'react';

const VideoList = (props) => {
    //const videos = props.videos;
    return(

        <p>Video number: {props.videos.lenght}</p>
    )
}

export default VideoList;

My problem is that this is what I am obtaining:

enter image description here

As you can see the props.videos.lenght seems to be null or something like this.

What is wrong? What am I missing? How can I try to fix it?