text:
Q: $\mathbb{P}(B) = 1 \implies \mathbb{P}(A \mid B) = \mathbb{P}(A)$ Suppose I have two events $A$, $B$ from the same sample space with $\mathbb{P}(B) = 1$ and $\mathbb{P}(A) > 0$. How can I show that $$\mathbb{P}(B) = 1 \implies \mathbb{P}(A \mid B) = \mathbb{P}(A)\text{?}$$
The definition of conditional probability doesn't help me, as it isn't clear what can be done with $\mathbb{P}(A \cap B)$. If I use Bayes' Theorem, I get $\mathbb{P}(B \mid A)\mathbb{P}(A)$, so the only way this would work is that $\mathbb{P}(B \mid A) = 1$. This makes intuitive sense, but I can't prove that $\mathbb{P}(B \mid A) = 1$.
This should be a trivial question, but I'm not seeing how to do it.
HINTS, not full solutions, are appreciated.

A: We have
$$P(A\cup B)=P(A)+P(B)-P(A\cap B)$$
but since $P(A\cup B)=P(B)=1$ then we get $P(A)=P(A\cap B)$.

A: $$P(B\,')=0\quad ,\quad P(A\cap B\,')\le P(B\,')=0$$
$$P(A|B)=\frac{P(A\cap B)}{P(B)}=P(A\cap (B\,')')=P(A)-P(A\cap B\,')=P(A)$$

A: Hints:

*

*If $\Pr(B)=1$ then $\Pr(A\cap B^c)\leq\Pr(B^c)=0$

*$\Pr(A)=\Pr(A\cap B)+\Pr(A\cap B^c)$

*$\Pr(A\mid B)\Pr(B)=\Pr(A\cap B)$

A: You should use the conditional probability definition indeed.
From the definition you have $P(A | B) =\frac{ P(A \cap B)}{P(B)} =P(A \cap B)$. As $P(B) = 1$.
Now if you take the intersection of two subsets, you have the elements that are in both subsets. Since $P(B) = 1$, this is like the sample space. Hence $P(A \cap B) = P(A)$.
Hence $P(A|B) = P(A)$


text:
Q: Youtube makes my secure server unsecure? The Youtube video make my website insecure, and I need it to be secure, what do I do to make it secure even though I have a Youtube video embeded? Simply I need my users to link videos.

I haven't really tried much since i searched the web and tried to research the issue but couldn't find any..

A: Change the http:// in the URL to video into //.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I calculate and hide my formulas in excel I have an excel file with a few sheets. After loading data to some sheets, the main sheet formulas must calculate some data. But if I tried to load only data from the file, it s empty because, until I open the excel file, the columns with formulas are not calculating. So how can I calculate formulas without opening ms excel?
I am working with python.

A: Openpyxl builds xlsx files, it does not interact with Excel so there is no instance of Excel and formulas are not executed. Openpyxl will provide either the value or formula in a cell depending of how the workbook is 'opened'. You need to interact with Excel so maybe something like this will help;

Xlwings interacts with Excel and therefore requires a local installation of Excel to use.
In the example cells A1 - A3 have integer values written and cell A4 has a formula written to sum A1:A3. The result of the summing, i.e. value of cell A4 is then printed which shows the value 16911.
You will see that Excel is opened but the workbook is hidden so no data can be seen. At the completion of the code run all instances of Excel are closed.
I have put a slight delay in the code so you can see that the Excel instance does not show the workbook or any of the data.
import time
import xlwings as xw

with xw.App() as app:
    app.display_alerts = False
    app.screen_updating = False

    filename = "formula_test.xlsx"
    wb = xw.Book(filename)
    ws = wb.sheets['Sheet1']

    ws.range("A1").value = 1234
    ws.range("A2").value = 5678
    ws.range("A3").value = 9999

    ws.range("A4").value = '=SUM(A1:A3)'
    time.sleep(10)  # Delay to check Excel instance

    print("Result :", ws.range("A4").value)

    wb.save(filename)
    wb.close()

There are other modules that can help with Excel formula calculation if this does not meet your requirement.
xlwings


text:
Q: SwiftUI View .tint(_ Color) method doesn't work I'm trying to change tint color for View.
What I got:
    var body: some View {
    Button {
        selectedTab = title
    } label: {
        VStack(alignment: .center) {
            image.renderingMode(.template)
            Text(title)
        }
        .foregroundColor(selectedTab == title ? .accentColor : .black.opacity(0.2))
        .padding()
    }
}

The problem:
When I use .accentColor(Color) in superview for this subview, Xcode said:

So, I use, like in docs: apple docs Use this method to override the default accent color for this view.  :
            if #available(iOS 15.0, *) {
            CustomTabView(tabs: "").tint(.red)
        } else {
            CustomTabView(tabs: "").accentColor(.green)
        }

Accent color work fine, but .tint doesn't. What I do wrong?

A: Your code doesn't work because when you use tint, and you select the tab, the tab's color gets overridden by the foregroundColor modifier. It'd set the tab's color to .accentColor, which is independent from the color that tint sets. The deprecated accentColor however, does set it, so that's why the deprecated accentColor modifier works.
One way to work around this is simply not use .accentColor for the foreground color. Use nil instead:
.foregroundColor(selectedTab == title ? nil : .black.opacity(0.2))

When it is nil, it will not override the tint.


text:
Q: AWS IAM Trust Policy - Allow only one resource to sts:AssumeRole Let's say the ARN of my State Machine is arn:aws:states:eu-west-1:123456789123:stateMachine:resource-1.
It has IAM role configured with some permissions and it's current trust policy is following:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "states.amazonaws.com"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
                "ArnEquals": {
                    "aws:SourceArn": "arn:aws:states:eu-west-1:123456789123:stateMachine:resource-1"
                }
            }
        }
    ]
}

The Condition specified in above trust policy is not working as I expect. My State Machine is not able to assume this IAM Role, however it works when I change like below, but there's no restriction to particular resource:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "states.amazonaws.com"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:states:eu-west-1:123456789123:stateMachine:*"
                }
            }
        }
    ]
}

My goal is to allow only this particular resource (arn:aws:states:eu-west-1:123456789123:stateMachine:resource-1) to assume this particular IAM role. All resources are in the same AWS Account.
I can't understand why the first trust policy doesn't work. Even AWS Documentation for Step Functions is showing it as an example: https://docs.aws.amazon.com/step-functions/latest/dg/procedure-create-iam-role.html#prevent-cross-service-confused-deputy


text:
Q: cross database trigger: server principal is not able to access the database under the current security context I have a two databases Source and Target hosted in the same SQL Server 2008 R2 instance. I have a Login which is mapped to Users in both databases. Each mapped User has a Role in its respective database which grants access to all objects in that database.
I have a cross-database trigger which propagates updates from a table in Source to a table in Target.
When I connect to the server in SQL Server Managment Studio with the Login and run an update query on Source, the cross-database update succeeds.
But when an equivalent update is initiated using the same Login from within an application, the trigger fails with error:
The server principal 'name' is not able to access the database 'Target' under the current security context.
By running a trace with SQL Server Profiler, I can verify that the update is being run under the same LoginName in both cases.
Questions:

*

*What is special about SSMS that allows the cross-database trigger to work?

*What does "current security context" mean?

*What do I need to modify to allow the update+trigger to work in the Application's context?
I've read about object ownership chaining, and I've not fully investigated that yet. But since it works in SSMS, I'm tempted to believe that a broken ownership chain is not the issue. But I could be wrong about that! I'd be really grateful for any diagnosis suggestions.

Update: I'm attempting to implement srutzky's suggestion. This is what I have run so far.
use [SourceDB];

create certificate [Access_TargetDB]
   encryption by password = 'password123'
      with subject = 'Cross-DB Access to TargetDB',
      expiry_date = '2099-12-31';

add signature to [MyTrigger]
    by certificate [Access_TargetDB]
    with password = 'password123';

backup certificate [Access_TargetDB]
    to file = 'C:\Access_TargetDB.cert';

use [TargetDB];

create certificate [SourceDB]
    from file = 'C:\Access_TargetDB.cert';

create user [SourceDBUser] for certificate [SourceDB];

exec sp_addrolemember 'StandardUserRole', 'SourceDBUser';

I am still getting the same error when attempting to update the table in SourceDB with the Application Role context.

I'm attempting to implement srutzky's 2nd suggestion. In addition to the above, I have also run the following. But the suggestion assumes a target stored procedure which I do not have, so maybe this isn't actually a valid test.
use master;

create certificate [SourceDB]
    from file = 'C:\SourceDB.cert';

create login [SourceDBLogin] from certificate [SourceDB];

grant authenticate server to [SourceDBLogin];

Still no change in the permissions available in the Application Role context.

A: This should be fairly simple to accomplish via module signing. Look at my other answers here on DBA.SE:

*

*Permissions not allowing Update or Select on a trigger executed function

*Permissions in triggers when using cross database certificates
The basic concept is as follows:

*

*Create a Certificate in the Source DB (i.e. where the Trigger exists).

*Sign the Trigger using ADD SIGNATURE.

*Create that same Certificate in the Target DB.

*Create a User in the Target DB from that Certificate.

*Grant that Certificate-based User INSERT, UPDATE permission on the table in the Target DB.

A: I discovered that the problem with update+trigger initiated from within the Application is because the Application is using an Application Role to supersede the Login's security context.
More information can be found in this blog post by Brian Kelley: SQL Server Security: Pros and Cons of Application Roles. In particular:

When an application role takes effect, it overrides any database and login credentials for the connection. That means if I try to access another database using the three-part naming convention like Northwind.dbo.Customers, I won't map into the database based on my original login. The only user I can use is guest.

So answers to the specific questions:

*

*SSMS is not special; it is the Application that blocks the cross-database access.

*The current security context is the list of login tokens and user tokens through which permissions are granted/denied. For example, the following query returns two rows when run in SSMS
SELECT name, type, usage FROM sys.login_token;

name         type           usage
------------ -------------- ---------------
mylogin      SQL LOGIN      GRANT OR DENY
public       SERVER ROLE    GRANT OR DENY

When the same query is run in the Application Role's context, only the public login token remains and the usage for that token becomes "DENY ONLY".
More information on TechNet: Understanding Execution Context

*I'm still looking for a solution! The Application developer will not abandon the recently added Application Role. And it would be exremely unwise to grant the necessary permissions to the public role in the Target database.


text:
Q: Reciprocating flow in a channel over a heated surface The following is a coupled heat transfer and fluid flow problem.
A thick plane channel is being heated with a constant flux from the bottom (at $y=-e$) with a constant heat flux $q$ as shown in the attached figure. The heated channel is subjected to a reciprocating flow with velocity $U(t)=u_{max}\sin(2\pi ft)$. I must state here that the flow velocity has a mean of $0$ which means for the first half of the cycle it reaches $u_{max}$ and in the second half reaches $-u_{max}$. In the expression for velocity the term $f$ stands for freqency of the oscillating flow. Thus, the time period of the flow is $\tau=1/f$. This indicates that for $0<t<\tau/2$, the boundary at ${x=0, 0<y<d}$ acts as the inlet, while for the second half, i.e., $\tau>t>\tau/2$ the boundary at ${x=L, d>y>0}$ is the inlet. The top plane ($y=d, 0<x<L$), the left solid face ($x=0, 0>y>-e$) and the right solid face ($x=L, -e<y<0$) are all insulated. The solid and fluid domains are coupled through the temperature and flux continuity at the interface ($y=0$).

