¿Por qué httpbody de NSMutableURLRequest cambia caracteres de mi string en swift?

Actualmente trabajo en un poryecto de swift en el que el usuario puede subir fotografias a un servidor, para lograr esto codifico la imagen capturada a base 64 esto lo consigo con el sguiente código:

func convertImageToBasee64(image: UIImage){     let imageData = image.jpegData(compressionQuality: 1)     let base64String = imageData!.base64EncodedString()     return base64String } 

Posteriormente creo la variable que uso como parámetro

let imagenEnviar = convertImageToBasee64(image: imagenVistaPrevia.image!) let parametros = "imagen=" + imagenEnviar 

y por último ejecuto la clase de conexion a mi server.

let conexion:clsConexionIA = clsConexionIA.init(url: "miurl.php", params: parametros) conexion.request{(output) in   print(output) } 

esta es mi clase de conexión:

class clsConexionIA {    let URL: String    let PARAMS: String     init(url: String, params: String) {        self.URL = url        self.PARAMS = params.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!    }     func request(successHandler: @escaping (_ response: String) -> Void)->Void{        let request = NSMutableURLRequest(url: NSURL(string: self.URL)! as URL)        request.httpMethod = "POST"        request.httpBody = self.PARAMS.data(using: String.Encoding.utf8, allowLossyConversion: false)        let headers = ["Content-Type": "application/x-www-form-urlencoded"]        request.allHTTPHeaderFields = headers         let task = URLSession.shared.dataTask(with: request as URLRequest) { datos, respuesta, error in            if error != nil {                successHandler(String(describing: error));            } else {                let responseString = NSString(data: datos!, encoding: String.Encoding.utf8.rawValue)                print("RESPUESTA \(responseString)")                successHandler((responseString as String?)!);            }        }        task.resume()    } } 

Mi problema es que del lado de mi servidor php estoy recibiendo una cadena que no es un base64 válido, por lo que la imagen se guarda corrupta-dañada.

He utilzado Charles Proxy para inspeccionar los parametros que le paso a mi servidor, y en notado que el string que se envía al server es distinto al que obtengo al inspeccionar en tiempo de ejecución la linea self.PARAMS.data(using: String.Encoding.utf8, allowLossyConversion: false)

¿a qué se debe esto y como puedo corregirlo? Yo imagino que la parte .data(using: String.Encoding.utf8, allowLossyConversion: false) hace alguna modificación a mi string, pero no he encontrado la forma de corregir esta situación. También he intentado obtener el .data sin el parámetro allowLossyConversion pero no noto cambio alguno.

Algunos de los cambios que noto en el string es, por ejemplo, que me reemplaza los caracteres + por espacios en blanco, también la longitud de caracteres es distinta, por lo que forzar un replace de espacios del lado del servidor no me funciona.

Se que hasta este punto self.PARAMS = params.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! mi string base64 es válido porque lo inspecciono en tiempo de ejecución, copio su valor y lo pego en algún decodificador online y la imagen se genera correctamente.

Espero y alguien pueda ayudarme, gracias de antemano comunidad!

remove specific characters from a string

I have a scenario where I need to replace spaces with comma and then remove certain extra specific chars from a string.

echo "$  d" >>Mon Apr 22 05:06:00 UTC 2019 jent=$  (echo $  jt1 | sed 's/[[:space:]]/,/g') echo "$  jent" >>Mon,Apr,22,05:06:00,UTC,2019 #this does the first job of replacing the space with comma 

But again I want to remove the UTC part and the comma before it, how can I achieve it any help?

desired output should be

Mon,Apr,22,05:06:00,2019 

Notepad++ REGEX 3 or 4 digits at the end of string

Why is my pattern only matching the thousands matching and not the hundreds? Thanks.

Here’s my pattern:

(.*)(\d{1}?\,?\d{3}\.\d{2}) 

Here’s my sample

