text:
Q: How to map LINQ To SQL to enable eager loading, return EntitySet or ICollection? This is related (but fairly independent) to my question here: Why SELECT N + 1 with no foreign keys and LINQ?
I've tried using DataLoadOptions to force eager loading, but I'm not getting it to work.
I'm manually writing my LinqToSQL mappings and was first following this tutorial: http://www.codeproject.com/Articles/43025/A-LINQ-Tutorial-Mapping-Tables-to-Objects
Now I've found this tutorial: http://msdn.microsoft.com/en-us/library/bb386950.aspx
There's at least one major difference that I can spot. The first tutorial suggest returning ICollection's and the second EntitySet's. Since I'm having issues I tried to switch my code to return EntitySet's, but then I got issue with needing to reference System.Data.Linq in my Views and Controllers. I tried to do that, but didn't get it to work. I'm also not sure it's a good idea.
At this point, I just want to know which return type I'm supposed to use for a good design? Can I have a good design and still be able to force eager loading in specific cases?

A: A lot of trial and error finally lead to the solution. It's fine to return ICollection or IList, or in some cases IEnumerable. Some think returning EntitySet or IQueryable is a bad idea, and I agree because it exposes to much of the datasource/technology. Some thing returning IEnumerable is a bad idea and it seems like it depends. The problem beeing that it can be used for lazy loading, which may or may not be a good thing.
One reoccuring issue is that of returning paged results with a count for the total items outside the page. This can be solved by creating a CollectionPage<T> ( http://www.codetunnel.com/blog/post/104/how-to-properly-return-a-paged-result-set-from-your-repository )
More on what to return from repositories here:
http://www.codetunnel.com/blog/post/103/should-you-return-iqueryablet-from-your-repositories
http://www.shawnmclean.com/blog/2011/06/iqueryable-vs-ienumerable-in-the-repository-pattern/
IEnumerable vs IQueryable for Business Logic or DAL return Types
List, IList, IEnumerable, IQueryable, ICollection, which is most flexible return type?
Even more important, DataLoadOptions can do the eager loading! I've now restructured my code so much I'm not 100% sure what I did wrong to cause DataLoadOptions not to work. As far as I've gathered I should get an exception if I tried to add it to the DataContext after the DataContext has been used, which it didn't. What I've found out though is to think in the Unit of Work-pattern. However, for my needs (and because I don't want to return EntitySet or IQueryable from my repositories) I'm not going to implement a cross-repository Unit of Work. Instead I'm just thinking about my repository methods as their own small Unit of Work. I'm sure there's bad things about this (for instance it might cause more round-trips to the database in some update scenarios), and in the future I might reconcider. However it's a simple clean solution.
More info here:
https://stackoverflow.com/a/7941017/1312533
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
This is what I ended up with in my repository:
public class SqlLocalizedCategoriesRepository : ILocalizedCategoriesRepository
{
    private string connectionString;
    private HttpContextBase httpContext;
    public SqlLocalizedCategoriesRepository(string connectionString, HttpContextBase httpContext) // Injected with Inversion of Control
    {
        this.connectionString = connectionString;
        this.httpContext = httpContext;
    }

    public CollectionPage<Product> GetProductsByLocalizedCategory(string category, int countryId, int page, int pageSize)
    {
        // Setup a DataContext
        using (var context = new DataContext(connectionString)) // Because DataContext implements IDisposable it should be disposed of
        {
            var dlo = new System.Data.Linq.DataLoadOptions();
            dlo.LoadWith<Product>(p => p.ProductSubs); // In this case I want all ProductSubs for the Products, so I eager load them with LoadWith. There's also AssociateWith which can filter what is eager loaded.
            context.LoadOptions = dlo;
            context.Log = (StringWriter)httpContext.Items["linqToSqlLog"]; // For logging queries, a must so you can see what LINQ to SQL generates

            // Query the DataContext
            var cat = (from lc in context.GetTable<LocalizedCategory>()
                       where lc.CountryID == countryId && lc.Name == category
                       select lc.Category).First(); // Gets the category into memory. Might be some way to not get it into memory by combining with the next query, but in my case my next step is that I'm also going to need the Category anyway so it's not worth doing because I'm going to restructure this code to take a categoryId parameter instead of the category parameter.

            var products = (from p in context.GetTable<Product>()
                            where p.ProductCategories.Any(pm => pm.Category.CategoryID == cat.CategoryID)
                            select p); // Generates a single query to get the the relevant products, which with DataLoadOptions loads related ProductSubs. It's important that this is just a query and not loaded into memory since we're going to split it into pages.

            // Return the results
            var pageOfItems = new CollectionPage<Product>
            {
                Items = products.Skip(pageSize * (page - 1)).Take(pageSize).ToList(), // Gets the page of products into memory
                TotalItems = products.Count(), // Get to total count of items belonging to the Category
                CurrentPage = page
            };
            return pageOfItems;
        }
    }
}


text:
Q: Some doubts about Java polymorphism applied to the Calendar and GregoriaCalendar case I have the following doubt.
Into my code I have:
Calendar today = Calendar.getInstance();

where today variable is an instance of Calendar so I can't use methods as isLeapYear() on it.
Doing in this way I can perform this method:
GregorianCalendar today = (GregorianCalendar) Calendar.getInstance();
int currentYear = today.get(Calendar.YEAR);

boolean bisestile = today.isLeapYear(currentYear);

My doubt is: exatly why? I am casting the same result instange returned by Calendar.getInstance() to be a GregorianCalendar.
Reading here: http://tutorials.jenkov.com/java-date-time/java-util-calendar.html
it seems to me to understand that The java.util.Calendar class is abstract so I cannot instantiate it so I think that the Calendar.getInstance() automatically return a GregorianCalendar object that have defined the previous isLeapYear() method.
But I can't use it if the object is defined as a simple Calendar and not as a GregorianCalendar.
I know about polymorphism but how exactly works in this specific case?
I think that putting the reference of a GregorianCalendar object (returned by Calendar.getInstance(), is it true?) into a Calendar (I can do it because Calendar is the super type) I can access only to the methods subset defined for this abstract class and not to all the methods defined for the concrete type.
Is it this reasoning correct or am I missing something?

A: This is polymorphism. Calendar provides an abstract framework, and subclasses like GregorianCalendar provide implementations. In other contexts, understand that Calendar.getInstance() maybe could return (for instance) a Chinese or a Hebrew calendar depending on the locality and system setup.
If what you really want is a GregorianCalendar explicitly, declare the variable as such.
GregorianCalendar cal = new GregorianCalendar();

A: The Answer by ControlAltDel is correct.
One of the benefits of Object-Oriented Programming is preventing fragile software that breaks after making some change. One of the ways to accomplish that is where we define an interface with one or more implementations. When other code refers to the interface, we can switch out the implementation without breaking the calling code.
So the general rule is to use the highest level of interface that meets your needs.
Example: Collections
For example in Java Collections, use the Collection interface where it meets your needs.
Collection<String> col = new ArrayList<>() ;

Get more specific only if your code requires the additional methods offered by a more specific interface. Here we use List, a sub-interface of Collection that promises additional methods.
List<String> list = new ArrayList<>() ;

Use the ArrayList as an ArrayList only if absolutely necessary, only if that class offers certain methods you require that are not included in its more general interfaces.
ArrayList<String> list = new ArrayList<>() ;

Later we may decide to replace that ArrayList with a LinkedList. Doing so won't break any code that was expecting a List or Collection but would break any calling code that expected an ArrayList specifically.
List<String> list = new LinkedList<>();

Calendar & GregorianCalendar
Similarly, you should use Calendar wherever possible, rather than GregorianCalendar.
Calendar cal = new GregorianCalendar() ;

But if the code absolutely needs the special features of GregorianCalendar then track the object as a GregorianCalendar as shown in the Answer by ControlAltDel.
GregorianCalendar cal = new GregorianCalendar() ;

You can mix this up, using a more-specific type internally and a more-general type externally. If you only need those special GregorianCalendar features inside your own class, but want to expose the calendar to other classes, you can declare the calendar object as a GregorianCalendar as the private member of your class while returning Calendar from a getter method.
…
private GregorianCalendar gregCal = new GregorianCalendar() ;
…
public Calendar getCalendar() {
    return this.gregCal ;  // Automatically upcast. Appears to any calling code to be a `Calendar`.
}

P.S. The java.util.Calendar & .GregorianCalendar are part of the troublesome old legacy date-time classes now supplanted by the java.time classes built into Java 8 and later. Avoid these old classes.

A: If you are in Thailand then your code
GregorianCalendar today = (GregorianCalendar) Calendar.getInstance();

will probably fail by throwing a ClassCastException because Calendar.getInstance() can yield the Thai-Buddhist calendar as default in that country. This use-case indicates a strong warning to use Calendar.getInstance() if you are really sitting in Thailand. And then you cannot make your gregorian-based assumptions when you are going to interprete expressions like calendar.get(Calendar.YEAR) (maybe yielding year values like 2543).
Conclusion: When handling date and time, it is much better NOT to use generic interfaces but to be as concrete as possible. I assume you are only interested into the gregorian calendar, so please use:
GregorianCalendar today = new GregorianCalendar();

By the way, the main designers of new java.time-package in Java-8 have also adopted this view to be as concrete as possible:

Most applications should declare method signatures, fields and
  variables as LocalDate, not this interface.

Practically this means: You should avoid types like TemporalAccessor, ChronoLocalDate etc., or in old world: Avoid types like java.util.Calendar in favor of concrete types like GregorianCalendar. Polymorphism is not a very good idea in the world of date and time. The concrete types are too different (sometimes in a very subtile way).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to unit test useFormik onSubmit in react? I have a react component called Subscribe.js. It has its own custom hook that takes care of the business logic. In that hook, I am using the useFormik hook to set up validations and onSubmit for the form in the Subscribe.js component.
How do I test the form submission functionality?
Here is what I have done so far
 it("should complete form submission", async () => {
    const handleSubmit = jest.fn();
    render(<Subscribe />);

    const inputElement = screen.getByPlaceholderText("Enter your email");

    userEvent.type(inputElement, "abc@gmail.com");
    const submitButton = screen.getByRole("button", { name: /submit/i });
    userEvent.click(submitButton);

    await waitFor(() => {
      expect(handleSubmit).toHaveBeenCalledTimes(1);
    });
  });

This is my test and I am referencing the example given on the official docs of the react testing library.
Here is my Subscribe.js component
import React from "react";
import {  Button, Form } from "react-bootstrap";
import useSubscribe from "./../../hooks/useSubscribe";
import { FormField } from "./../FormField/FormField";
function Subscribe() {
  const { formik, isLoading } = useSubscribe();
  return (
        <Form  onSubmit={formik.handleSubmit}>

              <FormField
                type="Email"
                className="w-100"
                placeholder="Enter your email"
                isInvalid={formik.errors.email}
                isValid={formik.touched.email && !formik.errors.email}
                error={formik.errors.email}
                {...formik.getFieldProps("email")}
              />

              <Button
                type="submit"
                variant="primary"
                size="lg"
                className="btn btn-primary btn-lg px-4 mb-2"
                onClick={formik.handleSubmit}
              >Submit
              </Button>
        </Form>
  );
}

