Padding multi-dimensional array to its max shape

For some machine learning purpose, I need to work with sequences with different lengths. To be able to process efficiently those sequences, I need to process them in batches of size size_batch. A batch typically has 4 dimensions and I want to convert it to a numpy’s ndarray with 4 dimensions. For each sequence, I need to pad with some defined pad_value such that each element has the same size: the maximal size.

For example with 3 dimensional input:

[[[0, 1, 2],   [3],   [4, 5]],  [[6]],  [[7, 8],   [9]]] 

desired output for pad_value -1 is:

[[[0, 1, 2],   [3, -1, -1],   [4, 5, -1]],  [[6, -1, -1],   [-1, -1, -1],   [-1, -1, -1]]  [[7, 8, -1],   [9, -1, -1],   [-1, -1, -1]]] 

which has shape (3, 3, 3). For this problem, one can suppose there are no empty list in the input. Here is the solution I came up with:

import numpy as np import itertools as it from typing import List  def pad(array: List, pad_value: np.int32, dtype: type = np.int32) -> np.ndarray:     """ Pads a nested list to the max shape and fill empty values with pad_value      :param array: high dimensional list to be padded     :param pad_value: value appended to     :param dtype: type of the output     :return: padded copy of param array     """     # Get max shape     def get_max_shape(arr, ax=0, dims=[]):         try:             if ax >= len(dims):                 dims.append(len(arr))             else:                 dims[ax] = max(dims[ax], len(arr))              for i in arr:                 get_max_shape(i, ax+1, dims)         except TypeError:  # On non iterable / lengthless objects (leaves)             pass          return dims      dims = get_max_shape(array)      # Pad values     def get_item(arr, idx):         while True:             i, *idx = idx             arr = arr[i]             if not idx:                 break         return arr      r = np.zeros(dims, dtype=dtype) + pad_value     for idx in it.product(*map(range, dims)):         # idx run though all possible tuple of indices that might          # contain a value in array         try:             r[idx] = get_item(array, idx)         except IndexError:             continue      return r 

It does not feel really pythonic but does the job. Is there any better way to do it I should know ? I think I might be able to improve its speed by doing smart breaks in the last loop but I haven’t dug much yet.

Thanks !

How to generate specific array of strings?

I have the following problem. I have an array:

const dates = ["19-June-2019", "18-June-2019", "17-June-2019", "16-June-2019", "14-June-2019"] 

I need to generate an array of date that are after I mean dates in row. So:

const datesInRow = ["19-June-2019", "18-June-2019", "17-June-2019", "16-June-2019"] 

Here is my initial function: (isAfter function = date-fns)

 function numberOfDaysInRow(arr) {   if (arr.length === 1) return arr;   let numberOfDaysInRowArr = [];   for (let i = 0; i < arr.length; i++) {     if (isAfter(new Date(arr[i]), new Date(arr[i + 1]))) {       numberOfDaysInRowArr.push(arr[i]);     }   }   return numberOfDaysInRowArr; } 

This returns only partial answer. For example If I have only two string in array like this:

const dates = ["19-June-2019", "18-June-2019"] 

It will return

["19-June-2019"] 

which is not what I want. Can someone help me how to solve this problem? Thank you.

Array que divide em outros 2 array

Qual o erro aqui? Na hora de exibir os vetores ele volta pro menu

