python – Number of occurrences of strings in array

This is a Hackerrank problem (https://www.hackerrank.com/challenges/sparse-arrays/problem).

We’re given an array of strings and an array of queries, and have to return an array of the number of occurrences of each query in the array of strings.
For example: s = (‘ab’, ‘abc’, ‘aba’, ‘ab’). q = (‘ab’, atr’, ‘abc). We need to return (2, 0, 1).

The constraints are 1 <= n <= 1000, 1 <= q <= 1000, where n and q are the number of strings and queries respectively, and 1 <= |strings(i)|, |queries(i)| <= 20.

Here is my code:

def matchingStrings(strings, queries):
    results = ()
    dic = {q:0 for q in queries}
    for s in strings:
        if s in dic: dic(s) += 1
    for q in queries:
        if q in dic: results.append(dic(q)) 
    return results

Is there anything I can optimize? Speed, memory usage? Anything else?

react – Como Somar os Valores De Dentro De Um Array?

Preciso somar os valores do atributo “valores” que estão dentro de objetos separados dentro de um Array.

Tentei fazer um FOR para somar todos os “item.valor”, mas o valor de “resultado” é 0.

Podem me ajudar?

API: https://gitlab.com/desafio-conta-simples/developer/-/blob/master/mocks/transacoes.json

Código:

class ResumoValores extends Component   {

constructor(props){
    super(props);

    this.state = {
        //Array que recebe os Itens da API
        transacoes: (),
    }   
}

componentDidMount(){
    fetch("http://localhost:3000/transacoes")
    .then(resultado => resultado.json().then(dados => this.setState({transacoes: dados})))
    
}

render() {
    return (
     
    <Container>

        {
        //NavBar
        }
        <NavBar></NavBar>    
        {

        //CheckBox
        
        }
           
        {
        //Tabela com os dados
        }
        <Table striped bordered hover variant="dark">
            <thead>
                <tr>
                <th>Resultado</th>
                </tr>
            </thead>
            <tbody>

               { 
                //Chama o Array Transacoes e Faz um Map para listar os itens
                this.state.transacoes.map((item, indice)  => {
                    var resultado = 0;
                    var somaValores = item.valor
                    for ( var i = 0; i < somaValores.length; i++ ){
                    resultado += somaValores(i);
                    }
                    console.log(resultado);
                        return (

                            <tr key={indice}>
                            <td> {resultado}</td>
                            </tr>
                           )
                     })
                }


            </tbody>
        </Table>
    </Container>
    )
}

}

export default ResumoValores;

arraylist – Não estou conseguindo listar meu Array em Java, alguém pode me ajudar?

Estou tentando listar um ArrayList que eu fiz em Java, no caso, ele cadastra, porém não estou conseguindo listar.

PS. A opção de listar é a número 4.

Classe Principal

public static void main(String() args) {

    Scanner in = new Scanner(System.in);
    
    Scanner dados1 = new Scanner(System.in);
    Scanner dados2 = new Scanner(System.in);
    
    CadastroCliente c1 = new CadastroCliente();
    CadastroListagemCliente controle = new CadastroListagemCliente();
    
    String nome = "";
    String cpf =  "";


    String menu = "Olá, Bem Vindo(a) ao Projeto Nota Fiscaln" +
                    "Escolha a operação que deseja realizarn" +
                    "1 - Cadastrar Clienten" +
                    "2 - Cadastra Produton" +
                    "3 - Cadastrar Natureza da Operaçãon" +
                    "4 - Listar Clientesn" + 
                    "5 - Listar Produtosn" +
                    "6 - Gerar Nota Fiscaln" +
                    "7 - Listar Nota Fiscaln" +
                    "0 - Sairn";

    int op = 10;

    while (op != 0) {

        System.out.println(menu);

        op = in.nextInt();

        switch (op) {

        case 1:

            System.out.println("Nome do Cliente: ");
            nome = dados1.nextLine();
            c1.setNome(nome);
            

            System.out.println("Nome do CPF do cliente : ");
            cpf = dados2.nextLine();
            c1.setCpf(cpf);
            
            controle.listaClientes();
            break;

        case 2:

            System.out.println("Teste2");

            break;
        case 3:

            System.out.println("Teste3");

            break;
        case 4:

            
            controle.listaClientes();
            break;

        case 5:

            System.out.println("Teste5");
            break;

        case 6:

            System.out.println("Teste6");
            break;


        case 7:

            System.out.println("Teste7");
            break;

        case 0:

            System.exit(0);
        }

    }

   
}

}

Classe CadastroCliente

public class CadastroCliente {

private String nome;
private String cpf;

public String getNome() {
return nome;
}

public String getCpf() {
return cpf;
}

public void setNome(String nome) {
this.nome = nome;
}

public void setCpf(String cpf) {
this.nome = cpf;
}
}

Classe CadastroeListagem

public class CadastroListagemCliente {

ArrayList<CadastroCliente> clientes = new ArrayList<>();

public void adicionarClientes(CadastroCliente c) {
    clientes.add(c);
}

public void listaClientes() {
    clientes.forEach((lc) -> {
        System.out.println("Nome do Cliente: " + lc.getNome());
        System.out.println("CPF do Cliente: " + lc.getCpf());
        System.out.println("-----------------------------");
    });
}
}

