text:
Q: Increased latency by time - C# ASP.NET Core Web API I have an ASP.NET Core 3.1 Web API service hosted on Windows Server 2016 (IIS). It's a very simple web service that routes all incoming requests to a particular endpoint.
Here is the code:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;

namespace Proxy
{
    public class ProxyMiddleware
    {
        private readonly RequestDelegate next;
        private readonly string destinationPath;
        private readonly IProxyHttpClient client;

        public ProxyMiddleware(RequestDelegate next, IProxyHttpClient client)
        {
            this.next = next;
            this.client = client;
            this.destinationPath = "otherservice.svc";
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                if (!context.Request.Path.ToString().ToLower().Contains(this.destinationPath))
                {
                    await next.Invoke(context);
                    return;
                }

                HttpResponseMessage response = await this.client.SendRequest(context.Request);
                context.Response.StatusCode = (int) response.StatusCode;

                await context.CopyProxyHttpResponse(response);
            }
            catch (HttpRequestException ex)
            {
                await context.Response.WriteAsync(ex.Message);
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
                await context.Response.WriteAsync(ex.ToString());
            }
        }
    }
}

IProxyClient:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace Proxy
{
    public class ProxyHttpClient : IProxyHttpClient
    {
        private readonly string otherServiceUrl = "https://172.21.22.3:443";
        private readonly HttpClient httpClient;

        public ProxyHttpClient()
        {
            var handler = new HttpClientHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => true
            };
            this.httpClient = new HttpClient(handler);
        }

        public async Task<HttpResponseMessage> SendRequest(HttpRequest httpRequest)
        {
            HttpRequestMessage requestMessage = httpRequest.CreateProxyHttpRequest(new Uri(this.otherServiceUrl + httpRequest.Path + httpRequest.QueryString));

            return await this.httpClient.SendAsync(requestMessage);
        }
    }
}

Extensions:
using System;
using System.Net.Http;
using Microsoft.AspNetCore.Http;

namespace Proxy
{
    public static class HttpRequestExtensions
    {
        // obtained from https://github.com/aspnet/Proxy/blob/master/src/Microsoft.AspNetCore.Proxy/ProxyAdvancedExtensions.cs
        public static HttpRequestMessage CreateProxyHttpRequest(this HttpRequest request, Uri uri)
        {
            var requestMessage = new HttpRequestMessage();
            var requestMethod = request.Method;
            if (!HttpMethods.IsGet(requestMethod) &&
                !HttpMethods.IsHead(requestMethod) &&
                !HttpMethods.IsDelete(requestMethod) &&
                !HttpMethods.IsTrace(requestMethod))
            {
                var streamContent = new StreamContent(request.Body);
                requestMessage.Content = streamContent;
            }

            // Copy the request headers
            foreach (var header in request.Headers)
            {
                if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
                {
                    requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
                }
            }

            requestMessage.Headers.Host = uri.Authority;
            requestMessage.RequestUri = uri;
            requestMessage.Method = new HttpMethod(request.Method);

            return requestMessage;
        }

    }
}

.proj:
<Project Sdk="Microsoft.NET.Sdk.Web">

    <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
        <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
        <AspNetCoreModuleName>AspNetCoreModuleV2</AspNetCoreModuleName>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.22" />
        <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
        <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
    </ItemGroup>

</Project>

As said previously, I have this service deployed on IIS on windows server 2016. Once deployed, it works perfectly, keeps working well for 6-8 hours and as it keeps working, latency increases by time. It keeps increasing till it reaches the point of effectively being down. E.g. requests take 3+ minutes to get a reply (which effectively turns into a timeout). This behavior is consistent whether I call the proxy service from inside the server itself (localhost) or from outside the network via it's public IP.
Once I restart the server, it all goes back healthy! It stays healthy for 6-8 hours and the same behavior happens again. I have even tried restarting the service itself on IIS or recycling the application pool -> doesn't work. It must be the server (machine) itself.
We have checked the resource utilization on the server at the point of timeout increase, things look fine - around 50% utilization on memory (2GB out of 4GB) and CPU barely used.

A: From Yarp docs:

Middleware should avoid interacting with the request or response bodies. Bodies are not buffered by default, so interacting with them can prevent them from reaching their destinations. While enabling buffering is possible, it's discouraged as it can add significant memory and latency overhead. Using a wrapped, streaming approach is recommended if the body must be examined or modified. See the ResponseCompression middleware for an example.

I'd recommend to use this library instead of a custom solution.
https://microsoft.github.io/reverse-proxy/articles/getting-started.html


