How do I return value modified by an AFTER INSERT trigger in Knex.js?

I want to get back a value after I insert my data

const data = {name: "Christmas Shirt 1", price: 5.99, sku: "20210911S", warehouse_id: 2}

const skuCode = await query.returning(['sku_code'], {includeTriggerModifications:true}).insert(data);

console.log(skuCode) // ["20210911-NY"];

However, the table that I’m inserting into has a AFTER INSERT trigger that will append a prefix to the sku_code field:

CREATE TRIGGER inventory_trigger
ON inventory AFTER TRIGGER AS
BEGIN
  UPDATE t
  SET sku_code = CASE t.warehouse 
    WHEN 1 THEN t.sku_code + "NV"
    WHEN 2 THEN t.sku_code + "NY"
  END
  FROM inventory t
  JOIN inserted i ON t.id = i.id
END

Is there a way for me to get the value after the AFTER INSERT trigger using Knex’s returning()? I know I can add similar logic in my JS code that manually prepends the prefix but I don’t want to duplicate the logic.

How to load two external files in D3.js version 7?

To load one TopoJson file in D3 version 7 is simple as:

d3.json("file01.json").then(function(topology) {

To load two files in previous versions you could use for example in version 6:

Promise.all([
    d3.json("file01.json"),
    d3.json("file02.json", function(d) {
        data.set(d.code, +d.pop)
    })
]).then(function(loadData){

and in version 4, for example:

d3.queue()
  .defer(d3.json, "file01.json")
  .defer(d3.json, "file02.json", function(d) { data.set(d.code, +d.pop); })
  .await(ready);

I tried both in version 7 and received the notice that promisse or queue are not a function. So I interpreted that in version 7 there’s another way to load two external files.

Thanks for any help which I couldn’t find until now, despite searching all over the in Internet. There’s a lot of material about version 3 to 6, but much less to version 7.

Count the number of values

Here is a task to count the number of true in each age:

users = {
 // ...
 age = x; // random number
 sport_life true; // or false
 // ...
}

And display it in a chart (chart.js). Here is how to update.
I don’t know how to put it all together. Thanks in advance!

Google Sheets: How do I list rows of data copied from another sheet consecutively, in order, and without overwriting current data through scripting?

I’m kind of new to working with Google Sheets, and I’ve stumbled across an issue while creating buttons for a ticket system. I’ve been having trouble getting the copied data to just fill the other sheet from the second row and down without gaps or overwriting existing data.

The script basically checks if a checkbox of a certain row is ticked, copies the data in that row, moves that data to another sheet, and then resets that row to it’s original state. Meaning it doesn’t completely delete the row or format, but only copies the contents.

Here’s the code I’ve been working with so far:

function MigrateInProgress() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();  
    var s = ss.getSheetByName('Copy of New Tickets');
    var s2 = ss.getSheetByName('In Progress');
    var r = s.getRange('G:G');    
    var v = r.getValues();  
    var dataset = [];
for(var i=v.length-1;i>=0;i--) 
    if(v[0,i]=='true') { 
        var data = s.getRange(i+1,1,1,6).getValues(); 
        s2.getRange(i+1,s2.getLastColumn()-6,data.length,6).setValues(data); 
        var datasetrange = s.getRange(i+1,1,1,6);
        datasetrange.clear({contentsOnly: true});
        datasetrange.clear({formatOnly: false});
        s.getRange(i+1,7).setValue(false);    
  }
}

Here’s some screenshots to help contextualize what I mean:

Screenshot 1

Screenshot 2

Screenshot 3

Any help would be greatly appreciated. Thank you!

Mobile browser positions elements as if the view is 360px wide, but renders images on the page at a higher resolution. How does this work?

I was having a hard time figuring out how to phrase this. Sorry if this is a noob question, I’m new to responsive design and mobile web design in general.

My phone (Galaxy s10e) will render my webpage as if it’s 360 pixels wide, with all elements positioned appropriately based on this width. I have several image tags on the site that are the same width. I was using src images that are 360px wide, and this looks fine on desktop because it is actually rendering my images at 360px, but on mobile the images alone appear to be rendering at a much higher resolution, causing it to look terrible due to upscaling.

If someone could explain to me what is happening here it would really help, since I can’t find information on this specific behavior. Some questions I have:

  • Is the browser choosing to position the elements based on a 360px width while rendering the actual content at the screen’s resolution?
  • How do I account for this in my design? I considered rendering the images at the higher resolution and then having the page dynamically scale those images down (so even though the actual div is 360px, the browser can use the ‘extra space’ allotted by max-width to render the image at a higher resolution), but I want the images to remain 360px wide on desktop, not the higher max-width for mobile rendering.
  • Where can I learn all about this behavior so I know how to tackle responsive image scaling in the future?

Thank you for your time. Let me know if you have any other questions. I’m using ReactJS to develop the site.

Need help transforming GraphQL results

A returned schema looks like the following:

{
    data: {
        posts: {
            edges: [
                {
                    post: {
                        id: ‘1’,
                        title: ‘Foo’
                    },
                    post: {
                        id: ‘2’,
                        title: ‘Bar’
                    }
                }
            ]
        }
    }
}

This works and I can use it, but I’m having to create nested interfaces unfortunately.

Question: Can I either simplify the returned results OR transform them with JavaScript map()?

Ideally, I’d like for the GQL response (or resulting object) to be like:

{
    data: {
        posts: [
            post: {
                id: ‘1’,
                title: ‘Foo’
            },
            post: {
                id: ‘2’,
                title: ‘Bar’
            }
        ]
    }
}

Note: I do not have the ability to update the server-side GraphQL schema. The solution must be client/consumer side.

Thanks!

Merge two array of objects not based on key

I want to marge two arrays not based on key

Array1

[
  { size: "45", color: "red" }, 
  { size: "48", color: "blue" }
]

Array2

[
  { designation: "short", price: "540" }, 
  { designation: "jeans", price: "600" }
]

I need to merge these two arrays and expected this array

[
  { size: "45", color: "red", designation: "short" }, 
  { size: "48", color: "blue", designation: "jeans" }
]

How can do it?

Problem, react-lazyload render all components at once

Hi I’m using Marvel API and I have this:

export default function App() {
  const [characters, setCharacters] = React.useState([]);
  
  const items = characters.map((character, idx) => (
    <LazyLoad key={idx} once throttle={2000} height={"300"}>
      <Character
        img={
          character.thumbnail.path +
          "/standard_xlarge." +
          character.thumbnail.extension
        }
        name={character.name}
      />
    </LazyLoad>
  ));

  React.useEffect(() => {
    fetch(
      "https://gateway.marvel.com/v1/public/characters?ts=1&apikey=e8aa37188987325dca0c570b01707e2c&hash=d784691874995aae3b9fb373b5a4d1da&limit=50"
    )
      .then((response) => response.json())
      .then((data) => setCharacters(data.data.results));
  }, []);

  React.useEffect(() => {
    forceCheck();
  });

  return (
    <div className="App">
      <h1>My Hero's</h1>
      <div>{characters.length ? items : null}</div>
    </div>
  );
}



function Character({ img, name }) {
  return (
    <div style={{ height: "300px", width: "200px", backgroundColor: "purple" }}>
      <h3>{name}</h3>
      <img height="200" width="200" src={img} />
    </div>
  );
}

My problem is that when the fetch loads all the data the lazyload components load all at once. Pls Help me. I’m using react-lazyload

My codesandbox

How to get the number of elements for elements that satisfy a condition

I’m having a problem. I have an array as shown below:

0: {type: 'Text', id_a: '123789', value: 'The fifth chapter of the World Première Ducati will be held at the Expo Dubai on December 9th.', number: 2, id: 7}
1: {type: 'Image', id_a: '123789', value: 'b_desertx-dwp2022-2-uc336332-high.jpg', number: 3, id: 8}
2: {type: 'Video youtube', id_a: '123789', value: 'https://youtu.be/SnuyDoXxC4g', number: 5, id: 10}
3: {type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
4: {type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video', number: 2, id: 2}

Of these I want, for example, to take those that have an id_a equal to 123456 and have me return the value (therefore, referring to id_a = 123456 it must return the two relative arrays) then

3: {type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
4: {type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video', number: 2, id: 2}

Except I get this below

{type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
{type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all her secrets with our video', number: 2, id: 2}

without the numbering in order to be able to retrieve the value (therefore using the value attribute) of each of them.

How can I do this?

   var myArr = JSON.parse(this.responseText);
   for(var i = 0, len = myArr.Items.length; i < len; i++){           
        var id_art = myArr.Items[i].id_a;
        if(id_art == 123456) {
            myArr.Items[i];
            console.log(myArr.Items[i]);
   }

Mongoose pre and post hooks do not work on models created with Model.discriminator

I am using mongoose 6.1.5.

I have a collection containing multiple types of related documents. Here is parameter-descriptor-item.model.js

const mongoose = require('mongoose');

const { Schema } = mongoose;

/** @summary The schema for a parameter item */
const itemSchema = new Schema({
  _id: String,
  name: Object,
});

itemSchema.pre(/^find/, function () {
  // eslint-disable-next-line no-console
  console.log('item pre hit');
});

/** @summary The base model for all parameter items */
module.exports = mongoose.model('Parameters', itemSchema);

ParameterDescriptor model inherits from ParameterDescriptorItem. Here is parameter-descriptor.model.js

const mongoose = require('mongoose');
const ParameterDescriptorItem = require('./parameter-descriptor-item.model');

const { Schema } = mongoose;

/** @summary The schema for additional fields for a project */
const parameterSchema = new Schema({
  direction: {
    type: String,
    enum: ['in', 'out'],
    required: true,
  },
  default: {
    type: Number,
    required: true,
  },
  min: {
    type: Number,
    required: false,
  },
  max: {
    type: Number,
    required: false,
  },
  unit: {
    type: String,
    required: false,
  },
});

parameterSchema.pre(/^find/, function () {
  // eslint-disable-next-line no-console
  console.log('parameter pre hit');
});


/** @summary The model for a parameter descriptor */
module.exports = ParameterDescriptorItem.discriminator('Parameter', parameterSchema);

And here is code to test the use of pre hooks.

const ParameterDescriptorItem = require('./parameter-descriptor-item.model');
const ParameterDescriptor = require('./parameter-descriptor.model');

await ParameterDescriptorItem.find();
// console shows: 'item pre hit'
await ParameterDescriptor.find();
// there is nothing additional in the console. Neither the 'pre' hooks from
// ParameterDescriptorItem or ParameterDescriptor is called.

This is a significant issue for me. Is there a way to address it? Is there a way to add pre and post hooks to models created with Model.discriminator?