text:
Q: Enter an operator to perform a math operation I want to enter an operator, +, -, , /, //, %, to perform a math operation using this program in python. How do I code these strings: "s = str(n) + "" + str(i) + "=  " + str(n * i)" for the .txt file funtions and "print(n, "*", i, "=", n * i)" to include the operator I choose? I'm not sure how to get this to work. Thanks for your time.
#!/usr/bin/python

def tablep():
    n=int(input("Enter Number of .txt Files to Create:")) # number of txt files

    for x in range(0, n):
        n=int(input("Enter a Number to Create Multiples of: "))
        import operator
        operatorlookup = {
            '+': operator.add,
            '-': operator.sub,
            '*': operator.mul,
            '/': operator.truediv}
        o=int(input("Enter Calculation Symbols for Calculation You Want to Perform: "))
        m=operatorlookup.get(o)
        start=int(input("Enter a Start Range Number: "))
        end=int(input("Enter an End Range Number: "))
        f=int(input("Enter Table Number to Name .txt File: "))
        f_path = "table_" + str(f) + ".txt" # this will numerate each table
        file = open(f_path, 'a') # 'a' tag will create a file if it doesn't exist

        if start<end:
            for i in range(start,end+1):
                s = str(n) + "*" + str(i) + "=  " + str(n * i) # I want to put the math operation of my choosing here in this "str(n * i)".
                file.write(s)
                file.write("\n")
                print(n,"*",i,"=", n * i) # I want to put the math operation of my choosing here in this "n * i)".

        elif start>end:
            for i in range(start,end,-1):
                s = str(n) + "*" + str(i) + "=  " + str(n * i) # I want to put the math operation of my choosing here in this "str(n * i)".
                file.write(s)
                file.write("\n")
                print(n, "*", i, "=", n * i) # I want to put the math operation of my choosing here in this "n * i)".

    file.close()
    print("\nYou are done creating files now. Run the program again if you want to create more. Thank you for using this program and have a nice day!\n")

w = tablep()

A: You could use a dictionary lookup:
def evaluate(a: int, b: int, operation: str):
    oper = {
        "+": a+b, "-": a-b, "*": a*b, "/": a/b, "%": a%b, "//": a//b
    }
    return oper.get(operation)

With a few test runs:
>>> evaluate(2, 5, "+")
7
>>> evaluate(2, 5, "-")
-3
>>> evaluate(2, 5, "*")
10
>>> evaluate(2, 5, "bananas")
None

A: Here is an option:
operator = input('Enter an operator: ')

operators = '+-**/'

if operator in operators:
    executable = f'print(2{operator}3)'
    exec(executable)

The program will ask for user input and then check if the input is in operators and if it is it will print out whatever result from using 2 and 3 and that operator. You can put pretty much any code in that f string.
About security:
As someone in the comments mentioned this isn't safe (the use of exec())? Since I can only assume it is because then it is possible to run any code (including malicious) You can just filter what the user inputs.
Here is probably an implementation to Your code (should use python 3.6 or higher or sth like that that supports f strings):
n = 5
i = 3
operator = '*'

# main part ========================
result = None
exec(f"""result = {n}{operator}{i}""", globals())

s = f'''{n} * {i} = {result}'''
print(s)

However this doesn't seem as efficient as I thought at first so You probably are better of using the other answer with using dictionaries and defining a function.

