text:
Q: Thread destroy never gets executed Download the source code with compiled executable (221 KB (226,925 bytes)): http://www.eyeclaxton.com/download/delphi/skeleton.zip
Why doesn't the Destroy destructor get called if I close the application (click the X button) before the thread has terminated? FastMM4 reports a memory leak with FPauseEvent event.
How should i destroy thread? If someone closes the application before the thread finishes.
unit SkeletonThread;

interface

uses
  Windows, Classes, SysUtils, SyncObjs;

type
  TOnInitialize = procedure(Sender: TObject; const AMaxValue: Integer) of object;
  TOnBegin = procedure(Sender: TObject) of object;
  TOnProgress = procedure(Sender: TObject; const APosition: Integer) of object;
  TOnPause = procedure(Sender: TObject; const APaused: Boolean) of object;
  TOnFinish = procedure(Sender: TObject) of object;
  TOnFinalize = procedure(Sender: TObject) of object;

  TMasterThread = class(TThread)
  private
    { Private declarations }
    FPaused: Boolean;
    FPosition: Integer;
    FMaxValue: Integer;
    FOnBegin: TOnBegin;
    FOnProgress: TOnProgress;
    FOnFinish: TOnFinish;
    FOnInitialize: TOnInitialize;
    FOnFinalize: TOnFinalize;
    FPauseEvent: TEvent;
    FOnPause: TOnPause;
    procedure BeginEvent();
    procedure ProgressEvent();
    procedure FinishEvent();
    procedure InitializeEvent();
    procedure FinalizeEvent();
    procedure PauseEvent();
    procedure CheckForPause();
  protected
    { Protected declarations }
    procedure DoInitializeEvent(const AMaxValue: Integer); virtual;
    procedure DoBeginEvent(); virtual;
    procedure DoProgress(const APosition: Integer); virtual;
    procedure DoPauseEvent(const APaused: Boolean); virtual;
    procedure DoFinishEvent(); virtual;
    procedure DoFinalizeEvent(); virtual;
  public
    { Public declarations }
    constructor Create(const CreateSuspended: Boolean; const theValue: Integer);
    destructor Destroy(); override;
    procedure Pause();
    procedure Unpause();
  published
    { Published declarations }
    property IsPaused: Boolean read FPaused write FPaused default False;
    property OnInitialize: TOnInitialize read FOnInitialize write FOnInitialize default nil;
    property OnBegin: TOnBegin read FOnBegin write FOnBegin default nil;
    property OnProgress: TOnProgress read FOnProgress write FOnProgress default nil;
    property OnPause: TOnPause read FOnPause write FOnPause default nil;
    property OnFinish: TOnFinish read FOnFinish write FOnFinish default nil;
    property OnFinalize: TOnFinalize read FOnFinalize write FOnFinalize default nil;
  end;

  TSkeletonThread = class(TMasterThread)
  private
    { Private declarations }
    procedure DoExecute(const theValue: Integer);
  protected
    { Protected declarations }
    procedure Execute(); override;
  public
    { Public declarations }
  published
    { Published declarations }
  end;

implementation

{ TMasterThread }
constructor TMasterThread.Create(const CreateSuspended: Boolean; const theValue: Integer);
begin
  inherited Create(CreateSuspended);
  Self.FreeOnTerminate := True;

  Self.FPosition := 0;
  Self.FMaxValue := theValue;
  Self.FPaused := False;
  Self.FPauseEvent := TEvent.Create(nil, True, True, '');
end;

destructor TMasterThread.Destroy();
begin
  FreeAndNil(FPauseEvent);
  if (Pointer(FPauseEvent) <> nil) then Pointer(FPauseEvent) := nil;
  inherited Destroy();
end;

procedure TMasterThread.DoBeginEvent();
begin
  if Assigned(Self.FOnBegin) then Self.FOnBegin(Self);
end;

procedure TMasterThread.BeginEvent();
begin
  Self.DoBeginEvent();
end;

procedure TMasterThread.DoProgress(const APosition: Integer);
begin
  if Assigned(Self.FOnProgress) then Self.FOnProgress(Self, APosition);
end;

procedure TMasterThread.ProgressEvent();
begin
  Self.DoProgress(Self.FPosition);
end;

procedure TMasterThread.DoFinishEvent();
begin
  if Assigned(Self.FOnFinish) then Self.FOnFinish(Self);
end;

procedure TMasterThread.FinishEvent();
begin
  Self.DoFinishEvent();
end;

procedure TMasterThread.DoInitializeEvent(const AMaxValue: Integer);
begin
  if Assigned(Self.FOnInitialize) then Self.FOnInitialize(Self, AMaxValue);
end;

procedure TMasterThread.InitializeEvent();
begin
  Self.DoInitializeEvent(Self.FMaxValue);
end;

procedure TMasterThread.DoFinalizeEvent();
begin
  if Assigned(Self.FOnFinalize) then Self.FOnFinalize(Self);
end;

procedure TMasterThread.FinalizeEvent;
begin
  Self.DoFinalizeEvent();
end;

procedure TMasterThread.DoPauseEvent(const APaused: Boolean);
begin
  if Assigned(Self.FOnPause) then Self.FOnPause(Self, APaused);
end;

procedure TMasterThread.PauseEvent();
begin
  Self.DoPauseEvent(Self.FPaused);
end;

procedure TMasterThread.Pause();
begin
  Self.FPauseEvent.ResetEvent();
  Self.FPaused := True;
  Self.Synchronize(Self.PauseEvent);
end;

procedure TMasterThread.Unpause();
begin
  Self.FPaused := False;
  Self.Synchronize(Self.PauseEvent);
  Self.FPauseEvent.SetEvent();
end;

procedure TMasterThread.CheckForPause();
begin
  if (not (Self.Terminated)) then Windows.Sleep(1);
  Self.FPauseEvent.WaitFor(INFINITE);
end;

{ TSkeletonThread }
procedure TSkeletonThread.DoExecute(const theValue: Integer);
var
  X: Integer;
begin
  Self.Synchronize(InitializeEvent);
  try
    Self.Synchronize(BeginEvent);
    try
      for X := 0 to (theValue - 1) do
      begin
    Self.CheckForPause();

    if (not Self.FPaused) and (not Self.Terminated) then
    begin
      Self.FPosition := Self.FPosition + 1;
      Self.Synchronize(ProgressEvent);
    end
    else begin
      Break;
    end;
      end;

      for X := Self.FPosition downto 1 do
      begin
    Self.CheckForPause();

    if (not Self.FPaused) and (not Self.Terminated) then
    begin
      Self.FPosition := X;
      Self.Synchronize(ProgressEvent);
    end
    else begin
      Break;
    end;
      end;
    finally
      Self.Synchronize(FinishEvent);
    end;
  finally
    Self.Synchronize(FinalizeEvent);
  end;
end;

procedure TSkeletonThread.Execute();
begin
  Self.DoExecute(Self.FMaxValue);
end;

end.

A: You have to terminate the thread yourself (tell it to stop). One way is to use the Terminate procedure of the thread, but you have to check for this in the thread Execute method. Something like this:
procedure Execute;
begin
  inherited;

  while not Terminated do
  begin
    // do your job
  end;
end;

procedure TForm1.StopThread;
begin
  MyThread.Terminate;

  // wait and block until the scheduling thread is finished
  AResult := WaitForSingleObject(MyThread.Handle, cShutdownTimeout);

  // check if we timed out
  if AResult = WAIT_TIMEOUT then
    TerminateThread(MyThread.Handle, 0);
end;

Or you can use signalization build into windows so you do not have to loop.
procedure Execute;
begin
  inherited;

  while not Terminated do
  begin
    WaitStatus := WaitForSingleObject(FTermEvent, Max(0, SleepInterval));

    // check what was the cause for signalization
    if WaitStatus <> WAIT_TIMEOUT then
      Terminate;
  end;
end;

procedure TForm1.StopThread;
begin
  // Terminate the thread
  SetEvent(FTermEvent);
  // close the handle
  CloseHandle(FTermEvent);

  // wait and block until the scheduling thread is finished
  AResult := WaitForSingleObject(MyThread.Handle, cShutdownTimeout);

  // check if we timed out
  if AResult = WAIT_TIMEOUT then
    TerminateThread(MyThread.Handle, 0);
end;

Signalization can be very neat way of signaling for termination because you can use WaitForMultipleObjects and release the wait in different conditions. I used WaitForSingleObject to not complicate things to much.
Also be sure to set "FreeOnTerminate := True" in thread constructor. Oh and the hard termination at the end is optional of course. It can be dangerous. You know best yourself if you will use it or not. You can also wait for a longer period or infinite if you are sure the thread will stop eventually.


text:
Q: Accessing Controls Inside ASP.NET View Controls (Event Handling) If I have the following ListView, how can I attach a SelectedIndexChanged event listener to the DropDownList so I can perform a command on the respective object? Imagine I have a list of new users and I want to add them to a usergroup by selecting the group from the DropDownList.
<asp:ListView ID="NewUsers" runat="server" DataSourceID="NewUsersSDS" DataKeyNames="ID">
    <LayoutTemplate>
        <asp:Table ID="groupPlaceholder" runat="server"><asp:TableRow></asp:TableRow></asp:Table>
    </LayoutTemplate>
    <GroupTemplate>
        <asp:TableCell ID="itemPlaceholder" runat="server"></asp:TableCell>
    </GroupTemplate>
    <ItemTemplate>
        <asp:Table ID="NewUsersTable" runat="server" Width="32%" CssClass="inlineTable">
            <asp:TableRow>
                <asp:TableCell Width="100px"><%# Eval("FullName").ToString.Trim()%></asp:TableCell>
                <asp:TableCell>
                    <asp:HiddenField ID="RowIndex" runat="server" Value="<%# Container.DisplayIndex %>" />
                    <asp:DropDownList ID="UserGroupSelect" runat="server" DataSourceID="UserGroupSelectSDS" DataValueField="ID" DataTextField="UserGroup"
                        OnSelectedIndexChanged="UserGroupSelect_SelectedIndexChanged" AutoPostBack="True">
                    </asp:DropDownList>
                </asp:TableCell>
            </asp:TableRow>
        </asp:Table>
    </ItemTemplate>
</asp:ListView>

I've been having issues accessing controls inside of __View controls. I read in a few places that you could access them by NewUsers.FindControl([ControlID as String]) but this doesn't seem to be working for me. I guess this is what's called a dynamic control? Not really sure, feeling a bit lost.
As always, your help is greatly appreciated. ;)
Additional Info / Code
'Now working code, thanks to James :)
Protected Sub ItemBind(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles NewUsers.ItemDataBound
    Dim lv As ListView = DirectCast(sender, ListView)
    If e.Item.ItemType = ListViewItemType.DataItem Then
        lv.DataKeys(e.Item.DataItemIndex).Value.ToString() 'get the datakey
    End If
End Sub
    Protected Sub UserGroupSelect_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim RowIndex As Integer = CInt(DirectCast(DirectCast(sender, DropDownList).Parent.FindControl("RowIndex"), HiddenField).Value)
    Dim pk As Integer = CInt(NewUsers.DataKeys(RowIndex)("ID"))
    Try
        MessageBox("Update key " + pk.ToString, "Update Key") 'Custom js "alert" box function
    Catch ex As Exception
        MessageBox("Something went wrong, is the update key empty?")
    End Try
End Sub

A: To access controls in a ListView (or any databound control), you need to use FindControl on the item/row:
ListViewItem item = ListView1.Items[0];
if (item != null)
{
    DropDownList ddl = item.FindControl("DropDownList1") as DropDownList;
    if (ddl != null)
    {
        string value = ddl.SelectedValue;
    }
}

As for attaching a SelectedIndexChanged event, you can do it like this:
<ItemTemplate>
    <asp:DropDownList ID="DropDownList1" runat="server"
        AutoPostBack="true"
        OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    </asp:DropDownList>
    <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Container.DisplayIndex %>' />
</ItemTemplate>

Code-behind:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    int rowIndex = Convert.ToInt32(((HiddenField)((DropDownList)sender).Parent.FindControl("HiddenField1")).Value);

    ListViewItem item = ListView1.Items[rowIndex];
    if (item != null)
    {
        //your logic here
    }
}

