text:
Q: Calculate average price of stock from a dataframe I have a data frame save order history when trading stock. The example data will be shown below:
import pandas as pd

date = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
price = [1020, 1050, 1110, 1080, 1050, 1020, 1050, 1110, 1080, 1050, 1050, 1140, 1110, 1100, 1140, 1170, 1200]
vol = [100, 0, 200, 0, -300, 100, 0, 200, 0, 0, 0, -100, -100, 100, 0, 0, -200]
df = pd.DataFrame({'date': date, 'price': price, 'vol': vol})

I want to calculate the average price of the trades I have made.
I have tried many methods and still can't seem to get it right.
This is my approach:
sum_stock = np.frompyfunc(lambda a, b: 0 if a + b < 0 else a + b, 2, 1)
df['num_of_stocks'] = sum_stock.accumulate(df.vol.values)
df['bought_price'] = df.loc[df['num_of_stocks'] > 0, 'price']
df['bought_vol'] = df.loc[df['num_of_stocks'] > 0, 'vol'].apply(lambda x: max(x, 0))
df['bought_value'] = df['bought_price'] * df['bought_vol']
sum_value = np.frompyfunc(lambda a, b: a + b if b == b else 0, 2, 1)
df['cumulative_bought_value'] = sum_value.accumulate(df['bought_value'].values)
df['cumulative_bought_vol'] = sum_value.accumulate(df['bought_vol'].values)
df['avg_price'] = df.loc[df['cumulative_bought_value'] > 0, 'cumulative_bought_value'] / df.loc[df['cumulative_bought_vol'] > 0, 'cumulative_bought_vol']
df = df.fillna(0)

And this is output:
avg_price = [1020.0, 1020.0, 1080.0, 1080.0, 0.0, 1020.0, 1020.0, 1080.0, 1080.0, 1080.0, 1080.0, 1080.0, 1080.0, 1085.0, 1085.0, 1085.0, 0.0]

Look the output, I can see that if I buy, hold, and sell all. My code will correct.
However, if I buy, hold, sell a portion, and then buy again, it will result in an error in the calculation of the average price.
This is my desired output:
avg_price = [1020, 1020, 1080, 1080, 0, 1020, 1020, 1080, 1080, 1080, 1080, 1080, 1080, 1090, 1090, 1090, 0]

I will explain:
On the first day, I bought 100 shares at a price of 1020, so the average price is 1020.
On the second day, I did not buy or sell, so the average price remained unchanged.
On the third day, I bought 200 shares at a price of 1110, so the average price became $(100 * 1020 + 200 * 1110) / (100 + 200) = 1080$.
On the fourth day, I did not buy or sell, so the average price remained unchanged.
On the fifth day, I sold all of my shares, so the average price became zero.
Similarly, from the sixth to the thirteenth day, I obtained the average price as indicated in the output.
However, on the fourteenth day, I bought 300 shares and sold 200 shares before. At this point, I had 100 shares remaining, and the average price was 1080. Then, I bought an additional 100 shares at a price of 1100. The new average price would be $(100 * 1080 + 100 * 1100) / (100 + 100) = 1090$.
My code is incorrect because I have used the total bought value until the number of shares becomes zero. Can you please help me find the desired output without using a for loop? Thank you!

A: I couldn't think of a way of doing this without looping, because calculating the average price of your current stocks is dependent on both the information of the current row, and the outcome of the same calculation of the previous row. Due to this iterative nature of the problem, I solved it like this:
# create a column with cumulative volume, which represents your stock level on any given day.
df['cumvol'] = df['vol'].cumsum()

# Set the first average price (we need an inception)
df.loc[0,'avg'] = df.loc[0,'price']

# loop over the remaining rows.
for i in range(1,len(df)):
    if df.loc[i, 'vol'] == 0:
        # take previous row value
        df.loc[i, 'avg'] = df.loc[i-1, 'avg']
    elif df.loc[i, 'vol'] > 0:
        # calculate new average
        df.loc[i, 'avg'] = ((df.loc[i-1, 'cumvol']*df.loc[i-1, 'avg']) + (df.loc[i, 'vol']*df.loc[i, 'price'])) / (df.loc[i, 'cumvol'])
    elif (df.loc[i, 'vol'] < 0) & (df.loc[i, 'cumvol'] > 0):
        # take previous row value
        df.loc[i, 'avg'] = df.loc[i-1, 'avg']
    else:
        # vol < 0 and cumsum = 0
        df.loc[i, 'avg'] = 0
print(df)

    date  price  vol  cumvol     avg
0      1   1020  100     100  1020.0
1      2   1050    0     100  1020.0
2      3   1110  200     300  1080.0
3      4   1080    0     300  1080.0
4      5   1050 -300       0     0.0
5      6   1020  100     100  1020.0
6      7   1050    0     100  1020.0
7      8   1110  200     300  1080.0
8      9   1080    0     300  1080.0
9     10   1050    0     300  1080.0
10    11   1050    0     300  1080.0
11    12   1140 -100     200  1080.0
12    13   1110 -100     100  1080.0
13    14   1100  100     200  1090.0
14    15   1140    0     200  1090.0
15    16   1170    0     200  1090.0
16    17   1200 -200       0     0.0


text:
Q: POST error 500 - jersey 2 rest api application Problem
I have a simple rest application with low complexity built using jersey 2. I use maven for dependency management. I was getting cors issue with post request(JSON) from angular app. It was working fine with other content type except for json payloads. requests with json data was working fine in  postman. Then I created a CORSFilter. Now the error is changed and everything is stopped working.
I need

*

*to find whether my project setup is correct or not

*to find what the blunder I have done

*send post request from angular app with json data and get response

Project deployment assembly
https://imgur.com/a/TolLvEJ
Project facets
https://imgur.com/a/Eqga93Z
My project structure
https://imgur.com/a/VZMP5Vu
I have followed so many suggestions and workarounds. Maybe I was wrongly following them.
My pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>OnlineOrganicMarket</groupId>
    <artifactId>OnlineOrganicMarket</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <release>11</release>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.1</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <jersey2.version>2.27</jersey2.version>
        <jaxrs.version>2.1</jaxrs.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm</artifactId>
            <version>6.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>

        <dependency> <groupId>javax.ws.rs</groupId> <artifactId>javax.ws.rs-api</artifactId>
            <version>${jaxrs.version}</version> </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>2.26-b03</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.27</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <version>2.27</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-json-org</artifactId>
            <version>2.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
    </dependencies>
</project>

My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>OnlineOrganicMarket</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>com.oom.services</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/api/*</url-pattern>
  </servlet-mapping>

</web-app>

CORS filter
package com.oom.services.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

import org.glassfish.jersey.server.ExtendedUriInfo;

@Provider
@Priority(Priorities.HEADER_DECORATOR)
public class CORSFilter implements ContainerRequestFilter, ContainerResponseFilter {
 private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
 private static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
 private static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
 private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
 private static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
 private static final String AUTHORIZATION = "authorization";
 private static final String ORIGIN = "Origin";

 private static String extractAllowedMethods(final ExtendedUriInfo extendedUriInfo) {
  final Optional<Class<?>> optional = extendedUriInfo.getMatchedRuntimeResources().stream()
    .flatMap(r -> r.getResources().stream()).flatMap(r -> r.getHandlerClasses().stream())
    .filter(r -> r.getPackage().getName().startsWith("com.oom.services")).findFirst();

  if (optional.isPresent()) {
   return Arrays.stream(optional.get().getDeclaredMethods())//
     .flatMap(m -> Arrays.stream(m.getAnnotations()))//
     .map(a -> a.annotationType().getAnnotation(javax.ws.rs.HttpMethod.class))//
     .filter(Objects::nonNull)//
     .map(HttpMethod::value)//
     .distinct()//
     .collect(Collectors.joining(", "));
  }
  // Returning OPTIONS is a bit shady, as ACAM is about *real*, actual methods only.
  return "OPTIONS";
 }

 @Context
 private HttpServletRequest request;

 @Context
 private ExtendedUriInfo extendedUriInfo;

 @Override
 public void filter(final ContainerRequestContext requestContext) throws IOException {
  final String origin = requestContext.getHeaderString(ORIGIN);
  if (origin != null && "OPTIONS".equals(requestContext.getMethod())) {
   request.setAttribute(this.getClass().getName(), true);
   requestContext.abortWith(Response.ok("CORS OK, carry on.", MediaType.TEXT_PLAIN_TYPE).build());
  }
 }

 /**
  * @see https://www.w3.org/TR/cors/
  * @see https://jmchung.github.io/blog/2013/08/11/cross-domain-on-jersey-restful-web-services/
  * @see https://solutionsisee.wordpress.com/2016/06/30/adding-cors-support-in-jersey-server/
  */
 @Override
 public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
   throws IOException {

  final MultivaluedMap<String, Object> responseHeaders = responseContext.getHeaders();
  final String origin = requestContext.getHeaderString(ORIGIN);

  if (origin != null) {
   // The presence of the Origin header marks a CORS request.
   responseHeaders.add(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
   responseHeaders.add(ACCESS_CONTROL_ALLOW_METHODS, extractAllowedMethods(extendedUriInfo));
   responseHeaders.add(ACCESS_CONTROL_ALLOW_HEADERS, AUTHORIZATION + ", X-Requested-With, Content-Type");
   if (requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_HEADERS) != null) {
    responseHeaders.add(ACCESS_CONTROL_ALLOW_CREDENTIALS, requestContext
      .getHeaderString(ACCESS_CONTROL_REQUEST_HEADERS).toLowerCase().contains(AUTHORIZATION));
   }
  }

  if (request.getAttribute(this.getClass().getName()) != null) {
   // We are in a CORS Preflight answer, fast tracked. The entity (== response body) is not
   // relevant.
  }
 }
}

