问:
How to make a condition for onclick loader when user don't completed all fields in form
I have a problem with the form, there is some information in the form and a photo to upload. The time to send the form is different depending on the weight of the file, if it is ~ 3MB it's ok, however if someone uses the mobile version they use the camera in the phone and then the photo can weigh up to 7MB - then the loading time is too long and the user is confused. Therefore I used a simple loader on onclick and the same with onload on the next page, works great, unless someone don't fill the field in the form, then the loader covers the whole page and turns forever. How can I make the condition that the loader appears on oncick only if all fields are completed correctly?

There's form:

```<code><div id="preloader" aria-busy="true" aria-label="Loading, please wait." role="progressbar"><img class="icon" src="https://raziraz.github.io/codepen/img/bolt.svg">
</div>

    <main id="site" role="main">
    <script  src="./preloaderr.js"></script>

        <h2>Dodaj nową licencję</h2>
        <form method="POST" action="Licencja_Użytkownik_Dodawanie_Skrypt.php" enctype="multipart/form-data">
        <input type="hidden" name="login" value="$login">

        <div id="inputtitle">Prześlij zdjęcie</div>
        <input type="file" name="licencja_plik" required>
        </br>

        <div id="inputtitle">Numer licencji</div>
        <input type="text" name="Numer_Licencji"  placeholder="Numer licencji" required></br>

        <div id="inputtitle">Numer wypisu</div>
        <input type="text" name="Numer_Wypisu"  placeholder="Numer wypisu" required></br>

        <div id="inputtitle">Miasto</div>
        <input type="text" name="Miasto_Licencji"  placeholder="Miasto" required></br>

        <div id="inputtitle">Numer rejestracyjny</div>
        <input type="text" name="Numer_Rejestracyjny"  placeholder="Numer rejestracyjny" required></br>

        <div id="inputtitle">Licencja ważna do:</div>
        <input type="date" name="Licencja_Do"  placeholder="05-02-2020" required></br>

        <div id="containera">
        <div id="right">

        <button type="submit" class="buttondodaj" onclick="teest(); window.parent.parent.scrollTo(0,0)">
        Dodaj   <i class="fas fa-arrow-right"></i>
        </button>

        </form></div>

        <form method="GET" action="Licencja_Użytkownik.php" >
        <input type="hidden" name="login" value="$login">

        <div id="left">

        <button type="submit" class="buttonanuluj">
        <i class="fas fa-arrow-left"></i>   Anuluj
        </button>

        </form>
        </div>
        </div>
    </main>

</code>```

There's js preloader and loader:

```<code>
function preloader() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "0";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "1";
}
window.onload = preloader;

function teest() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "1";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "0";

}
</code>```

I will be grateful for the hints :).

答: Just check that all the fields are filled before launching your function. By the way I advise you not to generate html like that with php. It's not readable</p>

Body:
I have a problem with the form, there is some information in the form and a photo to upload. The time to send the form is different depending on the weight of the file, if it is ~ 3MB it's ok, however if someone uses the mobile version they use the camera in the phone and then the photo can weigh up to 7MB - then the loading time is too long and the user is confused. Therefore I used a simple loader on onclick and the same with onload on the next page, works great, unless someone don't fill the field in the form, then the loader covers the whole page and turns forever. How can I make the condition that the loader appears on oncick only if all fields are completed correctly?

There's form:

Dodaj nową licencję

        <form method="POST" action="Licencja_Użytkownik_Dodawanie_Skrypt.php" enctype="multipart/form-data">
        <input type="hidden" name="login" value="$login">

Prześlij zdjęcie

        <input type="file" name="licencja_plik" required>

Numer licencji

        <input type="text" name="Numer_Licencji"  placeholder="Numer licencji" required>

Numer wypisu

        <input type="text" name="Numer_Wypisu"  placeholder="Numer wypisu" required>

Miasto

        <input type="text" name="Miasto_Licencji"  placeholder="Miasto" required>

Numer rejestracyjny

        <input type="text" name="Numer_Rejestracyjny"  placeholder="Numer rejestracyjny" required>

Licencja ważna do:

        <input type="date" name="Licencja_Do"  placeholder="05-02-2020" required>

        <button type="submit" class="buttondodaj" onclick="teest(); window.parent.parent.scrollTo(0,0)">
        Dodaj
        </button>

        </form>

        <form method="GET" action="Licencja_Użytkownik.php" >
        <input type="hidden" name="login" value="$login">

        <button type="submit" class="buttonanuluj">
           Anuluj
        </button>

        </form>

There's js preloader and loader:

function preloader() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "0";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "1";
}
window.onload = preloader;

function teest() {
  var preloader = document.getElementById("preloader");
  preloader.style.opacity = "1";
  preloader.setAttribute("aria-busy", "false");
  document.getElementById("site").style.opacity = "0";

}

I will be grateful for the hints :).


来源: stackexchange

问:
NamedPipeClientStream does not connect
In our main application we have the following function (in VB.Net):

```<code> Public Overrides Function GetNewResults(setToProcessed As Boolean) As List(Of ReceivedData)

    Dim client = New NamedPipeClientStream(".", "PipesOfPiece",
                                           PipeDirection.InOut, PipeOptions.None,
                                           TokenImpersonationLevel.Impersonation)
    client.Connect()
    Dim reader = New StreamReader(client)
    Dim writer = New StreamWriter(client)
    writer.AutoFlush = True

    writer.WriteLine(DbPath)

    Dim serialized = reader.ReadLine
    client.Close()

    Dim newResults = JsonConvert.DeserializeObject(Of List(Of ReceivedData))(serialized)

    Return newResults

End Function
</code>```

The NamedPipeServer has been written in C# and, for now, is hosted in a console application:

```<code> static void StartServer()
    {

        server = new NamedPipeServerStream("PipesOfPiece", direction: PipeDirection.InOut,maxNumberOfServerInstances:10);

        server.WaitForConnection();
        StreamReader reader = new StreamReader(server);
        StreamWriter writer=  new StreamWriter(server);
        writer.AutoFlush = true;

        while (true)
            {
                var dbPath = reader.ReadLine();
                if (string.IsNullOrEmpty(dbPath)) continue;
                if (!File.Exists(dbPath))
                {
                    writer.WriteLine($"{dbPath} does not exist.");
                    continue;
                }
                var communicator = new DapperBwsCommunicator(dbPath,provider: "Microsoft.Jet.OLEDB.4.0");
                var newResults = communicator.GetAllResults(setToProcessed: true);
                var serialized = JsonConvert.SerializeObject(newResults);
                writer.WriteLine(serialized);
            }
    }
</code>```

The GetNewResults function is called every three seconds. The first time this function is called it works correctly. But the second time the code blocks on  Client.Connect. It seems then that the server does not respond any more.

Where am I going wrong?

EDIT
Thanks to Fandango's answer I came with a different implementation. This seems to work:

```<code>static void StartServer()
{

    server = new NamedPipeServerStream("PipesOfPiece", direction: PipeDirection.InOut,maxNumberOfServerInstances:10);

    server.WaitForConnection();
    StreamReader reader = new StreamReader(server);
    StreamWriter writer=  new StreamWriter(server);
    writer.AutoFlush = true;

    while (true)
        {
            var dbPath = reader.ReadLine();
            if (string.IsNullOrEmpty(dbPath)) continue;
            if (!File.Exists(dbPath))
            {
                writer.WriteLine($"{dbPath} does not exist.");
                continue;
            }
            var communicator = new DapperBwsCommunicator(dbPath,provider: "Microsoft.Jet.OLEDB.4.0");
            var newResults = communicator.GetAllResults(setToProcessed: true);
            var serialized = JsonConvert.SerializeObject(newResults);
            writer.WriteLine(serialized);
            server.Disconnnect();
            server.WaitForConnection();
        }
}
</code>```

答: this happens because you keep creating a new client connection every 3 seconds, while on the server side, after the first WaitForConnection, the code is stuck inside the loop and not waiting for client connections anymore.</p>

ContentLicense: CC BY-SA 4.0

Title: NamedPipeClientStream does not connect

Body:
In our main application we have the following function (in VB.Net):

 Public Overrides Function GetNewResults(setToProcessed As Boolean) As List(Of ReceivedData)

    Dim client = New NamedPipeClientStream(".", "PipesOfPiece",
                                           PipeDirection.InOut, PipeOptions.None,
                                           TokenImpersonationLevel.Impersonation)
    client.Connect()
    Dim reader = New StreamReader(client)
    Dim writer = New StreamWriter(client)
    writer.AutoFlush = True

    writer.WriteLine(DbPath)

    Dim serialized = reader.ReadLine
    client.Close()

    Dim newResults = JsonConvert.DeserializeObject(Of List(Of ReceivedData))(serialized)

    Return newResults

End Function

The NamedPipeServer has been written in C# and, for now, is hosted in a console application:

 static void StartServer()
    {

        server = new NamedPipeServerStream("PipesOfPiece", direction: PipeDirection.InOut,maxNumberOfServerInstances:10);

        server.WaitForConnection();
        StreamReader reader = new StreamReader(server);
        StreamWriter writer=  new StreamWriter(server);
        writer.AutoFlush = true;

        while (true)
            {
                var dbPath = reader.ReadLine();
                if (string.IsNullOrEmpty(dbPath)) continue;
                if (!File.Exists(dbPath))
                {
                    writer.WriteLine($"{dbPath} does not exist.");
                    continue;
                }
                var communicator = new DapperBwsCommunicator(dbPath,provider: "Microsoft.Jet.OLEDB.4.0");
                var newResults = communicator.GetAllResults(setToProcessed: true);
                var serialized = JsonConvert.SerializeObject(newResults);
                writer.WriteLine(serialized);
            }
    }