text:
Q: Parse Xlsx file to JSON in Cypress I have some problems with implementing tests for downloading the XLSX file and checking the data inside using cypress.
https://kishorsharma69.wordpress.com/2021/07/06/cypress-data-driven-testing-with-excel-file/
I used this tutorial to do the data here look simple: data used in the tutorial
But in my project I have excel files which looks like this: data used in my project
When I'm using the xlsx file from the tutorial everything works well the JSON file is created properly: json file created from tutorial
But how I can make it with my file? How I can for example start from the 5 line of excel file and just take 5 and 6 lines from excel? Thanks for help :)
Here is code used in my tests:
Then('File is downloaded, parsed to json file and compared', () => {
cy.task('readXlsx', {file: 'cypress/downloads/test.xlsx', sheet: "Sheet1" }).then((rows) => {
rowsLength = rows.length;
cy.writeFile("cypress/fixtures/xlsxData.json", {rows})

Here you can find my index.js file: inde.js file
And the read-xlsx.js file: read-xlsx.js file

redpajama_set_name: RedPajamaStackExchange


text:
Q: picture taken with camera doesn't resize in uiimageview My code
- (IBAction)takePhoto:(UIButton *)sender {
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
    UIImagePickerController *picker = [UIImagePickerController new];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;

    [self presentViewController:picker animated:YES completion:nil];
}else{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ERROR!" message:@"Device has no camera!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}
}

and the delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
self.userImage.image = chosenImage;

[picker dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

[picker dismissViewControllerAnimated:YES completion:NULL];

}

Well, thats pretty simple and basic. My problem is that after assigning my image to the UIImageView I have (which has a pinned/fixed width and height) instead of resizing itself to the size of the uiimageview it stretches throughout my whole view, working more as a background that an image placed where it should be. Again, the width and height of my uiimageview has been pinned. Can anybody help? thanks

A: The contentMode of your UIImageView should be UIViewContentModeScaleAspectFit, instead of UIViewContentModeCenter as it seems to be.
If you need to change the content mode on the fly, just add this line:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    self.userImage.image = chosenImage;

    // Add this line
    self.userImage.contentMode = UIViewContentModeScaleAspectFit;

    [picker dismissViewControllerAnimated:YES completion:NULL];
}


text:
Q: Simple proof showing a subset has smaller cardinal In Shoenfield, page 254, I read a proof of the following fact: $x \subseteq y \implies Card(x) \le Card(y)$.
Recall

$Card(x)$ is the least ordinal $\alpha$ that is bijective to $x$.

Thus the above inequality just means that $Card(x) = Card(y) \lor Card(x) \in Card(y)$.
Simple proof
The proof uses a remark issued from the proof that the axiom of choice implies Zermelo's theorem. I'm looking for a direct proof which assumes already Zermelo's theorem to be equivalent to the axiom of choice and simple facts about ordinals such as the facts gathered here.

A: The thing here is that not everyone have their copy of Shoenfield's open, or even at reach (maybe it's in the office), or even a copy of the book.
In general, in $\sf ZF$ we say that for two arbitrary sets, the cardinal of $x$ is less or equal the cardinal of $y$ if and only if there is an injection from $x$ into $y$. So if $x\subseteq y$, the identity function is such injection.
Shoenfield's book, in contrast, defines $Card(x)$ as the smallest initial ordinal which is in bijection with $x$. Now the axiom of choice is equivalent to the statement "For every $x$, $Card(x)$ exists".
But you don't need the axiom of choice for most basic cardinal arithmetic results when involving ordinals, and certainly not for this one. Shoenfield's argument is as follows (and I apologise in advance if my notation is different):

*

*$x\subseteq y$, so if $f\colon y\to\sigma=Card(y)$ is a bijection, $f\restriction x$ is a bijection between $x$ and a subset of $\sigma$, say $f``x$.

*Looking at the function mapping $f``x$ to its order-type, say $\chi$, then $\chi$ is an ordinal and $\chi\leq\sigma$.

*Therefore, $Card(x)=Card(\chi)\leq\chi\leq\sigma=Card(y)$.

The axiom of choice is only used to claim that if $y$ is any arbitrary set, then $Card(y)$ exists. But the proof does not use any more choice than that. And if we consider a broader notion of cardinals which allow for sets which are not well-orderable to have a cardinal (which is not an ordinal, in this case), then the definition of $Card(x)\leq Card(y)$ is aligned with making this statement trivial (although we still need to prove that for initial ordinals the cardinal ordering coincides with the ordinal ordering which coincides with the inclusion ordering).

A: Here is my work on the way Shoenfield proves it. It does not provide an alternative proof. As it can be seen, the procedure doesn't use Zermelo's theorem. As one can see, simplicity comes when understanding that each proof is essentially counting the elements of a particular object using the ordinals.
Count of a set
Every set is equipotent to an ordinal.
Proof
Let $A$ be a set. We are going to count the elements of $A$ and put them in bijection with the elements of some ordinal $\alpha$. First thing to realize is that if we count an element, then we shouldn't count its parts (if they also belong to $A$) because their parts come for free to the ordinal $\alpha$.
So set $\delta = \mathcal{P}(A) \setminus \{\emptyset\}$ and $g$ its choice function. Since $A$ is a set, it cannot be equal to $V$ and there exists $b \notin A$. We will use transfinite recursion to define such an iteration. Here is the function $F: V \to V$: [
F x =
\begin{cases}
 g(A \setminus range(x)) & range(x) \subset A \\
 b                       & otherwise
 \end{cases}
] here is the corresponding transfinite recursive function $G: On \to V$: [
F \xi =
\begin{cases}
  g(A \setminus range(F \upharpoonright \xi)) & range(F \upharpoonright \xi) \subset A \\
  b                                           & otherwise
  \end{cases}
] Some calculation will show $F 0 = g A \in A$, $F 1 = g(A \setminus g A) \in A \setminus g A$ when $gA \subset A, \ldots$. So we already see that at each iteration we choose a fresh element and that iteration stops when the previously chosen elements exhaust $A$. Iteration has to stop since otherwise that would give an injection $On \to A$ contradicting that $A$ is a set. By transfinite induction, there will be a least stopping ordinal $\alpha$. At that point, $F\upharpoonright_{\alpha}: \alpha \to A$ is an injection and $range(F \upharpoonright_{\alpha}) = \{ F x. x \in \alpha \} \subseteq A$ cannot be a proper subset of $A$, thus $range(F \upharpoonright_{\alpha}) = A$. Thus, $F\upharpoonright_{\alpha}$ is a bijection with $\alpha$.
Count of a set of ordinals
If $x \subset \sigma \in On$ then $\exists \tau \in On. \tau \le \sigma$ and $\tau$ is bijective to $x$.
Proof
The counting theorem on sets gives as an ordinal $\tau$ that is equipotent to $x$ via a counting function $F: \tau \to x$ such that $F(\rho) = g ` (x - range(F \upharpoonright \rho))$. By contradiction, if $\sigma < \tau$ then it is mapped by $F$ to $F `\sigma \in x \subset \sigma \implies F `\sigma < \sigma$. But this doesn't match our intuition that we are counting our set $x$. So let $\rho$ be the least ordinal such that this unordering happens, i.e. $F `\rho < \rho$. Then necessarily $F ` F ` \rho = F ` \rho$. This violates the injectivity of F.
What we wanted
Note that $x$ will be bijective with a subset of $Card(y)$. So by the count of a set of ordinals. There is $\tau \le Card(y)$ bijective to $x$. So $Card(x) \le \tau \le Card(y)$.


text:
Q: Arreglo imprime otros valores a los esperados .c Hola estoy aprendiendo a programar en C y estoy haciendo un programa en donde se me pide registrar la cantidad de servicios hechos por 5 taxis en un arreglo bidimensional, donde se almacena el código de taxi, clave del cliente, tipo de servicio y el costo, este arreglo bidimensional lo paso a una funcion donde almaceno en un arreglo el total producido de cada taxi, segun su codigo (es decir si es el taxi 1, 2, 3, 4 o 5) y despues este arreglo donde pongo el total producido de cada taxi lo imprimo, pero al momento de imprimir ,imprime otros valores a los esperados, les dejo el codigo y una imagen a lo que imprime.
#include <stdio.h>
#include <string.h>

//Prototipo de las funciones//
void entradaDatos();
void imprimir(int m[][4],int nfilas);
void totalProducido(int m[][4],int nfilas);

int main(){

entradaDatos();

return 0;
}

//Funciones//

void entradaDatos(){
    int i,j,cant_ser;

    //Se solicita la cantidad de servicios realizados//
    printf("Ingrese la cantidad de servicios\n");
    scanf("%i", &cant_ser);

    int regServicio [cant_ser][c];

    //Ciclo para solicitar el registro de servicios//
    for(i = 0; i < cant_ser; i++){
            j = 0;
            //Se solicita y valida el codigo de taxi//
            do{
                printf("Ingrese el codigo de taxi\n");
                scanf("%i",&regServicio[i][j]);
                if(regServicio[i][j]!= 01 && regServicio[i][j] != 02 && regServicio[i][j] != 03 && regServicio[i][j] != 04 && regServicio[i][j] != 05){
                    printf("El codigo de taxi que ingreso no es valido, vuelva a intentarlo\n");
                }
            } while(regServicio[i][j] != 01 && regServicio[i][j] != 02 && regServicio[i][j] != 03 && regServicio[i][j] != 04 && regServicio[i][j] != 05);
            j++;
            //Se solicita la clave de cliente//
            do{
                printf("Ingrese la clave de cliente\n");
                scanf("%i",&regServicio[i][j]);

                if(regServicio[i][j] < 0){
                    printf("La clave que ingreso no es valida, vuelva a intentarlo\n");
                }
            } while(regServicio[i][j] < 0);
            j++;
            //Se solicita el tipo de servicio//
             do{
                printf("Ingrese el tipo de servicio\n");
                scanf("%i", &regServicio[i][j]);

                if(regServicio[i][j] != 01 && regServicio[i][j] != 02 && regServicio[i][j] != 03){
                    printf("El tipo de servicio que ingreso no es valido vuelva a intentarlo\n");
                }
            } while(regServicio[i][j] != 01 && regServicio[i][j] != 02 && regServicio[i][j] != 03);
            j++;
            //Solicita el costo del servicio//
            do{
                printf("Ingrese el costo del servicio\n");
                scanf("%i", &regServicio[i][j]);

                if(regServicio[i][j] <= 0){
                    printf("El costo que ingreso no es valido, vuelva a intentarlo\n");
                }
            } while(regServicio[i][j] <= 0);

    }
    system("cls");
    imprimir(regServicio,cant_ser);
    totalProducido(regServicio,cant_ser);
}

void imprimir(int m[][4],int nfilas){
    int i;

    //Impresion de los resultados//
    printf("%s %10s %10s %10s %10s\n","== Cliente == ","== Codigo Taxi == ","== Clave Cliente ==","== Tipo servicio ==","== Costo servicio ==");
    for(i = 0; i < nfilas; i++){
        printf("%6i %17i %21i %18i %18i\n", i + 1,m[i][0], m[i][1],m[i][2],m[i][3]);
    }
}

void totalProducido(int m[][4],int nfilas){
    int i, j = 0;
    int total[5];

    //Captura el total producido de cada taxi, segun el codigo del taxi//
    for(i = 0; i < nfilas; i++){
        if(m[i][0] == 1){
            total[0] += m[i][3];
        } else if(m[i][0] == 2){
                total[1] += m[i][3];
                } else if(m[i][0] == 3){
                        total[2] += total[2] + m[i][3];
                        } else if(m[i][0] == 4){
                            total[3] += m[i][3];
                                } else if(m[i][0] == 5){
                                        total[4] += m[i][3];
                                        }
    }

    //Impresion del total producido por cada taxi//
    printf("\n\n");
    for(i = 0; i < 5; i++){
        printf("El total producido del taxi %i es $%i\n", i + 1, total[i]);
    }
}

Esto sale al momento de ejecutar el codigo y por lo que ingrese, deberia salir que solo el taxi 2 genero 45 y los demas deberian estar en 0, no se a que se deba, así que quisiera saber porque sucede esto o como pudiera arreglarlo, gracias.

A: Tu código está bien etructurado en funciones, eso hace más fácil de encontrar y solucionar los errores. El primer problema que encontré en el código fué que no declarastes ni inicializastes la variable 'c' en la función entradaDatos(), la variable debe ser inicializada con el valor de 'c=4', ya que 4 es el número de columnas de tu arreglo.
La otra parte por la que el código no te funciona es porque no inicializastes los valores del arreglo. Al crear un arreglo, los valores dentro de él no son 0, sino que son direcciones en memoria, hasta que se guardan datos dentro de ellos. Por este motivo es que en la suma no te da los resultados esperados, al no estar sumando los valores a un número entero inicial = 0, estos datos son perdidos y mostrados como direcciones en memoria. Por este motivo tienes que establecer todos los valores de tu arreglo total[5] de la función totalProducido, en 0, así: int total[5] = {0,0,0,0,0};. para que despues cada espacio del arreglo te sirva para sumar los datos.
Este es el código completo corregido. Si la respuesta te ha servido de ayuda, por favor márcala como la correcta :)
#include <stdio.h>
#include <string.h>

//Prototipo de las funciones//
void entradaDatos();
void imprimir(int m[][4],int nfilas);
void totalProducido(int m[][4],int nfilas);

int main(){

entradaDatos();

return 0;
}

//Funciones//

void entradaDatos(){
    int i,j,cant_ser,c=4;

    //Se solicita la cantidad de servicios realizados//
    printf("Ingrese la cantidad de servicios\n");
    scanf("%i", &cant_ser);

    int regServicio [cant_ser][c];

    //Ciclo para solicitar el registro de servicios//
    for(i = 0; i < cant_ser; i++){
            j = 0;
            //Se solicita y valida el codigo de taxi//
            do{
                printf("Ingrese el codigo de taxi\n");
                scanf("%i",&regServicio[i][j]);
                if(regServicio[i][j]!= 01 && regServicio[i][j] != 02 && regServicio[i][j] != 03 && regServicio[i][j] != 04 && regServicio[i][j] != 05){
                    printf("El codigo de taxi que ingreso no es valido, vuelva a intentarlo\n");
                }
            } while(regServicio[i][j] != 01 && regServicio[i][j] != 02 && regServicio[i][j] != 03 && regServicio[i][j] != 04 && regServicio[i][j] != 05);
            j++;
            //Se solicita la clave de cliente//
            do{
                printf("Ingrese la clave de cliente\n");
                scanf("%i",&regServicio[i][j]);

                if(regServicio[i][j] < 0){
                    printf("La clave que ingreso no es valida, vuelva a intentarlo\n");
                }
            } while(regServicio[i][j] < 0);
            j++;
            //Se solicita el tipo de servicio//
             do{
                printf("Ingrese el tipo de servicio\n");
                scanf("%i", &regServicio[i][j]);

                if(regServicio[i][j] != 01 && regServicio[i][j] != 02 && regServicio[i][j] != 03){
                    printf("El tipo de servicio que ingreso no es valido vuelva a intentarlo\n");
                }
            } while(regServicio[i][j] != 01 && regServicio[i][j] != 02 && regServicio[i][j] != 03);
            j++;
            //Solicita el costo del servicio//
            do{
                printf("Ingrese el costo del servicio\n");
                scanf("%i", &regServicio[i][j]);

                if(regServicio[i][j] <= 0){
                    printf("El costo que ingreso no es valido, vuelva a intentarlo\n");
                }
            } while(regServicio[i][j] <= 0);

    }
    system("cls");
    imprimir(regServicio,cant_ser);
    totalProducido(regServicio,cant_ser);
}

void imprimir(int m[][4],int nfilas){
    int i;

    //Impresion de los resultados//
    printf("%s %10s %10s %10s %10s\n","== Cliente == ","== Codigo Taxi == ","== Clave Cliente ==","== Tipo servicio ==","== Costo servicio ==");
    for(i = 0; i < nfilas; i++){
        printf("%6i %17i %21i %18i %18i\n", i + 1,m[i][0], m[i][1],m[i][2],m[i][3]);
    }
}

void totalProducido(int m[][4],int nfilas){
    int i, j = 0;
    int total[5] = {0,0,0,0,0};

    //Captura el total producido de cada taxi, segun el codigo del taxi//
    for(i = 0; i < nfilas; i++){
        if(m[i][0] == 1){
            total[0] += m[i][3];
        } else if(m[i][0] == 2){
                total[1] += m[i][3];
                } else if(m[i][0] == 3){
                        total[2] += total[2] + m[i][3];
                        } else if(m[i][0] == 4){
                            total[3] += m[i][3];
                                } else if(m[i][0] == 5){
                                        total[4] += m[i][3];
                                        }
    }

    //Impresion del total producido por cada taxi//
    printf("\n\n");
    for(i = 0; i < 5; i++){
        printf("El total producido del taxi %i es $%i\n", i + 1, total[i]);
    }
}


text:
Q: How to read a 16 bit value from memory I have a 4096K binary in memory, in little-endian format. I want to read a couple of the 8 bit values as a uint16_t how do I do it in the most performant manner?
void execute_cart (i6507_t* cpu, uint8_t* memory) {
    // uint16_t start = memory[0xFFFC]; // this address contains a 16 bit value
}

Update: I am running on x86-64 arch, the binary is for an old 8 bit console.

A: You'll need to read two bytes separately and combine them into a single uint16_t variable:
unsigned offset = 0xfffc;
uint16_t start = memory[offset];
start |= (uint16_t)memory[offset+1] << 8;

If memory starts an an address that is well aligned and if the offset is a multiple of 2, then you can do this in a single read:
uint16_t start = *(uint16_t *)&memory[0xfffc];


text:
Q: Translating screen touch position to world position in AR with AR Foundation I'm having a problem with translating the touch position into world coordinates. I want to be able to place an object where I clicked on the plane, but I'm having trouble with Z axis.
I'm translating the Vector2 touch position into world position using camera.ScreenToWorldPoint(), but I can't seem to get the Z axis right.
Vector3 pos = new Vector3(vector2.x, vector2.y);
pos = camera.ViewportToScreenPoint(pos);
Ray ray = camera.ScreenPointToRay(new Vector3(pos.x, pos.y, 0));
RaycastHit hit;

if (Physics.Raycast(ray, out hit))
{
    distance = hit.distance;
}

pos = new Vector3(pos.x, pos.y, distance);
return camera.ScreenToWorldPoint(pos);

A: There is no need/it makes no sense to convert it first via ViewportToScreenPoint .. Touch.position already is in pixel screen space.
Then you can directly pass it into ScreenPointToRay which expects such a pixel space position.
And finally if you already have a RaycastHit it makes no sense to again recalculate the 3D world space position via the hit.distance but rather simply directly use the RaycastHit.point!
So assuming that vector2 equals your touch position in pixel space it would rather be simply
var ray = camera.ScreenPointToRay(vector2);

if (Physics.Raycast(ray, out var hit))
{
    var hitPos = hit.point;

    // ... whatever you want to do with the hit position
}

open question is: What shall be returned if nothing is hit by the ray?


text:
Q: Ubuntu suspended - external harddrive no longer powers? I recently got a new laptop and I've just installed Ubuntu 12.04 on it. I went to transfer files over from my old laptop using my external hard drive and closed the lid when I went away, forgetting I hadn't changed the power settings to do nothing when the lid is closed, so the laptop suspended.
When I reopened the lid, later on, I realised this and got errors that the folders could not be transferred anymore as they did not exist.
My external harddrive is no longer powering up. Is this normal? Can it be fixed?

A: This is the result of the ( brain-damaged imho ) way Linux handles USB disks during suspend.  It can't be sure that you didn't unplug the disk, plug it into another computer, modify it, and plug it back in to this one while it was suspended, so it just assumes you did unplug the drive, and breaks the mount point.
You'll have to make sure the drive is unmounted ( a reboot will be sure to do the trick ), and then plug the drive back in, and fsck it.  You can do this with either the gnome-disk-utility or gparted.


text:
Q: static content page not working in springboot application deployed in Kubernetes cluster My spring boot application have a simple static html file which I kept in src/main/resources/static/index.html and I have added an extra controller to return this view.
public class HomeController {

    @RequestMapping(path = "${url_prefix}/")
    private String home() {
        return "index.html";
    }

}

On my local machine deploy http://localhost:8080/ navigating to the index.html.
Then the same application is deployed into the kubernettes cluster where
if navigate to the page then it returns

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Thu Jul 11 15:32:14 GMT 2019
There was an unexpected error (type=Not Found, status=404).
No message available

I checked the content of the deployed spring boot jar and I can see the index.html in that jar.
  9213 Thu Jul 11 17:10:08 CEST 2019 BOOT-INF/classes/static/index.html

I do not have much info about the kubernettes cluster configuration. I am vey well understood that without much info about the deployment scenario, no one can really help me.
But can some one please shed some lights from  higher level point of view ( I know the meaning of 404 error).


text:
Q: Can I get my WPF application to play an image sequence at 120 FPS without using so much memory? I'm writing an application to play back an image sequence of varying size (possibly 1000+ images) at variable FPS (up to 120), and while my current solution works for a small amount of images, it eats up memory very quickly (playing ~109mb of images takes ~526mb of Process Memory, and it seems to increase exponentially) and if given a large amount of images will produce an OutOfMemoryException.
My MainWindow and VideoViewer classes look like this -
MainWindow:
public partial class MainWindow : Window
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    VideoViewer vV = new VideoViewer();
    DispatcherTimer timer = new DispatcherTimer();

    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = vV;
    }

    private void PlayButton_Click(object sender, RoutedEventArgs e)
    {
        timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1f/120f) };
        timer.Tick += TimerTick;
        timer.Start();
    }

    private void PauseButton_Click(object sender, RoutedEventArgs e)
    {
        timer.Stop();
    }

    private void TimerTick(object sender, EventArgs e)
    {
        vV.NextFrame();
    }

    private void BrowseButton_Click(object sender, RoutedEventArgs e)
    {
        // Set the file dialog to filter for graphics files.
        this.openFileDialog1.Filter =
            "Images (*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|" +
            "All files (*.*)|*.*";

        // Allow the user to select multiple images.
        this.openFileDialog1.Multiselect = true;
        this.openFileDialog1.Title = "My Image Browser";

        DialogResult dr = this.openFileDialog1.ShowDialog();
        if (dr == System.Windows.Forms.DialogResult.OK)
        {
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                List<ImageSource> images = new List<ImageSource>();

                // Read the files
                foreach (String file in openFileDialog1.FileNames)
                {
                    var fullFilePath = @file;

                    //Create a new bitmap to assign our image to
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                    bitmap.CacheOption = BitmapCacheOption.None;
                    bitmap.UriSource = new Uri(fullFilePath, UriKind.Absolute);
                    bitmap.EndInit();

                    images.Add(bitmap);
                }

                vV.imagesArray = images;
            }
        }
    }
}

VideoViewer:
public class VideoViewer : INotifyPropertyChanged
{
    private ImageSource image;
    private List<ImageSource> imageLocs = new List<ImageSource>();
    private int imageIndex = 0;

    public event PropertyChangedEventHandler PropertyChanged;

    public ImageSource imageSource
    {
        get
        {
            return image;
        }
        set
        {
            image = value;
            OnPropertyChanged("imageSource");
        }
    }

    public List<ImageSource> imagesArray
    {
        get
        {
            return imageLocs;
        }
        set
        {
            imageLocs = value;
            OnPropertyChanged("imagesArray");
        }
    }

    public void NextFrame()
    {
        //If not on first or last frame
        if(imageIndex < (imageLocs.Count - 1))
        {
            imageIndex += 1;
            imageSource = imagesArray[imageIndex];
            OnPropertyChanged("imageSource");
        }
        else if(imageIndex == (imageLocs.Count - 1))
        {
            imageIndex = 0;
            imageSource = imagesArray[imageIndex];
            OnPropertyChanged("imageSource");
        }
    }

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

When playing the sequence, the first loop plays back slowly, and this is where the memory is taken up. After the first loop, it plays back at the desired speed and the memory sits at a constant value, which leads me to think it's something to do with the caching of the images.
As you can see I've tried adjusting the caching options of the bitmap image but it didn't make a difference. I'm also currently building to x64 to give myself extra memory to use.
Is it possible to reduce the memory usage while keeping the playback speed?

A: I managed to find a solution for 1000+ PNGs without converting the image sequence to a movie, so here's my advice for anyone trying to achieve this:

*

*Make sure you compress your images as much as possible. I managed to downsize my PNGs by 70-80% using online tools without noticeable loss in quality.

*Load all your images at app start-up. Since BitmapImage takes the number of pixels times 4 bytes of memory (regardless of image compression), you're better off saving the actual file streams as a MemoryStream array. I found that memory usage is quite stable and close to the size of your files.

*With each timer tick, convert your current MemoryStream to a BitmapImage and update the source of your Image. Feel free to adjust the framerate as desired.

A: Possible Attempts to use Less Bitmap Memory
Try creating the BitmapSource by using the .StreamSource property rather than .UriSource, and use the OnLoad cache option.
var fullFilePath = @file;

//Create a new bitmap to assign our image to

using (FileStream fs = new FileStream(path, FileMode.Open))
{
    BitmapImage bitmap = new BitmapImage();
    bitmap.BeginInit();
    bitmap.StreamSource = fs;
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.EndInit();

    images.Add(bitmap);

    bitmap.Freeze();
}

See:

*

*How do you make sure WPF releases large BitmapSource from Memory?

*http://www.thejoyofcode.com/WPF_Image_element_locks_my_local_file.aspx

*How to dispose BitmapImage cache?

*.NET Memory issues loading ~40 images, memory not reclaimed, potentially due to LOH fragmentation

Alternative Approach - Converting Your Sequence of Images into a Video and Playing that
Effectively what you are trying to do is implement the behaviour of a video player, but with a "selected" set of frames.
Another way of doing what you want in a more efficient manner, would to take those set of frames, and generate a video file (say an MP4).
There are a number of libraries you could use to do that:

*

*ffmpeg
https://ffmpeg.org/download.html

*ffmpeg Autogen (a wrapper for NET)
https://github.com/Ruslan-B/FFmpeg.AutoGen

*accord-net-extensions (VideoWriter)
https://github.com/dajuric/accord-net-extensions
Image sequence to video stream?

*dot-imaging library
https://www.codeproject.com/Articles/828012/Introducing-Portable-Video-IO-Library-for-Csharp
https://github.com/dajuric/dot-imaging/)

*Microsoft Media Foundation

*Media Foundation .NET wrapper
https://sourceforge.net/projects/mfnet/

*Some samples on encoding a video using media foundation (note one is UWP...but it should give clues on how to achieve same on FullFramework/WPF).
(H.264 image encoding using Media Foundation .NET)
https://codereview.stackexchange.com/questions/136144/h-264-image-encoding-using-media-foundation-net
(How to encode several images to a video in universal Windows apps)
https://code.msdn.microsoft.com/windowsapps/How-to-encode-several-to-a-053953d1
You could then just use the standard build in MediaElement to play that file.
To support looping you could use the ideas here:

*

*Replaying a video continuously in a WPF media element

Working Solution
As confirmed below, you ended up using the "Accord" library to generate a video file from the sequence of images, and then played that in a MediaElement.

*

*Image sequence to video stream?


text:
Q: Apply MSO conditional statements when sending email via Gmail API I have been sending basic and more advanced HTML emails from multiple addresses in a GSuite account using PHP and SwiftMailer.
I have been sending these emails via SMTP, authenticating with a username and password. This means I need Gmail's Less Secure Apps (LSA) enabled on all the accounts. These emails have been displaying well everywhere as far as I know - including older versions of Outlook.
Ensuring the LSA setting stays turned on and that we have the latest account passwords in the system is enough of a reason to switch to the API method. Additionally, I've read that GSuite accounts would not be allowed to continue using the LSA method soon - it was already supposed to have happened but was delayed due to the pandemic.
https://9to5google.com/2019/12/17/g-suite-less-secure-apps/
I set up a mail service account in GSuite. I'm not using Swiftmailer for sending, opting for the Gmail 'quickstart' PHP library. This works with basic HTML-formatted emails. When I say basic, I'm talking about header and strong tags and a little inline css for font color.
The next goal is to send a more complex HTML email which includes more styling, embedded remote images and some MSO conditional statements. The emails are being sent and delivered. The MSO conditional statements, like other tags including MS-specific doctype stuff, appear to be stripped out when I view the HTML source of the email. This HTML was working with SwiftMailer and SMTP.
The emails still look great in Gmail, my Android email app and Thunderbird. They do not look correct in anything Microsoft that I have tried - Outlook 07 and Win 10 Mail so far. I probably don't need to worry about Outlook 07 anymore, but if Win 10 Mail doesn't work, my fear is Outlook 365 and such don't either.
If I cannot use these MSO conditional statements that would likely mean a new, simpler email template. According to everything I've read however, these conditions are valid.
Below is a HTML email I've been trying to send but the conditions either don't work or are being stripped. I've also included the Google service code I use to send the message.
I tried various encoding options, meta tags and various conditional tags I found here. It doesn't make sense that Google would strip things away with the API if it doesn't using SMTP. Perhaps the key is using Swiftmailer with the API - another rabbit hole I've been trying to avoid.
The Code
<?php
    require_once 'Google/google-api-php-client/vendor/autoload.php';

    $fromAddress = "validaccount@gsuite.com";

    $user_to_impersonate = $fromAddress;
    $sender = $user_to_impersonate;

    putenv("GOOGLE_APPLICATION_CREDENTIALS=path_to_my_gmail_service_account_json_file");
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->setSubject($sender);
    $client->setApplicationName("Quickstart");
    $client->setScopes(["https://www.googleapis.com/auth/gmail.compose"]);
    $service = new Google_Service_Gmail($client);

    $fromName = "Sender Name";
    $sender = "validaccount@gsuite.com";
    $toAddress = "me@me.com";
    $toName = "My Name";
    $replyName = "Sender Name";
    $replyAddress = "validaccount@gsuite.com";

    $subject = "API Test";

    $strBody .= '<!DOCTYPE html>';
    $strBody .= '';
    $strBody .= '';
    $strBody .= '<meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="x-apple-disable-message-reformatting">
        <meta name="format-detection" content="telephone=no,address=no,email=no,date=no,url=no">
        <meta name="color-scheme" content="light">
        <meta name="supported-color-schemes" content="light">';
    $strBody .= '<title></title>';
    $strBody .= '';

    $strBody .= "";

    $strBody .= '<![if !mso]>  HTML meant for non-Outlook clients but it shows up everywhere  <![endif]>';

    $strBody .= '<![if mso]>  HTML meant for Outlook clients only but it shows up everywhere  <![endif]>';

    $strBody .= '  I read this might work better, but again it shows up everywhere  ';

    $strBody .= '';

    $strBody .= "Everybody can see this";

    $strBody .= "";

    $rawMsgStr = "From: =?utf-8?B?" . base64_encode($fromName) . "?=<{$sender}>\r\n";
    $rawMsgStr .= "To: =?utf-8?B?" . base64_encode($toName) . "?=<{$toAddress}>\r\n";
    $rawMsgStr .= "Reply-To: =?utf-8?B?" . base64_encode($replyName) . "?=<{$replyAddress}>\r\n";

    $rawMsgStr .= "Subject: =?utf-8?B?" . base64_encode($subject) . "?=\r\n";
    $rawMsgStr .= "MIME-Version: 1.0\r\n";
    //$rawMsgStr .= "Content-Language: en-US;\r\n";
    $rawMsgStr .= "Content-Type: text/html; charset=utf-8\r\n\r\r";
    //$rawMsgStr .= "Content-Transfer-Encoding: quoted-printable\r\n";
    //$rawMsgStr .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
    //$rawMsgStr .= 'Content-Transfer-Encoding: 7bit\r\n\r\n';
    $rawMsgStr .= "{$strBody}\r\n";

    // The message needs to be encoded in Base64URL
    $mime = rtrim(strtr(base64_encode($rawMsgStr), '+/', '-_'), '=');
    $msg = new Google_Service_Gmail_Message();
    $msg->setRaw($mime);
    //return $msg;

    $service->users_messages->send($sender, $msg);

    echo "Complete!";
?>

The Resulting Source (Outlook 2007)
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="x-apple-disable-message-reformatting">
        <meta name="format-detection" content="telephone=no,address=no,email=no,date=no,url=no">
        <meta name="color-scheme" content="light">
        <meta name="supported-color-schemes" content="light"><title></title>  HTML meant for non-Outlook clients but it shows up everywhere    HTML meant for Outlook clients only but it shows up everywhere    I read this might work better, but again it shows up everywhere  Everybody can see this

The Resulting HTML in Gmail (Thunderbird is very similar)
Content-Type: multipart/alternative; boundary="000000000000dc4b5d05bf2b6835"

--000000000000dc4b5d05bf2b6835
Content-Type: text/plain; charset="UTF-8"

 HTML meant for non-Outlook clients but it shows up everywhere HTML meant
for Outlook clients only but it shows up everywhere I read this might work
better, but again it shows up everywhere Everybody can see this

--000000000000dc4b5d05bf2b6835
Content-Type: text/html; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

<meta http-equiv=3D"content-type" content=3D"text/h=
tml; charset=3DUTF-8">
=09    <meta name=3D"viewport" content=3D"width=3Ddevice-width">=20
=09=09<meta http-equiv=3D"X-UA-Compatible" content=3D"IE=3Dedge">=20
=09=09<meta name=3D"x-apple-disable-message-reformatting"> =20
=09=09<meta name=3D"format-detection" content=3D"telephone=3Dno,address=3Dn=
o,email=3Dno,date=3Dno,url=3Dno">=20
=09=09<meta name=3D"color-scheme" content=3D"light">
=09=09<meta name=3D"supported-color-schemes" content=3D"light"><title></tit=
le>  HTML meant for non-Outlook clients but it shows up everyw=
here    HTML meant for Outlook clients only but it shows up everywhere    I=
 read this might work better, but again it shows up everywhere  Everybody c=
an see this

--000000000000dc4b5d05bf2b6835--

A: Well I eventually confirmed it I think. The Gmail API is stripping comments from HTML emails as well as simplifying the doctype tag by stripping out the MSO-related stuff. It's not just MSO conditions, it's any HTML comment in the body of the email. So, I guess this is a duplicate of the following, and as the OP in that thread recently discovered, this issue is not fixed and possibly by design in Google's eyes.
Why does the GMail API strip the doctype and comments from outgoing messages?
In the end I designed a more-basic HTML template without any MSO conditions to get around the limitations.


text:
Q: All FireFTP passwords gone after auto-update For the last six months (since the Firefox madness started and they keep on taking control of my PC) I'm terrified to touch Firefox.
Problem is however, I've been using it in my business (since once upon a time it was a trustworthy application with useful extensions like FireFTP) and that installation (and plugins) holds four years of information.
So Firefox continually deletes my important data (by) messing up (or blocking/or worse: auto-updating) my plug-ins, even crashing my computer as a result.
Today Firefox killed FireFTP by (again) autoupdating FireFTP without my permission, and I did my best to disable that nonsense in about:config).
Result: none of the (over 100) FireFTP accounts can be logged on to, they suddenly all ask for a password. I do not have the time to to find all of the passwords and reconfigure FireFTP again.
How can I undo the mess Firefox created once again? That is, where are the passwords, how do I downgrade?
As a side-question, how can I make Firefox behave again? I'm the boss of my computer, not them! How can I once and for-all take back control and completely kill every kind of auto-update feature?
Update:
I've been in contact with the (very nice and helpful) author of fireFTP and as turns out, the passwords should indeed have been stored in firefox itself (sadly). This was apparently since the very beginning (according to the author).
Upon further research, the passwords appear to have been deleted by firefox during the forced update 3.6.28 to 12.
Thank you firefox!!
So here is another documented and provable proof of the MESS Firefox has created in just 6 months.
Sadly the browser (that the modern internet was built on/for) is no longer safe to use for any business or long-term personal environment: deleting data is just unacceptable.
Funny, whilst on the official support forums serious complaints that boil down to the depriving of choice are quickly done away with; on the background.. some firefox developers themselves realize that exactly this stupid move just might have killed firefox instead of saving it. See http://www.afterdawn.com/news/article.cfm/2012/07/10/mozilla_dev_admits_firefox_killed_its_rep_with_huge_amount_of_updates
I agree: the by now widely documented breach of trust (no means NO) will be almost impossible to recover from.
Apart from the fact that more and more old-school users are starting to refer to firefox as "FaceFox" (since they cater to much of their specific wishes thereby crippling the browser from being a standards-compliant tool and force those cripplings to knowledgeable users through the updates).
I wonder what fresh team (with un-tainted reputation) will build the browser for the next decade, that will take over the market the same way firefox once did: by having the knowledgeable early adopters unanimously at their side, spreading the word to their family members and friends/colleagues. Remember the time when they informed people to use google instead of king altavista (do you even remember altavista?) or the time when those people informed people not use IE6 but firefox?
So the final answer to the question is: FireFTP passwords gone (after update)? Then they are gone. Complain to firefox (since that is one of the other reasons behind the rapid update-scheme: if users don't publically complain on a large scale, then they assume everything is fine: that is their solution to saving time on testing, enabling the rapid-release cycle. (I read this 7 months ago on a official firefox developer's blog))

A: The passwords are saved along with your other firefox passwords.
So, go to Tools » Options… or (Edit » Preferences… under Linux/OS X) and from there go to Security » Show Passwords » Show Passwords.
For disabling auto-update:

*

*Type about:config in the address bar

*In the filter field, enter: app.update.enabled

*Set it to false

*Then again type in the Filter field: app.update.auto

*Set it to false
And also uninstall Mozilla Maintenance Service; as far as I know, it's only use is to auto-update Firefox.


text:
Q: SharePoint add break after span I have a question about jquery SharePoint add break after span element.
I have a taxonomy field with single line of tekst. I want to break evry field  with a break.
With Jquery il try the first element and the second element span.
$("[id^='Stukken_x0020_toevoegen']").children('span').append( "<br />" );

what am I doing wrong

A: try to display - block span
.valid-text{display:block;}


text:
Q: Simplest way to convert a list to a set based on a boolean property? I have a list of Objects, each of which has a boolean "selected" property. I want these in a set if the "selected" property is true. Other than a for loop through the objects adding each to the set, is there another way to achieve this?

A: For something this simple just write a loop and be done with it.
If this is a pattern you're going to implement over and over:
(untested so there may be a typo or two)
public interface Selector<T> {
    public boolean select(T t); }

public <T> Set<T> grep(Collection<T> coll, Selector<T> sel) {
    Set<T> result = new Set<T>;
    for (T item : coll)
        if (sel.select(T))
            result.add(T);
    return result;
}

And the invocation
List<SomeClasss> input = ...;
Set<SomeClass>   output = grep(
    input,
    new Selector<SomeClass> {
        public boolean select(SomeClass item) {
            return some-boolean-function-of-item; // decide which items to keep here
        }
    }
);

Implementations of Selector know how to examine objects and decide if they should be kept.

A: You can use any functional java library for it.
For example, from my experience with Lambdaj ( http://code.google.com/p/lambdaj/ ):
Set<Entity> entitiesSet = new HashSet<Entity>(filter(having(on(Entity.class).getSelected(), equalTo(true)), entities));

A: Hm, I guess what you're searching for is a functional approach. I would recommend taking a look on either lamdaj (if you want to stick to Java and need an API only) or Scala (if you would like a richer set of features).
An example
The imperative version:
List<Sale> salesOfAFerrari = new ArrayList<Sale>();
for (Sale sale : sales) {
    if (sale.getCar().getBrand().equals("Ferrari"))
        salesOfAFerrari.add(sale);
}

You can do it in one line with lambdaj:
List<Sale> salesOfAFerrari = select(sales,
    having(on(Sale.class).getCar().getBrand(),equalTo("Ferrari")));

A: if you used java 8 you could do this :
List<MyObject> myList = Arrays.asList(a,b,c,d);

Set<MyObject> mySet = myList
        .filter(e -> e.getMyBool())
        .into(new Set<MyObject>());

Assuming a - d are just instances of your object with the boolean property. But java 8 is not out yet, so I would just use a for loop.


text:
Q: Why use 'new' when creating objects with associated pointers? I am learning C++ by reading a textbook. The "objects and pointers" part says, that declaring a pointer to an object like this :
SomeClass *ptrMyClass;

does nothing by itself. Only after defining an instance of Class does it make sense, like this :
SomeClass *ptrMyClass;
ptrMyClass = new SomeClass;

Or by combining these together in :
SomeClass *ptrMyClass = new SomeClass;

My question is, why do we have to create an instance of SomeClass on the heap by using 'new' ? So far in the book, pointers always pointed to 'normal' variables ( like int, float... ) that weren't created by using 'new'. Thank you.

A: There are two main ways of instantiating objects in C++: stack and heap (or free store). For example:
void func()
{
    // On the stack:
    Widget blah;

    // On the heap:
    Widget * foo = new Widget;
    delete foo;
}

The advantage of stack objects/variables is that they tend to be a little a faster to allocate/access, and they are slightly easier to work with. However, the stack is a limited size, and the data is usually limited to local scope (with the exception of global variables, which are usually inadvisable). That is, the blah object in the example above will be automatically destroyed as soon as func() ends. There's nothing you can do about that. Any pointers to stack objects/variables therefore become invalid (aka 'dangling') when the original item goes out of scope.
The heap is (typically) much bigger, so it can cope with a lot more data than the stack. It tends to be slightly slower, but it has the advantage of letting you reallocate things at run-time. By contrast, stack objects/variables (and especially arrays) are fixed at compile-time.
Additionally, after an object has been allocated on the heap, you can leave it there for as long as you need it, maintaining valid pointers to it. In the past, you would have to call delete eventually to avoid a memory leak. In modern C++, smart pointers are encouraged instead (e.g. std::shared_ptr).
As an additional note, it gets slightly more complex when declaring members of a class. If the object is instantiated on the stack, then any of its direct members (i.e. members by composition) will be on the stack too. If the object is instantiated on the heap, then all of its members will be on the heap.

A:
My question is, why do we have to create an instance of SomeClass on the heap by using 'new' ?

You don't. You can dynamically create an object with new. Alternatively you can get a pointer to an existing object
SomeClass* ptrMyClass1;     // An uninitialized pointer.

                            // If an automatic object its value is indeterminate and
                            // You have not defined what it points at. It should not
                            // be used (until you explicitly set it to something).

                            // If a static object then it is initialized to NULL
                            // i.e. Global (or other static storage duration object).

SomeClass* ptrMyClass2 = new SomeClass; // A pointer to a dynamically
                                        // allocated object.

SomeClass  objMyClass3;                 // A normal object
SomeClass* ptrMyClass4 = &objMyClass3;  // A pointer to a normal object

A: Why create an instance of a class in the heap
There is a case when you have to do this kind of stuff.
When you're using an abstract class with no concrete methods, and classes that inherit from that abstract class (in Java or PHP world we would talk about inheritance from an interface):
class IMyAbstractClass
{
public:
    virtual int myFunction(void) = 0;
};

class MyInheritedClass : public IMyAbstractClass
{
public:
    int myFunction(void)
    {
        // doSomething
        return 0;
    }
};

If you need to refer to instances of inherited classes, by the abstract class they inherit from, then the syntax is:
IMyAbstractClass * myInstance;
myInstance = new MyInheritedClass;

So what does it allow you to do?
After having declared your object this way, you can pass it to another object's constructor as being an instance of IMyAbstractClass:
AnotherClass anotherObject(myInstance);

This constructor being coded like that:
class AnotherClass
{
public:
    AnotherClass(IMyAbstractClass * instance)
    {
        // doSomething
    }
};

Real life example anywhere?
This kind of behavior is used in the Strategy design pattern.

A:
why do we have to create an instance of SomeClass on the heap by using 'new' ?

You don't have to. You can also reference an instance created on the stack:
SomeClass some;
SomeClass* ptrMyClass(&some);

A: Modern theorists dislike to use term "heap" in relation to dynamic allocation of objects. It's not clear how this term is coined but it conflicts with the name of so-called heap-like structures (a set with particular properties, a pile). C++ standard doesn't use such term.
The main difference between static, automatic and dynamic allocation is self-explnatory if such terms are used. Statically allocated objects have predetermined identity, even if in given context.
They are named, their count and size fully defined at compile time.
Automatically created objects are result of a entry to a function or code block. Their names are known as local variables.  Within particular block they have identity predefined by program, but every recursive or parallel call to fuction would create another copy automatically. They are destroyed at exit.
Dynamically allocated objects can be created as many times as programmer desires and decision whether to create one or not and how many can be made during execution, no new stack frame is required. Those objects can't be named, but can be referenced and some relation between locations of objects or subobjects can be deduced by pointer arithmetics. One could say that dynamic allocation can create a pile of objects, hence a result of any pointer arithmetic operations applied to objects which are not subobjects of same object is undefined.
In C++ the only way to create array of size unknown to programmer is dynamic allocation. C99 had portable analig of 'alloca' function, known as Variable Length Array, which allocates such array within stack frame. Some popular C++ compilers support VLA as an extension, to dismay of code checkers and confusion of beginners.


text:
Q: Does &mut T implements Borrow break a mutable reference rule? &mut T implements Borrow<T>,so (&mut T).borrow() will create &T. Does this break the rule that "if we have one mutable reference, we can not have any other references (mutable or not)"?
use std::borrow::Borrow;
let mut n = 1;
let r1: &mut i32 = &mut n;
let r2: &i32 = r1.borrow();

println!("log: {r1} {r2}");

The code compiles, but if I change r1.borrow() to &n, it will report error
What's the exact rule of the reference system?
Playground

A: This is more general than Borrow. You can do the same thing with regular references:
let r1: &mut i32 = &mut n;
let r2: &i32 = &*r1;

When you think about it, it's very necessary to be able to make immutable references from mutable references. For example, you need it to call &self methods on &mut variables.
But rust still ensures you aren't using the mut property of the variable.
Things you can do:

*

*Give out more & references

let r3: &i32 = &*r1;

*

*Use it behind another & reference

fn takes_ref_mut_ref(_: &&mut i32) {}
takes_ref_mut_ref(&r1);

*

*Copy types that implement Copy
let r4 = *r1;

*

*Deref to & (this does &*r1 implicitly)

fn print_three(a: &i32, b: &i32, c: &i32) {
    println!("{a} {b} {c}")
}
print_three(r1, r2, r3);

Things you can't do:

*

*Implicitly use it as a &&
fn takes_ref_ref(_: &&i32) {}
takes_ref_ref(&r1);

*

*Use it as &mut directly

fn print_three_mut(a: &mut i32, b: &i32, c: &i32) {
    println!("{a} {b} {c}")
}
print_three_mut(r1, r2, r3);

*

*And obviously, mutate the variable

*r1 = 5;

(playground)


text:
Q: React native error: undefined is not a function Estou tendo e seguinte erro no React native

React native error: undefined is not a function

import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { connect } from 'react-redux';
import  checkLogin  from '../actions/AuthActions';

export class Preload extends Component {

    static navigationOptions = {
        title: '',
        header: null
    }

    constructor(props) {
        super(props);
        this.state = {};

        this.props.checkLogin();
    }

    render() {
        return (
            <View style={styles.container}>
                <Text>Carregando... {this.props.status}</Text>
            </View>
        );
    }

}

const styles = StyleSheet.create({
    container: {
        margin: 10
    }
});

const mapStateToProps = (state) => {
    return {
        status: state.auth.status
    };
};

const PreloadConnect = connect(mapStateToProps, { checkLogin })(Preload);
export default PreloadConnect;

A: O seu mapDispatchToProps esta errado tu tem que fazer assim, porque da maneira que voce esta fazendo ele nao vai mapear os dados nas props do react :
const mapDispatchToProps = (dispatch) => ({
  checkLogin: () => dispatch(checkLogin())
})

export default connect(mapStateToProps, mapDispatchToProps)(Preload)


text:
Q: Update function on Three.js How make an Update function in Three.js, like in Unity3d?
I mean, that i create an object:
var torus = new THREE.Mesh(
          new THREE.TorusKnotGeometry(60,20,100),
          reflectionMaterial
        );
and when i click on the body, i change a reflectionMaterial. But the image don't change, i see  a not changed reflectionMaterial (last figure). Always redrawing a render image???
Thank's for attention. Sorry for my English (I'm from Ukrainian).
P.S.: I work with Three.js onn my netbook and on (not my) notebook. On netbook i don't see a shaders. Why?? Did the Three.js support Shader Model number 3 and 0?

A: If I understand your question, you are having issues changing a material after you click on something? You may need to change a flag depending on if you already have a material or not, there are some dependencies - check the link below:
material.needsUpdate = true;

There is an article on How to update things in Three.js


text:
Q: if i use FILTER_SANITIZE_URL will it change my url i have the url which looks this
http://www.skymount.in/civil-gallery?id=%2527759349-submenuid%2527

now i want my url to look neat and clean something like
http://www.skymount.in/civil-gallery/2527759349/2527

i don't even it is possible but i would like my url to look good now i have heard about this function in php FILTER_SANITIZE_URL using this will it make my url look good

A: Looking at the website the structure of the urls in the menu system appear a little different to what you cited above.
For instance: http://www.skymount.in/civil-gallery.php?id='496720-submenuid'
I don't see the subsequent submenuid in the url so I'm not 100% sure if what follows is more or less what you are attempting to do.
RewriteRule ^civil-gallery/([0-9]+)/([0-9]+)(/?)$ /civil-gallery.php?id=$1-submenuid=$2 [NC,L]
RewriteCond %{THE_REQUEST} /(?:civil-gallery\.php)?\?id=([^&\s]+)-submenuid=([^&\s]+) [NC]
RewriteRule ^ /civil-gallery/%1/%2\? [R=302,L,NE]

So, if you were to enter ( in the browser's address bar ) a url like
http://www.skymount.in/civil-gallery.php?id=98765-submenuid=12345

It would be re-written to
http://www.skymount.in/civil-gallery/98765/12345


text:
Q: jquery mobile ajax uploading ok but inserted data do not show on page I am new to jquery mobile and I have create multiple page and transition for them.
I want to load content for respective page when i change page to page.
Please help me, I only want to load data content for page.is this possible?
Thank and waiting for answers

A: The guestion seems very broad and I am not sure what are you asking but since you said you are new to jquery mobile I was wondering could you mean how to change pages in jquery mobile when you have all the pages in a single html file? If so you can browse jQuery.mobile.changepage documentation here and here is the code example to change a page.
<script>
    $.mobile.changePage( "../resources/us.html", { transition: "slideup", changeHash: false});
</script>


text:
Q: Should normalization completely weed out correlation? I have two variables: ordering & length. The former measures the ordering of a sequence (i.e. all permutations of A-B-C), and the former is the length of the sequence (i.e. A-B-C has a length of 3). These are highly correlated, and I want to normalize the ordering measure by length. I was expecting this normalization to completely eradicate the correlation - but it doesn't. How can this be the case?
id      order   length  order/length
X1      4           3   1.333333333
X33     2           1   2
X566    44          6   7.333333333
X681    4           2   2
X682    46          6   7.666666667
X80     2           1   2

correlation before normalization: 0.958
correlation AFTER normalization: 0.610

The correlation has been reduced, but the variables are still highly correlated. My ambition was to partial out the component of "order" that is separate from "length", but it doesn't seem like I'm achieving that here. How can I do this? Where has my thinking gone wrong?

A: Admittedly, this is just an operationalization of @whuber's comment (thanks!), but I still find it helpful to document it.
normalization <- function(order, length){
  data <- as.data.frame(cbind(order, length))
  model <- lm(order ~ length, data)
  order_normalized <- order-(model$coefficients[1]+(model$coefficients[2]*length))
  (order_normalized)
}

If you input the two variables into the function, it will normalize the former by the latter using least-squares.

A: Instead of normalizing by the length, I would suggest to normalize by the maximum possible number of subsequences for the given length $\ell$.
The maximum is reached for a sequence made of the repetition of the alphabet. E.g., if the alphabet is {A,B,C}, the maximum for a sequence of length 6, would be the number of subsequences of A-B-C-A-B-C.
An upper bound of this maximum is $2^\ell$. It is the maximum as long as $\ell$ does not exceed the size of the alphabet.


text:
Q: Assign a specific number of random rows into datasets in R I have a dataset with 54285 observations. What I need is to assign randomly 50% of the rows into another dataframe, 30% into another dataset, and the rest (20%) into another one. This should be done without duplicates.
This is an example:

data<-data.frame(numbers=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
data
1
2
3
4
5
6
7
8
9
10

What I expect would be:

df1
5
3
8
1
7

df2
2
4
9

df3
6
10

A: Multiply the ratio by number of rows in the dataset and split the data to divide them in separate dataframes.
set.seed(123)
result <- split(data, sample(rep(1:3, nrow(data) * c(0.5, 0.3, 0.2))))
names(result) <- paste0('df', seq_along(result))
list2env(result, .GlobalEnv)

df1

#   numbers
#1        1
#3        3
#7        7
#9        9
#10      10

df2
#  numbers
#4       4
#5       5
#8       8

df3
#  numbers
#2       2
#6       6

For large dataframes using sample with prob argument should work as well. However, note that this might not give you exact number of rows that you expect like the above rep answer.
result <- split(data, sample(1:3, nrow(data), replace = TRUE, prob = c(0.5, 0.3, 0.2)))


text:
Q: how to query the first element of object array in react May be object array word is not appropriate I just say what I understand
Let me explain what it the issue actually is I am getting product details from the API and
here I am sharing the screenshot from the redux dev tools which explains my response

My Actual Question is When I do
{
  product.images &&
    product.images.map((item, i) => (
      <img
        className="item-thumb prod_img"
        key={i}
        src={item.url}
        alt={`${i} Slide`}
        onClick={() => {
          change_img()
        }}
        style={{ cursor: 'pointer' }}
      />
    ))
}

This works fine but why when I try to product.images[1].url this gives an error saying i don't understand who t is 1

I am actually clueless about what's wrong here when console.log the type of that it says object from there I come to the analogy object array correct me if I am wrong
here is my ProductDetail.js
import React, { useEffect, useState } from 'react'
import { change_img } from './main'
import { useParams } from 'react-router-dom'
import { getProductDetails } from '../../action/ProductAction'
import { useDispatch, useSelector } from 'react-redux'
import { Loading } from '../../components'
const ProductDetails = () => {
  const dispatch = useDispatch()
  let { id } = useParams()

  const { loading, error, product } = useSelector((state) => state.singleProduct)

  useEffect(() => {
    dispatch(getProductDetails(id))
  }, [])

  return (
    <>
      {loading ? (
        <Loading />
      ) : error ? (
        <> Error </>
      ) : product ? (
        <>
          {' '}

                      <img
                        src={`${product ? product.images[1].url : null}`}
                        alt=""
                        id="main_img"
                        style={{ display: 'block', margin: '0px auto', cursor: 'pointer' }}
                      />

                      {product
                        ? product.images.map((item, i) => (
                            <img
                              className="item-thumb prod_img"
                              key={i}
                              src={item.url}
                              alt={`${i} Slide`}
                              onClick={() => {
                                change_img()
                              }}
                              style={{ cursor: 'pointer' }}
                            />
                          ))
                        : null}

Product name

                      132 reviews

                        {' '}
                         154 orders{' '}

                      <var className="price h4">Price: $ 1233</var>

                      Lorem ipsum dolor, sit amet consectetur adipisicing elit. Neque, natus recusandae. Fuga blanditiis alias ipsum ipsa
                      temporibus ullam, labore excepturi qui nam sunt!

Model#

Odsy-1000

Color

Brown

Delivery

Russia, USA, and Europe

                        Quantity

                            <button className="btn btn-light" type="button" id="button-plus">
                              {' '}
                              +{' '}
                            </button>

                          <input type="text" className="form-control" value="1" />

                            <button className="btn btn-light" type="button" id="button-minus">
                              {' '}
                              −{' '}
                            </button>

                    <button href="#" className="btn  btn-primary mx-2">
                      {' '}
                      Buy now{' '}
                    </button>
                    <button href="#" className="btn  btn-outline-primary ">
                      {' '}
                      Add to cart {' '}
                    </button>

{' '}
        </>
      ) : null}
    </>
  )
}

export default ProductDetails


text:
Q: Find location of pattern in 4d array I have 4 dimensional array objects of dimension (Nx, Ny, Nz, 3) filled of singular values (only -3, 0, and 3). For instance:
m = np.random.randint(low=-1, high=2, size=(1024, 1024, 512, 3), dtype=np.int8)*3

I am trying to find the location of different patterns on the last dimension (eg. (0, 0, 0), (3, 3, 0), ...) as follows:
def where_global(data, pattern):
    return (data == pattern).all(axis=3).nonzero()

def where_split(data, pattern):
    return ((data[:, :, :, 0] == pattern[0]) &
            (data[:, :, :, 1] == pattern[1]) &
            (data[:, :, :, 2] == pattern[2])).nonzero()

which gives me for example the following execution times:
%time idx = where_global(m, (3, 0, 0))
CPU times: user 27.1 s, sys: 339 ms, total: 27.5 s
Wall time: 27.5 s

%time idx = where_split(m, (3, 0, 0))
CPU times: user 5.64 s, sys: 313 ms, total: 5.95 s
Wall time: 5.95 s

I have to repeat this operation 27 times (the 27 combinations of -3, 3 and 0) and would like to optimize this process even more.
Is someone know a faster formulation than the one given in where_split?


text:
Q: See messages search matches in OS X High Sierra I do a search in the messages application on High Sierra and it lists the conversations that have matches. But it only shows one match on the screen even it says there are multiple matches. How can I scroll to the next match in the same conversation?

A: Found the answer, it's Command + G to go to the next result.


text:
Q: Show that $d_2$ defined by $d_2(x,y)=\frac{|x-y|}{1+|x-y|}$ is a metric I am pretty sure that this is such a stupid, stupid question, but how do you prove that $d_2(x,y)={|x-y|\over {1+|x-y|}}$ satisfying the third condition to be a metric, which is the triangle inequality.
I know that I should really be able to do this, but I just can't, I keep seeing a contradiction. Please help me.

A: $d_2 (x,y)+d_2 (y,z)=\frac{d(x,y)}{1+d(x,y)}+\frac{d(y,z)}{1+d(y,z)}$
$ \geq
 \frac{d(x,y)}{1+d(x,y)+d(y,z)}+ \frac{d(y,z)}{1+d(x,y)+d(y,z)} = \frac{d(x,y)+d(y,z)}{1+d(x,y)+d(y,z)}$
$= 1-\frac{1}{1+d(x,y)+d(y,z)} \geq 1-\frac{1}{1+d(x,z)}$
$= \frac{d(x,z)}{1+d(x,z)}=d_2 (x,z)$


text:
Q: Show next sibling element if is previous element hovered with pure JavaScript I have this snippet of html

ul { display:none }
test 1
test 2
test 3

  sub 1

Test 4

  sub 2

By default ul elements are hidden.
I'm trying to achieve when the a element is hovered to show only ul element which is the next sibling.
For example, if test 3 link has hovered, the ul element with sub 1 link needs to show up and to stay while the a and ul are hovered.
I'm not so experienced, so any help would be appreciated.

A: Have a look at adjacent sibling combinator
I add focus so you can keep the UL open
Also the a in the UL should be in an li. That makes it somewhat harder to make a sub-sub menu

ul { display:none; position: absolute; top:50px }

a:hover + ul { display: block }

a:focus + ul { display: block }
test 1
test 2
test 3

sub 1

Test 4

sub 2


text:
Q: Entity Framework Many-Many Polymorphic Relationship I have a requirement to store images related to various entities in a database (sorted in a particular order), where the images are selected from a central 'media library'. I'm accessing the data with Entity Framework 6.
The general scenario is there's a central table of images, which users can relate to various entities within the system (e.g. locations can have images, users can have images - a location can re-use the same image used by a user).
In my head, the structure is as below. I'm having trouble figuring out what the implementation would look like as an Entity Framework entity layout.
I've looked at answers such as Entity Framework Polymorphic associations (Table-Per-Type?) but they seem to take the approach of linking EntityWithMedia1 and EntityWithMedia2 so they are related with a parent table, but this situation doesn't really lend itself to this approach in my opinion (e.g. the two entities happen to both include media, but should remain completely separate in terms of DB structure).
Media {
        ImageId (int)
        ImageName (string)
        ImageFileName (string)
        RelatedEntities (list) // Queries RelatedMedia table
}

RelatedMedia {
        ImageId (int)
        EntityWithMediaId (int) // Actual Id of the Entity to be used with Type below
        EntityWithMediaType (string) // In my head this says 'SomeEntity1' or some other ID such as a guid defined on the entity in c# (the 'Laravel approach')
        SortOrder (int)
}

SomeEntity1 {
        SomeEntity1Id (int)
        EntityName (string)
        SomeProperty (int)
        RelatedMedia (list) // Queries RelatedMedia table
}

SomeEntity2 {
        SomeEntity2Id (int)
        EntityName (string)
        AnotherProperty (string)
        RelatedMedia (list) // Queries RelatedMedia table
}

If this isn't supported out of the box, is there much scope to implement this by extending EF (e.g. write my own query so EF knows what to do when I try to use the RelatedEntities/RelatedMedia properties)?

A: When you want to join objects that don't have a physical relation ( SomeEntity1 / RelatedMedia ), you have to write your join clause, using the join keyword.
For instance:
var query =
   from media in context.RelatedMedias
   join entity in context.Entities on media.EntityWithMediaId equals entity.SomeEntityId
   where entity.EntityWithMediaType == "EntityType"
   select new { Media = media, Entity = entity };

If you want to load for a specific object:
var entity;
var medias = context.RelatedMedias.Where(i => i.EntityWithMediaType == "EntityType" && i.EntityWithMediaId == entity.EntityId);


text:
Q: How to update activity after uses changes appearance from preferences? When a user opens preferences on my app he may make changes for example changing the app theme.
The documentation for ContextThemeWrapper.setTheme(int) says:

Set the base theme for this context. Note that this should be called before any views are instantiated in the Context (for example before calling setContentView(View) or inflate(int, ViewGroup)).

So my first thought was restarting the app onResume() when the user changed the preferences. However I noticed that sometimes the process of restarting the activity is seamless while other times the activity is closed, the home screen is seen and only after some seconds the app opens again.
I'm wondering if there is a way to change handle the preferences changes. Like for instance changing the theme after onResume without restarting the activity or restarting the activity on the background while the user is on preferences.
What's the right way to handle this?

A: Assuming that your Preference screen is an Activity, when the user navigated to it, MainActivity was placed on a paused state (and then probably on a stopped state). When the user navigates back to MainActivity onResume() will be called; here you can change the sate of MainActivity accordingly to reflect the preferences that were changed.

A: I'm assuming you are storing user's selected theme in App Preferences. So in your Activity's onCreate(), add setTheme().
public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.Theme); // or whatever theme you're using

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
}

But changes don't take effect until the activity is restarted. So if you need to immediately apply theme changes, call recreate() afterwards applying theme:
// Might need to call them on getApplication() depending on Context
setTheme(userSelectedTheme);
recreate();

Also, as Attiq mentioned, re-creating an activity might result in loss of data fetched from network using Threads/AsyncTasks so you need to take that in to account as well.

A: When a user opens preferences on my app he may make changes that mean I have to restart my MainActivity however I don't want to user to notice anything happened.

User will not notice anything because, the activity life cycle will take care.
Tasks - EVENT 1 Main Activity (MA) TO Preference Activity (PA)
EVENT 2  Preference Activity (PA)TO Main Activity
Activity Life Cycle - MA onPause() TO PA onResume() ... PA onPause() TO MA onResume()
 nor remove it from the back stack.

If you want the same activity from backstack to resume and not a new MainActivity to be created, this can be done using launchmodes
Code sample
intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
        startActivity(intent);

A: Our application is offering multiple themes and we have already tried methods like updating themes from onResume or onStart[restart activity case] but it's requires onCreate() method calls to update the themes, you need to finish the activity and recreate it using selected themes.
Important point: Re-creating new activity might result in lose of data fetched from network using threads or asynctask in the activity so you need to take this issue as well.
In our application, we are saving the number of selected theme in the sharedpreferences and loading it during the creation of new activity.
To finish and restart the activity
public static void changeToTheme(Activity activity, int theme) {
    sTheme = theme;
    activity.finish();

    activity.startActivity(new Intent(activity, activity.getClass()));
}


text:
Q: Mozilla won't show special characters (such as chinese, korean, japanese, etc...) just numbers in squares on Debian I just installed Debian 10.3 and when I try to read special characters i see what is shown on the picture below. What am I supposed to do?
I've read some solutions, but they were only for arch linux, I am not sure how to do it on Debian. Any suggestions?

A: It looks like your system has no font which includes the special or asian glyphs. The package fonts-noto should contain fonts for all eventualities.


text: Q: Flutter Screen Recorder with Internal system audio I am working on a flutter project which needed to record the mobile screen along with the internal system audio. I don't need to record the audio from the mic. need to record the audio from the system instead, like we screen record gameplay in PC. How can I achieve this? thanks in advance.


text:
Q: Convert single LINQ value to string I am pulling a single value from the db using LINQ:
    public string GetPoliceDepartmentName(int id)
    {
        var PoliceDepartmentName = from p in db.PoliceDepartmentList
                                   join l in db.TrespassOrder on p.PoliceDeptId equals l.PoliceDepartmentId
                                   where l.IncidentId == id
                                   select p.DepartmentName.Single();
        return PoliceDepartmentName.ToString();
    }

The method runs, but instead of returning the expected "Boston PD", it returns System.Data.Objects.ObjectQuery`1[System.Char]
I'm not sure why my method isn't converting from queriable to string.  I will keep researching, but a hint would be nice at this point.

A: You're calling Single on string, which is IEnumerable<char>, so you'll get first (and only) char from string. That's probably not what you're looking for.
With proper brackets, you won't need ToString call at all, because PoliceDepartmentName will be types as string automatically.
var PoliceDepartmentName = (from p in db.PoliceDepartmentList
                           join l in db.TrespassOrder on p.PoliceDeptId equals l.PoliceDepartmentId
                           where l.IncidentId == id
                           select p.DepartmentName).Single();
return PoliceDepartmentName;

A: You need brackets :
(from p in db.PoliceDepartmentList
 join l in db.TrespassOrder on p.PoliceDeptId equals l.PoliceDepartmentId
 where l.IncidentId == id
 select p.DepartmentName).Single();


text:
Q: How to create a console application using Roslyn programmatically? My goal is to create a console application using Roslyn programmatically:
string codeToCompile = @"
using System;
public class Program
{
    public static void Main()
    {
        Console.WriteLine(""Hello World!"");
        Console.ReadLine();
    }
}";

// Parsing the code into the SyntaxTree
var syntaxTree = CSharpSyntaxTree.ParseText(codeToCompile);
var dotNetCoreDir = Path.GetDirectoryName(typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly.Location);

var refPaths = new[] {
    typeof(Object).GetTypeInfo().Assembly.Location,
    typeof(Console).GetTypeInfo().Assembly.Location,
    Path.Combine(dotNetCoreDir, "System.Runtime.dll")
};

var references = refPaths.Select(r => MetadataReference.CreateFromFile(r)).ToArray();

// Compiling
var compilation = CSharpCompilation.Create(Path.GetRandomFileName())
                                   .WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
                                   .AddReferences(references)
                                   .AddSyntaxTrees(syntaxTree);

compilation.Emit("output.exe", "output.pdb");

However the generated output.exe doesn't work as Windows executable:

Unhandled Exception: System.IO.FileNotFoundException: Could not load
file or assembly 'System.Private.CoreLib, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=<7cec85d7bea7798e' or one of its
dependencies. The system cannot find the file specified.

But it does seem to work using the Dotnet tool:
dotnet output.exe // Hello World!

My understanding: .NET Core assemblies cannot be invoked directly, which is why I wasn't able to execute the assembly in the first case. Instead, I must use a CoreCLR host.
My question: would it be possible to modify my approach to create an executable that can be run directly?


text:
Q: Do not overwrite settings.settings file with clickonce At first I had some userdefined settings stored in my app.config file, under appSettings.
These are properties the user can change during runtime.
The first problem I've got is when I deploy my application with ClickOnce it overwrites the app.config file and the user has lost his personal settings.
Then I moved the properties to the settings.settings file (= usersettings section in app.config) as I found on the internet that this section doesn't get overwritten when deploying with ClickOnce. Nah, it does..
Settings.Settings properties are:

*

*Build action = content

*Copy to = Do not copy

So how can I accomplish that my user's personal settings are not overwritten, either in the app.config file or the settings.settings file. Or is there another way and am I doing it wrong?
Thx!

A: This method copies the settings from the previous installation when deploying a new version of the application with ClickOnce.
So any user defined settings that the user made will be copied and thus available after the update. I tested this and it works for me.
public static void UpgradeUserSettings()
{
  if (Settings.Default.upgradeRequired)
  {
    Settings.Default.Upgrade();
    Settings.Default.upgradeRequired = false;
    Settings.Default.Save();
  }
}

ApplicationSettingsBase.Upgrade Method MSDN
other question on StackOverflow


text:
Q: How to include Google map to show places like hospital and restaurant in separate maps on same page I am using this script to show the restaurant in the nearby area

If I include the second script and change the type to school or hospital,
  types: ['restaurant'] the nearby location does not show in first map by all in the last script.
HTML

  Restaurant

   Hospitals

  Schools

The bootstrap tab is not loading the other tabs with the maps.
* Here I am testing these maps by putting the map div outside div*
So basically two questions,
How to show the different places in different maps and how to use load the map in the tab that are not active as well.

A: Include  bootstrap.js/ bootstrap.css, jquery.js and google map script
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Tab Load of Map</title>
    <link href="assets/bootstrap/css/bootstrap.css" rel="stylesheet">
    <link href="assets/css/stylesheet.css" rel="stylesheet">

Google Map Inside Tab Panel

   Location on Map

   Hospitals

  Schools


text:
Q: Why does a custom test() function only output first error? I have a class, which among other things stores vectors of a few other objects I have defined. I want to define a test() function which checks to see if all the objects are in a valid state and then call this via assert so that it only runs in debug mode and outputs each error that is found. However, only the first error is outputted.
Consider the following toy example:
class Foo
{
public:
    Foo(int index, int data) : _index(index), _some_data(data) {}

    bool test() const
    {
        bool valid = true;
        if (_some_data == 0)
        {
            std::cout << "Error! Foo " << _index << " has invalid data.\n";
            valid = false;
        }
        return valid;
    }

private:
    int _index;
    int _some_data; // for this example, should be non-zero
};

class MyClass
{
public:
    MyClass(std::vector<Foo> foos) : _foos(foos) {}

    bool test() const
    {
        bool valid = true;
        for (auto &foo : _foos)
        {
            valid = valid && foo.test();
        }
        return valid;
    }

private:
    std::vector<Foo> _foos;
};

int main()
{
    Foo foo1(0, 0);
    Foo foo2(1, 0);
    Foo foo3(2, 0);

    std::vector<Foo> foos({foo1, foo2, foo3}); // all three foos in invalid state

    MyClass my_class(foos);
    assert(my_class.test()); // outputs "Error! Foo 0 has invalid data." But does not show me errors in other two foos
}

Why does this output only the first invalid Foo and not every invalid Foo?
I guess this has something to do with the compiler trying to optimise the code (I'm running GCC). As soon as valid is equal to false it does not bother running the rest of the loop. How do I prevent this?


text:
Q: How to detect an empty line in java scanner I've searched a lot but found nothing that can solve this problem. I'm using nextInt to read the input from the user, but if the user enters nothing (just presses enter), it will loop infinitely until the user enters something. But what I want is to stop the program if the user enters nothing, and tell them "this is empty". What should I do? Could someone help me please?
Thanks in advance.
import java.util.Scanner;

public class Compare{
    public static void main(String[] args){

        Scanner scan = new Scanner(System.in);

        if (scan.hasNextInt()){

            int num1 = scan.nextInt();
            int num2 = scan.nextInt();

            int Difference = Math.abs(num2 - num1);

            if (num1 == num2) {
                System.out.println("They are equal");
            }else if (num1 < 0 | num2 < 0){
                System.out.println("No negative number!");
            }else{
                System.out.println("Their difference is " + Difference);
            }
        }else{
            System.out.println("Wrong! Please enter correct number");
        }
    }
}

A: This piece of code checks if the user pressed <Enter>. If they did then we print out "User pressed enter".
If they pressed something else then we attempt to parse the line as an integer.
import java.util.Scanner;

public class Play {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // The sc.nextLine() call will retrieve
        // the line that the user entered.
        String lineEnteredByUser = sc.nextLine();

        // If the user presses an empty line
        // the lineEnteredByUser variable will contain
        // the empty String "".
        if ("".equals(lineEnteredByUser)) {
            System.out.println("User pressed enter");

        } else {
            // If the user entered something else then
            // we try to parse it as an `int` using
            // `Integer.parseInt`. A NumberFormatException
            // might occur if the use did not input an int.
            int result = Integer.parseInt(lineEnteredByUser);
            System.out.println("User pressed " + result);
        }
    }
}

If we run the above java code (which I placed in a file called Play.java) we get the following:
$ java Play.java
1
User pressed 1

$ java Play.java

User pressed enter

$ java Play.java
1.2
Exception in thread "main" java.lang.NumberFormatException: For input string: "1.2"

The docs for the functions that I used you can find over here: parseInt, nextLine

A: You can take the input using scan.nextLine() and then check whether user gave an input with a correct pattern IN A SINGLE LINE. You can prompts the user to give the input in a single line separated by a space:
System.out.println("Please enter two numbers in a single line separated by a space. (i. e.: 4 12)");

You can check the pattern and do your job through split and parsing as folows:
if (Pattern.matches("\\d+ \\d+", input)) {
        String[] nums = input.split(" ");
        int num1 = Integer.parseInt(nums[0]);
        int num2 = Integer.parseInt(nums[1]);
        ....
}

The full program is as below:
public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    String input = scan.nextLine();
    if (Pattern.matches("\\d+ \\d+", input)) {
        String[] nums = input.split(" ");
        int num1 = Integer.parseInt(nums[0]);
        int num2 = Integer.parseInt(nums[1]);
        if (num1 == num2) {
            System.out.println("They are equal");
        } else if (num1 < 0 || num2 < 0) {
            System.out.println("No negative number!");
        } else {
            System.out.println("Their difference is " + Math.abs(num2 - num1));
        }
    } else {
        if (input.isEmpty()) {
            System.out.println("This is Empty");
        } else {
            System.out.println("Wrong! Please enter correct number");
        }
    }
}