inheritance – Override extended array size in java

I got a class LargeCell which is an extension of Cell class. I want to use same name for fixed array in both classes with a diffrence of array size. In cell class I want the size to be 1 and in LargeCell class I want size to be 2. When i try to add prisoner to LargeCell instead of prisoner being added to LargeCell, he is added to array in Cell class. I can override addPrisonerToCell() method but it does not seem like the best solution to me since it is copy paste from other class.
Is there any way, to make methods work on the right class without overriding them?

public class Cell {
private int cellNumber;
private Prisoner() prisoners;


public Cell(int cellNumber){
    this.cellNumber=cellNumber;
    this.prisoners=new Prisoner(1);
}


public boolean addPrisonerToCell(Prisoner prisoner) {
    for(int i=0; i<this.prisoners.length;i++){
        if(this.prisoners(i)==null){
            this.prisoners(i)=prisoner;
            return true;
        }
    }
    return false;
}}


public class LargeCell extends Cell {

private Prisoner() prisoners;

public LargeCell(int cellNumber) {
    super(cellNumber);
    this.prisoners = new Prisoner(2);

}
@Override
public boolean addPrisonerToCell(Prisoner prisoner) {
    for(int i=0; i<this.prisoners.length;i++){
        if(this.prisoners(i)==null){
            this.prisoners(i)=prisoner;
            return true;
        }
    }
    return false;
}}

how can i change the name of migration database in database array?

for a drupal migration from d7 to d8, i have to define my source database to be called ‘migrate’ in the settings.php as below: My question is how can i define the source as something other than ‘migrate’ . where is that set up?

`$databases('default')('default') = array(
  'database' => "db",
  'username' => "db",
  'password' => "db",
  'host' => $host,
  'driver' => "mysql",
  'port' => $port,
  'prefix' => "",
);


$databases('migrate')('default') = array(
  'database' => "drupal7",
  'username' => "db",
  'password' => "db",
  'host' => $host,
  'driver' => "mysql",
  'port' => $port,
  'prefix' => "",
);`

A little confusion on javaScript (array) map and forEach method

Why does they both not produce the same output, more specifically I’m scratching my head around why does forEach outputs undefined.

movieLists.forEach(list=>{
    return list.videos(0).id;    
});
// Outputs: undefined
movieLists.map(list=>{
    return list.videos(0).id;
});
// Outputs:(70111470, 65432445)

here is my array

var movieLists = (
            {
                name: "New Releases",
                videos: (
                    {
                        "id": 70111470,
                        "title": "Die Hard",
                        "boxart": "http://cdn-0.nflximg.com/images/2891/DieHard.jpg",
                        "uri": "http://api.netflix.com/catalog/titles/movies/70111470",
                        "rating": 4.0,
                        "bookmark": ()
                    },
                    {
                        "id": 654356453,
                        "title": "Bad Boys",
                        "boxart": "http://cdn-0.nflximg.com/images/2891/BadBoys.jpg",
                        "uri": "http://api.netflix.com/catalog/titles/movies/70111470",
                        "rating": 5.0,
                        "bookmark": ({ id: 432534, time: 65876586 })
                    }
                )
            },
            {
                name: "Dramas",
                videos: (
                    {
                        "id": 65432445,
                        "title": "The Chamber",
                        "boxart": "http://cdn-0.nflximg.com/images/2891/TheChamber.jpg",
                        "uri": "http://api.netflix.com/catalog/titles/movies/70111470",
                        "rating": 4.0,
                        "bookmark": ()
                    },
                    {
                        "id": 675465,
                        "title": "Fracture",
                        "boxart": "http://cdn-0.nflximg.com/images/2891/Fracture.jpg",
                        "uri": "http://api.netflix.com/catalog/titles/movies/70111470",
                        "rating": 5.0,
                        "bookmark": ({ id: 432534, time: 65876586 })
                    }
                )
            }
        );

How to prevent SQL Injection via the array parameter? (CVE-2017-14069)

Hello, this page suggest that the sql_query

$r = sql_query("SELECT modcomment FROM users WHERE id IN (" . implode(", ", $_POST(usernw)) . ")")or sqlerr(__FILE__, __LINE__);

Code (SQL):

is vulnerable to a SQL injection “via the usernw array parameter to nowarn.php.”

and the exploit is suggested:

POST nowarned=nowarned&usernw()=(select*from(select sleep(10))x)

Code (markup):

Please how that sql_query should look like so it prevent the abuse?
SEMrush

 

How do you access value of array with pointers in C?

I want to access nth element of array with pointers.

#define N_TH_POINTER(v, index, elem_size) ((char *)v + index * elem_size)
#define N_TH_ELEM(v, index) *(v + index)

int main()
{
  int a() = {4, 65, 2, -31, 0, 99, 2, 83, 257, 1};
  int elem_size = sizeof(int);

  printf("%dn", a(8)); // 257
  printf("%dn", N_TH_ELEM(a, 8)); // 257
  printf("%dn", *N_TH_POINTER(a, 8, elem_size)); // 1?
  return 0;
}

I understand why first two printf works, but why does not third?