The GetNewResults function is called every three seconds. The first time this function is called it works correctly. But the second time the code blocks on  Client.Connect. It seems then that the server does not respond any more.

Where am I going wrong?

EDIT
Thanks to Fandango's answer I came with a different implementation. This seems to work:

static void StartServer()
{

    server = new NamedPipeServerStream("PipesOfPiece", direction: PipeDirection.InOut,maxNumberOfServerInstances:10);

    server.WaitForConnection();
    StreamReader reader = new StreamReader(server);
    StreamWriter writer=  new StreamWriter(server);
    writer.AutoFlush = true;

    while (true)
        {
            var dbPath = reader.ReadLine();
            if (string.IsNullOrEmpty(dbPath)) continue;
            if (!File.Exists(dbPath))
            {
                writer.WriteLine($"{dbPath} does not exist.");
                continue;
            }
            var communicator = new DapperBwsCommunicator(dbPath,provider: "Microsoft.Jet.OLEDB.4.0");
            var newResults = communicator.GetAllResults(setToProcessed: true);
            var serialized = JsonConvert.SerializeObject(newResults);
            writer.WriteLine(serialized);
            server.Disconnnect();
            server.WaitForConnection();
        }
}


问:
Can't glreadPixels more than 3844x1065
I am trying to render to an off-screen FBO a scene I made, and if I set width/height above 3844/1065, my final image gets limited to that resolution. I am using two monitors. The following image was rendered using 4500x2160 resolution. The "active" area is 3844x1065.

Here is some code:

```<code>        windowWidth = 4500
        windowHeight = 2160
        mainWindow = glfw.create_window(windowWidth, windowHeight, windowTitle, None, None)
        glfw.set_window_pos(mainWindow, 10, 10)
        glfw.make_context_current(mainWindow)
        glfw.set_window_size_callback(mainWindow, window_resize)
        frameBuffer = glGenFramebuffers(1)
        glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer)
        renderBuffer = glGenRenderbuffers(1)
        glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer)
        glRenderbufferStorage(GL_RENDERBUFFER, GL_RGB8, windowWidth, windowHeight)
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderBuffer)

        glDrawBuffer(GL_COLOR_ATTACHMENT0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # draw all the stuff
        glReadBuffer(GL_COLOR_ATTACHMENT0)
        img_buf = glReadPixels(0, 0, windowWidth, windowHeight, GL_RGB, GL_UNSIGNED_BYTE)
        image = Image.frombytes(mode="RGB", size=(windowWidth, windowHeight), data=img_buf)
        image = image.transpose(Image.FLIP_TOP_BOTTOM)
        image.save('example.png')
        glfw.set_window_should_close(mainWindow, True)

        def window_resize(window, width, height):
            glViewport(0, 0, width, height)
</code>```

FOUND a hint:

If I do :

```<code>     w,h = glfw.get_window_size(self.mainWindow)
     print(w)
     print(h)
</code>```

I get:
3844
1065

Therefore GLFW limits my window size, and drawing buffer is using that size only.

How can I set output for drawing to FBO of my selected size ? (ex 5000x3000).

The parameters of size of set_window_size_callback in the call of window_resize are the ones from _GLFWwindowsizefun, which are 3844x1065

答:
The viewport size always has to be the size of the rendertarget. This is not necessarily the size of the window.

Before rendering to the renderbuffer, you have to set the viewport to the renderbuffer size:

```<code>glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer)
glViewport(windowWidth, windowHeight); //Not the size of the window but of the renderbuffer

glDrawBuffer(GL_COLOR_ATTACHMENT0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

# draw all the stuff
</code>```

When you render to the FBO as well as to the window, then you have to adjust the viewport settings whenever you change the render target:

```<code>glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer)
glViewport(fboWidth, fboHeight);

# Render to FBO

glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(windowWidth, windowHeight);

# Render to Window
</code>```

Title: Can't glreadPixels more than 3844x1065

Body:
I am trying to render to an off-screen FBO a scene I made, and if I set width/height above 3844/1065, my final image gets limited to that resolution. I am using two monitors. The following image was rendered using 4500x2160 resolution. The "active" area is 3844x1065.

Here is some code:

        windowWidth = 4500
        windowHeight = 2160
        mainWindow = glfw.create_window(windowWidth, windowHeight, windowTitle, None, None)
        glfw.set_window_pos(mainWindow, 10, 10)
        glfw.make_context_current(mainWindow)
        glfw.set_window_size_callback(mainWindow, window_resize)
        frameBuffer = glGenFramebuffers(1)
        glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer)
        renderBuffer = glGenRenderbuffers(1)
        glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer)
        glRenderbufferStorage(GL_RENDERBUFFER, GL_RGB8, windowWidth, windowHeight)
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderBuffer)

        glDrawBuffer(GL_COLOR_ATTACHMENT0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # draw all the stuff
        glReadBuffer(GL_COLOR_ATTACHMENT0)
        img_buf = glReadPixels(0, 0, windowWidth, windowHeight, GL_RGB, GL_UNSIGNED_BYTE)
        image = Image.frombytes(mode="RGB", size=(windowWidth, windowHeight), data=img_buf)
        image = image.transpose(Image.FLIP_TOP_BOTTOM)
        image.save('example.png')
        glfw.set_window_should_close(mainWindow, True)

        def window_resize(window, width, height):
            glViewport(0, 0, width, height)

FOUND a hint:

If I do :

     w,h = glfw.get_window_size(self.mainWindow)
     print(w)
     print(h)

I get:
3844
1065

Therefore GLFW limits my window size, and drawing buffer is using that size only.

How can I set output for drawing to FBO of my selected size ? (ex 5000x3000).

The parameters of size of set_window_size_callback in the call of window_resize are the ones from _GLFWwindowsizefun, which are 3844x1065

Body:
The viewport size always has to be the size of the rendertarget. This is not necessarily the size of the window.

Before rendering to the renderbuffer, you have to set the viewport to the renderbuffer size:

glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer)
glViewport(windowWidth, windowHeight); //Not the size of the window but of the renderbuffer

glDrawBuffer(GL_COLOR_ATTACHMENT0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

# draw all the stuff

When you render to the FBO as well as to the window, then you have to adjust the viewport settings whenever you change the render target:

glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer)
glViewport(fboWidth, fboHeight);

# Render to FBO

glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(windowWidth, windowHeight);

# Render to Window


问:
'Double' is not convertible to 'CGFloat?'
My Xcode keeps giving me a Double is not convertible to CGFloat error. Thing is the error keeps moving whenever I change the code. At first it was on this line:
Text("left") .frame(width: 100.0, height: 100.0, alignment: .center) where I set the height to 100.0 now it is at the bottom:TextField("example", text: "PLACEHOLDER") .frame(width: 300.0, height: 300.0, alignment: .center) at the height.

On the apple dev site it says for swiftUI as an example:
.frame(width: 200, height: 200, alignment: .topLeading)
I tried removing the decimals and I get an Int is not convertible to CGFloat.
At one point I tried to put CGFloat() around each and I got a 'CGFloat is not convertible to CGFloat?' error

Any help is appreciated thank you

```<code>import Cocoa
import SwiftUI

HSplitView{
    VStack{
        Text("left")
            .frame(width: 100.0, height: 100.0, alignment: .center)
        Text("left bottom")
            .frame(width: 100.0, height: 100.0, alignment: .center)
        Text("leftbottombottom")
            .frame(width: 100.0, height: 100.0, alignment: .center)
    }
    TextField("example", text: "PLACEHOLDER")
        .frame(width: 300.0, height: 300.0, alignment: .center)
}
</code>```

答:
SwiftUI sometimes reports wrong errors, as is the case here. Your problem is that you have a type error in TextField("example", text: "PLACEHOLDER"). The second argument should be a binding, not a string. This works:

```<code>import Cocoa
import SwiftUI

struct MyView: View {
  @State var text = "PLACEHOLDER"

  var body: some View {
    HSplitView{
      VStack{
        Text("left")
          .frame(width: 100.0, height: 100.0, alignment: .center)
        Text("left bottom")
          .frame(width: 100.0, height: 100.0, alignment: .center)
        Text("leftbottombottom")
          .frame(width: 100.0, height: 100.0, alignment: .center)
      }
      TextField("example", text: $text)
        .frame(width: 300.0, height: 300.0, alignment: .center)
    }
  }
}
</code>```

Body:
My Xcode keeps giving me a Double is not convertible to CGFloat error. Thing is the error keeps moving whenever I change the code. At first it was on this line:
Text("left") .frame(width: 100.0, height: 100.0, alignment: .center) where I set the height to 100.0 now it is at the bottom:TextField("example", text: "PLACEHOLDER") .frame(width: 300.0, height: 300.0, alignment: .center) at the height.

On the apple dev site it says for swiftUI as an example:
.frame(width: 200, height: 200, alignment: .topLeading)
I tried removing the decimals and I get an Int is not convertible to CGFloat.
At one point I tried to put CGFloat() around each and I got a 'CGFloat is not convertible to CGFloat?' error

Any help is appreciated thank you

import Cocoa
import SwiftUI

HSplitView{
    VStack{
        Text("left")
            .frame(width: 100.0, height: 100.0, alignment: .center)
        Text("left bottom")
            .frame(width: 100.0, height: 100.0, alignment: .center)
        Text("leftbottombottom")
            .frame(width: 100.0, height: 100.0, alignment: .center)
    }
    TextField("example", text: "PLACEHOLDER")
        .frame(width: 300.0, height: 300.0, alignment: .center)
}