To retrieve a datakey:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    int rowIndex = Convert.ToInt32(((HiddenField)((DropDownList)sender).Parent.FindControl("HiddenField1")).Value);

    int pk = (int)ListView1.DataKeys[rowIndex]["PrimaryKey"];
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to share a page without having Facebook share button Let's say, I've my own website with this page, http://sample.com/mypage
I want to share this, http://sample.com/mypage to my Facebook wall. The common way of sharing stuffs back to Facebook wall is by using share button just like how it's placed in Youtube.com etc. Once we click on the share button, it will pop up the share dialog, for us to confirm sharing.
However, what if I want to share it on behalf of user, without having user to press the share button and also the share confirmation dialog ?
Is there something like, the user first grant the permission to the website to share on behalf of them ?

A: Check into the feed dialog.

The Feed Dialog prompts the user to publish an individual story to a
  profile's feed. This does not require any extended permissions.
Your application can also publish directly to a profile's feed without
  user interaction, use the corresponding Graph API call.

http://developers.facebook.com/docs/reference/dialogs/feed/#graphapicall


text:
Q: How to render component in react server side with async data I searched a lot and didn't find any implementation to load data async in react server side before render the markup without any flux (redux) implementation.
Here's the view (both api and views together):
class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {meta: []};
  }

  componentDidMount() {
    Request.get('http://example.com/api/users').then((resp) => {
      this.setState({meta: resp.body});
    });

  }

  render() {
    return (

        {this.state.meta.map((m, i) => {

{m.user}

        })}
    );
  }
}

The router file (router.js):
export default (
    <Route component={App} path="/">
        <IndexRoute component={Home}/>
    </Route>
);

And this is what I use on server (with react-router)
app.use((req, res) => {

    Router.match({routes: routes, location: req.url}, (err, redirectLocation, renderProps) => {
        if(err) res.status(500).send(err.message);

        else if(redirectLocation)
            res.status(302).redirect(redirectLocation.pathname + redirectLocation.search);

        else if(renderProps) {
                var html = ReactDOM.renderToString(<RouterContext {...renderProps}/>);
                res.render("layout", {body: html});
        }
        else res.status(404).send("Page not Found");
    })
});

I know some basic thing that attach api calls to each router url and then resolve the renderToString() after that. But I don't understand how to do that with react-router.
I don't want to use any library or flux or redux implementation.

A: you can use getComponent prop in react-router to handle this situation.
//route.js
  function fetchAndGetComponent(location,callback){
    Request.get('http://example.com/api/users').then((resp) => {
      let meta = resp.body;
      callback(null,() => <Home meta={meta} />);
    });
  }

  <Route component={App} path="/">
        <IndexRoute getComponent={fetchAndGetComponent}/>
  </Route>


text:
Q: How can I parse date in Tue Apr 11 00:00:00 CEST 2017 format in Java? I have tried the below code to parse the date in Tue Apr 11 00:00:00 CEST 2017 format. But, it is showing parsing exception. How can I parse the date format for Tue Apr 11 00:00:00 CEST 2017?
SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");
Date bbDate=sdf.parse(String.valueOf("Tue Apr 11 00:00:00 CEST 2017"));
System.out.println(bbDate);

A: You have an unhandled exception. You need to surround the parse line in a try-catch, or have the function itself throw an exception.
    SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");

    try {
        Date bbDate = sdf.parse("Tue Apr 11 00:00:00 CEST 2017");
        System.out.println(bbDate);
    } catch (ParseException e) {
        // … Handle exception.
        System.out.println( "ERROR…" );
    }

Here is the documentation to learn more about Java exceptions.
https://docs.oracle.com/javase/tutorial/essential/exceptions/

A: It is better to use new Java Date Time api: http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html
You can do the same thing with the new api as follows:
ZonedDateTime.parse("Tue Apr 11 00:00:00 CEST 2017",
            DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy")).toLocalDateTime();

A: Its just not handled Parse Exception. Your SimpleDateFormat is good.
try {
        SimpleDateFormat sdf=new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");
        Date bbDate;
        bbDate = sdf.parse(String.valueOf("Tue Apr 11 00:00:00 CEST 2017"));
        System.out.println(bbDate);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

A: Since your string uses English names for week day and month, you need to make sure that your SimpleDateFormat uses a locale with English language, for example:
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.ROOT);

With this change your code prints (tested with Java 8):
Tue Apr 11 00:00:00 CEST 2017

EDIT: please fill in the appropriate (English-speaking) locale instead of Locale.ROOT.
I agree with Ali Sağlam in warmly recommending the java.time classes introduced in Java 8. You will still need to control the locale, though:
    ZonedDateTime.parse("Tue Apr 11 00:00:00 CEST 2017",
                        DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy",
                                                    Locale.ROOT))
            .toLocalDateTime();

Finally, while we're at the recommendations, see if you can find a way to avoid the three and four letter time zone abbreviations like CEST. Many of them are ambiguous, and CEST isn't even really a full time zone, just the summer half of the Central European time zone. While it works as expected with a date in the summer time half of year, I'm not even sure what I should expect if one day you have a date in winter with CEST time zone abbreviation.


text:
Q: Storing filename in db from ajax upload not working When I use $filename below I can never store anything in the database. I've tried basename function but it doesn't seem to store anything.
        $filename = $_FILES['file']['name'];

        /* Location */
        $location = "../media/images/profile-pics/".$filename;
        $uploadOk = 1;
        $imageFileType = pathinfo($location,PATHINFO_EXTENSION);

        /* Valid Extensions */
        $valid_extensions = array("jpg","jpeg","png");
        /* Check file extension */
        if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
           $uploadOk = 0;
        }

        if($uploadOk == 0){
           echo 0;
        }else{
           /* Upload file */
           if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){

           }else{
              echo 0;
           }
        }

        //$filename = basename($_FILES['file']); removed, but still doesn't store file in db.

        $stmt = $db->prepare("UPDATE contacts SET name = ?, email = ?, phone = ?, jobtitle = ?, profile_pic = ? WHERE id = ?");
        $stmt->bind_param("sssssi", $name, $email, $phone, $jobtitle, $filename, $id);
        $stmt->execute();
        $stmt->close();

A: Just get rid of $filename = basename($_FILES['file']); - you've already populated $filename with $_FILES['file']['name'] up above, which is the correct way to access the filename of the file as it was uploaded.


text:
Q: How to check a button color change from one color to another In the screenshot posted below, the cook, buyer and both are UIButton. User can click any one button. If one button is pressed, the button background color changes to green. After that when user clicks the register button, how do I check if the UIButton color is green or not. At least one UIButtonhas to be selected in order for the user to register.

I changed the button background color using this code:
@IBAction func cookact(_ sender: Any){

    cookbtn.backgroundColor = UIColor.green
}

How do I check if a button has been pressed?

A: There are two ways to do it. One assigning the tag values to buttons and compare, Other easy solution is by declaring the enum values:
Declare the enum:
Swift:
    enum REGISTER_TYPE {
            case COOK
            case BUYER
            case BOTH
        }

Objective - C
    typedef enum {
    COOK = 1,
    BUYER = 2,
    BOTH = 3
    }REGISTER_TYPE;

Now In your ViewController, create a property for the enum REGISTER_TYPE as
@property (nonatomic, assign) REGISTER_TYPE registerType;

When onClick the Button Action assign value to a property as
@IBAction func cookact(_ sender: Any){
   self.registerType = COOK
}

@IBAction func buyeract(_ sender: Any){
       self.registerType = BUYER
    }

So, self.registerType variable always holds a type of registration.
Hope it helps!

A: You can use a bool value.When the user presses the cook button or buyer button,you can change this bool value to true and on the basis of this bool value you can determine wether the button was clicked or not.


text:
Q: Docker Swarm: React frontend cannot connect to Kong API Gateway I am working on a project using microservices and I am trying to connect my frontend in React with my backend which is served through Kong API Gateway. The problem is that whenever I send a request to the server, I get the error net::ERR_NAME_NOT_RESOLVED. The frontend service is running in the same network as the API Gateway service, but apparently, the DNS resolution is not working.
This is how I build the React frontend Docker image:
FROM node:13.12.0-alpine

WORKDIR /app

ENV PATH /app/node_modules/.bin:$PATH

COPY package.json ./
COPY package-lock.json ./
RUN npm install --silent
RUN npm install react-scripts@3.4.1 -g --silent

COPY . ./

CMD ["npm", "start"]

This is how I send the request from the frontend:
handleLogin(event) {
    event.preventDefault();
    console.log("Log in " + JSON.stringify(this.state.loginForm));
    axios.post(`http://${process.env.API_URL}:${process.env.API_PORT}/api/users/login`, this.state.loginForm)
      .then((response) => {
        const model: LoginModel = response.data;
        this.handleLoginResponse(model);
      })
      .catch((errors) => alert(`Error sending login request to server: ${errors}`));
  }

This is my stack.yml configuration file for Docker Swarm deployment:
version: "3.8"

services:
  kong:
    image: kong:latest
    hostname: kong
    environment:
      KONG_DATABASE: "off"
      KONG_DECLARATIVE_CONFIG: /usr/local/kong/declarative/kong-plugins.yml
      KONG_PROXY_ACCESS_LOG: /dev/stdout
      KONG_ADMIN_ACCESS_LOG: /dev/stdout
      KONG_PROXY_ERROR_LOG: /dev/stderr
      KONG_ADMIN_ERROR_LOG: /dev/stderr
      KONG_ADMIN_LISTEN: 0.0.0.0:8001, 0.0.0.0:8444 ssl
    deploy:
      placement:
        constraints: [node.role == manager]
    ports:
      - 8000:8000
      - 8443:8443
      - 8001:8001
      - 8444:8444
    volumes:
      - ../../Kong:/usr/local/kong/declarative
    networks:
      - frontend-network
      - internal
      - logging

  frontend-service:
    image: virusx98/frontend
    environment:
      API_URL: kong
      API_PORT: 8000
    ports:
      - "3001:3000"
    networks:
      - frontend-network

  [...] /* other services */

volumes:
  [...] /* volumes for other services */

networks:
  frontend-network:
  [...] /* other networks */

secrets:
  [...] /* secrets for other services */

The stack works perfectly on the backend side. If I send requests using Postman, they reach the backend services and a result is returned. But if I send requests from the frontend, the above error is thrown, even though both services are placed in the same network and DNS resolution should work. The environment variables are read correctly by the React service, but it says it cannot resolve hostname kong. What am I missing here?

