Asp.net Core url action in javascript

Right now i’m using asp.net core mvc than using datatable for displaying data. I’ve an Edit action button when cliked it redirect to another page, what i want to ask is if there is a better way than the one I’m using now.

"render": function (data) {
           return `<div class="text-center">
                        <a onclick='Edit("/Admin/Category/Upsert/${data}")' 
                           class="btn btn-success text-white" style="cursor:pointer">
                           <i class="fas fa-edit"></i>
                        </a></div>';

And for the javascript

function Edit(data) {
window.location.href = data;}

How to push every attribute found to an array?

The following structure:

<div id="find_all_children_attributes">
    <div class="child" id="1"></div>
    <div class="child" id="2"></div>
    <div class="child" id="3"></div>
    <div class="child" id="4"></div>
</div>

I managed to get the first one:

let attributes = $('#find_all_children_attributes').find(".child").attr("id");

But how can I get all ids in an array?

How to sort by Numbers first then Alphabetical

I’m trying to sort an array:

["B3", "D2", "F1", "A9", "D12", "A2", "C1", "Z0", "B1"]

The expected output should be:

["Z0", "B1", "C1", "F1", "A2", "D2", "B3", "A9", "D12"]

Here’s my code:

let array = ["B3", "D2", "F1", "A9", "D12", "A2", "C1", "Z0", "B1"];
let collator = new Intl.Collator(undefined, {
  numeric: true,
  sensitivity: "base",
});
console.log(array.sort(collator.compare));

The output is then sorted by Alphabet first, which gives:

["A2", "A9", "B1", "B3", "C1", "D2", "D12", "F1", "Z0"]

So I figured out that if I switch the position of ever value like this:

["3B", "2D", "1F", "9A", "12D", "2A", "1C", "0Z", "1B"]

And then pass it in collator again, it’ll give me the correct sorted sequence, but just that the number and letters are flipped. I’ll then have to flip them back. Is there a better way of doing this?

Error: Objects are not valid as a React child If you meant to render a collection of children, use an array instead. Why?

Why I got this error?

Error: Objects are not valid as a React child (found: object with keys {id, unitPrice, organizationId, passTypeId, sellerPaymentId, createdAt, BarionPOSKey, passTickets, userId, userName, capacity, validatedAt, paymentOrPass, organizationName, imgId, sellerPaymentProvider, status, paymentId}). If you meant to render a collection of children, use an array instead.

I have this types:

export type BuyTicket2OutData = {
  price?: string;
  pricingOptions?: PricingOptions;
  pass: Pass;
};

export type Pass = {
  id: string;
  passTypeId: string;
  paymentId: string;
  createdAt: string;
  validatedAt: string;
  sellerPaymentId: string;
  organizationName?: string;
  userId: number;
  userIdFb?: string;
  userName?: string;
  unitPrice: string;
  status?: string;
  capacity: number;
  passTickets: {
    [eventTimeId: string]: PassTicket;
  };
  imgId?: string;
};
axios({
  method: "post",
  url: "buyTicket2",
  data: data,
  headers: {
    "Content-Type": "application/json",
    crossDomain: true,
  },
}).then((res) => {
  setBuyTicketData2(res.data.data); // <--- got here the error
});

This is the useState:

  const [buyTicketData2, setBuyTicketData2] = useState<
    BuyTicket2OutData | undefined
  >(undefined);

See those values here:
enter image description here

issue in multiple implementations of ngb-typeahed on same page using angular custom directive

I am using ngb-typeahed in my angular11 project, I have directive which has typeahed control which is being rendered repeatedly using ng-for,
I have requirement of showing all the available options in typeahed as soon as user click / focus on the control and then gradually filter the list based on users input,
I am able to do this using following code


  <div class="mt-3 mb-2">
    <div class="row d-flex flex-column justify-content-center">
      <div class="col">
        <div class="mt-1 mb-4" style="padding-left: 37px" *ngFor="let pl of model.previousplDetails; let i = index">
          <div class="row my-3">
            <div class="col col-md-10">
              <div class="row">
                <div class="col col-md-1">
                  <div class="d-flex justify-content-center">
                    <img class="coverage-image" [src]="pl.coverage.imageId" alt="">
                  </div>
                </div>
                <div class="col d-flex align-items-center">
                  <h6>{{ pl.coverage.name }}</h6>
                </div>
              </div>
            </div>
          </div>
          <div class="row mb-3">
            <div class="col col-md-6 p-2">
              <label for="currentCarrier1" [ngClass]="!pl.isValid?'required':''">Current Carrier</label>
              <div>
                <input type="text" placeholder="Type here" class="form-control" [(ngModel)]="pl.carrier"
                       #currentCarrier="ngModel"  name="currentCarrier{{i}}" id="currentCarrier{{i}}"
                       [ngbTypeahead]="search" [inputFormatter]="formatter"
                       [resultFormatter]="formatter" [editable]='false' (selectItem)="onCarrierSelectItem($event);"
                       [appRequiredIf]="!pl.isValid"
                       [placement]="i > model.previousplDetails.length - 3 ? 'top-left' : 'bottom-left'"
                       [disabled]="isInReadonlyMode" (ngModelChange)="onModelChange(i, 'currentCarrier')"
                       (focus)="focus$.next($any($event).target.value)"
                       (click)="click$.next($any($event).target.value)"
                       autocomplete="nope">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
formatter = (modal: CarrierModel) => modal.name;
  @ViewChild('instance', {static: true}) instance: NgbTypeahead;
  focus$ = new Subject<string>();
  click$ = new Subject<string>();

  search: (text$: Observable<string>) => Observable<CarrierModel[]> = (text$: Observable<string>) => {
    const debouncedText$ = text$.pipe(debounceTime(200), distinctUntilChanged());
    const clicksWithClosedPopup$ = this.click$.pipe(filter(() => !this.instance.isPopupOpen()));
    const inputFocus$ = this.focus$;

    return merge(debouncedText$, inputFocus$, clicksWithClosedPopup$).pipe(
      map(term => (term === '' ? this.carrierList
        : this.carrierList.filter(carrier => new RegExp(term, 'i').test(carrier.name) ||
          new RegExp(term ? 'No Current Coverage':'', 'i').test(carrier.name) ||
          new RegExp(term ? 'Do not know':'', 'i').test(carrier.name)))));
  }

with this code I am able to do achieve what I want to do, but there is one issue with this implementation, that is I have used ng-for here and hence I have multiple typeaheads linked with same subjects (focus$, click$) this causes showing options for all typeaheads when I click one of it.
Is there any way to tackle this situation?
Any help on this is highly appreciated
Thanks in advance.

React State Improvement

Can we write the code in a shorter version?

For example:

function Account() {
  const [code, setCode] = useState('')
  
  return <input onChange={(e) => setCode(e)} />
}

Could we do it even more shorter like without creating new function? Like:

<input onChange={setCode} />

Some way?

Best!

Transpile React app to make it appear in a modal

I’ve got a (small) React app (vanilla create-react-app), that I would like to appear in a modal (bootstrap or similar) on another site. Is there a library that will simplify this process?

Specifically, the entire use case is that if my Javascript file is loaded (and just one javascript file), it will insert a “Click Me” type call to action, and when clicked my App component will be loaded into a new modal. It will need the CSS (for the app) to be included in some form as well.

I think all of this (excluding the call-to-action which is fairly simple) could be done during Babel/Webpack transpilation but I can’t find anything off-the-shelf that seems to do this.

Passing parameters with comma values (European decimal format)

I have written a reusable function in Cypress:

fill_prices_ht_nt(until, AP, GP, AP_NT, new_bonus){
        this.add_range().click({force:true})
        this.range_until().type(until)
        this.ap().type(AP)
        this.gp().type(GP)
        this.ap_nt().type(AP_NT)
        this.new_bonus().type(new_bonus)

Now I want to use that function to type in values, but unfortunately I need to type in decimal values in European format (with comma instead of periods), like e.g. “9,35” or “6,47”

        pmmt.fill_prices_ht_nt(99999, 10, 9,35, 6,47, 100)

This is of course not working as Cypress/JS treats every comma as a separator.

Is there a somewhat easy workaround to this problem? Otherwise I will have to dump the reusable function and hard-code the values.

How to run knex migrations with JavaScript instead of CLI?

I have created four postresql tables. I am using nodejs with knexjs as a query builder.

I can create and execute migrations with the command line without any problems. Now I want to run migrations via Javascript. How can I proceed with this?

Here is my code: –

module.exports.runDBMigrations = async () => {
    knex.schema.hasTable(USERS_DB_NAME).then(function (exists) {
        if (!exists) {
            //Execute migrations to create users tables
        }
    })
        .catch(e => {
            console.log("Error creating tables: ", e);
        })

    knex.schema.hasTable(POSTS_DB_NAME).then(function (exists) {
        if (!exists) {
            //Execute migrations to create posts tables
        }
    })
        .catch(e => {
            console.log("Error creating tables: ", e);
        })

    knex.schema.hasTable(LIKES_DB_NAME).then(function (exists) {
        if (!exists) {
            //Execute migrations to likes users tables
        }
    })
        .catch(e => {
            console.log("Error creating tables: ", e);
        })

    knex.schema.hasTable(FOLLOWERS_DB_NAME).then(function (exists) {
        if (!exists) {
            //Execute migrations to create followers tables
        }   
    })
        .catch(e => {
            console.log("Error creating tables: ", e);
        })

}

how to make a form validation and then submit form in vue.js?(without plugins)

I have this form and I want to make a validation on it but after i press submit button it doesn’t check validation and send new data to to another component.how can I fix validation?

thank you for your help.

this is htmlcode and form:

    <form @submit.prevent="handleSubmit">
      <input type="text" required placeholder="name" v-model="firstName" />
      <div v-if="firstNameError" class="error">{{ firstNameError }}</div>
      <input type="text" required placeholder="lastname" v-model="lastName"/>
      <div v-if="lastNameError" class="error">{{ lastNameError }}</div>
      <input type="tel" required placeholder="mobilenumber" v-model="Mobile" />
      <div v-if="MobileError" class="error">{{ MobileError }}</div>
      <input type="tel" required placeholder="phonenumber" v-model="phone" />
      <div v-if="PhoneError" class="error">{{ PhoneError }}</div>
      <input type="text" required placeholder="address" v-model="address" />
      <div v-if="addressError" class="error">{{ addressError }}</div>
      <select v-model="gender">
        <option value="female">خانم</option>
        <option value="male">آقا</option>
      </select>
      <button>submit</button>
    </form>

and script code:

<script>
export default {
  data() {
    return {
      firstName: "",
      lastName: "",
      Mobile: "",
      phone: "",
      address: "",
      gender: "",
      firstNameError: "",
      lastNameError: "",
      MobileError: "",
      PhoneError: "",
      addressError: "",
    };
  },
  methods: {
    handleSubmit() {
        this.firstNameError =
          this.firstName.length > 3
            ? ""
            : "firstName must have at least 3 character";

        this.lastNameError =
          this.lastName.length > 3
            ? ""
            : "lastName must have at least 3 character";

        this.MobileError =
          this.Mobile.length > 11
            ? ""
            : "number must have at least 11 character";
        this.PhoneError =
          this.phone.length > 11
            ? ""
            : "number must have at least 11 character";
        this.addressError =
          this.address.length > 5
            ? ""
            : "address must have at least 5 character";
        let project = {
          firstName: this.firstName,
          lastName: this.lastName,
          Mobile: this.Mobile,
          phone: this.phone,
          address: this.address,
          gender: this.gender,
        };
        console.log(project);
        fetch("http://localhost:8000/forms", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(project),
        })
          .then(() => {
            this.$router.push("/");
          })
          .catch((err) => console.log(err));
      
    },
  },
};
</script>

How to get live OHLC market data smartAPI

I’ve been trying to get the live OHLC market data (basically market starts at 9:30 am to 3:30 pm, time: Asia/Kolkata (Region – India)). I tried smartAPI which provides us an API for algo trading such as HistoricalData getLtpData, but when I tried getLtpData the live candle data was wrong (plus always same values, not changing at all) when I compared to zerodha/NSE website. The library/API which I’m currently using: https://smartapi.angelbroking.com/docs

Issue: https://github.com/angelbroking-github/smartapi-javascript/issues/13

https://smartapi.angelbroking.com/docs/Orders#ltp

var axios = require('axios');
var data = JSON.stringify({
    "exchange":"NSE",
    "tradingsymbol":"SBIN-EQ",
    "symboltoken":"3045"
});

var config = {
  method: 'post',
  url: 'https://apiconnect.angelbroking.com/ 
  rest/secure/angelbroking/order/
  v1/getLtpData',

  headers: { 
    'Authorization': 'Bearer AUTHORIZATION_TOKEN', 
    'Content-Type': 'application/json', 
    'Accept': 'application/json', 
    'X-UserType': 'USER', 
    'X-SourceID': 'WEB', 
    'X-ClientLocalIP': 'CLIENT_LOCAL_IP', 
    'X-ClientPublicIP': 'CLIENT_PUBLIC_IP', 
    'X-MACAddress': 'MAC_ADDRESS', 
    'X-PrivateKey': 'API_KEY'
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

So, how can I fetch live OHLC data when the market starts?

Are there any other alternatives to this?

I’m in desperate need of help!

Javascript Grid/List View issue with initial page load

For my shop page I have a grid view with two columns and options to switch to list view. It’s all working well except when the page initially loads; the products are displaying in four columns.

var elements = document.getElementsByClassName("product");
var image = document.getElementsByClassName("attachment-woocommerce_thumbnail size-woocommerce_thumbnail jetpack-lazy-image jetpack-lazy-image--handled lazyloaded");
var i;

function listView(){
  for(i = 0; i < elements.length; i++){
      elements[i].style.width = "100%";
      elements[i].style.height = "15.1vw";
      image[i].style.width = "29%";
      
  }
}

function gridView(){
  for(i = 0; i < elements.length; i++){
      elements[i].style.width = "35%";
      elements[i].style.height = "35vw";
      image[i].style.width = "100%";

      
  }
}

I removed the default style. Is there a way to create a function to run a style only when the page initially loads?