UPDATE
If you want to make your program supportive to both single line input and double line input, you can refactor the code as follows:
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter two numbers in a single line separated by a space. (i. e.: 4 12)");
    String input = scan.nextLine().trim();
    if (input.matches("\\d+ \\d+")) {
        doParsingAndCalculation(input);
    } else {
        if (input.isEmpty()) {
            System.out.println("This is Empty");
        } else if (input.matches("\\d+")) {
            String secondLine = scan.nextLine().trim();
            StringBuilder stringBuilder = new StringBuilder(input);
            if(secondLine.matches("\\d+")) {
                stringBuilder.append(" ").append(secondLine);
                doParsingAndCalculation(stringBuilder.toString());
            } else {
                System.out.println("Wrong! Please enter correct number");
            }
        }
        else {
            System.out.println("Wrong! Please enter correct number");
        }
    }
}

private static void doParsingAndCalculation(String input) {
    String[] nums = input.split(" ");
    int num1 = Integer.parseInt(nums[0]);
    int num2 = Integer.parseInt(nums[1]);
    if (num1 == num2) {
        System.out.println("They are equal");
    } else if (num1 < 0 || num2 < 0) {
        System.out.println("No negative number!");
    } else {
        System.out.println("Their difference is " + Math.abs(num2 - num1));
    }
}