abc-anything320.00 abc-anything400.00 abc-anything577.32 abc-anything290.00 abc-anything204.00 abc-anything205.00 abc-anything214.00 abc-anything365.00 abc-anything365.00 abc-anything400.00 abc-anything299.00 abc-anything235.50 abc-anything213.00 abc-anything319.00 abc-anything272.00 abc-anything109.00 abc-anything239.00 abc-anything400.00 abc-anything600.00 abc-anything2,199.75 abc-anything289.00 abc-anything640.00 abc-anything157.00 abc-anything202.00 abc-anything125.00 abc-anything1,550.00 abc-anything194.00 

Replace by: $ 2

Android – Convert arrayList to String []

Bom dia pessoal, preciso converter um ArrayList para uma String[ ].

Não consegui fazer funcionar. Somente me retorna uma string gigante. Segue meu código

public List<Item> geral(){     buscaLatLong();     List<String> nomes = new ArrayList<String>();     String[] namesArr = nomes.toArray(new String[resuladoLista.size()]);      List<Item> item = new ArrayList<>();     String listagem[] = namesArr;        for (int i = 0; i<listagem.length; i++){         Item item = new Item();         item.setNome(listagem[i]);         item.setNum(String.valueOf(i+1));         itemList.add(item);     }      return itemList; } 

fiz um teste com uma string fixa no formato abaixo funcionou perfeitamente

String listagem[] = {“Teste1”, “Teste2”, “Teste3”, “Teste4”};

o resultado lista está como private static ArrayList resuladoLista; Como posso converter o meu resuladoLista para uma string idêntica ao listagem[]?

ASCII code decode to string

Hi i am working on this question and have my answer as following. I guess the time complexity is Big O(n ^2), anyone know the better solution for Big O(n)?

A string is encoded by performing the following sequence of actions: 1. Replace each character with its ASCII value representation. 2. Reverse the string.

For example, the table below shows the conversion from the string “HelloWorld” to the ASCII string “7210110810811187111114108100”:

Character H e l l o W o r l d ASCII Value 72 101 108 108 111 87 111 114 108 100

The ASCII string is then reversed to get the encoded string “0018014111117811180180110127”.

The characters in encoded string are within the range 10 – 126 which include special characters.

    def asciiencode(s: str) -> str:         s = s[::-1]         ch_map = {str(i): chr(i) for i in range(10, 127)}         res = []          def decode(s, substr):             if not s: return res.append(substr)             for i in (2, 3):                 if s[:i] in ch_map:                     decode(s[i:], substr + ch_map[s[:i]])          decode(s, '')         return res  

Java program skipping the string statement second time of the execution