Body:
SwiftUI sometimes reports wrong errors, as is the case here. Your problem is that you have a type error in TextField("example", text: "PLACEHOLDER"). The second argument should be a binding, not a string. This works:

import Cocoa
import SwiftUI

struct MyView: View {
  @State var text = "PLACEHOLDER"

  var body: some View {
    HSplitView{
      VStack{
        Text("left")
          .frame(width: 100.0, height: 100.0, alignment: .center)
        Text("left bottom")
          .frame(width: 100.0, height: 100.0, alignment: .center)
        Text("leftbottombottom")
          .frame(width: 100.0, height: 100.0, alignment: .center)
      }
      TextField("example", text: $text)
        .frame(width: 300.0, height: 300.0, alignment: .center)
    }
  }
}


问:
LLVM - Atomic Ordering Unordered
I'm working on a library that heavily relies on bitwise operations, where the most important operate on shared memory. I was also having a look at LLVM's atomic ordering documentation and noticed unordered, which seems to be even weaker than C/C++'s relaxed memory order. I have several questions about it:

What are the differences between unordered and relaxed?

Say I have an atomic bool, is it safe to mutate it via unordered load/store?

Say I have an atomic bitmask, is it safe to mutate it via unordered load/store?

Is it safe to mutate it via unordered fetch_and/or/xor?

Is it safe to mutate it via unordered swap?

Is it safe to mutate it via unordered compare_and_swap?

答:
The short answer is: whatever your problem is, unordered is screamingly unlikely to be the solution !

The longer answer is...

...the LLVM Language Reference Manual says:

unordered

The set of values that can be read is governed by the happens-before partial order. A value cannot be read unless some operation wrote it. This is intended to provide a guarantee strong enough to model Java’s non-volatile shared variables. This ordering cannot be specified for read-modify-write operations; it is not strong enough to make them atomic in any interesting way.

The "A value cannot be read unless some operation wrote it." is fun !  What this means is that “speculative” writes are not allowed.  Say you have if (y == 99) x = 0 ; else x = y+1 ;: an optimizer could turn that into x = y+1 ; if (y == 99) x = 0 ; where the first write of x is the “speculative” one.  (I'm not saying that's a sensible or common optimization.  The point is that transformations which are perfectly OK from the perspective of a single thread, are not OK for atomics.)  The C/C++ standards have the same restriction: no “out-of-thin-air” values are allowed.

Elsewhere the LLVM documentation describes unordered as loads/stores which complete without interruption from any other store -- so a load which reads two halves (say) of a value would not qualify if the two halves could be the result of two separate writes !

It seems monotonic is the local name for C/C++ memory_order_relaxed, and is described:

monotonic

In addition to the guarantees of unordered, there is a single total order for modifications by monotonic operations on each address. All modification orders must be compatible with the happens-before order.

Unlike unordered, with monotonic all threads will see writes to a given address in the same order.  This means that if thread 'a' writes '1' to a given location, and afterwards thread 'b' writes '2', then after that threads 'c' and 'd' must both read '2'.  (Hence the name.)

There is no guarantee that the modification orders can be combined to a global total order for the whole program (and this often will not be possible).

This is the relaxed bit.

The read in an atomic read-modify-write operation (cmpxchg and atomicrmw) reads the value in the modification order immediately before the value it writes.

Same like C/C++: read-modify-write cannot be interrupted by another write.

If one atomic read happens before another atomic read of the same address, the later read must see the same value or a later value in the address’s modification order. This disallows reordering of monotonic (or stronger) operations on the same address.

It's monotonic, guys.

If an address is written monotonic-ally by one thread, and other threads monotonic-ally read that address repeatedly, the other threads must eventually see the write.

So... there may be some latency between a write and reads, but that latency is finite (but may, I assume, not be the same for all threads).  The "eventually" is interesting.  The C11 standard says "Implementations should make atomic stores visible to atomic loads within a reasonable amount of time.", which is similar but with a more positive spin :-)

This corresponds to the C++0x/C1x memory_order_relaxed.

So there you go.

You asked:

Say I have an atomic bool, is it safe to mutate it via unordered load/store?

Say I have an atomic bitmask, is it safe to mutate it via unordered load/store?