export default Subscribe;

Here is my useSubscribe hook that is responsible for form submission and validations.

import { useFormik } from "formik";
import * as Yup from "yup";

const useSubscribe = () => {

  const initialValues = {
    email: "",
  };

  const formik = useFormik({
    initialValues: initialValues,
    validationSchema: Yup.object({
      email: Yup.string().email("Invalid Email").required("Email is required"),
    }),
    onSubmit: async (values) => {
   // call to backend with values
  });
  return {
    formik,
  };
};

export default useSubscribe;


text:
Q: Creating a smoother curve for high order polynom fit I am trying to visualise an over. and underfitting of data. It works fine but the high order polynom plotting has edges (due to too few points) but how can I feed it more points to predict for? i.e. create the model based on x,y but predict then for x_fine ...
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures

np.random.seed(19824)

step = 0.1
x = np.arange(0, 3, step)   # start,stop,step
y = np.sin(x)
numEl = len(x)

noise_mu = 0
noise_sigma = 0.05
noise_x = np.random.normal(noise_mu, noise_sigma, numEl)
noise_y = np.random.normal(noise_mu, noise_sigma*2, numEl)

x = x + noise_x
y = y + noise_y
x = x.reshape(-1, 1)

# linar model
lm = linear_model.LinearRegression()
model = lm.fit(x, y)
predictions = lm.predict(x)
plt.plot(x, y, "ob", alpha=0.5, label="data")
plt.plot(x, predictions, color='black', linewidth=1, alpha=0.5)

# poly 30
step = 0.01
x_fine = np.arange(0, 3, step)
x_fine = x_fine.reshape(-1, 1)

degree = 30

polynomial_features= PolynomialFeatures(degree=degree)
x_poly = polynomial_features.fit_transform(x)

model = linear_model.LinearRegression()
model.fit(x_poly, y)
y_poly_pred = model.predict(x_poly)

plt.plot(x, y_poly_pred, color='red', linewidth=1, alpha=0.5)

plt.show()

A: If you change the last lines of your code for these ones:
model = linear_model.LinearRegression()
model.fit(x_poly, y)

xx = np.linspace(x[0], x[-1], 1001)
xx_poly = polynomial_features.fit_transform(xx)
y_poly_pred = model.predict(xx_poly)

plt.plot(xx, y_poly_pred, color='red', linewidth=1, alpha=0.5)
plt.ylim(0, 1.5)

plt.show()

Then you obtain the smoother curve:

Note that fitting data with such a high degree polynomial can result in big spikes.


text:
Q: Como o Python trata o comando "yield" internamente? Estava lendo sobre o comando yield do Python, e me parece que este comando cria um generator que seria uma especie de lista de dados no qual o retorno do valor ocorre sobre demanda, como se o ultimo "estado" da interação fosse "memorizado" de alguma forma.
Para comprovar isso, veja esta função que retorna três letras:
def letras():
    yield 'A'
    yield 'B'
    yield 'C'

Chamando a função letras() num for para obter os dados:
for letra in letras():
    print(letra)

Perceba que a saída sera:
A
B
C

Agora, se eu modificar a função letras() para ela incrementar o valor de v que é uma variavel global:
def letras():
    global v
    v += 1
    print(v)
    yield 'A'
    yield 'B'
    yield 'C'

e a saída:
1
A
B
C

Veja que v possui o valor 1, isso mostra que a função letras() não memorizou o estado de v, apenas os valores retornados no yield, é como se a função tivesse sido chamada uma única vez. Por consequência, eu ainda não consigo ver de forma clara como é o funcionamento do yield, pois o comportamento da função parece ter sido diferente do que eu esperava e me gerou mais confusão ainda acerca do yield, talvez entender como o Python lida com ele internamente pode ajudar.
Pergunta
Portanto, eu gostaria de saber como o Python trata o comando yield internamente? Ou qual estrutura ou mecanismo o yield usa?

A: De fato quando tem um yield na função ela não retorna aquele valor, ela retorna um gerador. Este gerador é um objeto que guarda o estado necessário para seu controle, então ele sabe onde havia parado e assim pode continuar na próxima vez que for chamado.
O for tem um mecanismo próprio que administra isto. Se chamar na mão precisa cuidar do acesso ao gerador na mão. A função next() é usada para manipular o gerador.
Execute este código:
def letras():
    yield 'A'
    yield 'B'
    yield 'C'
gerador = letras()
print(next(gerador))
print(next(gerador))
print(next(gerador))
print(next(letras()))
print(next(letras()))

Coloquei no GitHub para referência futura.
Esta variável gerador é que guarda o gerador e portando o estado da execução, então toda vez que invocar a função ele vai olhar onde o gerador está e irá incrementar 1 no seu estado interno. Como ele faz isto é detalhe de implementação, mas basicamente guarda uma lista de dados e um contador. Esta lista pode ser um controle das linhas a serem executadas. Em Python padrão deve mudar pouco porque já há um mecanismo interno da VM que controla a pilha de execução, então é só encapsular isto em um objeto para controle do gerador.
Perceba que se chamar a função sem guardar o estado ela sempre começa com um gerador novo.
Você não vê no for mas um gerador é criado dentro dele que vai do começo ao fim, o for é uma abstração para o padrão de projeto chamado Iterador. E a função é construída para criar o objeto gerador, por ser uma abstração você não vê o estado sendo criado.
Experimenta chamar 4 vezes o next(gerador) ali em vez de três. O iterador lançará um exceção porque não tem mais dados para avaliar.
Os objetos não pegam iteradores implicitamente, por isso tem um método que retorna o iterador, e como isto é muito comum tem um padrão para pegar este iterador. Objetos que podem ser iteráveis possuem o método __iter__() e o objeto iterador deve possuir sua própria implementação da função __next__(). Os objetos nativos do Python já possuem isto.
No caso de uma função há um objeto interno que é capaz de ser iterável que é criado para lidar com o andamento da função e onde ele está, mas não é diferente de ter o estado e a capacidade de entregar o iterador e quem é o próximo item.

A: Entendendo o que acontece
O yield internamente faz realmente muita coisa:
Pra começar: o fato de uma função ter a palavra chave yield em qualquer parte em seu corpo faz com que ela seja tratada de forma diferente pelo Python. A função deixa de ser uma função e passa a ser uma "generator function".
Essa mudança só é comparável a funções que sejam declaradas explicitamente como assíncronas com a sequência async def em vez de somente def.
O quê acontece é mais ou menos fácil de entender: quando você chama uma função que tenha um yield em seu corpo - mesmo que esse yield nunca vá ser executado - nenhuma linha dessa função é executada de imediato. O que o Python faz é criar um objeto  especial do tipo  generator que é devolvido como se fosse o "retorno" dessa função.
Um "generator" por sua vez é um objeto que vai ter o método especial __next__, (e também  send e throw - falo mais abaixo).
Quando um "generator" é usado do lado direito de um comando for, a própria linguagem vai chamar o método __next__ do generator, uma vez para cada repetição do for.
Da primeira vez que o __next__ é chamado, aí sim, a função começa a ser executada na primeira linha - acontece com ela o que acontece com funções normais - ela recebe os parâmetros que foram passados na chamada inicial, e é executada linha a linha, até chegar no primeiro yield. Nesse momento a execução é "suspensa" - o valor de todas as variáveis locais do generator é salvo, e o valor que foi enviado pelo yield é retornado como resultado da chamada à função __next__. Na próxima chamada ao __next__, o processamento não começa de novo na primeira linha da função, e sim, justamente no ponto em que estava o yield -
o processamento continua a partir dali, linha a linha, até o encontro de um novo yield, ou um comando return (ou o final do código da função, que equivale, em Python, a um return None).
Quando o generator chega ao fim,  em vez de retornar o valor que está no return - ele gera uma exceção do tipo StpoIteration. O comando for captura automaticamente esse StopIteration e encerra o bloco do for.
Fica mais fácil entender se criarmos uma função com yield dentro, e a usarmos no modo "manual", sem o for:
In [275]: def exemplo():
     ...:     print("primeira parte")
     ...:     yield 0
     ...:     print("segunda parte")
     ...:     yield 1
     ...:     print("parte final")
     ...:     return 2
     ...:

In [276]: type(exemplo)
Out[276]: function

In [278]: gen = exemplo()

In [279]: gen, type(gen)
Out[279]: (<generator object exemplo at 0x7f5533e2a6d8>, generator)

In [281]: gen.__next__()
primeira parte
Out[281]: 0

In [282]: gen.__next__()
segunda parte
Out[282]: 1

In [283]: gen.__next__()
parte final
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-283-d5d004b357fe> in <module>
----> 1 gen.__next__()

StopIteration: 2

Perceba que nada foi impresso depois da execução da entrada "278" - a chamada exemplo() retorna um "generator", como podemos ver pela representação e o tipo, na entrada "279", e a linha que imprime "primeira parte" só é chamada quando chamamos o __next__ a primeira vez.
Usando a mesma função exemplo em um for, a saída é:
In [284]: for v in exemplo():
     ...:     print(v)
     ...:
primeira parte
0
segunda parte
1
parte final

Uma outra informação que é legal: os métodos especiais, com dois __ de prefixo e sufixo muito raramente tem que ser chamados diretamente - em geral esses métodos são chamados pela própria linguagem. Então, em vez de chamarmos direto o .__next__ em uma função, o mais comum é usar a função next do Python e passar o generator como parâmetro.
Então, o comando for do Python, quando usado com uma "generator function" é equivalente à esta sequencia usando while:
In [286]: gen = exemplo()

In [287]: while True:
     ...:     try:
     ...:         v = next(gen)
     ...:     except StopIteration:
     ...:         break
     ...:     print(v)
     ...:
primeira parte
0
segunda parte
1
parte final

(O for do Python é mais esperto que isso ainda por que funciona com outros tipo o de objetos: além de detectar generators, ele funciona também com iterables: objetos que tem o método __iter__, e objetos que tenham os métodos __len__ e __getitem__ e, opcionalmente keys, em conjunto.)
Na sua pergunta você acrescenta variáveis globais à generator function de exemplo: uma variável global é global e seu valor será preservado entre chamadas consecutivas ao mesmo generator ou intercaladas com outras instâncias do generator.
Como o Python distingue um generator de uma generator function:
Como dito acima, é o próprio compilador do Python que transforma uma função em uma "generator function".  O tipo de objeto de uma função que contenha um yield continua sendo uma function - como pode ser visto na saída "276" acima. O que o Python faz é que nos flags do  objeto __code__ de uma generator function, ela é marcada como tal - isso faz com que o comportamento da linguagem quando ela é chamada seja completamente diferente.
Ou seja, não é "fácil" ver que uma função é uma "generator function" sem olhar seu código e ver o yield lá - mas com os mecanismos de introspecção do Python, podemos ver que o flag de nome "GENERATOR" está setado no atributo .__code__.co_flags da  função. O valor desse flag pode ser visto no módulo dis:
In [288]: def exemplo():
     ...:     yield
     ...:

In [289]: def contra_exemplo():
     ...:     return None
     ...:

In [290]: import dis

In [291]: dis.COMPILER_FLAG_NAMES
Out[291]:
{1: 'OPTIMIZED',
 2: 'NEWLOCALS',
 4: 'VARARGS',
 8: 'VARKEYWORDS',
 16: 'NESTED',
 32: 'GENERATOR',
 64: 'NOFREE',
 128: 'COROUTINE',
 256: 'ITERABLE_COROUTINE',
 512: 'ASYNC_GENERATOR'}

In [292]: bool(exemplo.__code__.co_flags & 32)
Out[292]: True

In [293]: bool(contra_exemplo.__code__.co_flags & 32)
Out[293]: False

Detalhes internos
Perceba que se você criar mais de um generator a partir da mesma "generator function", e usa-los de forma intercalada, cada um vai ter suas próprias variáveis locais - elas não se misturam:
In [294]: def exemplo3():
     ...:     counter = 0
     ...:     yield counter
     ...:     counter += 1
     ...:     yield counter
     ...:

In [295]: gen1 = exemplo3()

In [296]: gen2 = exemplo3()

In [297]: next(gen1)
Out[297]: 0

In [298]: next(gen2)
Out[298]: 0

In [299]: next(gen2)
Out[299]: 1

In [300]: next(gen1)
Out[300]: 1

Onde essas variáveis locais ficam guardadas então?
Sempre que executamos um bloco de código em Python, seja uma função normal, seja um generator, seja o corpo de um módulo ou o corpo de uma classe, o Python cria um objeto do tipo Frame. A linguagem expõe esses Frames como objetos de Python bem normais - e você pode, dentro deles achar as variáveis locais e as globais de qualquer bloco de código em execução. Num programa que não faça uso de generators ou funções assíncronas, um novo objeto tipo Frame é criado cada vez que uma função é chamada - e o frame mais recente sempre tem uma referência ao anterior. Isso cria uma "pilha" - que chamamos de "pilha de chamada" em Python. Esses objetos Frame não são muito pequenos ou de criação eficiente, por isso que não usamos muito funções recursivas em Python, exceto em código didático ou onde realmente seja a melhor solução. Um dos atributos de um frame é o .f_back: uma referência direta ao frame anterior - e outra é o f_locals que é um dicionário que espelha as variáveis locais do código em execução (o f_locals no entando só funciona pra leitura dessas variáveis, não pra escrita de seus valores).
Uma função recursiva com alguns prints pode mostrar o uso normal de frames, sem generators:
In [306]: import sys

In [307]: def exemplo4(count):
     ...:     if count < 4:
     ...:         print("entrando")
     ...:         exemplo4(count + 1)
     ...:         print("saindo")
     ...:     else:
     ...:         print(f"count: {count}")
     ...:         frame = sys._getframe()
     ...:         frame_count = count
     ...:         while frame_count:
     ...:             print(frame, frame.f_locals["count"])
     ...:             frame = frame.f_back
     ...:             frame_count -= 1
     ...:
     ...:

In [308]: exemplo4(1)
entrando
entrando
entrando
count: 4
<frame at 0x564291236028, file '<ipython-input-307-165f77ce3bd1>', line 11, code exemplo4> 4
<frame at 0x564291308638, file '<ipython-input-307-165f77ce3bd1>', line 4, code exemplo4> 3
<frame at 0x56429132ead8, file '<ipython-input-307-165f77ce3bd1>', line 4, code exemplo4> 2
<frame at 0x5642910e4ff8, file '<ipython-input-307-165f77ce3bd1>', line 4, code exemplo4> 1
saindo
saindo
saindo

Quando um generator é pausado com o yield, o Frame de execução dele sai dessa pilha - o Frame do topo da pilha volta a ser o da função que chamou o __next__. O Frame do generator fica então guardado no atributo .gi_frame do próprio generator. O atributo f_locals pode inspecionar o valor das variáveis dentro do mesmo no momento em que o yield foi executado:
In [319]: def exemplo5():
     ...:     v = 10
     ...:     yield v
     ...:     v += 10
     ...:     yield v
     ...:

In [320]: gen = exemplo5()

In [321]: gen.gi_frame.f_locals["v"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-321-645eee9080b0> in <module>
----> 1 gen.gi_frame.f_locals["v"]

KeyError: 'v'

In [322]: next(gen)
Out[322]: 10

In [323]: gen.gi_frame.f_locals["v"]
Out[323]: 10

In [324]: next(gen)
Out[324]: 20

In [325]: gen.gi_frame.f_locals["v"]
Out[325]: 20

Emulando um generator com uma classe:
Nada impede que qualquer classe em Python se comporte exatamente como um generator. Nesse caso, as variáveis internas devem ser guardadas, entre uma iteração e outra, como um atributo da instância - enquanto que o Python salva as variáveis locais guardando o Frame de execução.
Para fazer isso, basta escrever uma classe que tenha o método especial __next__ de forma explícita, e o método __iter__ que será executado antes da primeira chamada ao __next__ pelo for (a classe pode inclusive ser separada em 2 estágios - o objeto retornado por __iter__ pode ser de outra classe ou outra instância, e implementar apenas o __next__). Note que os valores que um generator retorna usando yield devem ser retornados com um return comum desta função.
Então o código Python para gerar os quadrados dos números de 0 até n em Python pode ser escrito como uma "generator function" assim:
def squares(n):
    for i in range(n):
        yield i ** 2

ou como uma classe assim:
class Squares:
    def __init__(self, n):
        self.n = n
        self.i = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.i >= self.n:
            raise StopIteration()
        result = self.i ** 2
        self.i += 1
        return result

Usando essa classe no modo interativo:
In [331]: for s in Squares(4):
 ...:     print(s)
 ...:
0
1
4
9

Essas classes não são chamadas de "generators" - esse nome é usado apenas para os objetos criados quando se chama uma função que contenha um yield (as tais "generator functions"). Esse tipo de classe é chamado pelo nome mais genérico de iterável - qualquer objeto que possa produzir um iterador - um iterador, por sua vez, é o nome mais genérico para qualquer objeto que tenha o método __next__.
Outros métodos dos generators e "informações avançadas":
Além do método __next__, os generators também tem os métodos .send e .throw - esses métodos nunca são chamados automaticamente pelo for. Em vez disso, podem ser usados quando se usa um generator de forma "manual" para enviar valores para um generator que já está em execução, ou para causar um erro de um tipo determinado com o .throw - nesse caso, o argumento do throw é um objeto do tipo exceção - e ela é causada no ponto em que está o yield.
Essas funcionalidades são bem pouco usadas de forma explícita em código "do dia a dia", e foram acrescentadas por que com as mesmas, os generators de Python passam a poder ser usados como "co-rotinas". Isso é diferente de funções normais que sempre são "sub-rotinas". As co-rotinas podem ser chamadas em paralelo de forma colaborativa por um sistema especializado.
Uma outra expressão associada é o yield from - ela faz com que um generator possa "fazer yield" de um outro gerador, interno, sem que o valor nunca seja processado por ele mesmo - isso permite, por exemplo, generators recursivos.
Eu tenho um projeto "de brinquedo" em que uso generator functions como "co-rotinas", sem ser programação assíncrona - ele simula um efeito "chapado" de "Matrix" no terminal. Só funciona em um terminal que tiver os códigos ANSI habilitados, o que permite sequências especiais de impressão para posicionar o cursor e alterar a cor das letras - o que ainda não acontece no Windows. O projeto está aqui e funciona bem em Linux e Mac: https://github.com/jsbueno/terminal_matrix/blob/master/matrix.py (e para ativar os códigos ANSI no terminal do Windows, veja algo aqui: https://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences)
A combinação dos recursos propiciados pelos métodos .send, .throw e pela expressão yield from é o que foi usado para permitir o uso de programação assíncrona no Python: isso é, muitas funções que são executadas numa única thread, mas de forma paralela, passando a execução do programa para uma outra "co-rotina" toda vez que uma chamada tiver que acessar um recurso externo do sistema operacional que vai levar tempo para ser completada (uma requisição de rede, ler dados de um arquivo, uma pausa do tipo time.sleep, etc...).
A programação assíncrona, sua sintaxe e seu uso são um tópicos que pode dar nó na cabeça mesmo de programadores avançados - obviamente não cabe descrever tudo nesta resposta - mas vale a pena mencionar que até a versão 3.4 do Python, quando foi introduzida o módulo asyncio na linguagem, a forma de se fazer programação assíncrona em Python era com o uso de generators e  yield from, e a execução, pausa e continuação das co-rotinas era (e ainda é), controlada pelo loop de eventos do asyncio que usa os métodos __next__, send e throw.  A partir do Python 3.5 foi introduzida uma sintaxe separada para as funções assíncronas - o async def, await, e outras como async for, etc... - mas os mecanismos internos que o Python usa são os mesmíssimos que são usados para os generators.
Resumindo:
Uma função que contenha um yield ou um yield from é uma "generator function". Quando ela é chamada não é executada imediatamente- ela retorna um objeto do tipo "generator". Objetos do tipo "generator" tem um método __next__ que quando chamado executa o código da função original até encontrar um yield - nesse momento a função é "pausada" - sua execução "para onde está" e a execução do programa retorna para o ponto onde o método __next__ foi chamado - diretamente, ou de forma implícita com o comando for. Quando o __next__ for chamado de novo, o generator é "despausado" - e a execução continua no ponto do yield. Se em vez do método .__next__ o método .send do generator for chamado, o valor passado como parâmetro do .send é o valor que o yield assume dentro do código do generator (senão o yield vale None). Há também o método .throw: o parâmetro para o mesmo deve ser uma exceção - o Python faz com que aquela exceção aconteça no ponto em que está o yield
Outras perguntas com mais informações sobre o funcionamento do Yield:
Python geradores assincronos
Python palavra reservada yield
Para que serve o Yield?


text:
Q: Get texcount to ignore numbers Trying to get texcount to not count numbers as words, but setting alphabets=Latin doesn't seem to be solving the problem. Any suggestions?
MWE:
\begin{document}
testing 1 2 3 this should be five
\end{document}

texcount outputs:
  ➜ texcount  FORWORDCOUNT.tex
  File: FORWORDCOUNT.tex
  Encoding: ascii
  Words in text: 8
  Words in headers: 0
  Words outside text (captions, etc.): 0
  Number of headers: 0
  Number of floats/tables/figures: 0
  Number of math inlines: 0
  Number of math displayed: 0

  ➜ texcount -alphabets=Latin FORWORDCOUNT.tex
  File: FORWORDCOUNT.tex
  Encoding: ascii
  Words in text: 8
  Words in headers: 0
  Words outside text (captions, etc.): 0
  Number of headers: 0
  Number of floats/tables/figures: 0
  Number of math inlines: 0
  Number of math displayed: 0

A: Ugh, figured it out. Needed to set encoding to unicode. This works:
  ➜   texcount -alphabets=Latin FORWORDCOUNT.tex -unicode
  File: FORWORDCOUNT.tex
  Words in text: 5
  Words in headers: 0
  Words outside text (captions, etc.): 0
  Number of headers: 0
  Number of floats/tables/figures: 0
  Number of math inlines: 0
  Number of math displayed: 0

A: Updated answer:
Starting with version 3.2, it is possible to distinguish between words and numbers.
There is a new TeXcount instruction, %TC:wordtype {original-rule} {wordtype} {new-rule}, which allows the counting rule to be modified depending on word type: number, mixed (letters and numbers), or nonum (word without any digits).
Add the rule
%TC:wordtype text number ignore

and words in text be ignored. To do the same for "header words" and "other words", also add the following:
%TC:wordtype otherword number ignore
%TC:wordtype headerword number ignore

The text rule is just and alias for the word rule: the other rules also have aliases like oword and hword.
Beware that this feature is somewhat experimental and may change somewhat in future versions.

I'm moving from the comments to an answer, although it's not yet an answer to what is going on.
As mentioned in the comments, the option -alphabets=Latin should have worked without the -unicode option. When I test this on Windows 10, it works as it should.
The only effect of the -unicode option is to ensure the file gets decoded as UTF8, instead of as ASCII which would be the default since the input is pure ASCII. This could influence how the string is represented internally by Perl, but unless you're having an old Perl version, the internal representation should be UTF8.
Could you check which Perl version you run? I'd think perl --version should return that you're running some Perl 5 version.
I did some tests with small scripts like this:
use Encode;
use Devel::Peek;
my $enc=find_encoding('ascii');
my $x=$enc->decode('test123');
Dump($x);
$x=~s/(\p{Latin})/[$1]/g;
print $x;

However, no matter what I did, I couldn't get it to output anything other than [t][e][s][t]123 indicating that it had correctly identified the Latin letters.
I even tried my $x=$enc->encode('test123'); which forces a byte representation of $x (not with the UTF8 flag set), but it still gave the same result. I thought the Unicode character classes, eg Latin, might not work if the string is not in UTF8 representation, but that didn't seem to be a problem; maybe it would be on older/other Perl version.
I've been running TeXcount 3.1 on Windows 10 using Perl 5 (v5.24.0), but checked TeXcount 3.0 as well to make sure there were no relevant changes.


text:
Q: Reddit Praw Api usage to search submissions
Basic Code:

import praw
r = praw.Reddit(user_agent='Getting the data!!')
r.login("username","password",disable_warning=True)
results=r.search('whatever', subreddit=None, sort=None, syntax=None, period=None)
for x in results:
    print x

I wish to write a code to get all submissions and their comments related. The submissions should be constrained by a search query and time period.

The problems I face is that:

a. I can't understand how to specify the period in the above, the documentation tend to poor
b. I don't know if the result is constrained to a limit. The above code yields:
923 :: Reddit, type with whatever is on your mind no matter how insignificant...
5598 :: Google maps should have a "on the way" feature to find the most conve...
3961 :: LPT: If you're overheating for whatever reason, run your wrists under...
1556 :: As a lad, whenever my mother wanted me to do something and I was play...
5085 :: "THE ENTIRE STATE IS OFFLINE GET IN THERE NOW FIX IT DO WHATEVER IT T...
1259 :: Heyy, I do the webcomic "Subnormality," as well as artwork for Cracke...
604 :: IAMA Professional YouTuber.  Whatever that means... AMA is you'd like
1156 :: [Spoiler] Whatever happened to G2 vs Strix it's an absolute joke
1217 :: Yesterday I ate whatever I wanted and learned something
1291 :: LPT: Set Your Plugins (Flash, etc.) to be activated only with your cl...
1544 :: Whatever you do, don't step on a duck.
1301 :: A diner in Vegas called "Roulette Burger" where each booth has a roul...
649 :: Been trying to establish a very simply basic wardrobe. Not too preppy ...
1141 :: Mods no longer give a shit, post whatever : New Wow expansion doesn't...
549 :: Whatever happened to chatrooms?
212 :: IAmA graphic designer who will spend 5 mins on whatever you want.
673 :: AMA. Hi there, I'm David Ury, I played Spooge in season 2. Please ask ...
0 :: "Whatever they're going to blame on Osama Bin Laden... don't you even be...
3 :: Dinner time! 1/4/15 or 4/1/15 (whatever works)
536 :: Friendly reminder: If you've been given gold, it's perfectly within yo...
378 :: KP, Keratosis Pillaris, "Chicken skin" - whatever you call it, please ...
637 :: [WP]What if we lived in a world where whatever you did to other people...
1053 :: Instead of a gym, have a place where people can go build wood pallets...
69 :: Pick whatever you want Giveaway!
408 :: Just a reminder to newbies. you don't have to buy a whole bitcoin for ...

I highly doubt there must be many more than this. If yes, how can I get them. If the requests are constrained to a time-window. Is there some workaround to sleep and then get more?
c. I don't know if it is constraints like twitter over not accessing historcial data. Though the period argument states opposite. Still not certain.
d.It returns a generator. How can I access the full submission text and related comments' text as well.
Sorry if it seems a bit indirect, but the dearth of examples online and lack of proper documentation has led to face these issues.

A: A: It's looking for something like '3 months ago'. (You can see some information from API Documentation. it has to be one of (hour, day, week, month, year, all).
B: It is constrained to a limit, it will return about 1000 results max. There might be ways around that, but I'm not sure of what they are, or how easy they are.
C: Kind of the answer to B, I guess.
D: You're looking for the properties of the submission, which you access by attributes (e.g. object.attribute). You can see a full list of attributes for submissions on this page.
So if you wanted to access the self text that goes with a link, you'd have to do something like:
for x in results:
    print x.selftext

If you want to get the comments, though, those are not part of the object. You'd need to get the submission ID and then query the submission itself to get the comments.

A: The default limit is 25 unless another number is specified in the search parameters.
So if you want more results, for example 100 results:
results=r.search('whatever', subreddit=None, sort=None, syntax=None, period=None, **limit=100**)

Commenting on old questions:
Because it may help others who look for this in the future.


text:
Q: Error when trying to use Wine: zsh: bad CPU type in executable: wine So I am getting this error when I try to run the command wine on my command prompt. I think it's because I am on BigSur and need a 64-bit download but I can't find a 64-bit download.
So could someone please help me with this.


text:
Q: Finding the number of distinct sub-strings in a binary string. Whilst solving a question, I have come across a problem regarding the maximal number of possible distinct $k$-length binary sub-strings in an $n$-length binary string.
My thought process was that if you take some $n$-length binary string, then the number of possible sub-strings could be found as follows:
$$\sum_{k=1}^{n}{n-k+1}=n^{2}-\frac{n(n+1)}{2}+n=\frac{n^{2}+n}{2}$$
But this doesn't take into account the maximum possible number of distinct sub-strings, which will be $2^{k}$, when we're looking for sub-strings of length $k$.
Does anyone have any suggestions as to how I could find the maximal number of distinct sub-strings (of length $k\le n$) contained within some binary string of length $n$?
Thanks in advance!

A: I took my own advice: it's "Maximal number of distinct nonempty substrings of any binary string of length n." It seems that there is a question about this sequence that is very simple to state but is still open.

A: "On the maximum number of distinct factors of a binary string" (also here), by Jeffrey Shallit, proves that the answer (the attained maximum number of distinct factors of a length-$n$ binary string) is $$\binom{n-k+1}{2}+2^{k+1}-1,$$ where $k$ is the unique integer such that $$2^k + k - 1\ \le\ n\ \lt\ 2^{k+1}+(k+1)-1.$$ (This counts the empty string as a factor of every string.)

NB: A "closed form" for the answer can be found by noting that $k$ is just $\lfloor x \rfloor$, where $x$ is the real number such that $$2^x + x - 1=n.$$ Now, the substitutions
$$\begin{align}
X &:= \log(2)\ (n-x+1)\\
Y &:= \log(2)\ 2^{n+1}
\end{align}
$$
transform this equation into
$$X\ e^X = Y$$
whose solution is
$$X = W(Y),$$
where $W$ is the (principal branch of) the Lambert $W$ function.
Therefore,
$$\log(2)\ (n-x+1) = W(\log(2)\ 2^{n+1})$$
giving
$$k = \left\lfloor n+1-\frac{W(\log(2)\ 2^{n+1})}{\log(2)}\right\rfloor.$$

NB: Some comments at the OEIS link refer to the above results as "conjectures", in spite of the proof given in the cited paper.


text:
Q: Reshaping a 2D matrix of Time series vectors into a 3D matrix of sequences (frames) - overlapping windows I have a matrix (shape: m by 51) of 51 time series vectors  m samples each. I want to train two autoencoders one using CNN and another using LSTM network. I want to reshape the 2D matrix into a 3D matrix such that it contains m_new sequences for each of the 51 variables and each sequence is w long with overlapping of lap samples.
I managed to pull this off but without the overlapping part. Is there an efficient way to do it?
W = 20 #window size
m_new = int(np.floor(m/W))
m_trct = int(m_new*W)
X_raw_trct = X_raw[0:m_trct,:]
X = np.reshape(X_raw_trct,(m_new,W,X_raw_trct.shape[1]))

As demonstrated below, the sequences are generated with overlapping of   lap = w-1.

** UPDATE **
In reference to the answer in Split Python sequence (time series/array) into subsequences with overlap,
 using the function sub-sequences which splits the 1D array into w long  sub-sequences with overlap of w-1 (stride of 1) resulting in a 2D array of shape (m_new, w) . As in code 2
 below, I had to use a loop to work every vector of the 51 variables as a 1D array then appending the results of the 2D arrays to produce my final 3D array of shape (m_new, w, 51). However, the loop takes so long to execute.
**code 2**
def subsequences(ts, window):
## ts is of shape (m,)
    shape = (ts.size - window + 1, window)
    strides = ts.strides * 2
    return np.lib.stride_tricks.as_strided(ts, shape=shape, strides=strides)

# rescaledX_raw.shape is (m,51)
n = rescaledX_raw.shape[1]
# n = 51

a = rescaledX_raw[:,0]
# a.shape is (m,)

Xaa = subsequences(a,W)
X = ones(Xaa.shape)*-1
# X.shape is (m_new, W)

for kk in range(n):
## a is of shape (m,)
    a = rescaledX_raw[:,kk]
    Xaa = subsequences(a,W)
    X = np.dstack((X, Xaa))

X_nn = np.delete(X, 0, axis=2)
# X_nn.shape is (m_new, W, 51)

In addition, I tried to work it out as a full 2D array of shape (m by 51) to the 3D array of shape (m_new,w,51) using the function in code 3
**code 3**
def rolling_window(a, window):
## a is of shape (51,m)
    shape = (a.shape[-1] - window + 1,window,a.shape[0])
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

But the resulted 3D matrix is not the correct one. Kindly refer to the demonstration below. In addition, how can I add the stride as a variable I can change. In scripts above the stride is 1 (meaning the overlap is w-1)

A: I found a helpful post to get this done using TimeseriesGenerator. Custom Data Generator for Keras LSTM with TimeSeriesGenerator
class CustomGenFit(TimeseriesGenerator):
    def __getitem__(self, idx):
        x, y = super().__getitem__(idx)
        return x, x

Xsequences = CustomGenPredict(X, X, length=W, stride = s,sampling_rate=1, batch_size=m)

A: def lstm_data_transform(x_data, y_data, num_steps=10):
    """ Changes data to the format for LSTM training
for sliding window approach """
    # Prepare the list for the transformed data
    X, y = list(), list()
    # Loop of the entire data set
    for i in range(x_data.shape[0]):
        # compute a new (sliding window) index
        end_ix = i + num_steps
        # if index is larger than the size of the dataset, we stop
        if end_ix >= x_data.shape[0]:
            break
        # Get a sequence of data for x
        seq_X = x_data[i:end_ix]
        # Get only the last element of the sequency for y
        #seq_y = y_data[end_ix]#ori end-----fking somw wrong
        seq_y = y_data[i]#first correct wtf
        # Append the list with sequencies
        X.append(seq_X)
        y.append(seq_y)
    # Make final arrays
    x_array = np.array(X)
    y_array = np.array(y)
    return x_array, y_array


text:
Q: VSIX Flavored project custom .target file import issue I have a VSIX package with couple of custom designers over XML. This package has a flavored project system in which I use some custom build tasks to auto generate code at build time.
First challenge I had to face was with importing .targets files in my project template. I cannot give a fully qualified path to the .targets file in the project template because my package version changes and that makes the vsix installer to drop it inside a version-ed location on the target machine. The way I could solve was to add a user environment variable with package root path and then refer this environment variable in the project template to import .targets file. It works as expected with a caveat.
Now the caveat is how I can create this environment variable during the VSIX deployment process. I tried decorating the package class with a custom attribute derived from RegistrationAttribute. I overrode the Register method to run Environment.SetEnvironmentVariable() and it only works when I run the project on my dev box. Apparently, VSIXInstall.exe does not care about running the attribute register during the install.
It will be great if somebody can suggest an approach to solve this issue. I am running out of time and already tried so many things without any success :(

A: [Including my previous reply to this same question asked over email.]
MSBuild targets/tasks distributed via VSIX are not supported in Visual Studio 2010. The recommendation is for you to use MSI (or similar deployment technology) and drop your targets files to a directory of your choosing under %ProgramFiles%\MSBuild. You can then refer to them in your project templates via $(MSBuildExtensionsPath).
VSIX installation is essentially just an "unzip" of your VSIX. That's it. There's no registration or ability to do custom actions whatsoever. As you alluded to, at build time, a tool called CreatePkgDef.exe runs (which is what loads your assembly and calls your RegistrationAttribute) to create the pkgdef file which is included in your VSIX.
I think you'll need to do one of the following:

*

*Abandon VSIX and use MSI for deployment (the recommended approach)

*Include the custom targets in the project template. This is bad because now the targets are scattered amongst projects instead of installed to a single location, but it may be an acceptable solution for you.

*Do some initialization (e.g. setting your environment variable) on 'first launch' of your package/extension within VS. This of course, means that users will have to know this is a necessary post-installation step.

I realize that none of these solutions is ideal. Please know that better MSBuild support with VSIX is our top requested feature, so we've definitely received the feedback.


text:
Q: Elliptic Curve Diffie Hellman public key size I want to use Diffie hellman for generating a secret key between a c# Server and c++ Client. this code generates a public key for the server:
        serverECDH = new ECDiffieHellmanCng(ECCurve.NamedCurves.nistP256);
        serverECDH.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
        serverECDH.HashAlgorithm = CngAlgorithm.Sha256;
        ECDHPublicKey =Convert.ToBase64String(serverECDH.PublicKey.ToByteArray());
        Console.WriteLine(serverECDH.KeySize); //256
        Console.WriteLine(serverECDH.PublicKey.ToByteArray().Length); //72
        Console.WriteLine(ECDHPublicKey);

I wonder why publicKey Byte Array Size is 72 while I expect a 64 byte long array?
besides here is my implementation for generating public key in Client:
if (NULL == (pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL))) HandleErrors(1);
if (1 != EVP_PKEY_paramgen_init(pctx)) HandleErrors(2);
if (1 != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_X9_62_prime256v1)) HandleErrors(3);

if (!EVP_PKEY_paramgen(pctx, &params)) HandleErrors(4);
if (NULL == (kctx = EVP_PKEY_CTX_new(params, NULL))) HandleErrors(5);

if (1 != EVP_PKEY_keygen_init(kctx)) HandleErrors(6);
if (1 != EVP_PKEY_keygen(kctx, &pkey)) HandleErrors(7);

bio = BIO_new(BIO_s_mem());
PEM_write_bio_PUBKEY(bio, pkey);
int publicKeyLen = BIO_pending(bio);
cout << publicKeyLen << endl;
unsigned char* publicKeyChar = (unsigned char*)malloc(publicKeyLen);
BIO_read(bio, publicKeyChar, publicKeyLen);

ECDHPublicKey =  string(reinterpret_cast<char const*>(publicKeyChar),publicKeyLen);
cout << ECDHPublicKey << endl;

in this code, the public key length is 128 byte(Characters?) which is odd again because I specify NID_X9_62_prime256v1 curve. where is my mistake?
besides are NID_X9_62_prime256v1 and nistP256 matching in c++ and c#?
EDIT:
here is a example of  cout << ECDHPublicKey << endl output :

-----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUFD9ZNby6x2bf/VC16/NHSxIXdit
Ips60uLoi0/jKmbmMHRg2xbXVVzV8Uc1DElMlZA817bMFCnVvi1VsM5JYg==
-----END PUBLIC KEY-----

A: In the C++ code that public key is not just DER encoded, it is PEM encoded as well. That adds a header and footer around the base 64 encoded DER structure. PEM is used for text-based interface where binary data may get distorted. It is therefore also sometimes called "ASCII armor" (or "ASCII armour" depending on your dialect).
If you want to take a look at the structures of the C++ / OpenSSL code then simply paste base 64 encoded DER structure into this site or use openssl asn1parse.

The Mickeysoft structure returned by serverECDH.PublicKey.ToByteArray() seems to consist of "ECK1" + 20 00 00 00 followed by the two statically sized encoded coordinates (which could be big or little endian). ECK1 is probably Elliptic Curve Key format 1 - whatever that is - and 20 00 00 00 is probably the key / coordinate size in octets as 32 * 8 = 256. Note that C# officially uses platform endianess, so the 20 00 00 00 is a 32 bit little endian value. Probably you need an external library to encode their keys so that any other runtime can understand them.

As for your tag-on question: yes, the ANS(I) X9.62 prime256r1 curve is identical to NIST P-256 and secp256r1 as (I think) originally defined by Certicom corp. The curve was first defined and then picked up & standardized by various organizations.


text:
Q: Is there a straightforward way to sort with multikey and insert to a slice in Golang? I have function in python which looks like below
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        people = sorted(people, key=lambda x: (-x[0], x[1]))
        ans = []
        for a in people:
            ans.insert(a[1], a)
        return ans

Two things in above function.
1. Sort two dimensional array with multikeys x[0](descending order) and x[1](ascending order)
2. Insert an element in the array through a loop
Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
I couldn't find an easy or straight forward way of implementing this logic in Golang. Can someone help me out to translate this code in Go way?

A: package main

import (
    "container/list"
    "fmt"
    "sort"
)

type pair struct {
    x int
    y int
}

// print: prints the list
func print(l *list.List) {
    for e := l.Front(); e != nil; e = e.Next() {
        fmt.Printf("%v\n", e.Value)
    }
}

// do: does all the important operations
func do(queue []pair) *list.List {
    sort.Slice(queue, func(i, j int) bool {
        // If values are equal for first field then sort on
        // the basis of second field (ascending order)
        if queue[i].x == queue[j].x {
            return queue[i].y < queue[j].y
        }
        // Else sort on the basis of first field (decreasing order)
        return queue[i].x > queue[j].x
    })
    // Creates a list
    ans := list.New()
    for i := range queue {
        elem, ix, ixMark := &list.Element{}, 0, queue[i].y
        // Loops around to find the pos to fit in based on second field of element
        for elem = ans.Front(); elem != nil; elem = elem.Next() {
            if ix == ixMark {
                break
            }
            ix++
        }
        if elem == nil {
            // Add if list is empty
            ans.PushBack(queue[i])
        } else {
            // Add before the marked element
            ans.InsertBefore(queue[i], elem)
        }
    }
    return ans
}

func main() {
    elems := []pair{
        {7, 0},
        {4, 4},
        {7, 1},
        {5, 0},
        {6, 1},
        {5, 2},
    }
    queue := do(elems)
    print(queue)
    // Output:
    // {5 0}
    // {7 0}
    // {5 2}
    // {6 1}
    // {4 4}
    // {7 1}
}

The code is commented so that you can understand. So basically a combination of slice and list can help you achieve the same. No doubt there might be simpler, shorter ways to do the same in Go.
My implementation is quite a simple one.


text:
Q: pass event to a rendered component in vue I'm trying to create a rendered component that will do something when I click on it:
// A normal Vue component using a render function
Vue.component('greeting', {
    methods: {
        sayHello(){
            alert('hello')
        }

    },
    render(createElement){
        var self = this
        return createElement(
            'button',
            {
                '@click': self.sayHello
            },
            'if you click here I will say hello')
    }
})

new Vue({
    el: '#app'
})

I'm expecting an alert when I click on the button.  As far as I can tell, this will render something like
<button @click="sayHello" />

where the method sayHello is defined in the Vue instance.
Why doesn't this work?
https://codepen.io/dvdgdnjsph/pen/NWNwYOQ

A: Looks like the passed events need to be specified as 'on', like so:
{
  on: {
   click: somefunction
  }

}

https://codepen.io/dvdgdnjsph/pen/NWNwYOQ
https://v3-migration.vuejs.org/breaking-changes/render-function-api.html#_3-x-syntax-2

A: I have created a working copy of your example in this fiddle. I have modified the way we write click event. Refer below code snippet.
Working Button Click via Render Function

Vue.component('DraggableList', {
  methods: {
    sayHello() {
      alert('hello')
    }
  },
  render: function(createElement) {
    var self = this;
    return createElement(
      'button', // tag name
      {
        on: {
          click: this.sayHello
        }
      }, 'if you click here I will say hello'
    )
  }
})

new Vue({
  el: '#app'
})
.grid{
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    padding: 2em;
    grid-gap: 1em;
}
h1{
    margin: 0;
    padding: 0;
}
.grid input{
    grid-column-start: 1;
    grid-column-end: 3;
    text-align: center;
    font-size: 1.5em;
}
.polite{
    font-family: cursive;
    color: gray;
}
.rude{
    font-family: serif;
    font-weight: bold;
    color: red;
}

    <draggable-list></draggable-list>


text:
Q: How to check if a user is edting a table record before allowing another user to edit, not wait for post? I am developing a web site of artists profiles and a desktop software to manage its database content.
There are many operators that will receive in their in-boxes the same amount of pending records to be revised for approval and publish.
The problem is when two or more operators try to edit the same record. It the database server (remote mysql) will raise an lock error or simply will maintain only the data of the operator that saves it for the last.
What would be the best approach (simpler and more efficient way) to check if any one is already editing the record before grant access to this record to another user, or if the owner of the record is, himself, updating his record again in the website?
The software is still at the lab. But when I delivery it to client I know it will be a problem.
I could create a table to flag each record as "in edit" or "idle", so I don't need to alter the structure of the tables (because people are already using them on the site). But I need to be sure that there is a more elegant/faster way to do it.

A: There are many system-level approaches you could use to handle the problem.  Locking a record for exclusive editing is only one, traditionally chosen by older systems.
A more modern methodology is to allow both edits to proceed without locking—termed optimistic concurrency control.  If there is an overlapping edit, see if it can be resolved automatically—many simultaneous edits are, in fact, not contentious, especially if they edit unrelated parts of the record.
In the case there is a conflict, it is important that the first edit not be simply lost: the first editor was already signaled of a successful transaction.  The onus is to indicate to the second editor that their edit conflicts with an earlier one.  Usually the best course is to show him his proposed change as well as the other recent change and let them select what to do:  abandon their change, override the previous change (maybe with an indication to the first editor), or manually merge the changes.
This may not be a big deal.  The description of your system suggests users would not be closely synchronized to an edit-worthy event.  The random time at which each edit occurs suggests an edit conflicts would be rare.  In such a case, maybe your idle/editing indication is more than sufficient.


text:
Q: Is there such a thing as an unvoiced vowel? I can't think of any and google has not been helpful.

A: Yes, it's technically possible, but I think you'd only consider it as an allophone, otherwise, the better transcription might be /h/.  Wikipedia lists one example in English as potato, where the first o is not vocalized, but otherwise the mouth is in the same position and there is air flowing. (IPA transcriptions use a ring for devoicing).
Japanese seems to the more common language for it with their u vowel, but thinking about, European Portuguese might well do it where traditionally transcriptions will normally list them as elided.
For an academic citation, here's an article on devoiced vowels in English and German: "Vowel devoicing/deletion in English
and German", by Jonathan E. J. Rodgers.

A: To add to John Lawler's answer (since I can't comment): Shuar (a Jivaroan, or Chicham, language of Ecuador) has (or did have a few decades ago) voiceless vowels in certain positions.  I'll quote from Glen Turner's 1957 IU dissertation: "In a contour [= phrase] final open syllable, a single, unstressed, oral vowel following a consonant cluster of nasal plus homorganic stop or affricate or following any single consonant other than /w/ or /y/ may be unvoiced if it is also preceded by 2 or more vowels in the same word...  When followed by a morpheme or another word (i.e. contour medial), voiceless vowels may be come voiced, lost, or remain present but unvoiced..."  This word-final position was post-consonantal, so it would be odd to consider it to be an /h/.
FWIW, in English I usually pronounce 'Mississippi' with a voiceless vowel in the second syllable.  Again, given the position, it would be odd to consider this to be an /h/.  Otoh, it is more or less indistinguishable from lengthening the 's' (that is, merging the first 'ss' with the second).