In this scenario, after a certain time the entire system is supposed to reach a cyclic steady state. I will now mention the governing equations and boundary conditions:
Fluid
Hydrodynamic
$$\frac{\partial u}{\partial x} + \frac{\partial v}{\partial y} = 0 \tag1$$
$$\frac{\partial u}{\partial t} + u \frac{\partial u}{\partial x} + v \frac{\partial u}{\partial y} = \frac{-1}{\rho} \frac{\partial p}{\partial x} + \mu (\nabla^2 u) \tag2$$
$$\frac{\partial v}{\partial t} + u \frac{\partial v}{\partial x} + v \frac{\partial v}{\partial y} = \frac{-1}{\rho} \frac{\partial p}{\partial y} + \mu (\nabla^2 v) \tag3$$
No slip and No penetration condition on $y=0$ and $y=d$.
Thermal
$$\rho c_p \frac{\partial T}{\partial t} + \rho c_p u \frac{\partial T}{\partial x} + \rho c_p v \frac{\partial T}{\partial y}= k_f (\nabla^2 T) \tag4$$
The fluid has an inlet temperature $T=T_i$. So the boundary condition will be $T(x=0)=T_i, \frac{\partial T}{\partial x} \vert_{x=L} = 0$ for $\tau/2>t>0$ and $T(x=L)=T_i, \frac{\partial T}{\partial x} \vert_{x=0} = 0$ for $\tau/2<0<\tau$
Solid
Thermal
$$\rho_s c_{p,s} \frac{\partial T_s}{\partial t} = k_s \nabla^2 T_s \tag 5$$
The boundary conditions are: $\frac{\partial T_s}{\partial t}\vert_{x=0}=\frac{\partial T_s}{\partial t}\vert_{x=L} = 0$ and $-k_s\frac{\partial T_s}{\partial t} = q$.Here, $k_s$ is the solid thermal conductivity.
Coupling
At the interface between the solid and the fluid, the following holds which couples the problem:
Continuity of Temperature
$$T(x,0)= T_s(x,0), 0<x<L \tag6$$
Continuity of Flux
$$-k_s \frac{\partial T_s}{\partial y}\vert_{y=0,x} =  -k_f \frac{\partial T}{\partial y}\vert_{y=0,x} \tag7$$
The objective is to solve for the velocity and the temperature fields in the solid and fluid. Also, the flux transfer from the solid to the fluid at the interface is of interst. I have found a Mathematica fluid solver here, but it only simulates isothermal flows:
(1) Are there non-isothermal flow mathematica solvers ?
(2) How should I model the coupling between the solid and fluid using (6) and (7) ? In a time-step what should be calculated first, the solid temperature or the fluid? I do understand that both the fields have to be calculated simultaneously.
(3) Finally, since the flow is reversing, how should I model the switching of boundary conditions during each half cycle ?
Some parameter values L=0.025, d=0.002, e=0.002, k_f=0.614, k_s=390, q=5000, rho=997, rhos=8960, mu=8.90*10^-4, cp =4178, cps =385. These parameters represent flow of water over copper. A typical flow velocity profile can be U=0.3*sin(2*pi*1*t), which is a 1Hz flow giving tau=1.
A typical CFD result obtained from COMSOL
For the same material combinations but with a e=4, f=0.5, umax=0.22875, Ti=288 and a heat input of $1W$ which translates to q=40000, I attach the average interface ($y=0$) temperature (line integrated along the length from $x=0$ to $x=L$) variation with time.

A: We can solve this problem with method proposed on my page.
Solution1. We use nondimensional form of equations with scale d and $t_s = d^2/(k_f/(c_p \rho))$. We define two regions reg1, reg2 to describe fluid flow and temperature consequently. This is code in a case of divergent form of temperature equation. We use scaled form of heat flux qn = q ts/(cp rho)/d, but temperature is unscaled
{f = 1; L = 0.025, d = 0.002, e = 0.002, kf = 0.614, ks = 390,
 q = 5000, rho = 997, rhos = 8960, mu = 8.90*10^-4,
 cp = 4.178*10^3 (*J/kg/\[Degree]K*), cps = 385}; Pr =
 mu/rho/(kf/(cp rho));
Pr0 = Pr;   a = ks/kf; ts = d^2/(kf/(cp rho)); as =
 ts ks/(cp rho)/d^2; rs = cps rhos/(cp rho); u0 = .25 ts/d; om =
 2 Pi f ts; t0 = 1/om/10; nn = Round[4 Pi/(t0 om)]; qn =
 q ts/(cp rho)/d;
Needs["NDSolve`FEM`"]

reg1 = ImplicitRegion[0 <= x <= L/d && 0 <= y <= 1, {x, y}]; reg2 =
 ImplicitRegion[0 <= x <= L/d && -e/d <= y <= 1, {x, y}];