It rather depends on what you mean by safe :-(  With any atomic load of 'x' followed later by an atomic store of 'x', you have no idea how many other stores to 'x' there have been since the load.  But, the added joy of unordered is that it does not guarantee that all threads will see all writes to 'x' in the same order !

Your other questions are moot, because you cannot have unordered read-modify-write operations.

As a practical matter, your x86_64 guarantees that all writes are visible to all threads in the same order -- so all atomic operations are at the very least monotonic/memory_order_relaxed -- no LOCK prefixes and no xFENCE instructions are required, plain MOV to memory will do the trick.  In fact, better than that, plain MOV to/from memory gives memory_order_release/memory_order_acquire.

FWIW: you mention bit-wise operations.  I guess it's obvious that reading/writing a few bits is going to involve reading/writing some number of other bits as a side-effect.  Which adds to the fun.

My guess is that at a minimum you will need to be doing read-modify-write operations.  Again, on x86_64 this boils down to an instruction with a LOCK prefix, which is going to cost 10's of clocks -- how many 10's depends on the CPU and degree of contention.  Now, a mutex lock and unlock will each involve a LOCKed, so it's generally worth replacing a mutex_lock/...do some reading and writing.../mutex_unlock sequence by an atomic read-modify-write(s) really only if it's just one read-modify-write.

The disadvantage of a mutex is, of course, that a thread can be "swapped out" while it holds the mutex :-(

A spin-lock (on x86_64) requires a LOCK to acquire but not to release... but the effect of being "swapped out" while holding a spin-lock is even worse :-(

Title: LLVM - Atomic Ordering Unordered


问:
AlarmManager working on its own but not in JobSchedule
The first 2 alarms handled by the AlarmManager in MainActivity is working as expected however the 2 alarms handled by the AlarmManager in JobScheduler is supposed to come into effect every 10 seconds which it doesn't seem to. I have nothing in the logcat to indicate where I should look. Any ideas of where I might be going wrong?

MainActvity:

```<code>public class MainActivity extends AppCompatActivity {

    private static final String TAG = "Notifications";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Calendar c = Calendar.getInstance();
        Integer currentHour = c.get(Calendar.HOUR_OF_DAY);
        Integer currentMinute = c.get(Calendar.MINUTE);
        Integer currentSecond = c.get(Calendar.SECOND);
        Toast.makeText(this, String.valueOf(currentSecond), Toast.LENGTH_SHORT).show();

        setAlarm("Gym", currentHour,currentMinute,currentSecond + 3,1);
        setAlarm("Swimming", currentHour,currentMinute,currentSecond + 6,2);
        scheduleJob();
    }

    public void setAlarm(String activity, Integer hour, Integer minute, Integer second, Integer requestCode) {
        Calendar currentTime = Calendar.getInstance();
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, second);

        if (c.after(currentTime)) {
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
            intent.putExtra("Activity", activity);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, intent, 0);

            alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
            // alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
        }
    }
    public void scheduleJob() {
        ComponentName componentName = new ComponentName(this, NotificationService.class);
        JobInfo jobInfo = new JobInfo.Builder(123, componentName)
                .setRequiresCharging(true)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                .setPersisted(true)
                .setPeriodic(1000 * 10)
                .build();
        JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);

        int resultCode = jobScheduler.schedule(jobInfo);
        if (resultCode == JobScheduler.RESULT_SUCCESS) {
            Log.d(TAG, "Job scheduled");
        } else {
            Log.d(TAG, "Job scheduling failed");
        }
    }
}
</code>```

JobService:

```<code>public class NotificationService extends JobService {

    @Override
    public boolean onStartJob(JobParameters parameters) {
        doBackgroundWork(parameters);
        return true;
    }

    private void doBackgroundWork(final JobParameters parameters) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Calendar c = Calendar.getInstance();
                Integer currentHour = c.get(Calendar.HOUR_OF_DAY);
                Integer currentMinute = c.get(Calendar.MINUTE);
                Integer currentSecond = c.get(Calendar.SECOND);

                setAlarm("Gym", currentHour,currentMinute,currentSecond + 3,1);
                setAlarm("Swimming", currentHour,currentMinute,currentSecond + 6,2);
                jobFinished(parameters, false);
            }
        }).start();
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }

    public void setAlarm(String activity, Integer hour, Integer minute, Integer second, Integer requestCode) {
        Calendar currentTime = Calendar.getInstance();
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, second);

        if (c.after(currentTime)) {
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
            intent.putExtra("Activity", activity);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, intent, 0);

            alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
            // alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
        }
    }
}
</code>```

BroadcastReceiver:

```<code>public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String activity = intent.getExtras().getString("Activity");

        NotificationHelper notificationHelper = new NotificationHelper(context);
        NotificationCompat.Builder nb = notificationHelper.getChannelNotification(activity);
        notificationHelper.getManager().notify(1, nb.build());
    }
}
</code>```

NotificationHelper:

```<code>public class NotificationHelper extends ContextWrapper {

    public static final String channelID = "channelID";
    public static final String channelName = "Channel";
    private NotificationManager mManager;

    public NotificationHelper(Context base) {
        super(base);
        createChannels();
    }

    private void createChannels() {
        NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
        channel.enableLights(true);
        channel.enableVibration(true);
        channel.setLightColor(R.color.royalBlue);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

        getManager().createNotificationChannel(channel);
    }

    public NotificationManager getManager() {
        if (mManager == null) {
            mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }

        return mManager;
    }

    public NotificationCompat.Builder getChannelNotification(String activity) {
        return new NotificationCompat.Builder(getApplicationContext(), channelID)
                .setContentTitle(activity)
                .setContentText("Come on")
                .setSmallIcon(R.drawable.ic_event);
    }
}
</code>```

Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.app.notifications">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="com.app.notifications.AlarmReceiver" />

        <service
            android:name="com.app.notifications.NotificationService"
            android:permission="android.permission.BIND_JOB_SERVICE" />

    </application>

</manifest>
</code>```

答:
JobScheduler is triggered when all conditions mentioned in your JobInfo is satisfied and the system should also be free enough to handle the job.
Looks like you've added requires charging as one of the parameters of your job. Try removing that.
Also the network type condition given is unmetered. Please check if tweaking this helps your case.</p>

Body:
The first 2 alarms handled by the AlarmManager in MainActivity is working as expected however the 2 alarms handled by the AlarmManager in JobScheduler is supposed to come into effect every 10 seconds which it doesn't seem to. I have nothing in the logcat to indicate where I should look. Any ideas of where I might be going wrong?

MainActvity:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "Notifications";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Calendar c = Calendar.getInstance();
        Integer currentHour = c.get(Calendar.HOUR_OF_DAY);
        Integer currentMinute = c.get(Calendar.MINUTE);
        Integer currentSecond = c.get(Calendar.SECOND);
        Toast.makeText(this, String.valueOf(currentSecond), Toast.LENGTH_SHORT).show();

        setAlarm("Gym", currentHour,currentMinute,currentSecond + 3,1);
        setAlarm("Swimming", currentHour,currentMinute,currentSecond + 6,2);
        scheduleJob();
    }

    public void setAlarm(String activity, Integer hour, Integer minute, Integer second, Integer requestCode) {
        Calendar currentTime = Calendar.getInstance();
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, second);

        if (c.after(currentTime)) {
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
            intent.putExtra("Activity", activity);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, intent, 0);

            alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
            // alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
        }
    }
    public void scheduleJob() {
        ComponentName componentName = new ComponentName(this, NotificationService.class);
        JobInfo jobInfo = new JobInfo.Builder(123, componentName)
                .setRequiresCharging(true)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                .setPersisted(true)
                .setPeriodic(1000 * 10)
                .build();
        JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);

        int resultCode = jobScheduler.schedule(jobInfo);
        if (resultCode == JobScheduler.RESULT_SUCCESS) {
            Log.d(TAG, "Job scheduled");
        } else {
            Log.d(TAG, "Job scheduling failed");
        }
    }
}

JobService:

public class NotificationService extends JobService {

    @Override
    public boolean onStartJob(JobParameters parameters) {
        doBackgroundWork(parameters);
        return true;
    }

    private void doBackgroundWork(final JobParameters parameters) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Calendar c = Calendar.getInstance();
                Integer currentHour = c.get(Calendar.HOUR_OF_DAY);
                Integer currentMinute = c.get(Calendar.MINUTE);
                Integer currentSecond = c.get(Calendar.SECOND);

                setAlarm("Gym", currentHour,currentMinute,currentSecond + 3,1);
                setAlarm("Swimming", currentHour,currentMinute,currentSecond + 6,2);
                jobFinished(parameters, false);
            }
        }).start();
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }

    public void setAlarm(String activity, Integer hour, Integer minute, Integer second, Integer requestCode) {
        Calendar currentTime = Calendar.getInstance();
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, second);

        if (c.after(currentTime)) {
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
            intent.putExtra("Activity", activity);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, intent, 0);

            alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
            // alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
        }
    }
}

BroadcastReceiver:

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String activity = intent.getExtras().getString("Activity");

        NotificationHelper notificationHelper = new NotificationHelper(context);
        NotificationCompat.Builder nb = notificationHelper.getChannelNotification(activity);
        notificationHelper.getManager().notify(1, nb.build());
    }
}

NotificationHelper:

public class NotificationHelper extends ContextWrapper {

    public static final String channelID = "channelID";
    public static final String channelName = "Channel";
    private NotificationManager mManager;

    public NotificationHelper(Context base) {
        super(base);
        createChannels();
    }

    private void createChannels() {
        NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
        channel.enableLights(true);
        channel.enableVibration(true);
        channel.setLightColor(R.color.royalBlue);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

        getManager().createNotificationChannel(channel);
    }

    public NotificationManager getManager() {
        if (mManager == null) {
            mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }

        return mManager;
    }

    public NotificationCompat.Builder getChannelNotification(String activity) {
        return new NotificationCompat.Builder(getApplicationContext(), channelID)
                .setContentTitle(activity)
                .setContentText("Come on")
                .setSmallIcon(R.drawable.ic_event);
    }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.app.notifications">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="com.app.notifications.AlarmReceiver" />

        <service
            android:name="com.app.notifications.NotificationService"
            android:permission="android.permission.BIND_JOB_SERVICE" />

    </application>

</manifest>


问:
How to block previous year in JQuery Datepicker?
In jquery Datepicker, I won't block the previous year which means I only select the current year.
Ex: Current year is now 2020 but in jquery Datepicker, I choose the previous year(2019) also. But I want to Disable the previous year(2019).</p>

答: You can use the minDate option in the settings of the datepicker and set it to January 1st 2020. Link to API docs


问:
Update DB through Gridview selected DDL from DataSource
I have one gridview which is connected through SQL Data source from one table and I have enabled the EDIT and delete columns of gridview. When I'm Editing the value of row, a column is having DDL in Edit mode instead of textbox connected through another SQL datasource.

Once the page loads, after clicking the Edit Row of the Gridview, i'm selecting another value from dropdown and after clicking update it giving me error, can not insert null values into database.

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="CreateRoster.aspx.cs" Inherits="E_Scheduler.CreateRoster" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <link href="CSS/Addroster.css" rel="stylesheet" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="maindiv">

        <asp:GridView ID="GridView1" runat="server" ShowFooter="True" AutoGenerateColumns="False" BackColor="#

    CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" DataKeyNames="id" DataSourceID="SqlDataSource1" ForeColor="Black">
                <Columns>
                    <asp:CommandField ShowEditButton="True" ShowDeleteButton="True"></asp:CommandField>
                    <asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="id">
                        <EditItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Name" SortExpression="username">
                        <EditItemTemplate>
                           <%-- <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("username") %>'></asp:TextBox>--%>
                            <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="username" DataValueField="username"></asp:DropDownList>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("username") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Date" SortExpression="r_date">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("r_date") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text='<%# Bind("r_date") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="From" SortExpression="from_time">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("from_time") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label4" runat="server" Text='<%# Bind("from_time") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="To" SortExpression="to_time">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("to_time") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label5" runat="server" Text='<%# Bind("to_time") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <FooterStyle BackColor="#CCCCCC" />
                <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
                <RowStyle BackColor="White" />
                <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                <SortedAscendingCellStyle BackColor="#F1F1F1" />
                <SortedAscendingHeaderStyle BackColor="#808080" />
                <SortedDescendingCellStyle BackColor="#CAC9C9" />
                <SortedDescendingHeaderStyle BackColor="#383838" />
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DBCS %>" DeleteCommand="DELETE FROM [roster] WHERE [id] = @id" InsertCommand="INSERT INTO [roster] ([username], [r_date], [from_time], [to_time]) VALUES (@username, @r_date, @from_time, @to_time)" SelectCommand="SELECT [id], [username], [r_date], [from_time], [to_time] FROM [roster]" UpdateCommand="UPDATE [roster] SET [username] = @username, [r_date] = @r_date, [from_time] = @from_time, [to_time] = @to_time WHERE [id] = @id">
                <DeleteParameters>
                    <asp:Parameter Name="id" Type="Int32" />
                </DeleteParameters>
                <InsertParameters>
                    <asp:Parameter Name="username" Type="String" />
                    <asp:Parameter DbType="Date" Name="r_date" />
                    <asp:Parameter Name="from_time" Type="String" />
                    <asp:Parameter Name="to_time" Type="String" />
                </InsertParameters>
                <UpdateParameters>
                    <asp:Parameter Name="username" Type="String" />
                    <asp:Parameter DbType="Date" Name="r_date" />
                    <asp:Parameter Name="from_time" Type="String" />
                    <asp:Parameter Name="to_time" Type="String" />
                    <asp:Parameter Name="id" Type="Int32" />
                </UpdateParameters>
            </asp:SqlDataSource>

            <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString='<%$ ConnectionStrings:DBCS %>' SelectCommand="SELECT [username] FROM [users]"></asp:SqlDataSource>

        </div>
    </asp:Content>
</code>```

答:
You need to send BACK the SelectedValue of your dropdownlist:

Use this: SelectedValue='<%# Bind("username")%>' as:

```<code><EditItemTemplate>
      <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2"
           DataTextField="username" DataValueField="username"
           SelectedValue='<%# Bind("username")%>'>
      </asp:DropDownList>
</EditItemTemplate>
</code>```

Body:
I have one gridview which is connected through SQL Data source from one table and I have enabled the EDIT and delete columns of gridview. When I'm Editing the value of row, a column is having DDL in Edit mode instead of textbox connected through another SQL datasource.

Once the page loads, after clicking the Edit Row of the Gridview, i'm selecting another value from dropdown and after clicking update it giving me error, can not insert null values into database.

<%@ Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="CreateRoster.aspx.cs" Inherits="E_Scheduler.CreateRoster" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <link href="CSS/Addroster.css" rel="stylesheet" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

        <asp:GridView ID="GridView1" runat="server" ShowFooter="True" AutoGenerateColumns="False" BackColor="#

    CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" DataKeyNames="id" DataSourceID="SqlDataSource1" ForeColor="Black">
                <Columns>
                    <asp:CommandField ShowEditButton="True" ShowDeleteButton="True"></asp:CommandField>
                    <asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="id">
                        <EditItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Name" SortExpression="username">
                        <EditItemTemplate>
                           <%-- <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("username") %>'></asp:TextBox>--%>
                            <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="username" DataValueField="username"></asp:DropDownList>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("username") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Date" SortExpression="r_date">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("r_date") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text='<%# Bind("r_date") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="From" SortExpression="from_time">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("from_time") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label4" runat="server" Text='<%# Bind("from_time") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="To" SortExpression="to_time">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("to_time") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label5" runat="server" Text='<%# Bind("to_time") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <FooterStyle BackColor="#CCCCCC" />
                <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
                <RowStyle BackColor="White" />
                <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                <SortedAscendingCellStyle BackColor="#F1F1F1" />
                <SortedAscendingHeaderStyle BackColor="#808080" />
                <SortedDescendingCellStyle BackColor="#CAC9C9" />
                <SortedDescendingHeaderStyle BackColor="#383838" />
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DBCS %>" DeleteCommand="DELETE FROM [roster] WHERE [id] = @id" InsertCommand="INSERT INTO [roster] ([username], [r_date], [from_time], [to_time]) VALUES (@username, @r_date, @from_time, @to_time)" SelectCommand="SELECT [id], [username], [r_date], [from_time], [to_time] FROM [roster]" UpdateCommand="UPDATE [roster] SET [username] = @username, [r_date] = @r_date, [from_time] = @from_time, [to_time] = @to_time WHERE [id] = @id">
                <DeleteParameters>
                    <asp:Parameter Name="id" Type="Int32" />
                </DeleteParameters>
                <InsertParameters>
                    <asp:Parameter Name="username" Type="String" />
                    <asp:Parameter DbType="Date" Name="r_date" />
                    <asp:Parameter Name="from_time" Type="String" />
                    <asp:Parameter Name="to_time" Type="String" />
                </InsertParameters>
                <UpdateParameters>
                    <asp:Parameter Name="username" Type="String" />
                    <asp:Parameter DbType="Date" Name="r_date" />
                    <asp:Parameter Name="from_time" Type="String" />
                    <asp:Parameter Name="to_time" Type="String" />
                    <asp:Parameter Name="id" Type="Int32" />
                </UpdateParameters>
            </asp:SqlDataSource>

            <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString='<%$ ConnectionStrings:DBCS %>' SelectCommand="SELECT [username] FROM [users]"></asp:SqlDataSource>

    </asp:Content>

Body:
You need to send BACK the SelectedValue of your dropdownlist:

Use this: SelectedValue='<%# Bind("username")%>' as:

<EditItemTemplate>
      <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2"
           DataTextField="username" DataValueField="username"
           SelectedValue='<%# Bind("username")%>'>
      </asp:DropDownList>
</EditItemTemplate>


问:
How to make Round Squre Image Asset Icon in adroid studio
Hi I am try to make Squricle or Round Squre Icon In image Asset but can't make .
Any one please help me</p>

答:
create shape like this and make round using corner radius</p>

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners
        android:bottomRightRadius="10dp"
        android:radius="40dp" />

          <!--<solid
        android:color="#FFFFFF" />-->

</shape>
</code>```

Body:
create shape like this and make round using corner radius

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners
        android:bottomRightRadius="10dp"
        android:radius="40dp" />

          <!--<solid
        android:color="#FFFFFF" />-->

</shape>


问:
showing div to show action error
How can I show a div with information whenever an exception occurs when executing my action?

Here is what I have so far:

```<code><div id="dvErrorMsg">
    <a href="#" class="close">[x]</a>
    <p>
        <label id="errorMessage">
        </label>
    </p>
</div>

<script type="text/javascript">
        $(function () {

            $("#click_here").click(function (event) {
                event.preventDefault();
                $("#dvErrorMsg").slideToggle();
            });

            $("#dvErrorMsg a").click(function (event) {
                event.preventDefault();
                $("#dvErrorMsg").slideUp();
            });
        });
</script>
</code>```

And I have this action in my controller:

```<code>public ActionResult Validatecall()
{
    //if any exeption happen show div with the custom error
}
</code>```

How can I catch any exception and send the message back in the AJAX response?

答:
```<code>try {
  ... whatever
} catch (Exception $e) {
  $('errorMessage').html($e);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: showing div to show action error

Body:
How can I show a div with information whenever an exception occurs when executing my action?

Here is what I have so far:

    [x]

And I have this action in my controller:

public ActionResult Validatecall()
{
    //if any exeption happen show div with the custom error
}

How can I catch any exception and send the message back in the AJAX response?


问:
fetching data from Instagram api for android
Im trying to work on an android application which simply retrieves pictures from the api. Im trying to use retrofit but im consufed how to use it. also I dont understand how to get the access tokens? Do i need the user to login? Cant I simply get images from instagram not particularly related to any user?

I tried something like

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mButton = (Button) findViewById(R.id.button);

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri uri = Uri.parse("https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code"); // missing 'http://' will cause crashed
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    });
</code>```

this leads me to a login page and then it promts me to put in user details and after that gives me some sort of authentication error.

I cannot seem to understand the insta documentation

答:
That what I did to do the login:

Just load the web view after the user clicked OK and then extract the code authorization:

```<code>webView?.settings?.javaScriptEnabled = true
        webView?.loadUrl(AuthenticationPresenter.urlAuthentication())
        webView?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String): Boolean {
                if (url.contains("code=")) {
                    presenter.extractAuthorizationCode(url)
                    return true
                }
                return false
            }
        }