A: Voiceless vowels are quite possible, and occur in one way or another in many languages.
After all, all vowels and all consonants that are whispered are ipso facto voiceless.
Whisper [a] and you have pronounced a voiceless vowel.
However, the overwhelming majority of vowel sounds in speech are voiced, since vowel formants are modifications of a voiced airstream from the larynx. Exceptions to this rule fall into a number of categories.

*

*in some languages, like Japanese, some vowels become voiceless in some environments
(in Japanese, high vowels /i/ and /u/ are devoiced between voiceless consonants)

*in some languages, like English, voiceless vowels are allophones of a consonant phoneme
(English /h/ is a voiceless vocal onset, a voiceless version of whatever vowel it precedes)

*in some languages (Acehnese, for instance) some vowel phonemes are contrastively voiceless
(this is quite rare, however -- most voiceless vowels are conditioned rather than contrastive.)

A: I couldn't make sense of any voiceless vowel because vowels give the consonants the sounds they represent, so if vowels are said to be voiceless, it can only be whispers or the glottal sound 'h'.


text:
Q: Kali Linux Grub repair using live CD option does not work I tried to install Kali Linux but it failed due to internet connection issue. Then I tried to repair the grub file using Kali Linux Live CD option. I executed all the commands. However, I cannot see the Kali Linux in the OS list.
root@kali:~# sudo mount /dev/sda8 /mnt
root@kali:~# mount --bind /dev /mnt/dev
root@kali:~# mount --bind /proc /mnt/proc
root@kali:~# mount --bind /sys /mnt/sys
root@kali:~# mount /dev/sda+ /mnt/boot/efi
ntfs-3g: Failed to access volume '/dev/sda+': No such file or directory