A: scanner.hasNext() will always be true and the loop won't end, because there is always a string input even though it is empty "".
You can use this statement: if(line.length() == 0) break;

A:
I'm using nextInt to read the input from the user, but if the user enters nothing (just presses enter), it will loop infinitely until the user enters something.

That is true, assuming that the Scanner reads from standard input.  (The nextInt call will just keep reading until it gets non-whitespace characters.)
So if you want to give the user the option of typing ENTER to stop, you should not call nextInt() on the Scanner directly.  Instead, you could call nextLine() to get a complete input line from the user.  Then attempt to parse the line as an integer; e.g. using new Scanner(theLine).nextInt().
There are a number of possible variations on this.

If your goal is (literally) just to test for an empty line, then call Scanner.nextLine() and test if the result is an empty string.  However, you need to take account of what happened to the scanner before you called nextLine().  For example, if the last thing you did was (successfully) call nextInt(), then there will still be characters after the number ... on the current line.  You would need to "consume" those characters (with an extra nextLine() call) before you can read the next line.

A: Scanner scanner = new Scanner(System.in);
String nextLine = scanner.nextLine() ;

you can check  nextLine.equals("")  is an empty string  or not.


text:
Q: Add a Twitter field to user profiles Has anyone considered the potential of having a Twitter ID field in the profile (or fields for other similar microblogging/social networking services) so that those who want to can advertise their other profiles, allowing people to network with people in their field?
The particular value of this, I feel, is more in Stack Exchange sites where the sites are often much more specialised and you are participating in a small community where it's useful to keep tabs on who's doing what.