I am new to programming , & have just started learning c++,python & java side by side. While working in java on making the railway ticket account program the problem arrives in the output the program is working properly till when we enter 1 passenger is travelling but the problem arises when we enter multiple ( 2 )or more than two passenger were travelling, In the case of first passenger, it work’s properly but for the second passenger, it skip’s the first_name string statement and directly executes last_name string statement. Here is the main class….. `

 public static void main(String[] args) { Scanner inpu=new Scanner(System.in); String fi_name=null,li_name=null,cn_name=null,first_name=null,last_name=null,cnic_number=null; int Age=0,passenger=0,i=1,age_name=0,age_price=0,total=0 ;         System.out.println("Enter the number of Passenger Travelling"); passenger=inpu.nextInt(); passenger_attributes ob=new passenger_attributes(); while(passenger>=i) {    first_name=ob.fname(fi_name); last_name=ob.lname(li_name);    cnic_number=ob.cnum(cn_name);    Age=ob.age(age_name);  age_price=ob.age_checker(Age);     System.out.println("passenger "+i+" First name is :=" +first_name);     System.out.println("passenger "+i+" Last name is :=" +last_name);     System.out.println("passenger "+i+" cnic number is :=" +cnic_number);     System.out.println("passenger "+i+" Age is :=" +Age);     System.out.println("passenger "+i+" total price ticket is  :=" +age_price);  total=total+age_price;    i++;}         System.out.println("the total price of all the passenger is :=" +total);     }    } 

& that was my class program

  public class passenger_attributes {     Scanner input=new Scanner(System.in);     public String fname(String fi_name)     {         System.out.println("ENTER PASSENGER FIRST NAME :=");         fi_name=input.nextLine();         return fi_name;       }      public String lname(String la_name)     {         System.out.println("ENTER PASSENGER LAST NAME :=");         la_name=input.nextLine();         return la_name;       }       public String cnum(String cn_num)     {         System.out.println("ENTER PASSENGER Cnic Number :=");         cn_num=input.nextLine();         return cn_num;       }        public int age(int age_num)     {         System.out.println("ENTER PASSENGER Age :=");         age_num=input.nextInt();         return age_num;       }        public int age_checker(int Age)       {           int price_age;           if(Age<=12)           {              price_age=500;              return price_age;           }           else if (Age<=15 && Age>12)           {               price_age=1000;           return price_age;           }           else if(Age>15)           {               price_age=1500;           return price_age;           }           else{               return 0;           }        } } 

Determine whether there exists a one-to-one character mapping from one string to another

The task

Determine whether there exists a one-to-one character mapping from one string s1 to another s2.

For example, given s1 = abc and s2 = bcd, return true since we can map a to b, b to c, and c to d.

Given s1 = foo and s2 = bar, return false since the o cannot map to two characters.

My solution

const s1 = "foo"; const s2 = "bar";  const isMapable = (s1, s2) => new Set(s1).size === new Set(s2).size;;  console.log(isMapable(s1, s2)); 

Seems to be too easy…not sure whether I miss something…

Why do numpy string arrays cut strings when they see a forward slash?

I’m processing some text data with python, making charts, etc. I’m using numpy string arrays as it’s the framework i’m the most comfortable with.

I encountered a weird behaviour with forward slashes. When trying to get a string containing a forward slash inside a numpy array, it is cut at the slash and the rest disappears. See example below:

import numpy  a = numpy.array(["one","two","three"]) a[0] = "test/case" print(a) 

This gets me:

['test/','two','three']

What’s happening here, can I fix it ? Thank you !

¿Cómo incluir un void en un string toString (dentro de una clase C++)?

Antes que nada aclaro que soy nuevo programando, no llevo ni 2 meses. Bueno, esto que ven lo estoy escribiendo dentro de una clase, por si notan algo fuera de lo normal.

El caso es que la parte de “obtenerDivisiónDecimal()” me compila de maravilla.

Pero “elevarFracciónAlaN()” me salta un error diciendo “no matching function for call to Clase::elevarFraccionAlaN() Y básicamente es eso, me gustaría expresarlo mejor, pero no sé como. :c

string toString( ){   stringstream s;    s << "blablabla: " << obtenerDivisionDecimal( ) << endl;   s << "blablablah: " << elevarFraccionAlaN( ) << endl;    return s.str( ); }  float obtenerDivisionDecimal( ) {   return ( Numerador/Denominador ); }  void elevarFraccionAlaN( int N ) {   float elevarFraccionAlaN;    elevarFraccionAlaN = pow( ( Numerador / Denominador ), N );    return void ( elevarFraccionAlaN ); } 

for 1 string. find the longest string of conditions

give 1 character string of 2 characters A and B. Find the number of characters of the longest substring so that the difference between the two characters does not exceed 1. (consecutive substring) <=1000000 input:
AAAAAAAAABBAAAAAAABBBBAAAAAAAAAAABBB output: 13

please help me :'(

gets(s); T=(strlen(s)+1); s[T]='C'; for(int i=0;i<T;i++)     {         if(s[i] != s[k])             {                 Z[m]=i-k;                 k=i;                 D=m;                 m++;             }     }