ntfs-3g 2016.2.22AR.2 integrated FUSE 28 - Third Generation NTFS Driver
        Configuration type 7, XATTRS are on, POSIX ACLS are on

Copyright (C) 2005-2007 Yura Pakhuchiy
Copyright (C) 2006-2009 Szabolcs Szakacsits
Copyright (C) 2007-2016 Jean-Pierre Andre
Copyright (C) 2009 Erik Larsson

Usage:    ntfs-3g [-o option[,...]] <device|image_file> <mount_point>

Options:  ro (read-only mount), windows_names, uid=, gid=,
          umask=, fmask=, dmask=, streams_interface=.
          Please see the details in the manual (type: man ntfs-3g).

Example: ntfs-3g /dev/sda1 /mnt/windows

News, support and information:  http://tuxera.com
root@kali:~# mount /dev/sda8 /mnt/boot/efi
root@kali:~# mount -o remount,rw /dev/sda8 /mnt/boot/efi
root@kali:~# mkdir /mnt/hostrun
root@kali:~# mount --bind /run /mnt/hostrun
root@kali:~# chroot /mnt
root@kali:/# mkdir /run/lvm
root@kali:/# mount --bind /hostrun/lvm /run/lvm
root@kali:/# grub-install /dev/sda
Installing for i386-pc platform.
grub-install: warning: this GPT partition label contains no BIOS Boot Partition; embedding won't be possible.
grub-install: warning: Embedding is not possible.  GRUB can only be installed in this setup by using blocklists.  However, blocklists are UNRELIABLE and their use is discouraged..
grub-install: error: will not proceed with blocklists.
root@kali:/# grub-install --force /dev/sda
Installing for i386-pc platform.
grub-install: warning: this GPT partition label contains no BIOS Boot Partition; embedding won't be possible.
grub-install: warning: Embedding is not possible.  GRUB can only be installed in this setup by using blocklists.  However, blocklists are UNRELIABLE and their use is discouraged..
Installation finished. No error reported.
root@kali:/# update-grub
Generating grub configuration file ...
Warning: Setting GRUB_TIMEOUT to a non-zero value when GRUB_HIDDEN_TIMEOUT is set is no longer supported.
Found background image: /usr/share/images/desktop-base/desktop-grub.png
Found linux image: /boot/vmlinuz-4.13.0-kali1-amd64
Found initrd image: /boot/initrd.img-4.13.0-kali1-amd64
Found memtest86+ image: /boot/memtest86+.elf
Found memtest86+ image: /boot/memtest86+.bin
Found Windows 8 on /dev/sda4
Found Windows Recovery Environment on /dev/sda7
done
root@kali:/# exit
exit
root@kali:~# unmount /mnt/dev/pts
bash: unmount: command not found
root@kali:~# umount /mnt/dev/pts
umount: /mnt/dev/pts: not mounted.
root@kali:~# umount /mnt/dev
root@kali:~# umount /mnt/proc
root@kali:~# umount /mnt/sys
root@kali:~# umount /mnt
umount: /mnt: target is busy.
root@kali:~# umount -f /mnt
umount: /mnt: target is busy.
root@kali:~# umount -l /mnt
root@kali:~# umount -f /mnt
umount: /mnt: not mounted.
root@kali:~# ^C
root@kali:~#