UX[0][x_, y_] := 0;
VY[0][x_, y_] := 0;
P[0][x_, y_] := 0;
Tfs[0][x_, y_] := 0; appro =
 With[{k = 2. 10^4}, ArcTan[k #]/Pi + 1/2 &];
ade[y_] := (as + (1 - as) UnitStep[y] /. UnitStep -> appro);
rde[y_] := (rs + (1 - rs) UnitStep[y] /. UnitStep -> appro);

Do[
    {UX[i], VY[i], P[i]} =
      NDSolveValue[{{Inactive[

           Div][({{-\[Mu], 0}, {0, -\[Mu]}} . Inactive[Grad][
                          u[x, y], {x, y}]), {x, y}] + D[p[x, y], x] +
                  UX[i - 1][x, y]*D[u[x, y], x] +

         VY[i - 1][x, y]*D[u[x, y], y] + (u[x, y] - UX[i - 1][x, y])/
                    t0 ,
                Inactive[

           Div][({{-\[Mu], 0}, {0, -\[Mu]}} . Inactive[Grad][
                          v[x, y], {x, y}]), {x, y}] + D[p[x, y], y] +
                  UX[i - 1][x, y]*D[v[x, y], x] +

         VY[i - 1][x, y]*D[v[x, y], y] + (v[x, y] - VY[i - 1][x, y])/
          t0,
                D[u[x, y], x] + D[v[x, y], y]} == {0, 0, 0} /. \[Mu] ->
       Pr0, {

      DirichletCondition[{u[x, y] == u0*Sin[om*i*t0]*y*(1 - y),
        v[x, y] == 0}, x == 0],
            DirichletCondition[{u[x, y] == 0, v[x, y] == 0},
              y == 0 || y == 1]},
     DirichletCondition[p[x, y] == 0, x == L/d]}, {u, v,
     p}, {x, y} \[Element] reg1,
        Method -> {"FiniteElement",
            "InterpolationOrder" -> {u -> 2, v -> 2, p -> 1},
            "MeshOptions" -> {"MaxCellMeasure" -> 0.01}}];
  ux = If[y <= 0, 0, UX[i ][x, y]]; vy = If[y <= 0, 0, VY[i ][x, y]];
  Tfs[i] = NDSolveValue[{rde[y] ((ux*D[T[x, y], x] +
                    vy*D[T[x, y], y]) + (T[x, y] - Tfs[i - 1][x, y])/
                     t0 ) -
        Inactive[Div][
         ade[y]*Inactive[Grad][T[x, y], {x, y}], {x, y}] ==
              NeumannValue[qn, y == -e/d ],
            DirichletCondition[{T[x, y] == 0},

       x == 0 + L/d (1 - Sign[Sin[om*i*t0]])/2 && 0 <= y <= 1]},
     T, {x, y} \[Element] reg2,
         Method -> {"FiniteElement",
             "InterpolationOrder" -> { T -> 2},
             "MeshOptions" -> {"MaxCellMeasure" -> 0.01}}] //
    Quiet;, {i, 1, nn}] // AbsoluteTiming

Visualization of temperature
Table[DensityPlot[Tfs[i][x, y], {x, y} \[Element] mesh1,
  ColorFunction -> "Rainbow", PlotLegends -> Automatic,
  AspectRatio -> 1/2, PlotLabel -> i ts t0, PlotRange -> All,
  PlotPoints -> 50], {i, 5, nn, 10}]

Solution 2. We use unscaled version of code with given input parameters and boundary conditions as in a paper Oscillatory Heat Transfer in a Pipe Subjected to a Laminar Reciprocating Flow by T. S. Zhao &
P. Cheng
{f = 1; L = 0.025, d = 0.002, e = 0.002, kf = 0.614, ks = 390,
 q = 5000, rho = 997, rhos = 8960, mu = 8.90*10^-4,
 cp = 4.178*10^3 (*J/kg/\[Degree]K*), cps = 385}; u0 = .3; nu =
 mu/rho; om = 2 Pi f ; t0 = .1; nn = Round[10 Pi/(om t0)];

Needs["NDSolve`FEM`"]

reg1 = ImplicitRegion[0 <= x <= L && 0 <= y <= d, {x, y}]; reg2 =
 ImplicitRegion[0 <= x <= L && -e <= y <= d, {x, y}];
UX[0][x_, y_] := 0;
VY[0][x_, y_] := 0;
P[0][x_, y_] := 0;
Tfs[0][x_, y_] := 0; appro =
 With[{k = 2. 10^6}, ArcTan[k #]/Pi + 1/2 &];
ade[y_] := (ks + (kf - ks) UnitStep[y] /. UnitStep -> appro);
rde[y_] := (cps rhos + (cp rho - cps rhos) UnitStep[y] /.
   UnitStep -> appro);

Do[
    {UX[i], VY[i], P[i]} =
      NDSolveValue[{{Inactive[

           Div][({{-\[Mu], 0}, {0, -\[Mu]}} . Inactive[Grad][
                          u[x, y], {x, y}]), {x, y}] + D[p[x, y], x] +
                  UX[i - 1][x, y]*D[u[x, y], x] +

         VY[i - 1][x, y]*D[u[x, y], y] + (u[x, y] - UX[i - 1][x, y])/
                    t0 ,
                Inactive[

           Div][({{-\[Mu], 0}, {0, -\[Mu]}} . Inactive[Grad][
                          v[x, y], {x, y}]), {x, y}] + D[p[x, y], y] +
                  UX[i - 1][x, y]*D[v[x, y], x] +

         VY[i - 1][x, y]*D[v[x, y], y] + (v[x, y] - VY[i - 1][x, y])/
          t0,
                D[u[x, y], x] + D[v[x, y], y]} == {0, 0, 0} /. \[Mu] ->
       nu, {

      DirichletCondition[{u[x, y] == u0*Sin[om*i*t0], v[x, y] == 0},
       x == L (1 - Sign[Sin[om*i*t0]])/2 && 0 < y < d],
            DirichletCondition[{u[x, y] == 0, v[x, y] == 0},
              y == 0 || y == d]},
     DirichletCondition[p[x, y] == 0,
      x == L (1 + Sign[Sin[om*i*t0]])/2 && 0 < y < d]}, {u, v,
     p}, {x, y} \[Element] reg1,
        Method -> {"FiniteElement",
            "InterpolationOrder" -> {u -> 2, v -> 2, p -> 1},
            "MeshOptions" -> {"MaxCellMeasure" -> 0.00000005}}];
  ux = If[y <= 0, 0, UX[i ][x, y]]; vy = If[y <= 0, 0, VY[i ][x, y]];
  Tfs[i] = NDSolveValue[{rde[y] ((ux*D[T[x, y], x] +
                    vy*D[T[x, y], y]) + (T[x, y] - Tfs[i - 1][x, y])/
                     t0 ) -
        Inactive[Div][
         ade[y]*Inactive[Grad][T[x, y], {x, y}], {x, y}] ==
              NeumannValue[q, y == -e ],
            DirichletCondition[{T[x, y] == 0},
              x == L (1 - Sign[Sin[om*i*t0]])/2 && 0 <= y <= d]},
     T, {x, y} \[Element] reg2,
         Method -> {"FiniteElement",
             "InterpolationOrder" -> { T -> 2},
             "MeshOptions" -> {"MaxCellMeasure" -> 0.0000001}}] //
    Quiet;, {i, 1, nn}] // AbsoluteTiming

Visualization of temperature vs time at x=L/2, y=0 and x=L/2 for different t=1,2,3,4,5 s
ListLinePlot[Table[{i t0, Tfs[i][L/2, 0]}, {i, 0, nn}],
 AxesLabel -> {"t, s", "T"}]

Plot[Evaluate[Table[Tfs[i][L/2, y], {i, 10, nn, 10}]], {y, -e, d},
 PlotLegends -> Table[i t0, {i, 10, nn, 10}]]

Temperature and velocity distributions for different time shown above

Note, that temperature distribution is same for scaled and unscaled form of equation. Let consider test example posted by Avrana and solved with COMSOL. To get same average temperature we need to increase q up to q=120000, then we have
Needs["NDSolve`FEM`"]

{f = .5, L = 0.025, d = 0.001, e = 0.004, kf = 0.614, ks = 390,
 rho = 997, rhos = 8960, mu = 8.90*10^-4,
 cp = 4.178*10^3 (*J/kg/\[Degree]K*), cps = 385}; u0 = 0.22875; nu =
 mu/rho; om = 2 Pi f ; t0 = .1; nn =
 Round[40 Pi/(om t0)]; Ti = 288; q = 120000/Ti;

reg1 = ImplicitRegion[0 <= x <= L && 0 <= y <= d, {x, y}]; reg2 =
 ImplicitRegion[0 <= x <= L && -e <= y <= d, {x, y}];
UX[0][x_, y_] := 0;
VY[0][x_, y_] := 0;
P[0][x_, y_] := 0;
Tfs[0][x_, y_] := 293/Ti; appro =
 With[{k = 2. 10^6}, ArcTan[k #]/Pi + 1/2 &];
ade[y_] := (ks + (kf - ks) UnitStep[y] /. UnitStep -> appro);
rde[y_] := (cps rhos + (cp rho - cps rhos) UnitStep[y] /.
   UnitStep -> appro);

Do[
    {UX[i], VY[i], P[i]} =
      NDSolveValue[{{Inactive[

           Div][({{-\[Mu], 0}, {0, -\[Mu]}} . Inactive[Grad][
                          u[x, y], {x, y}]), {x, y}] + D[p[x, y], x] +
                  UX[i - 1][x, y]*D[u[x, y], x] +

         VY[i - 1][x, y]*D[u[x, y], y] + (u[x, y] - UX[i - 1][x, y])/
                    t0 ,
                Inactive[

           Div][({{-\[Mu], 0}, {0, -\[Mu]}} . Inactive[Grad][
                          v[x, y], {x, y}]), {x, y}] + D[p[x, y], y] +
                  UX[i - 1][x, y]*D[v[x, y], x] +

         VY[i - 1][x, y]*D[v[x, y], y] + (v[x, y] - VY[i - 1][x, y])/
          t0,
                D[u[x, y], x] + D[v[x, y], y]} == {0, 0, 0} /. \[Mu] ->
       nu, {

      DirichletCondition[{u[x, y] == u0*Sin[om*i*t0], v[x, y] == 0},
       x == L (1 - Sign[Sin[om*i*t0]])/2 && 0 < y < d],
            DirichletCondition[{u[x, y] == 0, v[x, y] == 0},
              y == 0 || y == d]},
     DirichletCondition[p[x, y] == 0,
      x == L (1 + Sign[Sin[om*i*t0]])/2 && 0 < y < d]}, {u, v,
     p}, {x, y} \[Element] reg1,
        Method -> {"FiniteElement",
            "InterpolationOrder" -> {u -> 2, v -> 2, p -> 1},
            "MeshOptions" -> {"MaxCellMeasure" -> 0.00000005}}];
  ux = If[y <= 0, 0, UX[i ][x, y]]; vy = If[y <= 0, 0, VY[i ][x, y]];
  Tfs[i] = NDSolveValue[{rde[y] ((ux*D[T[x, y], x] +
                    vy*D[T[x, y], y]) + (T[x, y] - Tfs[i - 1][x, y])/
                     t0 ) -
        Inactive[Div][
         ade[y]*Inactive[Grad][T[x, y], {x, y}], {x, y}] ==
              NeumannValue[q, y == -e ],
            DirichletCondition[{T[x, y] == 1},
              x == L (1 - Sign[Sin[om*i*t0]])/2 && 0 <= y <= d]},
     T, {x, y} \[Element] reg2,
         Method -> {"FiniteElement",
             "InterpolationOrder" -> { T -> 2},
             "MeshOptions" -> {"MaxCellMeasure" -> 0.0000001}}] //
    Quiet;, {i, 1, nn}];

Average temperature
ff = Interpolation[
  Table[{i t0,
    Ti/L NIntegrate[Tfs[i][x, 0], {x, 0, L}, AccuracyGoal -> 4,
      PrecisionGoal -> 4]}, {i, 0, nn}], InterpolationOrder -> 2]

Plot[ff[t], {t, 0, 40}, AxesLabel -> {"t, s", "T"}, PlotRange -> All]

A: It seems that the main challenge in this problem is Dirichlet BC which should be switched periodically on $x=0$ and $x=L$. I don't know whether it possible to switch BC inside NDSolveValue but we can run NDSolveValue every half period with new BC and take use solution obtained at last half period as a initial conditions.
Velocity field is not influenced by temperature so that partitioned coupling scheme can be used i.e. at first stage velocity is calculated than temperature is obtained. But in this case interpolation functions for velocity are involved into calculations inside the solver that significantly decelerates calculation. I propose to use here monolithic approach which implies calculation both temperature and velocity in single code. We will solve NS equations in computational domain which includes solid and fluid. By introducing the momentum sink term $-C\cdot \vec{V}$ into the momentum conservation equations one can set to zero the velocity in solid phase. Here $C$ is a large number. In current simulation the value $C=10^6$ was used. Lets write the governing equations in dimensionless form as in the paper [Zhao1996] which is mentioned by @Avrana in comments. Velocity and pressure are measured in units $u_0$ and $u_0^2\rho$, spatial coordinates and time are dimentionelized by $d$, $\omega^{-1}$ respectively. Here $\omega$, $u_0$ are circular frequency and inflow velocity accordingly. Temperature is measured in units $qd/k_f$, where $q$ is a heat flux density supplied from bottom wall.
Navier-Stokes equations
\begin{equation}
\frac{\partial \vec{V}}{\partial t}+\frac{A_0}{2}\left[ (\vec{V}\cdot\nabla)\vec{V} +\nabla P\right ]=\frac{1}{Re_{\omega}}\Delta \vec{V}
 \end{equation}
\begin{equation}
\nabla\cdot \vec{V}=0
 \end{equation}
Energy conservation in fluid
\begin{equation}
\frac{\partial T}{\partial t}+\frac{A_0}{2}(\vec{V}\cdot\nabla)T=\frac{1}{Re_{\omega}Pr}\Delta T
 \end{equation}
Energy conservation in solid
\begin{equation}
\frac{\partial T}{\partial t}=\frac{1}{\Gamma Pr Re_{\omega}}\Delta T
 \end{equation}
where $Re_{\omega}=\omega d^2/\nu$, $A_0=2u_0/(d\omega)$, $Pr=\nu/\alpha_f$,  $\Gamma=\alpha_f/\alpha_s$ are dimensionless parameters.
Input parameters
Needs["NDSolve`FEM`"]
Needs["MeshTools`"]

L = 0.025;(*length of the channel*)
d = 0.002;(*depth of the fluid*)
e = d;(*depth of the solid*)
l = L/d; (*dimensionless length*)
rhof = 997;(*fluid density*)
rhos = 8960;(*density of solid*)
mu = 8.9*10^-4;(*dynamic viscosity*)
nu = mu/rhof;(*kinematic viscosity*)
ks = 390;(*conductivity of solid*)
kf = 0.614;(*conductivity of liquid*)
cf = 4178;(*heat capacity of fluid*)
cs = 385;(*heat capacity of solid*)
AlphaF =kf/(cf*rhof); (*thermal diffusivity of fluid*)
AlphaS = ks/(cs*rhos); (*thermal diffusivity of solid*)
period = 1.;(*period*)
omega = 2*Pi/period;(*circular frequency*)
u0 = 0.3;(*inflow velocity*)
q = 5000;(*heat flux density*)

(*dimensionless model input parameters *)
A0 = 2*u0/(d*omega);
re = omega*d^2/(nu);
Pr = nu/AlphaF;(*Pandtl number*)
gamma=If[ElementMarker == 0, AlphaF/AlphaS, 1];
sigma = kf/ks;

FE mesh generation
It is convenient to use structured FE mesh for this particular case. All the manipulations with meshes were done here by means of utilities from MeshTools package.
Nx = 100;(*number of elements in x-direction *)
NyF = 20;(*number of elements in y-direction in fluid*)
NyS = 5;(*number of elements in y-direction in solid*)
hy = 1./NyF;(*linear dimension of element in fluid*)

raster = {
   {{0, 0}, {l, 0}},
   {{0, 1}, {l, 1}}
   };
MeshFluid = StructuredMesh[raster, {Nx, NyF}];(*FE mesh in fluid*)

raster = {
   {{0, -e/d}, {l, -e/d}},
   {{0, 0}, {l, 0}}
   };
MeshSolid =
 StructuredMesh[raster, {Nx, NyS}];(*FE mesh in solid*)
mesh =
 MergeMesh[MeshSolid, MeshFluid];
nodes = mesh["Coordinates"];
quads = mesh["MeshElements"][[1]][[1]];
(*ElementMarker=0 in soilid and 1 in fluid*)

mark = Table[z = Mean[nodes[[quads[[i]]]]][[2]];
   If[z < 0, 0, 1], {i, 1, Length[quads]}];
(*1d order mesh in total domain*)

MeshTotal1 =
  ToElementMesh["Coordinates" -> nodes,
   "MeshElements" -> {QuadElement[quads, mark]}];
(*2d order mesh in total domain*)

MeshTotal2 = MeshOrderAlteration[MeshTotal1, 2];
pic1 = Show[MeshTotal1["Wireframe"], ImageSize -> 600]
Export["pic1.jpeg", pic1, ImageResolution -> 300]

Solution procedure
NS solver used little differ from those in documentation. Function rampFunction introduced there helps to increase inflow velocity smoothly in time. Velocity inflow profile  UinfProfile[y] used here has a trapezoidal shape.

Clear[TopWall, BottomWall, reference, HeatInpBC, op, c, rampFunction,
  sf, UinfProfile, Profile];

rampFunction[min_, max_, c_, r_] :=
 Function[t, (min*Exp[c*r] + max*Exp[r*t])/(Exp[c*r] + Exp[r*t])]
sf = rampFunction[0, 1, 0.25, 100];

Profile =
 Interpolation[{{0, 0}, {hy, 1}, {1 - hy, 1}, {1, 0}},
  InterpolationOrder -> 1]
Uc = 1/NIntegrate[Profile[y], {y, 0, 1}];(*calibration coefficient*)
UinfProfile[y_] := Uc*Profile[y];(*inflow velocity profile*)

Define a PDE operator with boundary conditions
c = If[ElementMarker == 0, 10^6,
  0];(*define the constant in momentum sink term*)
op = {
  D[u[t, x, y], t] +
   Inactive[
     Div][({{-1/re, 0}, {0, -1/re}} .
      Inactive[Grad][u[t, x, y], {x, y}]), {x, y}] +
   0.5 A0*{{u[t, x, y], v[t, x, y]}} .
     Inactive[Grad][u[t, x, y], {x, y}] + 0.5 A0*D[p[t, x, y], x] +
   c*u[t, x, y],
  D[v[t, x, y], t] +
   Inactive[
     Div][({{-1/re, 0}, {0, -1/re}} .
      Inactive[Grad][v[t, x, y], {x, y}]), {x, y}] +
   0.5 A0*{{u[t, x, y], v[t, x, y]}} .
     Inactive[Grad][v[t, x, y], {x, y}] + 0.5 A0*D[p[t, x, y], y] +
   c*v[t, x, y],
  D[u[t, x, y], x] + D[v[t, x, y], y],
  D[T[t, x, y], t] +
   Inactive[
     Div][(-(1/(Pr*re*gamma))*
      Inactive[Grad][T[t, x, y], {x, y}]), {x, y}] +
   0.5*A0*{u[t, x, y], v[t, x, y]} . Inactive[Grad][T[t, x, y], {x, y}]
          };

TopWall =
  DirichletCondition[{u[t, x, y] == 0, v[t, x, y] == 0}, y == 1];
BottomWall =
  DirichletCondition[{u[t, x, y] == 0, v[t, x, y] == 0}, y <= 0];
(*setting pressure value in single node*)

reference = DirichletCondition[p[t, x, y] == 0., x == 0 && y == 0];
HeatInpBC = NeumannValue[sigma*AlphaS/(AlphaF*Pr*re), y == -1];

Finally, the next code realizes the solution procedure for first twenty half-periods
Clear[UxLast, UyLast, TLast, PLast];
UxLast[x_, y_] := 0;
UyLast[x_, y_] := 0;
TLast[x_, y_] := 0.;
PLast[x_, y_] := 0;

SolutData = {};
K = 20;(*number of half-periods considered*)
Do[
      Clear[u, v, p, t, HeatDBC];
      ti = (k - 1)*Pi;
      tf = ti + Pi;

 Clear[HeatDBC, Inflow, Outflow, bcs, ic, UxFun, UyFun, pressure,
  TFun];
 If[k == 1,
     Inflow =
   DirichletCondition[{u[t, x, y] == sf[t]*Sin[t]*UinfProfile[y],
     v[t, x, y] == 0}, x == 0 && y > 0 && y < 1];
     Outflow =
   DirichletCondition[{u[t, x, y] == sf[t]*Sin[t]*UinfProfile[y],
     v[t, x, y] == 0}, x == l && y > 0 && y < 1],

     Inflow =
   DirichletCondition[{u[t, x, y] == Sin[t]*UinfProfile[y],
     v[t, x, y] == 0}, x == 0 && y > 0 && y < 1];
     Outflow =
   DirichletCondition[{u[t, x, y] == Sin[t]*UinfProfile[y],
     v[t, x, y] == 0}, x == l && y > 0 && y < 1]
    ];

 If[OddQ[k] == True,
      HeatDBC =
   DirichletCondition[T[t, x, y] == 0, x == 0 && y >= 0 && y <= 1],
      HeatDBC =
   DirichletCondition[T[t, x, y] == 0, x == l && y >= 0 && y <= 1]
     ];

    ic = {u[ti, x, y] == UxLast[x, y], v[ti, x, y] == UyLast[x, y],
   p[ti, x, y] == PLast[x, y], T[ti, x, y] == TLast[x, y]};
    bcs = {TopWall, BottomWall, Inflow, Outflow, reference, HeatDBC};

 Monitor[
  {UxFun, UyFun, pressure, TFun} =
   NDSolveValue[{op == {0, 0, 0, HeatInpBC}, bcs, ic}, {u, v, p,
     T}, {x, y} \[Element] MeshTotal2, {t, ti, tf},

    MaxStepSize -> Pi*10^-3,

    Method -> {

      "TimeIntegration" -> {"IDA", "MaxDifferenceOrder" -> 2},

      "PDEDiscretization" -> {"MethodOfLines",
        "SpatialDiscretization" -> {"FiniteElement",
          "PDESolveOptions" -> {"LinearSolver" -> "Pardiso"},
          "InterpolationOrder" -> {u -> 2, v -> 2, p -> 1, T -> 2}}}}
    , EvaluationMonitor :> (currentTime = Row[{"t = ", CForm[t]}])]
  , currentTime];

   UxLast =
  ElementMeshInterpolation[{MeshTotal2}, Last[UxFun["ValuesOnGrid"]] ];
   UyLast =
  ElementMeshInterpolation[{MeshTotal2},
   Last[UyFun["ValuesOnGrid"]]];
   TLast =
  ElementMeshInterpolation[{MeshTotal2}, Last[TFun["ValuesOnGrid"]]  ];
   PLast =
  ElementMeshInterpolation[{MeshTotal1},
   Last[pressure["ValuesOnGrid"]]  ];

 n = Length[TFun["ValuesOnGrid"]];
 m = If[k < K, n - 1, n];

 AppendTo[SolutData,

   Take[Transpose[{TFun[[3]][[1]], TFun["ValuesOnGrid"]}], {1, m,
    10}]

         ]

     , {k, 1, K}
     ]

Postprocessing
Construction of interpolation function for temperature solution
Clear[TsolVec, TFun]
TsolVec =
  Interpolation[Flatten[SolutData, 1], InterpolationOrder -> 1];
TFun[t_?NumericQ] :=
 ElementMeshInterpolation[{MeshTotal2}, TsolVec[t]]

Visualization of thermal history in point $\{0.5L,0\}$
Plot[TFun[t][0.5 l, 0], {t, 0, K*Pi},
 PlotStyle -> {Thickness[0.005], RGBColor[0, 0, 0]},
 PlotRange -> {0, 0.02}, Frame -> True,
 FrameLabel -> {"time", "Temperature"},
 FrameTicks -> {Table[(k - 1) 2 \[Pi], {k, 1, 6}], Automatic},
 FrameStyle -> RGBColor[0, 0, 0], BaseStyle -> 14, ImageSize -> 500,
 LabelStyle -> RGBColor[0, 0, 0],
 PlotLabel -> "Thermal history in point {0.5l,0}"]

It is necessary to calculate at least 5 periods to reach quasi-stationary regime under the given input parameters (properties, geometry, inflow velocity) as we can see from the last pic. Distributions of temperature in cross section $x=0.5L$ at different times looks as follows
t1 = 2 Pi; t2 = 4 Pi;
t3 = 6 Pi; t4 = 8 Pi;
t5 = 10 Pi; t6 = 18 Pi;

Plot[{TFun[t1][0.5 l, y], TFun[t2][0.5 l, y],
   TFun[t3][0.5 l, y], TFun[t4][0.5 l, y], TFun[t5][0.5 l, y],
   TFun[t6][0.5 l, y]}, {y, -1, 1}, PlotStyle -> Thickness[0.005],
  PlotRange -> All, Frame -> True, FrameLabel -> {"y", "Temperature"},
   FrameStyle -> RGBColor[0, 0, 0], BaseStyle -> 14, ImageSize -> 500,
   PlotLegends -> {2 \[Pi], 4 \[Pi], 6 \[Pi], 8 \[Pi], 10 \[Pi],
    18 \[Pi]},
  PlotLabel ->
   "Temperature distribution along the line x=0.5L at different \
times", LabelStyle -> RGBColor[0, 0, 0]]

Multiplication $T\cdot qd/k_f$ with $q=5\cdot 10^3 W/m^2$ gives overheating (in Kelvins) above initial temperature of supplied water $T_0$.
Plot[{(q*d)/kf*TFun[t1][0.5 l, y/d], (q*d)/kf*TFun[t2][0.5 l, y/d], (
   q*d)/kf*TFun[t3][0.5 l, y/d], (q*d)/kf*TFun[t4][0.5 l, y/d], (q*d)/
   kf*TFun[t5][0.5 l, y/d], (q*d)/kf*TFun[t6][0.5 l, y/d]}, {y, -e,
  d}, PlotStyle -> Thickness[0.004], PlotRange -> All, Frame -> True,
 FrameLabel -> {"y, m", "T-\!\(\*SubscriptBox[\(T\), \(0\)]\), K"},
 FrameStyle -> RGBColor[0, 0, 0], BaseStyle -> 14, ImageSize -> 500,
 PlotLegends -> {"t=1s", "t=2s", "t=3s", "t=4s", "t=5s", "t=9s"},
 PlotLabel ->
  "Temperature distribution along line x=0.5L ar different times",
 LabelStyle -> RGBColor[0, 0, 0]]

It's interesting to analyze velocity profiles in different cross sections
VelocProfArr = Table[
   ParametricPlot[
     {
     {UxFun[t, 0, y], y},
     {UxFun[t, l/2, y], y},
     {Sin[t]*6 (y - y^2), y}
     },
    {y, 0, 1}, AspectRatio -> 0.25, Frame -> True,
    FrameStyle -> RGBColor[0, 0, 0], FrameLabel -> {"Velocity", "y"},
    BaseStyle -> 14, PlotRange -> {{-1.8, 1.8}, {0, 1}},
    LabelStyle -> Black, PlotLabel -> "time=" <> ToString[t],
    PlotLegends -> {"x=0", "x=0.5L", "Poiseuille profile"},
    ImageSize -> 500]
   , {t, ti, tf, 0.01*(tf - ti)}];

ListAnimate@VelocProfArr

$V_x$ distribution in longitudinal direction at $y=d/2$ is as follows
VelocLongArr = Table[
   Plot[
     {UxFun[t, x, 0.5],
     Sin[t]*6*(0.5 - 0.5^2)
     },
    {x, 0, l}, AspectRatio -> 0.25, Frame -> True,
    FrameStyle -> RGBColor[0, 0, 0], FrameLabel -> {"x", "Velocity"},
    BaseStyle -> 14, PlotRange -> {{0, l}, {-1.8, 1.8}},
    LabelStyle -> Black, PlotLabel -> "time=" <> ToString[t],
    PlotLegends -> {"y=0", "Poiseuille flow"}, ImageSize -> 500]
   , {t, ti, tf, 0.01*(tf - ti)}];

ListAnimate@VelocLongArr

As we can see, the velocity field differ from Poiseuille profile. Thereby the flow in channel can not be considered to be fully developed.


text:
Q: Cannot override fun done() I'm trying to save object in background by using Parse.com but I can't override
   override fun done(e: ParseException?) {
    //code
                  }

I'm getting error: Modifier 'override' is not applicable to 'local function
In java I would use:
myObject.saveInBackground(new SaveCallback() {
    public void done(ParseException e) {
      if (e == null) {
        myObjectSavedSuccessfully();
      } else {
       myObjectSaveDidNotSucceed();
      }
   }
  });

Here is my whole class
class StarterApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        Parse.initialize(Parse.Configuration.Builder(this)
                .applicationId(appID)
                .clientKey(null)
                .server(serverUrl)
                .build()
        )

        var exampleObject: ParseObject = ParseObject("ExampleObject")
        exampleObject.put("myString", "fwfwe")
        exampleObject.saveInBackground( {
               override fun done(e: ParseException?) { //here is an error //`Modifier 'override' is not applicable to 'local function`

              }

     })
    }
}

A: Just do like that:
exampleObject.saveInBackground(object : SaveCallback {
    override fun done(e: ParseException?) {
        // Add your code here
    }
})

In Java, you declare an anonymous class that extend SaveCallback. In Kotlin, you do this with Object Expressions.

A: you can also try the simplest solution like this
 exampleObject.saveInBackground({
 //you code here
  })

https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions


text:
Q: Reference for a special case of the Hanson-Wright inequality I would like find tail bounds for the expression
$$
\begin{align*}
\left|\left\langle a,\phi\right\rangle \left\langle \phi,b\right\rangle -\left\langle a,b\right\rangle\right|,
\end{align*}
$$
where $a$ and $b$ are fixed complex vectors and $\phi$ is a vector with iid Rademacher entries.
I know that this is a special case of Hanson-Wright inequality, but I couldn't find any reference that explicitly considers complex matrices. I hesitate to derive the desired bound using the real version, because I would like to obtain reasonably sharp constant factors.
Question: Can anyone point me to a reference that directly addresses complex Hanson-Wright inequality, or at least my special case?


text:
Q: Convertion of user-defined object to string by toString not showing correct output I have created a class CurrentDate which shows the system date in a particular format(e.g. 29-JUN-12). The class looks like :
package getset;

import java.util.*;
import getset.Getset;
public class CurrentDate{
    public static void main(String[] args){
        Calendar cal = new GregorianCalendar();
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        String toyear=String.valueOf(year);
        String newyear=toyear.substring(2,4);
        String newmonth=monthvalidation(month);
        System.out.println("Current date : " + day + "-" + (newmonth) + "-" + newyear);
    }

    private static String monthvalidation(int initmonth) {
        // TODO Auto-generated method stub
        //int initmonth=i;
        String finalmonth="";
        if(initmonth==1)
        {
            finalmonth="JAN";
        }
        if(initmonth==2)
        {
            finalmonth="FEB";
        }
        if(initmonth==3)
        {
            finalmonth="MAR";
        }
        if(initmonth==4)
        {
            finalmonth="APR";
        }
        if(initmonth==5)
        {
            finalmonth="MAY";
        }
        if(initmonth==6)
        {
            finalmonth="JUN";
        }
        if(initmonth==7)
        {
            finalmonth="JUL";
        }
        if(initmonth==8)
        {
            finalmonth="AUG";
        }
        if(initmonth==9)
        {
            finalmonth="SEP";
        }
        if(initmonth==10)
        {
            finalmonth="OCT";
        }
        if(initmonth==11)
        {
            finalmonth="NOV";
        }
        if(initmonth==12)
        {
            finalmonth="DEC";
        }
        return finalmonth;
    }
}

Now when I try to convert it using toString() it does not show what is expected. I tried:
CurrentDate date=new CurrentDate();
String sysdate=date.toString();
System.out.println(""+sysdate);

It shows something like: getset.CurrentDate@18a178a which is not human readable expected format. What can I do to correct this?

A: Override toString method in your class . Add a method like a as follows.
@Override
public String toString() {

    return day + "-" + newmonth + "-" + newyear;
}

A: You need to override the toString method.
In your CurrentDate class, add somethnig like
@Override
public String toString() {
    String toyear=String.valueOf(year);
    String newyear=toyear.substring(2,4);
    String newmonth=monthvalidation(month);
    return day + "-" + newmonth + "-" + newyear;
}

A: You are not overriding the Object implementation of toString()
To test your method, you could quickly put the logic in that you have developed into a public String toString() method.  then in your main method, create a CurrentDate and print the toString.

A: I see problem in your code.
First, you are not having fields for which you want toString() representation.I think you need to declare fields like:
int month;
int year ;
int day;
 @Override
public String toString() {
    return "CurrentDate [month=" + month + ", year=" + year + ", day="
            + day + "]";
}

If you are using Eclipse IDE, just generate toString() method, that will be a simple solution to your problem. Right now, object toString() is invoked for your toString(). In fact, as per Josh Bloch,

every class should override toString() for getting human readable format.

A: CurrentDate date=new CurrentDate();
String sysdate=date.toString();
System.out.println(""+sysdate);

In your above code you are using date object but not assigning  any value , only CurrentDate  class reference. so your are getting 'getset.CurrentDate@18a178a' when use toString() method.

If you want to format date to string you have to use

public static final String DATE_FORMAT_NOW = "dd-MMM-yy";

SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);


text:
Q: ASP.NET Core Identity will only insert one role This is very odd and I'm stumped. I've got some code for setting up my Identity tables with a few default roles.
Here is my code:
var role = new ApplicationRole
{
    Name = "SuperAdmin"
};

await _roleManager.CreateAsync(role);

role = new ApplicationRole
{
    Name = "User"
};

await _roleManager.CreateAsync(role);

role = new ApplicationRole
{
    Name = "Support"
};

await _roleManager.CreateAsync(role);

It runs fine. Except that only the first SuperAdmin role is created.
Stepping through, the RoleManager<ApplicationRole> never even fires CreateAsync on the latter two.
No exceptions are thrown. I cannot give you a stack trace because there isn't one.
What's going on? Any ideas?

A: Argh.
It's my own IRoleStore implementation backed with stored procedures and there was a logic error in the sproc. As soon as any Role existed, a row was always returned from CheckRoleExistsAsync.
Nevermind.


text:
Q: Touble with make an array from string I want to make an array for Dropdown From this string so can you help to make an array?
String:
---Tafadhali chagua---
Mwanafunzi
Muajiriwa
Nimejiajiri
Sina kazi
Nyinginezo

Attempt:
$pizza = "---Tafadhali chagua--- Mwanafunzi Muajiriwa Nimejiajiri Sina kazi Nyinginezo";
$pieces = explode("/n", $pizza);
print_r($pieces);

A: /n is not a new line, it is a forward slash and an n. A backslash and an n make a new line, better yet is to use the PHP constant PHP_EOL (for end of line).
$string = '---Tafadhali chagua---
Mwanafunzi
Muajiriwa
Nimejiajiri
Sina kazi
Nyinginezo';
print_r(explode(PHP_EOL, $string));

https://3v4l.org/00nN2


text:
Q: Stumped by boot time corruption I have a home build computer that has data corruption problems at boot time.  I have exhausted all the troubleshooting steps that I know to try.  Do you have any additional troubleshooting techniques that I should try?
Symptoms
I run both linux(ubuntu, mint and fedora) and win7 on this machine.  Sometimes I have just one installed.  Other times both in a dual boot setup.  The OS installs just fine.   The system runs just fine for a while.  Then it fails to boot.  At first I can fix the boot problems with grub or bootrec (/RebuildBcd, /FixMbr or /FixBoot) as indicated by the error messages.  Eventually the system fails to boot at all and I have to wipe the disk(s) and reinstall the operating system.
The linux installs seem to last a bit longer.  I typically have linux running for a month before the troubles start, but I have to repave and rebuild within 3 months.  The windows installs last at most 2 weeks before troubles develop.  The system is turned on for the day or evening then turned off overnight.
Once the system has booted all checks that I have run pass.  On windows fciv.exe, sfc.exe have never deteced and troubles.  On linux tripwire shows everything unchanged.  Chkdsk and fsck have never reported errors.
Hardware
ASUS M3A78-EM motherboard.  2x2GB kingston memory from the ASUS QVL for this motherboard.  I have used two hard disks in this system.  WD caviar black 640G (WDC WD6401AALS-00L3B2).  Seagate barracuda 7200.7 (ST3120026A).  On some rebuilds I have used just one of the drives, sometimes I have both installed.  The DVD burner is a LG 4x (HL-DT-ST DVD-RAM GH22NS30 ).  The power supply was originally an el-cheapo Allied unit that came with the case.  That has since been replaced with a Seasonic X650.
And that is all that is in this system.  I use the onboard video, sound and network.  I have never plugged an external device into the system (not even a USB flash drive!).
Trouble shooting so far...
I have run the memtest utility from both the ubuntu CD and the windows DVD many times.  Even when run for several day neither test utility has ever found a memory error.
I have run the seagate and western digital provided test and diagnostic tools on both of the hard disks.  I have done this on both the unstable ASUS M3A778-EM system and a very stable gateway system.  The disks have always tested good.
I have swapped out the HDD cables several times.  I have replaced the cables with new cables and with cables pulled from a stable system.
Because the corruption happens only at boot time I suspected the power supply was having problems under the extra load of disk spinup.  So, I replaced the power supply.  No success.
I have run the system with every version of the MB BIOS from the version that it shipped with to the latest and greatest.  The BIOS upgrades made no noticeable difference.
I have enabled and disabled automatic updates on both win7 and ubuntu linux.  That made no noticeable difference.
That is it.  That is all the troubleshooting ideas I have had.  What do you suggest?

A: I actually had the exact same problem with my desktop computer.
After a long time running with no issues, my system stopped booting correctly and would only boot after fixing the mbr. Finally, after a few months of forcing boots, the powersupply gave way and burned up.
I switched out every conceivable piece of hardware except for the motherboard and processor, including replacing the aging IDE drive with a new SATA drive, and a new, more powerful, powersupply. The machine ran perfectly until a month from now when the powersupply burned out again in the exact same manner.
The machien has always been plugged into a high-quality surge protector and no other machines/appliances have been damaged in the building.
After a long while trying to figure things out, I've concluded that there must be some faulty circuit in the motherboard somehow causing the hard drive to receive power-peaks (corrupting the drive on boot) and then slowly damaging the powersupply until it burns out completely.
Sorry I can't provide a better answer, but my problem was solved with a motherboard change. Good luck!
[EDIT]: Looking over your post and at my machine -- It may be a coincidence, but the first hard drive that failed on my system was a WD, the second was a Seagate, and I was running an older Asus mobo.

A: I hate these kind of problems. Maybe you're just in the line of fire of cosmic rays :p
You mentioned all that I would have tried, including the BIOS upgrades. Good call. All that's left is to swap out each piece of hardware, but that would mean buying a new PC if we consider your time frame of error.
Are there specific signs that you know corruption happens at boot time? Could the corruption happen during any other time, but that it only affect the boot sector? Actually... thinking of this, I wonder if your IDE controller is faulty. See if you can get hold of a new IDE controller, and disable the on-board one.
To make your life easier, I can suggest making a backup of your MBR, so that when this happens again you can just restore the backed up boot sector:
Backup the MBR (in Ubuntu):
sudo dd if=/dev/sda of=/mbr.bin bs=446 count=1

Restore the MBR: Boot into a LiveCD, Mount your root partition and:
dd if=/media/sda/mbr.bin of=/dev/sda bs=446 count=1

obviously /dev/sda will be the primary boot drive for your PC; confirm this with fdisk -l
Alternatively, you can just reinstall the boot loader, GRUB, which will detect your existing Ubuntu and Windows installations. Read here for more details.
Until then, good luck finding the problem!


text:
Q: Getting "UnauthorizedAccessException" in a BackgroundWorker without accessing UI thread I'm doing some heavy work on a backgroundworker, so that it doesn't affect my Silverlight UI thread. However, in the DoWork function I'm getting this exception:
UnauthorizedAccessException "Invalid cross-thread access".
I know I can't access the UI thread from the BackgroundWorker, However, this exception occurs on this line:
  ListBoxItem insert = new ListBoxItem();

How is that accessing my ui thread??
Here's the actual piece of code I've narrowed it down to. I'm basically doing work creating listboxitems which i'd like to insert to the sourceList listbox:
void FillSourceList()
{
    busyIndicator.IsBusy = true;
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += (sender, args) =>
        {
            List<ListBoxItem> x = new List<ListBoxItem>();
            for (int i = 0; i < 25; i++ )
            {
                ListBoxItem insert = new ListBoxItem(); //<---Getting exception here
                insert.Content = "whatever";
                x.Add(insert);
            }
            args.Result = x;
        };
    bw.RunWorkerCompleted += (sender, args) =>
        {
            foreach (ListBoxItem insert in (List<ListBoxItem>)(args.Result))
                sourceList.Items.Add(insert);
            busyIndicator.IsBusy = false;
        };

    bw.RunWorkerAsync();
}

A: A ListBoxitem derives from Control so it is considered part of the GUI. I would have expected a 'detached' item to be OK in a thread too but apparently it isn't.
The obvious solution: build up a list x of Content (strings) and delay the creation of the Items to the Completed event.


text:
Q: Switching from HTTP to HTTPS automatically in ASP.NET How to switch from HTTP to HTTPS automatically in ASP.NET?
Also no need to do same thing in Local connection

A: Lets start:
Open Global.asax code finde Application_BeginRequest,change it like this:
 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
            {
                Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl);
            }
        }

Bingo!


text:
Q: Error after changing extent+resolution in r I have a tiff file called "tiff4" and here is the information of it:
class       : RasterLayer
dimensions  : 49, 89, 4361  (nrow, ncol, ncell)
resolution  : 0.5, 0.5  (x, y)
extent      : 60.64135, 105.1413, 14.99839, 39.49839  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : C:\Users\Halima Usman\Documents\ICIMOD\hkh1.tif
names       : hkh1
Now I require an extent which of are of whole numbers and not decimal places. This is what I do to change extent
ext <- extent(61, 105, 16, 39)
extent(tiff4)<-ext
But after changing the extent the resolution also changes. I require a resolution of 0.5 degree
class       : RasterLayer
dimensions  : 49, 89, 4361  (nrow, ncol, ncell)
resolution  : 0.494382, 0.4693878  (x, y)
extent      : 61, 105, 16, 39  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : C:\Users\Halima Usman\Documents\ICIMOD\hkh1.tif
names       : hkh1
Then I change the resolution back to 0.5 by doing this:
res(tiff4)=0.5
But when i plot tiff4, it gives an error
Error in .plotraster2(x, col = col, maxpixels = maxpixels, add = add,  :
  no values associated with this RasterLayer
How can I fix this error or what is the reason behind this error?
(I have seen this question Can't change raster's extent, but as a beginner in R I am not getting desired result)

A: You changed ymin from 14.99 to 16. That is not good. You could get close by doing this
ext <- extent(60.5, 105, 15, 39.5)

That would "work" because (105-60.5) / .5 = 89 and (39.5-15) / .5 = 49. That is, the number of rows and columns matches the resolution. However, you have now moved the values spatially, and so they are no longer "correct". And the extent does not have whole numbers.
I would suggest you do something like this instead:
r <- raster(tiff4)
extent(r) <- c(60, 105, 15, 40)
r <- resample(tiff4, r)
r


text:
Q: My maven build is failing due to wadl-plugin issue it seems, Need help to resolve this error My maven build is failing due to wadl-plugin issue it seems, did anybody came across this issue? I donot have any clue how to fix this, Need help to resolve this error...
My JDK Version: Jdk.1.7.0_60
My Maven Version: 3.2.1
My Pom.xml:
<plugin>
                <groupId>com.sun.jersey.contribs</groupId>
                <artifactId>maven-wadl-plugin</artifactId>
                <version>${jersey.version}</version>
                <executions>
                    <execution>
                        <id>generate</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <phase>compile</phase>
                    </execution>
                </executions>
                <configuration>
                    <wadlFile>${project.build.outputDirectory}/application.wadl</wadlFile>
                    <formatWadlFile>true</formatWadlFile>
                    <baseUri>http://<HostName>:<port>/<contextname> </baseUri>
                    <packagesResourceConfig>
                        <param>com.myproject.resources</param>
                    </packagesResourceConfig>
                    <dependencies>
                        <dependency>
                            <groupId>org.slf4j</groupId>
                            <artifactId>slf4j-api</artifactId>
                            <version>${org.slf4j.version}</version>
                        </dependency>
                    </dependencies>
                    <wadlGenerators>
                        <wadlGeneratorDescription>
                            <className>
                                com.sun.jersey.server.wadl.generators.WadlGeneratorApplicationDoc
                            </className>
                            <properties>
                                <property>
                                    <name>applicationDocsFile</name>
                                    <value>${basedir}/src/main/resources/doc/application-doc.xml</value>
                                </property>
                            </properties>
                        </wadlGeneratorDescription>
                        <wadlGeneratorDescription>
                            <className>
                                com.sun.jersey.server.wadl.generators.WadlGeneratorGrammarsSupport
                            </className>
                            <properties>
                                <property>
                                    <name>grammarsFile</name>
                                    <value>${basedir}/src/main/resources/doc/application-grammars.xml</value>
                                </property>
                            </properties>
                        </wadlGeneratorDescription>
                        <wadlGeneratorDescription>
                            <className>
                                com.sun.jersey.server.wadl.generators.resourcedoc.WadlGeneratorResourceDocSupport
                            </className>
                            <properties>
                                <property>
                                    <name>resourceDocFile</name>
                                    <value>${project.build.outputDirectory}/resourcedoc.xml</value>
                                </property>
                            </properties>
                        </wadlGeneratorDescription>
                        <wadlGeneratorDescription>
                            <className>
                                myProject.MyWadlGenerator
                            </className>
                            <properties>
                                <property>
                                    <name>resourceDocFile</name>
                                    <value>${project.build.outputDirectory}/resourcedoc.xml</value>
                                </property>
                            </properties>
                        </wadlGeneratorDescription>
                    </wadlGenerators>
                </configuration>
            </plugin>

Error:

[ERROR] Failed to execute goal
  com.sun.jersey.contribs:maven-wadl-plugin:1.8:gen erate (generate) on
  project Myproject: Execution generate of goal com.
  sun.jersey.contribs:maven-wadl-plugin:1.8:generate failed: A
  required class was missing while executing
  com.sun.jersey.contribs:maven-wadl-plugin:1.8:generate:
  org/springframework/beans/factory/ListableBeanFactory

Thanks,
Sundar


text:
Q: How can I control the access of an API at definition/operation level in WSO2 API store console? Ex: Lets assume I have a 'Calculator' API and it has below operations/definitions.
1.addition
2.multiplication
I want restrict user with addition operation and remaining operations should not be visible/access in store console.
Is there any way to achieve this?

A: You can restrict the access for each resource by configuring scopes for each resources. If the user has access token binding to the particular scopes only can invoke the resources restricted with the scopes. Documentation has detailed useful information regarding this - https://wso2.com/library/articles/2017/01/article-an-overview-of-scope-management-with-wso2-api-manager/


text:
Q: Problem: If $f\in L^1[0,1]$, show that $\lim_{n\to\infty}\frac{1}{n}\sum_{k=0}^{n-1}f(x+\frac{k}{n})=\int_0^1 f(s)ds$ in $L^1[0,1]$. This is the solution from the Prof.:
Define $f_n(x)=\frac{1}{n}\sum_{k=0}^{n-1}f(x+\frac{k}{n})$. Then, unless $j<n$, we get $\hat f_n(j)=\frac{1}{n}\sum_{k=0}^{n-1}e^{2\pi i j k/n} \hat f(j)=0$ for $j\not=0$, while $\hat f_n(0)=\hat f(0)=\int_0^1f(s)ds.$ By the uniqueness of Fourier coefficients, $f_n(x)=\hat f(0)$ a.e. on $[0,1]$.
I don't understand the part "unless $j<n$". Since $\sum_{k=0}^{n-1}(e^{2\pi i j/n)^k}=\frac{1-e^{2\pi ij}}{1-e^{(2\pi ij)/n}}$ and $e^{2\pi ij}=1$, we get only problems if $j=0$ or $\frac{j}{n}\in\mathbb{Z^*}$. Shouldn't it therefore be "unless $j>n$?. And where do I need the limit $n\to\infty$?


text:
Q: CssRewrite filter does not convert relative urls to absolute I'm trying to combine all used css files into a single one. But included resources with relative paths causes problems. I tried assetic's CssRewriteFilter but it does not work.
Here is my code:
    $files = [
        '/node_modules/select2/dist/css/select2.min.css',
        '/node_modules/jquery-datetimepicker/jquery.datetimepicker.css',
        '/node_modules/icheck/skins/square/blue.css',
        '/node_modules/Plupload/js/jquery.plupload.queue/css/jquery.plupload.queue.css',
        '/node_modules/pace/themes/white/pace-theme-flash.css',
        '/node_modules/lightgallery/dist/css/lightgallery.min.css',
        '/node_modules/x-editable/dist/bootstrap3-editable/css/bootstrap-editable.css',
        '/node_modules/sweetalert2/dist/sweetalert2.css',
        '/node_modules/animate.css/animate.min.css',
        '/node_modules/fullcalendar/dist/fullcalendar.min.css',
        '/node_modules/flag-icon-css/css/flag-icon.min.css',
        '/theme/assets/skin/default_skin/css/theme.css',
    ];

    $am = new \Assetic\AssetManager();

    $items = [];

    foreach ($files as $file) {
        $filename = APP_ROOT_DIR . '/public/ui' . $file;
        $items[] = new \Assetic\Asset\FileAsset($filename, [new \Assetic\Filter\CssRewriteFilter()]);
    }

    $collection = new \Assetic\Asset\AssetCollection(
        $items
    );
    $collection->setTargetPath('vendor.css');

    $am->set('collection', $collection);

    $writer = new \Assetic\AssetWriter(APP_ROOT_DIR . '/public/ui/shared/css/');
    $writer->writeManagerAssets($am);

What i expect:
When a img is included with ../img/test.png code in /node_modules/test/css/test.css Assetic should rewrite it to /node_modules/test/img/test.png

A: Try constructing your FileAsset class like:
new \Assetic\Asset\FileAsset(
    $filename,
    [new \Assetic\Filter\CssRewriteFilter()],
    '/node_modules/test/'
);

In src/Assetic/Asset/FileAsset.php:37, we see that you can include a $sourcePath as a third argument.
https://github.com/kriswallsmith/assetic/blob/master/src/Assetic/Asset/FileAsset.php#L37
You may want to rejig your $files array to something like
$files = [
    ['/node_modules/select2/dist/css/', 'select2.min.css']
    ...
];

So that you can call the $sourcePath twice over like
new \Assetic\Asset\FileAsset(
    APP_ROOT_DIR . '/public/ui' . $file[0].$file[1],
    [new \Assetic\Filter\CssRewriteFilter()],
    '/public/ui'.$filename[0]
);


text:
Q: Subring of the field of rational numbers
Let $R=\{a\cdot2^n\mid a,n \in \mathbb{Z}\}$ be a subring or the field of rational numbers $\mathbb Q$.
i) What kind of elements are invertible in $R$?
ii) Prove that $R$ is a principal ideal ring, that is, every ideal in $R$ is principal.

