magento2 – URL rewrite having query string via htaccess in magento 2

I have current URL like this:

http://localhost/projectname/industries/index/index/industry/aircraft

(Here industries is the frontend route, index is controller and second index is action
industry is query param name, and aircraft is param value)

I want after rewrite the url will be :

http://localhost/projectname/industries/industry/aircraft

Or

http://localhost/projectname/industries/aircraft

bash – Issue with converting array or string to valid path

I’m trying to make a function that will make my life easier converting images to pdf. I’m using img2pdf which is a Python script. I want to be able to pass files and directory to my function (with wild mark for expansion like: directory/*).

I come to a point where I fix the issues with Windows path conversion, but then realize now the function doesn’t work if the path has spaces, or it comes to a point where Python will just error on pathing.

I tried writing the function, making a string that contains all the files:

imgtopdf(){
    list=""
    while (( "$1" != "" )) ; do
        list+=" '$(cygpath -w "$1")'" # Tried $(echo "$list" | xargs -0) echo but it removes back-slashes!
        shift
    done
    list="${list:1}"
    echo $list
    img2pdf -o img2pdf.pdf --pagesize A4 $list
}

Then tried using an array to hold all the files:

imgtopdf(){
    list=()
    while (( "$1" != "" )) ; do
        list+="$(cygpath -w "$1")"
        shift
    done
    echo ${list(@)}
    img2pdf -o img2pdf.pdf --pagesize A4 ${list(*)}
}

Note: cygpath -w is responsible for converting a /cygdrive/ path to Windows path, so that Python understands the pathing.

encryption – Is MD5 hash string not safe to show

Hash functions output binary data; byte array. This cannot be displayed correctly, therefore, you need encoding.

Transmitting binary data can create problems, don’t transmit binary data and we don’t. Many of the encryption programming errors in the StackOverflow are due to sending binary data. Most of the time works, seldomly fails and the coders wonder about the problem. The binary data corrupts the network protocol.

Therefore hex,base64, or similar encodings are necessary to mitigate this.

In another way, character encodings are reversible and don’t require encryption keys. This has nothing to do with security it is about visibility and tranferability.

Como comparar dois arrays de string de forma otimizada em JavaScript

Estou fazendo um programinha em JavaScript/Typescript que lê dois arquivos XML e precisa comparar as strings que existem dentro dos dois arquivos.

Primeiro criei uma estrutura de dados com um array para cada linha do tipo <string, string> onde a primeira string recebe o “identificador da string” e a segunda recebe o “valor” da string em si.

Fiz a leitura dos dois arquivos e criei um array de linhas pra cada arquivo. Esse array recebe cada uma das linhas do arquivo (array<string, string>), tanto para o arquivo1 quanto para o arquivo2.
Além disso, o primeiro item dos arrays de linhas (linhas(0)) contém quais são as strings-chave (única) daquela linha, ou seja, a string que identifica aquela linha nós dois arquivos, (aqui eu imaginei como se fosse os indices de uma tabela de banco de dados).

Minha dúvida é, como eu posso comparar de forma otimizada, na prática, os dois arrays dos arquivos, utilizando também o array com as strings-chave, de forma que mesmo que o arquivo seja muito grande eu consiga fazer uma comparação precisa e mais rápida?

algorithms – Suffix -Tree checks existence of P pattern before k position in T string

I need to design an algorithm that given a T string of n length, after a process O(n), for every string P of m length and a k value between 1 to n, to checks in O(m) time, if P appears on T before k position, only using Suffix Tree.

Unfortunately there are not any good bioinformatics books with fair examples and practical methodologies. Dan Gusfield book does not offer a solution manual.

bash – MacOS script to search a text file for a partial string and add a line if found

New here, and I tried a search but managed to find a lot of SIMILAR things but not quite what I’m after.

I’m looking for a shell or Applescript that will take a text file, search it for one of 3 string options and append a line of text to the end of the file. It’s probably not helping that the string contains special characters, notably “<” and “>” and is actually a line in an XML file that will be temporarily renamed to a txt for the operation.

I want the script to look at the file for any of these things:

<UserId>1</UserId> <UserId>2</UserId> or <UserId>3</UserId>

and add the following to the end of the document based on the result. I’d like to add it in a specific place, like for example Line 3, but one step at a time.:

ID=1 add <tags>Name1</tags>

ID=2 add <tags>Name2></tags>

ID=3 add <tags>Name3</tags>

I’ve tried various GREP and SED snippets but they’re not getting anywhere. I’m not a coder, but since the creator of the app that creates these files can’t or won’t add this feature I’m needing to do it myself.

Any help appreciated.

Imprimir letra por letra de uma string usando for of javascript

como o título diz, preciso imprimir letra por letra dessa string, de forma que, no termianal o texto fique na vertical. podem me ajudar?

let frase = “Essa semana vou no colearning”;

json – The argument type ‘String’ can’t be assigned to the parameter type ‘List’

tengo un problema y es que estoy intentando pasar un string y al momento que el otro widget recibe el parametro este lo ocupa como lista. El objeto se guarda correctamente en el provider solo que al pasarlo al widget que lo ocupa es cuando tengo los problemas. Abajo dejo el codigo que tengo.

Modelo

import 'dart:convert';

class DependenciasData {
  final int id;
  final String dependencia;

  DependenciasData({
    this.id,
    this.dependencia
  });

  factory DependenciasData.fromRawJson(String str) =>
      DependenciasData.fromJson(json.decode(str)(0));

  factory DependenciasData.fromJson(Map<String, dynamic> json) {
    return DependenciasData(
      id: json('id') as int,
      dependencia: json('dependencia') as String,
    );
  }
}

Provider

import 'package:control_acessos/models/dependencia.dart';
import 'package:flutter/material.dart';

class DatosDependencias with ChangeNotifier{
  DependenciasData data;
  DatosDependencias(){
    this.data = null;
  }

  bool get isEmpty => this.data == null;

  void clear() => this.data = null;

  void notify() => notifyListeners();

  void initDatosDependencias(String rawString){
    data = DependenciasData.fromRawJson(rawString);
    notifyListeners();
  }
}

El codigo donde ocupo el provider y crear la list:

      Widget _body(BuildContext context){
        final providerDependecias = Provider.of<DatosDependencias>(context);
        if (providerDependecias.isEmpty) {
          HttpServices.getDependencias(context);
          return Center(child: CircularProgressIndicator());
        }
        final dependencias = providerDependecias.data.dependencia;
        if (dependencias.length == 0 || dependencias.isEmpty) {
          return Center(child: Text('No dependencias que mostrar'));
        }else if(dependencias.length >= 1){
          
          return DependenciasList(dependencias:dependencias);
        }
        return Container();
      }
    }
    
    class DependenciasList extends StatelessWidget {
      DependenciasList({@required this.dependencias});
    
      final List<DependenciasData> dependencias; 
      
      @override
      Widget build(BuildContext context) {
        print(dependencias);
        return Container(
        );
      }
    }

Este es el json que estoy usando que esta en un servidor que tengo
introducir la descripción de la imagen aquí

Rescatar substrings en python desde una string

Tratando de ayudar en esta pregunta en Chess Exchange, estoy recorriendo un archivo .pgn de partidas de ajedrez que tiene una serie de partidas de ajedrez con el siguiente formato:

(Event "Live Chess")
(Site "Chess.com")
(Date "2020.12.09")
(Round "-")
(White "GMWSO")
(Black "Hikaru")
(Result "1-0")
(CurrentPosition "8/1k1K4/2Q5/1N6/8/6B1/8/8 b - -")
(Timezone "UTC")
(ECO "B06")
(ECOUrl "https://www.chess.com/openings/Modern-Defense-Standard-Line-3...c6")
(UTCDate "2020.12.09")
(UTCTime "20:25:00")
(WhiteElo "3099")
(BlackElo "3355")
(TimeControl "60+1")
(Termination "GMWSO won by checkmate")
(StartTime "20:25:00")
(EndDate "2020.12.09")
(EndTime "20:29:58")
(Link "https://www.chess.com/game/live/5927279266")

El usuario desea rescatar los valores Date, WhiteElo, BlackElo, White y Black y pasarlos a una hoja excel.

Al leer el archivo pgn se almacena todo como una string. He conseguido pasar los valores Date, WhiteElo y BlackElo a una hoja de cálculo con el siguiente código:

import pgn
import openpyxl
import os
pgn_text = open('ChessCom_gmwso_202012.pgn').read()
dates = ()
welo = ()
belo = ()
def getValues(file):
    test_str = file
    test_date = "(Date"
    res1 = (i for i in range(len(test_str)) if test_str.startswith(test_date, i))
    test_welo = "(WhiteElo"
    res2 = (i for i in range(len(test_str)) if test_str.startswith(test_welo, i))
    test_belo = "(BlackElo"
    res3 = (i for i in range(len(test_str)) if test_str.startswith(test_belo, i))
    test_white = '(White "'

    for i in res1:
        dates.append(test_str(i+5:i+17))
    for i in res2:
        welo.append(test_str(i+9:i+15))
    for i in res3:
        belo.append(test_str(i+9:i+15))

getValues(pgn_text)

def generateExcel(dates,welo,belo):
    file = 'chess_games.xlsx'
    if os.path.isfile(file):
         wb = openpyxl.load_workbook(filename=file)
         print ('Via isfile')
    else:
        wb = openpyxl.Workbook()
        print ("Via is not file")
    ws = wb("chess_games")
    for k in range (len(dates)):
        ws('A'+str(k+1)) = dates(k)
    for k in range (len(welo)):
        ws('B'+str(k+1)) = welo(k)
    for k in range (len(belo)):
        ws('C'+str(k+1)) = belo(k)
    wb.save(file)
generateExcel(dates,welo,belo)

Sin embargo, los valores de White y Black son nombres de distintas longitudes, y no se pueden rescatar usando posiciones fijas de la string.

¿Cómo podría rescatarlos para introducirlos en la hoja excel?

python – Is this a good handy util for converting hex to binary in the form of string?

This code returns a string of binary in 4-digit forms for a given hex in the form of string

def str_bin_in_4digits(aString):
    retStr = ''
    for i in aString:
        retStr = retStr+"{0:04b}".format(int(i, 16))+" "
    return retStr.strip()

for example,

>>> str_bin_in_4digits("20AC")
0010 0000 1010 1100

The code works as expected and my concern is could it be more elegant, like faster or less memory consumption?