Is there anything I'm doing wrong?

A: If Installation failed, Why searching for it... Often failed installation results in rollback of changes...
If however the installation was successful but not appearing in grub then :

USE boot-repair to repair grub

sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update
sudo apt-get install -y boot-repair && boot-repair


text:
Q: Python SyntaxError when creating a list using a generator I'm relatively new to Python and I'm just trying to get to grips with some of the common features.
I tried to write a simple script to get all the whole number square roots of numbers between 0 and 100. This is what I came up with:
mylist = [n for n*n in xrange(0,101)]

I got a SyntaxError when I ran it, and as far as I can tell, it's not liking the "n for n*n in" bit. Am I right in deducing that this is just not possible? Is there a way to achieve this, or do I need a sqrt() function?
Thanks

A: You need math.sqrt for something like this.
mylist = [math.sqrt(n) for n in xrange(0,101)]

Python isn't smart enough to see n*n = something and deduce that n = math.sqrt(something).  It's a good thing too -- Who's to say that it shouldn't be n = -math.sqrt(something)?
Alternatively, you could try the builtin map:
mylist = map(math.sqrt,xrange(0,101))

Although most prefer the list comprehensions these days.
Sometimes, these things can be re-written a little nicer into generator expressions:
def square_less_than(n):
    i = 0
    while True:
       if i*i < n:
          yield i
          i += 1
       else:
          break