For (i) I came to a conclusion that whenever $a=1$, the elements are invertible. Is it right? or it might be hold for any odd a? (I doubt as 1/a is an integer only when a=1..)
For the (ii) I assumed that $J$, which is not 0, is an ideal in $R$. Thus, there exists $c\cdot2^k$ in $J$… and $c$ should be the minimal positive odd integer? but how to show it?


text:
Q: QuickTime not looping wav file correctly I am trying to play a wav file on a loop in QuickTime 7.6.4 on Windows.  The wav file plays correctly the first time through but plays only a snippet of the file on subsequent loops.  The sound is like an alarm clock.  The second and all subsequent times through it appears to play only the last tone of the sound.
Windows Media Player can loop the file and it plays correctly on each loop.  I want it to play correctly in QT because this is a background sound I want to play on  web page in IE, safari, and firefox.  Firefox and Safari both are using QT.
You can find the file beep.wav at https://sites.google.com/site/busyspin/files
Any ideas?
Thanks,
Mark

A: Ok, I figured this out.  It turns out that QuickTime does some buffering at the beginning of a loop that causes the beginning of the file not to be played after the first time through.  Here is a link to an apple mailing list post about this issue.
http://lists.apple.com/archives/QuickTime-API/2007/Sep/msg00184.html


text:
Q: no kernel image is available for execution on the device Fatal Python error: Aborted I want to run yolov4 code in this repo: https://github.com/hunglc007/tensorflow-yolov4-tflite
And I installed python 3.7 and all requirements and cuda and cudnn.
By the log, the cudnn and cuda is installed well, but there is error of "no kernel image is available for execution on the device" what is this error? is it related in cuda or cudnn version error?
Python: 3.7.9, CUDA: 10.1, Tensorflow:2.3.0rc0, Tensorflow-GPU:not installed, CUDNN:7.5.0, OS: Windows10(x64)
py -3.7 save_model.py --weights ./data/yolov4.weights --output ./checkpoints/yolov4-416-tflite --input_size 416 --model yolov4 --framework tflite
2020-09-03 11:02:05.897607: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cudart64_101.dll
2020-09-03 11:02:09.504648: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library nvcuda.dll
2020-09-03 11:02:09.997508: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce 940MX computeCapability: 5.0
coreClock: 1.2415GHz coreCount: 3 deviceMemorySize: 2.00GiB deviceMemoryBandwidth: 13.41GiB/s
2020-09-03 11:02:10.017273: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cudart64_101.dll
2020-09-03 11:02:10.036505: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cublas64_10.dll
2020-09-03 11:02:10.059534: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cufft64_10.dll
2020-09-03 11:02:10.074749: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library curand64_10.dll
2020-09-03 11:02:10.094710: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cusolver64_10.dll
2020-09-03 11:02:10.115167: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cusparse64_10.dll
2020-09-03 11:02:10.140633: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cudnn64_7.dll
2020-09-03 11:02:10.148636: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1858] Adding visible gpu devices: 0
2020-09-03 11:02:10.155846: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations:  AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2020-09-03 11:02:10.188413: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x295adc030a0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-09-03 11:02:10.199421: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
2020-09-03 11:02:10.207675: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1716] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce 940MX computeCapability: 5.0
coreClock: 1.2415GHz coreCount: 3 deviceMemorySize: 2.00GiB deviceMemoryBandwidth: 13.41GiB/s
2020-09-03 11:02:10.222939: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cudart64_101.dll
2020-09-03 11:02:10.231890: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cublas64_10.dll
2020-09-03 11:02:10.241896: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cufft64_10.dll
2020-09-03 11:02:10.250393: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library curand64_10.dll
2020-09-03 11:02:10.260177: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cusolver64_10.dll
2020-09-03 11:02:10.268644: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cusparse64_10.dll
2020-09-03 11:02:10.278132: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cudnn64_7.dll
2020-09-03 11:02:10.286635: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1858] Adding visible gpu devices: 0
2020-09-03 11:02:10.380510: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1257] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-09-03 11:02:10.388703: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1263]      0
2020-09-03 11:02:10.394562: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1276] 0:   N
2020-09-03 11:02:10.402323: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1402] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 1464 MB memory) -> physical GPU (device: 0, name: GeForce 940MX, pci bus id: 0000:01:00.0, compute capability: 5.0)
2020-09-03 11:02:10.429701: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x295ae120140 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
2020-09-03 11:02:10.441631: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): GeForce 940MX, Compute Capability 5.0
2020-09-03 11:02:10.619742: F .\tensorflow/core/kernels/random_op_gpu.h:232] Non-OK-status: GpuLaunchKernel(FillPhiloxRandomKernelLaunch<Distribution>, num_blocks, block_size, 0, d.stream(), gen, data, size, dist) status: Internal: no kernel image is available for execution on the device
Fatal Python error: Aborted