Currently getting this error
<!doctype html><title>HTTP Status 500 – Internal Server Error</title>
HTTP Status 500 – Internal Server Error

Type Exception Report

Message org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/filter/TokenFilter

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/filter/TokenFilter
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:432)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause

org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/filter/TokenFilter
    org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:278)
    org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:260)
    org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:460)
    org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:285)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:272)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:268)
    org.glassfish.jersey.internal.Errors.process(Errors.java:316)
    org.glassfish.jersey.internal.Errors.process(Errors.java:298)
    org.glassfish.jersey.internal.Errors.process(Errors.java:268)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/filter/TokenFilter
    com.fasterxml.jackson.databind.ObjectMapper._newReader(ObjectMapper.java:640)
    com.fasterxml.jackson.databind.ObjectMapper.reader(ObjectMapper.java:3323)
    org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase._configForReading(ProviderBase.java:489)
    org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase._endpointForReading(ProviderBase.java:882)
    org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase.readFrom(ProviderBase.java:789)
    org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:257)
    org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:236)
    org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
    org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundReadFrom(MappableExceptionWrapperInterceptor.java:73)
    org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
    org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1091)
    org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
    org.glassfish.jersey.server.ContainerRequest.readEntity(ContainerRequest.java:271)
    org.glassfish.jersey.server.internal.inject.EntityParamValueParamProvider$EntityValueSupplier.apply(EntityParamValueParamProvider.java:97)
    org.glassfish.jersey.server.internal.inject.EntityParamValueParamProvider$EntityValueSupplier.apply(EntityParamValueParamProvider.java:80)
    org.glassfish.jersey.server.spi.internal.ParamValueFactoryWithSource.apply(ParamValueFactoryWithSource.java:74)
    org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:92)
    org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:133)
    org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:200)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:103)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:493)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:415)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:104)
    org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:277)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:272)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:268)
    org.glassfish.jersey.internal.Errors.process(Errors.java:316)
    org.glassfish.jersey.internal.Errors.process(Errors.java:298)
    org.glassfish.jersey.internal.Errors.process(Errors.java:268)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause

java.lang.ClassNotFoundException: com.fasterxml.jackson.core.filter.TokenFilter
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1363)
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1186)
    com.fasterxml.jackson.databind.ObjectMapper._newReader(ObjectMapper.java:640)
    com.fasterxml.jackson.databind.ObjectMapper.reader(ObjectMapper.java:3323)
    org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase._configForReading(ProviderBase.java:489)
    org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase._endpointForReading(ProviderBase.java:882)
    org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase.readFrom(ProviderBase.java:789)
    org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:257)
    org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:236)
    org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
    org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundReadFrom(MappableExceptionWrapperInterceptor.java:73)
    org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
    org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1091)
    org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
    org.glassfish.jersey.server.ContainerRequest.readEntity(ContainerRequest.java:271)
    org.glassfish.jersey.server.internal.inject.EntityParamValueParamProvider$EntityValueSupplier.apply(EntityParamValueParamProvider.java:97)
    org.glassfish.jersey.server.internal.inject.EntityParamValueParamProvider$EntityValueSupplier.apply(EntityParamValueParamProvider.java:80)
    org.glassfish.jersey.server.spi.internal.ParamValueFactoryWithSource.apply(ParamValueFactoryWithSource.java:74)
    org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:92)
    org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:133)
    org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:200)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:103)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:493)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:415)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:104)
    org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:277)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:272)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:268)
    org.glassfish.jersey.internal.Errors.process(Errors.java:316)
    org.glassfish.jersey.internal.Errors.process(Errors.java:298)
    org.glassfish.jersey.internal.Errors.process(Errors.java:268)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Note The full stack trace of the root cause is available in the server logs.

Apache Tomcat/9.0.20

redpajama_set_name: RedPajamaStackExchange


text:
Q: jest + mongoose gives Error Schema with array of arrays I'm doing tests with jest and mongoose with the following schema:
import mongoose from 'mongoose';

const PolygonSchema = new mongoose.Schema({
  type: {
    type: String,
    enum: ['Polygon'],
    required: true
  },
  coordinates: {
    type: [[[Number]]], // Array of arrays of arrays of numbers
    required: true
  }
});

export default PolygonSchema;