print list(square_less_than(10))

Or, the equivalent 1-liner using the excellent itertools module in the standard library:
import itertools
print list(itertools.takewhile(lambda i:i*i < 10,itertools.count()))

A: The syntax of your list comprehension is incorrect. You can write something like:
import math
mylist = [math.sqrt(n) for n in xrange(0, 101)]

A: You can also  try :
mylist = [n*n for n in xrange(0,101)]


text:
Q: Building up a compiler with JFlex/CUP and with some questions I am currently developing an easy compiler for the language BASIC and I have found some problems which I would like to ask you.
The first one is easy, where I should define my tokens? I mean, in the Lexer.java file I send the tokens to the parser using the expression:
return symbol(sym.STATIC);
STATIC is a token for me, but I don't know where to define it.
Second, where I should define the main class in which I create the instances of Lexer and Parser? In the Parser class or in another?
Thanks in advanced.

A: First: a file with the class defining those symbols will be generated automatically for you
Second: you create your own class with a main where you create an object from the generated Lexer, to which you pass the InputStream, and one from the Parser, to which you pass the Lexer.
After you create those two objects you call the method parse() belonging to Parser.

A: First: You should not be editing the .java file directly. You should be editing the Scanner.jflex file. That should contain the
return symbol(sym.STATIC);.
When you use something in the .jflex file, you also need to declare it simultaneously in the Parser.cup file.
Below the block that says: parser code {::},
you need to declare the STATIC symbol in the following way:
terminal STATIC;
Second: You do not need to create the main file yourself. When using JFLEX and CUP together, you just need to compile the files using the Apache Ant build tool or NetBeans. The main file will automatically be created for you.