A: The error indicates that the pre-built binary used in tensorflow, does not support the SM version (compute capability) supported by your actual hardware.
You can refer to below link for supported combinations:
https://www.tensorflow.org/install/source_windows#gpu
Based on this, both 2.1.0 and 2.3.0 require CUDNN 7.4 and CUDA 10.1. You should try with these supported combinations.
[2.3.0 release/rc2/rc0 specific] from https://github.com/tensorflow/tensorflow/releases/tag/v2.3.0 - TF 2.3 includes PTX kernels only for compute capability 7.0 to reduce the TF pip binary size. Earlier releases included PTX for a variety of older compute capabilities.


text:
Q: Which file to locate to see data of database in SQLite browser I'm creating a database "UserDataBase.db" and while opening this in SQLite browser neither data nor tables is being shown if I am doing any CRUD operations then it works.I am providing images link also regarding which file I am locating in SQLite browser.First I am synchronizing these files and saving on Desktop and opening in SQLite browser.I have tried to fetch the data from the database it works fine.

A: As the database is just 4k and that the -wal file is 80.5k the data hasn't been written/comitted. You need to close the database or checkpoint the database and then copy the file. Or you could copy the -wal and -shm files into DB Browser open it and then close it and then re-open it.


text:
Q: how to allocate an 128 bit array with new Intel instructions with dynamic memory? I am new working with new Intel instructions, so until now I just had been working with static memory, so I have a declaration as:
__m128i  pResult[10];