A: Edit based on comment
The reason you are unable to reach the API is because the Node process is not sending the request. Your browser is sending the request. The API must be accessible from your (and everyone else's) browser. In this case, your URL would need to be localhost:8000 in your javascript, so that your browser will be able to reach the kong container.
Original answer (only helps with env  vars)
react-scripts will only load a couple environment variables from Node. From their documentation:

Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name.

This means you have to update docker-compose.yml like so:
    environment:
      REACT_APP_API_URL: kong
      REACT_APP_API_PORT: 8000

Doing this, and console.log(process.env) yields:
{
  "NODE_ENV": "development",
  "PUBLIC_URL": "",
  "FAST_REFRESH": true,
  "REACT_APP_API_PORT": "8000",
  "REACT_APP_API_URL": "kong"
}

This being said, you should not use react-scripts start for production purposes. Always make a production build. You should instead add a .env file to your project so those variables get injected in the build. You won't be able to inject them via docker-compose.
Reference:

*

*https://create-react-app.dev/docs/adding-custom-environment-variables/


text:
Q: Getting iPhone Auto-Lock Setting Is it possible to ask the OS via code if the Auto-Lock and or Password Lock is enabled on the device?
A secure app I am making needs to warn the user if these are not set.

A: No, currently this is not possible (used to be prior to 5.0).  You can consider implementing a lock screen for the application.


text:
Q: Makefile with different source types doesn't notice make.depend I want my Makefile to accept different source file types. It does, but it does not recompile when I alter an include file. Here's the Makefile:
C_SOURCES       := $(wildcard *.c)
CPP_SOURCES     := $(wildcard *.cpp)
CC_SOURCES      := $(wildcard *.cc)
ALL_SOURCES     := $(notdir $(C_SOURCES) $(CPP_SOURCES) $(CC_SOURCES))

C_OBJECTS       := ${C_SOURCES:.c=.o}
CPP_OBJECTS     := ${CPP_SOURCES:.cpp=.o}
CC_OBJECTS      := ${CC_SOURCES:.cc=.o}
ALL_OBJECTS     := $(notdir $(C_OBJECTS) $(CPP_OBJECTS) $(CC_OBJECTS))

#############################################################

all: a.out

a.out: $(ALL_OBJECTS)
    g++ -o $@ -g $^

%.o:    %.cpp
        g++ -c $@ -g $^

%.o:    %.cc
        g++ -c $@ -g $^

%.o:    %.c
        g++ -c $@ -g $^

clean:
    rm -f a.out
    rm -f *.o

make.depend: $(ALL_SOURCES)
        g++ -MM $^ > $@

-include make.depend

The lines starting with *.o: are a recent addition -- I wondered if it might help. No effect.
make.depend is doing its job: I checked it out, and its dependencies are correct. (For my MCVE I have one source file main.cpp which includes date.h.)
main.o: main.cpp date.h

The output of $(info $(ALL_OBJECTS)) is main.o.
So: how can I get it to recognize changes to includes?

A: It would be helpful, when asking questions, to show an example of running the commands and what is printed.  Given the makefile you provide I'd be surprised of make actually ran any commands at all, other than generating the depend file.
That's because this:
C_OBJECTS       := ${C_SOURCES:     .c  =.o}

is invalid syntax.  Or more precisely, it doesn't do what you want to do.  It replaces the literal string _____.c__ (where the _ are whitespace... SO won't let me just use spaces) at the end of each word in C_SOURCES with .o.  Of course you don't have any of those, so basically your ALL_OBJECTS variable contains just your source files (since no changes are made by the substitution).
You can use:
$(info $(ALL_OBJECTS))

to see what happens here.
This needs to be written:
C_OBJECTS       := ${C_SOURCES:.c=.o}
CPP_OBJECTS     := ${CPP_SOURCES:.cpp=.o}
CC_OBJECTS      := ${CC_SOURCES:.cc=.o}

Whitespace in makefiles is very tricky.  You definitely have to be careful where you put it and you can't add it anywhere you like.
Also I have no idea why you're using notdir since all your files are in the current directory.
And technically it's incorrect to compile .c files with the g++ compiler front-end.
ETA also your pattern rules are incorrect: you're missing the -o option to the compiler; they should all be the equivalent of:
%.o:    %.c
        g++ -c -o $@ -g $^

Better is to use the standard make variables, then you can customize the behavior without rewriting all the rules:
CFLAGS = -g

%.o: %.c
        $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

A: Update Just use the comprehensively enginerred automatic dependency file generation @MadScientist describes at http://make.mad-scientist.net/papers/advanced-auto-dependency-generation/. This works with both GCC and clang (due to clang's explicit goal to be commandline compatible to GCC).
For completeness' sake, my original answer:
The generated dependency rules must depend on the sources determined by the dependeny rule generating rule. This requires the -MT parameter to gcc.
I have included this as an example in a slightly cleaned up version of your GNUmakefile:
#############################################################

ALL_CFLAGS   = -g
ALL_CXXFLAGS = -g

#############################################################

.PHONY: all
all: all-local

#############################################################

bin_PROGRAMS += test-cxx

test_cxx_OBJECTS += main.o
test_cxx_OBJECTS += main-c.o

test-cxx: $(test_cxx_OBJECTS)
    $(LINK.cc) $(ALL_CXXFLAGS) -o $@ $^

ALL_OBJECTS += $(test_cxx_OBJECTS)

#############################################################

%.o: %.cpp
    $(COMPILE.cpp) $(ALL_CXXFLAGS) -o $@ -c $<

%.o: %.cc
    $(COMPILE.cc)  $(ALL_CXXFLAGS) -o $@ -c $<

%.o: %.c
    $(COMPILE.c)   $(ALL_CFLAGS)   -o $@ -c $<

#############################################################

%.dep: %.cpp
    $(COMPILE.cpp) -MM -MT "$*.o $@ " $< > $@.tmp
    mv -f $@.tmp $@

%.dep: %.cc
    $(COMPILE.cc)  -MM -MT "$*.o $@ " $< > $@.tmp
    mv -f $@.tmp $@

%.dep: %.c
    $(COMPILE.c)   -MM -MT "$*.o $@ " $< > $@.tmp
    mv -f $@.tmp $@

ALL_DEPS = $(ALL_OBJECTS:.o=.dep)
-include $(ALL_DEPS)

#############################################################

.PHONY: all-local
all-local: $(bin_PROGRAMS)

.PHONY: clean
clean:
    rm -f $(bin_PROGRAMS)
    rm -f *.dep
    rm -f *.o

#############################################################

The *.dep generating rules will recursively examine all included source files, and list them all in the generated *.dep file.
Using a separate *.dep file for each object file means that if you change only one source file, only the *.dep files needing regeneration will actually be regenerated.
The *.dep generating rule creates a *.dep.tmp file first, and only moves that to *.dep if generating the *.dep.tmp file has been successful. So if for some reason generating the *.dep.tmp file fails (e.g. you might be including a non-existing header file), you will not have a newly generated (and thus considered up to date) empty *.dep file being included by make.


text:
Q: Trying to set and get attribute from one class to another via a 3rd class in JAVA I have a bean class which looks like this
@ManagedBean(name = "usingBean")
@SessionScoped
public class UserInfo implements Serializable {

    private static final long serialVersionUID = 2668727340500045081L;

    String loginId;

}

I set this bean attributes in a filter class.
I am trying to get this attribute in another bean class
@ManagedProperty(value = "#{usingBean}")
private UserInfo user;

public UserInfo getUser() {
    return user;
}

public void setUser(UserInfo user) {
    this.user = user;
}
UserInfo neededBean = (UserInfo) context.getApplication()
                .createValueBinding("#{usingBean}").getValue(context);
                return neededBean.getLoginId();

It says null when I try to print it, but it does get inserted into the DB.  It does not change when a different user logs in.

A: Try with simple way, in your filter class set your attribute to session
       FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context
                .getExternalContext().getRequest();
        HttpSession httpSession = request.getSession(false);
        httpSession.setAttribute("loginId", loginId);

In the other class, you can get the "loginId" from session ...
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context
                .getExternalContext().getRequest();
        HttpSession httpSession = request.getSession(false);
        String loginId= (String) httpSession.getAttribute("loginId");


text:
Q: Manga where the MC has some sort of system that helps him develop by annoying people I don't remember many details, but I believe the original language was Chinese. The protagonist is an orphan and has a sister to take care of.
Before he got the system's power, he used to sell tofu or whatnot on the streets. The system is designed to give points to him when he annoys or makes fun of other people, much similar to the system from "Strongest Anti M.E.T.A". The difference is that he stays in his original world.
Also, I think the art style was similar to "The Lord of Catastrophe".

A: Da Wang Rao Ming (Spare Me, Great Lord!, 2021).
From this review on MyAnimeList:

Lu Shu, an orphan abandoned by his Mother grew up in poverty with an adopted little sister Lu Xiaoyu struggling to gather money for their tuition. However, it all changes when Lu Shu is hit by a truck and dies in an accident. Activating powers passed on from his Mother, Lu Shu is revived and gets granted a Gacha System where he earns points from angering or intimidating people. The points he gathers are used to spin the wheel in hopes of getting a special cultivation fruit, single use healing, body upgrades and more.
[...]
At times the smaller details were very hard to avoid such as counting anger points which was done much better in "I annoy millions of cultivators" because at the end of each episode Lu Shu would be in a surplus of unspent points and arbitrarily spend them when needed. In the beginning we see that most of his points go to failed gacha spins and stinky tofu with special attributes but apart from that we rarely see the gacha system utilized especially later in the series.

Found by sheer, dumb luck: my partner described it to me briefly earlier this week when I asked him what he was watching. I prompted him to give me the show's name just as he was headed to bed tonight, he could not remember, but fortunately his browser history did!


text:
Q: How to use html tag in code behind? I need to use html tags such as  in code behind without declaring anything in aspx page.
So far I've tried below:
string s = HtmlTextWriterTag.Sup.ToString("1");

A: Try this one:
var strVariable = "This is a string object";
strVariable = strVariable.sup();

From MSDN

A: you may use html gerneric contorls
HtmlGenericControl sub= new HtmlGenericControl("sub");
  sub.Attributes.Add("class", "your-class");
  sub.ID = "subId";
  sub.ClientIDMode = ClientIDMode.Static;


text:
Q: How to get data from [Object] android I am getting this response from my Express API Call.
Here's the Response:
{
    "responseData": [{
        "unitNames": [
            "Matrices",
            "Complex Numbers"
        ],
        "subject": "maths",
        "unitTopics": {
            "1": [{
                    "topicName": "1.1 Introduction",
                    "topicURL": ""
                },
                {
                    "topicName": "1.2 Square Matrix",
                    "topicURL": ""
                }

            ],
            "2": [{
                    "topicName": "2.1 Numbers",
                    "topicURL": ""
                }

            ]
        }
    }]
}

I got the response by using Retrofit in Android. It works great.But it can't parse Objects
Here's my Problem in Android Side.
{
        "responseData": [{
            "unitNames": [
                "Matrices",
                "Complex Numbers"
            ],
            "subject": "maths",
            "unitTopics": {
                "1": [[Object],
                    [Object]

                ],
                "2": [[Object]

                ]
            }
        }]
    }