A: You can add your twitter link to your profile's Website field or in your about me secion:
my twitter

I think that would be just as effective.


text:
Q: How to compare the values of three matrices are equal? I'm new to Matlab. I need help with matrix comparison.
I have three matrices: R, S and T (size: 95956 x 1) and I need to compare all of their elements and see which elements are equal. Then we multiply the same values by a fourth matrix.
In a Matlab file, I read the coordinates and separate them into three matrices. Thus obtaining matrices R, S and T saved in "data.mat". Then I read in another file "data.mat" and used a For loop:
for t=1:1:length(CoordinateIndex)
    index = R == S;
    ts=ts+1;
end

Is this correct and how I will multiply only those values which are equal to a fourth matrix?

A: Using some simple example matrices and logical indexing, we can find the values that are common among all three via:
R = [1:4 1:4 1:4 1:4];
S = [1:2 1:2 1:4 1:6 1:2];
T = [1:6 1:2 1:8];
R_common = R(R==S&R==T);

This produces:
R_common =

     1     2     1     2     3     4

If you want the indices that are common among all three matrices, use:
I = find(R==S&R==T);

which gives
I =
     1     2     9    10    11    12

EDIT: As @Adiel suggested, you may be interested in the values that are common among the matrices regardless of their location in the matrices. This can be accomplished simply via the intersect function (also see this):
RST_intersection = intersect(intersect(R,S),T)

For my example matrices this gives
RST_intersection =

     1     2     3     4

Note that the arguments to intersect can be different lengths, which may be helpful.


text:
Q: Import external json file to package.json I have a module with extra configuration into package.json file
This configuration can grow a lot and I would like to put it in a separate file so I can import it to the package.json and get extra configurations from that file  (something like index config file).
Something like this:
external.json file:
{
    "moduleConf": {
      "some_conf": "dist/...",
      "some_conf2": "dist/...",
     }
}

And then import to package.json like this:
"my-module": "../external.json"

I have tried many configurations but none works for me
example of my Package.json
{
"scripts": {
 "build-my-module": "cd src && copyfiles moduleConf/**/*.png moduleConf/**/**/*.png
 moduleConf/**/*.html moduleConf/**/**/*.html ../dist/"
  },

 "main": "...js",
  "my-module": {
    "moduleConf": {
      "some_conf": "dist/...",
      "some_conf2": "dist/...",
        ...
    }
  },
  "devDependencies": {
      "my-module": "^0.0.0",
   },
  "dependencies": {
      ...
   }

}