text:
Q: How to set up Windows server 2008 to receive email? First off apologies, I'm from a medical background not a networking one, but I've got roped into setting up a windows 2008 server.
So far web server running, fixed IP address assigned (within a large private network of the National Health Service in the UK if that makes any difference) and the network team have assigned a DNS entry for me which works, so the server can be addressed as nww.myserver.nhs.uk
I've only got ports open on the router for 80 and 443 (http and https) at the moment, so presume I need a different port to enable email services.
My need is to be able to accept an email to the domain name like admin@myserver.nhs.uk in order to pick up a confirmation mail from an SSL issuer (Comodo) I guess to confirm that I control the domain.
After that I don't actually need mail services on the server.
I see lots of stuff about setting up SMTP services but thought that was about mail out and re-routing, but how do you get the server to "listen" for mail to the domain (assuming I open port xyz or whatever it is) ?

A: Sounds like you need to set up SMTP on the server. I had some issues getting everything working on 2008 so I changed direction and went with hMailServer as my server of choice. It's failry flexable and is free. It's also dead simple to get in and configure. Not to mention lots of documentation to help guide you through the porcess.
Once you have it installed you would need to open, and forward, the needed ports from your router to the mail server. Normally they are 25 (SMTP) and 110 (POP3) unless your using SSL then you would need to congifure the ports accordingly. You can also configure it to forward your out bound mail to a relay if desired/needed based on your ISP and their restrictions, if any.
You of course also need to set up the proper MX record(s) in DNS and have it pointing to your domain/IP.

A: ask your friendly sysadmin at admin@nhs.uk to accept the email for you (this should be allowed by the issuer), or get an MX record in DNS for myserver.nhs.uk to point to another mail server that is setup & configure it to accept mail for your domain.
If you do want to go down the path of setting up email on your server, then you'll need to open up port 25 at the router, create an MX record to point to your server. You'll need to get a 3rd party program to setup windows server 2008 for email & as you only need it to setup an SSL certificate, Exchange would be overkill! This serverfault question has answers on recommended mail server software.


text:
Q: REST-Client: 302 Found when trying to pass XML-String I want to implement a REST-Client which handles form input data and sends it to an REST Backend.
$strXml = file_get_contents($_FILES['xmlfile']['tmp_name']);
$service_url = 'api/index.php/pojects';
$curl = curl_init($service_url);
$curl_post_data = array(
    "title" => $_POST['title'],
    "client" => $_POST['client'],
    "comment" => $_POST['comment'],
    "project_number" => $_POST['project_number'],
    "xml" => $strXml,
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
curl_close($curl);
var_dump($curl_response);
var_dump($strXml);

But it seems, that there's something wrong, maybe with the webserver config.
It says:
    302 Found
The document has moved here.

But the var_dump of the xml string is correct. What's my error in reasoning?

A: You are facing a redirect.. Add this cURL param
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);


text:
Q: Creating a custom Stackpanel with Transparent "Windows" Good evening.  I have been researching my issue for about two days now, and have tried at least a dozen variations of the problem.  Every single last one of them has been a complete total failure, so I won't bother posting any code here.
What I need is a StackPanel for a Border-less Window.  The StackPanel needs to have an opaque background, and the children need to have a transparent background.  I need the transparency to carry ALL the way through the child element, StackPanel, and underlying main window.
Does anyone have any idea as to how to go about this, and where I should start? I am an intermediate level programmer, and have hit a solid wall here. I have tried to inherit from Panel Class, over-riding the usual suspects; MeasureOverride, ArangeOveride, OnRender, etc..
One of the thoughts I also had, was using some form or another of CombinedGeometry between the parent, and all child nodes.
Thanks in advance!!

A: What you are probably missing is Window.AllowsTransparency="True". Sad to say that you have to build your own window title and border because WindowStyle property must be set to None.
I've created a sample for you:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        AllowsTransparency="True"
        Background="Transparent"
        WindowStyle="None"
        WindowStartupLocation="CenterScreen">
    <Border BorderBrush="Black" BorderThickness="1">
        <DockPanel>
            <Menu DockPanel.Dock="Top">
                <MenuItem Header="Application">
                    <MenuItem Header="_Close" Click="MenuItem_Click"/>
                </MenuItem>
            </Menu>
            <ToolBar DockPanel.Dock="Bottom">
                <Button>sample button</Button>
            </ToolBar>
            <StackPanel>
                ... your whiteboard ...
            </StackPanel>
        </DockPanel>
    </Border>
</Window>

.
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    this.Close();
}

A: Ok, so after many, MANY, hours of brute force "hacking," I have managed to figure out a means to accomplish what I need.
<Border Name="OuterBorder" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderBrush="Orange" BorderThickness="1.5">
    <Border Name="FillerStrip" BorderBrush="Black" BorderThickness="20">
        <Border Name="InnerBorder" BorderBrush="Orange" BorderThickness="1.5">
            <StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Transparent">
                <local:GlassBoardControl BorderBrush="Orange"            BorderThickness="2" AxisBrush="LawnGreen" AxisThickness="15" x:Name="screen" />

            </StackPanel>
        </Border>
    </Border>
</Border>

Now my only question is how on earth do I go about creating a custom panel with this as it's border?  Any ideas as to where I should start would be much appreciated.


text:
Q: Margins of error cut-off at variable value of zero, if variable values cannot be negative? Does it make statistical sense to just "cut off" a confidence interval at a variable value of 0 where variable values can by definition not be < 0?
Suppose you conduct a survey and draw a sample of repondents with the goal of presenting them with a statement and measuring their the extent to which they agree with said statement. The mean agreement, which is, ceteris paribus, your best estimate of the population's average agreement, can range anywhere between 0% and 100%. For the sake of the example, let's assume the statement is quite controversial and hence agreement is on the lower end of the scale. Let's further assume that the sample is rather small so your margins of error are considerably large. More specifically, the margins of error are larger than the mean of your agreement variable.
If you were to plot this agreement variable as an errorbar (mean +/- error), would it make statistical sense to take the scissors to the lower end of the errorbar and "chop it off"? Or would that be fundamentally wrong, given that the margins of error have been calculated under the (wrong) assumption, that variable values can be <0?

A: That would be sound. A proportion cannot be negative, so including negative values in a confidence interval does not give meaning, it just looks silly.
On the other hand, you could avoid the problem by using methods designed for proportions.


text:
Q: Why doesn't Spring tool suite's, tomcat server restart's mac keyboard shortcut work unless you click on server under "Servers" tab? I'm using tomcat server in Spring tool suite.
I am trying to learn and remember keyboard shortcuts to be efficient.
Whenever I do "Option" + "Command" + "R" it doesn't restart the server.
But if I click the Tomcat server under "Servers" tab, and then if I use keyboard shortcut, it works. But that doesn't make efficient. Its double the work.
Why is it so?
Is this a defect or missing something in settings?

A: By default, "Option" + "Command" + "R" is set to run under "servers view". You can use "Option + Shift + X, R" instead to run on the server.
EDIT:

Key bindings can be changed as per your preference under
Preferences --> General --> Keys


text:
Q: Jest: Typescript TS6059 rootDir warning on FeathersJS tests I have a Typescript setup of FeathersJS with tests based on the feathers generated services.
Randomly, but especially after a fresh setup, I have this warning occurrence:
ts-jest[ts-compiler] (WARN) error TS6059: File '/api/test/services/users.test.ts' is not under 'rootDir' '/api/src'. 'rootDir' is expected to contain all source files.
  The file is in the program because:
    Root file specified for compilation

Note: This warning appears multiple times for many test of many services.
How to resolve this warning properly?
I have not so much more information to give right now. Don't hesitate to ask for specific config or example, I'll update the thread accordingly.


text:
Q: Trying to get a user input to make a 2-D array multiplication table int main (void)
{
    int range, i, j;

    printf("Input size of multiplication table: ");
    scanf("%i", &range);

    int output[range][range];

    for (i = 0; i<=range; ++i)
    {
        for (j=0; j<=range; ++j)
        {
            output[i][j] = i * j;
            if(j!=range && output[i][j] != 0)
            {
                printf("%3i ", output[i][j]);
            }
            else if (j==range)
            {
                printf("%3i", output[i][j]);
            }
            else if (output[i][j] == 0)
            {
                printf("%3i "), i+2;
            }
            else
            {
                printf("%3i", j + i - range);
            }
        }
        printf("\n");
    }
    return 0;
}

I am having it output:
0   1   2   3   4   0
5   1   2   3   4   5
10   2   4   6   8  10
15   3   6   9  12  15
20   4   8  12  16  20
25   5  10  15  20  25

and I need the 0 on the end to be a five and the first column to be 0,1,2,3,4,5 instead of 0,5,10,15,20,25.
If anyone could help I would appreciate it.

A: You have two primary problems, (1) you fail to validate your user input, and (2) your loop bounds are incorrect, e.g.
Any time you take user input, you must validate that you actually received what you expected and that any conversion required, was completed successfully. Failure to validate will lead to Undefined Behavior it invalid (or no) input is provide. (e.g. What if the user enters foo instead of 10?) When using scanf, you must validate the return which provides the count of the number of conversions that successfully took place, e.g.
    printf ("Input size of multiplication table: ");
    if (scanf("%i", &range) != 1) { /* VALIDATE ALL USER INPUT */
        fprintf (stderr, "error: invalid input.\n");
        return 1;
    }

That is bare minimum. You can also check if the return is EOF to indicate the user canceled input with a [Ctrl+D] (or [Ctrl+Z] on windoze -- must be explicitly enabled on Win10).
Next, your loop bound are for (i = 0; i < range; i++) not i <= range, that invokes Undefined Behavior by attempting to access memory outside your array bounds. Simply fix the loop condition, e.g.
    for (i = 0; i< range; i++) {    /* fill multiplication table */
        for (j = 0; j< range; j++) {
            output[i][j] = (i + 1) * (j + 1);   /* i+1 * j+1 */
        }
    }

Putting it altogether, you could do something similar to:
#include <stdio.h>

int main (void) {

    int range, i, j;

    printf ("Input size of multiplication table: ");
    if (scanf("%i", &range) != 1) { /* VALIDATE ALL USER INPUT */
        fprintf (stderr, "error: invalid input.\n");
        return 1;
    }

    int output[range][range];       /* variable length array */

    for (i = 0; i< range; i++) {    /* fill multiplication table */
        for (j = 0; j< range; j++) {
            output[i][j] = (i + 1) * (j + 1);   /* i+1 * j+1 */
        }
    }

    for (i = 0; i< range; i++) {    /* output table */
        for (j = 0; j< range; j++)
            printf (" %3d", output[i][j]);
        putchar ('\n');
    }

    return 0;
}