But now I am wondering if it is possible to allocate the memory in a dynamic way, as using malloc or calloc but for this new instructions.

A: Just like any other malloc:
__m128i *p = (__m128i*)malloc(10 * sizeof(__m128i));


text:
Q: How should I access a variable from javascript in PHP to perform some actions? I have a file named sample.php, in which I have some JS code, and some PHP code. This is some sort of sample snippet of the code I have :
<!DOCTYPE html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<head>
<script type="text/javascript">
var ThunkableWebviewerExtension = {
  receiveMessage: function(fxn) {
    var callbackFunction = function(event) {
      if (typeof fxn === 'function') {
        fxn(event.data)
      }
    };
    document.addEventListener('message', callbackFunction, false);
    window.addEventListener('message', callbackFunction, false);
  }
}
</script>
</head>

<body>
<script type="text/javascript">
var value;
ThunkableWebviewerExtension.receiveMessage(function(message) {
  value = message;
});

//sending the value with ajax
$.ajax({
  url : "./sample.php", //same file
  method : "GET",
  data: {"name": value},

  success : (res) => {
    console.log(value);
  },
  error : (res) => {
    console.log(res);
  }
})
</script>

<?php
echo $_GET['name'];
?>

</body>
</html>

The problem is the PHP code doesn't print anything - Are there any error/bug I need to fix? Or is there a better method for accessing a JS variable in PHP?
Thanks! :)