When running the test with jest i'm getting the following error:
Test suite failed to run

    TypeError: _schemaType.caster.clone is not a function

      1 | import mongoose from 'mongoose';
      2 |
    > 3 | const PolygonSchema = new mongoose.Schema({
        |                       ^
      4 |   type: {
      5 |     type: String,
      6 |     enum: ['Polygon'],

      at Schema.Object.<anonymous>.Schema.path (node_modules/mongoose/lib/schema.js:679:40)
      at Schema.add (node_modules/mongoose/lib/schema.js:444:12)
      at new Schema (node_modules/mongoose/lib/schema.js:121:10)
      at Object.<anonymous> (src/models/polygon.schema.js:3:23)
      at Object.<anonymous> (src/models/geofence.model.js:3:1)
      at Object.<anonymous> (src/services/geofence.service.js:3:1)
      at Object.<anonymous> (tests/services/geofence.test.js:5:1)

The code is running well, only with jest I get this error.
I'm also using babel-jest.
Any ideas for a fix?
Thanks ahead


text:
Q: Magento 2 - Custom Variables API I was wondering if there is an API for the Custom Variables in Magento under System > Other Settings > Custom Variables.
Going through the System > Integrations > API lists it as Available APIs. But I cannot find it anywhere in the swagger doc.
https://devdocs.magento.com/swagger/index_23.html#/


text:
Q: Gulp Rev doesn't include paths in my manifest file I have Gulp tasks set up to concat, minify and fingerprint assets all at once, writing them directly to my assets folder:
(the css part)
gulp.task('styles:cssmin', function(){
    return gulp.src('src/css/*.css')
        .pipe(concat('main.css')) // combine them
        .pipe(cssmin()) // minify them
        .pipe(rev()) // Pipe through gulp-rev to fingerprint generated file
        .pipe(gulp.dest('assets/css'))  // write rev'd assets
        .pipe(rev.manifest({
            merge: true // Merge because this happens for .js and images too
        }))
        .pipe(gulp.dest('./')); // write manifest
});

This fingerprints the files and generates a manifest, but I can't get any paths to be saved to the manifest file. Here's the manifest it generates:
{
  "bg.jpg": "bg-447ac2238b.jpg",
  "logo.png": "logo-e31e139d4d.png",
  "main-min.js": "main-min-cc3a682299.js",
  "main.css": "main-ea0d06582f.css",
  "main.js": "main-35ec0bb3c8.js"
}

Which I would like to have as:
{
  "assets/img/bg.jpg": "assets/img/bg-447ac2238b.jpg",
  "assets/img/logo.png": "assets/img/logo-e31e139d4d.png",
  "assets/js/main-min.js": "assets/js/main-min-cc3a682299.js",
  "assets/css/main.css": "assets/css/main-ea0d06582f.css",
  "assets/jsg/main.js": "assets/js/main-35ec0bb3c8.js"
}

Especially considering the docs give an example which includes the relative paths

A: I was having the same issue, and ended up renaming the asset dirs in the stream to what I wanted and specifying the path of the rev-manifest.
var rename = require("gulp-rename");

gulp.task('styles:cssmin', function(){

    return gulp.src('src/css/*.css')
        .pipe(concat('main.css')) // combine them
        .pipe(cssmin()) // minify them
        .pipe(rename({
            dirname: "assets/css" //manually fixing path for rev-manifest
        }))
        .pipe(rev('path/to/your/rev/rev-manifest.json')) // Specify manifest location
        .pipe(gulp.dest('assets/css'))  // write rev'd assets
        .pipe(rev.manifest({
            merge: true // Merge because this happens for .js and images too
        }))
        .pipe(gulp.dest('./')); // write manifest
});

A: I ended up having to edit the source. Annotated in there, sorry I can't highlight it.
plugin.manifest = function (pth, opts) {
    if (typeof pth === 'string') {
        pth = {path: pth};
    }

    opts = objectAssign({
        path: 'rev-manifest.json',
        merge: false
    }, opts, pth);

    // Changed the following line to the next line:
    // var firstFileBase = null
    var firstFileBase = opts.base || null;
    var manifest = {};

    return through.obj(function (file, enc, cb) {
        // ignore all non-rev'd files
        if (!file.path || !file.revOrigPath) {
            cb();
            return;
        }

        firstFileBase = firstFileBase || file.base;

        var revisionedFile = relPath(firstFileBase, file.path);
        var originalFile = path.join(path.dirname(revisionedFile), path.basename(file.revOrigPath)).replace(/\\/g, '/');

        manifest[originalFile] = revisionedFile;

        cb();
    }, function (cb) {
        // no need to write a manifest file if there's nothing to manifest
        if (Object.keys(manifest).length === 0) {
            cb();
            return;
        }

        getManifestFile(opts, function (err, manifestFile) {
            if (err) {
                cb(err);
                return;
            }

            if (opts.merge && !manifestFile.isNull()) {
                var oldManifest = {};

                try {
                    oldManifest = JSON.parse(manifestFile.contents.toString());
                } catch (err) {}

                manifest = objectAssign(oldManifest, manifest);
            }

            manifestFile.contents = new Buffer(JSON.stringify(sortKeys(manifest), null, '  '));
            this.push(manifestFile);
            cb();
        }.bind(this));
    });
};

Not an ideal solution, will break on update. I would love it if there were a better way.


text:
Q: Von Neumann stability vs eigenvalues of amplification matrix My, limited, understanding of the stability analysis of PDEs is that broadly speaking there are two methods: von Neumann analysis which looks at the growth the error of the solution, as described here
https://en.wikipedia.org/wiki/Von_Neumann_stability_analysis
and the method of constructing an amplification matrix and looking to see if the mag. of the largest eigenvalue is greater than or less than 1.
i.e. for a simple PDE (and using forward Euler for simplicity) $y' = \lambda \hat{\nabla} y \implies y^{n+1} = (1 + \Delta t \lambda \hat{\nabla})y^n $
where I chose a gradient operator instead of some other prefactor to emphasize i am going to do this with a particular finite difference discretization i.e. it's now a matrix equation with amplification matrix $G = 1+\Delta t \lambda \hat{\nabla}$. Depending on the discretization and value of $\Delta x$ in $\nabla$ we get some kind of CFL condition based on the eigenvalues of $G$.
Assuming the above is correct, i'm interesting in the following: the latter seems to be a statement about whether or not the solution is, at least locally, exponential (assume for now $\lambda$ is real). The former seems to be a statement about the behaviour of the error of the solution. In principle it seems one could have an accurate or inaccurate solution to an exponential. I also understand that in the von Neumann case an argument is made that if the PDE is linear then the equation for the error is the same as for the solution, and so if the error is unbounded then so will the solution (right?)
My question is then: to what extent is the above correct and in what sense are these two approaches equivalent?

A: This is a huge topic, and if you want to understand it you need to do a lot of reading.  It is also a very active area of research.  The techniques you've mentioned are the very basics.
To try to answer you briefly: von Neumann analysis is just the amplification matrix analysis applied to circulant matrices, since their eigenvectors are discrete Fourier modes.  And yes, for linear discretizations the truncation error and the solution obey the same equation.  There are some small problems in what you've written; for instance, stability (in the sense required for convergence) does not require that the amplification factor be less than or equal to unity -- it is more subtle than that.
Get a good introductory numerical analysis text, like LeVeque's "Finite Difference Methods for ODEs and PDEs".  You'll also want to learn about things like Lax-Richtmeyer stability and the Kreiss Matrix Theorem, for starters.


text:
Q: C++ console test app for a Runtime Component Library(C++/WinRT) I need to create a C++/WinRT library for a BLE device. And also I need to create a test app for testing the APIs in the library. I am just a start learner of this new technology.
What are the different ways to use the C++/WinRT library(dll) functions in a C++ console test application?
If multiple ways are there, which one is better?
Could any kind soul shed some light? Thanks a lot!

A: It is not supported to test a Windows Runtime Component in a C++ console application. The compiler will tell you that a reference to your Windows Runtime Component cannot be added to a console application because the two projects target different platforms. Based on the document, you could learn that a Windows Runtime Component is callable from a Universal Windows Platform(UWP) app built using any Windows Runtime language(including C#, C++/WinRT, Visual Basic, JavaScript, and C++/CX).
I noticed that you mentioned Runtime Component and C++/WinRT library(dll), they are different kind of project in my opinion. The former should be a Windows Runtime Component(C++/WinRT) project, and the latter should be a DLL(Universal Windows) project. I don't know which one you use, but the both two kinds of projects are not supported to be tested in a C++ console application. You could test them in a UWP app.
We suggest you use a UWP app to test your Windows Runtime component. For more information about UWP apps you could refer to the tutorial. You could also refer to the above document which shows how to reference a component in a UWP app.

A: From 2012
You can use Windows Runtime Component (C++/CX) in C++ Console Application, it base on consume Windows Runtime metadata (.winmd) file, tutorial from Intel is here
Update: From 2020
You can use C++/WinRT on Windows 7 (which are not include Windows Runtime like Windows 8 or Windows 10) too. It is new C++/WinRT 2.0

The cppwinrt.exe tool takes a Windows Runtime metadata (.winmd) file, and generates from it a header-file-based standard C++ library that projects the APIs described in the metadata. That way, you can consume those APIs from your C++/WinRT code.

This is demo repository C++/WinRT for Windows 7 (author is Kenny Kerr - creator of C++/WinRT). In theory, it also work with Windows Vista, but now no one checking compatible.


text:
Q: Prove this endomorphism cannot have real eigenvalues? $f$ is an endomorphism of an $\Bbb R$-vector space $E$ with dimension $n\geq1$. $f$ satisfies $f^2+f+$Id$_E = 0$.
How can I go about showing that $f$ can't have real eigenvalues?

A: Assume $x$ is an eigenvector of $f$ with eigenvalue $\lambda$ then evaluating your equation at $x$ gives $f(f(x))+f(x)+id(x)=0$, but since $x$ is an eigenvector $f(x)=\lambda x$ and $f(f(x))=f(\lambda x)=\lambda f(x)=\lambda^2 x$ where we used the linearity of $f$, so inserting into the first equation yields $$\lambda^2 x+\lambda x+x=0$$ which by the vector space axioms of scalar multiplication is equivalent to $$(\lambda^2+\lambda+1)x=0$$ Now since all eigenvector are assumed nonzero we have that $$\lambda^2+\lambda+1=0$$
But this equation has no real solutions so our linear map cannot have real eigenvalues.

A: Hint
The minimal polynomial $q(x)$ of $f$ is the smallest anulator polynomial in the sense that if $p(f)=0$ then $q(x)\mid p(x)$. Moreover, $\lambda $ is an eigenvalue of $f$  if and only if $q(\lambda )=0$.

A: Well, if $x$ is an eigenvector of $f$ with $f(x) = \lambda x$.
Then $0 = 0(x) = (f^2+f+id)(x) =f^2(x) + f(x) + x = \lambda^2 x + \lambda x + x = (\lambda^2+\lambda + 1)x$.
If $x\ne 0$, then $\lambda^2+\lambda+x=0$. But this polynomial has negative discriminant $D=1^2-4\cdot 1\cdot 1 = -3$ and so no real-valued solution.

A: Any eigenvalue $\lambda$ would have to satisfy $\lambda^2+\lambda+1=0\implies \lambda=(1\pm\sqrt3i)/2$.


text:
Q: ArcGIS automatically convert string variables to numeric? If arcgis is automatically coverting string values to numeric variables in a text document generated by stata, how do you change those variables back into string? I tried opening up the fields under properties in arccatalog and it says I cannot change them because the tables are not empty

A: ArcGIS reads the first 8 (maybe 11?) rows of data to determine what the data type should be for each field. Kind of a hackish workaround, but you could make some dummy rows for that and populate it with alphabetic characters. Then delete the rows once imported. Another method would be to add a new text field, and use Field Calculator to cast the values from the problem column back to text.
I'm thinking there's a better way, but my brain isn't retrieving it right now, sorry.


text:
Q: Jquery not applying on dynamic elements created in context menu I have a script containing $('a').on('click', function () {alert($(this).attr('class')); });
In my contextmenu function, I create a list with links
$(function () {
$('a').on('contextmenu', function (event) {
        $("

")
        .append('
Test 1
')
        .append('
Test 2
')
        .appendTo("body")
        .css({ top: event.pageY + "px", left: event.pageX + "px" });
        return false;
    });

});
However, the first piece of code (the on click event) does not fire when the link in the list is clicked. However, it fires for every other link on the page. How can I fix this so that my script works on dynamic elements

A: Just a rehash of another SO question.
Calling the jQuery on method on $(document) and providing the 'selector' option will bind the callback to dynamically added elements matching the selector parameter.
That is, this:
$(document).on('click', 'a', function () {
  alert( $(this).attr('class') );
});

instead of this:
$('a').on('click', function () {
  alert($(this).attr('class'));
});


text:
Q: How to restrict the particular method to be executed once only, When factory and dataprovider annotation method is used?
*

*I am automating database automation. I am using @factory and
@Dataprovider annotation in feed the inputs.

*I want to restrict this method related alone runs once getCountOfPt1(poiLocId)

*I tried setting boolean value also, but it fails, because I am using factory as well as dataprovider annotation.

*The code Which I want to restrict and execute only once is

String pt1 = null;
    if(!alreadyExecuted) {
    Map<String, Integer> records = DbMr.getCountOfPt1(poiLocId);
    pt1 = getMaxKey(records);
    LOG.debug("Max key value is...." + pt1);
    if (StringUtils.isBlank(pt11)) {
        records.remove(null);
        pt1 = getMaxKey(records);
        alreadyExecuted = true;
    }
    }

Note: poiLocId which I passed in this method is from factory method
@Factory
public Object[] factoryMethod() {
    Object[] poiLocIdData = null;
    if (StringUtils.isNotBlank(cityName)) {
        List<String> poiLocId = DbMr.getPoiLocId(cityName);

        int size = poiLocId.size();
        poiLocIdData = new Object[size];
        for (int i = 0; i < size; i++) {
            poiLocIdData[i] = new CollectsTest(poiLocId.get(i));
        }
    } else {
        LOG.error("The parameter is required: Pass City Name");
        Assert.fail("Problems with parameters");
    }

    return poiLocIdData;
}

public CollectTest(String locationId) {
    poiLocId = locationId;
    this.reportsPath = "reports_" + cityName;
    this.extent = new ExtentReports();
}

@DataProvider(name = "pData")
public Object[][] getPData() {
    List<PData> pList = DbMr.getCollectionPs(poiLocId);

    Object[][] testData = new Object[pList.size()][];
    for (int i = 0; i < poiList.size(); i++) {
        testData[i] = new Object[] { pList.get(i) };
    }
    return testData;
}

@BeforeClass
private void setup() throws Exception {
    ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(reportsPath + "/" +
     cityName + "_extent.html");
     htmlReporter.loadXMLConfig("src/test/resources/extent-config.xml");
    extent.attachReporter(htmlReporter);
}

@Test(dataProvider = "pData")
public void verifyData(PData pData) throws Exception {
    extentTest = extent.createTest(pData.toString());
    String pt1 = null;
    if(!alreadyExecuted) {
    Map<String, Integer> records = DbMr.getCountOfPt1(poiLocId);
    pt1 = getMaxKey(records);
    LOG.debug("Max key value is...." + pt1);
    if (StringUtils.isBlank(pt11)) {
        records.remove(null);
        pt1 = getMaxKey(records);
        alreadyExecuted = true;
    }
    }

    if (pt1.equalsIgnoreCase("xxxx")) {
        Assert.assertEquals(pData.getpt1(), "xxxx");

        }

A: Since @factory and @DataProvider work with the instance of the test class, so try to make the "alreadyExecuted" variable as a static variable.(since static variable is at class level")

A: The below code works fine and it runs once only, I have used map to execute only once.
// declare it as global variable
private static Map<String, String>LOC_ID_AND_PT1_COUNT_MAP = new HashMap();

//test method
@Test(dataProvider = "pData")
public void verifyData(PData pData) throws Exception {
    extentTest = extent.createTest(pData.toString());
    String pt1 = LOC_ID_AND_PT1_COUNT_MAP.get(LocId);
        if (pt1 == null) {
    Map<String, Integer> records =
  DbMr.getCountOfPT1(LocId);
            pT1 = getMaxKey(records);
            LOG.debug("Max key value is...." + pt1);
            if (StringUtils.isBlank(pt1)) {
                records.remove(null);
                pt1 = getMaxKey(records);
                LOG.debug("Max key value is...." + pt1);
            }

            LOC_ID_AND_PT1_COUNT_MAP.put(locId, pt1);
        }


text:
Q: Username with System.User Today I wanted to greet the user in my app by name, but I did not manage to get it.
I found System.User, but lacking some examples I did not manage to get the info I needed. I saw no possibility to get the current user (id) to call User.GetFromId().
Can you guide me into the right direction? Have I been on the wrong path?

A: Okay, So first things first, getting access to a user's personal information is a privilege you have to request, so in your store app's Package.appxmanifest, you'll need to enable the User Account Information capability in the Capabilities tab.
Next, you'll want to be using the Windows.System.User class, not the System.User (System.User isn't available to Windows store apps, which you appear to be discussing given the tags you provided for your question)
Third, you'll want to request personal information like this.
IReadOnlyList<User> users = await User.FindAllAsync(UserType.LocalUser, UserAuthenticationStatus.LocallyAuthenticated);
User user = users.FirstOrDefault();
if (user != null)
{
   String[] desiredProperties = new String[]
   {
      KnownUserProperties.FirstName,
      KnownUserProperties.LastName,
      KnownUserProperties.ProviderName,
      KnownUserProperties.AccountName,
      KnownUserProperties.GuestHost,
      KnownUserProperties.PrincipalName,
      KnownUserProperties.DomainName,
      KnownUserProperties.SessionInitiationProtocolUri,
   };

   IPropertySet values = await user.GetPropertiesAsync(desiredProperties);
   foreach (String property in desiredProperties)
   {
      string result;
      result = property + ": " + values[property] + "\n";
      System.Diagnostics.Debug.WriteLine(result);
   }
}

When you call GetPropertiesAsync, your user will get a permission prompt from the system asking them if they want to give you access to that. If they answer 'No', you'll get an empty user object (but you'll still get a unique token you can use to distinguish that user if they use the app again).
If they answer yes, you'll be able to get access to the properties below, and various others.
See the UserInfo Sample Microsoft provided for more examples.


text:
Q: How to check if a particular argument is supported in parser.parse_args()? For example, How can I know whether there is an argument like args.manual_selection in args (args = parser.parse_args())

A: One way to do it would be just to convert args to a dictionary
args = vars(parser.parse_args())
Then you can check for the existence of the key, e.g.
args.get("manual_selection", False)
If that returns False, the key does not exist. Of course the default returned for non-existence must not overlap with valid user input.


text:
Q: Rails why is calling .valid? removing my error messages Calling ActiveModel::Validations#valid? on my @item instance is removing my error messages. This is best shown by example.
[1] pry(#<ChangeObjectsController>)> @item.errors.add(:new_error, "new error has occurred")
=> ["new error has occurred"]
[2] pry(#<ChangeObjectsController>)> @item.errors.full_messages
=> ["Connection error has occurred", "New error new error has occurred"]
[3] pry(#<ChangeObjectsController>)> @item.valid?
=> true
[4] pry(#<ChangeObjectsController>)> @item.errors.full_messages
=> []

In my model class I am including the validation library (note it does not inherit from ActiveRecord::Base):
  include ActiveModel::Validations
  extend ActiveModel::Naming

The error message is added in this way:
Can anyone provide clarity on this issue? For example, is this desired behavior and I am using it incorrectly?

A: This is normal behaviour. It would be inconsistent if valid? returned true but there were error messages. You can see in the rails source that valid? explicitly clears the error messages.
The normal way to add error messages is via a validation, either a built in one or a custom one.


text:
Q: Try to connect IP camera but no error found and no stream I try to connect live stream of my IP camera with python code but unable to connect. No error and no stream
import cv2
import time
import pandas
capture = cv2.VideoCapture('rtsp://192.168.1.13')
a=1
while True:
    a=a+1`enter code here`
    check,frame=capture.read()
    capture = cv2.VideoCapture('rtsp://admin:123456@192.168.1.13')
    print('a')
    print(frame)
    #print('b')
    #print('c')
    cv2.imshow('live',capture)
    print.capture
    print('d')
    cv2.waitKey(1)
print(a)
video.release()
cv2.destroyAllWindows


text:
Q: How to show div in multiple lines instead one line I have centered the div contents in a wrapper using display:flex. now the problem is the child divs are showing in one line, but I wanted to make it displayed above each other. here is my code:

.news-content-inner{
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    background-color:#cccccc;
    width:300px;
}
.news-by-category-items > .news-content-inner > .category-tags{
    display: inline-block;
    padding: 2px 8px;
    font-size: 14px;
    color: #fff;
    font-weight: bold;
}
.news-by-category-items > .news-content-inner > .news-title{
    font-size: 16px;
    color: #fff;
    font-weight: bold;
}
.news-by-category-items > .news-content-inner >  .news-date{
    font-size:14px; color: #fff;
}

block level text 1

block level text 2

block level text 3

A: Just add flex-direction: column;

.news-content-inner{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    background-color:#cccccc;
    width:300px;
}
.news-by-category-items > .news-content-inner > .category-tags{
    display: inline-block;
    padding: 2px 8px;
    font-size: 14px;
    color: #fff;
    font-weight: bold;
}
.news-by-category-items > .news-content-inner > .news-title{
    font-size: 16px;
    color: #fff;
    font-weight: bold;
}
.news-by-category-items > .news-content-inner >  .news-date{
    font-size:14px; color: #fff;
}

block level text 1

रblock level text 2

block level text 3


text:
Q: Does backing up a keycloak database backup everything? I am wondering if simply backing up the keycloak database associated with postgres is enough so that if I every lose access to the keycloak instance. I can simply restore the database and everything will be smooth sailing?
P.S: I am using docker for keycloak
Thanks!


text:
Q: How to Fit Perfect Squares Into a Rectangle I have been looking all over the Internet for an answer on this. None of them answer my question, and I need help. The ones that do somewhat answer my question assume the fact I understand their college-level mathematical understanding, when in reality I am a 10th grade programmer.
I'm trying to make an emulated screen of a much lower pixel density, but can't seem to figure out how to figure out how many 50x50 squares my rectangular screen with a ratio of 3x4.
I appreciate all answers in advance!

A: Let's say your screen is $1200 \times 900$ "normal" pixels, which is a $4:3$ ratio.
You can fit $1200/50 = 24$ giant pixels along the long edge, and $900/50 = 18$ giant pixels along the short edge.
So the total number of giant pixels is $24 \times 18 = 432$.
Another way is to use the area directly.  A $1200 \times 900$ screen has $108000$ pixels.  Each giant pixel contains $50 \times 50 = 2500$ normal pixels.  So in total you have $108000/2500 = 432$ giant pixels.
Is that what you're after?


text:
Q: How does this JavaScript random number generator work? I can't seem to understand this loop.
for (i = 1; i < 50; i++) {
    rand = Math.ceil(Math.random() * 49);
    temp = nums[i];
    nums[i] = nums[rand];
    nums[rand] = temp;
}

It is part of a larger code. nums[i] is an array of 1-49 filled with their respective index numbers, then it is run through this for loop and filled with random numbers.
I don't understand why the temp variable is created, how the nums[rand]=temp; line of code works and what does it do, and why is it not even initialized without the var keyword.
Can someone explain how this loop works?

A: What the code attempts to do is to shuffle the array.
It works by going through the array, and for each position, store the value in a temp variable, pick another position in the array and swap the values with the other position.
The temp variable is required as this is the most simple way to swap the values of the variables.

A: It's just randomly swapping two values in the nums array.  Although ignoring the very first one; javascript arrays start at 0, but the loop only starts at 1, so it only starts from the 2nd array element.
So stepping through the code, every time it goes round the loop it does something like this:
nums = [a, b, c];  // just mocking some data

rand = 0..2;  // lets say it = 2
temp = nums[1]; // = 'b', the 2nd array element
nums[1] = temp;  // so nums[1] goes from 'b' to 'c'
nums[temp] = temp; // and nums[2] goes from 'c' to 'b'

overall it's pretty bad code.  If it's working with an array it should use array.length instead of hardcoding 50 for the upper limit of the loop.


text:
Q: Can I get some simplified explanation about semi-colon use in php? I have seen some articles explaining that a semi colon is not required in the last line of a PHP code due to the closing PHP tag (?>). Is this the case or is there any other theory around it?

A: A semicolon is to denote end of the instruction, and that a new one may start.
When a closing tag is found, no new instructions are expected so it's technically not needed.
It's useful in cases like <?= 'foobar' ?> so you don't need to use a semicolon to echo out the string, but <?= 'foobar'; ?> works just as well.


text:
Q: Swipe right to dismiss edge size Is it possible to increase edge size interactivePopGestureRecognizer of UINavigationController reacts user touches?
I.e. is it possible to make swipe right from middle of screen to move and pop current top Viewcontroller same way as from the left screen edge?

A:
    override func viewDidLoad() {
        super.viewDidLoad()
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
        swipeRight.direction = .right
        self.view.addGestureRecognizer(swipeRight)

        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
        swipeLeft.direction = .left
        self.view.addGestureRecognizer(swipeLeft)

    }

    // you can track all direction swipe like below, and to do that first you have to add gesture in the view you want to track.
    @objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
            switch swipeGesture.direction {
            case .right:
                // push pop here
                print("Swiped right")
            case .down:
                print("Swiped down")
            case .left:
                // push pop here
                print("Swiped left")
            case .up:
                print("Swiped up")
            default:
                break
            }
        }
    }

A: Finally, found a solution to increase the edge touch size using this library: SwipeTransition


text:
Q: creating a cost function in jgrapht jgrapht supports the idea of putting a wehight(a cost) on an edge/vertex between two nodes. This can be achieved using the class DefaultWeightedEdge.
In my graph I do have the requirement to not find the shortest path but the cheapest one. The cheapest path might be longer/have more hops nodes to travel then the shortest path.
Therefor, one can use the DijkstraShortestPath algorithm to achieve this.
However, my use case is a bit more complex: It needs to also evaluate costs on actions that need to be executed when arriving at a node.
Let's say, you have a graph like a chess board(8x8 fields, each field beeing a node). All the edges have a weight of 1. To move in a car from left bottom to the diagonal corner(right upper), there are many paths with the cost of 16. You can take a diagonal path in a zic zac style, or you can first travel all nodes to the right and then all nodes upwards.
The difference is: When taking a zic zac, you need to rotate yourself in the direction of moving. You rotate 16 times.
When moving first all to the right and then upwards, you need to rotate only once (maybe twice, depending on your start orientation).
So the zic zac path is, from a Djikstra point of view, perfect. From a logical point of view, it's the worst.
Long story short: How can I put some costs on a node or edge depending on the previous edge/node in that path? I did not find anything related in the source code of jgrapht.
Or is there a better algorithm to use?

A: This is not a JGraphT issue but a graph algorithm issue. You need to think about how to encode this problem and formalize that in more detail

*

*Incorporating weights on vertices is in general easy. Say that every vertex represents visiting a customer, which takes a_i time. This can be encoded in the graph by adding a_i/2 to the cost of every incoming arc in node i, as well as a_i/2 to the cost of every outgoing arc.

*A cost function where the cost of traveling from j to k dependents on the arc (i,j) you used to travel to j is more complicated.
Approach a.: Use a dynamic programming (labeling) algorithm. This is perhaps the easiest. You can define your cost function as a recursive function, where the cost of traversing an arc depends on the cost of the previous arc.
Approach b.: With some tricks you may be able to encode the costs in the graph by adding extra nodes to it. Here's an example:
Given a graph with vertices {a,b,c,d,e}, with arcs: (a,e), (e,b), (c,e), (e,d). This graph represents a crossroad with vertex e being in the middle. Going from a->e->b (straight) is free, however, a turn from a->e->d takes additional time. Similar for c->e->d (straight) is free and c->e->b (turning) should be penalized.
Decouple vertex e in 4 new vertices: e1,e2,e3,e4.
Add the following arcs:
(a,e1), (e3,b), (c,e2), (e4,d), (e2, e3), (e1, e3), (e1, e4), (e2, e4).
(e1,e4) and (e2,e3) can have a positive weight to penalize turning.


text:
Q: insertListItem(index, text) Wrong Index I am trying to use Google Apps Script to replace text into a Docs template and save it as a .pdf.  I am mostly successful, but I am having one problem.  I'd like for the script to search for a text in the template, replace the text with provided text, using bullets.  It will ignore any extra \n that may have been placed into the text.  Here is an example text:
Today was a good day.
Tomorrow will be a good day.

Yesterday was a decent day.

In my document, I would like the text to replace _text_ in a line: Comments: _text_.  Ultimately, what should print out is the following:
Comments:
- Today was a good day.
- Tomorrow will be a good day.
- Yesteday was a decent day.

This is the code that I have so far, but it is not working too well.  If anyone could offer any help, it would be greatly appreciated.
var listr = "";
var trunc = text.split("\n"); \\ where text is to be placed into the template
var index = b.findText("_text_").getStartOffset(); \\ var b is getBody()
for (var j = (trunc.length - 1); j >= 0; j--)
  if(!trunc[j].equals("")) b.insertListItem(index, trunc[j]);
b.replaceText("_text_", "");

Any help would be much appreciated.  I am having the hardest time understanding the concept of the indexes in Google Docs.  Thank you.

Hello.  Just wanted to let you know how I have ended up implementing this:
var trunc = text.split("\n"); \\where text is to be placed into the template
var index = b.getChildIndex(b.findText("foo").getElement().getParent()) + 1;
for (var j = (trunc.length - 1); j >= 0; j--)
  if (trunc[j] != "") b.insertListItem(index, trunc[j]);

Hope that helps.  It pushes the elements back on to each other backwards.

A: Ok well this crude code seems to insert at the beginning of the PARAGRAPH containing the TEXT, which appears to be a separate child element. Probably this particular code will only work if the text is not inside a sub-table, sub-list, etc... but maybe it will help.
var element = DocumentApp.create('newDoc').getBody()
  .appendListItem('testing').copy();
var index = b.getChildIndex(
  b.findText('_text_').getElement().getParent().asParagraph() );
b.insertListItem(index, element);

I've had a long day maybe I can improve it later, mostly what I think was missing was the getChildIndex() function. Also using the newDoc the insertListItem() had some weird "Element must be detached." message until I used .copy() so mental note there.


text:
Q: Request response is being stored as bool I am trying to use Shopify's API to pull order information with PHP. This is my first time using PHP for requests and wanted to get some experience as I am new to PHP in general.
function order_status($url, $user, $pass){
    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: *.*','Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $pass);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);

    curl_close($ch);
    return $response;
}

$response = order_status($url, $user, $pass);
$responseJSON = json_decode($response);

echo "\n" , $responseJSON , "\n";

This is what is output to the terminal.
{"orders":[{"id":2083102294069,"name":"1031"}]}
1

I used the gettype method to check what was being returned in $response and it was a bool. Sorry if this is an obvious mistake but why isn't the JSON data being returned as a string in the response variable? Also, what is printing out the correct JSON to the terminal?

A: You are missing
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

CURLOPT_RETURNTRANSFER
TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it directly.

Then to check if things work, either
echo $response;

or
var_export( $responseJSON );


text:
Q: Issue Related to Read only DB file after installation I have an Application in WinForms,
I have created SetupDevelopment project and then install an application using Setup.exe file
i have added MSAcceess db file into application folder file,
when i install an application the database file gets readonly. how can i make file writtable after installation?
I found some solution on internet and found that when i tried to install application in different path other than "C:\ProgramFile\"  and make application available to all user,it solves my Problem, but i want to install an application only in "C:\ProgramFile\" and want to available to only "Current user"
how can i achieve my Problem ?

A: In modern Windows Operating System the folders 'Program Files' or 'Program Files (x86)' are read only for the common users. This choice has been done for security reasons and you cannot easily bypass this rule. The reccomended folders, to use just for the current user, are  C:\users\username\AppData\Roaming or C:\users\username\AppData\Local identified by the Environment.SpecialFolder.ApplicationData or Environment.SpecialFolder.LocalApplicationData. To this base folders add another subfolder identifying your application or company and install your database there.
If you want your database available to all users of the current PC, you could install it in the Environment.SpecialFolder.CommonApplicationData that resolves to C:\programdata. (Again, adding a subfolder specific for your application or company)
Again, don't try to force the operating system to work against its rules. You will find yourself in trouble very often.


text:
Q: TeamCity 8.1.2 REST API: Get the running build of the specified build configuration I'm using TeamCity 8.1.2 REST API and I want to check if there is a running build in my build configuration.

To get builds in a queue I can use the following request:
> http://<tc_address>/app/rest/latest/buildQueue/?locator=buildType:<my_buildTypeId>

It returns the builds in the queue but not the running one.

Accroding to documentation https://confluence.jetbrains.com/display/TCD8/REST+API to get running builds this request can be used:
> http://<tc_address>/app/rest/builds/?locator=buildType:<my_buildTypeId>,running:true

But it returns no builds. I tried
http://<tc_address>/app/rest/builds/?locator=running:true

which returns running builds from other build configuration but the running build from my build configuration is not listed.

A: Your API call is correct but seems like you are missing some configuration.
Check below setting for the given issue :
-> Go to Build Configuration

    -> Edit Configuration Settings

        -> General Settings

            -> Build options

                -> Enable status widget [Check this checkbox]

after that check API call


text:
Q: How to show selected options from dropdown in javascript Hi guys i have written some javascript code to display some values depend on another dropdown. So now i would like to display those selected values in my edit page..
Here is my code:
function getSubjectsTopics(subject_id)
{
    if(subject_id) {
        loading_show();

        axios.get("/master/topic/get-topic-by-subject-id/" + subject_id)
        .then(function(response) {
            var optionHtml = '<option value="0">Parent</option>';
            if(response.data.status) {
                $.each(response.data.subject_topics, function(i,v) {
                    optionHtml += `<option value="${v.id}" >${v.name}</option>`;
                }

            $("#ddl_topic_type").html(optionHtml).attr('disabled', false).select2();
            loading_hide();
        })
        .catch(function(error) {
            loading_hide();
            console.log(error);
            Swal.fire({
                type: 'error',
                title: 'Oops...',
                text: 'Something went wrong!'
            })
        })
    } else {
        $("#ddl_topic_type").attr('disabled', true);
    }
}

Can some one help me how can i add my selected code in optionhtml variable.TIA

A: In the $.each block, you can use a ternary operator and add the "selected" keyword based on the selection criteria.
First assign a boolean to isSelected variable after checking whether it should be selected or not. Then add the selected keyword into the template literals using a ternary operator
optionHtml += `<option value="${v.id}" ${isSelected ? 'selected' : ''} >${v.name}</option>`;


text:
Q: jQuery Mobile for mobile and desktop? I'm developing a web app. MySql/PHP back-end, and HTML/jQuery front-end.
I wanted to use jQuery UI framework.
Now is see that jQuery Mobile is out, and I want to make the app accessible to mobile devices as much as possible.
I Googled, but didn't find a quality answer.
Can I make it all to work form the same code if I use jQuery Mobile?
I'd like it to show mobile widgets if accessed form mobile browser.
But use jQuery UI widgets is accessed from desktop browser.
Is that possible just by using jQuery Mobile and its markup, or I have to write the front-end for mobile (jQuery Mobile) and desktop (jQuery UI) separately?
That is, can jQuery Mobile, automatically "fall-back" to jQuery UI if accessed from desktop browser.

A: Here is the full source code: https://github.com/ti-dev/Scrum-it for an open source Scrum Board which is designed for desktop devices and Apple iPad. So it is possible to combine these two worlds in one webpage.

A: I think it largely depends on what you want to do and functionality you're trying to capture.  If you want a webpage to behave a certain way on mobile and the same desktop, then with some careful coding/testing, you'll be alright with jquery.mobile.
If you check out the CSS for jquery.mobile (uncompressed version), you can actually edit the code directly to show the HTML elements the way you want to for particular screen sizes. Just select the one for desktop / large screen sizes to scale appropriately.
Depending on what you're trying to accomplish in terms of your mobile version, I'd also check out jQTouch - which allows for mobile-specific functionality, such as "tap" (in place of "click"), as an example - but also has a desktopCompatability option, so it reverts for desktop browsers.
One note, with either of these libraries, you'll still need the root jquery library.
Hope this helps.

A: First of all you will have to consider that the workflows for mobile and desktop differ vastly. Trying to flip between the desktop version and the mobile version will not be just a toggle between resources.
Secondly the two UI frameworks differ vastly in how they are used. jQuery UI is a collection of widgets that you can invoke when you like and where you like, it is in a sense library(ish) with a CSS framework backing it. jQuery mobile works quite differently however, by default it is a markup driven framework and to get it up and running it doesn't require you to write even 1 line of Javascript.
My advise to you is to think about the data layer as your common code and the client side as 2 completely separate pieces of work. Personally I have managed to create applications using common REST webservices. I use the jQuery UI to consume webservices and create mashups for the client-side. I then for the mobile version consume the webservices server-side to produce jQuery-mobile html pages for use on mobile.
Also note that generating dynamic HTML on the client side using jQuery Mobile will most certainly cause you huge headaches. Until the project matures I would use it only to enhance the frameworks highly semantic markup. Create a good solid data layer and the rest will be piss easy :)


text:
Q: Get records containing iframe elements with 'src="http:' with PostgreSQL I need to get all records with iframe elements with the attribute "src" starting with "http:".
e.g.
In table "entries" there is a column "content", which contains HTML strings. These strings may contain zero or more iframe elements.
If inside "content" a record has something like this:
<iframe title="Some title" src="http://webpage.com" />

It should be returned.
I'm currently trying with the next query but results are not as expected.
SELECT content FROM entries WHERE content ~ '.*<iframe.*src="http:.*'

A: You can use the following regex:
 '<iframe[^>]*src="http:[^>]*>'

Here is a regex demo (see the right-side pane for more regex details)
The regex matches <iframe literally, then 0 or more characters other than >, then src="http: literally, then again 0 or more charactets other than > and the final >.

A: I think you need a regex like this:
(?i)(<iframe[^>]*title="[^>]*"[^>]*src="[^>]*"[^>]*>)|(<iframe[^>]*src="[^>]*"[^>]*title="[^>]*"[^>]*>)

or
/(<iframe[^>]*title="[^>]*"[^>]*src="[^>]*"[^>]*>)|(<iframe[^>]*src="[^>]*"[^>]*title="[^>]*"[^>]*>)/i

For more accurate check you can add spaces like this:
/(<iframe[^>]* title *= *"[^>]*"[^>]* src *= *"[^>]*"[^>]*>)|(<iframe[^>]* src *= *"[^>]*"[^>]* title *= *"[^>]*"[^>]*>)/i


text:
Q: Postgres.exe crashes and tears down all apps, recovers and is running again I'm running an application with about 20 processes connected to a postgres DB (10.0) on windows server 2016.
Since about a month I have unexpected crashes of postgres.exe.
To isolate the problem I extended the logging by setting log_min_duration_statement = 0
This creates more detailed logfile. What I can see is:
LOG:  server process (PID xxxxx) was terminated by exception
0xFFFFFFFF DETAIL:  Failed process was running: COMMIT HINT:  See C
include file "ntstatus.h" for a description of the hexadecimal value.

Then it tears down all 20 processes like this:
LOG:  terminating any other active server processes
WARNING:  terminating connection because of crash of another server process
DETAIL:  The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.
HINT:  In a moment you should be able to reconnect to the database and repeat your command.
WARNING:  terminating connection because of crash of another server process
DETAIL:  The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.Then DB recovers:
HINT:  In a moment you should be able to reconnect to the database and repeat your command.
LOG:  all server processes terminated; reinitializing
LOG:  database system was interrupted; last known up at 2021-06-11 18:17:18 CEST

DB enters recovery mode
FATAL:  the database system is in recovery mode
FATAL:  the database system is in recovery mode
FATAL:  the database system is in recovery mode
FATAL:  the database system is in recovery mode
LOG:  database system was not properly shut down; automatic recovery in progress
...
LOG:  redo starts at 1B2/33319E58
FATAL:  the database system is in recovery mode
LOG:  invalid record length at 1B2/33D29930: wanted 24, got 0
LOG:  redo done at 1B2/33D29908
LOG:  last completed transaction was at log time 2021-06-11 18:21:39.830526+02
FATAL:  the database system is in recovery mode
...
FATAL:  the database system is in recovery mode
LOG:  database system is ready to accept connections

Now it's running again like normal
The crashed PID xxxxx I can identify to a postgres.exe running for one of the 20 application processes. It's not always the same one. This happens about every 5-10 days.
Can anybody give me some advice how to track down the reason of this crash?
Extensions used:
oracle_fdw 2.0.0, PostgreSQL 10.0, Oracle client 11.2.0.3.0, Oracle server 11.2.0.2.0

Crashdump:
Followed the link :
https://wiki.postgresql.org/wiki/Getting_a_stack_trace_of_a_running_PostgreSQL_backend_on_Windows
Although the postgres user has "full control" of the crashdump folder in the security tab it does not write something. Folder stays empty.
Follow-Up on the comment @Laurenz Albe:
The COMMIT is not the reason of the crash. It is the last successfull executed command of the session. Explained on the following example:
Process gets a job and starts to do it's job
2021-06-15 16:27:51.100 CEST [25604] LOG:  duration: 0.061 ms  statement: DISCARD ALL
2021-06-15 16:27:51.100 CEST [25604] LOG:  duration: 0.012 ms  statement: BEGIN
2021-06-15 16:27:51.100 CEST [25604] LOG:  duration: 0.015 ms  statement: SET TRANSACTION ISOLATION LEVEL READ COMMITTED

now a lot of action going on within session 25604
and among others the oracle foreign datawrapper
2021-06-15 16:28:13.792 CEST [25604] LOG:  duration: 0.016 ms  execute <unnamed>: FETCH ALL FROM "<unnamed portal 689>"

finishes action successfully (data of the transaction in the database)
2021-06-15 16:28:13.823 CEST [25604] LOG:  duration: 0.059 ms  statement: COMMIT

a lot of action is going in different sessions
among others the oracle foreign datawrapper
more the 7 minutes afterwards the next job is requested and now postgres.exe crash
2021-06-15 16:36:01.524 CEST [17904] LOG:  server process (PID 25604) was terminated by exception 0xFFFFFFFF

The process does not do DISCARD ALL, BEGIN and SET TRANSACTION ISOLATION LEVEL READ COMMITTED
It crashes immediately
My Conclusion:
"the possibly corrupted shared memory" was initiated by one of the processes before. Meaning between the last successful COMMIT and the new request.
That's a 7 minutes time span where the problem occurs.
Some feedback on this conclusion?


text:
Q: Post request with basic authorisation I am writing a C# console app to send a POST request with basic authentication to obtain an access token from an api. I have to pass grant_type=password&username=&password= and I am not sure how to pass this in with the post request. So far I have
var response = await client.PostAsync(uri, content);

Do I pass the password/username in the content, if so how?  Thanks

A: You should use FormUrlEncodedContent:
var parameters = new List<KeyValuePair<string, string>>();
parameters.Add(new KeyValuePair<string, string>("grant_type", "password"));
parameters.Add(new KeyValuePair<string, string>("username", "your_username"));
parameters.Add(new KeyValuePair<string, string>("password", "your_password"));

var request = new HttpRequestMessage(HttpMethod.Post, uri)
{
    Content = new FormUrlEncodedContent(parameters)
};

var response = await client.SendAsync(request);


text:
Q: Is it right that ASP.NET bundles get generated on every request? We hit a performance issue recently that highlighted something that I need to confirm.
When you include a bundle like this:
@Scripts.Render("~/jquery)

This appears to be running through (identified using dotTrace, and seen it running through this):
Microsoft.Ajax.Utilities.MinifyJavascript()

for every single request to both the page that has the include, and also the call to the script itself.
I appreciate that in a real world scenario, there will only be 1 hit to the script as the client will cache it.  however, it seems inefficient to say the least.
The question is, is this expected behavior, as if it isn't, I'd like to fix it (so any suggestions), but if it is, we can pre-minify the scripts.
UPDATE
So, even if I change the compilation mode to debug, it's still firing the minify method.  It outputs the individual urls, but still trys to minify it.
However, if remove all the references to the render methods, it doesn't try to minify anything, and runs rapidly, doesn't balloon the app pool, and doesn't max the CPU on the web server.


text:
Q: Need a non-TAB character to traverse li items in a drop-down menu default elements in html that are tabbable are:
<a> , <area> , <button> , <input> , <object> , <select> , and <textarea>
If someone were to "plop" my code for drop-down menus, my tabbable elements are my li.
What I wish to do is select a non- TAB key to traverse my li, thus keeping the TAB key reserved by HTML
FWIW, I just let my selection of the TAB key ride ... eventually it gets to my last li and then tabs to your <a> or <input> etc. html and then proceeds to the Browser's tabbable stuff and cycles back to the beginning of my li items.
Not too awful I guess?
Suggestions appreciated.

A: You can give your <li> items a tabindex of -1 to make sure they're not focusable vith the TAB character, then focus the next element with Javascript using the HTMLElement.focus() method and onkeyup event.


text:
Q: Jquery dialog submit not working yesterday I started working on a Jquery Dialog box to replace the default confirm box that jquery has... I came across an issue and all the tutorials I see tell me to use .submit() on my form but that does not seem to want to play nicely (or play at all for that matter)
This is the JSFIDDLE
And now this is my javascript that is not working for me :
<script>

$(document).ready(function() {
        $(function() {
            var currentForm;
            $("#dialog-confirm").dialog({
                resizable: false,
                autoOpen: false,
                draggable: false,
                height: 310,
                width: 500,
                modal: true,
                buttons: {
                    'Cancel': function() {
                        $(this).dialog("close");
                    },
                    'Enter Queue': function() {
                        currentForm.submit();
                    }
                }
            });
        });

    $("#signinform").submit(function() {
        currentForm = this;
        $('#dialog-confirm').dialog('open');
        return false;
    });
});

</script>

The problem is happening at the "Enter Queue" button. Pretty much the scenario (as it is shown on the jsfiddle) is I need users to acknowledge the rules of the office, and if they do so they click on a check-box, once they do so then they click Submit, which then sends a dialog explaining to the user what they are getting into. However for some reason the "Enter Queue" button does nothing. I am quite confused. Any help would be great.
Thanks

A: It's because your re-using the $(document).on('submit', "#signinform", function(e) method
which got e.preventDefault(); for first instruction when you call $('#signinform').submit();.
You need to set a temporary variable to see wether you come from your code or the submit button.
Here is a JSFiddle with a working test, but you should do something nicer =)
EDIT : Javascript is an asynchronous langage, it means that your $('#dialog-confirm').dialog('open'); doesn't block and just modify the html, so the submit event always will return false -> it will never be sent.
So I get that JSFiddle which not really works like you want but if you trigger the submit button a second time after clicked the Enter Queue button it will work, so i'm wondering why the submit() method don't work when called from here.
A method you could use is to send the form with ajax (look at post() in jquery) and then redirect your user with something like window.location = "yourpage".

A: Try this way (jsFiddle):
$(document).ready(function() {
    window.enterQueue=false;
    $("#signinform input:submit").on('click',function() {
        return getDialog(window.enterQueue);
    });

    function getDialog(enterQueue){
        if(!enterQueue){
            $("#dialog-confirm").dialog({
                resizable: false,
                autoOpen: true,
                draggable: false,
                height: 310,
                width: 500,
                modal: true,
                buttons: {
                    'Cancel': function() {
                        $(this).dialog("close");
                    },
                    'Enter Queue': function() {
                        window.enterQueue=true;
                        $(this).dialog("close");
                        $("#signinform input:submit").trigger('click');
                    }
                }
            });
            return false;
        } else
            return true;
    }

});

A: I figured it out last night with the help of jquery website and a lot of google-ing. Thanks to the both of you for your help and time it took for the answers. + 1
This is my solution :
<script type="text/javascript">

    $(document).ready(function()
    {
        var Form = $("#signinform");
        $(function()
        {
            $("#dialog-confirm").dialog(
            {
                resizable: false,
                autoOpen: false,
                dialogClass: "no-close",
                draggable: false,
                height: 320,
                width: 500,
                modal: true,
                buttons:
                {
                    'Cancel': function()
                    {
                        $(this).dialog("close");
                        Form.data("confirmProgress", false);
                    },
                    'Submit Information': function()
                    {
                        Form.submit();
                        Form.data("confirmProgress", false);
                    }
                }
            });
        });
        Form.submit(function()
        {
            if (!$(this).data("confirmProgress"))
            {
                $(this).data("confirmProgress", true);
                $('#dialog-confirm').dialog('open');
                return false;
            } else {
                return true;
            }

        });
    });
    // Everything under this is the Jquery for my second Dialog that has always been working, the issue was the above dialog which is now fixed.
 $(document).on('click', "#Cancel", function(e)
    {
        e.preventDefault();
        var href = '<?php echo base_url(); ?>studentlogin_controller/studentlogin';
        $("#dialog-noconfirm").dialog(
        {
            resizable: false,
            dialogClass: "no-close",
            draggable: false,
            height: 320,
            width: 500,
            modal: true,
            buttons:
            {
                "Cancel": function()
                {
                    $(this).dialog("close");
                },
                "Go Back": function()
                {
                    window.location.href = href;
                },
            }
        });
    });

</script>


text:
Q: How to sort values of tree map grabbed from twitter api and show it in TextView(android)? Using twitter 4j library, I grab latest tweet of the user and then grab retweeters id and their followers count.
Now what i need to do is show the id of retweeeters, sort them in descending order of followers i.e highest follower first rank.
I grabbed and put the followers count in tree map , now how to sort them ? and then show them in TextView ?
Using twitter4j i grabbed tweets of the user and put them in 'status' rest of it is :-
//get  the first status
        status = statuses.get(0);
     //get id of the status
          long l= status.getId();
        //get retweeters id
          ki =twitter.getRetweeterIds(l, 100, -1);

         long[] id=ki.getIDs();
         //for every retweeter id, get followers count and put in treemap
         TreeMap<Integer,Long> tm = new TreeMap<Integer, Long>();
         for(int k=0;k<=id.length;k++)
         {
             u = twitter.showUser(id[k]);
             follower=u.getFollowersCount();
             tm.put(follower,id[k] );
         }
        NavigableMap<Integer,Long> reverseTreeMap = tm.descendingMap();

A: Solved!
This is how i did it
//Using treemap to sort retweeters according to their followers
 TreeMap<Integer,String> tm = new TreeMap<Integer, String>();
 try{
     for(int k=0;k<10;k++)
         {
             publishProgress(5);
             Log.i(a, "treemap followers"+k);
             u = twitter.showUser(id[k]);
             follower=u.getFollowersCount();
             url=u.getProfileImageURL();
             tm.put(follower,url );
         }
    }
catch(Exception e)
    {
        Log.e(a, e.toString());
    }
Log.i(a, "Done treemap");

 //Reverse the order of the treemap
 Log.i(a, "Reversing Treemap");
 NavigableMap<Integer,String> reverseTreeMap = tm.descendingMap();
 publishProgress(5);

 //Put treemap values in string array
 s=reverseTreeMap.values().toString();
 s=s.replace("[", "");
 s=s.replace("]", "");
  Log.i(a, "Done");

//use String array to show them in Textview or anywhere


text:
Q: Currency symbol: French franc Is there a LaTeX symbol for French franc; the F-like symbol with a lower horizontal bar -- see http://en.wikipedia.org/wiki/French_franc?
I have had a look a both Detexify and The Comprehensive LaTeX Symbol List without any luck.
Update
If I try the follwing, the symbol is not written; only 123 is:
\documentclass{article}

\usepackage{fontspec}
\usepackage{siunitx}

\fontspec{FreeSerif.otf}
\DeclareSIUnit{\franc}{^^^^20a3}

\begin{document}

\SI{123}{\franc}

\end{document}

How should I change the code?

A: The Unicode symbol for ₣ is:
U+20A3 FRENCH FRANC SIGN

Libertine is an example for a Unicode font that supports the character:
% lualatex or xelatex
\documentclass{article}
\usepackage{libertineotf}
\begin{document}
^^^^20a3 % ASCII notation
\end{document}

Example for GNU FreeFont:
\documentclass{article}
\usepackage{fontspec}
\begin{document}
\fontspec{FreeSerif.otf}
^^^^20a3
\end{document}

Another example for Times New Roman (from Windows 7):
\documentclass{article}
\usepackage{fontspec}
\begin{document}
\fontspec{times.ttf}
^^^^20a3
\end{document}

\fontspec{Comfortaa-Regular.ttf}% Comfortaa Regular:

\fontspec{OpenSans-Regular.ttf}% Open Sans Regular:

Example for siunitx and pdfLaTeX
If lualatex or pdflatex cannot be used, then the symbol can be included as graphics. The graphics is generated by:
% franc.tex
\nofiles
\documentclass{article}
\usepackage{fontspec}
\begin{document}
\fontspec{FreeSerif.otf}
^^^^20a3
\end{document}

It is compiled via:
$ lualatex franc
$ pdfcrop franc

Then franc-crop.pdf can be used as image for pdfLaTeX:
\documentclass{article}
\usepackage{graphicx}
\usepackage{siunitx}
\DeclareRobustCommand*{\myfranc}{\includegraphics[scale=.1]{franc}}
\DeclareSIUnit{\franc}{\myfranc}

\begin{document}
\SI{123.45}{\franc}
\end{document}

If you are using lualatex or xelatex, then the font can be used directly, e.g.:
\DeclareRobustCommand*{\myfranc}{%
  \begingroup
    \fontspec{FreeSerif.otf}%
    ^^^^20a3%
  \endgroup
}


text:
Q: Is Automapper supposed to work with private setters OOB? I have a nested child class with public properties with private setters. In the parent class I am able to use Automapper to map to the child class and the values of the private setters are being set. Everything I've read points to Automapper not supporting this and requiring a custom constructor in the child class to populate private setters.
Is the current version using reflection or something to map the private setters? The setters are definitely private because in the parent class I am unable set Child.Property but in the same place Mapper.Map is able to set the property.

A: Automapper uses reflection extensively, and there is no reason not to use it to set private setters.
Actually, until your question I didn't know that it works.
If we look at unit tests we can found the fact that private setters are set automatically. Please see PrivateSetterInParentWorks.
Note, Silverlight doesn't support setting private fields through reflection. So, the feature doesn't work with it.


text:
Q: Have two navs at the top of the page with one fixed-top yet not overlapping the other I'm trying to achieve the result illustrated here.
The promotional banner needs to be sticky to the top of the page while the nav that is below it will scroll up with the rest of the content.
Here is some basic HTML that I use to do this. I have also set body {padding-top: 40px;} so the nav with the actual menu appears below the promotional banner.
Promotional banner text goes here promotional banner text goes here promotional banner text goes here

  Top navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home

        Link

    (555) 555 5555

That's great if the viewport is wide enough to fit the text of the promotional banner, but if the text breaks onto second line it overlaps the menu. In this scenario, I would ideally have the menu just shift further below the promotional banner, but currently I've defined the distance of the nav bar from the top of the page using CSS body {padding-top: 40px;}
What is the correct way of solving this problem?

A: OK, I put the promo banner into a container and nested that within a container-fluid. Normally, containers shouldn't be nested but this is one of those rare exceptions.
Your navbar also sits inside a container. This is to make sure that users on wide 4K displays won't get mad at you. I also replaced some of your custom css with native Bootstrap 4 classes and that's pretty much it.
Here's the code:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Promotional banner text goes here promotional banner text goes here promotional banner text goes here. Promotional banner text goes here promotional banner text goes here promotional banner text goes here.

       Top navbar
       <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

       </button>

                   Home

                   Link

           (555) 555 5555


text:
Q: Distributing IronPython: MissingMethodException InitializeModuleEx I have an application written in IronPython that I want to distribute as an .exe on other PCs. I've been using pyc.py following the instructions here, and been somewhat successful. I end up with a dir containing:

*

*my_app.exe

*my_app.dll

*StdLib.DLL [this contains the standard IronPython library, as suggested in the SO post referenced above]

*IronPython.dll

*IronPython.Modules.dll

*Microsoft.Dynamic.dll

*Microsoft.Scripting.dll

*Microsoft.Scripting.Metadata.dll

I'm using IronPython 2.7.3; on my dev machine I have .NET 4.0.30319.17929.
The problem I have is that when I distribute the above to other machines, on some machines it works perfectly, and on others I get the following:
Unhandled Exception: System.MissingMethodException: Method not found: 'Int32 Iro
nPython.Runtime.Operations.PythonOps.InitializeModuleEx(System.Reflection.Assemb
ly, System.String, System.String[], Boolean)'.
   at PythonMain.Main()

The machines it works on include both Windows 7 and Windows XP boxes, and the machines it fails on also include both Windows 7 and Windows XP. I've checked the .NET versions, comparing the machines where it works and where it doesn't work and I can't see anything obvious. For example, on an XP machine where it fails I have a .NET profile of:
<32Bit>
1.1.4322.2494
  ->C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322
2.0.50727.3634
  ->C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
4.0.30319.269
  ->C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319

< Installed .NET Frameworks >
.NET FW 1.1 SP 1
.NET FW 2.0 SP 2
.NET FW 3.0 SP 2
.NET FW 3.5 SP 1
.NET FW 4.0 Client
.NET FW 4.0 Full

and on an XP machine where it works fine I have a .NET profile of:
<32Bit>
1.1.4322.2494
  ->C:\Windows\Microsoft.NET\Framework\v1.1.4322
2.0.50727.3634
  ->C:\Windows\Microsoft.NET\Framework\v2.0.50727
4.0.30319.269
  ->C:\Windows\Microsoft.NET\Framework\v4.0.30319

< Installed .NET Frameworks >
.NET FW 1.1 SP 1
.NET FW 2.0 SP 2
.NET FW 3.0 SP 2
.NET FW 3.5 SP 1
.NET FW 4.0 Client
.NET FW 4.0 Full

which looks identical to me.
I don't really know what to look at next; any clues?

A: Jeff Hardy's comment above is the answer: the machines getting the error already had older versions of IronPython installed, and were using the those assemblies rather than the local ones distributed in the same dir as the exe. Solved by uninstalling IronPython on the problematic machines.


text:
Q: How to define custom themes in vue.js using typescript? I am trying to change the colours of a Vue template (uses vuetify) that I am using but after pouring over the docs for a day I am not sure what else I can try.
My main file:
//src/main.ts

import '@babel/polyfill';
// Import Component hooks before component definitions
import './component-hooks';
import Vue from 'vue';
import './plugins/vuetify';
import './plugins/vee-validate';
import App from './App.vue';
import router from './router';
import store from '@/store';
import './registerServiceWorker';

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount('#app');

the vuetify plugin file:
//src/plugins/vuetify.ts

import Vue from 'vue';
import Vuetify from 'vuetify';

Vue.use(Vuetify, {
  theme: {
      themes: {
          light: {
            primary: '#17242d',
          },
          dark: {
            primary: '#17242d',
        },
      },
    },
});

I tried many variations of defining different themes in the vuetify.ts file but nothing changes the colours in of any component that references (for example) "primary".
Other people seemed to have success with my approach: https://forum.vuejs.org/t/vuetify-how-to-add-a-custom-color-theme-after-create-the-project/40241/2
Am I missing something? Where should I look next?
EDIT 1: Removed reference to vuetify.min.css in main.ts. Now I can see my selected colour for a few ms before it switches back to default after server restart.
EDIT 2: Using the web inspector I could figure out that the primary colour is appended with !important (which as far as I understood means that this definition supersedes all others). How would I fid where that definition is?

A: Instead of importing Vuetify from node_modules within your main.ts you should rather import the file from your plugins folder.
So in your main.ts instead of
import Vuetify from 'vuetify';

try this
import './src/plugins/vuetify.ts';

A: //src/plugins/vuetify.ts
import Vue from "vue";
import Vuetify from "vuetify/lib/framework";
import "vuetify/dist/vuetify.min.css";

Vue.use(Vuetify);

export default new Vuetify({
  theme: {
    themes: {
      light: {
        primary: "#17242d",
      },
      dark: {
        primary: "#17242d",
      },
    },
  },
});

//src/main.ts
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import vuetify from "./plugins/vuetify";

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  vuetify,
  render: (h) => h(App),
}).$mount("#app");

Repo with demo