Its showing Object instead of my Data. How to fix this
Here's the Code:
System.out.println(response.body().getResponseData())
String received_data = response.body().getResponseData();
received_data_sub_units_topics_json = new JSONArray("["+received_data+"]");
System.out.println("MAIN2 "+received_data_sub_units_topics_json);

After converting to jsonarray, it shows like this,
{
        "responseData": [{
            "unitNames": [
                "Matrices",
                "Complex Numbers"
            ],
            "subject": "maths",
            "unitTopics": {
                "1": [["Object"],
                    ["Object"]

                ],
                "2": [["Object"]

                ]
            }
        }]
    }

Please help me with some solutions

A: For json i always use the library com.fasterxml.jackson.
You can use too org.json.JSONArray, org.json.JSONObject.
Here is an example of each one:
1- jackson
For implements this (is a bit long but you will convert it to java classes, so, you will can edit the values and obtain it more easily than if you use JSONObject), you have to create classes wich has the same structure than your json:
public class principalClass {
     ArrayList<ResponseData> responseData;
     ...
     //Getters, setters and constructors
}

public class ResponseData {
    public ArrayList<String> unitNames;
    public String subject;
    public UnitTopics unitTopics;
    ...
    //Getters, setters and constructors
}

public class UnitTopics {
    public ArrayList<Topics> first;
    public ArrayList<Topics> second;
    ...
    //Getters, setters and constructors
}

public class Topics {
    public String topicName;
    public String topicURL;
    ...
    //Getters, setters and constructors
}

Something like that, and then you use jackson to pass your json to you class principalClass:
ObjectMapper obj= new ObjectMapper();
PrincipalClass principal= obj.readValue(json, PrincipalClass.class);

The second posibility is to convert the values to JSONArray and JSONObject:
JSONObject bodyJSON = new JSONObject(json);

JSONArray responseData = bodyJSON.getJSONArray("responseData");

JSONArray unitNames= responseData.getJSONArray(0);
JSONObject subject= responseData.getJSONObject(1);
...

And if u want, u can loop through a JSONArray:
for (int i = 0; i < unitNames.length(); i++) {
     String element = unitNames.getString(i);
}

A: Hey have you tried converting this JSON Object to a POJO.
I'd recommend using:
This website
It saves a lot of time and effort.
These will be your model classes:
package com.example.app;

import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class ResponseDatum implements Serializable
{

@SerializedName("unitNames")
@Expose
private List<String> unitNames = null;
@SerializedName("subject")
@Expose
private String subject;
@SerializedName("unitTopics")
@Expose
private UnitTopics unitTopics;

public ResponseDatum() {
}

public ResponseDatum(List<String> unitNames, String subject, UnitTopics unitTopics) {
super();
this.unitNames = unitNames;
this.subject = subject;
this.unitTopics = unitTopics;
}

public List<String> getUnitNames() {
return unitNames;
}

public void setUnitNames(List<String> unitNames) {
this.unitNames = unitNames;
}

public String getSubject() {
return subject;
}

public void setSubject(String subject) {
this.subject = subject;
}

public UnitTopics getUnitTopics() {
return unitTopics;
}

public void setUnitTopics(UnitTopics unitTopics) {
this.unitTopics = unitTopics;
}

}

package com.example.app;

import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class ResponseObject implements Serializable
{

@SerializedName("responseData")
@Expose
private List<ResponseDatum> responseData = null;

public ResponseObject() {
}

public ResponseObject(List<ResponseDatum> responseData) {
super();
this.responseData = responseData;
}

public List<ResponseDatum> getResponseData() {
return responseData;
}

public void setResponseData(List<ResponseDatum> responseData) {
this.responseData = responseData;
}

}

package com.example.app;

import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class UnitTopics implements Serializable
{

@SerializedName("1")
@Expose
private List<com.example.app._1> _1 = null;
@SerializedName("2")
@Expose
private List<com.example.app._2> _2 = null;

public UnitTopics() {
}

public UnitTopics(List<com.example.app._1> _1, List<com.example.app._2> _2) {
super();
this._1 = _1;
this._2 = _2;
}

public List<com.example.app._1> get1() {
return _1;
}

public void set1(List<com.example.app._1> _1) {
this._1 = _1;
}

public List<com.example.app._2> get2() {
return _2;
}

public void set2(List<com.example.app._2> _2) {
this._2 = _2;
}

}

package com.example.app;

import java.io.Serializable;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class _1 implements Serializable
{

@SerializedName("topicName")
@Expose
private String topicName;
@SerializedName("topicURL")
@Expose
private String topicURL;

public _1() {
}

public _1(String topicName, String topicURL) {
super();
this.topicName = topicName;
this.topicURL = topicURL;
}

public String getTopicName() {
return topicName;
}

public void setTopicName(String topicName) {
this.topicName = topicName;
}

public String getTopicURL() {
return topicURL;
}

public void setTopicURL(String topicURL) {
this.topicURL = topicURL;
}

}

package com.example.app;

import java.io.Serializable;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class _2 implements Serializable
{

@SerializedName("topicName")
@Expose
private String topicName;
@SerializedName("topicURL")
@Expose
private String topicURL;

public _2() {
}

public _2(String topicName, String topicURL) {
super();
this.topicName = topicName;
this.topicURL = topicURL;
}

public String getTopicName() {
return topicName;
}

public void setTopicName(String topicName) {
this.topicName = topicName;
}

public String getTopicURL() {
return topicURL;
}

public void setTopicURL(String topicURL) {
this.topicURL = topicURL;
}

}

A: You can use gson converter with retrofit to convert your json data to java object model class
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Or you can convert json data to model class like
Gson gson = new Gson();
String jsonInString = "{your json data}";
ResponseModel response= gson.fromJson(jsonInString, ResponseModel.class);


text:
Q: SQL output activity not have I have 3 tables called Classes, Courses and Activitys.
The Courses and Classes tables have the columns Id and Name.
The Activitys table has the columns ClassId and CourseId.
How do I show a list where I print the courses that the class doesnt have?
Output should look like this:

-Class-    -Missing class-
class1     course1
class1     course3
class2     class 2
CLass 1 only have course 2
CLass 2  have course 1 and course 3

A:  SELECT Name FROM Courses WHERE Id NOT IN (SELECT Id FROM Activitys WHERE ClassId = <Id> );

From the scratch of my head I'd try that. That should give you all the Courses that the chosen Class does not have.
<Id> in the end has to be the Id of the class you want to check for.


text:
Q: Why does ls not subset by filetype recursively (with -R)? I want to list all .jpg files in all subdirectories using ls.
For the same directory this works fine:
ls *.jpg
However, when using the -R for recursiveness:
ls -R *.jpg
I get:
zsh:no matches found: *.jpg
Why does this not work?
Note: I know it can be done using find or grep but I want to know why the above does not work.

A: The program ls is not designed to handle patterns by itself.
When you run ls -R *.jpg, the pattern *.jpg is not directly passed to ls. The shell replaces it by a list of all files that match the pattern. (Only if there is no file with a matching name, ls will see the file name *.jpg and not find a file of this name.)
Since you are using zsh (with the default setting setopt nomatch), it prints an error message instead of passing the pattern to ls.
If there are matching files, e.g. A.jpg, B.jpg, C.jpg, the command
ls *.jpg

will be run by the shell as
ls A.jpg B.jpg C.jpg

In contrast to this, find is designed to handle patterns with its -name test.  When using find you should make sure the pattern is not  replaced by the shell, e.g. by using -name '*.jpg' or -name \*.jpg. Otherwise you might get unexpected results or an error if there are matching files in the current directory.

Edit:
As shown in Martin Tournoij's answer you could use the recursive glob pattern ls **/*.jpg, but this is also handled by the shell not by ls, so you don't need option -R. In zsh this recursive pattern ** is enabled by default, in bash you need to enable it with shopt -s globstar.

A: The shell first expands any glob patterns, and then runs the command. So from ls's perspective, ls *.jpg is exactly the same as if you had typed ls one.jpg two.jpg. The -R flag to ls only makes sense if you use it on a directory, which you're not doing here.
This is also why mv *.jpg *.png doesn't work as expected on Unix systems, since mv never sees those patterns but just the filenames it expanded to (it does on e.g. Windows, where the globbing is done by the program rather than the shell; there are advantages and disadvantages to both approaches).

* matches all characters except a /, so *.jpg only expands to patterns in the current directory. **/ is similar, but also matches /, so it expands to patterns in any directory. This is supported by both bash and zsh.
So ls **/*.jpg will do what you want; you don't need to use find or grep. In zsh, especially you rarely need to use find since globbing is so much more powerful than in the standard Bourne shell or bash.
In zsh you can also use setopt glob_star_short and then **.jpg will work as well, which is a shortcut for **/*.jpg.