A: Here's how you can access PHP code within in a <script> (without using AJAX):
<?php
echo"<script>";
  include ('javascriptStuff.js');
  echo'let x =  '.json_encode($phpVariable).';';
echo"</script>";
?>


text:
Q: dlib dnn synchronisation seems to not store everything I noticed a strange behaviour with the trainer.set_synchronization_file().
As far as I undersood (according to trainer_abstract.h and implementation in trainer.h), it saves the current status of the trainer (inc net) so that we can stop the training at some point and restart from the exact same step.
However when using the example dnn_metric_learning_on_images_ex.cpp (from master b4a54490783). If I stop the training (e.g. ctrl+c) and then restart, the loss is decreasing significantly, as if some momentum was reset or so, and SGD is finding a better path for improvement.
As anybody an idea?
Here is some code sample. Only the stopping criteria is updated after synchronisation.
dnn_trainer<net_type> trainer(net, sgd(0.0001, 0.9), {1,0});
trainer.set_learning_rate(0.1);
trainer.be_verbose();
trainer.set_synchronization_file("face_metric_sync", std::chrono::minutes(5));
trainer.set_iterations_without_progress_threshold(10000);
// data loaders (...)
while(trainer.get_learning_rate() >= 1e-5)
{
    qimages.dequeue(images);
    qlabels.dequeue(labels);
    trainer.train_one_step(images, labels);
}