A: To get it to work, I took the code I had: "s = str(n) + "*" + str(i) + "=  " + str(n * i)" and modified this line using inspiration from code provided by @Matiiss: "exec(f"""result = {n}{operator}{i}""", globals())". My new line is this: "str(n) + str(operator) + str(i) + "= " + str(n + i)". I then made 4 lines with it. Each line does one math operation: +, -, *, /. Then I did a nested if statement for each individual operation under the four lines that calls on the dictionary that @JacobLee provided. Combined with the user input code for choosing an operator, the operator the user chooses will call on the corresponding nested if statement. Finally, the code inside the nested if statement will perform the math and write it to the .txt file. Thanks for your answers everyone, they helped a lot. Have a nice day.


text:
Q: session_destroy não inicializa nova sessão Estou tentando usar o código abaixo para quando o usuário clicar em sair, ele for redirecionado para o arquivo abaixo de destruir a sessão, porém depois de destruída a sessão não é possível logar novamente, porque a página a seguir após o login não carrega, só aparece o nome da próxima página na barra de endereço.
Página que contém as funções de login:
session_start();

$_SESSION['usuariosession'] = $user;
$_SESSION['senhasession'] = $pass;
$_SESSION['autenticandosession'] = true;

header('Location:views/painel.php/');

Próxima página após o login:
session_start();

    if(!isset($_SESSION['autenticandosession']) || $_SESSION['autenticandosession'] != true){
        echo "Acesso não autorizado
";
        echo "Por favor faça seu login  clicando aqui ";
        exit();
    }else{
        echo "
 Bem vindo ".ucfirst($_SESSION['usuariosession'])."

";
    }

    <title> Painel </title>

 Olá eu sou o painel, se voce chegou até aqui é porque suas credenciais deram certo...

     Sair

Página com a função para sair:
session_start();

    unset ($_SESSION['usuariosession']);

    unset ($_SESSION['senhasession']);

    session_destroy();
    header('Location:views/login.php/');

A: No login.php você está redirecionando pra /view/painel.php e no sair.php está direcionando para views/login.php. E não existe login.php nesse diretório view.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linux Gnome, can NOT install PPAs needed by KIVY The first step on the kivy website already fails:
https://kivy.org/docs/installation/installation-linux.html
This fails for bouth repositories, you can choose from

A: Currently there is no PPA for Ubuntu Bionic as shown in the Kivy PPA list. In the meantime, you might want to install Kivy in a virtual environment.


text:
Q: How do I define a static constexpr array member of a template class specialisation I am attempting to use static constexpr arrays within a template specialised class as shown below:
///////////////////////////////////////////////////////////////////////////
struct good {
    static constexpr int values[1] = { 0 };
};

constexpr int good::values[1];

///////////////////////////////////////////////////////////////////////////
template <typename T>
struct bad;

template <>
struct bad<int> {
    static constexpr int values[1] = { 0 };
};

constexpr int bad<int>::values[1];

///////////////////////////////////////////////////////////////////////////
int
main (int argc, char **argv)
{
#if 1
    return good::values[0];
#else
    return bad<int>::values[0];
#endif
}

I am aware of the requirement to both declare and define static members, and the 'good' case from above appears to succeed with gcc-6.2.0 and clang-3.9.0 using -std=c++1z.
However the 'bad' case results in an undefined reference under clang-3.9.0, giving the output as follows:
danny@steve ~/src $ clang++ -std=c++1z scratch.cpp
/tmp/scratch-56fa44.o: In function `main':
scratch.cpp:(.text+0x15): undefined reference to `bad<int>::values'
clang-3.9: error: linker command failed with exit code 1 (use -v to see invocation)

Is there something additional I need to do, or that I'm missing, to instantiate static constexpr members? The code appears to work fine when modified to use static const members.
The code will link successfully if the unit is instead compiled with -std=c++1y.

A:
Is there something additional I need to do, or that I'm missing, to instantiate static constexpr members?

The code looks well formed, but it indeed fails to link in Clang up to version 5.0.2, however it is fully accepted in Clang 6.0. Demo: https://gcc.godbolt.org/z/Ka7W4bbqf
This suggests that it was just a compiler bug.


text:
Q: How to conduct and report pairwise comparisons with estimated marginal means? I have two mouse strains (C57 and CBA) that are exposed to a treatment with three levels (suum, lumb or control). My dependent variable is immune cell counts and the model is a negative binomial with an interaction e.g.
NB.Eos <-  glm.nb(Eosinophils_total ~ Strain * Species, data = Liver_PMNC)
I then run some customized comparisons and calculate the estimated marginal means.
# Pairwise comparisons:
C57_ctrl <- c(1, 0, 0, 0, 0, 0)
C57_lumb <- c(0, 1, 0, 0, 0, 0)
C57_suum <- c(0, 0, 1, 0, 0, 0)
CBA_ctrl <- c(0, 0, 0, 1, 0, 0)
CBA_lumb <- c(0, 0, 0, 0, 1, 0)
CBA_suum <- c(0, 0, 0, 0, 0, 1)

emm.total.Eos = emmeans(NB.Eos, ~ Species * Strain, type = 'response')
contrast(
  emm.total.Eos,
  method = list(
    'C57_ctrl vs C57_lumb' = C57_ctrl - C57_lumb,
    'C57_ctrl vs C57_suum' = C57_ctrl - C57_suum,
    'CBA_ctrl vs CBA_lumb' = CBA_ctrl - CBA_lumb,
    'CBA_ctrl vs CBA_suum' = CBA_ctrl - CBA_suum,
    'C57_ctrl vs CBA_ctrl' = C57_ctrl - CBA_ctrl,
    'C57_suum vs CBA_suum' = C57_suum - CBA_suum,
    'C57_lumb vs CBA_lumb' = C57_lumb - CBA_lumb
  ),
  adjust = 'bonf'
)

Some of my models don't have an interaction e.g. different immune cell type as a response (e.g. NB.Eos <-  glm.nb(Basophils_total ~ Strain + Species, data = Liver_PMNC)). So I have two questions:

*

*Where there is no interaction should I simply switch my * for a + throughout?

*What statistic do I report for the interactions that these p-values are associated with?

Sample data are available here

A: You have worked far harder than needed to get these contrasts. Examining these, note that these are all what is known as simple contrasts: comparisons of one factor while holding the other fixed. The first 2 are Dunnett-style comparisons of Species at Strain=C57, the next two are the same at CBA, and the last three are comparisons of Strain at each species. (BTW, in the context of rthe question and the names of the levels, why is it Species, not Treatment?)
In addition, your manual construction of contrasts depends very much on getting the order of results exactly the same as are computed by emmeans. It is safer to use the tools available to specify the needed contrasts using factor names.
So here are the first 4 contrasts:
con1 <- contrast(emm.total.Eos, "trt.vs.ctrl1", by = "Strain")

and the last 3:
con2 <- contrast(emm.total.Eos, "trt.vs.ctrl1", by = "Species")

So if you want to collect these and adjust as one family of 7 contrasts, do:
summary(con1 + con2, type = "response", adjust = "bonferroni")

BTW, here is a speedier way to get these results:
rbind(contrast(emm.total.Eos, "trt.vs.ctrl1", simple = "each",
               type = "resp", adj = "bonf"))

In answer to Q.1, if you don't have an interaction in the model, that implies that the 1st and 3rd contrasts are identical, the 2nd and 4th are identical, and the 5th, 6th, and 7th are identical. So there are only 3 different contrasts. For those additive models, you should do:
conI = contrast(emmeans(model, "Species"), "trt.vs.ctrl1")
conII = contrast(emmeans(model, "Strain"), "trt.vs.ctrl1")
summary(conI + conII, type = "response", adj = "bonf")

That will give you a set of 3 contrasts, adjusted as one family.
You might consider using the "mvt" adjustment; it is "exact" in a sense, rather than conservative.
I'm not certain what you are asking in Q.2. But I think you will see in this example t ratios with Inf degrees of freedom -- which means they are really z tests. Those are what I would report. (Note: because link function is the log, the contrasts will back-transform to ratios. However, the t statistics are computed before back-transforming.)


text:
Q: Android: ArrayIndexOutOfBoundsException when passing the values I am getting this ArrayIndexOutOfBoundsException  when i am trying to pass latitude and logitude
private String getId(String facebookUser,String lat, String expiryMinute, String messageId, String message, String referenceKey, String placeId) {

        lang = Utils.formatDouble(Constants.searchLocation.getLongitude());
        lat = Utils.formatDouble(Constants.searchLocation.getLatitude());
        String traceId = null;
        HttpClient client = new HttpClient();
        PostMethod post = null;
        try {

            NameValuePair[] params = null;
            NameValuePair param = new NameValuePair();

            if(Constants.isMessageForPosting){
                params = new NameValuePair[6];
                param.setName("gadget");
                param.setValue("gettraceid");
                params[0] = param;

                if(messageId == null || messageId.trim().isEmpty()){
                    messageId = "1";
                }
            }else{
                params = new NameValuePair[8];
                param.setName("gadget");
                param.setValue("getrequestid");
                params[0] = param;
                if(messageId == null || messageId.trim().isEmpty()){
                    messageId = "2";
                }
            }

            if(expiryMinute == null || expiryMinute.trim().isEmpty()){
                expiryMinute = "0";
            }

            param = new NameValuePair();
            param.setName("fbuserid");
            param.setValue(facebookUser);
            params[1] = param;

            param = new NameValuePair();
            param.setName("userid");
            param.setValue(Constants.USERID);
            params[2] = param;

            param.setName("expiryminute");
            param.setValue(expiryMinute);
            params[3] = param;

            param.setName("msgid");
            param.setValue(messageId);
            params[4] = param;

            param = new NameValuePair();
            param.setName("msg");
            param.setValue(message);
            params[5] = param;

            param = new NameValuePair();
            param.setName("lat");
            param.setValue(lat);
            params[9] = param;

            param = new NameValuePair();
            param.setName("lang");
            param.setValue(lang);
            params[10] = param;
        */
            if(!Constants.isMessageForPosting){
                param = new NameValuePair();
                param.setName("referencekey");
                param.setValue(referenceKey);
                params[6] = param;

                param = new NameValuePair();
                param.setName("placeid");
                param.setValue(placeId);
                params[7] = param;
            }

            post.setQueryString(params);
        int statusCode = client.executeMethod(post);
            traceId = post.getResponseBodyAsString();

        } catch (Exception e) {
            Log.e(TAG, "For Facebook Trace Id:", e);

        } finally {
            post.releaseConnection();
            post = null;
        }
        return Id;
    }

below is my stack trace
02-26 15:39:52.131: E/MainFragment(23117): For Facebook Trace Id:
02-26 15:39:52.131: E/MainFragment(23117): java.lang.ArrayIndexOutOfBoundsException: length=6; index=9
02-26 15:39:52.131: E/MainFragment(23117):  at org.appright.mycity.activity.MainFragment.getTraceId(MainFragment.java:291)
02-26 15:39:52.131: E/MainFragment(23117):  at org.appright.mycity.activity.MainFragment.access$7(MainFragment.java:225)
02-26 15:39:52.131: E/MainFragment(23117):  at org.appright.mycity.activity.MainFragment$PostFBMessage.doInBackground(MainFragment.java:553)
02-26 15:39:52.131: E/MainFragment(23117):  at org.appright.mycity.activity.MainFragment$PostFBMessage.doInBackground(MainFragment.java:1)

Any help is appreciated.

A: The problem is that you are declaring params variable with either 6 element or 8 element. but at later on you are accessing the 8th & 9th element, which is wrong.
Solution:
Either you should use static array size wih 10 element or use ArrayList Class.


text:
Q: Xcode 7.3 and Interactive Playgrounds without creating a Framework Is there any way to use playgrounds inside an existing project to design and test View Controllers or other project views with Interactive Playgrounds without creating a Framework?
I tried to import ViewController and similar into playground inside my project but nothing works. I can't access to project files from playgrounds.
Any idea?
Thanks!


text:
Q: Possible algorithms to solve this problem I have a list of extracted names of one hotel , and these are the names taken by n websites about the same hotel . The list contains m names about 1 hotel . I have to select one name from the list based on correctness , similarity , less mistakes . How can I achieve this ?
Any direction is helpful .
Example: List of names for hotelId 1 {"ABC Hotel","CDE hotel" , "Hotel ABC" ,"AB Hotel" , "Hotel BCA" ...}
With the initital research it looks like a graph related problem

A: This is not gonna work. You will not get similarities based on the names. Especially if almost every hotel has the keyword hotel in its name.
You need more information to match similarities.
Address, Geo location, attributes about the hotel could also help (wifi, parking, close to beach, pool), if this is a chain and so on. The more information you have the better the matching result you can get.

A: You can try to leverage some of Bing or Google APIs --> i.e. do a search for the hotel name with some details from address in Search APIs or in some Map APIS (e.g. search for ["ABC Hotel 5AV Philliadelphia","CDE hotel 5AV Philliadelphia" , "Hotel ABC 5AV Philliadelphia",..] then compare your data with the API response.


text:
Q: Python sns.catplot sum of group by Tryin to do a sum of all minutes.
When doing just a DataFrame - receiving just a first value
sns.catplot(x="hour", hue="VehicleType", kind="count",
        palette="pastel", edgecolor=".6",
        data=df_test);

enter image description here
When doing with a group by (that is what I want to see) - getting the MAX value of 1
sns.catplot(x="hour", hue="VehicleType", kind="count",
        palette="pastel", edgecolor=".6",
        data=df_hour_group);

enter image description here
How I can show a group by sum with 2 categories, 24 hours?
Thank you in advanced

A: okay, figure that out
Don't need to use group by. Use pivot instead
df_plot= pd.pivot_table(df_test, columns='VehicleType', index=['hour'], aggfunc='sum', values='Minutes_Idling').plot(kind='bar')


text:
Q: Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED. Error when trying to save the feature maps I want to save the feature maps which are generated when i give an image as input to VGG16. But I'm getting this error. Please help me :)
2020-05-03 19:31:42.361061: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudnn64_7.dll
2020-05-03 19:31:43.634465: E tensorflow/stream_executor/cuda/cuda_dnn.cc:329] Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED
2020-05-03 19:31:43.638077: E tensorflow/stream_executor/cuda/cuda_dnn.cc:329] Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED
2020-05-03 19:31:43.641090: W tensorflow/core/common_runtime/base_collective_executor.cc:217] BaseCollectiveExecutor::StartAbort Unknown: Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.
         [[{{node block1_conv1/convolution}}]]
Traceback (most recent call last):
  File "C:\Users\sreec\OneDrive\Desktop\8th Sem\Project\Test\Test.py", line 44, in <module>
    feature_maps = model.predict(img)
  File "D:\Anaconda\lib\site-packages\keras\engine\training.py", line 1462, in predict
    callbacks=callbacks)
  File "D:\Anaconda\lib\site-packages\keras\engine\training_arrays.py", line 324, in predict_loop
    batch_outs = f(ins_batch)
  File "D:\Anaconda\lib\site-packages\tensorflow_core\python\keras\backend.py", line 3727, in __call__
    outputs = self._graph_fn(*converted_inputs)
  File "D:\Anaconda\lib\site-packages\tensorflow_core\python\eager\function.py", line 1551, in __call__
    return self._call_impl(args, kwargs)
  File "D:\Anaconda\lib\site-packages\tensorflow_core\python\eager\function.py", line 1591, in _call_impl
    return self._call_flat(args, self.captured_inputs, cancellation_manager)
  File "D:\Anaconda\lib\site-packages\tensorflow_core\python\eager\function.py", line 1692, in _call_flat
    ctx, args, cancellation_manager=cancellation_manager))
  File "D:\Anaconda\lib\site-packages\tensorflow_core\python\eager\function.py", line 545, in call
    ctx=ctx)
  File "D:\Anaconda\lib\site-packages\tensorflow_core\python\eager\execute.py", line 67, in quick_execute
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.UnknownError:  Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.
         [[node block1_conv1/convolution (defined at D:\Anaconda\lib\site-packages\keras\backend\tensorflow_backend.py:3009) ]] [Op:__inference_keras_scratch_graph_458]

Function call stack:
keras_scratch_graph

Press any key to continue . . .

A: You can try GPU memory resources management by limiting GPU memory growth.
It can be done by calling tf.config.experimental.set_memory_growth, which attempts to allocate only as much GPU memory as needed for the runtime allocations: it starts out allocating very little memory, and as the program gets run and more GPU memory is needed, we extend the GPU memory region allocated to the TensorFlow process.
To turn on memory growth for a specific GPU, use the following code prior to allocating any tensors or executing any ops.
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  try:
    # Currently, memory growth needs to be the same across GPUs
    for gpu in gpus:
      tf.config.experimental.set_memory_growth(gpu, True)
    logical_gpus = tf.config.experimental.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Memory growth must be set before GPUs have been initialized
    print(e)


text:
Q: how to create UNIX / Linux commands? I'm looking to create my own Unix/ Linux commands using C programming.
Say for example .. I wrote simple file copy program, I'd like to make it as a Unix/ Linux command.
How do I do it ?

A: Any executable file placed in a directory that is in the PATH (shell) variable will be a Unix command.

A: *

*Write your code using stdin, stdout and stderr in order to allow executing it from the command line and pipe its output

*Parse command line arguments and use them (if you need)

*Compile the binary

*Locate in any directory in the PATH (e.g. /usr/sbin)


text:
Q: How to Parse thyemeleaf Context variables in HTML Page Facing problems with Thymeleaf Template Engine.
I need to add some dynamic content to the html page.
I've a map like this
Map<String, String> info = new HashedMap<String, String>();
info.put("user_name", "username");
info.put("host_user_name", "host_user_name");
info.put("title", "Element_title");
info.put("url", "https://www.google.com");
info.put("conv_url","/#/home/" + "23243242" + "/services?fid=543545"&fview=conversation")

and I am adding the info in the map to the context
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
Context context = new Context();
System.out.println("---------0------------");
info.forEach((key, value) -> {
    context.setVariable(key, value);
});
String template = templateEngine.process("my-html", context);

my-html is like this

        [[${host_user_name}]] [[${title}]]

                [[${followers}]] followers | [[${replies}]] replies

inline text is modifying for me, but how to change href and src attribute values.

This should be replaced by

Can anyone help me on this?

A: Please, read this documentation.
Particularly, look at this example in this documentation :

You have to use th:href

A: This is Working for me

                 &


text:
Q: How to get the x and y position of a deeply embedded element with respect to the root element itself? What is the best way, if indeed there is a way, to get the X and Y position of any element embedded deep inside another element (called root for convenience) with respect to the root element itself. The embedded element may have layers of other containers with different position CSS (e.g. relative, absolute, etc.).
I prefer JQuery but a pure JS solution would be even better.
For example:

 <other elements....>

 <other elements...>

I want to know the absolute X and Y positions of input field with id "id1" with respect to div with id "root".
EDIT: "root" is always set to position:relative


text:
Q: Linear Algebra and subset of basis Let $V$ be a finite dimensional vector space with basis $B$. Under what conditions will a subspace $U$ of $V$ that is not $V$ have a basis consisting of elements of $B$?
I'm wondering about this and know that it is generally not true, but when does it hold?

A: That will happen if and only if $U$ is spanned by a subset of $B$.
In fact, if $B'\subset B$ and $U=\operatorname{span}(B')$, then $B'$ is a basis of $U$. On the other habd, if $B^\ast$ is a subset of $B$ which is a basis of $U$, then $U=\operatorname{span}(B^\ast)$.


text:
Q: How do I "Rebuild and Run" using CodeBlocks in one single action? Is there a way to have a button or shortcut to "Rebuild and run"? Because I have to click "Rebuild" and then click "Run" every time. This is very annoying...
PS.: For the project I'm working on, "Build and Run" button is not enough because I need to REbuild the entire project every time I change something in the code.

A: No, there is no such feature currently.
You can bind "Clean" to a shortcut, for example Shift-F9, and then run "Build and Run" using F9.
But CodeBlocks is open source, so if this isn't good enough for you either implement this yourself or suggest it on http://forums.codeblocks.org/
For binding the "Clean" to a shortcut, you go into Settings -> Editor -> Keyboard shortcuts.


text:
Q: Can we prove that this formula correctly describes the $n$th least significant digit? So if we take a look at the binary representation of numbers, we can see that the digits follow a pattern:
$$0 = 0000$$
$$1 = 0001$$
$$2 = 0010$$
$$3 = 0011$$
$$4 = 0100$$
$$\dots$$
i.e. the least significant digit goes 0,1,0,1,... and repeats.  The 2nd least significant digit goes 0,0,1,1,... and repeats.  So I have a formula for the "generating function" of the $i$th least significant digit for the first $2^V$ values:
$$f(i,V) = \left(\prod_{k=0}^{i-1}(1+x^{2^k})\right)x^{2^i}\left(\prod_{k=i+1}^{V}(1+x^{2^k})\right)$$
Can we prove this formula is correct?
UPDATE
Here's an easier version of the formula:
$$f(i,V) = \left(\prod_{k=0}^{V}(1+x^{2^k})\right)\frac{x^{2^i}}{1+x^{2^i}}$$

A: I would write your generating function as
$$\dfrac{x^{2^i}}{1 + x^{2^i}} \prod_{k=0}^V (1 + x^{2^i})$$
Now $P_V(x) = \prod_{k=0}^V (1 + x^{2^i}) = \sum_{j=0}^{2^{V+1}-1} x^j$, since each $j$ is represented in exactly one way as
the sum of a set of powers of $2$.  On the other hand,
$$ \dfrac{x^{2^i}}{1 + x^{2^i}} = x^{2^i} - x^{2 \cdot 2^i} + x^{3 \cdot 2^i} + \ldots$$
In expanding the product of this with $P_V(x)$,  $x^m$ occurs once for every way of writing
$m = j + r \cdot 2^i$ with $0 \le j < m$, with coefficient $-1$ if
$r$ is even and $+1$ if $r$ is odd.
If $j_0$ is the least residue of $m$ mod
$2^i$, we can have $r =  1, 2, \ldots, (m - j_0)/2^i$.  If $(m-j_0)/2^i$ is odd there is one more odd $r$ than even $r$, so the coefficient of $x^m$ in your generating function is $1$, while if $(m - j_0)/2^i$ is even there are
as many odd as even $r$ and the coefficient is $0$.  But the $2^i$'s digit
of the binary expansion of $m$ is the $1$'s digit in the expansion of
$(m - j_0)/2^i$, which is $1$ if and only if $(m - j_0)/2^i$ is odd.


text:
Q: How to get location (latitude and longitude) using SIM7600 GSM module without the help of GPS? i am using SIM7600G GSM module to get the location information without using GPS in it. Anyone know about how to find the location from GPRS SIM itself?!

A: If such information could have been obtained from a device it wouldn't be the SIM but the GSM hardware. What you can hope to get is the cell ID of the serving cell, typically using AT commands, but this is not always true for all devices.
Depending on your country, you can find the position (longitude, latitude) of the site bearing that cell (there exist some databases). Depending on site location, urban zone or rural zone, you can approximate the position of the device within the coverage area of the cell from some hundreds meters (urban) to few tens of kilometers (rural zone where the network is usually much less dense), the theoretical maximum being 35Km...
The only way to have a precise position is by using the GPS


text:
Q: How to Validate HttpServletRequest using @Valid annotation? I am currently working on a rest api and I need to validate the HttpServletRequest object which my Controller method receives. Is there a way to validate it using the @Valid annotation? I need to check the content type, request body? I know we can use the @Valid annotation to validate user defined classes. Can we use the same for HttpServletRequest Class? If not what other options do i have?
thanks,
kayzid


text:
Q: Implicit Second Derivatives using Partial Derivatives I've got a pretty simple derivative question for you guys.  Currently, I'm a high school shop teacher preparing kids for a timed calculus competition.  It's been almost 45 years since I've taken multivariate calculus, and I'm having a hard time remembering some tricks.
Almost every round features where you must find $\frac{dy}{dx}$ given something like this.
$$
x^2 + 2xy +7 = 0
$$
The kids are taught to differentiate implicitly, then solve for $\frac{dy}{dx}$.  I remembered that you could set the original equation equal to some function $g$, and simplify with this formula (from chain rule):
$$\frac{dy}{dx} = \frac{-\frac{\partial g}{\partial x}}{\frac{\partial g}{\partial y}}$$
I know there's a way to extend this to finding the second derivative of $y$ with respect to $x$, but I just cannot remember how.
I think I take the partial of the first derivative wrt $x$, multiply by the first derivative, then add the partial of the first derivative wrt $y$, but it doesn't seem to be working.
Any help?

A: If
$$
y'=-\frac{F_x}{F_y},
$$
it can be computed, that
$$
y''=-\frac{F'_xF_y-F_xF'_y}{F^2_y}=-\frac{(F_{xx}+F_{xy}y')F_y-F_x(F_{yx}+F_{yy}y')}{F^2_y}=\\\\=-\frac{\left( F_{xx}+F_{xy}\left( -\frac{F_x}{F_y}\right)\right)  F_y-F_x\left( F_{yx}+F_{yy}\left( -\frac{F_x}{F_y}\right) \right) }{F^2_y}=\\\\=-\frac{F_y^2 F_{xx}-F_xF_y(F_{xy}+F_{yx})+F_x^2F_{yy}}{F^3_y}
$$
However, $y=y(x)$, hence differentiating $y'(x)$ is usually a quicker method than using the formula above.

A: It's just the chain rule, so it doesn't need to be as complicated as the solution above.
If you call your first derivative $h$, you can find the second derivative with this.
$$
\frac{d^2y}{dx^2}=\frac{\partial h}{\partial x} + \frac{\partial h}{\partial y}\frac{dy}{dx}
$$
What you said at the end was almost correct, but you had backward which partial you multiplied by the first derivative.


text:
Q: Google Map not showing up Javascript Ionic 4 I've been trying to insert a Google Map on my Ionic 4 Webiste, but I've been unable to because the map is not showed up.
Here's my code below
  ionViewDidEnter(){
    console.log('creating map')
    // var latlng = new google.maps.LatLng(39.305, -76.617);
    this.map = new google.maps.Map(document.getElementById("map"), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 8
    });
}

This is how I'm inserting it on the HTML file

Any hint or help will be greatly appreciated.

A: Josh Morony has a great blog post that walks through how to build out a map component. Basically it goes something like this:
Install the types for Google maps
 npm install @types/googlemaps --save-dev

Initialize the map in your component
/// <reference types="@types/googlemaps" />
import { Component, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements AfterViewInit {

  constructor() {}

  async ngAfterViewInit() {
    const googleMaps = await getGoogleMaps("YOUR-API-KEY-HERE");
    this.initMap();
  }
  initMap() {
    const POSITION = {lat: -25.344, lng: 131.036};

    const map = new google.maps.Map(document.getElementById("map"), {
      zoom: 4,
      center: POSITION || { lat: 22, lng: 22 }
    });
  }
}

function getGoogleMaps(apiKey: string): Promise<any> {
  const win = window as any;
  const googleModule = win.google;
  if (googleModule && googleModule.maps) {
    return Promise.resolve(googleModule.maps);
  }

  return new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}`;
    script.async = true;
    script.defer = true;
    document.body.appendChild(script);
    script.onload = () => {
      const googleModule2 = win.google;
      if (googleModule2 && googleModule2.maps) {
        resolve(googleModule2.maps);
      } else {
        reject("google maps not available");
      }
    };
  });
}

The first line /// <reference types="@types/googlemaps" /> of the component is to address a Typescript related issue (details here)
Lastly, make make sure your CSS is setup to render the map.
#map {
    width: 100%;
    height: 100%;
    display: contents;
}

Hope this helps.


text:
Q: Is deprecating all single record operations with multiple record operations a good idea? TL;DR
Look at code examples and tell me which one would you choose.
The entire thing
I am in progress of making an GraphQL API. Amid doing that, I have realized, that I'd love to mass insert data, but I could not, because the only method available to me was the one used for single item insertion. This revealed a problem. If someone was to insert higher volumes of data, they would either have to send single item requests one by one, or I have to add another mutation that allows array of items as an input. As the first option is for apparent reasons not an option. This meant adding another method, but this got me thinking, why should I even be keeping single operations methods (get/update/add single item) in the first place, as they do exactly the same, just with the limitation of sending max 1 item, are harder to maintain, and pollute API documentation.
My question is, would you go ahead and replace all those single operation methods with a multiple operation method?
To me it's a no-brainer and the answer is yes. The reason why am I asking is, that vast majority of APIs does have the above described structure of using one endpoint for responding with singular item and one for responding with multiple items and I bet there is a reason for it.
Code example of what I mean:
Deprecating this:
/*=============================================
                    Types
=============================================*/
interface UpdateDog {
    _id: string,
    name: string
}
interface AddDog {
    name: string
}
/*=============================================
                    Main
=============================================*/
export const DogModule = {
    resolvers: {
        Query: {
            dog: async (parents: any, args: { _id: string }) => {
                // Returns one of only one ID is passed in array
            },
            dogs: async (parents: any, args: { _ids: string[] }) => {
                // Returns dogs
            },
            allDogs: async () => {
                // Returns all dogs
            }
        },
        Mutation: {
            addDog: async (parents: any, args: { input: AddDog}, context: GraphqlContext) => {
                // Add dog to the database
            },
            addDogs: async (parents: any, args: { input: AddDog[] }, context: GraphqlContext) => {
                // Add dogs to the database
            },
            updateDog: async (parents: any, args: { input: UpdateDog }, context: GraphqlContext) => {
                // Update dog
            },
            updateDogs: async (parents: any, args: { input: UpdateDog[] }, context: GraphqlContext) => {
                // Update dogs
            }
            ...
        }
    }
}

export default DogModule

In favor of this:
/*=============================================
                    Types
=============================================*/
interface UpdateDog {
    _id: string,
    name: string
}
interface AddDog {
    name: string
}
/*=============================================
                    Main
=============================================*/
export const DogModule = {
    resolvers: {
        Query: {
            dogs: async (parents: any, args: { _ids: string[] }) => {
                // Returns one of only one ID is passed in array
                // Multiple on multiple IDs
                // All if not IDs are passed
            }
        },
        Mutation: {
            addDogs: async (parents: any, args: { input: AddDog[] }, context: GraphqlContext) => {
                // Add them to the database
            },
            updateDogs: async (parents: any, args: { input: UpdateDog[] }, context: GraphqlContext) => {
                // Update dogs
            },
            ...
        }
    }
}

export default DogModule

Additional info:

*

*Once done API will be a publicly accessible with API key. Meaning that I will be able to limit the amount of changes coming from one source.

*I am aware that I cannot replace every single operation method multi operation method. (such as logins, or signup)


text:
Q: How to check if the element is near the bottom of the screen? How is the way to check if some the element is near the bottom of the screen let say 100px from the bottom? (not the bottom of page).
The thing is i wanted that when this element is clicked, an another element will shown up and will slide to top rather to down if is near the bottom of the screen?

A: You can identify when an element is under 100px from the bottom of the screen with the following condition (without the need to use jQuery):
if (window.innerHeight - element.getBoundingClientRect().bottom < 100){
  // the desired place
}

A: I think what you want is a button that displays when the user is almost at the bottom of your screen and when the user clicks on it, it scrolls them back to the top of the screen.
You may want to use JavaScript to achieve this.
Using the jQuery library
<script type="text/javascript>
    $(document).scroll(function(){
        var x = $(this).scrollTop();
        if (x > 250) //The 250 is the total height of div that the user scrolls to before the button displys for the user to click
        {
            $('.button').fadeIn();
        } else {
            $('.button').fadeOut();
        }

        $('.button').click(function() {
        $('html, body').animate({
            scrollTop: $('.topmost_div').offset().top}, 'slow'); //tell the page to scroll back to the div at the top of the page.
        });
    });
</script>

Hope this helps


text:
Q: EDGE não consegue copiar imagens grandes usando JS de/para um canvas? Tenho o seguinte código, que copia pedaços da imagem "smoothchartshowAnalisysCopy" (500px X 250px)  para a imagem maior (32172px X 250px).
var c   = document.getElementById('analysisFullGraph1'); 32172px X 250px
var ctx = c.getContext('2d');

var imageNow = document.querySelector('#smoothchartshowAnalisysCopy');
var ctxImageNow = imageNow.getContext('2d');

function copy(){
    var elmnt  = document.querySelector('#analysisFullGraphContainer1');
    var x = elmnt.scrollLeft;
    var y = elmnt.scrollTop;
    var imgData = ctx.getImageData(x, 0, 828, 270);
    ctxImageNow.putImageData(imgData, 0, 0);

}

Está funcionando perfeitamente com IE, Firefox, Chrome, Safari e Vivaldi, exceto com o MS Edge. O MS Edge só copia os pedaços da imagem do começo até a posição de 14000px.
Em posições maiores de 14000px, não aparece nem sequer um erro, mas nada é copiado.
Não encontrei nada na documentação da Microsoft, nem algo relevante no Google.


text:
Q: how to get the name of the currently connected device to computer? When I connect my phone to the computer and visit Google play store in google chrome, it seams like the page knows that the device is connected, like this picture:

How can I do it using JavaScript?

A: From what I can tell, once you link your phone to your Google account, Google attaches your phone's to your Google Play account and then displays it to you when you're looking at apps using your computer's web browser. Don't think there's any Javascript at play here.

A: You can't. The Google Play website doesn't know your phone is connected to your computer, it just knows which Android devices you've configured with you're Google account.


text:
Q: C# WPF - VLC - LibVLCSharp.Shared.VLCException: 'Failed to load required native libraries I have tested the WPF minimal VLC sample on code.videolan website, and it works fine.
I then prepare (and package) the app for the Windows store following Microsoft documentation here, and basically it no longer works with the failed to load libs message.
Setting the .package project as startup project creates the issue. Theses are the packages I have, although UWP has just been added and is not referenced anywhere.

Within the VLC sample, it fails directly on Core.Initialize();
void VideoView_Loaded(object sender, RoutedEventArgs e)
{
     Core.Initialize();

     _libVLC = new LibVLC();
     _mediaPlayer = new MediaPlayer(_libVLC);

     VideoView.Media

     _mediaPlayer.Play(new Media(_libVLC, new Uri("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4")));
}

If I put:
var url = typeof(LibVLC).Assembly.Location;

before the Core.ini line to check where it's looking, I get:
"C:\Users\franc\Documents\Visual Studio 2019\Projects\VLCTest\VLC.Package\bin\x64\Debug\AppX\VLCTest\LibVLCSharp.dll"
Which looks ok to me.. Any suggestions?

Edit 1

The libvlc folder is not being created under AppX folder:
{"Failed to load required native libraries. \r\nHave you installed the latest LibVLC package from nuget for your target platform?\r\nSearch paths include
...Projects\VLCTest\VLC.Package\bin\x64\Debug\AppX\VLCTest\libvlc\win-x64\libvlc.dll,
...Projects\VLCTest\VLC.Package\bin\x64\Debug\AppX\VLCTest\libvlc\win-x64\libvlccore.dll;
...Projects\VLCTest\VLC.Package\bin\x64\Debug\AppX\VLCTest\libvlc\win-x64\libvlc.dll,
...Projects\VLCTest\VLC.Package\bin\x64\Debug\AppX\VLCTest\libvlc\win-x64\libvlccore.dll;
...Projects\VLCTest\VLC.Package\bin\x64\Debug\AppX\VLCTest\libvlc.dll,"}

So I manually copied the folder from the WPF project (no longer the startup project) to the new .package startup project AppX ... folder and it worked.
What would be the clean solution for this?

A: Packaging with MSIX has never been tested as far as I know.
Does your libvlc.dll, libvlccore.dll files and plugins folder get copied properly next to your app's DLL?
If you're not using UWP, don't reference LVS.UWP.


text:
Q: How to access web application class into silverlight application I am beginner in silverlight..I have created a silverlight project. When a new silverlight project is created it is automatically creating a silverlight application and one web application. I have added a class in both applications. Now I want to access a method of web application class into silverlight application class. Is it possible? I have tried to add web application reference to silverlight but VS is not allowing. Is there any another way to do??

A: What you need is called WCF.  A really simple tutorial that should get you going is found here: How to call WCF methods from Silverlight controls
Fundementally WCF allows the silverlight client to make method calls on a class instance hosted on the web site.

A: Yes it is possible, but not in the normal way. A Silverlight assembly can only reference another Silverlight assembly (this is a limitation of VS2008, i don't know if it has been changed in VS2010).
What you need to do is add an existing file to your Silverlight project, when the file browse dialog opens you navigate to the class file you want to reuse, but instead of just clicking the Add button, click on the little down arrow on the button and choose Add as link - now the file will "exist" in both projects and can be used in both.
If you are going to do this repeatedly though, you will want to move those shared class files out into a separate assembly, do a project reference from your web app, and have the equivalent Silverlight class library mirroring it (sharing the files as links), and then project reference that Silverlight class library from your Silverlight app.


text:
Q: Ajax cache not working for some reason I am having problems understanding why and how my ajax requests are not being cached.
I've read up on about 50-60 different articles on the web that say this should work.
$.ajax({
  type: "GET",
  cache: true,
  url: 'get.php',
});

but when I look in firebug or developer net tab. I keep seeing the page being loaded with a 200 response code which means it is loading a fresh new page instead of an older cached.
So to make the test even more basic, I added a blank separate page purely display a datetime, so I can see if it is being cached or not.
It did not work, datetime was still being updated.
So next I tried to set the headers like this on get.php:
$cache_length=600;

header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600));
header("Pragma: cache");
header("Cache-Control: max-age=$cache_length");
header("User-Cache-Control: max-age=$cache_length");
echo date('Y-m-d H:i:s');

That still doesn't cache it.
Then I tried this:
$.ajax({
  type: "GET",
  cache: true,
  url: 'get.php',
});

Still the same problem, no caching taking place
Then I also tried this, still no caching
$.ajaxSetup({ cache: true });
    $.ajax({
      type: "GET",
      cache: true,
      url: 'get.php',
    });
Then I tried this, still no caching
$.ajaxSetup({ cache: true });
$.ajax({
  type: "GET",
  cache: true,
  url: 'get.php',
});

So I am baffled why it won't cache it, when examples online seem to make it pretty simple to cache it by specifying cache:true.
No matter what i try, I am still seeing an updated time in get.php, make me believe that cache is still not working, but don't understand know why
How do I cache the page for one hour?

A: I think you are misunderstanding how the cache variable works.  The default value for cache is true, so you don't even have to set it.  It doesn't actually tell your browser or computer or server to cache anything.  The main purpose of the variable is to be able to set it to false so it forces the browser to not cache the page by way of adding "_={timestamp}" to the GET parameters.
Further explanation: http://api.jquery.com/jquery.ajax/
Keeping the value at true simply means the response will behave like any other page.


text:
Q: Как корректно передать значение День добрый, что-то понять не могу в чем проблема.
Через php передаю функцию
$k = 'a'.$k.$drot;
echo "
;
echo "
	";

функцию объявляю через
function  func(kok) {
 document.getElementById(kok).style.background = 'red';
 console.log(kok);
}

Когда запускаю и нажимаю на требуемый элемент мне пишет:
TypeError: document.getElementById(...) is null

В чем моя ошибка? Ведь по идее должно вывести значение переданной в функцию переменной kok и сменить цвет в элементе.
Начал только недавно учить js, просмотрел кучи сайтов, но так и не понял в чем проблема. Сама передаваемая переменная kok в массиве изменяется и каждый раз передается в функцию новая. Переменная $k всегда(!!!) имеет какое-то значение.

A: Вот такой код:
$k = 1;
$drot = 2;
$k = 'a'.$k.$drot;
echo "
";
echo "
	";

выводит:

              ^------ разные -----^

Думаю выводы вы сделаете сами, где вы делаете лишнюю конкатенацию

A: В общем разобрался в чем проблема. Не в неправильном идентификаторе как отметил товарищ Сергей выше, а в том что передаваемое в функцию значение не было заранее определено.
Было:
$x = 'A'.$k.$drot;

Решило проблему:
$x = '';
$x = 'A'.$k.$drot;

Не знаю почему, но после этого стало нормально видить переменную.


text:
Q: visualize numerical strings as a matrixed heatmap I'm trying to visualize a matrix of numerical strings, as a heatmap
Take this example, of 36 element length "History" numerical strings, and, say I have 6 rows (i actually have 500 rows). I want to visualize a heat map of a matrix of 6x36 "pixels or cells".  Additionally it would be great to sort or split them visually by True/False on the "Survive" variable.
    testdata=
       History                                Survive
    1  111111111111111211111111111111111111   FALSE
    2  111111111111111110000000000000000000   TRUE
    3  000111222111111111111111111111110000   FALSE
    4  111111111111111111111111100000000000   TRUE
    5  011231111111111111111111111111111111   FALSE
    6  111111234111111111111111110000000000   TRUE

A: Here is one idea. We can split the Histroy column and then created rowid and ID column to plot the data as a heatmap.
library(tidyverse)

testdata2 <- testdata %>% mutate(History = str_split(History, pattern = ""))

testdata3 <- testdata2%>%
  rowid_to_column() %>%
  unnest() %>%
  group_by(rowid) %>%
  mutate(ID =row_number())

p <- ggplot(testdata3, aes(x = ID, y = rowid, fill = History)) +
  geom_tile(color = "black") +
  scale_fill_brewer() +
  scale_y_reverse() +
  labs(x = "", y = "") +
  theme_minimal()

print(p)

If we want to plot the data as facets by TRUE and FALSE in the Survival column, we need to create the rowid separately as TRUE and FALSE for Survival.
testdata4 <- testdata2%>%
  group_by(Survive) %>%
  mutate(rowid = row_number()) %>%
  unnest() %>%
  group_by(Survive, rowid) %>%
  mutate(ID = row_number())

p2 <- ggplot(testdata4, aes(x = ID, y = rowid, fill = History)) +
  geom_tile(color = "black") +
  scale_fill_brewer() +
  scale_y_reverse() +
  labs(x = "", y = "") +
  theme_minimal() +
  facet_grid(~ Survive)

print(p2)

Data
testdata <- read.table(text =
    "  History                                Survive
    1  111111111111111211111111111111111111   FALSE
    2  111111111111111110000000000000000000   TRUE
    3  000111222111111111111111111111110000   FALSE
    4  111111111111111111111111100000000000   TRUE
    5  011231111111111111111111111111111111   FALSE
    6  111111234111111111111111110000000000   TRUE",
    header = TRUE, stringsAsFactors = FALSE,
    colClasses = c("numeric", "character", "logical"))


text:
Q: How did "biscuit" come to have a distinct meaning in North American English? The Oxford Living Dictionary makes a clear distinction between the usage of biscuit in Britain and North America:

British: A small baked unleavened cake, typically crisp, flat, and sweet.
  'a chocolate biscuit'
North American: A small, soft round cake like a scone.

When I hear biscuit being used in a British context, it usually refers to a confection (what Americans call cookies).  In a U.S. context, it never refers to a confection. [See also: Biscuits & Gravy]
Why did this distinction come into being?

A: A minor addition to other answers:
If we accept a common meaning including something we might unambiguously call hardtack, i.e. a hard unleavened bread, we can consider from a culinary point of view what may have happened since then. The quotes from and referring to Franklin in RaceYouAnytime's answer dates such a meaning to the 18th century.
Modern meanings include both unleavened and leavened products. Recipes calling for yeast are rare and mainly modern, so most of the leavened interpretations rely on chemical raising agents (baking powder or baking soda). According to Wikipedia , these date from the early 19th century. The addition of baking powder would make a softer, more porous dough that wouldn't keep as well as a hard biscuit, but this wouldn't matter except when travelling, and would be more pleasant to eat in quantity. So someone making a sort of raised biscuit for sale as a staple food might expect to do quite well, and this would them become popular.
Mrs Beeton, writing in mid-19th-century London, has several recipes in her famous book fitting the British definition of biscuits, that is unleavened, hard and made mainly from flour and butter.  She also includes some with beaten eggs that are clearly lighter, and some recipes which use the terms biscuit and cake almost interchangeably.  Most contain sugar except "SIMPLE HARD BISCUITS...These biscuits are very nice for the cheese course." One recipe stands out though:

SODA BISCUITS.

*INGREDIENTS.—1 lb. of flour, 1/2 lb. of pounded loaf sugar, 1/4 lb. of fresh butter, 2 eggs, 1 small teaspoonful of carbonate of soda.

Mode.—Put the flour (which should be perfectly dry) into a basin; rub
in the butter, add the sugar, and mix these ingredients well together.
Whisk the eggs, stir them into the mixture, and beat it well, until
everything is well incorporated. Quickly stir in the soda, roll the
paste out until it is about 1/2 inch thick, cut it into small round
cakes with a tin cutter, and bake them from 12 to 18 minutes in rather
a brisk oven. After the soda is added, great expedition is necessary
in rolling and cutting out the paste, and in putting the biscuits
immediately into the oven, or they will be heavy.
Time.—12 to 18 minutes. Average cost, 1s.
Sufficient to make about 3 dozen cakes. Seasonable at any time.

[italics mine]
The warning or they will be heavy clearly implies they're meant to be light, and the recipe is similar to scones or (US) biscuits (though Mrs Beeton's dough is drier and uses less baking soda).
Having made the recipe (pictured below) these are indeed softer than a shortbread or similar plain biscuit, like a denser (and rather sweet) scone, or a dense, sweet version of the American biscuit. This is a very different softness to a soft cookie. These soda biscuits can be regarded as intermediate between the two current meanings, giving us an idea of when the meanings were more fluid.

There are parallels with the history of Irish soda bread, and Wikipedia's article on biscuit (bread) is also worth a read.  Both of these sources discuss the suitability of certain American wheats for quick breads.  There's a long history of the same word ending up with different meanings either side of the Atlantic; flapjack is a related example, but  we can also consider elk or robin.

A: A look at early (pre-1800) English dictionaries points to a possible source of confusion early in the career of biscuit. Two dictionaries—Edward Phillips & John Kersey, The New World of Words: Or, Universal English Dictionary (1706) and John Kersey, Dictionarium Anglo-Britannicum: or, a General English Dictionary (1708)—have identical definitions for biscotin:

Biscotin, (F.) a sort of Confection made of fine Flower, the Whites of Eggs, Powder-Sugar, &c.

But John Kersey, A New English Dictionary; or, A Compleat Collection of the Most Proper and Significant Words, and Terms of Art commonly used in the English Language (1713) has this very different definition for bisket:

A Bisket, a sort of Bread.

At least superficially, the definition of biscotin might describe a type of modern English biscuit, while the definition of bisket might serve as a rough description of a modern American biscuit.
Thomas Dyche & William Pardon, A New General English Dictionary, third edition (1749) is the earliest dictionary I've been able to find that lists the spelling biscuit:

BISKET, BISCUIT, or BISQUET (S.) commonly understood of small cakes made by the confectioners, of fine flower, eggs, sugar, &c. also the bread carried to sea, is called sea biscuit.

This same definition appears in editions of Dyche & Pardon as late as the eighteenth edition (1781).
Next to weigh in is Samuel Johnson, A Dictionary Of The English Language (1755), with entries for biscotin and biscuit:

BISCOTIN, n. s. {French} A confection made of flour, sugar, marmalade, eggs, &c.
BISCUIT, n. s. {from bis, twice, Lat. and cuit, baked, Fr.} 1. A kind of hard dry bread, made to be carried to sea; it is baked for long voyages four times. [Cited examples:] The biscuit also in the ships, especially in the Spanish gallies, was grown hoary, and unwholesome. Knolles's History of the Turks. Many have been cured by abstinence from drink, eating dry biscuit, which creates no thirst, and strong frictions four or five times a day. Arbuthnot on Diet. 2. A composition of fine flour, almonds, and sugar, made by the confectioners.

From Johnson's remark that sea biscuits are baked for long voyages four times, we might conclude that a more suitable name for these items would be quadriscuits or tetriscuits. Richard Knolles, The Generall Historie of the Turkes (1603) does indeed contain the passage that Johnson quotes, but he spells the word bisket:

for all the water thereabout was most vnpleasant and exceeding brackish, so that both sicke and whole were glad when they could get a crab to quench the extremitie of their thirst : although the emperour did what he might to remedie these extremities, and much releese was in good time sent both from SICILIA and NAPLES : the bisket also in the ships, especially in the Spanish gallies, was growne hoarie and vnwholesome.

In fact, Knolles uses bisket five times in the course of his Historie—including this instance:

there was such a dearth in the Turks armie, that they were enforced to giue their camels bisket and rice, and when that failed, they gaue them their pack-saddles to eat, and after that pieces of wood beaten into pouder, and at the last the very earth : which dearth endured vntill they arriued at VAN.

It seems clear from this instance that Knolles used the term bisket for what much later in the United States came to be called hardtack. In pioneer days, land travelers as well as sea travelers commonly carried hardtack with them on long trips. Here is the entry for hardtack in The American Heritage Dictionary of the English Language, fifth edition (2010):

hardtack n. A hard biscuit or bead made with only flour and water. Also called sea biscuit, sea bread, ship biscuit.

Next, chronologically, in my dictionary survey comes Nathan Bailey, The New Universal English Dictionary, fifth edition (1760), which covers biscotin and bisket/bisquet:

BISCOTIN (Confect.) a confection made of fine flower, powder'd sugar, marmalade, the white of eggs, &c.
...
BISKET, BISQUET (with Confectioners) a composition of fine flower, eggs, sugar, &c.

The seventh edition of Bailey's New Universal English Dictionary (1776) further complicates the picture by adding a separate entry for bisquet:

BISCOTIN (Confect.) a confection made of fine flower, powder'd sugar, marmalade, the white of eggs, &c.
...
BISQUET (probably of bis, twice, and coctus, baked) a sort of hard baked-brad or cake.
BISQUET, BISKET (with Confectioners) a composition of fine flower, eggs, sugar, &c.

Conclusion
The history of bisket, biscotin, biscuit, and bisquet is quite convoluted. At various times before 1800, dictionaries have used all of these words to identify a confection made with flour, eggs, sand sugar (among other ingredients). But at other times before 1800, dictionaries have applied the words bisket, biscuit*, and bisquet to tiny rounds of hard-baked bread.
Under the circumstances—especially in view of the equivocal treatment of the word in Samuel Johnson's tremendously influential 1755 dictionary, it is hardly surprising that British English went one way with the word biscuit and North American English went the other.

A: An interesting anecdote appears in Benjamin Franklin's Autobiography.

Then I walked up the street, gazing about till near the market-house I met a boy with bread. I had made many a meal on bread, and, inquiring where he got it, I went immediately to the baker's he directed me to, in Second-street, and ask'd for bisket, intending such as we had in Boston; but they, it seems, were not made in Philadelphia. Then I asked for a three-penny loaf, and was told they had none such. So not considering or knowing the difference of money, and the greater cheapness nor the names of his bread, I bade him give me three-penny worth of any sort. He gave me, accordingly, three great puffy rolls

The story is described in the context of the English language in Speaking American: A History of English in the United States by Richard W. Bailey:

Biskit in New England was a collective noun like salt: "Please give me some of the bisket."
[...]
Bisket, a staple food in Franklin's native Boston, was an unleavened bread made from flower [sic], salt, and water, a food known later in American English as hardtack.  The contrast between the dry bread of Boston and the yeasty confection of Philadelphia is plain enough, but Franklin had more in mind with this anecdote.  Boston and Philadelphia spoke different kinds of English, and they do so to this day.

All of this goes to show that confusion about the meaning of "biscuit" in American English dates back quite far, and in fact other sources seem to suggest that the distinction dates back to early cooking habits of European migrants colonizing North America, where yeast was a rare commodity and unique methods of preparing dough for baking biscuits allowed for a kind of bread textured well for mixing with gravy, resulting in the common dish "biscuits and gravy," which became a popular dish in the U.S. after the American Revolutionary War.
In essence, it seems that this method of baking was cheap, efficient, and provided a hearty breakfast to agricultural workers in the American South, where these fluffy biscuits were a common breakfast food.  Judging from the sort of confusion illustrated in Franklin's story about ordering a "bisket," it seems unsurprising that a term for one kind of baked good could be appropriated to refer to another.
For what it's worth, the OED points out with uncharacteristically judgmental language that the modern spelling "biscuit" was only adopted in the 18th century.  Previously both the English and American pastries were commonly spelled bisket:

The regular form in English from 16th to 18th cents. was bisket, as still pronounced; the current biscuit is a senseless adoption of the modern French spelling, without the French pronunciation.


text:
Q: Interjection after completing a difficult task What interjection a native English speaker might use after completing a difficult task? Something like "oof", "ooh", etc.

______! It's been a tough day!
______! Running a marathon is not easy!
______! I think I've finally solved this puzzle

A: "Phew" (mentioned in a comment above) is probably the most common interjection for such a situation. M-W says that it is "used to express relief or fatigue". Oxford Learner's Dictionaries says that it can show that someone is "happy that something bad has finished" and gives this example:

"Phew, I'm glad that's all over."

Other interjections are also possible but are more commonly used for other purposes. For example, "oh", "Jesus", and "wow" are frequently used to express shock or surprise. ("Oh" can also indicate pain or distress, as in "oh, my back!", which might be appropriate after some difficult tasks.)

A: There are many possible words. "Phew", "Wow", "Oh", many others. Almost any obscenity would fit.


text:
Q: Format null DateTime in DataGridView WinForm how to format null datetime in datagridview?
I create the datagridviewcolumn programmatically, in the form load
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.Format = "dd-MM-yyyy";

DataGridViewTextBoxColumn updatedDateColumn = new DataGridViewTextBoxColumn();
updatedDateColumn.DataPropertyName = "UpdatedDate";
updatedDateColumn.HeaderText = "Updated Date";
updatedDateColumn.Name = "UpdatedDate";
updatedDateColumn.DefaultCellStyle = style;

the problem is when the update date value is null
datagridview display 01/01/0001 12:00:00
I've tried to edit
style.NullValue = string.Empty;

but it didn't work
how to solve this?
thanks

A: You can use ISNULL to set null date to null in sql server and set the NullValue property of datagridviewCellStyle to string.Empty ; like this one in sql server
ISNULL(DateColumnName , NULL) and set style.NullValue = string.Empty

in dataGridViewCellStyle


text:
Q: Visual Studio Pro 2013 - Intellisense only works on pages with code-behind I've installed Visual Studio Pro 2013.  No complaints except that intellisense won't work on pages that have .Net code.  If I have a page with a separate code-behind page, then no problem.  I have tried deleting the solution file, reboot VS 2013.  I've tried a number of different projects and it's the same.  Any ideas?

A: I had the same issue and it was fixed by resetting user settings.
Try to reset user settings win+r devenv.exe /resetuserdata


text:
Q: Resize all components in layeredPane at once retaining relative position and size I have made a GUI using Swing and layeredPanes, specifying dimensions and (x,y) co-ordinates of about 60 items. The JFrame dimensions I set are (1080, 720) but I need now to rescale the whole lot to fit (800, 600).
Is there a quick way of resizing the whole screen so all images and text retain their position and relative size without going through every component and re-specifying its setBounds(x, y, width, height)?

A: You could add a ComponentListener to your JLayeredPane, and then in the
void componentResized(ComponentEvent e)
you could rescale everything based on the current height and width to maintain a specific ratio. You could just do some math some simple math to get the difference ratio between say, 720 and your current width, then adjust the width of each of your components to their actual width times this ratio.
Then do the same for height. This way everything would maintain aspect ratio.
I would also store each component in a List to access them more easily.
EDIT: I just re-read your question:

without going through every component and re-specifying

I forgot about this while answering, and I don't think there is a simple way of doing it without going through all of them. But there are simple ways of looping through them tho!


text:
Q: Pass the view that manages something to the second view - Backbone I have two views, one for rendering google maps and another to render list of events that contain's latitude and longitude to render markers on the view that contains google maps. When I try to pass the view that manages the map to the initialize method of the second view and save an instance reference, display in console the following error:

Here's my code
app.js
var ev = new Application();

ev.Router = Backbone.Router.extend({

    routes: {
        "": "home",
        "evento/:id" : "evento"
    },

    home: function(){
        var mapView = new ev.views.Home();
        $('#home').html(mapView.el);
        $('#rightcolumn').html(new ev.views.Home_Eventos(mapView).el);
    },

    evento: function(id){
        $('#rightcolumn').html(new ev.views.Evento(id).el);

    }
});

$(document).on('ready', function() {
    // Load HTML templates for the app
    ev.templateLoader.load(['shell', 'home', 'home_list_eventos', 'evento'], function () {
        ev.shell = new ev.views.Shell({el: "#shell"});
        ev.router = new ev.Router();
        Backbone.history.start();
    });
});

home.js
ev.views.Home = Backbone.View.extend({
    map: 'null',
    initialize: function(){
        this.template = _.template(ev.templateLoader.get('home'));
        this.render();
    },

    initMap: function(){

        var that = this;
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos;
                pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                var infowindow = new google.maps.InfoWindow({
                    map: that.map,
                    position: pos
                });

                that.map.setCenter(pos);
            });
        }

        var mapOptions = {
            zoom: 12,
        };
        that.map = new google.maps.Map(that.$el.find('#map_canvas')[0],mapOptions);
        google.maps.event.addDomListener(window, "resize", function() {
            var center = that.map.getCenter();
            google.maps.event.trigger(that.map, "resize");
            that.map.setCenter(center);
        });
    },

    render: function(){

                this.$el.html(this.template());
                this.initMap();
                return this;
    }
});

home_events.js
ev.views.Home_Eventos = Backbone.View.extend({
    initialize: function(mapView){
        this.template = _.template(ev.templateLoader.get('home_list_eventos'));
        this.mapView = mapView;
        console.log(this.mapView.map);
        this.render();
        console.log("sou inicializado");
    },

    render: function(){

        var that = this;
        var imagens = new ev.models.ImagemCollection();
        imagens.fetch({
            success: function(){
                that.$el.html(that.template({imagens: imagens.models}));

                var marcadores = imagens.models;
                setTimeout(function() {
                _.each(marcadores, function(marcador){
                    var myLatlng = new google.maps.LatLng(marcador.get('latitude'),marcador.get('longitude'));
                    var marker = new google.maps.Marker({
                        position: myLatlng,
                        map: map,
                    });

                });
                    }, 6000);

                return that;
            }
        });
    }

});

Templates of document:
shell.html:

    ...

home.html:

            <form role="form">

                    Pesquise
                    <input type="text" class="form-control" id="pesquisar" placeholder="Pesquisar...">

                    Quando
                    <input type="text" class="form-control" id="quando" placeholder="Quando">

            </form>

            <form role="form">

                    Onde
                    <input type="text" class="form-control" id="pac-input" placeholder="Onde">

                    Género
                    <input type="text" class="form-control" id="genero" placeholder="Genero">

            </form>

            <button id="search" type="button" class="btn btn-primary botao">Pesquisar</button>

            <button type="button" class="btn btn-danger botao">Mais Filtros</button>

                <% _.each(imagens, function(imagem){  %>

                        <img src="<%= imagem.get('imagem') %>" class="img-responsive  back" alt="Responsive image">
                        <a href='#evento/<%= imagem.get('id') %>' class="btn btn-primary">Ver Mais

                <% }); %>

A: You initialize new ev.views.Home_Eventos(mapView) as a parameter to $.html(), which is fine except that the render function in that view is 'async' because of the fetch in it. So the el it returns should be an empty
 since the success callback doesn't return until after the initialize is complete.


text:
Q: Is $L^p\cap L^q$ a real intersection? For $p\neq q$, is the notation $L^p\cap L^q$ a set-theoretic intersection, or an intersection taken with respect to some topological embeding ? Since $L^p$'s elements are equivalence classes, I am not sure that such [classes of] functions live in the same "space" (strictly speaking).
Thanks for answers :)


text:
Q: Solving a matrix of the form $XA = cX$ I am trying to solve a matrix of the form $XA = cX$ where $A$ is a square matrix of size $N$ with known values and $c$ is a scalar representing the largest eigenvalue of matrix $A$ (though I would think a solution would hold for any scalar). $X$ is a $1 x N$ row vector of variables. I want to solve for the values of $X$
$A$ is the infinitesimal generator for a continuous time markov chain and what I am trying to accomplish here is solving for the system of linear equations (of the form described above) that characterize the steady-state solution.
My thoughts so far:

*

*We can write $B$ = $A/c$ to move the scalar to the left hand side

*$XB = X$ can be written as $B'X = X$ where $B'$ is the transpose of $B$

*$B'X = X$ can be written as $(B'-I)X = 0$, where $I$ is the identity matrix of size $N$

A: You can simply write:
$XA=cI_NX$
Where $I_N$ is the identity matrix:
$XA=X(cI_N) \Rightarrow X(A-cI_N)=0 \Rightarrow (A-cI_N)^t X^t=0 $
Since $c$ is an eigenvalue of $A$($\det(A-cI_N)=\det(A-cI_N)^t=0$) and the system is homogeneous, it admits non-trivial solutions.Notice that:
$(A-cI_N)^t=(A^t-cI_N)$. So the system becomes:
$(A^t-cI_N) X^t=0 $
So $X^t$ has to be in the eigenspace of the eigenvalue $c$ of the matrix $A^t$. I think nothing more can be said(if $c$ is not an eigenvalue of $A$ there aren't non-trivial solutions)


text:
Q: Using Unirest Library with Xcode I am trying to get this simple request to work but i get 2 errors in Xcode.
Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_UNIRest", referenced from:
      objc-class-ref in ViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
    NSDictionary* headers = @{@"accept": @"application/json"};
    NSDictionary* parameters = @{@"parameter": @"value", @"foo": @"bar"};

    UNIHTTPJsonResponse *response = [[UNIRest post:^(UNISimpleRequest *request) {
      [request setUrl:@"http://httpbin.org/post"];
      [request setHeaders:headers];
      [request setParameters:parameters];
    }] asJson];


text:
Q: How to access Vuex store modules in vue router? Here is the code:
// store.ts
export type Store = AuthStore<Pick<RootState, 'auth'>>;
export const store: Store = createStore({
  modules: {
    auth
  }
})

And the router:
import { store } from '@/store'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    beforeEnter: (to, from) => {
      return store.state.auth.common.isLoggedIn
    }
  }
]

When I write store.state.auth.common.isLoggedIn TS says that there is no common property in auth. I checked a lot of questions on StackOverflow but nothing worked. How can I access properties in store modules with no TS errors?


text:
Q: MySQL Count and Convert Row to Colum Involve One Table Only I have a table name histories that record user activities which consists of user_id, branch_id and duration.
The table look like this:
+++++++++++++++++++++++++++++++++++
id | user_id | branch_id | totHours
+++++++++++++++++++++++++++++++++++
|1 |   100   |     1     |    1   |
|2 |   199   |     1     |    1   |
|3 |   121   |     1     |    1   |
|4 |   140   |     1     |    1   |
|5 |   103   |     2     |    3   |
|6 |   107   |     2     |    1   |
|7 |   299   |     1     |    2   |
|8 |   209   |     2     |    2   |
|9 |   119   |     1     |    5   |

I would like to produce an output like this:
+++++++++++++++++++++++++++
Hours | Branch A | Branch B
+++++++++++++++++++++++++++
|1    |    4    |     1   |
|2    |    1    |     1   |
|3    |    0    |     1   |
|4    |    0    |     0   |
|5    |    1    |     0   |

I try make it using this query, but when i use group by on totHours column only, it return error because i need to include the branch_id in the group by.
Here is my query:
select totHours as Hours,
   coalesce(case when branch_id = 1 then count(totHours) else 0 end) as 'Branch A',
   coalesce(case when branch_id = 2 then count(totHours) else 0 end) as 'Branch B'
from histories
group by totHours, branch_id;

And if the totHours is not in the table (for example in this table 4), it will display 0 for both branch column.
Here is my db fiddle
Update: MySQL version 5.7.22

A: If you're using MySQL version 8+ (or any version support windows function), you can make use of the recursive common table expression to generate the hour values for you then LEFT JOIN table histories with it. After that you can do SUM() with CASE expression in SELECT to generate your expected output:
WITH RECURSIVE hours AS (
    SELECT 1 AS hr, MAX(totHours) AS maxth FROM histories UNION ALL
    SELECT hr+1, maxth FROM hours WHERE hr+1 <= maxth)
SELECT hours.hr,
       SUM(CASE WHEN histories.branch_id=1 THEN 1 ELSE 0 END) AS Branch_A,
       SUM(CASE WHEN histories.branch_id=2 THEN 1 ELSE 0 END) AS Branch_B
FROM hours
 LEFT JOIN histories
 ON hours.hr=histories.totHours
GROUP BY hours.hr;

If you're using version that doesn't support window function, you can create a subquery to represent the hours (including missing hour). This is a hard-coding approach where you may have to always update the subquery to include new hour value (if any):
SELECT hours.hr,
       SUM(CASE WHEN histories.branch_id=1 THEN 1 ELSE 0 END) AS Branch_A,
       SUM(CASE WHEN histories.branch_id=2 THEN 1 ELSE 0 END) AS Branch_B
FROM
    (SELECT 1 hr UNION
      SELECT 2 UNION
      SELECT 3 UNION
      SELECT 4 UNION
      SELECT 5) AS hours
 LEFT JOIN histories
 ON hours.hr=histories.totHours
GROUP BY hours.hr;

Demo fiddle
Edit the hours subquery to add more, for example if you want until 7, you just add:
(SELECT 1 hr UNION
      SELECT 2 UNION
      SELECT 3 UNION
      SELECT 4 UNION
      SELECT 5 UNION
      SELECT 6 UNION
SELECT 7) AS hours

to the subquery. Another way is to define the hours beforehand and create a reference table. Let's say you estimate the hour to be until 100, then it's better if you create a table that stores 1-100 as reference for the LEFT JOIN


text:
Q: In Makefile, run a dummy target (first) if other targets out of date (or run recipe before dependencies) (using GNU make)
I have a Makefile with default target being responsible for 'compiling' code.  I than have run_test target that executes tests but will recompile if required.
I want to clear a log file before any compilation steps are run, but only if compilation steps are run, so not if just a test runs.  I defined a reset_log target to clear the logs.  The behaviour I want is:

*

*make all when all up to date - nothing runs, logs not cleared

*make all when not up to date - logs cleared, then appropriate compile rules run

*make run_test when all up to date - nothing compiles, logs not cleared, tests run

*make run_test when not up to date - logs cleared, then appropriate compile rules run, then tests run

How do I get the reset_log target (or equivalent commands) to run only when compilation must occur, but before any dependency recipe runs?  Here is simplified Makefile:
LOG_FILE = file.log

all: compile

compile: final.out

reset_log:
    -rm -f $(LOG_FILE)

final.out: final.in reset_log 1.out 2.out
    cp -v final.in final.out | tee -a $(LOG_FILE)

1.out: 1.in
    cp -v 1.in 1.out | tee -a $(LOG_FILE)

2.out: 2.in
    cp -v 2.in 2.out | tee -a $(LOG_FILE)

run_test: compile
    @echo "======= Run Test Here ======="

clean:
    -rm *.out $(LOG_FILE)

.PHONY: local_target reset_log run_test clean

NOTE: this example does not work (reset_log and final.out targets get rerun every time, because reset_log is a dependency of final.out and in itself has no dependency), but demonstrates where I would want reset_log to be run.
One possible solution would be to have a way to run a recipe for a target out of date before the dependency recipes are run.

Update 2016-10-18
Based on user657267's solution (and the minor improvement I suggested in a comment), here is a re-code of above example, i.e. the final solution to what I need:
LOG = file.log

all: compile

compile: $(LOG)

$(LOG): final.out
    mv $@.tmp $@ || ( echo "WARNING: $< not found. Creating dummy $@ to allow make to run" > $@ )

final.out: 1.out 2.out

%.out: %.in
    cp -v $< $@ | tee -a $(LOG).tmp

run_test: compile
    @echo "======= Run Test Here ======="

clean:
    -rm *.out $(LOG)

.PHONY: run_test clean compile

A: Use a second temporary log file
log := file.log
out := final.out 1.out 2.out

.PHONY: run_test clean

$(log): $(out)
    mv $@.tmp $@

run_test: $(log)
    @echo "======= Run Test Here ======="

clean:
    $(RM) $(out) $(log)

%.out: %.in
    cp -v $< $@ | tee -a $(log).tmp


text:
Q: iPad SDK for 2D graphics and gui elements? Im looking for some sort of SDK or library on top of iOS, which might help me produce iPad/IPHONE games.
The sort of functionality Im looking for is..

*

*GUI elements, skinnable buttons, lists, dialog boxes etc

*Any routines to help with tile based games

*Functions to paint and move sprites

*Any vector libs to help with rotation, skew etc

Im confident I could write all this from scratch, but Im guessing theres some libraries already out there. Im not afraid of getting my hands dirty in code, so please dont slate me for asking for prebuilt stuff :)
Thanks

A: The defacto answer is cocos2d. Open source, MIT licensed, sprite library (including tiling map support baked in).
As for UI - Cocos has some helper utilities for dealing with UI elements, however its not very hard to skin UIKit (though the more customization you do the more drawing code you end up with).

A: most of the bits are already available in UIKit, but http://www.cocos2d-iphone.org/ is a framework worth looking at for game dev.

A: Two notes about cocos-2d:
- cocos has its own implementation of UI control called MenuItem. It can be used to easily emulate the behaviors of Buttons. There is also a simple layout algorithm to dispose this items in columns, rows, grids. There are also other controls that allow you to display text on the screen (labels). No text editors though, AFAIK.
- cocos can be easily integrated with the rest of UIKit, so it is simple to show standard "message boxes", some UIKit elements on top or behind it. I was able to use the cocos view as the child view of a UIImagePicker, for example.


text:
Q: Spring Cloud DataFlow and Kafka Security Is it possible to configure authentication for Spring Cloud DataFlow for Apache Kafka?
Where can I see examples?
Thanks.

A: The current GA release of Kafka binder in Spring Cloud Stream/Spring Cloud Data Flow is based on Kafka 0.8.2. The 0.9 release of Kafka includes security support and we have recently merged the 0.9 compatibility. We are yet to review the security capabilities, though. It'd be great if you can share your use-cases, so we can validate as part of our acceptance.
You can track the release progress here.


text:
Q: Same Typescript but utlizing different HTML View formats in Angular 8 I have a typescript form which gathers a Formbuilder data, and applies some logic to it. The customer came out with Requirement to attach a different HTML view to work with the logic. Is there optionality in Angular to keep copy the same back Typescript, but utilize a different HTML?
say this is in,
app-mailing-address-ts.
want to replace the html with something else,
  public electronicsFormChangeEvent(electronicsFormEvent) {
    this.productForm = electronicsProductEvent;
  }

  public furnitureFormChangeEvent(furnitureFormEvent) {
    this.productForm = furnitureProductEvent;
  }

  public groceryFormChangeEvent(groceryFormEvent) {
    this.productForm = groceryFormEvent;
  }

  public bookFormChangeEvent(bookFormEvent) {
    this.productForm = bookFormEvent;
  }

  public carFormChangeEvent(carFormEvent) {
    this.productForm = poBoxFormEvent;
  }

  public calculateTotalAmount() {
    if (this.productForm == 'Furniture') {
        this.TotalAmount = UnitAmount * Quantity
        ......
        .....
    }
    this.calculateTotal = true;
  }

A: Yes in Angular you have different ways to share code.
There are pipes and constants and the most common:  services. You want to inject a shared service that contains the common code into two different components, the components will define the different HTML templates.

A: You can create Singleton service for common code.
https://angular.io/guide/singleton-services
How to create a common service throughout the app in angular4
If you need to create shared component that can be used in Template Driven Form and Reactive Form.  Here is good example
https://codeburst.io/how-to-create-shared-components-in-angular-template-driven-and-reactive-form-ddb095cc7904


text:
Q: Cannot return a public list as the return type of a method So I have a public class like below that also has another nested public class inside it
public class OuterClass
{
   // other stuff
   public class InnerClass
   {
      // some public get set properties
   }

   public List<InnerClass>  InnerClasses;
}

Then in my repository I have a method like this:
public InnerClass.InnerClasses MyGetMethod()
{
   // go get stuff from DB
}

BUT it doesn't allow me do that! I can't use InnerClass.InnerClasses as the type of that method.  Why?

A: InnerClasses is field in your class, so it can't be used like a type.
You probably want OuterClass.InnerClass as your output type or List<OuterClass.InnerClass>:
//public OuterClass.InnerClass MyGetMethod()
public List<OuterClass.InnerClass> MyGetMethod()
{
    // go get stuff from DB
}


text:
Q: how to reset a filter by leaving it empty? I have a filter on a list :
<input ng-model="searchFileName" />

        {{ file.name }}

I would like to clear searchFileName value when I click on a result.
This is openFolder function :
$scope.openFolder = function(name) {
    $scope.searchFileName = null;

    $http.jsonp($scope.server + '?open=' + encodeURIComponent($scope.buildTreePath()) + '&callback=JSON_CALLBACK').success(function(data){
        $scope.folders = data;
    });
}
}

I can't empty my filter field, it doesn't work... Where am I wrong ?

A: just use:
  $scope.openFolder = function(name) {

    $scope.searchFileName = null;
  }

var app = angular.module('app', []);

app.controller('fCtrl', function($scope) {

  $scope.folders = [

    {
      name: "Ala"
    }, {
      name: "Ata"
    }, {
      name: "Ara"
    }, {
      name: "Ama"
    }

  ];

  $scope.openFolder = function(name) {

    $scope.searchFileName = null;
  }

});

    <input ng-model="searchFileName" />

        {{ file.name }}


text:
Q: Why is "throws Exception" necessary when calling a function? class throwseg1
{
    void show() throws Exception
    {
        throw new Exception("my.own.Exception");
    }

    void show2() throws Exception  // Why throws is necessary here ?
    {
        show();
    }

    void show3() throws Exception  // Why throws is necessary here ?
    {
        show2();
    }

    public static void main(String s[]) throws Exception  // Why throws is necessary here ?
    {
        throwseg1 o1 = new throwseg1();
        o1.show3();
    }
}

Why compiler reports that methods show2(), show3(), and main() have

unreported exception Exception that must be caught or declared to be thrown

when I remove throws Exception from these methods?

A: The throws Exception declaration is an automated way of keeping track of methods that might throw an exception for anticipated but unavoidable reasons.  The declaration is typically specific about the type or types of exceptions that may be thrown such as throws IOException or throws IOException, MyException.
We all have or will eventually write code that stops unexpectedly and reports an exception due to something we did not anticipate before running the program, like division by zero or index out of bounds.  Since the errors were not expected by the method, they could not be "caught" and handled with a try catch clause.  Any unsuspecting users of the method would also not know of this possibility and their programs would also stop.
When the programmer knows certain types of errors may occur but would like to handle these exceptions outside of the method, the method can "throw" one or more types of exceptions to the calling method instead of handling them.  If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw. Since programs can have many layers of methods written by many different programs, it becomes difficult (impossible) to keep track of which methods might throw exceptions.
Even though Java has the ability to declare exceptions, you can still write a new method with unhandled and undeclared exceptions, and Java will compile it and you can run it and hope for the best. What Java won't let you do is compile your new method if it uses a method that has been declared as throwing exception(s), unless you either handle the declared exception(s) in your method or declare your method as throwing the same exception(s) or  if there are multiple exceptions, you can handle some and throw the rest.
When a programmer declares that the method throws a specific type of exception, it is just an automated way of warning other programmers using the method that an exception is possible.  The programmer can then decide to handled the exception or pass on the warning by declaring the calling method as also throwing the same exception.  Since the compiler has been warned the exception is possible in this new method, it can automatically check if future callers of the new method handle the exception or declare it and enforcing one or the other to happen.
The nice thing about this type of solution is that when the compiler reports Error: Unhandled exception type java.io.IOException it gives the file and line number of the method that was declared to throw the exception.  You can then choose to simply pass the buck and declare your method also "throws IOException".  This can be done all the way up to main method where it would then cause the program to stop and report the exception to the user.  However, it is better to catch the exception and deal with it in a nice way such as explaining to the user what has happened and how to fix it.  When a method does catch and handle the exception, it no longer has to declare the exception.  The buck stops there so to speak.

A: Exception is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception must handle or declare it.

A: Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.
For example:
class throwseg1 {
    void show() throws Exception {
        throw new Exception();
    }
}

Should be written as:
class throwseg1 {
    void show() {
        try {
            throw new Exception();
        } catch(Exception e) {
            // code to handle the exception
        }
    }
}

This way you can get rid of the "throws Exception" declaration in the method declaration.

A: In Java, as you may know, exceptions can be categorized into two: One that needs the throws clause or must be handled if you don't specify one and another one that doesn't. Now, see the following figure:

In Java, you can throw anything that extends the Throwable class. However, you don't need to specify a throws clause for all classes. Specifically, classes that are either an Error or RuntimeException or any of the subclasses of these two. In your case Exception is not a subclass of an Error or RuntimeException. So, it is a checked exception and must be specified in the throws clause, if you don't handle that particular exception. That is why you needed the throws clause.

From Java Tutorial:

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Now, as you know exceptions are classified into two: checked and unchecked. Why these classification?
Checked Exception: They are used to represent problems that can be recovered during the execution of the program. They usually are not the programmer's fault. For example, a file specified by user is not readable, or no network connection available, etc., In all these cases, our program doesn't need to exit, instead it can take actions like alerting the user, or go into a fallback mechanism(like offline working when network not available), etc.
Unchecked Exceptions: They again can be divided into two: Errors and RuntimeExceptions. One reason for them to be unchecked is that they are numerous in number, and required to handle all of them will clutter our program and reduce its clarity. The other reason is:

*

*Runtime Exceptions: They usually happen due to a fault by the programmer. For example, if an ArithmeticException of division by zero occurs or an ArrayIndexOutOfBoundsException occurs, it is because we are not careful enough in our coding. They happen usually because some errors in our program logic. So, they must be cleared before our program enters into production mode. They are unchecked in the sense that, our program must fail when it occurs, so that we programmers can resolve it at the time of development and testing itself.

*Errors: Errors are situations from which usually the program cannot recover. For example, if a StackOverflowError occurs, our program cannot do much, such as increase the size of program's function calling stack. Or if an OutOfMemoryError occurs, we cannot do much to increase the amount of RAM available to our program. In such cases, it is better to exit the program. That is why they are made unchecked.
For detailed information see:

*

*Unchecked Exceptions — The Controversy

*The Catch or Specify Requirement

A: package javaexception;

public class JavaException {
   void show() throws Exception
    {
        throw new Exception("my.own.Exception");
    }

void show2() throws Exception  // Why throws is necessary here ?
{
    show();
}

void show3() throws Exception  // Why throws is necessary here ?
{
    show2();
}
public static void main(String[] args) {

   JavaException a = new JavaException();

   try{
   a.show3();
   }catch(Exception e){
       System.out.println(e.getMessage());
   }
}

Only small changes in your program. What It seems to be misunderstood by many regarding the main issue, is whenever you throw exception you need to handle it, not necessary in the same place ( ex. show1,2,3 method in your program) but you must at first caller method inside the 'main'. in one word, there is 'throw', there must be 'catch/try', even if not same method where exception happens.

A: void show() throws Exception
{
    throw new Exception("my.own.Exception");
}

As there is checked exception in show() method , which is not being handled in that method so we use throws keyword for propagating the Exception.
void show2() throws Exception //Why throws is necessary here ?
{
show();
}

Since you are using the show() method in show2() method and you have propagated the exception atleast you should be handling here. If you are not handling the Exception here , then you are using throws keyword.
So that is the reason for using throws keyword at the method signature.

A: Basically, if you are not handling the exception in the same place as you are throwing it, then you can use "throws exception" at the definition of the function.

A: If you propagate the exception by declaring the throws directive in the signature of the current method, then somewhere up the line or call stack a try/catch construct must be used to handle the exception.


text:
Q: Linear Algebra - properties of positive semidefinite matrix Let $A=(a_{ij})$ be a positive semi-definite, symmetric matrix, of order $3\times 3$ satisfying:
$$
\Sigma_{j=1}^{3}  a_{ij}=0
$$
for $i=1,2,3$ (i.e.- the sum of each row is zero).
Prove:
$a_{ij}\leq 0, \quad \forall i\neq j$.
I know that $det(A)\geq 0$, and that the determinant of every principal submatrix is also nonnegative. I also know that the trace of every principal submatrix is nonnegative, which implies that the diagonal elements are nonnegative. But I wasn't able to use these properties in order to deduce the required claim.
Will you please help me with this?
Thank you very much

A: Are you sure?
Define the matrix $A$ as
$$A=\begin{pmatrix}1&-2&1\\-2&4&-2\\1&-2&1\end{pmatrix}.$$
Clearly, the matrix $A$ is symmetric and the sum of the coefficients of each of its rows is nil. Moreover, the eigenvalues of $A$ are $0$ (double eigenvalue), and $6$, hence $A$ is positive semi-definite.
Yet, $a_{13}=1>0$.