text:
Q: fractional part of $n^2\alpha$ is equidistributed Question:
$\alpha$ is an irrational number.Denoted the fractional part of $n^2\alpha$ as $\{n^2\alpha\}$.Prove that $\{n^2\alpha\}$ is equidistributed,i.e.
$$\lim_\limits{N\to\infty} \frac{\#\{1\leq n\leq N:\{n^2\alpha\}\in(a,b)\}}{N}=b-a,\forall (a,b)\subset [0,1).$$
Attempt:
By Weyl's criterion we just need to show that
$$\frac1N \sum_\limits{n=1}^{N}e^{2\pi ikn^2\alpha}\to 0,\forall k\in \mathbb{N_+}.$$
I try to estimate the sum by integration,and get $\int_1^N e^{2\pi ikx^2\alpha} {\rm{d}}x=O(1)$.
But I have trouble estimating the difference $\sum_\limits{n=1}^{N-1}\int_n^{n+1} (e^{2\pi ikx^2\alpha}-e^{2\pi ikn^2\alpha}) {\rm{d}}x.$


text:
Q: CString Hex value conversion to Byte Array I have been trying to carry out a conversion from CString that contains Hex string to a Byte array and have been
unsuccessful so far. I have looked on forums and none of them seem to help so far. Is there a function with just a few
lines of code to do this conversion?
My code:
BYTE abyData[8];    // BYTE = unsigned char

CString sByte = "0E00000000000400";

Expecting:
abyData[0] = 0x0E;
abyData[6] = 0x04; // etc.

A: You can simply gobble up two characters at a time:
unsigned int value(char c)
{
    if (c >= '0' && c <= '9') { return c - '0'; }
    if (c >= 'A' && c <= 'F') { return c - 'A' + 10; }
    if (c >= 'a' && c <= 'f') { return c - 'a' + 10; }

    return -1; // Error!
}

for (unsigned int i = 0; i != 8; ++i)
{
    abyData[i] = value(sByte[2 * i]) * 16 + value(sByte[2 * i + 1]);
}

Of course 8 should be the size of your array, and you should ensure that the string is precisely twice as long. A checking version of this would make sure that each character is a valid hex digit and signal some type of error if that isn't the case.

A: How about something like this:
for (int i = 0; i < sizeof(abyData) && (i * 2) < sByte.GetLength(); i++)
{
    char ch1 = sByte[i * 2];
    char ch2 = sByte[i * 2 + 1];

    int value = 0;

    if (std::isdigit(ch1))
        value += ch1 - '0';
    else
        value += (std::tolower(ch1) - 'a') + 10;

    // That was the four high bits, so make them that
    value <<= 4;

    if (std::isdigit(ch2))
        value += ch1 - '0';
    else
        value += (std::tolower(ch1) - 'a') + 10;

    abyData[i] = value;
}

Note: The code above is not tested.

A: You could:
#include <stdint.h>
#include <sstream>
#include <iostream>

int main() {
    unsigned char result[8];
    std::stringstream ss;
    ss << std::hex << "0E00000000000400";
    ss >> *( reinterpret_cast<uint64_t *>( result ) );
    std::cout << static_cast<int>( result[1] ) << std::endl;
}

however take care of memory management issues!!!
Plus the result is in the reverse order as you would expect, so:
result[0] = 0x00
result[1] = 0x04
...
result[7] = 0x0E


text:
Q: R: Creating a custom error message giving argument values for a function in a package Suppose there is a set of functions, drawn from a package not written by me, that I want to assign to a special behavior on error. My current concern is with the _impl family of functions in dplyr. Take mutate_impl, for example. When I get an error from mutate, traceback almost always leads me to mutate_impl, but it is usually a ways up the call stack -- I have seen it be as many as 15 calls from the call to mutate. So what I want to know at that point is typically how the arguments to mutate_impl relate to the arguments I originally supplied to mutate (or think I did).
So, this code is probably wrong in too many ways to count -- certainly it does not work -- but I hope it at least helps to express my intent. The idea is that I could wrap it around mutate_impl, and if it produces an error, it saves the error message and a description of the arguments and returns them as a list
str_impl  <- function(f){tryCatch(f, error = function(c) {
    msg <- conditionMessage(c)
    args <- capture.output(str(as.list(match.call(call(f)))))
    list(message =  msg, arguments = args)
}
assign(str_impl(mutate_impl), .GlobalEnv)

Although, this still falls short of what I really want, because even without  the constraint of working code, I could not figure out how to produce a draft. What I really want is to be able to identify a function or list of functions that I want to have this behavior on error, and then have it occur on error whenever and wherever that function is called. I could not think of any way to even start to do that without rewriting functions in the dplyr package environment, which struck me as a really bad idea.
The final assignment to the global environment is supposed to get the error object back to somewhere I can find it, even if the call to mutate_impl happens somewhere inaccessible, like in an environment that ceases to exist after the error.

A: Probably the best way of achieving what you want is via the trace functionality. It's surely worth reading the help about trace, but here is a working example:
library(dplyr)

trace("mutate_impl", exit = quote({
  if (class(returnValue())[1]=="NULL") {
    cat("df\n")
    print(head(df))
    cat("\n\ndots\n")
    print(dots)
  } else {
    # no problem, nothing to do
  }
}), where = mutate, print = FALSE)

# ok
xx <- mtcars %>% mutate(gear = gear * 2)
# not ok, extra output
xx <- mtcars %>% mutate(gear = hi * 2)

It should be fairly simple to adjust this to your specific needs, e.g. if you want to log to a file instead:
trace("mutate_impl", exit = quote({
  if (class(returnValue())[1]=="NULL") {
    sink("error.log")
    cat("df\n")
    print(head(df))
    cat("\n\ndots\n")
    print(dots)
    sink()
  } else {
    # no problem, nothing to do
  }
}), where = mutate, print = FALSE)


text:
Q: SQLAlchemy how to define two models for the same table I have a single table, and one of the columns is a varchar with two values ('groupA','groupB')
When I created my models I wanted to achieve two things:

*

*model for groupA - that hold X amount of related functions

*model for groupB - that hold Y amount of related functions

the functions are not the same for both models, though they represents the same table:
class GroupA(Base):
  __tablename__ = 'groups'

  id = Column('id', Integer, primary_key=True)
  name  = Column('name',  String(80))
  group_type = Column('type', String(15), default="groupA")

And for groupB:
class GroupB(Base):
  __tablename__ = 'groups'

  id = Column('id', Integer, primary_key=True)
  name  = Column('name',  String(80))
  group_type = Column('type', String(15), default="groupB")

So GroupA & B are the same table: "groups", but GroupA has 100 rows, groupB has 20rows
I want to prevent writing this all the time:
session.query(GroupA).filter(group_type = 'groupA')
session.query(GroupB).filter(group_type = 'groupB')

How can I configure my model with some kind of a "fitler" that when I'll query.all() it will return the data relavent for each model ? right now I receive all data in both models no matter which model I queried...
Thanks in advance.
EDIT with the solution based on answer
To use inheritence I had to change the entire structure to
class Group(Base):
   id = Column('id', Integer, primary_key=True)
   name  = Column('name',  String(80))
   group_type = Column('type', String(15))

    __mapper_args__ = {
        'polymorphic_on': g_type,
        'polymorphic_identity': 'Group'
    }

# Replacing Base => Group
class GroupA(Group):
   __mapper_args__ = {
      'polymorphic_identity': 'GroupA'
   }

class GroupB(Group):
   __mapper_args__ = {
      'polymorphic_identity': 'GroupB'
   }

And it's working, thank you very much !

A: Single Table Inheritance is what you need. Define your group_type as the polymorphic identity and you're all set.


text:
Q: Vertical Lines in Table not showing in Dark Mode (swift) I have a table in which each row has 5 UILabels.
In the UITableViewCell class I set each label.layer.borderWidth = 0.5.
Then, in a table configuration function, I set tableView.separatorColor = lineColor.
The horizontal lines appear in the table but the vertical lines do not.  I've increased the borderWidth, changed colors, checked both portrait and landscape, but the vertical lines just do not appear.
Light:
Dark:
How do I display vertical lines separating the cells when in Dark Mode?


text:
Q: Custom node package does not provide an export named I feel like I've tried everything but nothing seem to work.
I have created and published the following module:
Index.ts :
import ContentIOService from "./IOServices/ContentIOService";

export = {
    ContentIOService: ContentIOService,
}

Where ContentIOService is the following file:
import {SuperIO} from "../Framework/SuperIO";
export interface ICMSContentData {
    id: number;
    url: string;
    htmlTag: string;
    importJSComponent: string;
    componentData: string
}

export interface CMSData {
    id: number;
    url: string;
    htmlTag: string;
    importJSComponent: string;
    componentData: Object
}

export default  class ContentIOService extends SuperIO {

    private static instance: ContentIOService;

    public static getInstance(): ContentIOService {
        if (!ContentIOService.instance) {
            ContentIOService.instance = new ContentIOService();
        }
        return ContentIOService.instance;
    }

    public async GetContent(url: string) {
        const response = await super.get<ICMSContentData[]>(url, {});
        try {
            if (response?.parsedBody) {
                return this.ProcessResponse(response.parsedBody);
            } else {
                this.handleHTTPError(new Error("Error"))
            }

        } catch (e) {
            this.handleHTTPError(e);
        }

    }

    private ProcessResponse(ContentData: ICMSContentData[]): CMSData[] {
        let CMSData: CMSData[] = [];
        for (let i = 0; i < ContentData.length; i++) {
            CMSData.push({
                id: ContentData[i].id,
                url: ContentData[i].url,
                htmlTag: ContentData[i].htmlTag,
                importJSComponent: ContentData[i].importJSComponent,
                componentData: this.parseComponentData(ContentData[i].componentData)
            })
        }
        return CMSData;
    }

    private handleHTTPError(e: Error) {
        console.log(e)
    }

    private parseComponentData(parseAbleString: string): Object {
        return JSON.parse(parseAbleString);
    }
}

Then I have built this together and bundled it into a /lib folder:

This is built with the following tsconfig
  {
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./lib",
    "esModuleInterop": true,
    "strict": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/__tests__/*"]
}

For the sake of argument I will also post my Package.json should that be necessary:
    {
  "name": "sdk-io-package",
  "version": "1.1.6",
  "description": "",
  "main": "lib/index.js",
  "types": "lib/index.d.ts",
  "scripts": {
    "test": "jest --config jestconfig.json",
    "build": "tsc",
    "format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"",
    "lint": "tslint -p tsconfig.json"
  },
  "keywords": [],
  "author": "Marc Rasmussen",
  "license": "MIT",
  "devDependencies": {
    "@types/jest": "25.2.2",
    "chai": "^4.2.0",
    "es6-promise": "^4.2.8",
    "isomorphic-fetch": "^2.2.1",
    "jest": "25.2.2",
    "prettier": "^2.1.1",
    "ts-jest": "^26.3.0",
    "tslint": "^6.1.3",
    "tslint-config-prettier": "^1.18.0",
    "typescript": "^3.9.7"
  },
  "files": [
    "lib/**/*"
  ]
}

I publish this module on my private proget server and import it in my other project:

Where the index.js file looks like this:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var ContentIOService_1 = __importDefault(require("./IOServices/ContentIOService"));
module.exports = {
    ContentIOService: ContentIOService_1.default,
};

Then inside of my typescript I import it:
import {LitElement, html, customElement, property} from 'lit-element';
import {ContentIOService} from 'sdk-io-package';
@customElement('my-test-element')
export class MyTestElement extends LitElement {

    @property()
    text: string = "Hello world";

    render() {
        this.test();
        return html`
        ${this.text}
    `;
    }

  async  test (){
        const instance = ContentIOService.getInstance();
        const data = instance.GetContent("https://httpbin.org/get")
        console.log(data);
    }
}

declare global {
    interface HTMLElementTagNameMap {
        'my-test-element': MyTestElement;
    }
}

I then run my application (it builds without any typescript errors) and serve, Go to the browser and I get the following error:

Uncaught (in promise) SyntaxError: The requested module '../../node_modules/sdk-io-package/lib/index.js' does not provide an export named 'ContentIOService'

I simply don't know what I've done wrong.
Small update
When I look in the browser in the node_modules folder I actually don't see the folders inside lib and thereby not the module?:

A: export = {
    ContentIOService: ContentIOService,
}

This does NOT export a value named ContentIOService. Instead, it's a default export of an object that has a property named ContentIOService. Those two scenarios are not the same thing.
A named export would look more like this:
import _ContentIOService from "./IOServices/ContentIOService";

export const ContentIOService = _ContentIOService;

Which you can clean up by using a re-export:
export { default as ContentIOService } from "./IOServices/ContentIOService";


text:
Q: How do I cast dd/mm/yyyy string into date in BigQuery? I have 3 columns
1. dd/mm/yyyy (stored as a string)
2. app_id and #downloads of apps
I have to find unique ids of apps downloaded within a week.
Thank you

A: Shorter with REGEXP_REPLACE:
SELECT ds,
   TIMESTAMP(REGEXP_REPLACE(ds, r'(..)/(..)/(....)', r'\3-\2-\1')) ts
FROM (SELECT '23/03/2015' ds)

EDIT
Updated version for non-leading zero dates:
SELECT ds,
   TIMESTAMP(REGEXP_REPLACE(ds, r'(.?.)/(..)/(....)', r'\3-\2-\1')) ts
FROM (SELECT '1/01/2017' ds)

A: Even shorter using standard SQL:
SELECT TIMESTAMP(PARSE_DATE('%d/%m/%Y','23/03/2015'))

A: You can convert your dd/MM/yyyy strings into BigQuery timestamps using something like the following:
SELECT TIMESTAMP(year + '-' + month + '-' + day) as output_timestamp
FROM (
  SELECT
    REGEXP_EXTRACT(input_date, '.*/([0-9]{4})$') as year,
    REGEXP_EXTRACT(input_date, '^([0-9]{2}).*') as day,
    REGEXP_EXTRACT(input_date, '.*/([0-9]{2})/.*') AS month
  FROM
    (SELECT '30/10/2015' as input_date),
    (SELECT '25/01/2015' as input_date)
)

Once you have converted them to timestamps, you may find the date and time functions useful, depending on what you're trying to do.


text:
Q: Why is there no product/quotient rule for integration? So it's known that there's no product rule and quotient rule for integration. But is there a reason why they don't exist, and the rules exist for differentiation?

A: Edit: In light of Carmeister's comment, I would like to clarify that (in my opinion) there does exist an integral analogue to the product rule, and that analogue is integration by parts.
Unfortunately you can't comment an image, but I think this visual would supplement the above answers very nicely:

To see how this relates to the product rule, take qbert's answer and change $f(t)$ and $g(t)$ with $u$ and $v$.
You can see how this works for definite and indefinite integrals by taking the standard integration by parts formula,
$$\int v \, du = uv - \int u\,dv$$
and evaluating it between the points $(v_1,u_1)$ and $(v_2,u_2$), giving you
$$\int_{u_1}^{u_2} v \, du = u_2v_2 - u_1v_1 -\int_{v_1}^{v_2} u\,dv$$
Side note: I hate doing integration by parts with $u$ and $v$ — they just look too similar! That's why I prefer to use $w$ and $z$.

A: The product rules is in fact an easy way to derive integration by parts! If we have
$$
\frac{d}{dt}\bigl(f(t)\,g(t)\bigr)=f'(t)\,g(t)+f(t)\,g'(t)
$$
then the FTC tells us that
$$
\int_{a}^x\frac{d}{dt}\bigl(f(t)\,g(t)\bigr)\,\mathrm dt=\int_a^xf'(t)\,g(t)\,\mathrm dt+\int_{a}^xf(t)\,g'(t)\,\mathrm dt\\
\implies f(x)\,g(x)-\int_a^xf'(t)\,g(t)\,\mathrm dt=\int_{a}^xf(t)\,g'(t)\,\mathrm dt+C
$$
where $C=f(a)\,g(a)$.

A: Integration doesn't follow any type of general rule in case of fractions.
However, for integration of product functions, we've the following breakdown -
Let there be two functions $u(x)$ and $v'(x)$ (further denoted by $u$ and $v$), such that $\displaystyle \int v'(x)  \; dx = v(x)$,
Then by product rule, we've $$d(uv)=u'v+uv'$$
Integrating both the sides
$$uv=\int u'v+\int uv' $$
$$\implies \color{blue}{\int uv'=uv-\int u'v}$$
This is known as Integration by Parts

A: I'll try to approach this question in a bit more abstract way. I know I won't be 100% precise in my statements, but I think that this is the point.
First, note that indefinite integration is basically an inverse operation to the derivative, and this is basically the only definition we have. Yes, you can define indefinite integral as $F(x) = \int_a^x f(\xi) d\xi$ and use Riemann (or Lebesgue) integral, but these involve crazy formulas with strange limits of sums and stuff.
The fact that there's an easy formula for the derivative of a product is useless for the inverse derivative of a product. Similarly, note that computing a product of two functions is easy, but computing the inverse function of a product is tough.
Actually, product of invertible functions may not even be invertible! (Example: $e^x\sqrt{1/x}$.)
Or, the inverse may not be expressible in elementary functions. (Example: $e^x\sqrt{x}$.)
And this is in my opinion similar to the integrals, where a product of two functions with integrals expressible in elementary functions may not have such an integral. (The same two examples work.)
So somehow, this issue is related to the fact that when some operation works well on products, its inverse need not to, implicitly.

A: First and foremost, the integration rule that's most "analogous" to the product rule is integration by parts:
$$ \int u \, dv = uv - \int v \, du $$
This formula can be established by starting with the product rule:
$$ d(uv) = v \cdot du + u \cdot dv $$
Now integrate both sides and rearrange a bit.  This leaves out some details, but at a high level that's what's going on.
In general, it's just the case that integration is a much more difficult problem than differentiation.  You can take the derivative of any elementary function you can write down.  But the same is not true of integration.  For example, $e^{\sin x}$ is very easy to differentiate with the chain rule.  But there is no formula to integrate it.

A: I agree with @yo', but I thought it was worth saying more. Because of the chain rule and the product rule, along with the derivative formulas for basic functions, derivatives in general can be calculated mechanically. Algebraically, integration is of course the inverse process, and sometimes inverses can be calculated just as mechanically as the forward operation, but not usually.
I think the idea of entropy is useful here, at least as a metaphor. There are a lot more ways for a formula to get more complicated (one might almost say disorderly, although it is driven by the underlying order of mathematics) than for it to get simpler. So most differentiation operations (especially the product rule) are going to  make formulas more complicated. That means the inverse operation is unlikely to have a simple form.
In the specific case of the product rule, it's impossible for there to be a simple product rule for integration, because the product rule for derivatives goes from a product of two functions to a sum of two products. Reversing the operation requires you to carefully cancel the extra product of functions, and that's not always possible. But that "careful cancellation" is just the process of integration by parts that several other answers talked about.


text:
Q: Bundle to be considered in the Dirac monopole When dealing with the Dirac magnetic monopole from the point of view of the gauge theory, most authors consider a principal bundle over $S^2$ under the pretext of being homotopic to $\mathbb{R}^3 \setminus \{0\}$. I do not understand why homotopy guarantees the invariance of such treatment.
Appreciate.


text:
Q: passport.authenticate() gets called twice only on error I am authenticating the user using Ldap authentication. This works fine during a successful authentication or when the user provides incorrect credentials. But in case of an error being thrown the passport.authenticate() function gets called twice and i get the below error.
_http_outgoing.js:470
throw new ERR_HTTP_HEADERS_SENT('set');
^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the
client

So why does passport.authenticate function gets called twice only on error. Below is the code used for authentication.
let callCnt = 0

function pPortAuth(req,res,next) {
//Fetch the roles of the gid from the database
console.log("Called Here")
passport.authenticate('ldapauth', { session: false }, function (err, user,
info) {
    console.log("Hetre " + req.method)
    ++callCnt
    console.log(callCnt)

    if (err || !user) {
        if (err && (err.code == 'ETIMEDOUT' || err.code == 'ENOTFOUND')) {
            console.log("Could not reach Ldap Server" + err.code)

            return res.status(400).json({ success: false, message: 'Could
    not reach Ldap Server' })
        }else if(!user){
            console.log("Authentication Failed or not a valid user")
        return res.status(400).json({ success: false, message:
   'Authentication Failed' });
        }
    }

    let roles = (user.sAMAccountName == 'g705615')?['readWrite']:
    ['readOnly']
    console.log(roles)
    return res.send({
        success: true,
        gid: user.sAMAccountName,
        name: user.name,
        token: jwt.sign({ sub: user.sAMAccountName, roles: roles,
   loggedInUsername: user.name }, config.secret)
    });
})(req,res,next)
}

And below is the log
Called Here
Hetre POST
1
Could not reach Ldap ServerENOTFOUND
Hetre POST
2
Could not reach Ldap ServerENOTFOUND

If you see the function function pPortAuth(req,res,next) gets called only once but the passport.authenticate() function gets called twice on error.
Can anyone please tell me where i am making a mistake
UPDATE
//users.controller.js
let express = require('express');
let userAuth = express.Router();
let expressJwt = require('express-jwt');
let passport = require('passport')
let config = require("../config.json")
let userAuthSvc = require('../_services/user.service')

let Ldap = require('../config/ldap.config');

passport.serializeUser((user, done) => {
done(null,user)
})
passport.deserializeUser((user,done) => {
done(null,user)
})

passport.use(Ldap)

let initializePport = passport.initialize();

//userAuth.use(userAuthSvc.pportInit);
userAuth.post('/ldapLogin',initializePport, authenticate)

function authenticate (req, res, next) {
userAuthSvc.pportAuth(req, res, next);
}

//user.service.js
let passport = require('passport')

function pPortAuth(req,res,next) {
//Fetch the roles of the gid from the database
console.log("Called Here")
passport.authenticate('ldapauth', { session: false }, function (err, user,
info) {
    console.log("Hetre " + req.method)
    ++callCnt
    console.log(callCnt)

    if (err || !user) {
        if (err && (err.code == 'ETIMEDOUT' || err.code == 'ENOTFOUND')) {
            console.log("Could not reach Ldap Server" + err.code)

            return res.status(400).json({ success: false, message: 'Could
  not reach Ldap Server' })
        }else if(!user){
            console.log("Authentication Failed or not a valid user")
        return res.status(400).json({ success: false, message:
 'Authentication Failed' });
        }
    }

    let roles = (user.sAMAccountName == 'g705615')?['readWrite']:
 ['readOnly']
    console.log(roles)
    return res.send({
        success: true,
        gid: user.sAMAccountName,
        name: user.name,
        token: jwt.sign({ sub: user.sAMAccountName, roles: roles,
 loggedInUsername: user.name }, config.secret)
    });
 })(req,res,next)
 }

A: Another place you can get multiple calls to passport is from your strategy.
Check the callbacks inside your strategy function and that the inner user validation function only calls back once.
For me it was forgetting to put return in front of one of the callbacks in my username db lookup function, causing two callbacks.
function strategy(username, password, cb) {
    getEmailFromDB(username, async (err, user) => {
        console.log('stragegy res',err,user);
        if (err) {
            console.log('lookup error',err);
            return cb(err);
        }
        if (!user) {
            console.log('bad username');
            return cb(null, false);
        }
        ...

function getEmailFromDB(id, cb) {
    process.nextTick(async () => {
        try {
            var account = await r.table('users').get(id).run(rconn)
            if(!account) {
                console.log('User doesnt exist',id);
                return cb(true);                       // had forgot return here
            }
            cb(null, {
                'id'        : account.id,
                'name'      : account.name,
                'password'  : account.password,
                'roles'     : account.roles
            });
        } catch (e) {
            console.log('Lookup error for user',id);
            cb(true);
        }
    });
}

A: The only workaround that i could come up with for my problem was to prevent the response being sent twice.
The problem i think is that when the passport.authenticate() function encounters the error ENOTFOUND it calls the callback again as i believe that is not handled properly. So to overcome this issue i just put a check to see if the headers were already sent and if yes then just return from the function else send a response. Below is my code, please comment on it if you need any assistance.
app.post('/ldapLogin', function (req, res, next) {
passport.authenticate('ldapauth', { session: false }, function (err, user, info) {

    let resObj = {}
    let resStatus
    if (err || !user) {
        if (err && (err.code == 'ETIMEDOUT' || err.code == 'ENOTFOUND')) {
            resStatus = res.status(400)
            resObj['success'] = false
            resObj['message'] = 'Could not reach Ldap Server'

        }else if(!user){
            console.log("Authentication Failed or not a valid user")
            resStatus = res.status(400)
            resObj['success'] = false
            resObj['message'] = 'Authentication Failed'
        }
    }else{
        resStatus = res
        let roles = (user.sAMAccountName == 'xxxxx')?['readWrite']:['readOnly']
        resObj['success'] = true
        resObj['gid'] = user.sAMAccountName
        resObj['name'] = user.name
        resObj['token'] = jwt.sign({ sub: user.sAMAccountName, roles: roles, loggedInUsername: user.name }, config.secret)
    }
    if(res.headersSent)
    return
    return resStatus.send(resObj);
})(req, res, next)
})

A: I had this problem as well and solved by changing the error handler middleware to force stopping request's progression. in fact, the error handler middleware must stop the request.
the wring error handler middleware:
export const errorHandler = (err, req, res, next) => {
    console.error(err);
    res.status(400).send({errors: [{message: 'Something went wrong.'}]});
};

the correct error handler middleware:
export const errorHandler = (err, req, res, next) => {
    console.error(err);
    return res.status(400).send({errors: [{message: 'Something went wrong.'}]});
};

the differenc is just a simple "return" keyword :)


text:
Q: Sum of binomial distributed random variables Let $X \sim Bi(n,p), Y \sim Bi(m,p)$. "Visual arguments" suggest that $X+Y \sim Bi(m+n,p)$. However, I am unable to prove that.
Using the definition I can reduce the problem to
$$\sum_{i=0}^k \binom{m}{i} \binom{n}{k-i} = \binom{n+m}{k},$$
which is – according to Wolfram Alpha – correct. But I have no idea for a proof here as well. (I only tried to use the definition of the binomial coefficients, but that did not help me.)
So: How to prove the statement above?
Thanks in advance, Keba.

A: This is known as Vandermonde's identity.
A combinatorial interpretation of the identity follows:  Suppose you have $n$ boys and $m$ girls.  The RHS counts the number of ways to choose $k$ children out of the total $n+m$ children regardless of sex; the LHS counts the number of ways to choose $i$ girls and $k-i$ boys for each $i = 0, 1, 2, \ldots, k$.  Obviously, the two are equal.


text:
Q: setImageResource undefined in java I have an ImageView initialized with an image. Then in java when process accept some condition I want to change the picture. I made this code
if(i==1)
{
    ImageView imgv = (ImageView) findViewById(R.id.imageView2);
    imgv=setImageResource(R.drawable.player1);
}

But I get an error in java saying the method setImageResource() is undefined in the type javaFile. What does that mean? How to overcome this error? Is there any better way for changing an image like the way I wanted?

A: you should be calling imgv.setImageResource(R.drawable.player1);, note the period character, you have used an equals character.

A: Try:
imgv.setImageResource(R.drawable.player1);

Instead of:
imgv=setImageResource(R.drawable.player1);

Because setImageResource is a method of the ImageView.


text:
Q: How to get sorted result within INNER JOIN on joined table I'm trying to get results from a join of 2 tables. Typically, not an issue, but I'm banging my head on this one. Basically, table1 (sales_dealers) is joined with table2 (sales_dealerEvents). Normally, easy-peasy. The problem is that I want to only get records from table2 if there are only 2 events (why I added the HAVING). But I need to get the value of the second event. With my query now, I can only get the value of the first event. It's like I need an ORDER BY EventID DESC on the joined table. It giving me ASC by default with this query.
Here is my query:
SELECT e.EventAction
     , d.DealerID
     , d.AgentID
     , d.DealerName
     , d.Email
     , SUBSTRING_INDEX(d.PrimaryContactName, ' ', 1) AS FirstName
     , d.State
     , COUNT(e.EventID) AS EventCount
  FROM sales_dealers d
  JOIN sales_dealerEvents e
    ON d.DealerID = e.DealerID
 WHERE d.AgentID = 1
   AND d.StatusID = 3
   AND d.Email REGEXP '^[a-zA-Z0-9][a-zA-Z0-9._-]*@[a-zA-Z0-9][a-zA-Z0-9._-]*\\.[a-zA-Z]{2,4}$'
 GROUP
    BY d.DealerID
HAVING COUNT(e.EventID) = 2
 ORDER
    BY e.EventID DESC

Here is my Schema for the two tables (mysql version 5.7.27 )
sales_dealers
------------------
DealerID (int PK)
StatusID (int)
AgentID (int)
DealerName (varchar)
Email (varchar)
PrimaryContactName (varchar)
State (varchar)

sales_dealerEvents
------------------
EventID (int PK)
DealerID (FK)
AgentID (FK)
EventDateTime (datetime)
EventAction (longtext)

Here is sample data. Currently, the above query returns this:
Prospect Entry  784     1   Dealer Name One     sales@dealer.com            CA  2
Prospect Entry  782     1   Some other dealer   hello@dealer.com            MT  2
Prospect Entry  781     1   Dealer Store        contact@dealer.com          OK  2

I would like it to return this:
Initial Contact 784     1   Dealer One      sales@dealer.com            CA  2
Initial Contact 782     1   Some other dealer   hello@dealer.com            MT  2
Initial Contact 781     1   Dealer Store        contact@dealer.com          OK  2

Here is the same sample data of but showing the relationship of the one to many in sales_dealerEvents
sales_dealer
    784 Dealer Name One

sales_dealerEvents
    1000    784 1 Prospect Entry    2020-06-02 01:00:00
    1010    784 1 Initial Contact   2020-07-03 01:00:00

I'm feeling I might have to do this in a subquery to sort the event so the second event is first. Not sure. I might also need to match criteria of that second event too.
UPDATE - Here is my SQL fiddle
http://sqlfiddle.com/#!9/ef6f2c/2
As you can see with the fiddle.. all event records returned are 'prospect entry'.. which were the first entries for 'events' for those. Each have 2. The second is 'Initial Contact'. Their date and EventID is after the 'prospect entry'.

A: Hope the below query helps and you can see the demo here: http://sqlfiddle.com/#!9/ef6f2c/37/0
SELECT
   EventAction,
   DealerID,
   AgentID,
   DealerName,
   Email,
   FirstName,
   State,
   EventID
from
   (
      SELECT
         e.EventAction,
         d.DealerID,
         d.AgentID,
         d.DealerName,
         d.Email,
         SUBSTRING_INDEX(d.PrimaryContactName, ' ', 1) AS FirstName,
         d.State,
         e.EventID as EventID
      FROM
         sales_dealers d
         JOIN
            sales_dealerEvents e
            ON d.DealerID = e.DealerID
      WHERE
         d.AgentID = 1
         AND d.StatusID = 3
         AND d.Email REGEXP '^[a-zA-Z0-9][a-zA-Z0-9._-]*@[a-zA-Z0-9][a-zA-Z0-9._-]*\\.[a-zA-Z]{2,4}$'
      ORDER BY
         e.EventID DESC
   )
   a
GROUP BY
   DealerID
HAVING
   COUNT(EventID) = 2

A: This sounds like you want window functions:
select . . .
from sales_dealers d join
     (select e.*,
             row_number() over (partition by e.DealerID order by e.EventDateTime) as seqnum
      from sales_dealerEvents e
     ) e
     on e.DealerID = d.DealerID and e.seqnum = 2
where . . .

Note this gets data from the second event even if there are more than two events.  That seems consistent with the question, but it is easy enough to use count(*) as a window function to do further filtering.


text:
Q: pygame moving fatser in one direction than another I'm currently making a tile based platformer and programming the "engine" for it. I am pretty far, but lately noticed that the player is moving faster going left than right for no apparent reason. I check for the velocity but it is as intended limited bewteen -5.5 and 5.5. When checking for the distance bewteen the last position and current position it's visible though. When moving right the console outputs the delta position to be about 3 ("about" because I made the movement depending on the delta time so it varies when the pc is running faster), but when moving left it says the difference is -4. Is that a common bug? I tried limiting the negative velocity to a lower level when negative but that is a very janky solution and not very percise.
I know that pythons float numbers are a bit weird but I can't explain to myself why this happening.
Here is the movement code (note that this is not the whole script, but where the bug happens).
Also, limit(__value, __min, __max) is a function I made myself for as you can tell limiting a value between two values
            self.state = "stand"

            # move animation
            if math.fabs(self.vel.x) > 0.1:
                temp = math.fabs(self.vel.x) / 30
                if temp < 0.4:
                    temp = 0.4
                self.state = "walk" + str(int(math.fmod(int(self.walk_time * temp), 2)))
                self.walk_time += dt
            else:
                self.walk_time = 0

            # gravity
            if not self.is_grounded:
                self.vel.y += (self.grav * (1 + float(input["down"]))) * dt
            self.vel.y = limit(self.vel.y, -21, 21)

            # set acc to input
            self.acc.x = (float(input["right"]) - float(input["left"])) * float(not input["down"])
            if input["right"] and not input["left"]:
                self.dir = 1
            if input["left"] and not input["right"]:
                self.dir = -1

            # apply acc
            self.vel.x += (self.acc.x / 2)
            self.vel.x = limit(self.vel.x, -self.speed, self.speed)

            # handle in_air
            if self.is_grounded:
                self.in_air = 0
            else:
                self.in_air += 1 * dt

            # handle jumping
            if self.in_air <= 3:
                if input["down"] and self.in_air <= 3:
                    self.state = "duck"
                self.fall_time = 0
                # apply friction
                if self.acc.x == 0:
                    if self.vel.x > 0:
                        self.vel.x -= self.fric * dt
                        if self.vel.x <= self.fric:
                            self.vel.x = 0
                    if self.vel.x < 0:
                        self.vel.x += self.fric * dt
                        if self.vel.x >= -self.fric:
                            self.vel.x = 0
            else:
                if self.vel.y < 0:
                    self.state = "jump"
                elif self.vel.y > 1:
                    self.state = "fall" + str(int(math.fmod(int(self.fall_time / 30), 2)))
                self.fall_time += 1 * dt

            if self.is_grounded:
                self.can_jump = True
            else:
                if input["up_up"]:
                    self.can_jump = False

            # jumping
            if self.jumping == 0 and input["up"]:
                if self.in_air <= 3:
                    self.jumping += 1 * dt
            elif (0 < self.jumping <= 8) and input["up"]:
                self.jumping += 1 * dt
            else:
                self.jumping = 0
            # jump
            if input["up"] and (self.in_air <= 3 or 0 < self.jumping <= 6):
                self.vel.y = -8
                self.state = "jump"

        # collision
        self.is_grounded = False
        self.is_ceiled = False
        self.is_walled = False

        self.rect.x += self.vel.x * dt
        colls = self.collision(tiles)
        for tile in colls:
            if self.vel.x > 0:
                self.rect.right = tile.left
                self.vel.x = 0
            if self.vel.x < 0:
                self.rect.left = tile.right
                self.vel.x = 0
            # check vars
            if tile.right == self.rect.left or tile.left == self.rect.right:
                self.is_walled = True

        self.rect.y += self.vel.y * dt
        colls = self.collision(tiles)
        for tile in colls:
            if self.vel.y > 0:
                self.rect.bottom = tile.top
                self.vel.y = 0
            if self.vel.y < 0:
                self.rect.top = tile.bottom
                self.vel.y = 0

            # check vars
            if tile.top == self.rect.bottom:
                self.is_grounded = True
                self.vel.y = 0
            if tile.bottom == self.rect.top:
                self.is_ceiled = True
                self.jumping = 99

        print((self.rect.x - self.last_pos[0], self.rect.y - self.last_pos[1]))
        self.last_pos = [self.rect.x, self.rect.y]

Every help is appreciated

A: This is an accuracy problem. Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.

The coordinates for Rect objects are all integers. [...]

The fraction part of the coordinates gets lost when the velocity is add to the Rect object:

self.rect.x += self.vel.x * dt

self.rect.y += self.vel.y * dt

Therefore the object moves "faster" to the left and top than to the right an bottom.
Add attributes with floating point accuracy for the position of the object
self.x = ...
slef.y = ...

Add the velocity to this attributes. round the position and assign it to the pygame.Rect object:
self.x += self.vel.x * dt
self.rect.x = round(self.x)

self.y += self.vel.y * dt
self.rect.y = round(self.y)


text:
Q: logic for slider dynamic images loop with php I am working on bootstrap carousel slider. I am trying to load the dynamic images in the slider with PHP array. I have 4(count is not fixed) image paths in PHP array.
My HTML code below:

        <img src="<?=base_url()?>images/product-details/similar1.jpg" alt="">
        <img src="<?=base_url()?>images/product-details/similar2.jpg" alt="">
        <img src="<?=base_url()?>images/product-details/similar3.jpg" alt="">

        <img src="<?=base_url()?>images/product-details/similar1.jpg" alt="">
        <img src="<?=base_url()?>images/product-details/similar2.jpg" alt="">
        <img src="<?=base_url()?>images/product-details/similar3.jpg" alt="">

        <img src="<?=base_url()?>images/product-details/similar1.jpg" alt="">
        <img src="<?=base_url()?>images/product-details/similar2.jpg" alt="">
        <img src="<?=base_url()?>images/product-details/similar3.jpg" alt="">

I need a logic to loop the array and load my images in the html.
My expected HTML like

        <img src="<?=base_url()?>images/product-details/similar1.jpg" alt="">
        <img src="<?=base_url()?>images/product-details/similar2.jpg" alt="">
        <img src="<?=base_url()?>images/product-details/similar3.jpg" alt="">

        <img src="<?=base_url()?>images/product-details/similar1.jpg" alt="">

please help me

A: do like this

        <?php
        $count = 0;
        foreach ($images as $key => $image)
        {
            if ($count == 2)
            {
            ?>

                <?php
                $count = 0;
            }
            ?>
                <img src="<?=base_url()?>images/product-details/<?= $image?>" alt="">
            <?php
            $count += 1;
        }
        ?>

What you should do in above code

*

*$images should be your array name

*<?=base_url()?>images/product-details/<?= $image?> add the correct path here

What happens in above code
Each and every time  tab with print inside  and whenever it meets if == 2 (count is 3) it will add new
 and make count to 0

A: $count = 1;
 foreach( $images as $img )
 {
   if ($count%4 == 1)
  {
     echo '
';

  }
  echo '<img src="<?=base_url()?>images/product-details/similar1.jpg" alt="">';

  if ($count%4 == 0)
  {
          echo "
";
  }
   $count++;
 }
  if ($count%4 != 1) echo "
";


text:
Q: word-break не переносит текст Всем привет,
Нужно справа от чекбокса вывести текст и он выводится, но проблема в том, что текст длинный и не вмещяясь
в одну строку, ntrcn переносится он переносится на другую строку, но и чекбоксы уходят вверх
http://www.codeply.com/go/MWSsqNXrou
Я прописал    break-word для класса с определением параграфа :
p.notice_p{
    text-align: left;
    text-indent: 0px;
    margin-bottom: 5px;
    font-size: 14px;
    word-wrap: break-word;

    border: 1px dotted navy;
}

но это не помогло.
А как правильно ?
Спасибо!

A: Вам следует указать ширину блока .hostel2_data_block или для параграфов (p.notice_p), в которых отображается текст, который нужно перенести. Таким образом, когда текст не поместится в параграф, он будет перенес на следующую строку. Сейчас перенос не работает, так как ширина параграфов ничем не ограничена.


text:
Q: Postfix not starting in gitlab docker container I am trying to get postfix running on the gitlab/gitlab-ce:9.3.6-ce.0 docker container and it doesn't seem to work startup
I get the following error:
postfix start
postfix/postfix-script: starting the Postfix mail system
postfix/postfix-script: fatal: mail system startup failed

My config looks like:
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
compatibility_level = 2
inet_interfaces = all
inet_protocols = all
mailbox_size_limit = 0
mydestination = $myhostname, ipayroll.co.nz, ip-10-136-28-218.ap-
southeast-2.compute.internal, localhost.ap-southeast-2.compute.internal, localhost
myhostname = ip-10-136-28-218.ap-southeast-2.compute.internal
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
myorigin = /etc/mailname
readme_directory = no
recipient_delimiter = +
relayhost =
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated
defer_unauth_destination
smtpd_tls_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file = /etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_session_cache_database =
btree:${data_directory}/smtpd_scache
smtpd_use_tls = yes

and here is the os of the image:
NAME="Ubuntu"
VERSION="16.04.2 LTS (Xenial Xerus)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 16.04.2 LTS"
VERSION_ID="16.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
VERSION_CODENAME=xenial
UBUNTU_CODENAME=xenial

I believe this is an issue with the container as I have got postfix going before, on other containers. I just can't figure it out on this one. I have tried many methods of installing postfix but this is the general one I use.
apt-get update && apt-get install postfix

A: The problem here was I was running my commands using the wrong shell, I was using /bin/bash and not /bin/sh. Once I tried doing this through the dockerfile and starting via an entrypoint all went well.


text:
Q: Angular 5 reactive forms custom control inconsistent validation state on conditionally add/remove from DOM Issue related to reactive forms, Angular v4.3.
Multiselect-dropdown.component.ts
Implemented ControlValueAccessor, Validator.
Added validate interface method as below
validate(ctrl: FormControl) {
  return this.selections.length > 0 ? null : {required: "no selection"} : null;
}

Reactive Forms
My form is divided into multiple sections with a let nav menu. All form is constructed in one single page and on based on menu selection, showing the part of the form using *ngIf.
I have added Multiselect-dropdown control in first section of the form.
First time form loads with first section selected by default.
All works good till here.
Now i have clicked the dropdown but not selected any item which leave the dropdown empty. Here since i touched the control, it shows required validation error. Now leaving the error, i switch to another section and come back to the first section. Now it still shows the required validation error which is correct.
Now the issue is, here if select an item from dropdown, the validate() method returns null but the required validation error doesn't go off.
After i debug, i found that since *ngIf recreate the component, the new component is not the one the FormControl created in formGroup initially.
A workaround i used is remove the FormControl from formGroup and recreate it again when switch to that section. But this is not the correct solution.
I want to understand this behaviour. I need any help that can solve or understand this issue
Here is the link
https://github.com/angular/angular/issues/26792
where explained with POC and steps to reproduce
Thanks
Sankara


text:
Q: Lagrange Interpolation in java using BigInteger I am trying to find a function to perform Lagrange Interpolation in java.  I have 3 (x,y) pairs, where x and y are BigInteger objects, and would like to use some interpolation function to determine f(0) for the polynomial f used to calculate my x,y these pairs.  Something like this seems perfect, except that this class doesn't seem to actually belong to a package I can import: http://nssl.eew.technion.ac.il/files/Projects/thresholddsaimporvement/doc/javadoc/Lagrange.html
Forgive me if my question is naive, any help I can get would really be appreciated.

A: A similar class seems to be in Apache Commons Math. This is probably going to be much more reliable than what you found.
http://commons.apache.org/math/apidocs/org/apache/commons/math3/analysis/polynomials/PolynomialFunctionLagrangeForm.html
It would appear that you construct it with PolynomialFunctionLagrangeForm(double[] x, double[] y), then call value(0) to get the value at x = 0.


text:
Q: Dealing with dates in mysql? EDIT: changed the whole question sorry, im trying to deal with the mysql DATETIME values,
this is my mysql query:
$result="SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m. m.dt
FROM relationships r, notes m, user u
WHERE m.user_id = r.leader
AND r.leader = u.user_id
AND r.listener ='".$_SESSION['user_id']."'
UNION
SELECT username, picture, id, user_note, reply_id, reply_name, dt
FROM user u, notes b
WHERE u.user_id = b.user_id
AND b.user_id = '".$_SESSION['user_id']."'
AND dt < '".$lastmsg."'
ORDER BY dt DESC
LIMIT 10 ";

im trying to find rows from this query older than '$lastmsg' and not $lastmsg itself, i thought about using less than but not equal to operator! im not sure if that was stupid!!!
P.S the query works, but its retriving wrong information!!

A: Shouldn't the query fragment that looks at the date be
AND dt > '".$lastmsg."'

?

A: You are only restricting the date on the second half of your UNION.  Try this instead:
SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt
FROM relationships r, notes m, user u
WHERE m.user_id = r.leader
AND r.leader = u.user_id
AND r.listener ='".$_SESSION['user_id']."'
AND m.dt < '".$lastmsg."'
UNION
SELECT username, picture, id, user_note, reply_id, reply_name, dt
FROM user u, notes b
WHERE u.user_id = b.user_id
AND b.user_id = '".$_SESSION['user_id']."'
AND dt < '".$lastmsg."'
ORDER BY dt DESC
LIMIT 10


text:
Q: Select all customers loyal to one company? I've got tables:
TABLE     | COLUMNS
----------+----------------------------------
CUSTOMER  |  C_ID, C_NAME, C_ADDRESS
SHOP      |  S_ID, S_NAME, S_ADDRESS, S_COMPANY
ORDER     |  S_ID, C_ID, O_DATE

I want to select id of all customers who made order only from shops of one company - 'Samsung' ('LG', 'HP', ... doesn't really matter, it's dynamic).
I've come only with one solution, but I consider it ugly:
( SELECT DISTINCT c_id FROM order JOIN shop USING(s_id) WHERE s_company = "Samsung" )
EXCEPT
( SELECT DISTINCT c_id FROM order JOIN shop USING(s_id) WHERE s_company != "Samsung" );

Same SQL queries, but reversed operator. Isn't there any aggregate method which solves such query better?
I mean, there could be millions of orders(I don't really have orders, I've got something that occurs more often).
Is it efficient to select thousands of orders and then compare them to hundreds of thousands orders which have different company? I know, that it compares sorted things, so it's O( m + n + sort(n) + sort(m) ). But that's still large for millions of records, or isn't?
And one more question. How could I select all customer values (name, address). How can I join them, can I do just
SELECT CUSTOMER.* FROM CUSTOMER JOIN ( (SELECT...) EXCEPT (SELECT...) ) USING (C_ID);

Disclaimer: This question ain't homework. It's preparation for the exam and desire to things more effective. My solution would be accepted at exam, but I like effective programming.

A: I like to approach this type of question using group by and a having clause.  You can get the list of customers using:
select o.c_id
from orders o join
     shops s
     on o.s_id = o.s_id
group by c_id
having min(s.s_company) = max(s.s_company);

If you care about the particular company, then:
having min(s.s_company) = max(s.s_company) and
       max(s.s_company) = 'Samsung'

If you want full customer information, you can join the customers table back in.
Whether this works better than the except version is something that would have to be tested on your system.

A: How about a query that uses no aggregate functions like Min and Max?
select  C_ID, S_ID
from    shop
group by C_ID, S_ID;

Now we have a distinct list of customers and all the companies they shopped at. The loyal customers will be the ones who only appear once in the list.
select  C_ID
from    Q1
group by C_ID
having count(*) = 1;

Join back to the first query to get the company id:
with
Q1 as(
  select  C_ID, S_ID
  from    shop
  group by C_ID, S_ID
),
Q2 as(
  select  C_ID
  from    Q1
  group by C_ID
  having count(*) = 1
)
select  Q1.C_ID, Q1.S_ID
from    Q1
join    Q2
    on  Q2.C_ID = Q1.C_ID;

Now you have a list of loyal customers and the one company each is loyal to.