/*Faça um programa que leia os dados de 10 alunos (nome, matricula, média final), armazenados num vetor. Uma vez lido os dados, divida estes dados em 2 novos vetores, o vetor dos aprovados e o vetor dos reprovados. Considere a média mínima para a aprovação como sendo 6.0. Exibir na tela os dados do vetor de aprovados, seguido dos dados do vetor de reprovados. */ #include <stdio.h> #include <string.h> #define tf 2   struct medialunos {     int matricula;     char nome[20];     double mediafinal;  };  void leitura (struct medialunos vet[tf], struct medialunos vt1[tf], struct medialunos vt2[tf], int cont1, int cont2){     int i;     for (i=0;i<tf;i++){             printf ("\nEntre com a matricula: ");             scanf ("%d", &vet[i].matricula);              printf ("\nEntre com o nome: ");             fflush (stdin);             fgets (vet[i].nome,20,stdin);              printf ("\nEntre com a media final: ");             scanf ("%lf", &vet[i].mediafinal);             printf ("\n_____________________________________________\n");              if (vet[i].mediafinal >= 6){                 vt1[cont1] = vet[i];                 cont1++;          }             else {             vt2[cont2] = vet[i];             cont2++;         }     } }  void exibevet (struct medialunos vetor[tf]){     int i;     for (i=0;i<tf;i++){         printf ("\nMatricula do aluno: %d", vetor[i].matricula);         printf ("\nNome do aluno: %s", vetor[i].nome);         printf ("\nMedia do aluno: %.2lf", vetor[i].mediafinal);         printf ("\n___________________________________________________\n");     } }  void aprovados (struct medialunos vt1[tf], int cont1){     int i;     for (i=0;i<cont1;i++){         printf ("\nAprovado!");         printf ("\nMatricula do aluno: %d", vt1[i].matricula);         printf ("\nNome do aluno: %s", vt1[i].nome);         printf ("\nMedia do aluno: %.2lf", vt1[i].mediafinal);     }    }  void reprovados (struct medialunos vt2[tf], int cont2){     int i;     for (i=0;i<cont2;i++){         printf ("Reprovado!");         printf ("\nMatricula do aluno: %d", vt2[i].matricula);         printf ("\nNome do aluno: %s", vt2[i].nome);         printf ("\nMedia do aluno: %.2lf", vt2[i].mediafinal);     } }  int main (){     struct medialunos vt[tf];     struct medialunos vt1[tf], vt2[tf];     int cont1=0, cont2=0;     int opcao = 0;      while (opcao != 5){          printf ("\n\n################ MENU ##########################");         printf ("\n1 - Leitura dos alunos");         printf ("\n2 - Exibir todos os alunos");         printf ("\n3 - Exibir Vetor Aprovados");         printf ("\n4 - Exibir Vetor Reprovados");          printf ("\n5 - Sair");         printf ("\n\nQual a sua opcao? ");         scanf ("%d", &opcao);          switch (opcao){             case 1: leitura (vt, vt1, vt2, cont1, cont2);                     break;              case 2: exibevet (vt);                     break;               case 3: aprovados (vt1, cont1);                     break;              case 4: reprovados (vt2, cont2);                     break;               default:                      printf ("\nOpcao invalida!");         }      }  } 

Take k numbers from the array and xor them with x to get maximum sum

Given an array A of n numbers and integers k and x. We can perform the following operation any number of times (including zero times). Take exactly k numbers from the array and replace each of them after doing xor with x . For example, we took ith element among k elements, we will replace Ai with Ai ⊕ x . We wish to maximize the sum of elements in the array.

https://www.codechef.com/problems/LENTMO

I’ve seen the editorial, I am hoping a simpler explanation here.

Mongo aggregation on array values

I have a mongo document like this:

{  "_id":"5cfe7767f4046327ad57ec33",  "area":"Actor",   "profile":{    "about":true,     "gallery":true,    "characteristics":[      "Gender": true,      "Height": false,      "Weight": false    ]  } } 

And another one like this:

{  "_id":"5cfe7767f4046327ad57ec33",  "characteristic":"Gender",   "items":["Female","Male"] } 

I want to aggregate the characteristics from the first document that are true with the values of the other document. Something like this:

{  "_id":"5cfe7767f4046327ad57ec33",  "area":"Actor",   "profile":{    "about":true,     "gallery":true,    "characteristics:[      "Gender": ["Female","Male"],      "Height": false,      "Weight": false    ]  } } 

Is it possible?

from given array create new array with length

I’m learning “Go language” and enjoy its simplicity.

I have written code and Benchmarking for the very small problem in go,

The problem is let’s suppose I have given array [1,2,3,5] and length is 10. so here function f takes two parameters array and length f(array, length) and produce the output [1,2,3,4,4,3,2,1,1,2]

so input is f([1,2,3,4], 10)

and produce output [1,2,3,4,4,3,2,1,1,2]

So Please review my code and suggest me if changes in the code required

Thank you

main.go

package main      func main() {         var array = []int{1, 2, 3, 4}         f(array, 10)     }      func f(array []int, length int) {         len := len(array)         var arr []int         for index := 0; index < length; index++ {             if (index/len)%2 == 0 {                 arr = append(arr, array[index%len])             } else {                 arr = append(arr, array[len-index%len-1])             }         }     } 

main_test.go

package main  import "testing"  func Benchmarkf (b *testing.B){     for N:=0; N < b.N; N++{         for _, value := range [][]int{             {1,2,3,4}, {5,6,7,8},         }{            f(value, 10)         }     } } 

make an array of objects which explicitly has label and value eg [{label: ‘school’, value: ‘college’}

using this.state.student in react to display (name,school,class.etc).. how do i change the “school” display to “college” without replacing the value of “School” in the api.

where do i place it in reactjs? . i just started learning

i tried ‘var student = [ {“name”, “school”, “class”}];’ ‘student[1] = “college”;’

but it replaces the actual value i don’t want that

result should be when drop down is clicked it shows “college” but the api value remains “school”

Como almacenar array en session Laravel y luego recuperarlos

Estoy intentado almacenar diferentes arrays en diferentes sessiones para luego poder recuperarlos, mi pregunta es si se puede hacer y si se podria guardar en una misma session todo. Esto es lo que he intentado.

Esta es mi llamada donde tfactura tcantidad y tprecio son arrays

$  .ajax({             type: "GET",             url: "almacenar",             data: {nombre: tfactura, cantidad: tcantidad, precio: tprecio}             dataType: 'json' }); 

Y luego en mi controlador tengo estas funciones.

public function getArrays(){     $  nombre = $  request->session()->get('nombre');     $  cantidad = $  request->session()->get('cantidad');     $  precio = $  request->session()->get('precio');      return response()->json(['nombre' => $  nombre], ['cantidad'=> $  cantidad], ['precio' => $  precio]); } public function almacenar(request $  request){      $  nombre = $  request->nombre;     $  cantidad = $  request->cantidad;     $  precio = $  request->precio;     $  request->session()->put('nombre', $  cantidad);     $  request->session()->put('cantidad', $  cantidad);     $  request->session()->put('precio', $  cantidad); } 

How to return all array permutations iteratively into a two-dimensional array?

I am trying to write a program that will iterate through all possible permutations of a String array, and return a two dimensional array with all the permutations. Specifically, I am trying to use a String array of length 4 to return a 2D array with 24 rows and 4 columns.

I have only found ways to print the Strings iteratively but not use them in an array. I have also found recursive ways of doing it, but they do not work, as I am using this code with others, and the recursive function is much more difficult.

For what I want the code to do, I know the header should be:

public class Permutation {      public String[][] arrayPermutation(String[] str)      {           //code to return 2D array      } } 

//I tried using a recursive method with heap’s algorithm, but it is very //complex with its parameters.

I am very new to programming and any help would be greatly appreciated.

Inserir valor no array mongoose

Minha model funciona da seguinte forma. Um usuário possui documentos, mas o usuário se cadastra antes de ter esses documentos. O que basicamente estou tentando fazer é dar um Update em usuários no array de documentos. SCHEMA

'user strict';  const mongoose = require('mongoose'); const Schema = mongoose.Schema;  const schema = new Schema({     email: {         type: String,         required: true     },     password: {         type: String,         required: true     },     name: {         type: String,         required: true     },     documents: [         {         title: {             type: String         },         content: {             type: String         },         notes: [             {             note: {             type: String             }         }     ]     } ]  });  module.exports = mongoose.model('User', schema); 

Então busquei algumas possíveis respostas e cheguei a isto QUERY

exports.put = (req, res, next) => {     const id = req.params.id;     User     .update({id}, {         $  push: {             "documents.$  .title": req.body.title,             "documents.$  .content": req.body.content         }     }).then(x => {         res.status(200).send({             message: 'Usuário atualizado com sucesso!'         });     }).catch(e => {         res.status(400).send({             message: 'Falha ao atualizar o Usuário =(', data: e         });     });   }; 

Ele não retorna erro, cai no THEN e dá como se o usuário tivesse sido atualizado com sucesso. Alguém poderia me ajudar?