fun urlAuthentication() = "https://api.instagram.com/oauth/authorize/" +
                "?client_id=$CLIENT_ID" +
                "&redirect_uri=$REQUEST_URL_CALLBACK" +
                "&scope=${USER_PROFILE},${USER_MEDIA}" +
                "&response_type=$RESPONSE_TYPE"
</code>```

Getting the code authorization from the URL:

```<code>override fun extractAuthorizationCode(url: String) {
        val uri: Uri = Uri.parse(url)
        val code = uri.getQueryParameter("code")
        if (code != null)
            view?.authorizationCodeSuccess(code)
        else
            view?.authorizationCodeFail()
    }
</code>```

After getting the code authorization, you should be able to get the access token.

Here's an example using Retrofit2:

```<code>interface AuthenticationApiHelper {

    @FormUrlEncoded
    @POST("/oauth/access_token")
    suspend fun getCredentials(
        @Field("code") code: String,
        @Field("client_id") client: String = CLIENT_ID,
        @Field("client_secret") secret: String = CLIENT_SECRET,
        @Field("grant_type") type: String = GRANT_TYPE,
        @Field("redirect_uri") uri: String = REQUEST_URL_CALLBACK
    ): Credentials
}
</code>```

Body:
Im trying to work on an android application which simply retrieves pictures from the api. Im trying to use retrofit but im consufed how to use it. also I dont understand how to get the access tokens? Do i need the user to login? Cant I simply get images from instagram not particularly related to any user?

I tried something like

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mButton = (Button) findViewById(R.id.button);

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri uri = Uri.parse("https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code"); // missing 'http://' will cause crashed
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    });

this leads me to a login page and then it promts me to put in user details and after that gives me some sort of authentication error.

I cannot seem to understand the insta documentation

Body:
That what I did to do the login:

Just load the web view after the user clicked OK and then extract the code authorization:

webView?.settings?.javaScriptEnabled = true
        webView?.loadUrl(AuthenticationPresenter.urlAuthentication())
        webView?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String): Boolean {
                if (url.contains("code=")) {
                    presenter.extractAuthorizationCode(url)
                    return true
                }
                return false
            }
        }

fun urlAuthentication() = "https://api.instagram.com/oauth/authorize/" +
                "?client_id=$CLIENT_ID" +
                "&redirect_uri=$REQUEST_URL_CALLBACK" +
                "&scope=${USER_PROFILE},${USER_MEDIA}" +
                "&response_type=$RESPONSE_TYPE"

Getting the code authorization from the URL:

override fun extractAuthorizationCode(url: String) {
        val uri: Uri = Uri.parse(url)
        val code = uri.getQueryParameter("code")
        if (code != null)
            view?.authorizationCodeSuccess(code)
        else
            view?.authorizationCodeFail()
    }

After getting the code authorization, you should be able to get the access token.

Here's an example using Retrofit2:

interface AuthenticationApiHelper {

    @FormUrlEncoded
    @POST("/oauth/access_token")
    suspend fun getCredentials(
        @Field("code") code: String,
        @Field("client_id") client: String = CLIENT_ID,
        @Field("client_secret") secret: String = CLIENT_SECRET,
        @Field("grant_type") type: String = GRANT_TYPE,
        @Field("redirect_uri") uri: String = REQUEST_URL_CALLBACK
    ): Credentials
}


问:
What's the common practice of gitignore for aspnet core project
I know it depends on the project but i want to learn is there a common practice for typical asp.net core project(such as ignoring node_modules).

答:
as of 2020, you should be using</p>

```<code>dotnet new gitignore
</code>```

Body:
as of 2020, you should be using

dotnet new gitignore


问:
Tricky situation calling variable with ÅÄÖ and & afterwards
I have these tricky problems.

On my site I allow registrations with the characters åäö in them, and I have friendly URLs linking to their profile, so lets say an URL looks like this:

example.com/profile/åäöismyname/

and the userfriendly variable is $_GET['vanlig'].

Now, this is called example.com/profile/åäömyname&favorisera

$_GET['vanlig'] is now called as åäömyname&favorisera instead of åäömyname, and &favorisera is not called.

This works perfectly fine as long as I don't have åäö in the $_GET variable, &favorisera is then called properly.

Any suggestions to this? Changing their friendly names is not an option. Since this may cause duplicate names in the DB.

I'm using nginx as a webserver for friendly URLs.

EDIT:

i tried this

```<code>$userid = urlencode($userid);

