postgresql – Postgres 12: Inserting array of composite types, composite type has an array field. Malformed array literal, unexpected end of input

I’m having an issue with inserting a simple array of integers into my table in Postgres via a procedure. The array of integers is declared within a composite type and I’m trying to insert an array of these types via the procedure.

Just to put this out there: this code works without the array of numbers (i.e. if I were to just remove the variable as_ids from the table, composite type, and procedure, the code runs the way its supposed to. for some reason it just doesn’t work with the array).

The table

CREATE TABLE user_ans(
ans_id INT GENERATED ALWAYS AS IDENTITY,
fq_id INT NOT NULL,
p_id INT NOT NULL,
j_id INT NOT NULL,
u_id INT NOT NULL,
d_id INT,
ans TEXT NOT NULL,
as_ids INT() NOT NULL,
created TIMESTAMP,
updated TIMESTAMP
);

The composite type

CREATE TYPE new_ans_obj AS (
    ans TEXT, 
    as_ids INT(),
    created TIMESTAMP,
    d_id INT,
    fq_id INT,
    j_id INT,
    p_id INT,
    u_id INT
);

The procedure

CREATE OR REPLACE PROCEDURE add_ans_arr (
    new_ans new_ans_obj()
)
    LANGUAGE plpgsql
AS $$
BEGIN
    INSERT INTO user_ans(ans, as_ids, created, d_id, fq_id, j_id, p_id, u_id)
    SELECT * from unnest(new_ans);
    COMMIT;
END;$$;

Attempts

Command I use:

call add_ans_arr((ARRAY('(sdf,{2002,2005},2021-01-19T21:48:28.997Z,1001,7001,3,6001,1)', '(sdf,{2002,2005},2021-01-19T21:48:29.626Z,1001,7002,3,6001,1)'))::new_ans_obj());

Output:

ERROR:  malformed array literal: "{2002"
LINE 1: call add_ans_arr((ARRAY('(sdf,{2002,2005},2021-01-19T21:4...
                                   ^
DETAIL:  Unexpected end of input.

Command I use:

call add_ans_arr((ARRAY('(sdf,(ARRAY(2002,2005))::int(),2021-01-19T21:48:28.997Z,1001,7001,3,6001,1)', '(sdf,(ARRAY(2002,2005))::int(),2021-01-19T21:48:29.626Z,1001,7002,3,6001,1)'))::new_ans_obj());

Output:

ERROR:  malformed array literal: "(ARRAY(2002"
LINE 1: call add_ans_arr((ARRAY('(sdf,(ARRAY(2002,2005))::int(),2021...
                                ^
DETAIL:  Array value must start with "{" or dimension information.

Post obvious attempts

I’ve also tried different variations of the two above commands (using parenthesis, putting the size of the array in, etc), but with similar outputs. I’ve read other posts about inserting arrays into Postgres, as well as the documentation and it seems like I’m using the right syntax (although probably not)?

I was thinking that the array of integers might be conflicting with the ‘unnest’ function, so I rewrote the procedure to following, but still the same problem pops up:

CREATE OR REPLACE PROCEDURE add_ans_arr (
    arr new_ans_obj()
)
    LANGUAGE plpgsql
AS $$
DECLARE
    ans_obj new_ans_obj;
BEGIN
    FOREACH ans_obj IN ARRAY arr
    LOOP
        INSERT INTO user_ans(ans, as_ids, created, d_id, fq_id, j_id, p_id, u_id)
        VALUES (ans_obj.ans, ans_obj.as_ids, ans_obj.created, ans_obj.d_id, ans_obj.fq_id, ans_obj.j_id, ans_obj.p_id, ans_obj.u_id);
    END LOOP;
    COMMIT;
END;$$;

I’m able to individually insert these objects into the table:

insert into user_ans(ans, as_ids, created, d_id, fq_id, j_id, p_id, u_id) VALUES ('lala', '{2002}', '2021-01-19T21:48:29.626Z', 1001, 7002, 3, 6001, 1);

But I don’t really understand why the above method isn’t working? I’ve tried putting the single quotes into the my first command, but I just get a syntax error. Also I don’t want to mess too much with the

ARRAY('','')::ans_obj()

structure because it works for the rest of my other procedures, and this structure is generated by my server. Although I’m open to change it the server-side code if there’s something horribly wrong with this structure, but again – it works for the rest of my stored procedures.

Any direction/help would be greatly appreciated.

array nao funciona ao criar polyline leaflet

marker no mapa

Alguem poderia me ajudar, estou com dificuldade para extrair latitude e longitude de array php e adicionar ao mapa leaflet (JavaScript). As coordenadas aparecem conforme print mas os marcadores so puxam uma localização.
———————-SEGUE CODIGO QUE UTILIZO PARA OBTER OS DADOS DO BANCO MYSQL————-

<?php

while ($row = mysqli_fetch_assoc($resultado_alerta)) {

$imei = $row('imei');
$identificacao = $row('identificacao');
$lat = $row('latitude');
$lon = $row('longitude');
$endereco = $row('endereco');
$data = $row('data');
$hora = $row('hora');
$velocidade = $row('velocidade');
$tipo = $row('tipo');

$string = '(' . floatval($row('latitude')) . ', ' .$row('longitude') . ')';

$lats() = $lat;
$lons() = $lon;
}

foreach ($lats as $lat) {
  echo $coords = $lat.",".$lon;
 // echo $lon;
//echo $coord = ($coord);
}

?> 
<script type="text/javascript">
var coord = "<?php echo $coords?>";
var lat = "<?php echo $lat?>";
var lon = "<?php echo $lon?>"
console.log(coord);

var map = L.map('map').setView((lat,lon), 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

L.marker((lat, lon)).addTo(map)
    .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
    .openPopup();


    var coords = ((lat +','+lon));
    for(var i = 0; i < coords.length; i++) {
    console.log(coords(i));
}
var pointA = new L.LatLng(lat, lon);
var pointB = new L.LatLng(lat, lon);
var coords = (pointA, pointB);
        

        //var coord = "<?php echo $coords ?>";
        alert(coords);
        coords.forEach(function(coordinate)
        {

          new L.Marker(coordinate).addTo(map);

          });
    var polyline = L.polyline(coords, {color: 'red', className: 'west_side_drive'}).addTo(map);

    map.fitBounds(polyline.getBounds());


</script>

c++ – Setting an array in the HLSL shader

I have a array of six float4x4’s in my shader.

cbuffer pseudeocb
{
    float4x4 Mypseudo(6);
};

I need to set these in my code.

   ID3DX11EffectMatrixVariable* Pseudo;
    void SetPseudo(CXMMATRIX M)              { Pseudo->SetMatrix(reinterpret_cast<const float*>(&M)); }
   Pseudeo = mFX->GetVariableByName("Mypseudo")->AsMatrix();

This will set one. How do i set six of them? with a SetPseudo function?

Do i just do this?????

XMMATRIX *p = new XMMATRIX(6);

or

XMMATRIX p(6);

php – Como fazer uma array com argumentos que possuem duas variáveis cada?

As linhas abaixo se repetem diversas vezes:

define("NS_CIRCULAR", 3068);
define("NS_CIRCULAR_TALK", 3069);
$wgExtraNamespaces(NS_CIRCULAR) = "Circular";
$wgExtraNamespaces(NS_CIRCULAR_TALK) = "Circular_talk";
$smwgNamespacesWithSemanticLinks(NS_CIRCULAR) = true;

define("NS_DESPACHO", 3070);
define("NS_DESPACHO_TALK", 3071);
$wgExtraNamespaces(NS_DESPACHO) = "Despacho";
$wgExtraNamespaces(NS_DESPACHO_TALK) = "Despacho_talk";
$smwgNamespacesWithSemanticLinks(NS_DESPACHO) = true;

Para economizar linhas, é possível fazer uma array para “define”, uma para “$wgExtraNamespaces” e uma para “$smwgNamespacesWithSemanticLinks” sem quebrar o php?

9 – The “Array” plugin does not exist after saving the order type form in Commerce

After saving any order type, the following error shows:

DrupalComponentPluginExceptionPluginNotFoundException: The "Array" plugin does not exist. Valid plugin IDs for Drupalstate_machineWorkflowManager are: invoice_default, order_default, order_default_validation, order_fulfillment, order_fulfillment_validation, payment_default, payment_manual, shipment_default in DrupalCorePluginDefaultPluginManager->doGetDefinition() (line 53 of core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

Any ideas?

c – Find at what array half of the total sum is and show the value of the each array as it goes

So I have this program where I introduce the number of vehicles made in each month with the array and in the end I´m supposed to get the accumulated amount, the total production and at what month did the company achieve or surpassed half of the production. I will give you an example.

January 450 // February 300 // March 250 // April 300 // May 450 // June 300 // July 250 // August 300 // September 450 // October 300 // November 250 // December 300 //

The result has to show:

Accumulated Ammount:
January 450 // February 750 ( 450 + 300) // March 1000 ( 450 + 300 + 250) and so on.

Total: 3900

Month of half of the production (3900/2= 1950): printf “It was in the month of June”

{
    int months(12), n = 12, i;
    int sum = 0;



        for (i = 0; i < n; i++)
        {
            printf("Final Production of %d: ", (i + 1));
            scanf("%d", &months(i));
            sum += months(i);
        }


    printf("nTotal Production: %dnn", soma);
} ```

javascript – Parse proxy strings to array of objects

The goal of this module is to take in a string (user input, someone copy and pasting a large list of proxies) and parse it into an array of objects.

I appreciate any and all feedback, but I’m specifically interested in improving the stringToProxy function.

Namely I’m unsure about mutating the string parameter, seems like there could be a better solution. And the way I’m declaring the proxy at the beginning of the function feels wrong to me (using As) but I couldn’t think of any better solution. I also feel as though I may be overusing string.split().

Thanks for your time!

interface Proxy {
    host: string;
    port: number;
    auth?: {
        username: string;
        password: string;
    };
    protocol?: string;
}

function parse(string: string): Proxy() {
    const rawArray = stringToArray(string);
    const proxyArray = rawArray.map((string) => stringToProxy(string));
    return proxyArray;
}

function stringToArray(string: string): string() {
    return string.trim().replace(/( ,n)+/g, ",").split(",");
}

function stringToProxy(string: string) {
    const proxy = {} as Proxy;

    if (string.includes("://")) {
        const (protocol, remainder) = string.split("://");
        proxy.protocol = protocol;
        string = remainder;
    }
    if (string.includes("@")) {
        const (auth, remainder) = string.split("@");
        const (username, password) = auth.split(":");
        proxy.auth = { username, password };
        string = remainder;
    }
    const (host, port) = string.split(":");
    proxy.port = parseInt(port);
    proxy.host = host;

    return proxy;
}

export = parse;

const parse = require("parse-proxy");

parse(`1.1.1.1:80, 2.2.2.2:80, 3.3.3.3:80`)

//result
(
  { host: '1.1.1.1', port: 80 },
  { host: '2.2.2.2', port: 80 },
  { host: '3.3.3.3', port: 80 }
)

parse(`https://user:pass@104.236.55.48:8080nhttps://user:pass@213.105.29.14:3128`)

//result 
(
  {
    protocol: 'https',
    auth: { username: 'user', password: 'pass' },
    host: '104.236.55.48',
    port: 8080
  },
  {
    protocol: 'https',
    auth: { username: 'user', password: 'pass' },
    host: '213.105.29.14',
    port: 3128
  }
)

vue.js – Array in post converts to string

in html if you do

<form action="" method="post">
  <select multiple name="items[]">
    <option value.... 

the post result will be an array. With vue, if you do

<input type="hidden" name="items[]" v-model="myArray">

you get back an array with one element containing a string “1,2,3”. Essentially, v-model converts into a string on the post request. How can I get it to post an actual array?

java – help me solve it i want to find the occurrence of number in an array and a combination of same element into an arraylist

I am trying to find the combination of same numbers in an array in java e.g i have number in an array e.g numbers{1,2,2,2,1,1,1,2,2,2,1,1,2,2,2,1,1,1,2,2,1} .So i want the program to check all combinations of number that occurred in a sequence of order only like 1, or 2,2,2 or 1,1,1 or 2,2,2 then it will check how many times did 2 or 1 occur so the occurred number will be stored in an arraylist. In that case first 1 occurred 1 time then 2 occured 3 times then 1 occurred 3 times then 2 occurred 3 times and so on it will show how elements are arranged in an array .i have wrote a code but it is not working in java as i want it to

public class Main {

private static ArrayListPlistItem=new ArrayList();

private static ArrayListNlistItem=new ArrayList();

private static ArrayListPwillhappen=new ArrayList();

private static ArrayListNNhappen=new ArrayList();

private static ArrayList LhappenList=new ArrayList();

private static ArrayList NhappenList=new ArrayList();

private static ArrayList LhappenListTotal=new ArrayList();

private static ArrayList NhappenListTotal=new ArrayList();

private static int Lhappen=0;
private static int Lhappen2=0;

private static int Nhappen=0;
private static int Nhappen2=0;
private static int () items ={1,2,2,2,1,1,1,2,2,2,1,1,2,2,2,1,1,1,2,2,1};
private static int () Nhappenitems =new int(1);
private static int () Lhappenitems =new int(1);

public static void main(String ()args){

PlistItem.add(1);
NlistItem.add(2);

//comparing elements from an array which with an arraylist number
for(int y=0; y<items.length; y++){

if(PlistItem.get(0)==items(y)){
//counter to count how many times 1 occurred
Lhappen++;
//counter to count how many times 1 occurred
Lhappen2++;
//adding the counter in arraylist
Pwillhappen.add(0, Lhappen);

//adding the numbers how many times it occured in arraylist
Lhappenitems(0)=Lhappen2;

//adding in total number it occur in an arraylist
LhappenListTotal.add(0,Pwillhappen.get(0));
//setting the counter into 0
Nhappen=0;

}else if(NlistItem.get(0)==items(y)){
//counter to count how many times 2 occurred
Nhappen++;
//counter to count how many times 2 occurred
Nhappen2++;
//adding the counter in arraylist
NNhappen.add(0,Nhappen);
//adding the numbers how it many times it occurred in arraylist
Nhappenitems(0)=Nhappen2;

//adding in total number it occur in an arraylist
NhappenListTotal.add(0, NNhappen.get(0));
//setting the counter into 0
Lhappen=0;

}

}

System.out.println(” RESULTS ” );
System.out.println(“——————————————————————————–“);
System.out.println(“1 occurrence total “+ Nhappenitems(0) +” times”);
System.out.println(“2 occurence total “+ Lhappenitems(0) +” times”);
System.out.println(“——————————————————————————–“);
for(int i=0; i<LhappenListTotal.size(); i++){
System.out.println(” combination of 1’s occurred “+ LhappenListTotal.get(i) +” times”);

}

System.out.println(“——————————————————————————–“);
for(int i=0; i<NhappenListTotal.size(); i++){

System.out.println(“combination of 2’s occurred “+ NhappenListTotal.get(i)+” times”);
}

}
}

RESULTS

1 occurrence total 11 times

2 occurence total 10 times

combination of 1’s occurred 1 times

combination of 1’s occurred 3 times

combination of 1’s occurred 2 times

combination of 1’s occurred 1 times

combination of 1’s occurred 2 times

combination of 1’s occurred 1 times

combination of 1’s occurred 3 times

combination of 1’s occurred 2 times

combination of 1’s occurred 1 times

combination of 1’s occurred 1 times

combination of 2’s occurred 2 times

combination of 2’s occurred 1 times

combination of 2’s occurred 3 times

combination of 2’s occurred 2 times

combination of 2’s occurred 1 times

combination of 2’s occurred 3 times

combination of 2’s occurred 2 times

combination of 2’s occurred 1 times

combination of 2’s occurred 3 times

combination of 2’s occurred 2 times

combination of 2’s occurred 1 times

my code when i run it is showIng as above results instead i want my results to be as below so help me to solve the code to produce the results as below it show produce the result same as the elements how they are arranged in an array.. items ={1,2,2,2,1,1,1,2,2,2,1,1,2,2,2,1,1,1,2,2,1};

RESULT

combination of 1’s occurred 1 times

combination of 1’s occurred 3 times

combination of 1’s occurred 2 times

combination of 1’s occurred 3 times

combination of 1’s occurred 1 times

combination of 2’s occurred 3 times

combination of 2’s occurred 3 times

combination of 2’s occurred 3 times

combination of 2’s occurred 2 times

spfx webparts – Iterate nested array of objects and append children to a particular object using jQuery/React

Iterate nested array of JSON objects and append children to a particular object using jQuery/React

We are trying to create a tree view navigation using PnP react TreeView control for SharePoint document library using SPFx web part. We are are getting and setting initial data to the component’s state by making an REST call to get first level folders.
Below is the JSON array we are setting to the component state.

TreeLinks: [
    {
          key: UniqueId,
          label: "Training Documents",
          data: ServerRelativeUrl
    }
    {
          key: UniqueId,
          label: "Training Videos",
          data: ServerRelativeUrl
    }
    {
          key: UniqueId,
          label: "Training Events",
          data: ServerRelativeUrl
    }
]

Note: “TreeLinks” is an array of type “ITreeItem” and it is state of the component.
We want to add children to a specific node on select/click event. Suppose we clicked on “Training Documents” and it’s sub folders are “SharePoint, PowerApps, Power Automate, Power BI, SQL”

Expected output.

TreeLinks: [
    {
      key: UniqueId,
      label: "Training Documents",
      data: ServerRelativeUrl,
      children: [
        {
          key: UniqueId,
          label: "SharePoint",
          data: ServerRelativeUrl
        }
        {
          key: UniqueId,
          label: "PowerApps",
          data: ServerRelativeUrl
        }
        {
          key: UniqueId,
          label: "Power Automate",
          data: ServerRelativeUrl
        }
        {
          key: UniqueId,
          label: "Power BI",
          data: ServerRelativeUrl
        }
        {
          key: UniqueId,
          label: "SQL",
          data: ServerRelativeUrl
        }
      ]
    }
    {
      key: UniqueId,
      label: "Training Videos",
      data: ServerRelativeUrl
    }
    {
      key: UniqueId,
      label: "Training Events",
      data: ServerRelativeUrl
    }
]

and if we click further on “PowerApps” node, expected output

TreeLinks: [
    {
      key: UniqueId,
      label: "Training Documents",
      data: ServerRelativeUrl,
      children: [
        {
          key: UniqueId,
          label: "SharePoint",
          data: ServerRelativeUrl
        }
        {
          key: UniqueId,
          label: "PowerApps",
          data: ServerRelativeUrl,
          children: [
            {
              key: UniqueId,
              label: "Canvas Apps",
              data: ServerRelativeUrl
            }
            {
              key: UniqueId,
              label: "Model Driven Apps",
              data: ServerRelativeUrl
            }
            {
              key: UniqueId,
              label: "Portal Apps",
              data: ServerRelativeUrl
            }
          ]
        }
        {
          key: UniqueId,
          label: "Power Automate",
          data: ServerRelativeUrl
        }
        {
          key: UniqueId,
          label: "Power BI",
          data: ServerRelativeUrl
        }
        {
          key: UniqueId,
          label: "SQL",
          data: ServerRelativeUrl
        }
      ]
    }
    {
      key: UniqueId,
      label: "Training Videos",
      data: ServerRelativeUrl
    }
    {
      key: UniqueId,
      label: "Training Events",
      data: ServerRelativeUrl
    }
]

IMPORTANT: Nesting can be upto n number of levels.

Requesting to help us out on adding children to nested array of JSON objects dynamically.

For information about TreeView control please see this link