text:
Q: sendRedirect VS requestDispatcher.forward for error page? So there is an error.jsp page and I want user to occur on this page after he/she inputs invalid data.
Is it better to use sendRedirect or requestDispatcher.forward for redirecting to the error page?
I know, it may depend on whether I want to put some attributes to the request object and so on. And I'd prefer to use requestDispatcher.forward, but is it safe? Cause in this case after page refreshing the data will be sent to the server one more time. Yeah, it doesn't make any effect (insert, update, delete) on database since the data is invalid so the user occurs at the error page once again. But... idk, I feel like something is being wrong with the approach of using requestDispatcher.forward, even though it's kind of idempotent action.
So what do you think?

A: The important difference is :
The function sendRedirect  will send a 302 response code to browser, then the browser will send another request to server again
https://en.wikipedia.org/wiki/HTTP_302
but the function requestDispatcher.forward is a server internal redirection, The browser has no feeling about it !


text:
Q: What MAXDOP setting should be used for MS SQL Server 2012? I am getting a performance degradation error in one of my cluster production server. The error is like that

A significant part of sql server process memory has been paged out.
  This may result in a performance degradation. Duration: 0 seconds.
  Working set (KB): 608612, committed (KB): 1204128, memory utilization:
  50%.
A significant part of sql server process memory has been paged out.
  This may result in a performance degradation. Duration: 0 seconds.
  Working set (KB): 619280, committed (KB): 1226552, memory utilization:
  50%.

And My working Environment is like that
OS - Microsoft Windows Server 2012 R2 Standard
Hardware information - VMware, Inc, VMware Virtual Platform
Processors - Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz
Installed memory (RAM) - 4 GB

And MS SQL Server version is

Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) Dec 28 2012
  20:23:12  Copyright (c) Microsoft Corporation Standard Edition
  (64-bit) on Windows NT 6.2  (Build 9200: ) (Hypervisor)

After execution of this TSQL The  'max degree of parallelism' & 'max server memory' is like that
exec sp_configure 'max degree of parallelism';

Name                       minimum  maximum   config_value    run_value
max degree of parallelism     0     32767       1               1

exec sp_configure 'max server memory';

Name                       minimum         maximum        config_value    run_value
max server memory(MB)       128           2147483647     6144             6144

I have also gone through the StackExchange and found a similar question SQL Server R2 Standard Edition MAXDOP setting, but didn't get the proper answer there. That's why I ask the question.
And I am getting this error from yesterday (i.e; 27/12/2015).
Any suggestion will be appreciated.

A: Based on the message

A significant part of sql server process memory has been paged out. This may result in a performance degradation.

You might be having OS memory pressure - based on your RAM and MAX Memory configuration. Other causes might be leaking driver or incorrectly configured VMWARE especially - Brent has a good post on How to Set SQL Server Max Memory for VMware ?

The WHAT ?
From kb 2028324 -

SQL Server monitors the various memory related information about the SQL Server process. In this case it has detected that the working set of the process is less than 50% of the committed process memory. As a result this warning is printed. The normal causes of this warning are:

*

*The operating system pages out large portions of the the SQL Server committed memory to the paging file.

*This could be due to sudden increased demand for memory from other applications or operating system needs.

*This could also happen when certain device drivers request contiguous memory allocations for their needs.

Bob Dorr has written an excellent article on The SQL Server Working Set Message which is worth reading.

The WHY ?
Based on your sp_configure output, you have configured 6GB of max memory. Your installed RAM is ONLY 4GB ! <-- This is the problem
From BOL :

Recommendation :
Based on your workload, you should get more RAM and then set a good value for your MAX MEMORY. As per kb - 918483, you should enable LPM (Lock Pages in Memory).
Also, monitor the sys.dm_os_ring_buffers especially RING_BUFFER_RESOURCE_MONITOR for any low memory notifications - be it inside SQL Server as a process or from windows being under memory pressure.

RESOURCE_MEMPHYSICAL_HIGH - SQL can grow memory usage
RESOURCE_MEMPHYSICAL_LOW - System or internal physical memory - shrink
RESOURCE_MEM_STEADY
RESOURCE_MEMVIRTUAL_LOW  –  Virtual address range for SQL Server process is becoming exhausted.

Also, on a side note, unless the server instance is a sharepoint instance, you should configure a sensible MAXDOP setting.

A: Not sure, if looking MAXDOP initially for this error would be a good start towards troubleshooting, as it is more related to the memory being paged out.
You will need to focus more on the terms like Working set (KB): committed (KB): , Working Set trimming
There are couple of situations where SQL Server Process working set might be paged out by Windows despite these memory resource notification mechanism as explained here

1.If windows is not sending the correct notifications to all listening processes at the right moment and thresholds.
2.If SQL Server is not responding fast enough to the low memory resource notification from Windows
3.When low physical memory notification is received by SQL Server it will scale down its memory usage by trimming internal caches. This
  effect is applied for 5 seconds and then paused for 1 minute. This is
  to avoid any hungry/faulty application to consume all the memory
  making SQL Server to  scale its usage continuously. If low memory
  conditions still exist after 1 minute pause, the effect is applied
  again. So if there is physical memory pressure even after SQL Server
  scaling its usage for 5 seconds windows will still page out SQL
  Server's working set.
4.Conditions in Windows where working sets of all processes are trimmed
5.Windows might decide to trim a certain percentage of working set of various or specific processes

Therefore, i believe you need to gather and collect more data on memory usage with help of memory performance counters and see if there is any process which caused so.
Also, the system being on very low memory end, i.e 4 GB (not sure of the load o n you're system), try analyzing the load and cap the MAX server memory settings accordingly.
Additionally consider using the Lock pages in memory privilege. Here to note is that it protects only the Buffer Pool from paging and Non-Bpool allocations can still be paged out.

A: Your error seems more related to memory pressure. Maxdop is a CPU setting.
The Max degree of parallelism is heavily depending on your queries and your needs. You need to try it out. What should know is the following:

*

*MAXDOP default is 0, which means ALL cores will be used IN CASE the query goes in parallel

I think you have 8 cores in your CPU E5-2670 0 @ 2.60GHz , correct?
I would try out MAXDOP settings of 2 and 4 and check how fast your parallel queries go.
tip: you can add the maxdop setting as a query hint by appending
OPTION (MAXDOP 1)

to your T-SQL code.
But also you should understand how to check if you are under memory pressure.
You have only 4 GB of memory, which seems very low, understanding that these 4 GB are also for the operating system.
Since I can't explain it better than Brent, here is a link which may help you understanding whether you are under memory or not.
brent ozar memory pressure
Good Luck :)

A: MAXDOP can not solve this problem you need more RAM

redpajama_set_name: RedPajamaStackExchange