<div class="privat" onclick="window.location = '/profil/<?=$userid?>&favorisera'" style="cursor:pointer;" title=""></div>
</code>```

without any success, the linking shows ( as an actual example from the source code ) :

```<code><div class="privat" onclick="window.location = '/profil/k%C3%A5taelin&favorisera'" style="cursor:pointer;" title=""></div>
</code>```

When clicked, i return a var dump of $_GET['vanlig'], which results in string(19) "kåtaelin&favorisera" anyway.

答: The ampersand is a special character signifying a new variable, so try using urlencode() on your strings for the links, and then urldecode() when you manipulate it in your page or database.</p>

Body:
I have these tricky problems.

On my site I allow registrations with the characters åäö in them, and I have friendly URLs linking to their profile, so lets say an URL looks like this:

example.com/profile/åäöismyname/

and the userfriendly variable is $_GET['vanlig'].

Now, this is called example.com/profile/åäömyname&favorisera

$_GET['vanlig'] is now called as åäömyname&favorisera instead of åäömyname, and &favorisera is not called.

This works perfectly fine as long as I don't have åäö in the $_GET variable, &favorisera is then called properly.

Any suggestions to this? Changing their friendly names is not an option. Since this may cause duplicate names in the DB.

I'm using nginx as a webserver for friendly URLs.

EDIT:

i tried this

$userid = urlencode($userid);

<div class="privat" onclick="window.location = '/profil/<?=$userid?>&favorisera'" style="cursor:pointer;" title="">

without any success, the linking shows ( as an actual example from the source code ) :

When clicked, i return a var dump of $_GET['vanlig'], which results in string(19) "kåtaelin&favorisera" anyway.


问:
Java generic type issue
Consider the following simplified example:

```<code>package com.test;

class B<S> {
    B(Class<S> clazz) {}
}

class A<T> {
    class SubB extends B<SubB> {
        SubB() {
            super(SubB.class);
        }
    }
}
</code>```

Although IntelliJ is not showing any error (as it usually does when compile errors exist), the actual compilation when starting the program ends with error located in super(SubB.class);:

Error:(8, 23) java: incompatible types: java.lang.Class<com.test.A.SubB> cannot be converted to java.lang.Class<com.test.A<T>.SubB>

I am curious, why is this happening? And how could I solve it?

Compilation is done with AdoptOpenJDK 11.

答:
In generics the inheritance is not as we usually know, i.e
lets take an example
class ArrayList<String> is not a subclass of List.
Whereas List<String> is not same as List.

Also in generics you will not generally get a compilation error easily since the Generic types are been transformed to their raw types during the compilation.

Hence we need to cast as mentioned by @JohannesKuhn.

Title: Java generic type issue

Body:
Consider the following simplified example:

package com.test;

class B<S> {
    B(Class<S> clazz) {}
}

class A<T> {
    class SubB extends B<SubB> {
        SubB() {
            super(SubB.class);
        }
    }
}

Although IntelliJ is not showing any error (as it usually does when compile errors exist), the actual compilation when starting the program ends with error located in super(SubB.class);:

Error:(8, 23) java: incompatible types: java.lang.Class<com.test.A.SubB> cannot be converted to java.lang.Class<com.test.A<T>.SubB>

I am curious, why is this happening? And how could I solve it?

Compilation is done with AdoptOpenJDK 11.


问:
PHP global variable shared between two files
I have two different files in the same folder, the first one is called "form.php" the second one is called "add.php", I can't get the value of the global variable in "form.php"

"form.php"

```<code><?php
include("add.php");
global $Resultat;
echo $Resultat;
?>
</code>```

"add.php"

```<code><?php
global $Resultat;
if (isset($_POST["submit"])) {
    if (empty($_POST["val_1"]) || empty($_POST["val_2"])) {
        header("Location: form.php?FillTheForm");
        exit();
    } else {
        $Resultat=$_POST["val_1"]+$_POST["val_2"];
        echo "$Resultat"; //this works if I don't use header (the next instruction).
        header("Location: form.php"); // I want to redirect and still echo the value in "form.php".
    }
}
</code>```

If I don't use the header in the else statement it echos the value in "add.php" but i want to redirect to "form.php" and echo it there.

答:
You said that you want to redirect to "form.php" and echo it there.

echo ' window.location = "add.php" ';

Do this instead of INCLUDE.

Body:
I have two different files in the same folder, the first one is called "form.php" the second one is called "add.php", I can't get the value of the global variable in "form.php"

"form.php"

<?php
include("add.php");
global $Resultat;
echo $Resultat;
?>

"add.php"

<?php
global $Resultat;
if (isset($_POST["submit"])) {
    if (empty($_POST["val_1"]) || empty($_POST["val_2"])) {
        header("Location: form.php?FillTheForm");
        exit();
    } else {
        $Resultat=$_POST["val_1"]+$_POST["val_2"];
        echo "$Resultat"; //this works if I don't use header (the next instruction).
        header("Location: form.php"); // I want to redirect and still echo the value in "form.php".
    }
}

If I don't use the header in the else statement it echos the value in "add.php" but i want to redirect to "form.php" and echo it there.


问:
Can glReadPixels be used to read layers from GL_TEXTURE_3D?
I'm trying to read a 3D texture I rendered using an FBO. This texture is so large that glGetTexImage results in GL_OUT_OF_MEMORY error due to failure of nvidia driver to allocate memory for intermediate storage* (needed, I suppose, to avoid changing destination buffer in case of error).

So I then thought of getting this texture layer by layer, using glReadPixels after I render each layer. But glReadPixels doesn't have layer index as a parameter. The only place where it actually appears as something that directs I/O to the particular layer is gl_Layer output in the geometry shader. And that is for the writing stage, not reading.

As I tried simply doing the calls to glReadPixels anyway after I render each layer, I only got the texels for layer 0. So glReadPixels at least doesn't fail to get something.

But the question is: can I get arbitrary layer of a 3D texture using glReadPixels? And if not, what should I use instead, given the above described memory constraints? Do I have to sample the layer from 3D texture in a shader to render the result to a 2D texture, and read this 2D texture afterwards?

*It's not a guess, I've actually tracked it down to a failing malloc call (with the size of the texture as argument) from within the nvidia driver's shared library.

答:
Yes, glReadPixels can read other slices from the 3D texture. One just has to use glFramebufferTextureLayer to attach the correct current slice to the FBO — instead of attaching the full 3D texture as the color attachment. Here's the replacement code for glGetTexImage (a special FBO for this, fboForTextureSaving, should be generated beforehand):

```<code>GLint origReadFramebuffer=0, origDrawFramebuffer=0;
gl.glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &origReadFramebuffer);
gl.glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &origDrawFramebuffer);
gl.glBindFramebuffer(GL_FRAMEBUFFER, fboForTextureSaving);
for(int layer=0; layer<depth; ++layer)
{
    gl.glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                 texture, 0, layer);
    checkFramebufferStatus("framebuffer for saving textures");
    gl.glReadPixels(0,0,w,h,GL_RGBA,GL_FLOAT, subpixels+layer*w*h*4);
}
gl.glBindFramebuffer(GL_READ_FRAMEBUFFER, origReadFramebuffer);
gl.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, origDrawFramebuffer);
</code>```

Anyway, this is not a long-term solution to the problem. The first reason for GL_OUT_OF_MEMORY errors with large textures is actually not lack of RAM or VRAM. It's subtler: each texture allocated on GPU is mapped to the process' address space (at least on Linux/nvidia). So if your process doesn't malloc even half of the RAM available to it, its address space may be already used by these large mappings. Add to this a bit of memory fragmentation, and you get either GL_OUT_OF_MEMORY, or malloc failure, or std::bad_alloc somewhere even earlier than expected.

The proper long-term solution is to embrace the 64-bit reality and compile your app as 64-bit code. This is what I ended up doing, ditching all this layer-by-layer kludge and simplifying the code quite a bit.

Body:
Yes, glReadPixels can read other slices from the 3D texture. One just has to use glFramebufferTextureLayer to attach the correct current slice to the FBO — instead of attaching the full 3D texture as the color attachment. Here's the replacement code for glGetTexImage (a special FBO for this, fboForTextureSaving, should be generated beforehand):

GLint origReadFramebuffer=0, origDrawFramebuffer=0;
gl.glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &origReadFramebuffer);
gl.glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &origDrawFramebuffer);
gl.glBindFramebuffer(GL_FRAMEBUFFER, fboForTextureSaving);
for(int layer=0; layer<depth; ++layer)
{
    gl.glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                 texture, 0, layer);
    checkFramebufferStatus("framebuffer for saving textures");
    gl.glReadPixels(0,0,w,h,GL_RGBA,GL_FLOAT, subpixels+layer*w*h*4);
}
gl.glBindFramebuffer(GL_READ_FRAMEBUFFER, origReadFramebuffer);
gl.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, origDrawFramebuffer);

Anyway, this is not a long-term solution to the problem. The first reason for GL_OUT_OF_MEMORY errors with large textures is actually not lack of RAM or VRAM. It's subtler: each texture allocated on GPU is mapped to the process' address space (at least on Linux/nvidia). So if your process doesn't malloc even half of the RAM available to it, its address space may be already used by these large mappings. Add to this a bit of memory fragmentation, and you get either GL_OUT_OF_MEMORY, or malloc failure, or std::bad_alloc somewhere even earlier than expected.

The proper long-term solution is to embrace the 64-bit reality and compile your app as 64-bit code. This is what I ended up doing, ditching all this layer-by-layer kludge and simplifying the code quite a bit.


问:
Inherit and rename the table from default setting
I would like to rename the default table comes from Django.
Meta does copy the table but the columns are totally difference
How can i over come with it?

答:
The reason this happens is because Session is a concrete model. What here happens is that you specify you want to inherit the Session table. This is implemented in the SQL layer by making a new table that contains, besides the extra fields, a OneToOneField to the parent table, and furthermore this acts as a primary key as well. For more information on how Django handles model inheritance, see the section on Multi-table inheritance in the documentation.

If you want to implement your own session model, you should inherit from the AbstractBaseSession model [Django-doc]. This is an abstract model that has as fields sesion_key, session_data and expire_date. You can then override or "monkey patch" the get_model_class of the SessionStore.


问:
jQuery can't remove class from material bootstrap
I'm using material bootstrap. And trying to remove waves-effect waves-light classes. But it does not work:

```<code>$("nav a").removeClass("waves-effect waves-light");
</code>```

While if I do add class;

```<code>$("nav a").addClass("testing"); // it works!
</code>```

It works if use setTimeout:

```<code>setTimeout(function(){
  $("nav a").removeClass("waves-effect waves-light");
},100)
</code>```

But I'm not sure why is this required? I have added script after mdb script.

```<code><script type='text/javascript' src='http://localhost/site/js/jquery.min.js'></script>
<script type='text/javascript' src='http://localhost/site/js/popper.min.js'></script>
<script type='text/javascript' src='http://localhost/site/js/bootstrap.min.js'></script>
<script type='text/javascript' src='http://localhost/site/js/mdb.min.js'></script>
<script type='text/javascript' src='http://localhost/site/js/custom-script.js'></script>
</code>```

答:
addClass work because you trying to add a new class to element, but removeClass not, because waves-effect waves-light class add after you. As you edited your question, you used setTimeOut but it's not a stable solution, you are using a library mdb, it can load after 100ms, or even after 1000, you should use setInterval and clear when it removed like below example, this is a safe solution, but I rather to remove this class from source code.

var rm = setInterval(remover, 100);

function remover() {
  $("nav a").removeClass("waves-effect waves-light");
}

function StopInterval() {
  if (!$("nav a").hasClass('.waves-effect.waves-light')) {
    clearInterval(rm);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  Blah
</nav></code>```