Here is an example of status before stopping:
Saved state to face_metric_sync
step#: 198726  learning rate: 0.001  average loss: 0.00928623   steps without apparent progress: 5923
step#: 198844  learning rate: 0.001  average loss: 0.00950317   steps without apparent progress: 6183
step#: 198963  learning rate: 0.001  average loss: 0.00971744   steps without apparent progress: 6525
step#: 199082  learning rate: 0.001  average loss: 0.00917967   steps without apparent progress: 6681
step#: 199200  learning rate: 0.001  average loss: 0.00942927   steps without apparent progress: 6834
step#: 199319  learning rate: 0.001  average loss: 0.00938926   steps without apparent progress: 6941
step#: 199438  learning rate: 0.001  average loss: 0.00917057   steps without apparent progress: 6915
Saved state to face_metric_sync
step#: 199552  learning rate: 0.001  average loss: 0.00964872   steps without apparent progress: 7487
^C

And after restarting
objs.size(): 75656
step#: 199507  learning rate: 0.001  average loss: 0.00974885   steps without apparent progress: 7146
step#: 199654  learning rate: 0.001  average loss: 0.00720691   steps without apparent progress: 64
step#: 199812  learning rate: 0.001  average loss: 0.00687095   steps without apparent progress: 209
step#: 199970  learning rate: 0.001  average loss: 0.00705782   steps without apparent progress: 439
step#: 200128  learning rate: 0.001  average loss: 0.00690515   steps without apparent progress: 584


text:
Q: Как правильно вывести дату и время? в переменной message.date лежит значение, если его вывести в шаблон то выдаст = 2022-04-21 10:39:58.000000+0300
Я хочу чтобы выводило только 10:39
Подскажите как это сделать?

A: Используя getHours и getMinutes

let date = new Date();
let time = date.getHours() + ':' + date.getMinutes();
console.log(time);

А если у вас дата в виде строки то так

let string = '2022-04-21 10:39:58.000000+0300';
let date = new Date(string);
let time = date.getHours() + ':' + date.getMinutes();
console.log(time);


text:
Q: Как в объект передать зависимость, минуя методы и свойства этого объекта? Есть следующие типы в пространстве имен:
namespace Model {
   public interface IData {
      void Send(string str);
   }
   public class Test {
      public void Run() {
        // (1)
      }
   }
}

В методе Test.Run для его работы должна оказаться ссылка на объект с реализацией IData.

Есть следующая реализация интерфейса IData и код для работы с Test.
class Data : Model.IData {
    public void Send(string str) { }
}

var d = new Data();
var t = new Test();

// (2)

Какой код должен быть вместо (1) и (2), чтобы в Test.Run оказалась ссылка на Data?
При этом в определении класса Test нельзя что-либо менять, нельзя добавлять конструктор(ы), методы, свойства и поля, и нельзя менять сигнатуру метода Run.

Также нельзя использовать Singleton.
p.s.
Это не для "размять мозги", как сказали в комментах. Есть огромное количество кода. И есть просто драконовский анализатор кода. Добавлять/менять правила в анализаторе не будут. Код Model менять нельзя и синглтоны исключены, а в Test.Run надо добавить зависимость. На вопрос, - как? Ответили, - как хотите так и делайте.
Если есть идеи - напишите как, а не минусуйте вопрос.

A: Вот рабочий пример с thread local storage:
namespace Model
{
    public interface IData
    {
        void Send(string str);
    }
    public class Test
    {
        public void Run()
        {
            LocalDataStoreSlot slot = Thread.GetNamedDataSlot("dict");
            var dict = (Dictionary<Model.Test, Model.IData>)Thread.GetData(slot);
            var d = dict[this];
        }
    }
}

namespace ThreadLocalTest
{
    class Data : Model.IData
    {
        public void Send(string str) { }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var d = new Data();
            var t = new Model.Test();

            LocalDataStoreSlot slot = Thread.AllocateNamedDataSlot("dict");
            var dict = new Dictionary<Model.Test, Model.IData>();
            Thread.SetData(slot, dict);
            dict[t] = d;
            t.Run();
            Thread.FreeNamedDataSlot("dict");
        }
    }
}

По поводу других возможных опций, вот ещё: http://blog.stephencleary.com/2013/04/implicit-async-context-asynclocal.html (это пригодится, если вы хотите протащить контекст через границу await).

A: В порядке дурацкого предложения.
Создаём новый класс, который слушает сетевой порт. В конструктор передаём адрес объекта типа Data. В Test.Run подключаемся к порту и получаем адрес.
Можно также использовать вместо сетевых соединений pipe или класть адрес в файл с фиксированным расположением.


text:
Q: Ember-data createRecord with hasMany relationship without saving I want to create a new site record. The model looks like:
var SiteModel = DS.Model.extend({
    name: attr(),
    ...

    languages: DS.hasMany('language'),
});

The language property describes in which languages the content of a site can be written. To create the form, I need to create a model in my route. So I want to create a new record, without saving this one to the db:
 var WebsitesNewRoute = Ember.Route.extend({
     model: function() {
         return this.store.createRecord('site', {
              languages: Ember.A()
         });
     }
 }

That does not work as intended, as I got the following error: cannot set read-only property "languages" on object: <app@model:site::ember1012:null>>. Why is the languages property readOnly? As far as I know I did not configure that in my model...

I know the question Ember Data- createRecord in a hasMany relationship, but in my case I don't want to save anything yet (I only want to create the model, so I could use it in my template).

A: Ember-Data defines languages as a read-only property because it doesn't want you to replace the array. No matter if you're saving or not, Ember-Data wants you to add relationships with addObject and remove relationships with removeObject.
So if you wanted to add a language, you would do this:
model: function() {
    var model = this.store.createRecord('site');
    var language = getLanguage();
    model.get('languages').addObject(language);
    return model;
}

What you're doing by giving languages to createRecord, is essentially calling model.set('languages', Ember.A()), and Ember-Data doesn't like that.
It's dumb, I know, but that's just how Ember-Data works.


text:
Q: How to change the favicon dynamically in VueJs I would like to do this very common trick that is to be able to change the favicon of my VueJs app dynamically.
For example : I have a timer in my app that is running in background and I would like to change the favicon when the timer is running.
In VueJs since the favicon is set in the index.html file I really don't know how could I do to be able to modify it in others component of my app. ?
I tried this approach but it did not work
Thanks for your help

A: This will help, it is awesome libary with utilities for Vue 2 and 3.
VueUse useFavicon

A: You should be able to grab the favicon w/ document.querySelector("link[rel~='icon']").
Then, this article on CSS tricks should help you achieve the result you wish.

A: Great question, I'd like to toggle my favicon depending on the dark/light mode  in Vue2 with Vuetify application.
Hence path to favicon is static in index.html in Vue I think there is way around messing with index.html by selectors or CSS.
The most elegant way of doing it is using VueUse!
The link in the correct answer above by Sebastian Wrzalek is broken please use this link for VueUse reference
https://vueuse.org/core/usefavicon/


text:
Q: How to estimate if an image is in focus I am building a test measurement (optics) to look a rectangular slit opening (1mm x 15 microns). The slit opening is illuminated by a white LED and using a microscope objective to magnify it to 10X on an image sensor.
What would be the possible method to estimate if the image is in it's best focus?
Current method, using a line profile and look for peaking position.
Any other ideas ?

A: Since you're imaging something that is basically a 2D rectangle function you would need an infinite amount of spatial frequencies reconstruct it in the Fourier domain.
You could take the FFT of the image and vary the image or object distance until you got the highest possible spatial frequencies.

A: You could try using contrast. The contrast in the image is highest when the image is in best focus. You can analyze the contrast information and move the object, lens, or sensor into a position that gives the maximum contrast value.
The downside to this is that you will need to typically adjust your opto-mechanics through the full range of motion to find the peak contrast. In other words, you may need a brute force search to find the maximum contrast.


text:
Q: SQL Azure IaaS encryption using Key Vault and a certificate I'm trying to create an ARM template which can deploy a SQL Enterprise VM in Azure with Transparent Data Encryption (TDE), utilizing Key Vault as the EKM.
I've found examples of how to enable TDE through Key Vault including the 101 SQL KeyVault template and SQL ARM Provision but in both instances they only require the Key Vault URL and access credentials (AppID and Secret).
Being as no existing secret URL is supplied, this seems to imply that the asymmetric key residing in the EKM (Key Vault) will be created by the deployment process which, according to Microsoft's Security Note, is bad practice for Production workloads being as the key can never be exported.
Given the above, I'm attempting to point SQL to an existing asymmetric key I've imported into Key Vault as a pfx file, but I can't seem to find any documentation on how to reference this when it comes to creating the VM via an ARM template.  If anyone knows whether this is possible, instead of having to do a number of manual steps via PowerShell and/or T-SQL once the VM's been created, I'd be very grateful.

A: As a small prewarning, this isn't something I've used, so far it was just from having a read through the source, I'll likely try it at some point soon, but this might help along the way.
Looking at the files for the Commit that added keyvault to the Azure SQL Extension the part that templates interact with appears to be the part that the Template configures
This is also the part that the Azure SQL VM Powershell commands interact with, which also feed into the same parts.
If you can configure it from Powershell through that extension then it should also be possible to do so through templates.

A: Microsoft have confirmed that it's not currently possible to configure end-to-end EKM via Key Vault using an ARM template alone.  The vast majority of it has to be achieved via PowerShell and/or T-SQL.  An ARM template can be used to create a Key Vault, but you're not currently able to configure Azure AD Apps (required to authenticate to Key Vault) at present, neither can you add the asymmetric certificate required for TDE into a Key Vault Key.