text:
Q: Date formats in ActiveRecord / Rails 3 In my model, I have a departure_date and a return_date.
I am using a text_field instead of the date_select so that I can use the JQuery datepicker.
My app is based in the US for now but I do hope to get international members.
So basically this is what is happening.  The user (US) types in a date such as 04/01/2010  (April 1st).
Of course, MySQL stores it as a datetime such as 2010-04-01...
Anyway, when the user goes to edit the date later on, it shows "01/04/2010" because I am using a strftime("%m/%d/%Y) which doesn't make sense....so it thinks it is January 4th instead of the original April 1st.
It's like the only way to accurately store the data is for the user to type in: 2010-04-01
I hope all of this makes sense.  What I am really after is a way for the user to type in (or use the datepicker) a date in their native format.
So someone in Europe could type in 01/04/2010 for April 1st but someone in the US would type in 04/01/2010.
Is there an easy, elegant solution to this?
Thanks for any suggestions.

A: I have been confronted to the same issue lately.
My website is based in france, so i have to store date as a french date.
I also use a Jquery DatePicker.
To do this, i set the I18n.locale to the visitor's country. For exemple :
I18.locale = :fr

You can do this with a before_filter into your application_controller
Then, into your locales/fr.yml you can define the way you want to show the date
And finally, into your view, you can set the date format view, with the JqueryDatePicket properties.
If i remember well, this methode was something like that:
$.datepicker.formatDate('dd-mm-yyyy');

You can find it anyway on the datepicker documentation.
And this format can be found for exemple into your locale/fr.yml
And that's all !
Hope this will help !


text:
Q: image dispaly fail SOOMETIMES with QT&&VS in C++ connect(myThread2, SIGNAL(label_display1()), this, SLOT(display_camera1()));
void MainWindow::display_camera1()
{
            QImage* QmyImage = new QImage();
        //判断是黑白、彩色图像
        if (myImage1->channels()>1)
        {
            //将myImage1中的数据传给QImage
            *QmyImage = QImage((const unsigned char*)(myImage1->data), myImage1->cols, myImage1->rows, QImage::Format_RGB888);
        }
        else
        {
            *QmyImage = QImage((const unsigned char*)(myImage1->data), myImage1->cols, myImage1->rows, QImage::Format_Indexed8);
        }

        *QmyImage = (*QmyImage).scaled(ui->imageView1->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        //显示图像
        ui->imageView1->setPixmap(QPixmap::fromImage(*QmyImage));
        delete QmyImage;
        QmyImage = NULL;
}

There are 2 display() signals. One image is displayed well but the other is not. When the .exe runs for a time(maybe 4 hours),the screen where should show the image begins to be grey.But the threads run well. The display is the only problem.
Do you have some experience like this or some steps to deal with it?Thank you.


text:
Q: SQL BulkCopy vs OPENDATASOURCE which one is faster I want to insert  data into sqlserver from access .mdb file,
which is the fastest way to perform the data inserts SQL BulkCopy or OPENDATASOURCE using OLEDB.
Data would be like 100,000s of records for about 20 tables.
Thanks.
I am doing this from c# code,where i need which one performs better,I am not able to compare because OPENDATASOURCE is asking for admin permissions.

A: In my Opinion the very best insert performance for inserting large volumes of data can be attained by using SQL Bulk Copy as this method bypasses the SQL query language entirely and streams data directly to SQL.
Further Performance Improvements

*

*By defaults SqlBulkCopy uses row locks during the bulk copy operation. If TableLock option in the SqlBulkCopyOptions is specified, it obtains a bulk update lock for the duration of the bulk copy operation and performance will be improved.

*Clustered Table: if it is feasible, the best way to load it is to remove the clustered index.

*Indexes: Indexes create huge problems with the parallelism so is it always a good
idea to load without any indexes active

You may read more on Whitepaper: performance of SqlBulkCopy http://www.sqlbi.com/wp-content/uploads/SqlBulkCopy-Performance-1.0.pdf

A: have you tried importing data to sql database from access file?
Database->Tasks->Import, Microsoft Access as data source, mdb file as parameter
If you want to do this via C# then you should consider using User Defined Table Types with stored procedures.


text:
Q: Automatically add #pragma once to header files I try to remove every unnecessary boilerplate code from my personal projects. The first thing, I have noticed, is first line of every header files #pragma once. Not so surprising.
However, I would like to ask my compiler (clang SVN HEAD version) to automatically add this line to my header files (for example with a pattern like this: src/*.hpp). I think there are very rare cases when you actually want to include one header multiple times.

*

*Do you agree?

*Is there any existing solution for this problem?

*Do you think this is a good idea?

With clang tools this issue can be solved, but I need some little help to start this extension.

*

*Which clang tool should I use?

Theoretical usage of this tool/extension:
clang --auto-pragma-once src/*.hpp src/*.cpp -o test
Thank you for any advice
EDIT:

*

*I do not want to store this pragma once in my file. So any editor or any other tools which place new things in the files are not working for this problem.

*This topic is about the one-time inclusion of header files, not the pragma once.

A: Just bite the bullet and put the pragma in your header files. It's only one line and if there is nothing, it might confuse others who look at your files.

A: I'm not sure why you'd want to use clang for this.  It depends
on the editor, but every editor I know allows you to trigger on
things like opening a new file whose name matches a specific
pattern, and insert boilerplate in it.  In industry, it's pretty
much forbidden not to use this, since that's how the copyright
notices get inserted.  In my case, for example, if I create
a new file with the name xyz.hh, the editor comes up with
/****************************************************************************/
/*      File:       xyz.hh                                                  */
/*      Author:     J. Kanze                                                */
/*      Date:       25/09/2013                                              */
/*      Copyright ....                                                      */
/* ------------------------------------------------------------------------ */

#ifndef xyz_hh_20130925QPIvFK6xMJYLBhSpv58ROPOU
#define xyz_hh_20130925QPIvFK6xMJYLBhSpv58ROPOU

#endif
//  Local Variables:                        --- for emacs
//  mode: c++                               --- for emacs
//  tab-width: 8                            --- for emacs
//  End:                                    --- for emacs
//  vim: set ts=8 sw=4 et filetype=cpp:     --- for vim

If I do this in my work domain, the copyright notice is
different, the include guards follow a different standard, and
there's also a #pragma once.


text:
Q: Why do we drop the abolute value bars when doing indefinite integration? Say, for instance, we're trying to solve $\frac{dy}{dx}=y\cos(x)$.
Separating the variables, we get: $$\int \frac{1}{y}dy=\int \cos(x) dx.$$
So $\ln|y|=\sin(x)+c \iff |y|=Ae^{\sin(x)}$ (where $A:=e^c$), yielding:
$$y=\pm Ae^{\sin(x)}$$, which is inconsistent with Wolfram Alpha's $y=Ae^{\sin(x)}$.
Now, I know that $A$ could be either positive or negative, but it's a constant, so it's either one or the other.
So, what I'm asking is: how can WA justify dropping the absolute value bars?
Thanks

A: $-Ae^{\sin x}$ is just $Ae^{\sin x}$ with a different $A$.

A: You have
$$
|y| = A\sin x = e^Ce^{\sin x}.
$$
The number $e^C$ is necessarily positive if $C$ is real.  Hence
$$
|y|= (\text{a positive constant}\cdot e^{\sin x}).
$$
From this it follows that
$$
y = (\text{a non-zero constant}\cdot e^{\sin x}).
$$
Then the question is why the value $0$ is allowed.  You'll notice that you divided by $y$ fairly early and you can't divide by $0$.  This method finds only non-zero solutions.  Whether the function in which the constant is $0$ is a solution can be checked separately by plugging it into the original equation.

A: What you wrote is not a good proof (divide by $y$: does it mean $y\neq 0$? what about the solution $y(x)=0$?).
A better one:
Theorem:
   the general solution of the equation $y'(x) = a'(x)y(x)$ on the interval $[a,b]$ is:
   $$y(x) = C\exp a(x), C\in\Bbb R$$
Proof: consider $x\to y(x) \exp(-a(x))$ and prove this is a constant.


text:
Q: How do you read JSON files in apache beam (dataflow) via python? I'm trying to read a JSON file via apache beam in python and apply some data quality rules over it.
Currently I'm using beam.io.ReadFromText to read each json line and use some functions to modify the data.
What would be a better way to read the JSON data and modify them ?
(p
  | 'Getdata' >> beam.io.ReadFromText(input)
  | 'filter_name' >> beam.FlatMap(lambda line: dq_name(line))
  | 'filter_phone' >> beam.FlatMap(lambda line: dq_phone(line))
  | 'filter_zip' >> beam.FlatMap(lambda line: dq_zip(line))
  | 'filter_address' >> beam.FlatMap(lambda line: dq_city(line))
  | 'filter_website' >> beam.FlatMap(lambda line: dq_website(line))
  | 'write' >> beam.io.WriteToText(output_prefix)  )

Note: I'm fairly new to this, I'm sorry if my current approach looks too shoddy of stupid.

A: You are approaching Apache Beam (Dataflow) from the wrong direction.
You are trying to read a line and then apply transforms to this line one at a time.
Instead, you need to look at Beam being a parallel processor. You will read in all the lines ReadFromText() and then apply transforms to each line in parallel.
Look into the function beam.ParDo(). This will allow you to create a class that can process each line of your JSON file. Your code would then have major steps like ReadFromText(), ParDo(MyJsonProcessor()), WriteToText().
Remember that your JSON will need to be Newline Delimited JSON. http://ndjson.org/

A: I think your pipeline is okay. It will run in parallel without any problem. FYI, if you use FlatMap just for filtering elements, you can also use Filter.


text:
Q: How to use the algorithm of dynamic programming to find out the optimal selection scheme of this knapsack problem? Take out a certain number of items from M items and put them in a bag with a space of W. the volume of each item is V1, V2 to Vn, and the corresponding value is P1, P2 to PN. The quantity of each item is N1, N2 to NN, which items can be put into the backpack to maximize the total value.
    name = {"A", "B", "C", "D", "E"}
    V = {91, 71, 105, 103, 96};
    P = {2.36, 2.12, 1.89, 3.77, 2.87};
    "N" = {3, Infinity, 5, Infinity, Infinity};
    W = 50;
KnapsackSolve[<|"A" -> {91, 2.36, 3}, "B" -> {71, 2.12},
  "C" -> {105, 1.89, 5}, "D" -> {103, 3.77}, "E" -> {96, 2.87}|>, 50]

In addition, I also require that $C$ and $D$ must be selected. The sum of $C$ and $D$ must be greater than or equal to 2 and less than or equal to 5.But the MMA built-in function KnapsackSolve mentioned above cannot add additional constraints. How to use the algorithm of dynamic programming to find the optimal collocation scheme satisfying all constraints.
Maximize[{91 x1 + 71 x2 + 105 x3 + 103 x4 + 96 x5,
  2.36 x1 + 2.12 x2 + 1.89 x3 + 3.77 x4 + 2.87 x5 <= 50,
  0 <= x1 <= 3 && 1 <= x3 <= 5 && 1 <= x4, 2 <= x3 + x4 <= 5}, {x1, x2, x3,
   x4, x5}, NonNegativeIntegers]

It is hoped that the result of dynamic programming algorithm can be consistent with that of MMA built-in function Maximize as much as possible.

A: W = 50;
V = {91, 71, 105, 103, 96};
P = {2.36, 2.12, 1.89, 3.77, 2.87};
ub = {3, Infinity, 5, Infinity, Infinity};

KnapsackSolve[Transpose@{V, P, ub}, W]
{3, 9, 5, 0, 5}

Using LinearProgramming we get the same result:
LinearProgramming[-V, {P}, {{W, -1}}, Thread[{0, ub}], Integers]

{3, 9, 5, 0, 5}

Constraints that specify lower bounds on item counts can be handled easily by changing the arguments. For example,
lb = {0, 0, 1, 1, 0}; (* items 3 and 4 should be included in the knapsack *)

lb + KnapsackSolve[Transpose@{V, P, ub - lb}, W - P.lb]

{3, 14, 5, 1, 0}

which is the same as LP solution under the same constraints:
LinearProgramming[-V, {P}, {{W, -1}}, Thread[{lb, ub}], Integers]

{3, 14, 5, 1, 0}

Similarly, to add an additional constraint that requires having exactly 1 unit of item 2 in the solution we make the lower and upper bounds for that item 1:
ub2 = {3, 1, 5, Infinity, Infinity};
lb2 = {0, 1, 1, 1, 0};

lb2 + KnapsackSolve[Transpose@{V, P, ub2 - lb2}, W - P.lb2]

{0, 1, 5, 1, 12}

LinearProgramming[-V, {P}, {{W, -1}}, Thread[{lb2, ub2}], Integers]

{0, 1, 5, 1, 12}

For constraints that involve multiple items (e.g., total count of items 3 and 4  should be between 2 and 5) I am not aware of a general method to get KnapsackSolve to work, but LinearProgramming can handle any linear constraint easily:
For the case with the constraints  (1) items 3 and 4 should both be present, and (2) total count of items 3 and 4 should be between 2 and 5, we can use:
LinearProgramming[-V,
 {P, {0, 0, 1, 1, 0}, {0, 0, 1, 1, 0}},
 {{W, -1}, {2, 1}, {5, -1}},
 Thread[{lb, ub}],
 Integers]

{3, 0, 4, 1, 11}

Adding the constraint that exactly one unit of item 2 is in the solution:
ub3 = {3, 1, 5, Infinity, Infinity};
lb3 = {0, 1, 1, 1, 0};
LinearProgramming[-V,
  {P, {0, 0, 1, 1, 0}, {0, 0, 1, 1, 0}},
  {{W, -1}, {2, 1}, {5, -1}},
  Thread[{lb3, ub3}],
  Integers]

{2, 1, 4, 1, 11}

A: I use genetic algorithm to find the near optimal solution, but this
method can' t deal with the integer point situation and the
calculation speed is very slow:
clear

P0 = 0.2;

num = 100;

constraints = (2.36 x1 + 2.12 x2 + 1.89 x3 + 3.77 x4 + 2.87 x5 <=
     25) && (0 <= x1 <= 3 && 0 <= x2 && 1 <= x3 <= 5 && 1 <= x4 &&
     0 <= x5) && (2 <= x3 + x4 <= 5);
vars = {x1, x2, x3, x4, x5};
imreg = ImplicitRegion[constraints, Evaluate@vars];
Rho = 0.6;

caltau[{a_, b_, c_, d_, e_}] :=
  If[constraints /. Thread[vars -> #] &@{a, b, c, d, e},
   91 a + 71 b + 105 c + 103 d + 96 e, 8000];
ants = RandomPoint[imreg, num];
taus = Map[caltau[#] &, ants];

selectbest[antss_, tau_List, lamuda_] :=
 Module[{sants = Round /@ antss, taubest = Max[tau], taumin, p,
   lsindex, gsindex, objvalue, sobjvalue, tindex},(*sants=ants;*)
  taubest = Max[tau];
  taumin = Min[tau];

  p = Abs[taubest - tau];
  lsindex = Flatten[Position[p, n_ /; n < P0], 1];
  gsindex = Flatten[Position[p, n_ /; n >= P0], 1];
  If[Length[lsindex] >= 1, r = RandomPoint[imreg, Length[lsindex]];
   sants[[lsindex]] = sants[[lsindex]] + r*lamuda;];

  If[Length[gsindex] >= 1, r = RandomPoint[imreg, Length[gsindex]];

   sants[[gsindex]] = sants[[gsindex]] + r;

   sants = RegionNearest[imreg, #] & /@ sants;];

  objvalue = Map[caltau[#] &, antss];
  sobjvalue = Map[caltau[#] &, sants];
  tindex = Flatten[Position[Negative[sobjvalue - objvalue], True]];
  sants[[tindex]] = antss[[tindex]];
  sants
  ]

t = 1;
Do[ants = selectbest[ants, taus, 1/t];
 taus = (1 - Rho)*taus + Map[caltau[#] &, ants]; t++;(*Print[t]*), 50]
Map[caltau[#] &, ants]
constraints /. Thread[vars -> #] & /@ ants

Maximize[{91 x1 + 71 x2 + 105 x3 + 103 x4 + 96 x5,
  2.36 x1 + 2.12 x2 + 1.89 x3 + 3.77 x4 + 2.87 x5 <= 25,
  0 <= x1 <= 3 && 1 <= x3 <= 5 && 1 <= x4, 2 <= x3 + x4 <= 5}, {x1,
  x2, x3, x4, x5}, NonNegativeReals]


text:
Q: Verify: If every open interval has $x \neq 0, f(x) = 0$, then $f^{(n)} = 0$ Let $f: \mathbb R \to \mathbb R$ such that for any open interval $I$ containing zero, there exists $x \in I, x \neq 0$ with $f(x) = 0$.  Show that $f^{(n)}(0)$ (the nth-derivative of $f$ at zero), if defined, is zero.
Please help me fix this proof; see Equation (1) and its error.
Proof: Let $(x_n)$ be a sequence converging to zero such that $x_n \neq 0, f(x_n) = 0$ for all $n \in \mathbb N$.  Such a sequence always exists, for example, by picking appropriate $x_n$ in $(-1/n, 1/n)$.  If $f'(0)$ is defined, $f$ is continuous at zero, and $f(0) = f(\lim x_n) = \lim f(x_n) = 0$.
Likewise, since for all $n \in \mathbb N, x_n \neq 0$ and $\frac {f(x_n)}{x_n} - 0$, if $f'(0)$ is defined, $$\begin{align*}f'(0) &= \lim_{h \to 0} \frac {f(h) - f(0)}h \\ &= \lim \frac {f(x_n)}{x_n} \\ &= 0.\end{align*}$$
For all $p \in \mathbb N$, if $f^{(p)}(0) = 0$ and $f^{(p+1)}(0)$ is defined, then $f^{(p)}$ is continuous at zero and defined on an open interval $I_p$ including zero.  Restrict $(x_n)$ to the subsequence in $I_p$.  Then $f^{(p+1)}(0) = 0$, since $$\begin{align*}f^{(p+1)}(0) &= \lim_n \frac {f^{(p)}(0 + x_n) - f^{(p)}(0)}{x_n} \\
&= \lim_n \frac {f^{(p)}(x_n)}{x_n} \tag{1} \\
&= 0.\end{align*}$$
I'm unable to justify Line 1 unless $f^{(p)}$ is zero on an interval containing zero, not just a point. I tried expanding $f^{(p)}$ to the limit definition, and using double limits, but this seemed to complicate things without getting anywhere.  Can you guide me here?
By definition of derivative, if $f^{(p+1)}(0)$ is defined, then $f^{(p)}(0)$ must also be defined.  Therefore, we have by induction that if $f^{(p)}(0)$ is defined, it equals zero.
Discussion:
Intuitively, this means that if a function that is arbitrarily close to flat at a point, to the extent that it is smooth at that point, its derivatives must vanish.  This holds for both functions that flatten out simply, such as $x \mapsto x^n$ as well as for functions with never ending small ripples, such as $x \mapsto 0$ if $x = 0$ otherwise $x^n \sin(1/x)$.  (This comment is not meant to convey rigor, but to give an intuitive sense of the result.)

A: If $n$th derivative exists at $x=0$, then all derivatives up to $n-1$st exist in some neighbourhood of zero. Let's restrict ourselves to that neighbourhood.
Per the conditions of the problem, one can find the sequence $x_1,x_2,x_3,\ldots$ converging to $0$ such that $f(x_i)=0$. WLOG we can assume $x_1>x_2>x_3>\ldots>0$.
As per Rolle's theorem, this gives rise to a sequence $x_1'>x_2'>x_3'>\ldots>0$ converging to $0$ such that $f'(x_i')=0$. ($x_i'$ is between $x_i$ and $x_{i+1}$). Repeating the same argument $n-1$ times, we find a sequence $x_1^{(n-1)}>x_2^{(n-1)}>\ldots>0$ converging to $0$ such that $f^{(n-1)}(x_i^{(n-1)})=0$. This implies that $f^{(n-1)}(0)=0$ and, ultimately, that $f^{(n)}(0)=\lim_{i\to\infty}\frac{f^{(n-1)}(x_i^{(n-1)})-f^{(n-1)}(0)}{x_i^{(n-1)}}=\lim_{i\to\infty}\frac{0-0}{x_i^{(n-1)}}=0$.


text:
Q: How to use template variables in mailer I am building a Rails 5.2 app.
In this app I let my users save email templates that are then used to send emails to customers. In these templates the users can add placeholder variables, for example %{sender.firstname}.
I need these values to be replaced with actual first name of the sender in this case.
Ruby got a feature that can take care of this (almost).
body = "Hello %{firstname}"
body % { :firstname => "James" }

The above code outputs:
Hello James

The problem is I want to use the prefix sender, like below but then I get an error. Seems like I have to use a single word symbol?
body = "Hello %{sender.firstname}"
body % { "sender.firstname" => "James" }

The error is:
Traceback (most recent call last):
        2: from (irb):44
        1: from (irb):44:in `%'
KeyError (key{sender.firstname} not found)

How can I use the above method to look through a objects body, replace the variables and output the correct values?

A: Calling #to_sym on "sender.firstname" will fix it.
body % { "sender.firstname".to_sym => "James" }
# => "Hello James"


text:
Q: Xcode - Vertical Stack of Horizontal Stacks constraints I'm very new to using Interface Builder and Auto Layout so please bear with me.
I'm trying to lay out a vertical stack of horizontal stacks, with each horizontal stack being made up of a label and another horizontal stack of two labels. The whole vertical stack is wrapped in another view that has 10 points left and right constraints. I want the two stack elements of each horizontal stack to be at the edges of the stack.
I can get the layout to look how I want it on the interface builder but when I run it, the Sunrise AM/PM label gets cut off.
Storyboard next to simulator instance where AM label is truncated
View hierarchy with constraints
Please let me know if there's anything unclear about what my goal or my issue is.

A: The Problem is that your programm does need to truncate something to fit everything on the screen. Since you probably did not define which element to truncate (by altering the compression resistance) it takes the last one in the stack - the am/pm one. Changing the compression resistance should fix this.
Check out this guide to learn about it.


text:
Q: How to Separate a value from a Column Column Populates with Debit and credit values like
100
150
-300
400

I created new column for -300 as CREDIT_ACCOUNT. Since value is populating in that column. That Value should set to null in DEBIT COLUMN
Entire data is pulled and populated based on Select and Case statements. How to make sql WORK to SET NULL for -300 in DEBIT COLUMN
That is populated based on
COALESCE
        (
        CASE DBO.TRUNC_NUM1((DBO.TO_NUMBER(DBO.TO_DATE(#prompt('Q_Date','string')#,'yyyy-mm-dd')-AR_ACCOUNT_ITEM_NEW.BILL_DATE))/#prompt('P_Interval')#)
           WHEN 0 THEN
                       CASE RTRIM(AR_ACCOUNT_ITEM_NEW.BILL_REF)
                          WHEN 'BILL' THEN AR_ACCOUNT_ITEM_NEW.REMAINING_AMOUNT
                       END
           ELSE NULL
        END
        ,0) THIS_MONTH,
        COALESCE
        (
        CASE DBO.TRUNC_NUM1((DBO.TO_NUMBER(DBO.TO_DATE(#prompt('Q_Date','string')#,'yyyy-mm-dd')-AR_ACCOUNT_ITEM_NEW.BILL_DATE))/#prompt('P_Interval')#)
           WHEN 1 THEN
                       CASE RTRIM(AR_ACCOUNT_ITEM_NEW.BILL_REF)
                          WHEN 'BILL' THEN AR_ACCOUNT_ITEM_NEW.REMAINING_AMOUNT
                       END
           ELSE NULL
        END
        ,0) THIRTY,
        COALESCE
        (
        CASE DBO.TRUNC_NUM1((DBO.TO_NUMBER(DBO.TO_DATE(#prompt('Q_Date','string')#,'yyyy-mm-dd')-AR_ACCOUNT_ITEM_NEW.BILL_DATE))/#prompt('P_Interval')#)
           WHEN 2 THEN
                       CASE RTRIM(AR_ACCOUNT_ITEM_NEW.BILL_REF)
                          WHEN 'BILL' THEN AR_ACCOUNT_ITEM_NEW.REMAINING_AMOUNT
                       END
           ELSE NULL
        END
        ,0) SIXTY,
        COALESCE
        (
        CASE DBO.TRUNC_NUM1((DBO.TO_NUMBER(DBO.TO_DATE(#prompt('Q_Date','string')#,'yyyy-mm-dd')-AR_ACCOUNT_ITEM_NEW.BILL_DATE))/#prompt('P_Interval')#)
           WHEN 3 THEN
                       CASE RTRIM(AR_ACCOUNT_ITEM_NEW.BILL_REF)
                          WHEN 'BILL' THEN AR_ACCOUNT_ITEM_NEW.REMAINING_AMOUNT
                       END
           ELSE NULL
        END
        ,0) NINETY,
        DBO.TO_NUMBER
        (
        COALESCE
        (
        CASE DBO.TRUNC_NUM1((DBO.TO_NUMBER(DBO.TO_DATE(#prompt('Q_Date','string')#,'yyyy-mm-dd')-AR_ACCOUNT_ITEM_NEW.BILL_DATE))/#prompt('P_Interval')#)
           WHEN 0 THEN NULL
           WHEN 1 THEN NULL
           WHEN 2 THEN NULL
           WHEN 3 THEN NULL
           ELSE
                CASE RTRIM(AR_ACCOUNT_ITEM_NEW.BILL_REF)
                   WHEN 'BILL' THEN AR_ACCOUNT_ITEM_NEW.REMAINING_AMOUNT
                END
        END
        ,0)
        ) ONETWENTY,

A: If you just want to have the negative values to be in a different column, here is how:
Select Case When Debit_Amount >= 0 then Debit_Amount Else Null End as Debit_Amount,
    Case When Debit_Amount < 0 then Debit_Amount Else Null End as Credit_Amount,
<Other Columns>
From
(
    -- Your Query to get Debit_Amount and other data
) Q

-- Or if your table is already populated:
Update YourTable
Set Credit_Amount = Debit_Amount
Where Debit_Amount < 0

Update YourTable
Set Debit_Amount = Null
Where Debit_Amount < 0


text:
Q: NiftyNet: indices are out-of-bounds error I'm just starting to use NiftyNet for medical image segmentation. To get going with the software, I was trying to run the demo that segments images from the Brats Challenge dataset (http://www.braintumorsegmentation.org/).
I have downloaded the Brats, data, used rename_crop_brats on it, and set my $PYTHONPATH. However, when I run the command:
python net_run.py train -c train_whole_tumor_sagittal.ini --app brats_segmentation.BRATSApp --name anisotropic_nets.wt_net.WTNet
I get the following error message:
tensorflow.python.framework.errors_impl.InvalidArgumentError: Provided indices are out-of-bounds w.r.t. dense side with broadcasted shape

I'm not quite sure what I've messed up here, any advice welcomed.

A: This error means that you have more discrete labels in your training images than the your network can output. Here, it seems like there are more than 2 labels, while this network is set up to do binary classification.
Could you check which file the 'histogram_ref_file' in the .ini file is pointing to? It should point to the one provided in the [niftynet]/demos/BRATS17 directory, which binarises the tumour mask. This file should have the following text:
labellabelfrom 0 1 2 4
labellabelto 0 1 1 1

Which assigns all tumour labels to 1, and all background labels to 0. If you haven't given the path to this file, the network will have generated it automatically, giving the training images 4 discrete classes.
Does this solve the problem?


text:
Q: Override default AWS profile for SpringBoot Application I'm running SpringBoot applications that use AWS resources from two different AWS accounts (depending on the project—each application only needs resources from one of the two AWS accounts).
I have two different profiles set up in my AWS config file (a default one and a secondary one). When I use AWS CLI, I just specify --profile=secondary and everything is happily working.
I can't seem to find any way to specify the secondary profile for a SpringBoot Application using AWS Java SDK. What are my options?

A: This can be achieved using ProfileCredentialsProvider(String profile) where profile is, the question's case, secondary.


text:
Q: GETUTCDATE en Indexed View Certificacion MSCA estoy preparándome para tomar el examen para obtener la certificacion de microsoft de SQL Server, para ello conseguí ejemplos de preguntas que me pueden tomar en el examen, sin embargo hay una de las preguntas la cual no logro entender.
You have a date related query that would benefit from an indexed view. You need to create the indexed view. Which two Transact-SQL functions can you use? (Each correct answer presents a complete solution. Choose two.)
A.    DATEADD
B.    AT TIME ZONE
C.    GETUTCDATE
D.    DATEDIFF
Tanto en una aplicación que utilizo para prepararme como buscando por internet, he econtrado que siempre responden que las respuestas correctas son la C y la D haciendo referencia al sitio de microsft https://docs.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-2017#DateandTimeFunctions.
Sin embargo no entiendo el porque.
Yo entiendo que pregunta "Cuales funciones T-SQL se pueden usar" se refiere a la creacion de la vista indexada, con lo cual GETUTCDATE es no deterministico y por ende no se puede utilizar en la creación de una vista indexada.
Estoy entendiendo mal la pregunta?
Igualmente al margen que la respuesta ofrecida no la entiendo, tampoco entiendo cuales 2 serían las respuestas, ya que para mi serian A, B y C.
Alguien podrá ayudarme a entender?
Muchas Gracias

A: Las respuestas correctas serían A y D. Porque son las únicas que usan funciones determinísticas (DATEADD y DATEDIFF).
AT TIME ZONE y GETUTCDATE no son determinísticas y no pueden ser utilizadas para vistas indexadas.
Si encuentras que hay otras respuestas disponibles, es probable que estén en un error. Dejo unos ejemplos que puedes validar.
Con funciones permitidas
USE AdventureWorks2016
GO

CREATE VIEW Sales.vSalesOrder
WITH SCHEMABINDING
AS
SELECT SalesOrderID, OrderDate,
    DATEDIFF( dd, 0, DATEADD( dd, SalesOrderID, OrderDate)) AS DiasDesde1900
FROM Sales.SalesOrderHeader;

GO
CREATE UNIQUE CLUSTERED INDEX CI_vSalesOrder ON Sales.vSalesOrder(DiasDesde1900);

GO

DROP VIEW Sales.vSalesOrder

Con funciones NO permitidas
USE AdventureWorks2016
GO

CREATE VIEW Sales.vSalesOrder
WITH SCHEMABINDING
AS
SELECT SalesOrderID, OrderDate,
    GETUTCDATE() AS SomeDate
FROM Sales.SalesOrderHeader;

GO
CREATE UNIQUE CLUSTERED INDEX CI_vSalesOrder ON Sales.vSalesOrder(OrderDate_TimeZonePST);

GO

DROP VIEW Sales.vSalesOrder

.
USE AdventureWorks2016
GO

CREATE VIEW Sales.vSalesOrder
WITH SCHEMABINDING
AS
SELECT SalesOrderID, OrderDate,
    DATEADD( dd, 1, OrderDate AT TIME ZONE 'Pacific Standard Time' AS OrderDate_TimeZonePST
FROM Sales.SalesOrderHeader;

GO
CREATE UNIQUE CLUSTERED INDEX CI_vSalesOrder ON Sales.vSalesOrder(OrderDate_TimeZonePST);

GO

DROP VIEW Sales.vSalesOrder


text:
Q: Extend Exisiting Entity to override getters and setters I want to override an existing Entity's getters and setters. Is it possible to do this?
I want to add additional logic to the getters and setters.
Thanks
Jake He

A: for this you must make an entity that extend that entity you want to override
e.g
my base entity
abstract class AbstractEntity
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="create")
     */
    protected $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime", nullable=true)
     * @Gedmo\Timestampable(on="update")
     */
    protected $updatedAt;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     *
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }

    /**`enter code here`
     * Get created
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     *
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}

and then in my entity
class Group extends BaseEntity
{
    public function __construct()
    {
        $this->children = [];
        $this->users = [];
        $this->accounts = [];
        $this->isActive = true;
    }

     /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     *
     */
    public function setCreatedAt($createdAt)
    {
        parent::setCreatedAt($createdAt); //
        TODO: Override the implementation
    }

}

hope it will help


text:
Q: 3 numbers the same from a random numbers list between 1-9 If I have a array that gives me 9 random numbers, from a list of 9 numbers, how do I make sure that it can only duplicate 3 of the same numbers?
for example if my random numbers array is [4,3,4,4,7,8,8,8,9].
I need there to only be one trio of numbers in any one array not two like seen above.

A: You'll need to replace randomNum with whatever it is you are using to store the random numbers being added to the array, but try this:
var arrayOfRandomNums = [];

function maxInstancesInArray(arr, val) {
    var hits = [];
    for(i = 0; i < arr.length; i++)
        if (arr[i] === val)
            indexes.push(i);
    return indexes.length > 2;
}

if(!maxInstancesInArray(arrayOfRandomNums, randomNum) {
    arrayOfRandomNums.push(randomNum);
}

The function will return true if there are 3 or more instances of the incoming number already in the array, so you can use that to define whether or not you push the next one to the array.

A: i've made a jsFiddle that can help. the idea is that instead of trying to get rundom numbers everytime and check, to have the list of available numbers in an array and random the index of this array.
https://jsfiddle.net/m8ohmxmb/
  function randNumber(maxRange,maxOccurrencies, resultArrayLenght) {
     var num = [];
     var occ = [];
     var result = [];
     var randElem;

     for (var i = 0; i < maxRange; i++) {
        num.push(i + 1);
        occ.push(0);
     }

     for(i = 0; i < resultArrayLenght; i++) {
         randElem = Math.floor(Math.random() * num.length);
         occ[randElem] = occ[randElem] + 1;
         result.push(num[randElem]);
         if(occ[randElem] === maxOccurrencies) {
             occ.splice(randElem,1);
             num.splice(randElem,1);
         }
     }
     return result;
  }

A: This is a straight forward approach with a temporary object for keeping the insertet values and their count.

function push(n) {
    if (count.full && count[n] === 2) {
        alert('can not insert ' + n);
        return;
    }
    array.push(n);
    count[n] = (count[n] || 0) + 1;
    if (count[n] === 3) {
        count.full = true;
    }
}

var array = [],
    count = {};

[4, 3, 4, 4, 7, 8, 8, 8, 9].forEach(push);
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');


text:
Q: How to use handlebars with nodemailer to send email? I am using nodemailer to send emails using the following nodemailer-express-handlebars plugin. I used this {dead blog post} as reference
The code is compiling the welcome template but is not using the layout
My code is as below:
var nodemailer = require('nodemailer');
var mg = require('nodemailer-mailgun-transport');
var hbs = require('nodemailer-express-handlebars');

var config = {auth: {api_key: "key-xxx",domain: "mydomain.com}}
var nodemailerTransport = nodemailer.createTransport(mg(config));

var options = {
    viewEngine: {
        extname: '.handlebars',
        layoutsDir: 'views/email/',
        defaultLayout : 'layout',
    },
    viewPath: 'views/email/'
}

nodemailerTransport.use('compile', hbs(options));

nodemailerTransport.sendMail({
        from: 'from@mydomain.com',
        to: 'to@gmail.com',
        subject: 'Welcome to the XXX',
        template: 'welcome'
    }, function (err, results) {
        if (err) console.log('Error: ' + err);
        else console.log('Response: ' + results);
});

My layout.handlebars has the following code
<html>
<body>
{{> _header }}
    {{{body}}}
{{> _footer }}
</body>
</html>

A: You are missing a partialsDir option.
I have tested with the following options and it works fine :
 var options = {
   extName:'.hbs', /* or '.handlebars' */
   viewPath:__dirname+'/views/email/',
   layoutsDir:__dirname+'/view/email',
   defaultLayout:'template',
   partialsDir:__dirname+'/views/email/partials/'
 }

To use my directory structure :

*

*Where the script is place a folder : views

*Inside of it place a folder called email (here store 'template.hbs')

*Inside of the email folder create a partials folder (here as example store 'header.hbs')


text:
Q: Freeze or copy current RandomState in Python/Numpy I try to implement a Multi-Step-Player for the 2048 game in Python which chooses the best move by calculating the maximum score for each move over multiple steps. In each step, the game randomly spawns a new tile on the board. I use np.random.RandomState for this.
Problem: after the player simulates a few steps in order to obtain the best move, the RandomState has changed and the actual score is different from the one predicted due to different spawning tiles.
My idea was to store the current RandomState before simulating the next steps and restore it afterwards so that the spawning tiles are identical. From what I understand, the RandomState is just a pointer but I haven't found any way to copy or store it.
Any ideas? Thank you!

A: The RandomState object has methods get_state() and set_state() - just use those:
state = np.random.get_state()
... # Do some simulations
np.random.set_state(state)


text:
Q: Как привязать BackDrop к низу экрана? | BottomSheetBehavior | Kotlin Как мне привязать BottomSheet к низу экрана? А то, когда я листаю до самого низа, то у меня появляется пустое простанство. Глянул через Layout Inspector и это вина первого ConstraintLayout.
Есть xml фрагмент:
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/dark">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/image"
        android:layout_width="160dp"
        android:layout_height="220dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:src="@drawable/ic_placeholder"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/genre"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/marker_v2"
        android:gravity="start|center_horizontal"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:text="@string/simple_genre"
        android:textColor="@color/white"
        app:fontFamily="@font/oswald"
        app:layout_constraintStart_toEndOf="@+id/image"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/simple_ongoing_title"
        android:textColor="@color/white"
        android:textSize="18sp"
        app:fontFamily="@font/montserrat"
        app:layout_constraintStart_toEndOf="@+id/image"
        app:layout_constraintTop_toBottomOf="@+id/genre" />

    <TextView
        android:id="@+id/author"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/title_notifications"
        android:textColor="@color/sky"
        android:textSize="12sp"
        app:layout_constraintStart_toEndOf="@+id/image"
        app:layout_constraintTop_toBottomOf="@+id/title" />
</androidx.constraintlayout.widget.ConstraintLayout>

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/contentLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="16dp"
    android:background="@drawable/book_second_layout"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/image">

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="MissingConstraints">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@drawable/book_second_layout"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            tools:ignore="MissingConstraints">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:id="@+id/constraintLayout3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="4dp"
                android:layout_marginEnd="8dp"
                android:layout_marginRight="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/imageView5">

                <TextView
                    android:id="@+id/textView25"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal|left"
                    android:text="@string/Comments"
                    android:textColor="@color/black"
                    android:textSize="18sp"
                    app:fontFamily="@font/oswald"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    tools:ignore="RtlHardcoded" />

                <TextView
                    android:id="@+id/textView26"
                    android:layout_width="wrap_content"
                    android:layout_height="0dp"
                    android:drawableRight="@drawable/ic_baseline_arrow_forward_ios_24"
                    android:gravity="center_vertical"
                    android:text="46 Комментариев"
                    android:textSize="10sp"
                    app:fontFamily="@font/montserrat"
                    app:layout_constraintBottom_toTopOf="@+id/commentsRecycler"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    tools:ignore="SmallSp" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/commentsRecycler"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="8dp"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@+id/textView25" />
            </androidx.constraintlayout.widget.ConstraintLayout>
        </LinearLayout>
    </androidx.core.widget.NestedScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

А это в коде:
val contentLayout: ConstraintLayout? = root?.findViewById(R.id.contentLayout)

    val sheetBehavior = contentLayout?.let { BottomSheetBehavior.from(it) }
    sheetBehavior?.isFitToContents = false
    sheetBehavior?.isHideable = false

    sheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED

A: Проблема была в отступе, что я назначил второму ConstraintLayout. Убрав его, все решилось. А привязать BackDrop невозможно, т.к. он основан на CoordinatorLayout, который по своей суте похож на FrameLayout.


text:
Q: Makefile printing messages without compiling every time I have a makefile that compiles and links several c++ projects, and in general I would like it to print a message for every project it compiles/links - but only when it has to do something for that target. I have something like this:
Project_1: print_1 main_1.o $(Objects_1)
    ${CXX} main_1.o $(Objects_1) -o $@ ${CXXLDFLAGS}

print_1:
    @echo "Project 1"

$(DIR_BLD_CXX)/main_1.o: $(DIR_SRC_CXX)/main_1.cpp $(Hfiles_1)
    ${CXX} -c $(DIR_SRC_CXX)/main_1.cpp ${MYCXXFLAGS} -o $@

And this works; however everywhere I use a phony target (?) to print something it will compile/link every time, regardless if something relevant has been changed.
Is there a way to print a message at certain targets, but only whenever something has changed that means the target has to be compiled?


text:
Q: How to add phone number masking in woo commerce my account page in wordpress I want to add phone number masking on my account page of Woocommerce in wordpress?

A: Add the below code snippet in your active theme's functions.php file -
// Add field in Account Details
function wc_add_field_edit_account_form() {
    woocommerce_form_field(
        'user_phone_number',
        array(
            'type'        => 'tel',
            'required'    => true, // for false do not need this `woocommerce_save_account_details_required_fields` callback
            'label'       => __( 'Phone Number', 'yourtextdomain' ),
        ),
        get_user_meta( get_current_user_id(), 'user_phone_number', true )
    );
}
add_action( 'woocommerce_edit_account_form', 'wc_add_field_edit_account_form' );

// Save field data
function wc_save_account_details( $user_id ) {
    update_user_meta( $user_id, 'user_phone_number', wc_clean( $_POST[ 'user_phone_number' ] ) );
}
add_action( 'woocommerce_save_account_details', 'wc_save_account_details' );

// Add field required
function wc_add_account_details_required_fields( $required_fields ){
    $required_fields[ 'user_phone_number' ] = __( 'Phone Number', 'yourtextdomain' );
    return $required_fields;
}
add_filter( 'woocommerce_save_account_details_required_fields', 'wc_add_account_details_required_fields' );


text:
Q: Angular - How can I use a direct URL to a lazy loaded angular route? I have been trying to get lazy loaded routes to work in my app, and so far it works fine when navigating to routes inside the app. I would now like to allow users to directly link to portions of the application once they are already logged in. The way it stands now, they are always directed to the default route instead of to their deep linked route.
Example: If the user requests http://localhost:4200/ui/customers, they are taken to http://localhost:4200/ui/quotes instead (the default route).
I am using a UI component to handle the layout of the application instead of applying those styles into the root of the app itself (inside app.component). Each of the subsequent Modules also follows a similar structure with the root managing the layout and deeper links providing the implementations.
Is there something I need to do differently to allow my routes to be activated via a direct link?
I tried using canLoad, canActivate, and canActivateChild to make sure that wasn't blocking the routes, but even removing it altogether, users still cannot reach a deep link.
Note: I am using Angular 13 with Nrwl in a mono-repo configuration.
Code:
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard, authRoutes } from '@my-app/auth';

const routes: Routes = [
  {
    path: 'ui',
    loadChildren: () => import('@my-app/ui').then((m) => m.UiModule),
    canLoad: [AuthGuard],
    //canActivate: [AuthGuard],
    //canActivateChild: [AuthGuard],
  },
  { path: 'auth', children: authRoutes },
  { path: '**', redirectTo: 'ui', pathMatch: 'full' },
];

@NgModule({
  exports: [RouterModule],
  imports: [
    RouterModule.forRoot(routes, {
      onSameUrlNavigation: 'reload',
      initialNavigation: 'enabled',
    }),
  ],
})
export class AppRoutingModule {}

app.module.ts
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AuthModule } from '@my-app/auth';
import { UiModule } from '@my-app/ui';
import { UiAlertModule } from '@my-app/ui-alert';
import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from '../environments/environment';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    StoreModule.forRoot(
      {},
      {
        metaReducers: !environment.production ? [] : [],
        runtimeChecks: {
          strictActionImmutability: true,
          strictStateImmutability: true,
        },
      }
    ),
    EffectsModule.forRoot([]),
    !environment.production ? StoreDevtoolsModule.instrument() : [],
    AppRoutingModule,
    AuthModule,
    UiModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

auth.guard.ts
import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  CanActivateChild,
  CanLoad,
  Route,
  Router,
  RouterStateSnapshot,
} from '@angular/router';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AuthFacade } from '../../+state/auth.facade';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
  constructor(private router: Router, private authFacade: AuthFacade) {}
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    const url: string = state.url;
    return this.handleGuard(url);
  }

  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    const url: string = state.url;
    return this.handleGuard(url);
  }

  canLoad(route: Route): Observable<boolean> {
    const url = `/${route.path}`;

    return this.handleGuard(url);
  }

  private handleGuard(url: string) {
    this.router.events.subscribe((event) => {
      // eslint-disable-next-line no-restricted-syntax
      console.debug('GUARD', event, url);
    });
    return this.authFacade.userToken$.pipe(
      map((user) => {
        if (user) {
          return true;
        } else {
          this.router.navigate([`/auth/login`]);
          return false;
        }
      })
    );
  }
}

ui-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LayoutComponent } from './layout/layout.component';

const routes: Routes = [
  {
    path: '',
    component: LayoutComponent,
    children: [
      {
        path: 'customers',
        loadChildren: () =>
          import('@my-app/ui-customers').then((m) => m.UiCustomersModule),
      },
      {
        path: 'quotes',
        loadChildren: () =>
          import('@my-app/ui-quotes').then((m) => m.UiQuotesModule),
      },
      {
        path: 'users',
        loadChildren: () =>
          import('@my-app/ui-users').then((m) => m.UiUsersModule),
      },
      { path: '', redirectTo: 'quotes', pathMatch: 'full' },
    ],
  },
];

@NgModule({
  exports: [RouterModule],
  imports: [RouterModule.forChild(routes)],
})
export class UiRoutingModule {}

ui.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AuthModule } from '@my-app/auth';
import { TypeaheadModule } from 'ngx-bootstrap/typeahead';
import { LayoutComponent } from './layout/layout.component';
import { UiRoutingModule } from './ui-routing.module';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    TypeaheadModule.forRoot(),
    UiRoutingModule,
    AuthModule,
  ],
  declarations: [LayoutComponent],
  exports: [LayoutComponent],
  providers: [],
})
export class UiModule {}

Thank you for your help and consideration!


text:
Q: How do i enter the password while joining the Linux machine to Active Directory using shell script? I am joining Linux machines to windows active directory and i am able to do it successfully using SSSD.
Now I am trying to automate the same process wherein i came across the step where i need to enter a password while joining the domain.
Can someone help in how to enter the password via shell script?
My code is :
#!/bin/bash

set -x

passwd=`cat /domain/domain_join.txt | grep password | awk -F '[=]' '{print$2}'`
 /usr/bin/expect << EOF
 spawn realm join domainname -U username@domainname -v
 expect "Password for username@domainname: \r"
 send "$passwd\r"
EOF
set +x

A: This isn't actually an LDAP question - it's AD and Kerberos and sshd.
It looks like you've got a user account to join the machine - presumably it has the correct rights. The easiest thing to do is to get a keytab created for that account, and then you can do a kinit and call the script in that context
kinit principal@EXAMPLE.COM -k -t keytab; joinscript

You don't need to define your username in the realm join command if you've already done the kinit.
Sorry, I can't test this, and it's been a while, but the secret sauce is a keytab for the Windows credential.


text:
Q: How to force login in angular full stack yeoman? Is there a way to force the user to log in first in an app generated by the angular full stack yeoman ?
I tried to add the following code in the run part of app.js but was not successful
Auth.isLoggedIn(function(loggedIn) {
  console.log(loggedIn);
  if (!loggedIn) {
    console.log("redirecting");
    // event.preventDefault();
    $state.go('login');
  }
});

I found authentication controls in api index.js files but none for the / landing page ...
Thx

A: I did not use google as i should have !
To force authentication for a state, just add

authenticate: true

in the state (or all states in my case)

A: Without more code or information on which router you are using (generator-angular-fullstack supports both the default NgRouter and UIRouter) it is tough to give a complete answer. By your answer to your question I am assuming you have UI Router and have figured out how to do client side authentication within the generated fullstack code. However, you will also need to implement something similar to what they have done in their 'users' api to protect your api end points on the server side and return a 401/403 error.
'use strict';

var express = require('express');
var controller = require('./user.controller');
var config = require('../../config/environment');
var auth = require('../../auth/auth.service');

var router = express.Router();

router.get('/', auth.hasRole('admin'), controller.index);
router.delete('/:id', auth.hasRole('admin'), controller.destroy);
router.get('/me', auth.isAuthenticated(), controller.me);
router.put('/:id/password', auth.isAuthenticated(),         controller.changePassword);
router.get('/:id', auth.isAuthenticated(), controller.show);
router.post('/', controller.create);

module.exports = router;

In the above code (which can be found by navigating to the server folder, then the api folder, then the user folder and looking at index.js) you will see that they are calling a couple of functions.
They are calling auth.hasRole('admin') and auth.isAuthenticated().
Those are functions which can be found in the server side auth/role service under the folder auth and in the auth.service.js file.
function hasRole(roleRequired) {
if (!roleRequired) throw new Error('Required role needs to be set');

return compose()
.use(isAuthenticated())
.use(function meetsRequirements(req, res, next) {
  if (config.userRoles.indexOf(req.user.role) >= config.userRoles.indexOf(roleRequired)) {
    next();
  }
  else {
    res.status(403).send('Forbidden');
  }
});
}

I think it is important to understand how this is working on the server side also. So, if you navigate to localhost:9000/admin and open console you will see that there is a 401 or 403 error depending on whether or not you are logged in and/or logged in as an admin user.

A: Just Paste authenticate:true on main.js
angular.module('testcesarApp')
 .config(function ($routeProvider) {
 $routeProvider
  .when('/', {
    templateUrl: 'app/main/main.html',
    controller: 'MainCtrl',
    authenticate:true
  });
 });


text:
Q: Send http requests in Ruby and stay logged in? I am trying to crawl websites with ruby. The way I am implementing it is that I send request for a page, and get all the links(href tags) in the page, and then generate another GET request. The problem is that I want to stay logged in during the whole process. I wrote some code as followed.
def start_crawling
    uri = URI(@host + "/login")
    @visited.push @host + "/login"
    req = Net::HTTP::Post.new(uri)
    req.set_form_data({
      'email' => 'test',
      'password' => 'test'
    })
    Net::HTTP.start(uri.hostname, uri.port) do |http|
      res = http.request req
      puts uri
      puts res.code
      content = res.body
      puts content
      puts res.response
      cookie = res.response['Set-Cookie'] # this gives nothing
      puts cookie
      puts res["Set-Cookie"] # prints nothing here
      hrefs = get_href_tag_array_from_html(content)
      send_get_requests(hrefs, cookie)
    end
  end

  def send_get_requests(hrefs, cookie)
    while not hrefs.empty?
      href = hrefs.pop
      href = @host + href if not href.start_with?"http"
      next if @visited.include?(href)
      puts "href: " + href
      uri = URI(href)

      Net::HTTP.start(uri.host, uri.port) do |http|
        req = Net::HTTP::Get.new uri
        res = http.request req
        puts "------------------href: #{href}---------------------------"
        puts res.code
        puts res.message
        puts res.class.name
        puts "Cookie: "
        puts res['Set-Cookie'] # this works and prints cookies
        puts res.body
        puts "------------------end of: #{href}---------------------------"
        new_hrefs = get_href_tag_array_from_html(res.body)
        hrefs += new_hrefs
      end
      @visited.push href
    end
  end

I want to start crawling from the login page. Ideally I want to stay logged in during the whole crawling procedure. I don't know much about session/cookie stuff, but I guess if I can get the cookie from the previous response and send it with the next request, I should be able to stay logged in. However, I cannot get any cookie from the login response. The response body is a 302 redirection, as I would expect. I checked it on the browser and the 302 response header does contain a cookie field, and this cookie is used for the next get request to redirect to the home page, but I cannot get the cookie field.
When I send GET request and get the response, I can get the cookie field out of it, but when I send POST request for the login page, I cannot get any cookie. Is there any fundamental difference between GET and POST requests in such cases?
Any idea how can I get this cookie field? Or do I have some basic misunderstanding in solving this crawling problem? Thanks.


text:
Q: Is data masking available in IBM DataWorks Data Load API? Can you implement data masking when using IBM DataWorks Data Load API to protect confidential information?

A: Yes, IBM DataWorks Data Load supports data masking. The information on how to accomplish this can be found in DataWorks API documentation Integrating the Data Load REST API into your application. Here is an excerpt of that document:

... If you classify the data in a source column as sensitive, Data Load masks the data in that column when it is moved to the target

Note: This question was answered on dW Answers by user jcantella.


text:
Q: Get the value of columns on Check_changed Event of checkbox in gridview I have a grid view which contains date and time string in dataBound field and check box in item template field. Now when user check any check box, i want to make isChecked field of my data table(Which is data source for gridview and isCheck is added programatically) true/false accourdingly. How can I get date time string from gridview based on the check box checked/uncheked??

A: You can do like...
<asp:TemplateField HeaderText="Date">
    <ItemTemplate>
      <asp:Label ID="lblDate" runat="server" Text='<%# Eval("Date") %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>
     <asp:TemplateField HeaderText="Checkbox">
        <ItemTemplate>
           <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true"
                    oncheckedchanged="CheckBox1_CheckedChanged" />
         </ItemTemplate>
</asp:TemplateField>

protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
   String Date = ((Label)((CheckBox)sender).Parent.FindControl("lblDate")).Text;
}


text:
Q: TNS:could not resolve service name error in asp.net I am connecting to oracle database through asp.net. My code is running well on server machine but when I try to run it on local machine I am getting TNS error.
My connection Strings are :
 <add name="oraclebldb" connectionString="DataSource=SKM.SMEBANK.ORG;Persist Security Info=True;User ID=bldb;Password=bldb;Unicode=True" providerName="System.Data.OracleClient"/>
    <add name="OraConnectionString" connectionString="Data Source=skm;Persist Security Info=True;User ID=bldb;Password=bldb;Unicode=True" providerName="System.Data.OracleClient"/>

A: There must be tnsname.ora file in your local machine where you must be having oracle client installed.
go to
localdrive:\oracle\product\oracle version\client_1\Network\admin
Note: localdrive must b C or D based on location given at the time of installation
or
go to command prompt and type path which will give you the oracle home directory path of your local machine.
See below definition for your reference
mydb =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = myserver )(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = mydb)
)
)


text:
Q: jquery loop to create dynamic-multiple vars I am not sure if this is possible, but I want to create a multiple vars dynamically, for instance, these are the vars I create manually,
var left_1 = $('.column-global.left .item-global').eq(0);
var left_2 = $('.column-global.left .item-global').eq(1);
var left_3 = $('.column-global.left .item-global').eq(2);

but the problem is I only need two or one vars above sometimes. but three is the max.
so I am thinking of passing a parameter into the function to tell the code to create either 2 or 3 vars,
// I declare empty vars first
var left_1;
var left_2;
var left_3;

// get the number from somewhere, from the class for instnace
var last_class = $(this).attr("class").split(' ').slice(-1);

// loop the number with for loop
for( var i = 1; i <= last_class; i++){
    left_1 = $('.column-global.left .item-global').eq(i-1);
}

but you notice that I am stuck - how can I loop the var in the {} of the for-loop?
basically I want the for loop to produce the multiple vars like these (same as above),
var left_1 = $('.column-global.left .item-global').eq(0);
var left_2 = $('.column-global.left .item-global').eq(1);
var left_3 = $('.column-global.left .item-global').eq(2);

is it possible??
thanks.
p.s.
some answers here suggesting an array, but I have another problem further...
bcos I also need to pass the vars into another function which is kept within that parent function like this,
another_function(left_1, left_2, left_3);

so how can I achieve this with the array?? thanks

A: Instead of running the same selector 3 times and pulling out the item you want one at a time, why not just run it once and store that jQuery object?
var $globals = $('.column-global.left .item-global')

Then you can use whichever element(s) you need when you want.
$globals.eq(1).doSomething();

Or because a jQuery object is an Array-like object, you can get each individual DOM element by index, like:
$globals[1] // to get the actual non-jQuery wrapped DOM element

EDIT: With regard to the update in your question, first I'd rework the function if possible to accept 1 jQuery object.
If that is not possible, and you just need to pass individual arguments, I'd do one of two things.
First idea.
If possible, change the function so that it can accept DOM elements, then wrap them inside the function:
var $globals = $('.column-global.left .item-global');

another_function.apply( this, $globals.get() );

another_function(left_1, left_2, left_3) {
      // Wrap the DOM elements
    for( var i = 0, len = arguments.length; i < len; i++ ) {
        arguments[ i ] = $( arguments[ i ] );
    }
    // ...the rest of the code
}

By calling your another_function with .apply(), you're able to pass an Array of arguments, which will be assigned to the various parameters for the function.
Here we used jQuery's .get() method to pass an Array of DOM elements.
Second idea.
If you absolutely must accept individually wrapped DOM elements, do the same as above, but create the Array of individually wrapped elements like this:
var $globals = $('.column-global.left .item-global').map(function() {
    return $(this);
});

another_function.apply( this, $globals.get() );

This uses .map() to create a jQuery object of jQuery objects, then uses .get() to pull the Array out of the object.
But really I'd change your another_function if possible.

A: Why not use an array?
var left = []

for( var i = 1; i <= last_class; i++){
     left[i] = $('.column-global.left .item-global').eq(i-1);
}

or more likely, since arrays are 0-based:
for( var i = 0; i < last_class; i++){
     left[i] = $('.column-global.left .item-global').eq(i);
}i


text:
Q: Use of singletons in compiler I am writing a compiler for a C++-like language. I have to deal with symbol table which is represented in my code with class that has only static data and methods.
It's like:
class GlobalTable
{
    /* static members */
    static map<int, Symbol*> symbol_by_id;
    static map<Symbol*, int> id_by_symbol;

    /* some static methods */
};

Also is have a class which represents config:
class GlobalConfig
{
    static const int int_size;
    /* and so on ... */
};

I need to access these from a lot of places. Passing it around will result in swelling of code.
Is it convenient to use my class like that, or there is a better way to organize everything?

A: In a compiler, usually you store a symbol type in a symbol table, for some definition of symbol. Generally, I have a symbol table per scope, so the global scope in each module or compilable unit has its own symbol table.
You'll also have AST nodes that have symbols and symbol subtpes as their members.
Most internal compiler apis deal with symbol and ast subtypes, and those are stored in a indexed, fast access data structure. All of this has to be available to most compiler functions, so you either use a global compiler or context variable, or pass one around as a paramter.
Strictly, there is no need to use singletons. I can only talk in examples, so the way I do it is with a Compiler class that has instance members like currentScope and globalScope as well as the root AST or currentCompilableUnit, so the parser main instantiates a Compiler, and everything is reentrant. It is a bit more convenient, though, if your compiler instance is a global variable, so your functions can omit the compiler parameter, but besides that, not really any need for any others.
In short, it is typical for most APIs to include a "scope" or "compiler" struct or class in many of its signatures. Though if you use OOP to model the compiler, any methods of the class have implicit "this" access.


text:
Q: Get referer url from google cloud function I have a google cloud API function that is built on Node.js. I want to find the source of API request. I mean request header referer. I have tried using req.get('referer') but that was returning null. Can I access this information in any other way? Please help

A: Doing a quick test for the same situation you're handling, it works without any issue.
It was tested with: curl "<FUNCTION_ URL>" --referer "https://google.com"
And to get the request header, I used: req.get('Referrer')
Have in mind that if the URL is not valid, the result would be undefined, as follows:

If the solution provided still does not work, it might be an issue with your request to Cloud Functions.


text:
Q: I seem to have two different Vim environments. What is causing this? I am trying to set up a development environment on Windows 10. So far I've installed Vim and Cmder (the full version with Git for Windows).
Playing around, I noticed some strange behavior which I don't understand, but I feel like it is important that I understand.
Case A

*

*I open PowerShell

*Locate the folder that contains vim.exe

*Run .\vim.exe

*Vim pops up and displays the default screen (VIM - Vi IMproved, version 8.1.1, etc.)

*In Normal Mode I type :version to check the version number and to see where my _vimrc file is located

*Vim gives me the expected output

Case B

*

*I open Cmder and open a new PowerShell tab (I am assuming that that gives me access to the PowerShell instead of the default cmd.exe, but please correct me if I am wrong.)

*NOW THIS IS WHERE IT GETS INTERESTING
If I repeat steps 2-6 exactly as in Case A, I get exactly the same result.
BUT:
If instead of locating the folder that stores vim.exe I just type in vim and hit Enter it opens Vim once again, but this time it has a tab on the bottom that says "unix". See attached images.
Out of curiosity, in Normal Mode I type :version, just like in Case A, but this time I am getting a different date in the version section, a different selection of options, and a different Unix-like path to the vimrc file which in now .vimrc instead of _vimrc.

What gives? My guess is that Git for Windows that came with Cmder is simulating a Unix environment and accessing a different Vim version that was compiled for Unix?
If this is true, then could you help me make sense of this Windows/Unix environment duality? Do I now have two HOME folders, two copies of the vimrc file, and two copies of who knows what else? What is simulating this Unix environment - Cmder?
Thanks!

A: I don't have experience with Cmder, but I use Git for Windows a lot.
Git for Windows comes with some Unix utilities and uses Cygwin which is Unix emulator for running those. Vim is among them as default text editor for commit messages, etc. So it might be it.
I tried to reproduce this on my machine. but I cannot reproduce what you are seeing. Nonetheless I found the vimrc file for the Vim you are probably using in the second case.
It is in <Cmder-dir>\vendor\git-for-windows\etc\vimrc.

A: You have two different versions of Vim installed, and depending on the environment you start it from, one or the other gets selected. Git (as a tool that initially was developed on and for Linux) typically brings with it a set of Windows-ports.
You can check what Vim binary is used (respectively) from within Vim via
:echo v:progpath

Whether you live with this duplication or try to consistently use one Vim instance is up to you. It looks like the Vim that accompanies Git has more Unix-centric settings; it might be good to keep that to avoid interoperability issues.
You definitely don't need to clone your whole Vim configuration - as long as you stick to Unix-style (LF) line endings, it can be understood by any Vim. By setting the HOME environment variable (but that may affect other programs!), you can make Vim use the same location. Else, you could give one Vim config location a small .vimrc that just corrects 'runtimepath', and then :sources the "real" vimrc from the other location.


text:
Q: не складываются значения checkbox

function onclickCheckbox(cb1,cbv1) {
  var cb = document.getElementsByName('check1')[cb1];
  if (cb.checked) {
    var cbv=cbv+parseInt(document.getElementsByName('check1')[cb1].value);
    document.getElementsByName('chires')[cbv1].value=cbv;

}};
 <input type="checkbox" name="check1" class="liver_1" value="5"onclick="onclickCheckbox(0,0)">
если у вас болит печень 1

<input type="checkbox" name="check1" class="liver_1" value="3" onclick="onclickCheckbox(1,0)">
если у вас болит печень 1

<input type="text" name="chires" value="0" size="5">
Нарушение порядка 'чи' печени(застой 'чи').

A: Не складывается из-за ошибки в коде. Переменная cbv не определена на момент использования.
Также есть логическая ошибка - после снятия галочки значение не вычитается
Должно быть как-то так:

function onclickCheckbox(cb1,cbv1) {
  var cb = document.getElementsByName('check1')[cb1];
  var sum_node = document.getElementsByName('chires')[cbv1];
  var current = parseInt( sum_node.value );

  if(cb.checked) {
    var cbv=current+parseInt(cb.value);
  } else {
    var cbv=current-parseInt(cb.value);
  }
  sum_node.value=cbv;
};
 <input type="checkbox" name="check1" class="liver_1" value="5"onclick="onclickCheckbox(0,0)">
если у вас болит печень 1

<input type="checkbox" name="check1" class="liver_1" value="3" onclick="onclickCheckbox(1,0)">
если у вас болит печень 1

<input type="text" name="chires" value="0" size="5">
Нарушение порядка 'чи' печени(застой 'чи').

A: var summ = 0;

for (var i = 0; i<document.getElementsByTagName ("input").length; i++) {
    if (document.getElementsByTagName ("input")[i].type == "checkbox") {
        var num = parseInt (document.getElementsByTagName ("input")[i].value)
        summ += num;

        if (i==document.getElementsByTagName ("input").length-1) {
            alert (summ);
        };
  };
};

Получение суммы текстбоксов. Без всяких имён :)


text:
Q: Vue Vuex: old data remains for some time before computed property changes I'm new to vuex and I still I have over used it. For say, I have a product lists in my store state. When I view one product i make axios call with that product.id and commit the product data into currentProduct state. Then if I view another product then the page is rendered with currentProduct state i.e old
 data at first then after my action commits.. it is then updated to newly fetched currentProduct then vue changes my view data to new data. The user can clearly see old data being replaced by new data.
But I want to load the page only after new data is commited to my state.
`store.js`

state :{
    productList:{},
    currentProduct:{
     id:'',name:'',price:'','seller'
    }
},
mutations:{
    UPDATE_CURRENT_PRODUCT : (state, data) =>{
     state.currentProduct = Object.assign({},state.currentProduct, data);
    }

},
actions:{
    fetchProducts(){
     const response = fetch...... // logic to fetch product
     commit('UPDATE_CURRENT_PRODUCT', response.data);
    }
}

My render page:
This page displays the lists of my products
'productList.vue'

{{product.name}}

computed(){

    ...mapState(['productList'])

},
methods:{
    viewProduct(product_id){
        this.$store.state.dispatch('fetchProducts', product_id);
    }
}

This page renders the view of that particular product
`product.vue`

{{currentProduct.name}}

computed(){

    ...mapState(['currentProduct'])

}

In my product.vue first old data is shown then after some time new data replaces it ... Something is missing.. I want to see the new data directly with out seeing old data being replaced by new data. Is there a way around vuex

A: The key part is:

I want to load the page only after new data is commited to my state

You want to make the async methods follow each other. There is a cool way to do that.
I guess in the fetchProducts() an axios get / post the data. Because axios is based on promise, you can return with it.
fetchProducts() {
 return axios.get('/get/some/data')
    .then(r => { // commit and stuff
     })
    .catch(e => { // error handling
     })
}

Then you can easily do this:
this.$store.state.dispatch('fetchProducts', product_id)
 .then(r=> {if(r){ // get the data from vuex
 } else { // error
 })
 .catch(e => {});

The then of dispatch runs after the then of axis. (e.g.: If there are two axios call what have to run sequentially, you can call the second one in the then method of first, and it solves the problem.)
I hope you understand this. :)

A: The simple solution would be to reset the data to a initial value when the actions are loaded/dispatched.
So, try editing your code from this:
actions:{
    fetchProducts(){
     const response = fetch...... // logic to fetch product
     commit('UPDATE_CURRENT_PRODUCT', response.data);
    }
}

To this:
actions:{
    fetchProducts(){
     // Add below line to reset the state when loading.
     commit('UPDATE_CURRENT_PRODUCT', null);
     /***********************************************/
     const response = fetch...... // logic to fetch product
     commit('UPDATE_CURRENT_PRODUCT', response.data);
    }
}

The above solution worked for me. Hope this works for you or someone else too.

A: For this you should use async await so that your component will only be updated after your new data is retrieved.
async fetchProducts(){
    await const response = fetch...... // logic to fetch product
    commit('UPDATE_CURRENT_PRODUCT', response.data);
   }

And the same in your viewProduct method.
Refer following llink for more details(last example on the page)
https://vuex.vuejs.org/guide/actions.html


text:
Q: Show that the canonical inclusion $ L^\infty → L^1 $ is continuous but not compact. (a problem in real analysis) Would you mind giving some hints (not the whole solution) to me?

Problem: Consider the space $ L^p = L^p(0, 1),$ with $ p ∈ [1, ∞].$ Show that the canonical inclusion
  $ L^\infty → L^1 $
  is continuous but not compact.
Is it possible to find $ p, q ∈ [1, ∞] $ with $p < q$ such that the inclusion $L^q \to L^p$ is compact?

A: If a set $C$ is compact in $\mathbb L^p(0,1)$, then
  $$\lim_{h\to 0}\sup_{f\in C}     \int_{(0,1)\cap (h,1-h) } \left\lvert f(x+h)-f(x)\right\rvert^p\mathrm dx=0.            $$
In order to disprove compactness, find for any $n$ a set $A_n$ such that
$$ \int_{\left (0,1-2^{-n}\right)   } \left\lvert\mathbf 1_{A_n}  \left (x+2^{-n}  \right)-\mathbf 1_{A_n}(x)\right\rvert^p\mathrm dx\geqslant 1/2.$$
For example, choose $A_n$ as a union of $2^{n-1}$ intervals of length $2^{-n}$, with a gap of $2^{-n}$  between them.


text:
Q: Integrate GWT Compile and selenium testing into a single maven goal I wanted to create a single gwt project which gets selenium tested just by typing 'mvn test'. That is, I need plugins to

*

*compile,

*bring up gwt server,

*run selenium tests,

*bring down gwt server.

I am not able to find something for steps 2 and 4. Does anyone have experience with this?
Thanks,
Aman

A: Should be straightforward if you use the integration-test phase instead:

*

*prepare-package ⇒ gwt:compile

*pre-integration-test ⇒ jetty:start (or tomcat7:start, or similar with another plugin)

*integration-test ⇒ your selenium tests

*post-integration-test ⇒ jetty:stop (or equivalent for another plugin)

If you'd like to run the selenium tests in DevMode, then I'm afraid there's no way to do it: there's no equivalent to gwt:run that would fork the process and allow its termination with another mojo (like jetty:start+jetty:stop vs. jetty:run)
Also, maybe you could use Arquillian to start the server right from within your test, but that wouldn't solve the issue of either compiling the GWT module or launching DevMode (these can be launched from Java code, but it's discouraged)

A: check the gwt:test goal of Maven GWT Plugin
In your pom:
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>gwt-maven-plugin</artifactId>
            <version>2.4.0</version>
            <configuration>
                <mode>selenium</mode>
                <selenium>localhost:4444/*firefox"</selenium>


text:
Q: Interpolate curved line betweenstart and end points for ggplot2 I'd like to create a sankey-like plot that I can create in ggplot2 where there are curved lines between my start and end locations. Currently, I have data that looks like this:
df <- data.frame(Line = rep(letters[1:4], 2),
                 Location = rep(c("Start", "End"), each=4),
                 X = rep(c(1, 10), each = 4),
                 Y = c(c(1,3, 5, 15), c(9,12, 14, 6)),
                 stringsAsFactors = F)

ex:
  Line Location  X Y
1    a    Start  1 1
2    a      End 10 9

and creates a plot that looks something like this:
library(ggplot2)
ggplot(df) +
  geom_path(aes(x= X, y= Y, group = Line))

I would like to see the data come out like this:

This is another option for setting up the data:
df2 <- data.frame(Line = letters[1:4],
                  Start.X= rep(1, 4),
                  Start.Y = c(1,3,5,15),
                  End.X = rep(10, 4),
                  End.Y = c(9,12,14,6))

ex:
  Line Start.X Start.Y End.X End.Y
1    a       1       1    10     9

I can find examples of how to add a curve to the graphics of base R but these examples don't demonstrate how to get a data frame of the points in between in order to draw that curve. I would prefer to use dplyr for data manipulation. I imagine this will require a for-loop to build a table of the interpolated points.
These examples are similar but do not produce an s-shaped curve:
Plotting lines on map - gcIntermediate
http://flowingdata.com/2011/05/11/how-to-map-connections-with-great-circles/
Thank you in advance!

A: The code below creates curved lines via a logistic function. You could use whatever function you like instead, but this is the main idea. I should note that for other than graphical purposes, creating a curved line out of 2 points is a bad idea. It implies that the data show a certain type of relation while it actually doesn't imply that relation.
df <- data.frame(Line = rep(letters[1:4], 2),
                 Location = rep(c("Start", "End"), each=4),
                 X = rep(c(1, 10), each = 4),
                 Y = c(c(1,3, 5, 15), c(9,12, 14, 6)),
                 stringsAsFactors = F)

# logistic function for curved lines
logistic = function(x, y, midpoint = mean(x)) {
  ry = range(y)
  if (y[1] < y[2]) {
    sign = 2
  } else {
    sign = -2
  }
  steepness = sign*diff(range(x)) / diff(ry)
  out = (ry[2] - ry[1]) / (1 + exp(-steepness * (x - midpoint))) + ry[1]
  return(out)
}

# an example
x = c(1, 10)
y = c(1, 9)
xnew = seq(1, 10, .5)
ynew = logistic(xnew, y)
plot(x, y, type = 'b', bty = 'n', las = 1)
lines(xnew, ynew, col = 2, type = 'b')

# applying the function to your example
xnew = seq(min(df$X), max(df$X), .1) # new x grid
m = matrix(NA, length(xnew), 4) # matrix to store results

uniq = unique(df$Line) # loop over all unique values in df$Line
for (i in seq_along(uniq)) {
  m[, i] = logistic(xnew, df$Y[df$Line == uniq[i]])
}
# base R plot
matplot(xnew, m, type = 'b', las = 1, bty = 'n', pch = 1)

# put stuff in a dataframe for ggplot
df2 = data.frame(x = rep(xnew, ncol(m)),
                 y = c(m),
                 group = factor(rep(1:ncol(m), each = nrow(m))))

library(ggplot2)
ggplot(df) +
  geom_path(aes(x= X, y= Y, group = Line, color = Line)) +
  geom_line(data = df2, aes(x = x, y = y, group = group, color = group))


text:
Q: Encrypt and sign a message using Microsoft Security Support Provider Interface (SSPI) I want to use Microsoft's Security Support Provider Interface (SSPI) in a Windows Domain environment (with Kerberos) to send encrypted and signed messages between two entities (in C++).
Based on the documentation within the MSDN, there are the two functions MakeSignature() and EncryptMessage() [1] but the documentation as well as the example code [2] do not explicitly anwser the question of how to send data encrypted and signed (according to encrypt-than-mac).
Can anyone confirm that I have to use manually invoke EncryptMessage() and MakeSignature() in sequence to get to the desired result? Or do I miss something there and EncryptMessage() has a way to directly create a signature of the encrypted data?
[1] MSDN documentation of EncryptMessage() and MakeSignature()
https://msdn.microsoft.com/en-us/library/windows/desktop/aa378736(v=vs.85).aspx
https://msdn.microsoft.com/en-us/library/windows/desktop/aa375378(v=vs.85).aspx
[2] MSDN Example Code
https://msdn.microsoft.com/en-us/library/windows/desktop/aa380531(v=vs.85).aspx
---- Reply to Remus Rusanu's answer 2017-03-09 ---------------------------
Thanks @Remus Rusanu for your answer, I didn't take the GSSAPI interoperability document into account yet.
Here it is stated that "GSS_Wrap and GSS_Unwrap are used for both integrity and privacy with the use of privacy controlled by the value of the "conf_flag" argument." and that "The SSPI equivalent to GSS_Wrap is EncryptMessage (Kerberos) for both integrity and privacy".
You said that "EncryptMessage [...] will do the signing too, if the negotiated context requires it.". This means for me, that the at least the following fContextReq flags need to be set for InitializeSecurityContext():

*

*ISC_REQ_CONFIDENTIALITY

*ISC_REQ_INTEGRITY

Can you (or somebody else) can confirm this?
---- Update 2017-03-16 ----------------------------------------------------------------
After further research I came up with the following insights:

*

*The Kerberos specific EncryptMessage() function does not provide message integrity, regardless of how the Securitycontext was initialized.

*

*The general EncryptMessage() and general DecryptMessage functions support the feature of creating and verifying the message's integrity because there exists some supporting Security Support Providers (SSPs) - but Kerberos does not.

*If DecryptMessage would check the message's integrity, there must be a respective error return code in case of a modified message. The general DecryptMessage interface lists the error code "SEC_E_MESSAGE_ALTERED" which is described as "The message has been altered. Used with the Digest and Schannel SSPs.".

*The specific DecryptMessage interface for the SSPs Digest and Schannel lists the SEC_E_MESSAGE_ALTERED - but the Kerberos DecryptMessage does not.

*Within the parameter description of the general EncryptMessage's documentation, the term 'signature' is used only regarding the Digest SSP: "When using the Digest SSP, there must be a second buffer of type
SECBUFFER_PADDING or SEC_BUFFER_DATA to hold signature information".

*MakeSignature does not create a digital signature according to Wikipedia's definition (authenticity + non-repudiation + integrity). MakeSignature creates a cryptographic hash to provide message integrity.

*

*The name of the MakeSignature() function leads to the idea that SSPI creates a digital signature (authenticity + non-repudiation + integrity) but the MakeSignature documentation explains that only a cryptographic checksum is created (providing integrity): "The MakeSignature function generates a cryptographic checksum of the message, and also includes sequencing information to prevent message loss or insertion."

*The VerifySignature documentation helps as well to clarify SSPI's terminology: "Verifies that a message signed by using the MakeSignature function was received in the correct sequence and has not been modified."

*From (1) and (2) it follows that one needs to invoke EncryptData() and afterwards MakeSignature() (for the ciphertext) to achieve confidentiality and integrity.
Hope that my self-answer will help someone at some point in time ;)
If someone has something to add or correct in my answer, please reply and help to improve the information collected here!

A: If I remember correctly you only call EncryptMessage/DecryptMessage and this will do the signing too, if the negotiated context requires it. For example if you look at SSPI/Kerberos Interoperability with GSSAPI it states that EncryptMessagepairs with GSS_Unwrap and DecryptMessage pairs with GSS_Wrap, without involving MakeSignature. The example in the link also shows that you must supply 3 SecBuffer structures (SECBUFFER_TOKEN, SECBUFFER_DATA and SECBUFFER_PADDING, the last I think is optional) to EncryptMessage and 2 for DecryptMessage. The two complementary examples at Using SSPI with a Windows Sockets Server and Using SSPI with a Windows Sockets Client give  full functional message exchange and you can also see that MakeSignature/VerifySignature are never called, the signature is handled by Encrypt/Decrypt and is placed in the 'security token' header or trailer (where to it goes on the wire is not specified by SSPI/SPNego/Kerberos, this is not TLS/Schannel...).

A: If you want to create a GSS Wrap token with only a signature (not encrypted), pass KERB_WRAP_NO_ENCRYPT as the qop value to EncryptMessage. The signed wrap token includes the payload and the signature.
MakeSignature creates a GSS MIC token - which is only the signature and does not include the payload. You can use this with application protocols that require a detached signature.


text:
Q: WordPress converts the hyphen to the dash in the title automatically In my WordPress blog, i found it would convert the hyphen character to the dash character automatically.
For example, I create a blog post with the following TITLE:
Wikipedia - the free encyclopedia
However, when I checked the post, I found the title was displayed as:
Wikipedia – the free encyclopedia
And I check the source code of HTML:
<title>Wikipedia – the free encyclopedia</title>

So, The hyphen (-) was changed to the dash (–), why was this?
How to disable such conversion?


text:
Q: Como colocar pontinho ou marcadores de localização no mapa Como posicionar aqueles "marcadores" no meu mapa, passando a Longitude e a Latitude?
Esse é meu script HTML do mapa:

E o JavaScript:
var map;
$('[href*="#mapa-"]').click(function () {
    var $map = $('.map-canvas', $(this).attr('href'));
    map = new google.maps.Map($map.get(0), {
        zoom: 10,
        center: new google.maps.LatLng($map.data('opt').txtLatitude, $map.data('opt').txtLongitude)
    });
});

A: Segundo a documentação na seção Marcadores.
O construtor google.maps.Marker pega um único literal do objeto Marker options que especifica as propriedades inicial do marcador. Os campos a seguir são particularmente importantes e comumente definidos durante a construção do marcador.

*

*position: (obrigatório) especifica um LatLng que identifica a localização inicial do marcador.

*map (opcional): especifica o objeto Map no qual o marcador deve ser posicionado.

No construtor Marker, você deve especificar o mapa no qual o marcador deve ser adicionado. Se você não especificar esse argumento, o marcador será criado, mas não será anexado (ou exibido) no mapa. Você poderá adicionar o marcador posteriormente, chamando o método setMap() do marcador.
Exemplo(retirado da documentação):
var myLatlng = new google.maps.LatLng(-19.212355602107472,-44.20234468749999);
  var mapOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title:"Meu ponto personalizado"
  });