Body:
I'm using material bootstrap. And trying to remove waves-effect waves-light classes. But it does not work:

$("nav a").removeClass("waves-effect waves-light");

While if I do add class;

$("nav a").addClass("testing"); // it works!

It works if use setTimeout:

setTimeout(function(){
  $("nav a").removeClass("waves-effect waves-light");
},100)

But I'm not sure why is this required? I have added script after mdb script.

Body:
addClass work because you trying to add a new class to element, but removeClass not, because waves-effect waves-light class add after you. As you edited your question, you used setTimeOut but it's not a stable solution, you are using a library mdb, it can load after 100ms, or even after 1000, you should use setInterval and clear when it removed like below example, this is a safe solution, but I rather to remove this class from source code.

var rm = setInterval(remover, 100);

function remover() {
  $("nav a").removeClass("waves-effect waves-light");
}

function StopInterval() {
  if (!$("nav a").hasClass('.waves-effect.waves-light')) {
    clearInterval(rm);
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <a class="waves-effect waves-light">Blah</a>
</nav>


问:
How can I add item number on the cart icon at at appBar icon in flutter? And how can I make it animate adding new item?
I want to add item numbers on the cart icon in flutter like this in picture, and want to animate while adding new item to cart. My cart icon is in appBar.

答:
You can use badges package.

Example:

```<code>Chip(
  backgroundColor: Colors.deepPurple,
  padding: EdgeInsets.all(0),
  label: Text('BADGE', style: TextStyle(color: Colors.white)),
),
Badge(
  badgeColor: Colors.deepPurple,
  shape: BadgeShape.square,
  borderRadius: 20,
  toAnimate: false,
  badgeContent:
      Text('BADGE', style: TextStyle(color: Colors.white)),
),
</code>```

Body:
You can use badges package.

Example:

Chip(
  backgroundColor: Colors.deepPurple,
  padding: EdgeInsets.all(0),
  label: Text('BADGE', style: TextStyle(color: Colors.white)),
),
Badge(
  badgeColor: Colors.deepPurple,
  shape: BadgeShape.square,
  borderRadius: 20,
  toAnimate: false,
  badgeContent:
      Text('BADGE', style: TextStyle(color: Colors.white)),
),


问:
Is there any C function that can evalute a string expression defined in the standard library?
I am looking for a function that can evaluate a string expression into an integer, like f.e.:

```<code>10/2+4*3-(12+5); //Equals 0
</code>```

into an object of type int with the value of 0.

A function for complex operation would be preferable even though that's not the need of the hour:

```<code>2^(1/2)-99
</code>```

Is there any such definition defined in the standard C library (C89, C90, if it's compiled)?

Is there any non-standard library which has such an function?

The more the characters the expression supports the better it is.

But even basic operation like +,-,*,/,() would do.

答:
There is no function in the Standard C library to evaluation arithmetic expressions. Here is a quick and dirty implementation of an evald function for double result. It supports the 5 classical binary operations +, -, *, /, % and the exponentiation with ^, handles any depth of parentheses but needs more work for unary + and -.

It is easy to convert to integer only arithmetic.

Here is the code:

#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

double evald(const char *s, char **endp) {
    struct operand {
        double val;
        int op, prec;
    } stack[4], *sp, x;
    char *p;

    for (sp = stack;;) {
        if (*s == '(') {
            x.val = evald(s + 1, &p);
            s = p;
            if (*s == ')')
                s++;
        } else {
            x.val = strtod(s, &p);
            s = p;
        }
        while (isspace((unsigned char)*s))
            s++;
        switch (x.op = *s++) {
        case '^': x.prec = 3; break;
        case '*':
        case '/':
        case '%': x.prec = 2; break;
        case '+':
        case '-': x.prec = 1; break;
        default:  x.prec = 0; x.op = 0; s--; break;
        }
        while (sp > stack && x.prec <= sp[-1].prec) {
            switch ((--sp)->op) {
            case '^': x.val = pow(sp->val, x.val); break;
            case '*': x.val = sp->val * x.val; break;
            case '/': x.val = sp->val / x.val; break;
            case '%': x.val = fmod(sp->val, x.val); break;
            case '+': x.val = sp->val + x.val; break;
            case '-': x.val = sp->val - x.val; break;
            }
        }
        if (!x.op) break;
        *sp++ = x;
    }
    if (endp) *endp = (char *)s;
    return x.val;
}

int main(int argc, char *argv[]) {
    if (argc > 1) {
        for (int i = 1; i < argc; i++) {
            printf("%s -> %.17g\n", argv[i], evald(argv[i], NULL));
        }
    } else {
        char buf[100];
        for (;;) {
            printf("eval> ");
            fflush(stdout);
            if (!fgets(buf, sizeof buf, stdin) || (buf[0] == 'q' && buf[1] == '\n'))
                break;
            printf(" -> %.17g\n", evald(buf, NULL));
        }
    }
    return 0;
}
```

Body:
I am looking for a function that can evaluate a string expression into an integer, like f.e.:

10/2+4*3-(12+5); //Equals 0

into an object of type int with the value of 0.

A function for complex operation would be preferable even though that's not the need of the hour:

2^(1/2)-99

Is there any such definition defined in the standard C library (C89, C90, if it's compiled)?

Is there any non-standard library which has such an function?

The more the characters the expression supports the better it is.

But even basic operation like +,-,*,/,() would do.


问:
How to join multiple tables to one table with lambda expression?
I have 3 Table and Model like below

Table 1: Student

```<code>+----+-------+---------+
| ID | Name  | Subject |
+----+-------+---------+
| 1  | Alex  | 2       |
+----+-------+---------+
| 2  | Peter | 1       |
+----+-------+---------+
| 3  | Thomas| null    |
+----+-------+---------+

public class Student {

    public int ID {get; set;}
    public string Name {get; set;}
    public int Subject {get; set;}
}
</code>```

Table 2: Subject

```<code>+----+---------+---------+
| ID | Subject | Teacher |
+----+---------+---------+
| 1  | Math    | 5       |
+----+---------+---------+
| 2  | History | 6       |
+----+---------+---------+

public class Subject {

    public int ID {get; set;}
    public string Subject {get; set;}
    public int Teacher {get; set;}
}
</code>```

Table 3: Teacher

```<code>+----+---------+---------------+
| ID | TeacherName | Email     |
+----+-------------+-----------+
| 6  | John        | null      |
+----+-------------+-----------+
| 2  | Anna        | anna@aa.c |
+----+-------------+-----------+

public class Teacher {

    public int ID {get; set;}
    public string TeacherName {get; set;}
    public string Email {get; set;}
}
</code>```

I create a new model like this

```<code>public class newModel{

    public Student studentList;
    public Teacher teacherList;
    public Subject subjectList;
}
</code>```

How can I merge 3 table (model) above to a new table (model) with lambda expression?

It's mean I want join Table 1 to Table 2 by SubjectID.
Then, new Table created by Table 1 and Table 2 join with Table 3 by Teacher ID. But keep every Things in Table 1 in new.

It's look like

```<code>List<newModel> finalList = new List<newModel>();
finalList = db.Student.Join( .... )
</code>```

and the final result of finalList like below:

```<code>+----+--------+---------+-------------+-----------+-------------+-------+
| ID | Name   | Subject | SubjectName | TeacherID | Teachername | Email |
+----+--------+---------+-------------+-----------+-------------+-------+
| 1  | Alex   | 2       | History     | 6         | John        | null  |
+----+--------+---------+-------------+-----------+-------------+-------+
| 2  | Perter | 1       | Math        |           |             |       |
+----+--------+---------+-------------+-----------+-------------+-------+
| 3  | Thomas | null    |             |           |             |       |
+----+--------+---------+-------------+-----------+-------------+-------+
</code>```

答:
If you have navigation properties then you can use Include() otherwise you can do join manually like below:

```<code>var result = (from student in db.Students
             join subject in db.Subjects on student.Subject equals subject.ID
             join teacher in db.Teachers on subject.Teacher equals teacher.ID
             where student.ID = 1
             select new newModel()
             {
                 studentList = student,
                 teacherList = teacher,
                 subejctList = subject
             }).ToList();
</code>```

Body:
I have 3 Table and Model like below

Table 1: Student

+----+-------+---------+
| ID | Name  | Subject |
+----+-------+---------+
| 1  | Alex  | 2       |
+----+-------+---------+
| 2  | Peter | 1       |
+----+-------+---------+
| 3  | Thomas| null    |
+----+-------+---------+

public class Student {

    public int ID {get; set;}
    public string Name {get; set;}
    public int Subject {get; set;}
}

Table 2: Subject

+----+---------+---------+
| ID | Subject | Teacher |
+----+---------+---------+
| 1  | Math    | 5       |
+----+---------+---------+
| 2  | History | 6       |
+----+---------+---------+

public class Subject {

    public int ID {get; set;}
    public string Subject {get; set;}
    public int Teacher {get; set;}
}

Table 3: Teacher

+----+---------+---------------+
| ID | TeacherName | Email     |
+----+-------------+-----------+
| 6  | John        | null      |
+----+-------------+-----------+
| 2  | Anna        | anna@aa.c |
+----+-------------+-----------+

public class Teacher {

    public int ID {get; set;}
    public string TeacherName {get; set;}
    public string Email {get; set;}
}

I create a new model like this

public class newModel{

    public Student studentList;
    public Teacher teacherList;
    public Subject subjectList;
}

How can I merge 3 table (model) above to a new table (model) with lambda expression?

It's mean I want join Table 1 to Table 2 by SubjectID.
Then, new Table created by Table 1 and Table 2 join with Table 3 by Teacher ID. But keep every Things in Table 1 in new.

It's look like

List<newModel> finalList = new List<newModel>();
finalList = db.Student.Join( .... )

and the final result of finalList like below:

+----+--------+---------+-------------+-----------+-------------+-------+
| ID | Name   | Subject | SubjectName | TeacherID | Teachername | Email |
+----+--------+---------+-------------+-----------+-------------+-------+
| 1  | Alex   | 2       | History     | 6         | John        | null  |
+----+--------+---------+-------------+-----------+-------------+-------+
| 2  | Perter | 1       | Math        |           |             |       |
+----+--------+---------+-------------+-----------+-------------+-------+
| 3  | Thomas | null    |             |           |             |       |
+----+--------+---------+-------------+-----------+-------------+-------+

Body:
If you have navigation properties then you can use Include() otherwise you can do join manually like below:

var result = (from student in db.Students
             join subject in db.Subjects on student.Subject equals subject.ID
             join teacher in db.Teachers on subject.Teacher equals teacher.ID
             where student.ID = 1
             select new newModel()
             {
                 studentList = student,
                 teacherList = teacher,
                 subejctList = subject
             }).ToList();


答:
The reason for this behavior is a bit complicated. Consider java.util.List.class, which has the type Class<java.util.List>, not Class<java.util.List<?>>. This is a limitation of the class literal.

In your example, SubB.class has the type Class<com.test.A.SubB>, again with the raw type of SubB. But the constructor expects some type of Class<com.test.A<T>.SubB>.

That's why we need to cast the literal to it's desired type:

```<code>super((Class<SubB>) (Class<?>) SubB.class);
</code>```

This will produce a warning, but a quick examination will show that there is nothing to worry about.

Title: Java generic type issue

Body:
The reason for this behavior is a bit complicated. Consider java.util.List.class, which has the type Class<java.util.List>, not Class<java.util.List<?>>. This is a limitation of the class literal.

In your example, SubB.class has the type Class<com.test.A.SubB>, again with the raw type of SubB. But the constructor expects some type of Class<com.test.A<T>.SubB>.

That's why we need to cast the literal to it's desired type:

super((Class<SubB>) (Class<?>) SubB.class);

This will produce a warning, but a quick examination will show that there is nothing to worry about.


问:
My loop isn't filling my matrix with the data I ask
I'm trying to fill a matrix with the results of sum I included in a loop, but every time I run the loop, the matrix is shown filled with 0s instead of the values that should be filling it from the loop. This is the code:

```<code>cada_aerolinea<-unique(aerolineas)
resultados<-matrix(0, length(cada_aerolinea), 1)
row.names(resultados)<-cada_aerolinea
for (i in length(cada_aerolinea)) {
  resultados[i]<-sum(fatalities[aerolineas==cada_aerolinea[i]])
  print(resultados[i])
}
</code>```

When I run the full code, the line "print(resultados[i])" only gives back one number, "41", which I don't know where it comes from, and when I just run "resultados", r just shows the matrix filled with 0s. Anyone knows what am I doing wrong?

答:
```<code>for (i in length(cada_aerolinea)) {
</code>```

should be

```<code>for (i in 1:length(cada_aerolinea)) {
</code>```

I'm doing that mistake all the time ;). Also, I think you can replace your loop by:

```<code>resutados = tapply(facilities, cada_aerolinea, SUM)
</code>```

Body:
I'm trying to fill a matrix with the results of sum I included in a loop, but every time I run the loop, the matrix is shown filled with 0s instead of the values that should be filling it from the loop. This is the code:

cada_aerolinea<-unique(aerolineas)
resultados<-matrix(0, length(cada_aerolinea), 1)
row.names(resultados)<-cada_aerolinea
for (i in length(cada_aerolinea)) {
  resultados[i]<-sum(fatalities[aerolineas==cada_aerolinea[i]])
  print(resultados[i])
}

When I run the full code, the line "print(resultados[i])" only gives back one number, "41", which I don't know where it comes from, and when I just run "resultados", r just shows the matrix filled with 0s. Anyone knows what am I doing wrong?

Body:
for (i in length(cada_aerolinea)) {

should be

for (i in 1:length(cada_aerolinea)) {

I'm doing that mistake all the time ;). Also, I think you can replace your loop by:

resutados = tapply(facilities, cada_aerolinea, SUM)


答:
At first, update your models as below:

Student Model:

```<code>public class Student
{

    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    [ForeignKey(nameof(Subject))]
    public int? SubjectId { get; set; }
    public virtual Subject Subject { get; set; } //Navigation Property
}
</code>```

Subject Model:

```<code>public class Subject
{
    [Key]
    public int Id { get; set; }
    public string SubjectName { get; set; }

    [ForeignKey(nameof(Teacher))]
    public int TeacherId { get; set; }
    public virtual Teacher Teacher { get; set; } //Navigation Property
}
</code>```

And the Teacher Model:

```<code>    public class Teacher
    {
        [Key]
        public int Id { get; set; }
        public string TeacherName { get; set; }
        public string Email { get; set; }
    }
</code>```

Then Add-Migration and update-Database. After All of these change your tables are connected together and with the below query, you can fetch data of these 3 tables.

```<code>var newModel = dbcontext.Students
                .Include(i => i.Subject)
                .ThenInclude(i => i.Teacher)
                .ToList();
</code>```

now, base on your data, the result of newModel.First().Subject.Teacher.TeacherName is John. and as a conclusion, when you fetch these data you can map these data to another model or do anything that you want.

feel free to ask question. good luck.

Title: How to join multiple tables to one table with lambda expression?

Body:
At first, update your models as below:

Student Model:

public class Student
{

    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    [ForeignKey(nameof(Subject))]
    public int? SubjectId { get; set; }
    public virtual Subject Subject { get; set; } //Navigation Property
}

Subject Model:

public class Subject
{
    [Key]
    public int Id { get; set; }
    public string SubjectName { get; set; }

    [ForeignKey(nameof(Teacher))]
    public int TeacherId { get; set; }
    public virtual Teacher Teacher { get; set; } //Navigation Property
}

And the Teacher Model:

    public class Teacher
    {
        [Key]
        public int Id { get; set; }
        public string TeacherName { get; set; }
        public string Email { get; set; }
    }

Then Add-Migration and update-Database. After All of these change your tables are connected together and with the below query, you can fetch data of these 3 tables.

var newModel = dbcontext.Students
                .Include(i => i.Subject)
                .ThenInclude(i => i.Teacher)
                .ToList();

now, base on your data, the result of newModel.First().Subject.Teacher.TeacherName is John. and as a conclusion, when you fetch these data you can map these data to another model or do anything that you want.

feel free to ask question. good luck.