note: the trivial parts of the table is omitted (e.g. 0 * anything), and duplicated rows of 1 * anything are also not shown. If you need to additional rows, you can add them back.
Example Use/Output
$ ./bin/multable
Input size of multiplication table: 10
   1   2   3   4   5   6   7   8   9  10
   2   4   6   8  10  12  14  16  18  20
   3   6   9  12  15  18  21  24  27  30
   4   8  12  16  20  24  28  32  36  40
   5  10  15  20  25  30  35  40  45  50
   6  12  18  24  30  36  42  48  54  60
   7  14  21  28  35  42  49  56  63  70
   8  16  24  32  40  48  56  64  72  80
   9  18  27  36  45  54  63  72  81  90
  10  20  30  40  50  60  70  80  90 100

Look things over and let me know if you have further questions.

To Show the 1X Rows
You simply update your print routine as follows:
    for (i = 0; i< range; i++) {    /* output table */
        if (!i) {
            printf ("    ");
            for (j = 0; j< range; j++)
                printf (" %3d", output[i][j]);
            putchar ('\n');
        }
        printf (" %3d", i + 1);
        for (j = 0; j< range; j++)
            printf (" %3d", output[i][j]);
        putchar ('\n');
    }

Example Use/Output
$ ./bin/multable1
Input size of multiplication table: 10
       1   2   3   4   5   6   7   8   9  10
   1   1   2   3   4   5   6   7   8   9  10
   2   2   4   6   8  10  12  14  16  18  20
   3   3   6   9  12  15  18  21  24  27  30
   4   4   8  12  16  20  24  28  32  36  40
   5   5  10  15  20  25  30  35  40  45  50
   6   6  12  18  24  30  36  42  48  54  60
   7   7  14  21  28  35  42  49  56  63  70
   8   8  16  24  32  40  48  56  64  72  80
   9   9  18  27  36  45  54  63  72  81  90
  10  10  20  30  40  50  60  70  80  90 100

A: Check the solution below. It's all about properly managing iterators (note the less-equal sign in the ranges and the subtraction of indexes by 1 in the assignment). You can do it very concisely by assigning to output inside the printf and using a ternary-if. (I also used dynamic allocation in order to comply with ISO standards.)
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int range, i, j;

    printf("Enter the size of the multiplication table:\n");
    scanf("%d", &range);

    int ** output = (int **) malloc(sizeof(int *) * (long unsigned int) range);

    for(i = 0; i <= range; ++i)
    {
        output[i] = (int *) malloc(sizeof(int) * (long unsigned int) range);

        for(j = 0; j <= range; ++j)
            printf("%3d ", !i ? j : !j ? i : (output[i - 1][j - 1] = i * j));

        printf("\n");
    }

    return 0;
}


text:
Q: Best practice / idioms in C# to create "case classes" I have the following situation:

*

*The user can execute a number of different actions.

*I want to remember the actions taken in a List.

*To store each type of action, I need to store different parameters. (Let's say, an ID and a string for a rename action or a DateTime for a start action.)

I have been coding in Scala for a while, there I would write something like
abstract class Action
case class RenameAction(id: Int, newTitle: String) extends Action
case class StartAction(time: Instant) extends Action

so that I could then write functions like
def process(action: Action) = action match {
    case RenameAction(id, title) => ...
    case StartAction(time) => ...
}

My question is: What is the best practice / most idiomatic way to solve this in C#?
I'll describe some thoughts I have:

1st possibility: Direct translation
public abstract class Action
{
}

public sealed class RenameAction : Action
{
    public readonly int id;
    public readonly string title;

    public RenameAction(int id, string title)
    {
        this.id = id;
        this.title = title;
    }
}

public sealed class StartAction : Action
{
    public readonly DateTime time;

    public StartAction(DateTime time)
    {
        this.time = time;
    }
}

...

public void process(Action action)
{
    if (action is RenameAction)
    {
        RenameAction ra = action as RenameAction;
        ...
    }
    else if (action is StartAction)
    {
        StartAction sa = action as StartAction;
        ...
    }
}

This obviously works, but feels clunky to me.
(It's just a small private project without time pressure, and in those I like to write code that I'm happy about ;))

2nd possibility: Using an enum, I could do something like this:
public sealed class Action
{
    public readonly ActionType type;
    public readonly object[] parameters;

    public Action(ActionType type, params object[] parameters)
    {
        this.type = type;
        this.parameters = parameters;
    }
}

enum ActionType
{
    RENAME,
    START
}

...

public void process(Action action)
{
    switch(action.type)
    {
        case ActionType.RENAME:
            var id = action.parameters[0] as int;
            var title = action.parameters[1] as string;
            ...
            break;
        case ActionType.START:
            var time = action.parameters[0] as DateTime;
            ...
            break;
    }
}

This has the benefit that the number of action types is fixed, however the object[] parameters feels clunky again.

A: As noted in the comments, C# 7 has pattern matching on types in switches. You could write
public void Process(MyAction action)
{
    if (action is RenameAction)
    {
        RenameAction ra = action as RenameAction;
        ...
    }
    else if (action is StartAction)
    {
        StartAction sa = action as StartAction;
        ...
    }

more concisely as
public void Process(MyAction action)
{
    switch(action)
    {
      case RenameAction ra:
        ...
      case StartAction sa:
        ...
      case null:
        ...
      default:
        ...
    }

and so on.
Note that you can also add constraints:
case RenameAction ra when (ra.TargetName != null):

That said: switching on a set of possible subtypes is considered to be a poor programming practice by many, for some good reasons. Such as (1) if new subtypes are created, then every switch has to be updated, (2) if there's behaviour that varies by subtype then that behaviour should be captured in the subtype, not in code external to the subtype, and so on.

A: Both proposed ways (with switches and ifs) have the same flaw: each time a new action type is introduced you are obliged to modify the switch or and another else-if construction. You may be OK with it working on a pet project of your own, but it is not an example of a flexible, maintainable design. After a while these switches tend to become really huge and dreadful. And what is even worse is that no one is able to extend you functionality not having an access to your code (i.e. having it referenced as a library).
Keeping in mind SOLID principles, try to do the following:

*

*Define an interface that all your actions would implement. It may be really simple, like this:

    public interface IAction
    {
        void Do();
    }

    public class RenameAction : IAction
    {
        public readonly int id;
        public readonly string title;

        public RenameAction(int id, string title)
        {
            this.id = id;
            this.title = title;
        }

        public void Do()
        {
            // Perform an action
        }
    }

*The caller class should know nothing about which particular classes are passed into its method: its responsibility is only to run all the actions one by one:

    public class ActionExecutor
    {
        // ommit details
        public void Execute(IEnumerable actions)
        {
            foreach (var action in actions)
            {
                action.Do();
            }
        }
    }

*Assuming that different actions may have completely different sets of input parameters, I would suggest introducing abstract factories for them as well:

    public interface IActionFactory
    {
        IAction Create();
    }

    public class RenameActionFactory : IActionFactory
    {
        public IAction Create(IDictionary parameters)
        {
            // using a dictionary - is not a best choise. Just an example
            return new RenameAction(parameters["id"], parameters["title"]);
        }
    }

*Then, you have to have some correspondence between action types (they may be defined as enum members, or constants mapped to some DB configuration table, or something else) and factories. On of the ways would be have a configuration class

    public class ActionFactoriesConfiguration
    {
        private readonly Dictionary _configuration;

        public ActionFactoriesConfiguration()
        {
            _configuration =  new Dictionary
            {
                { ActionType.Rename, RenameActionFactory }
            }
        }

        public Type GetActionFactoryType(ActionType actionType)
        {
            if (_configuration.ContainsKey(actionType))
            {
                return _configuration[actionType];
            }
            return null;
        }
    }

Another way would be storing a lambda-functions for each action type. In this case no factories are needed, but the code becomes harder to test.
Another yet way includes using some of the IoC-frameworks.

*Finally, to create a factory you may implement another class

    public class ActionFactoryResolver
    {
        private readonly ActionFactoriesConfiguration _configuration;

        public ActionFactoryResolver(ActionFactoriesConfiguration configuration)
        {
            _configuration = configuration;
        }

        public IActionFactory CreateFactory(ActionType actionType)
        {
            var factoryType = _configuration.GetActionFactoryType(actionType);
            if (factoryType != null)
                return Activator.CreateInstance(actionType);

            return null;
        }
    }

This may seem as a huge overhead for a private project. But the strong side of this approach is that most of the classes are written (and tested) only once and never get changed with new actions adding. So they can be developed independently.


text:
Q: createShadowRoot makes element not visible I am following this tutorial on the shadow DOM:

http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/

For some reason, when I call the createShadowRoot function on the element, that element becomes invisible.
Here is my code:

Bob

<template id="nameTagTemplate">

            Hi! My name is

            Bob

</template>

When I don't call this method then the code works fine.
Any ideas why it is making it invisible?
Thanks :)

A: The main objective of shadow DOM is separation of content from presentation. Read: The content is in the document; the presentation is in the Shadow DOM
In Shadow DOM <content> acts as the insertion point for the content (in this case,
the text 'Bob' in the element) we want to show . Without this, the content, though already available in the document, can't be presented.
So, You need to modify your code to this -
<template id="nameTagTemplate">

    Hi! My name is

   <content></content>

</template>

And, try using
    var shadow = document.querySelector('#nameTag').createShadowRoot();
    var template = document.querySelector('#nameTagTemplate');
    //shadow.appendChild( template.content.cloneNode() ); // does not work
    shadow.appendChild( template.content.cloneNode(true) );
    // or
    shadow.appendChild( template.content );

A: using pure javascript:
// shadow DOM example with <template> and template string
//
var nameTag = function(selector, newName)
{
     var name = newName || document.querySelector(selector).innerHTML;
     var shadow = document.querySelector(selector).createShadowRoot();
     var templateNode = createNameTagTemplate(name);
     var clone = document.importNode(templateNode, true);
     shadow.appendChild(clone.content);
};

function createNameTagTemplate(name)
{
     var templateNode = document.createElement("template");
     templateNode.innerHTML = `

           Hi! My name is

           ${name}

`;
   return templateNode;
}

then if you have this:

Bob

nameTag("#foo") will make the div into a nametag using current name, or
nameTag("#foo", "Joe") will make it for name "Joe" instead.
NOTE: Supported in Firefox behind the dom.webcomponents.enabled flag (about:config).


text:
Q: How define images for arrows, drag and track in the new version of jScrollPane? I downloaded the last version of jScrollPanel (2.0 beta 5) but when opened jquery.jscrollpane.css I can't find any rules to apply images for top and down arrow, instead I found only this rule .jspArrow. I try to add an background image and it worked but the image shows on the top and down, how I can specify image for each side and also for .jspTrack,.jspDrag
Just like in the old version (v1).
Thanks

A: You can see an example setting graphics on the arrow buttons here:
http://jscrollpane.kelvinluck.com/themes/lozenge/
The relevant CSS classes are .jspArrowUp, .jspArrownDown, .jspArrowLeft and .jspArrowRight. You can also do things like .jspVerticalBar .jspArrow if you want to share one image between both vertical arrows (like in my example).
I would recommend using Firebug to inspect the generated HTML from a scroll pane. This is the easiest way to see all the classes that have been added.