问:
How do I hide navbar when i select login or signup in react?
I am trying to hide the Menu component when I select log in my app. I am working with react hooks and I have no idea how to do it.

My main looks like this :

```<code> <div>
        <Menu/>
        <Router>
            {
                domainList === "error" ?
                    (
                        <ErrorMessage
                            message="Error"
                        />
                    )
                    :
                    Boolean(domainList) === true ?
                        (
                            <Main
                                endpoint={endpoint}
                                callbackReFetchDomains={reFetchDomains}
                                domainList={domainList}
                                hasDomainListError={hasDomainListError}
                                appendDomainList={appendDomainList}
                                changeDomainList={changeDomainList}
                            />
                        )
                        :
                        (
                            <LoadingSpinner/>
                        )
            }
        </Router>
    </div>
</code>```

My main looks like this :

```<code><>
        <div>
            {/*Switch will only render the first matched <Route/> child.*/}
            <Menu/>
            <Switch>
                <Route path="/topics">
                    <ExampleComponentStructure/>
                </Route>
                <Route path="/login">
                    <Login/>
                </Route>
                <Route path="/domains">
                    <DomainList
                        endpoint={props.endpoint}
                        callbackReFetchDomains={props.callbackReFetchDomains}
                        domainList={props.domainList}
                        hasDomainListError={props.hasDomainListError}
                        appendDomainList={props.appendDomainList}
                        changeDomainList={props.changeDomainList}
                    />
                </Route>
                <Route path="/signup">
                    <Signup/>
                </Route>
                <Route path="/users">
                    <UserMaintainList
                        endpoint={props.endpoint}
                    />
                </Route>
                <Route path="/">
                    <StickerList
                        endpoint={props.endpoint}
                        callbackReFetchDomains={props.callbackReFetchDomains}
                        domainList={props.domainList}
                        hasDomainListError={props.hasDomainListError}
                        changeDomainList={props.changeDomainList}
                    />
                </Route>

            </Switch>
        </div>
    </>
</code>```

I know that the code is not clean. I am just starting with react and need some help doing this login screen. Thank you.

答:
If i understood correct, you want to hide component Menu (is it navbar?). First you can check url you are in, by creating some flag, for example:

```<code>const isLogin = props.match.path === "/login"
</code>```

And then just render component if it is false

```<code>{!isLogin && <Menu/>}
</code>```

Body:
I am trying to hide the Menu component when I select log in my app. I am working with react hooks and I have no idea how to do it.

My main looks like this :

        <Menu/>
        <Router>
            {
                domainList === "error" ?
                    (
                        <ErrorMessage
                            message="Error"
                        />
                    )
                    :
                    Boolean(domainList) === true ?
                        (

                        )
                        :
                        (
                            <LoadingSpinner/>
                        )
            }
        </Router>

My main looks like this :

<>

            {/*Switch will only render the first matched <Route/> child.*/}
            <Menu/>
            <Switch>
                <Route path="/topics">
                    <ExampleComponentStructure/>
                </Route>
                <Route path="/login">
                    <Login/>
                </Route>
                <Route path="/domains">
                    <DomainList
                        endpoint={props.endpoint}
                        callbackReFetchDomains={props.callbackReFetchDomains}
                        domainList={props.domainList}
                        hasDomainListError={props.hasDomainListError}
                        appendDomainList={props.appendDomainList}
                        changeDomainList={props.changeDomainList}
                    />
                </Route>
                <Route path="/signup">
                    <Signup/>
                </Route>
                <Route path="/users">
                    <UserMaintainList
                        endpoint={props.endpoint}
                    />
                </Route>
                <Route path="/">
                    <StickerList
                        endpoint={props.endpoint}
                        callbackReFetchDomains={props.callbackReFetchDomains}
                        domainList={props.domainList}
                        hasDomainListError={props.hasDomainListError}
                        changeDomainList={props.changeDomainList}
                    />
                </Route>

            </Switch>

    </>

I know that the code is not clean. I am just starting with react and need some help doing this login screen. Thank you.

Body:
If i understood correct, you want to hide component Menu (is it navbar?). First you can check url you are in, by creating some flag, for example:

const isLogin = props.match.path === "/login"

And then just render component if it is false

{!isLogin && <Menu/>}


来源: stackexchange

问:
Displaying varbinary(max) from database using content disposition
I am making a file uploader using HTML tags. I have a column in my table Data which has a datatype varbinary(max) so files are successfully being saved in the database in binary format.

I am also displaying the list of files in a grid with an icon next to it for viewing the file. When I click on that icon it should read my data which is in binary format and then view that file.

My code for upload at code behind is:

```<code>    protected void Upload(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
        string contentType = FileUpload1.PostedFile.ContentType;

        using (Stream fs = FileUpload1.PostedFile.InputStream)
        {
            using (BinaryReader br = new BinaryReader(fs))
            {
                byte[] bytes = br.ReadBytes((Int32)fs.Length);
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string query = "insert into FileUploader2 values (@Name, @ContentType, @Data)";
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                        cmd.Parameters.AddWithValue("@Name", filename);
                        cmd.Parameters.AddWithValue("@ContentType", contentType);
                        cmd.Parameters.AddWithValue("@Data", bytes);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        Context.Response.Write("Uploaded Successfully!");
                    }
                }
            }
        }

        Response.Redirect(Request.Url.AbsoluteUri);
    }
</code>```

I am also able to successfully read my data back. The code for which is as follows:

```<code>    [System.Web.Services.WebMethod]
    public static void ShowDocument()
    {

        string filename = string.Empty;
        string contentType = string.Empty;
        byte[] bytes = null;
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            con.Open();

            using (SqlCommand com = new SqlCommand("SELECT * FROM FileUploader2", con))
            {
                using (SqlDataReader reader = com.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        filename = (string)reader["Name"];
                        contentType = (string)reader["ContentType"];
                        bytes = (byte[])reader["Data"];
                    }
                }
            }
        }

        System.Web.HttpContext.Current.Response.ContentType = contentType;
        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;
        filename=" + filename);
        System.Web.HttpContext.Current.Response.OutputStream.Write(bytes, 0, bytes.Length);
        System.Web.HttpContext.Current.Response.Flush();
}
</code>```

Now after reading, it should also display the contents of the file or a link to download the file since I'm using the attachment. But it does nothing. It is giving me the correct values after debugging. But why it is not displaying the file? What am I doing wrong? As far as I know, since I am using content-disposition, it should display on its own.

答:
I think you're missing the part...

```<code>    string strFileName = "FileName";//Here you have to set the File Name...

    if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "pdf")
    {
        Response.ContentType = "application/PDF";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "doc")
    {
        Response.ContentType = "application/msword";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "docx")
    {
        Response.ContentType = "application/msword";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "xls")
    {
        Response.ContentType = "application/vnd.ms-excel";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "xlsx")
    {
        Response.ContentType = "application/vnd.ms-excel";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "ppt")
    {
        Response.ContentType = "application/vnd.ms-powerpoint";
    }
    else if (strFileName.Substring(strFileName.IndexOf('.') + 1).ToLower() == "txt")
    {
        Response.ContentType = "text/plain";
    }
    else
    {
        Response.ContentType = "text/plain";
    }

    System.IO.FileInfo file = new System.IO.FileInfo(strFileName);

    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
    Response.AddHeader("Content-Length", file.Length.ToString());

    Response.WriteFile(file.FullName);
    Response.End();
</code>```

After edit, if your data is in bytes, try last time:

```<code>public void byteArrayToImage(byte[] bytes)
    {
        if (byteArray != null)
        {
            MemoryStream ms = new MemoryStream(bytes);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms, false,  false);

            img.Save(Server.MapPath("Photo/image.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);//Set Your image Location...
            ms.Close();
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am making a file uploader using HTML tags. I have a column in my table Data which has a datatype varbinary(max) so files are successfully being saved in the database in binary format.

I am also displaying the list of files in a grid with an icon next to it for viewing the file. When I click on that icon it should read my data which is in binary format and then view that file.

My code for upload at code behind is:

    protected void Upload(object sender, EventArgs e)
    {
        string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
        string contentType = FileUpload1.PostedFile.ContentType;

        using (Stream fs = FileUpload1.PostedFile.InputStream)
        {
            using (BinaryReader br = new BinaryReader(fs))
            {
                byte[] bytes = br.ReadBytes((Int32)fs.Length);
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string query = "insert into FileUploader2 values (@Name, @ContentType, @Data)";
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                        cmd.Parameters.AddWithValue("@Name", filename);
                        cmd.Parameters.AddWithValue("@ContentType", contentType);
                        cmd.Parameters.AddWithValue("@Data", bytes);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        Context.Response.Write("Uploaded Successfully!");
                    }
                }
            }
        }

        Response.Redirect(Request.Url.AbsoluteUri);
    }

I am also able to successfully read my data back. The code for which is as follows:

    [System.Web.Services.WebMethod]
    public static void ShowDocument()
    {

        string filename = string.Empty;
        string contentType = string.Empty;
        byte[] bytes = null;
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            con.Open();

            using (SqlCommand com = new SqlCommand("SELECT * FROM FileUploader2", con))
            {
                using (SqlDataReader reader = com.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        filename = (string)reader["Name"];
                        contentType = (string)reader["ContentType"];
                        bytes = (byte[])reader["Data"];
                    }
                }
            }
        }

        System.Web.HttpContext.Current.Response.ContentType = contentType;
        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;
        filename=" + filename);
        System.Web.HttpContext.Current.Response.OutputStream.Write(bytes, 0, bytes.Length);
        System.Web.HttpContext.Current.Response.Flush();
}

Now after reading, it should also display the contents of the file or a link to download the file since I'm using the attachment. But it does nothing. It is giving me the correct values after debugging. But why it is not displaying the file? What am I doing wrong? As far as I know, since I am using content-disposition, it should display on its own.

Body:
I think you're missing the part...

    string strFileName = "FileName";//Here you have to set the File Name...

    if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "pdf")
    {
        Response.ContentType = "application/PDF";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "doc")
    {
        Response.ContentType = "application/msword";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "docx")
    {
        Response.ContentType = "application/msword";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "xls")
    {
        Response.ContentType = "application/vnd.ms-excel";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "xlsx")
    {
        Response.ContentType = "application/vnd.ms-excel";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "ppt")
    {
        Response.ContentType = "application/vnd.ms-powerpoint";
    }
    else if (strFileName.Substring(strFileName.IndexOf('.') + 1).ToLower() == "txt")
    {
        Response.ContentType = "text/plain";
    }
    else
    {
        Response.ContentType = "text/plain";
    }

    System.IO.FileInfo file = new System.IO.FileInfo(strFileName);

    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
    Response.AddHeader("Content-Length", file.Length.ToString());

    Response.WriteFile(file.FullName);
    Response.End();

After edit, if your data is in bytes, try last time:

public void byteArrayToImage(byte[] bytes)
    {
        if (byteArray != null)
        {
            MemoryStream ms = new MemoryStream(bytes);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms, false,  false);

            img.Save(Server.MapPath("Photo/image.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);//Set Your image Location...
            ms.Close();
        }
    }


问:
How to install PHP Xdebug in Eclipse on Windows?
I have a PHP file and I want to debug that file in Eclipse. I have heard about Xdebug as the best way to debug a PHP file in Eclipse.

What are the steps needed to be able to debug PHP files in Eclipse? I am using Windows OS.

答:
Download PHP for eclipse (PLUGIN eclipse)

Use update URL
https://download.eclipse.org/tools/pdt/updates/7.0

Download XAMPP for windows and install it
https://www.apachefriends.org/es/download.html

Now you can follow alternative instructions here or continue to the next point where i explain what you need to do.
http://robsnotebook.com/php_debugger_pdt_xdebug

After installing XAMPP you should start Apache

Download Xdebug e.g http://xdebug.org/files/php_xdebug-2.9.2-7.2-vc15-x86_64.dll  and check if it is correctly installed. Follow next instructions

```<code>1. Download php_xdebug-2.9.2-7.2-vc15-x86_64.dll.
2. Move the downloaded file to C:\xampp\php\ext
3. Update C:\xampp\php\php.ini and change the lines

    [XDebug]
    ;; Only Zend OR (!) XDebug
    ; zend_extension_ts="C:\xampp\php\ext\php_xdebug.dll"
    ; Modify the filename below to reflect the .dll version of your xdebug
    zend_extension = C:\xampp\php\ext\php_xdebug-2.9.2-7.2-vc15-x86_64.dll
    xdebug.remote_enable=true
    xdebug.remote_host=127.0.0.1  ; if debugging on remote server,
                              ; put client IP here
    xdebug.remote_port=9000
    xdebug.remote_handler=dbgp
    xdebug.profiler_enable=0
    xdebug.profiler_output_dir="C:\xampp\tmp"

4. Restart the XAMPP webserver in your XAMPP control Panel
</code>```

Comment out any Zend Optimizer in php.ini because it is not compatible with XDebug. For example, all of this should be commented out (using “;”):
[Zend]

```<code>; zend_extension_ts = "C:\xampp\php\zendOptimizer\lib\ZendExtensionManager.dll"
; zend_extension_manager.optimizer_ts = "C:\xampp\php\zendOptimizer\lib\Optimizer"
; zend_optimizer.enable_loader = 0
; zend_optimizer.optimization_level=15
;zend_optimizer.license_path =
</code>```

Check that it is working with phpinfo. You go to your browser and go to:
http://localhost/dashboard/phpinfo.php
Or create in your c:/xampp/htdocs
A file calling phpinfo e.g.
http://localhost/phpinfocall.php

Configuration PHP debug in eclipse
You can create a PHP project. That project should be pointint to C:\xampp\htdocs

The C:\xampp\htdocs is the localserver root folder in xampp. Inside you can create subfolders.

Configure PHP Preference of eclipse
Connect eclipse with php parser of xampp

Configure this and check that xdebug is detected in eclipse from xampp

How to create a debug view from a PHP file in your project

Debug view configuration below,

Lastly, you will see in the debug perspective, that the debugger stop automatically on the first line of your php file.

Body:
Download PHP for eclipse (PLUGIN eclipse)

Use update URL
https://download.eclipse.org/tools/pdt/updates/7.0

Download XAMPP for windows and install it
https://www.apachefriends.org/es/download.html

Now you can follow alternative instructions here or continue to the next point where i explain what you need to do.
http://robsnotebook.com/php_debugger_pdt_xdebug

After installing XAMPP you should start Apache

Download Xdebug e.g http://xdebug.org/files/php_xdebug-2.9.2-7.2-vc15-x86_64.dll  and check if it is correctly installed. Follow next instructions

1. Download php_xdebug-2.9.2-7.2-vc15-x86_64.dll.
2. Move the downloaded file to C:\xampp\php\ext
3. Update C:\xampp\php\php.ini and change the lines

    [XDebug]
    ;; Only Zend OR (!) XDebug
    ; zend_extension_ts="C:\xampp\php\ext\php_xdebug.dll"
    ; Modify the filename below to reflect the .dll version of your xdebug
    zend_extension = C:\xampp\php\ext\php_xdebug-2.9.2-7.2-vc15-x86_64.dll
    xdebug.remote_enable=true
    xdebug.remote_host=127.0.0.1  ; if debugging on remote server,
                              ; put client IP here
    xdebug.remote_port=9000
    xdebug.remote_handler=dbgp
    xdebug.profiler_enable=0
    xdebug.profiler_output_dir="C:\xampp\tmp"

4. Restart the XAMPP webserver in your XAMPP control Panel

Comment out any Zend Optimizer in php.ini because it is not compatible with XDebug. For example, all of this should be commented out (using “;”):
[Zend]

; zend_extension_ts = "C:\xampp\php\zendOptimizer\lib\ZendExtensionManager.dll"
; zend_extension_manager.optimizer_ts = "C:\xampp\php\zendOptimizer\lib\Optimizer"
; zend_optimizer.enable_loader = 0
; zend_optimizer.optimization_level=15
;zend_optimizer.license_path =

Check that it is working with phpinfo. You go to your browser and go to:
http://localhost/dashboard/phpinfo.php
Or create in your c:/xampp/htdocs
A file calling phpinfo e.g.
http://localhost/phpinfocall.php

Configuration PHP debug in eclipse
You can create a PHP project. That project should be pointint to C:\xampp\htdocs

The C:\xampp\htdocs is the localserver root folder in xampp. Inside you can create subfolders.

Configure PHP Preference of eclipse
Connect eclipse with php parser of xampp

Configure this and check that xdebug is detected in eclipse from xampp

How to create a debug view from a PHP file in your project

Debug view configuration below,

Lastly, you will see in the debug perspective, that the debugger stop automatically on the first line of your php file.


问:
How to import python classes from another directory
I am working in kaggle notebook.
I have uploaded a python script name ResidualAttentionNetwork.py. There is a class defined by name ResidualAttentionNetwork.
This class is uploaded into sub-folder.

Sub-folder is like :

```<code>input
  |_ residual_attention
      |_ Code
         |_ ResidualAttentionNetwork.py
</code>```

My python code:

```<code>from Code.ResidualAttentionNetwork import ResidualAttentionNetwork
</code>```

This throws an error : ModuleNotFoundError: No module named 'Code'

So I cant't get access to class ResidualAttentionNetwork.
Can you please help me.
here is the screenshot

答:
Make sure you have </p>

```<code>__init__.py
</code>```

<p>file exists in the directory you want to import classes from .  </p>

Body:
I am working in kaggle notebook.
I have uploaded a python script name ResidualAttentionNetwork.py. There is a class defined by name ResidualAttentionNetwork.
This class is uploaded into sub-folder.

Sub-folder is like :

input
  |_ residual_attention
      |_ Code
         |_ ResidualAttentionNetwork.py

My python code:

from Code.ResidualAttentionNetwork import ResidualAttentionNetwork

This throws an error : ModuleNotFoundError: No module named 'Code'

So I cant't get access to class ResidualAttentionNetwork.
Can you please help me.
here is the screenshot

Body:
Make sure you have

__init__.py

file exists in the directory you want to import classes from .


问:
React createPortal call fails because document.body doesn't exist?
I've got a React component for a modal dialog. It works just fine when I don't do anything special with it:

```<code>return (
    <Modal className={isShowing ? "modal is-active" : "modal"}>
        <ModalBackground></ModalBackground>
        <ModalCard>
            <ModalHeader>
                <ModalTitle>
                    <NoticeIcon type={noticeType}/>
                    {title}
                </ModalTitle>
                <ModalClose onClick={handleHideModal}></ModalClose>
            </ModalHeader>
            <ModalContent>
                {content}
            </ModalContent>
            <ModalFoot>
                { buttonSpecs.map((spec) =>
                    <BottomButton key={spec.label} label={spec.label} handleClick={spec.handleClick} isPrimary={spec.isPrimary} />
                )}
            </ModalFoot>
        </ModalCard>
    </Modal>
);
</code>```

However, the prescribed approach for displaying a dialog is to display it at the bottom of the DOM document, rather than wedged inside whatever component happens to be invoking it, including one into which the component's outer DOM element may not even be allowed. (Indeed, in one case, I'm invoking a modal dialog from inside a component that renders a table row, at TR. It "works" but it triggers an error message to the Chrome console, as nothing but TH and TD are allowed inside a TR). The way to do that is with ReactDOM.createPortal:

```<code>import ReactDOM from 'react-dom';
...
return (ReactDOM.createPortal(
    <Modal className={isShowing ? "modal is-active" : "modal"}>
        <ModalBackground></ModalBackground>
        <ModalCard>
            <ModalHeader>
                <ModalTitle>
                    <NoticeIcon type={noticeType}/>
                    {title}
                </ModalTitle>
                <ModalClose onClick={handleHideModal}></ModalClose>
            </ModalHeader>
            <ModalContent>
                {content}
            </ModalContent>
            <ModalFoot>
                { buttonSpecs.map((spec) =>
                    <BottomButton key={spec.label} label={spec.label} handleClick={spec.handleClick} isPrimary={spec.isPrimary} />
                )}
            </ModalFoot>
        </ModalCard>
    </Modal>
), document.body);
</code>```

The call to ReactDOM.createPortal, with document.body as its second parameter, is supposed to render the component at the end of the body. But it's giving me an error: "Target container is not a DOM element".

At the time I'm displaying the dialog, the page and everything else in it already exists, so the body exists.

I've tried another approach I've seen explained, which is to create an explicit div at the end of the outer HTML structure of the document as a container for the modal:

```<code><div id="root"></div>
<div id="modalRoot"></div>
</code>```

and then substitute document.getElementById('modalRoot') for document.body. But that's giving me the same error.

The only answers I've found for this involve cases where the modal is being invoked on first rendering, by script that's in the HEAD section of the document, so that the body doesn't already exist. The advice in those cases has been to move the script to the end of the document. In my case, the dialog is being displayed in response to some action of mine inside a document that's already been rendered.

Any ideas?

答:
```<code>import ReactDOM from 'react-dom';
...
return ReactDOM.createPortal(
    <Modal className={isShowing ? "modal is-active" : "modal"}>
        <ModalBackground></ModalBackground>
        <ModalCard>
            <ModalHeader>
                <ModalTitle>
                    <NoticeIcon type={noticeType}/>
                    {title}
                </ModalTitle>
                <ModalClose onClick={handleHideModal}></ModalClose>
            </ModalHeader>
            <ModalContent>
                {content}
            </ModalContent>
            <ModalFoot>
                { buttonSpecs.map((spec) =>
                    <BottomButton key={spec.label} label={spec.label} handleClick={spec.handleClick} isPrimary={spec.isPrimary} />
                )}
            </ModalFoot>
        </ModalCard>
    </Modal>
), document.body);
</code>```

Your function should return object returned by ReactDOM.createPortal function. You added extra ( at start of return function. Refer : https://reactjs.org/docs/portals.html#usage

Body:
I've got a React component for a modal dialog. It works just fine when I don't do anything special with it:

return (
    <Modal className={isShowing ? "modal is-active" : "modal"}>
        <ModalBackground></ModalBackground>
        <ModalCard>
            <ModalHeader>
                <ModalTitle>
                    <NoticeIcon type={noticeType}/>
                    {title}
                </ModalTitle>
                <ModalClose onClick={handleHideModal}></ModalClose>
            </ModalHeader>
            <ModalContent>
                {content}
            </ModalContent>
            <ModalFoot>
                { buttonSpecs.map((spec) =>
                    <BottomButton key={spec.label} label={spec.label} handleClick={spec.handleClick} isPrimary={spec.isPrimary} />
                )}
            </ModalFoot>
        </ModalCard>
    </Modal>
);

However, the prescribed approach for displaying a dialog is to display it at the bottom of the DOM document, rather than wedged inside whatever component happens to be invoking it, including one into which the component's outer DOM element may not even be allowed. (Indeed, in one case, I'm invoking a modal dialog from inside a component that renders a table row, at TR. It "works" but it triggers an error message to the Chrome console, as nothing but TH and TD are allowed inside a TR). The way to do that is with ReactDOM.createPortal:

import ReactDOM from 'react-dom';
...
return (ReactDOM.createPortal(
    <Modal className={isShowing ? "modal is-active" : "modal"}>
        <ModalBackground></ModalBackground>
        <ModalCard>
            <ModalHeader>
                <ModalTitle>
                    <NoticeIcon type={noticeType}/>
                    {title}
                </ModalTitle>
                <ModalClose onClick={handleHideModal}></ModalClose>
            </ModalHeader>
            <ModalContent>
                {content}
            </ModalContent>
            <ModalFoot>
                { buttonSpecs.map((spec) =>
                    <BottomButton key={spec.label} label={spec.label} handleClick={spec.handleClick} isPrimary={spec.isPrimary} />
                )}
            </ModalFoot>
        </ModalCard>
    </Modal>
), document.body);

The call to ReactDOM.createPortal, with document.body as its second parameter, is supposed to render the component at the end of the body. But it's giving me an error: "Target container is not a DOM element".

At the time I'm displaying the dialog, the page and everything else in it already exists, so the body exists.

I've tried another approach I've seen explained, which is to create an explicit div at the end of the outer HTML structure of the document as a container for the modal:

and then substitute document.getElementById('modalRoot') for document.body. But that's giving me the same error.

The only answers I've found for this involve cases where the modal is being invoked on first rendering, by script that's in the HEAD section of the document, so that the body doesn't already exist. The advice in those cases has been to move the script to the end of the document. In my case, the dialog is being displayed in response to some action of mine inside a document that's already been rendered.

Any ideas?

Body:
import ReactDOM from 'react-dom';
...
return ReactDOM.createPortal(
    <Modal className={isShowing ? "modal is-active" : "modal"}>
        <ModalBackground></ModalBackground>
        <ModalCard>
            <ModalHeader>
                <ModalTitle>
                    <NoticeIcon type={noticeType}/>
                    {title}
                </ModalTitle>
                <ModalClose onClick={handleHideModal}></ModalClose>
            </ModalHeader>
            <ModalContent>
                {content}
            </ModalContent>
            <ModalFoot>
                { buttonSpecs.map((spec) =>
                    <BottomButton key={spec.label} label={spec.label} handleClick={spec.handleClick} isPrimary={spec.isPrimary} />
                )}
            </ModalFoot>
        </ModalCard>
    </Modal>
), document.body);

Your function should return object returned by ReactDOM.createPortal function. You added extra ( at start of return function. Refer : https://reactjs.org/docs/portals.html#usage


问:
Jest, testing object contains correct function type
I have this method:

```<code>export function getTableConfig(priceEntity: any) {
  const columns: any = { columns: [] };
  const keys: Array<string> = Object.keys(priceEntity);
  keys.forEach((key: string) => {
    columns.columns.push({
      key: key,
      label: key,
      values: (obj: any) => ({ value: obj[key] })
    });
  });

  return columns;
}
</code>```

I am trying to test the return using Jest. I wrote something like this:

```<code>expect(tableConfig).toEqual({
  columns: [
    { key: 'id', label: 'id', values: expect.any(Function) },
  ]
});
</code>```

But I'd like to be more specific regarding the type of the function, something like

```<code>expect(tableConfig).toEqual({
  columns: [
    { key: 'id', label: 'id', values: (obj: any) => ({ value: string }) }
  ]
});
</code>```

But I have no idea how to do that. Any thoughts?

答:
You can try something like that</p>

```<code>expect(tableConfig).toEqual({
  columns: [
    { key: 'id', label: 'id', values: (obj: any) => ({ value: string }) }
  ]
});
expect(tableConfig.columns[0].values({id: 'testId'})).toBe('testId');
</code>```

Body:
I have this method:

export function getTableConfig(priceEntity: any) {
  const columns: any = { columns: [] };
  const keys: Array<string> = Object.keys(priceEntity);
  keys.forEach((key: string) => {
    columns.columns.push({
      key: key,
      label: key,
      values: (obj: any) => ({ value: obj[key] })
    });
  });

  return columns;
}

I am trying to test the return using Jest. I wrote something like this:

expect(tableConfig).toEqual({
  columns: [
    { key: 'id', label: 'id', values: expect.any(Function) },
  ]
});

But I'd like to be more specific regarding the type of the function, something like

expect(tableConfig).toEqual({
  columns: [
    { key: 'id', label: 'id', values: (obj: any) => ({ value: string }) }
  ]
});

But I have no idea how to do that. Any thoughts?

Body:
You can try something like that

expect(tableConfig).toEqual({
  columns: [
    { key: 'id', label: 'id', values: (obj: any) => ({ value: string }) }
  ]
});
expect(tableConfig.columns[0].values({id: 'testId'})).toBe('testId');


问:
How to avoid the "Circular view path" exception with Spring MVC test
I have the following code in one of my controllers:

```<code>@Controller
@RequestMapping("/preference")
public class PreferenceController {

    @RequestMapping(method = RequestMethod.GET, produces = "text/html")
    public String preference() {
        return "preference";
    }
}
</code>```

I am simply trying to test it using Spring MVC test as follows:

```<code>@ContextConfiguration
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class PreferenceControllerTest {

    @Autowired
    private WebApplicationContext ctx;

    private MockMvc mockMvc;
    @Before
    public void setup() {
        mockMvc = webAppContextSetup(ctx).build();
    }

    @Test
    public void circularViewPathIssue() throws Exception {
        mockMvc.perform(get("/preference"))
               .andDo(print());
    }
}
</code>```

I am getting the following exception:

Circular view path [preference]: would dispatch back to the current
  handler URL [/preference] again. Check your ViewResolver setup! (Hint:
  This may be the result of an unspecified view, due to default view
  name generation.)

What I find strange is that it works fine when I load the "full" context configuration that includes the template and view resolvers as shown below:

```<code><bean class="org.thymeleaf.templateresolver.ServletContextTemplateResolver" id="webTemplateResolver">
    <property name="prefix" value="WEB-INF/web-templates/" />
    <property name="suffix" value=".html" />
    <property name="templateMode" value="HTML5" />
    <property name="characterEncoding" value="UTF-8" />
    <property name="order" value="2" />
    <property name="cacheable" value="false" />
</bean>
</code>```

I am well aware that the prefix added by the template resolver ensures that there is not "circular view path" when the app uses this template resolver.

But then how I am supposed to test my app using Spring MVC test?

答:
In my case, I had this problem while trying to serve JSP pages using Spring boot application.

Here's what worked for me:

application.properties

```<code>spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
</code>```

pom.xml

To enable support for JSPs, we would need to add a dependency on tomcat-embed-jasper.

```<code><dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
</code>```

Body:
I have the following code in one of my controllers:

@Controller
@RequestMapping("/preference")
public class PreferenceController {

    @RequestMapping(method = RequestMethod.GET, produces = "text/html")
    public String preference() {
        return "preference";
    }
}

I am simply trying to test it using Spring MVC test as follows:

@ContextConfiguration
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class PreferenceControllerTest {

    @Autowired
    private WebApplicationContext ctx;

    private MockMvc mockMvc;
    @Before
    public void setup() {
        mockMvc = webAppContextSetup(ctx).build();
    }

    @Test
    public void circularViewPathIssue() throws Exception {
        mockMvc.perform(get("/preference"))
               .andDo(print());
    }
}

I am getting the following exception:

Circular view path [preference]: would dispatch back to the current
  handler URL [/preference] again. Check your ViewResolver setup! (Hint:
  This may be the result of an unspecified view, due to default view
  name generation.)

What I find strange is that it works fine when I load the "full" context configuration that includes the template and view resolvers as shown below:

<bean class="org.thymeleaf.templateresolver.ServletContextTemplateResolver" id="webTemplateResolver">
    <property name="prefix" value="WEB-INF/web-templates/" />
    <property name="suffix" value=".html" />
    <property name="templateMode" value="HTML5" />
    <property name="characterEncoding" value="UTF-8" />
    <property name="order" value="2" />
    <property name="cacheable" value="false" />
</bean>

I am well aware that the prefix added by the template resolver ensures that there is not "circular view path" when the app uses this template resolver.

But then how I am supposed to test my app using Spring MVC test?

Body:
In my case, I had this problem while trying to serve JSP pages using Spring boot application.

Here's what worked for me:

application.properties

spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

pom.xml

To enable support for JSPs, we would need to add a dependency on tomcat-embed-jasper.

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>


问:
debugger in code lite opens and closes immediately
i am a student and i use the debugger to know what is really going on on the background using break points  when i start the debugger  it opens and closes at the moment , note : using c++

i have tried to delete all break points and add them back but nothing changed

int main()
{
    Base b; // i added break point here

    Derived d {100}; // and here

    return 0;
}
```

the debugger windows (as watch) opens and closes immediately
this is the build output :

C:\Windows\system32\cmd.exe /C ""C:/Users/Hussein Okasha/Downloads/mingw64/bin/mingw32-make.exe" -j8 SHELL=cmd.exe -e -f  Makefile"
  "----------Building project:[ ConstructorsAndDestructors - Debug ]----------"
  mingw32-make.exe[1]: Entering directory 'D:/c++ projects/test/ConstructorsAndDestructors'
  "C:/Users/Hussein Okasha/Downloads/mingw64/bin/g++.exe"  -c  "D:/c++ projects/test/ConstructorsAndDestructors/main.cpp" -g -O0 -Wall  -o ./Debug/main.cpp.o -I. -I.
  "C:/Users/Hussein Okasha/Downloads/mingw64/bin/g++.exe" -o ./Debug/ConstructorsAndDestructors @"ConstructorsAndDestructors.txt" -L.
  mingw32-make.exe[1]: Leaving directory 'D:/c++ projects/test/ConstructorsAndDestructors'
  ====0 errors, 0 warnings====
  and this is the output :
  Current working directory: D:\c++ projects\test\ConstructorsAndDestructors\Debug
  Running program: le_exec.exe D:/c++ projects/test/1/1.project
  Program exited with return code: -1073741510

答: The solution is so simple you just go to build->clean project

Body:
i am a student and i use the debugger to know what is really going on on the background using break points  when i start the debugger  it opens and closes at the moment , note : using c++

i have tried to delete all break points and add them back but nothing changed

int main()
{
    Base b; // i added break point here

    Derived d {100}; // and here

    return 0;
}

the debugger windows (as watch) opens and closes immediately
this is the build output :

C:\Windows\system32\cmd.exe /C ""C:/Users/Hussein Okasha/Downloads/mingw64/bin/mingw32-make.exe" -j8 SHELL=cmd.exe -e -f  Makefile"
  "----------Building project:[ ConstructorsAndDestructors - Debug ]----------"
  mingw32-make.exe[1]: Entering directory 'D:/c++ projects/test/ConstructorsAndDestructors'
  "C:/Users/Hussein Okasha/Downloads/mingw64/bin/g++.exe"  -c  "D:/c++ projects/test/ConstructorsAndDestructors/main.cpp" -g -O0 -Wall  -o ./Debug/main.cpp.o -I. -I.
  "C:/Users/Hussein Okasha/Downloads/mingw64/bin/g++.exe" -o ./Debug/ConstructorsAndDestructors @"ConstructorsAndDestructors.txt" -L.
  mingw32-make.exe[1]: Leaving directory 'D:/c++ projects/test/ConstructorsAndDestructors'
  ====0 errors, 0 warnings====
  and this is the output :
  Current working directory: D:\c++ projects\test\ConstructorsAndDestructors\Debug
  Running program: le_exec.exe D:/c++ projects/test/1/1.project
  Program exited with return code: -1073741510


问:
Using wicket 7.10.0, how to change packaged version of jquery 3.2.1
trying to get wicket app to use packaged jquery v 3.2.1. I see this along with v 1.x and 2.x files in wicket-core-7.10.0.jar\org\apache\wicket\resource\jquery.

i tried below in my app init but this is not finding the resource
ResourceReference rnew = new UrlResourceReference(Url.parse("jquery/jquery-3.2.1.js")).setContextRelative(true);

I see there is a class called JQueryResourceReference but the constructor takes no params and only defaults to jquery 1.12.4. there is a class called DynamicJQueryResourceReference which seems to default to 1.12.4 or 2.2.4 based on browser version

trying to see if there is a obvious way to override Wicket 7 use of Jquery to 3 overall or i need to supply my own version as a seperate resource and refer to it using UrlResourceReference...

答:
In a Wicket 8.6.1 project with Spring-boot & webjars I just overrode WicketApplication#init() like this:</p>

```<code>@Override
protected void init()
{
    super.init();

    final WebjarsJavaScriptResourceReference ref =
            new WebjarsJavaScriptResourceReference( "jquery/3.4.1/jquery.min.js" );
    getJavaScriptLibrarySettings().setJQueryReference( ref );
}
</code>```

Body:
In a Wicket 8.6.1 project with Spring-boot & webjars I just overrode WicketApplication#init() like this:

@Override
protected void init()
{
    super.init();

    final WebjarsJavaScriptResourceReference ref =
            new WebjarsJavaScriptResourceReference( "jquery/3.4.1/jquery.min.js" );
    getJavaScriptLibrarySettings().setJQueryReference( ref );
}


问:
Multiple database tables within one AR model in Rails 3
I was asked to make some kind of reporting (logging) service. The employee has locally installed web application (just some dynamic website, written in PHP) in many companies. This web app is some kind of survey. All data is saved on local database, but now the requirement is that this data (result of survey) will also be sent to central server after every form submit.

There are four types of surveys. They have organised it this way, that there are many Projects, and each Project can have only one Survey of each type (STI here?) and Survey belongs to one Project. Each Survey will receive a report from local app, so it will have many Reports. The Rails 3 app that logs this reports should mimic somehow this logic. First question is: does this AR structure make sense for you?

```<code>  Project-1--------1-Survey-1-------*-Report

  Project
    has_one :survey
    has_many :reports, :through => :survey

  Survey
    belongs_to :project
    has_many :reports

  Report
    belongs_to :survey
</code>```

Second question is about having multiple tables for one AR Model. If all data will be stored in reports table, the table will become huge very quickly, and efficient querying for reports that belong to specific survey might be a problem after some time. Maybe it would be better to have separate tables for each Survey? Like reports_<survey_id>. Is this possible?

Also, I am somehow forced to use MySQL, but if there is another, much better solution for this, I could try to push it through.

If you are still here, thank you for reading this :)

答:
Second question is about having multiple tables for one AR Model. If all data will be stored in reports table, the table will become huge very quickly, and efficient querying for reports that belong to specific survey might be a problem after some time. Maybe it would be better to have separate tables for each Survey? Like reports_. Is this possible?

Yes, it is possible.

You can do it this way:

```<code>class Report < AR::Base
  table_name_suffix = ''
end

Report.table_name_suffix = 'foo'
</code>```

UPDATE

```<code># simple example of sharding model

class Survey < AR::Base
  has_many :reports

  def shard_reports
    Report.table_name_suffix = "_survey_#{self.id}"
    returning(reports){ Report.table_name_suffix = "" }
  end

end

Survey.first.reports_shard
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was asked to make some kind of reporting (logging) service. The employee has locally installed web application (just some dynamic website, written in PHP) in many companies. This web app is some kind of survey. All data is saved on local database, but now the requirement is that this data (result of survey) will also be sent to central server after every form submit.

There are four types of surveys. They have organised it this way, that there are many Projects, and each Project can have only one Survey of each type (STI here?) and Survey belongs to one Project. Each Survey will receive a report from local app, so it will have many Reports. The Rails 3 app that logs this reports should mimic somehow this logic. First question is: does this AR structure make sense for you?

  Project-1--------1-Survey-1-------*-Report

  Project
    has_one :survey
    has_many :reports, :through => :survey

  Survey
    belongs_to :project
    has_many :reports

  Report
    belongs_to :survey

Second question is about having multiple tables for one AR Model. If all data will be stored in reports table, the table will become huge very quickly, and efficient querying for reports that belong to specific survey might be a problem after some time. Maybe it would be better to have separate tables for each Survey? Like reports_<survey_id>. Is this possible?

Also, I am somehow forced to use MySQL, but if there is another, much better solution for this, I could try to push it through.

If you are still here, thank you for reading this :)

Body:
Second question is about having multiple tables for one AR Model. If all data will be stored in reports table, the table will become huge very quickly, and efficient querying for reports that belong to specific survey might be a problem after some time. Maybe it would be better to have separate tables for each Survey? Like reports_. Is this possible?

Yes, it is possible.

You can do it this way:

class Report < AR::Base
  table_name_suffix = ''
end

Report.table_name_suffix = 'foo'

UPDATE

# simple example of sharding model

class Survey < AR::Base
  has_many :reports

  def shard_reports
    Report.table_name_suffix = "_survey_#{self.id}"
    returning(reports){ Report.table_name_suffix = "" }
  end

end

Survey.first.reports_shard


问:
Http failure response for http url: 401 Unauthorized
When ever I use the following method I am able to call my service from angular

```<code>   @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.csrf().disable().authorizeRequests().antMatchers("/").permitAll();
    }
</code>```

but when I change the configure method as below I am getting 401 error.

```<code>@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable()
                // dont authenticate this particular request
                .authorizeRequests().antMatchers("/authenticate", "/register","/basicauth").permitAll().
                // all other requests need to be authenticated
                        anyRequest().authenticated().and().
                // make sure we use stateless session; session won't be used to
                // store user's state.
                        exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }
</code>```

How to overcome this problem.

my error as below

答: You need to specify the entire endpoint in antMatchers(). As far as I can see, the url you're trying to reach is .../api/v1/basicauth => change the /basicauth string to /api/v1/basicauth.

Body:
When ever I use the following method I am able to call my service from angular

   @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.csrf().disable().authorizeRequests().antMatchers("/").permitAll();
    }

but when I change the configure method as below I am getting 401 error.

@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable()
                // dont authenticate this particular request
                .authorizeRequests().antMatchers("/authenticate", "/register","/basicauth").permitAll().
                // all other requests need to be authenticated
                        anyRequest().authenticated().and().
                // make sure we use stateless session; session won't be used to
                // store user's state.
                        exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

How to overcome this problem.

my error as below


问:
How to filter out multiple specific keys and values from an array
I have this array of objects. I want to filter out only few of them, particularly the ones containing numbers.

```<code>const arr = [
    {
      Title: "Joker",
      Year: "2019",
      Rated: "R",
      Released: "04 Oct 2019",
      Runtime: "122 min",
      Genre: "Crime, Drama, Thriller",
      Director: "Todd Phillips",
      Writer:
        "Todd Phillips, Scott Silver, Bob Kane (based on characters created by), Bill Finger (based on characters created by), Jerry Robinson (based on characters created by)",
      Actors: "Joaquin Phoenix, Robert De Niro, Zazie Beetz, Frances Conroy",
      Plot:
        "In Gotham City, mentally troubled comedian Arthur Fleck is disregarded and mistreated by society. He then embarks on a downward spiral of revolution and bloody crime. This path brings him face-to-face with his alter-ego: the Joker.",
      Language: "English",
      Country: "USA, Canada",
      Awards: "Won 2 Oscars. Another 57 wins & 163 nominations.",
      Poster:
        "https://m.media-amazon.com/images/M/MV5BNGVjNWI4ZGUtNzE0MS00YTJmLWE0ZDctN2ZiYTk2YmI3NTYyXkEyXkFqcGdeQXVyMTkxNjUyNQ@@._V1_SX300.jpg",
      Ratings: [
        { Source: "Internet Movie Database", Value: "8.6/10" },
        { Source: "Rotten Tomatoes", Value: "69%" },
        { Source: "Metacritic", Value: "59/100" }
      ],
      Metascore: "59",
      imdbRating: "8.6",
      imdbVotes: "665,555",
      imdbID: "tt7286456",
      Type: "movie",
      DVD: "17 Dec 2019",
      BoxOffice: "N/A",
      Production: "Warner Bros. Pictures",
      Website: "N/A",
      Response: "True"
    }
  ];

</code>```

Initially Api response was in object, so I converted the object to an array somehow. Now I want to filter out the numbers to compare. Here's what I tried:

```<code>const makeArr = obj => {
    let arr = [];
    for (let [key, value] of Object.entries(obj)) {
      arr.push({
        [key]: value
      });
    }
    return arr.filter(item => {
      if (Object.values(item).includes(isNaN(parseInt(Object.values(item))))) {
        return item;
      }
    });
  };

</code>```

答:
Why converted API response object to array? You can iterate over an object using for...in

const obj =     {
      Title: "Joker",
      Year: "2019",
      Rated: "R",
      Released: "04 Oct 2019",
      Runtime: "122 min",
      Genre: "Crime, Drama, Thriller",
      Director: "Todd Phillips",
      Writer:
        "Todd Phillips, Scott Silver, Bob Kane (based on characters created by), Bill Finger (based on characters created by), Jerry Robinson (based on characters created by)",
      Actors: "Joaquin Phoenix, Robert De Niro, Zazie Beetz, Frances Conroy",
      Plot:
        "In Gotham City, mentally troubled comedian Arthur Fleck is disregarded and mistreated by society. He then embarks on a downward spiral of revolution and bloody crime. This path brings him face-to-face with his alter-ego: the Joker.",
      Language: "English",
      Country: "USA, Canada",
      Awards: "Won 2 Oscars. Another 57 wins & 163 nominations.",
      Poster:
        "https://m.media-amazon.com/images/M/MV5BNGVjNWI4ZGUtNzE0MS00YTJmLWE0ZDctN2ZiYTk2YmI3NTYyXkEyXkFqcGdeQXVyMTkxNjUyNQ@@._V1_SX300.jpg",
      Ratings: [
        { Source: "Internet Movie Database", Value: "8.6/10" },
        { Source: "Rotten Tomatoes", Value: "69%" },
        { Source: "Metacritic", Value: "59/100" }
      ],
      Metascore: "59",
      imdbRating: "8.6",
      imdbVotes: "665,555",
      imdbID: "tt7286456",
      Type: "movie",
      DVD: "17 Dec 2019",
      BoxOffice: "N/A",
      Production: "Warner Bros. Pictures",
      Website: "N/A",
      Response: "True"
    }

for (let key in obj) {
   if (!isNaN(obj[key])) {
     console.log(key, obj[key]);
   }
}```

Body:
I have this array of objects. I want to filter out only few of them, particularly the ones containing numbers.

const arr = [
    {
      Title: "Joker",
      Year: "2019",
      Rated: "R",
      Released: "04 Oct 2019",
      Runtime: "122 min",
      Genre: "Crime, Drama, Thriller",
      Director: "Todd Phillips",
      Writer:
        "Todd Phillips, Scott Silver, Bob Kane (based on characters created by), Bill Finger (based on characters created by), Jerry Robinson (based on characters created by)",
      Actors: "Joaquin Phoenix, Robert De Niro, Zazie Beetz, Frances Conroy",
      Plot:
        "In Gotham City, mentally troubled comedian Arthur Fleck is disregarded and mistreated by society. He then embarks on a downward spiral of revolution and bloody crime. This path brings him face-to-face with his alter-ego: the Joker.",
      Language: "English",
      Country: "USA, Canada",
      Awards: "Won 2 Oscars. Another 57 wins & 163 nominations.",
      Poster:
        "https://m.media-amazon.com/images/M/MV5BNGVjNWI4ZGUtNzE0MS00YTJmLWE0ZDctN2ZiYTk2YmI3NTYyXkEyXkFqcGdeQXVyMTkxNjUyNQ@@._V1_SX300.jpg",
      Ratings: [
        { Source: "Internet Movie Database", Value: "8.6/10" },
        { Source: "Rotten Tomatoes", Value: "69%" },
        { Source: "Metacritic", Value: "59/100" }
      ],
      Metascore: "59",
      imdbRating: "8.6",
      imdbVotes: "665,555",
      imdbID: "tt7286456",
      Type: "movie",
      DVD: "17 Dec 2019",
      BoxOffice: "N/A",
      Production: "Warner Bros. Pictures",
      Website: "N/A",
      Response: "True"
    }
  ];

Initially Api response was in object, so I converted the object to an array somehow. Now I want to filter out the numbers to compare. Here's what I tried:

const makeArr = obj => {
    let arr = [];
    for (let [key, value] of Object.entries(obj)) {
      arr.push({
        [key]: value
      });
    }
    return arr.filter(item => {
      if (Object.values(item).includes(isNaN(parseInt(Object.values(item))))) {
        return item;
      }
    });
  };


问:
Converting a member function to a static function in C++
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

```<code>typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}
</code>```

答:
If your compiler supports 0x lambdas, you can use a closure:

```<code>int main() {
  MemoryTester tester;  // If no need for dynamic allocation, don't use it.

  setAllocateFunction([&tester](uint8_t size) { return tester.malloc(size); });
  setFreeFunction([&tester](void *p) { tester.free(p); });

  return 0;
}
</code>```

No changes required to your MemoryTester class nor whichever library setAllocateFunction & setFreeFunction belong to.

Without lambdas, instead of a singleton class, use a single global object:

```<code>struct MemoryTester {
  void* malloc(uint8_t size);  // Neither are static.
  void free(void *p);
};

MemoryTester tester_a;
void* tester_a_malloc(uint8_t size) { return tester_a.malloc(size); }
void tester_a_free(void *p) { return tester_a.free(p); }

int main() {
  setAllocateFunction(&tester_a_malloc);
  setFreeFunction(&tester_a_free);
}
</code>```

The advantage here is the entire MemoryTester class isn't hamstrung because of one particular need for it.  You can create more functions (e.g. tester_b_malloc/free) as needed to accommodate other uses within the same program.

Body:
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}

Body:
If your compiler supports 0x lambdas, you can use a closure:

int main() {
  MemoryTester tester;  // If no need for dynamic allocation, don't use it.

  setAllocateFunction([&tester](uint8_t size) { return tester.malloc(size); });
  setFreeFunction([&tester](void *p) { tester.free(p); });

  return 0;
}

No changes required to your MemoryTester class nor whichever library setAllocateFunction & setFreeFunction belong to.

Without lambdas, instead of a singleton class, use a single global object:

struct MemoryTester {
  void* malloc(uint8_t size);  // Neither are static.
  void free(void *p);
};

MemoryTester tester_a;
void* tester_a_malloc(uint8_t size) { return tester_a.malloc(size); }
void tester_a_free(void *p) { return tester_a.free(p); }

int main() {
  setAllocateFunction(&tester_a_malloc);
  setFreeFunction(&tester_a_free);
}

The advantage here is the entire MemoryTester class isn't hamstrung because of one particular need for it.  You can create more functions (e.g. tester_b_malloc/free) as needed to accommodate other uses within the same program.


问:
Docker compose won't find $PWD environment variable
Here's my docker-compose:

```<code>version: '2'
services:
  couchpotato:
    build:
        context: ./couchpotato
        dockerfile: Dockerfile
    ports:
     - 5050:5050
    volumes:
     - "${PWD}/couchpotato/data:/home/CouchPotato/data/"
     - "${PWD}/couchpotato/config:/home/CouchPotato/config/"
</code>```

When I run it inside the shell, in the directory of the docker-compose.yml, I get:

```<code>WARNING: The PWD variable is not set. Defaulting to a blank string.
</code>```

and the compose starts with PWD being empty.

I don't see any error in the file, as seen here: https://docs.docker.com/compose/environment-variables/

答: My advice: change all $PWD to .

Body:
Here's my docker-compose:

version: '2'
services:
  couchpotato:
    build:
        context: ./couchpotato
        dockerfile: Dockerfile
    ports:
     - 5050:5050
    volumes:
     - "${PWD}/couchpotato/data:/home/CouchPotato/data/"
     - "${PWD}/couchpotato/config:/home/CouchPotato/config/"

When I run it inside the shell, in the directory of the docker-compose.yml, I get:

WARNING: The PWD variable is not set. Defaulting to a blank string.

and the compose starts with PWD being empty.

I don't see any error in the file, as seen here: https://docs.docker.com/compose/environment-variables/

Body: My advice: change all $PWD to .


问:
pythonic way to count multiple columns conditionaly check
I'm trying to  make a ordinary loop under specific conditions.

I want to interact over rows, checking conditions, and then interact over columns counting how many times the condition was meet.

This counting should generate a new column e my dataframe indicating the total count for each row.

I tried to use apply and mapapply with no success.

I successfully generated the following code to reach my goal.

But I bet there is more efficient ways, or even, built-in pandas functions to do it.

Anyone know how?

sample code:

```<code>import pandas as pd
df = pd.DataFrame({'1column': [11, 22, 33, 44],
        '2column': [32, 42, 15, 35],
        '3column': [33, 77, 26, 64],
        '4column': [99, 11, 110, 22],
        '5column': [20, 64, 55, 33],
        '6column': [10, 77, 77, 10]})
check_columns = ['3column','5column', '6column' ]

</code>```

```<code>df1 = df.copy()
df1['bignum_count'] = 0
for column in check_columns:
  inner_loop_count = []
  bigseries = df[column]>=50
  for big in bigseries:
    if big:
      inner_loop_count.append(1)
    else:
      inner_loop_count.append(0)

  df1['bignum_count'] += inner_loop_count

# View the dataframe
df1
</code>```

results:

```<code>1column   2column   3column 4column 5column 6column bignum_count

0   11  32  33  99  20  10  0

1   22  42  77  11  64  77  3

2   33  15  26  110 55  77  2

3   44  35  64  22  33  10  1
</code>```

答:
Use DataFrame.ge for >= with counts Trues values by sum:

```<code>df['bignum_count'] = df[check_columns].ge(50).sum(axis=1)
#alternative
#df['bignum_count'] = (df[check_columns]>=50).sum(axis=1)
print(df)
   1column  2column  3column  4column  5column  6column  bignum_count
0       11       32       33       99       20       10             0
1       22       42       77       11       64       77             3
2       33       15       26      110       55       77             2
3       44       35       64       22       33       10             1
</code>```

Body:
I'm trying to  make a ordinary loop under specific conditions.

I want to interact over rows, checking conditions, and then interact over columns counting how many times the condition was meet.

This counting should generate a new column e my dataframe indicating the total count for each row.

I tried to use apply and mapapply with no success.

I successfully generated the following code to reach my goal.

But I bet there is more efficient ways, or even, built-in pandas functions to do it.

Anyone know how?

sample code:

import pandas as pd
df = pd.DataFrame({'1column': [11, 22, 33, 44],
        '2column': [32, 42, 15, 35],
        '3column': [33, 77, 26, 64],
        '4column': [99, 11, 110, 22],
        '5column': [20, 64, 55, 33],
        '6column': [10, 77, 77, 10]})
check_columns = ['3column','5column', '6column' ]

df1 = df.copy()
df1['bignum_count'] = 0
for column in check_columns:
  inner_loop_count = []
  bigseries = df[column]>=50
  for big in bigseries:
    if big:
      inner_loop_count.append(1)
    else:
      inner_loop_count.append(0)

  df1['bignum_count'] += inner_loop_count

# View the dataframe
df1

results:

1column   2column   3column 4column 5column 6column bignum_count

0   11  32  33  99  20  10  0

1   22  42  77  11  64  77  3

2   33  15  26  110 55  77  2

3   44  35  64  22  33  10  1

Body:
Use DataFrame.ge for >= with counts Trues values by sum:

df['bignum_count'] = df[check_columns].ge(50).sum(axis=1)
#alternative
#df['bignum_count'] = (df[check_columns]>=50).sum(axis=1)
print(df)
   1column  2column  3column  4column  5column  6column  bignum_count
0       11       32       33       99       20       10             0
1       22       42       77       11       64       77             3
2       33       15       26      110       55       77             2
3       44       35       64       22       33       10             1


问:
Removing the displayModeButton in UISplitViewController in iOS
I want to remove the displayModeButton from the detailViewController's Navigation Bar in splitveiwconroller. I tried setting leftBarButtionItem.isEnable = false in AppDelegate.swift file(as below)

```<code>if let splitViewController = self.window!.rootViewController as? UISplitViewController {
            let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
            navigationController.topViewController!.navigationItem.leftBarButtonItem?.isEnabled = false
            }
</code>```

it hides the displaymodebutton intially when the application start. But when i swipt right to open the master view and then swipe left to dismiss the masterview controller the dispaly mode buttom reappars again. Please help me to hide the displayModeButton from detail view conroller.

答:
Do the same in master viewController viewWillAppear:

```<code>   let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window!.rootViewController = controller
if let splitViewController = appDelegate.window!.rootViewController as? UISplitViewController {

let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem?. isEnabled = false
navigationController.topViewController!.navigationItem.leftBarButtonItem?. tintColor = UIColor.clearColor()
     }
</code>```

OR if above does not work, use below code in AppDelegate

```<code>navigationController.topViewController!.navigationItem.setLeftBarButton(nil, animated: true)
</code>```

Body:
I want to remove the displayModeButton from the detailViewController's Navigation Bar in splitveiwconroller. I tried setting leftBarButtionItem.isEnable = false in AppDelegate.swift file(as below)

if let splitViewController = self.window!.rootViewController as? UISplitViewController {
            let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
            navigationController.topViewController!.navigationItem.leftBarButtonItem?.isEnabled = false
            }

it hides the displaymodebutton intially when the application start. But when i swipt right to open the master view and then swipe left to dismiss the masterview controller the dispaly mode buttom reappars again. Please help me to hide the displayModeButton from detail view conroller.

Body:
Do the same in master viewController viewWillAppear:

   let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window!.rootViewController = controller
if let splitViewController = appDelegate.window!.rootViewController as? UISplitViewController {

let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem?. isEnabled = false
navigationController.topViewController!.navigationItem.leftBarButtonItem?. tintColor = UIColor.clearColor()
     }

OR if above does not work, use below code in AppDelegate

navigationController.topViewController!.navigationItem.setLeftBarButton(nil, animated: true)


问:
OctoberCMS Translate plugin redirect with hash
I am using OctoberCMS Translate plugin (https://octobercms.com/plugin/rainlab-translate) and its working as per my expectations.

However, I have one custom requirement in which I am generating hash in url (i.e. http://localhost/ibis/whats-on/details#2020-sydney-international-whitewater-event - #2020-sydney-international-whitewater-event).

Now the thing is, when I am supposed to redirect using below code,

```<code> {% for code, name in locales %}
  <a class="dropdown-item" href="#" data-request="onSwitchLocale" data-request-data="locale: '{{ code }}'">
      {{ name |upper }}
  </a>
</code>```

I am able to redirect, however, my url looses its hash tag and it becomes something like http://localhost/ibis/fr/whats-on/details (fr is my selected french language).

Here below  is my overwrite code in my layout's code tab to onSwitchLocale method which is  provided by Translate plugin.

```<code>use RainLab\Translate\Models\Locale as LocaleModel;
use RainLab\Translate\Classes\Translator;
use October\Rain\Router\Router as RainRouter;

function onSwitchLocale()
{
    $this->translator = Translator::instance();
    $locale = post('locale');

    if (!$locale = post('locale')) {
            return;
    }
    $this->translator->setLocale($locale);

    $pageUrl = $this->translator->withPreservedQueryString($this->translator->makeLocaleUrlFromPage($locale), $locale);
    if ($this->property('forceUrl')) {
        return Redirect::to($this->translator->getPathInLocale($pageUrl, $locale));
    }

    return Redirect::to($pageUrl);
}
</code>```

As you can see I am trying to accomplish url redirect with hash, but I am getting error here saying

Call to undefined method RainLab\Translate\Classes\Translator::withPreservedQueryString()

And unable to proceed this request. I researched further and found withPreservedQueryString has protected method and I tried various ways to execute this method but unable to do so.

So first I need to accomplish this and second I want to append that hash tag in my url.

Can someone guide me from here on how can I achieve this ?

Thanks

答:
I am not sure $this->translator [ Translator::instance(); ] has this method there ! its just method of LocalePicker component.

This is implemented code there, so use this and define your own method

protected function withPreservedQueryString($pageUrl, $locale)
{
    $page = $this->getPage();
    $query = request()->query();

    /**
     * @event translate.localePicker.translateQuery
     * Enables manipulating the URL query parameters
     *
     * You will have access to the page object, the old and new locale and the URL query parameters.
     *
     * Example usage:
     *
     *     Event::listen('translate.localePicker.translateQuery', function($page, $params, $oldLocale, $newLocale) {
     *        if ($page->baseFileName == 'your-page-filename') {
     *             return YourModel::translateParams($params, $oldLocale, $newLocale);
     *         }
     *     });
     *
     */
    $translatedQuery = Event::fire('translate.localePicker.translateQuery',
                                    [$page, $query, $this->oldLocale, $locale], true);

    $query = http_build_query($translatedQuery ?: $query);

    return $query ? $pageUrl . '?' . $query : $pageUrl;
}
```

<blockquote>
  <p>Use it like this </p>
</blockquote>

<pre class="lang-php prettyprint-override"><code>$pageUrl = $this->
    withPreservedQueryString(  // <- this call
        $this->translator->makeLocaleUrlFromPage($locale),
        $locale
    );
if ($this->property('forceUrl')) {
    return Redirect::to($this->translator->getPathInLocale($pageUrl, $locale));
}
</code>```

it should work, if any doubt please comment.

Body:
I am using OctoberCMS Translate plugin (https://octobercms.com/plugin/rainlab-translate) and its working as per my expectations.

However, I have one custom requirement in which I am generating hash in url (i.e. http://localhost/ibis/whats-on/details#2020-sydney-international-whitewater-event - #2020-sydney-international-whitewater-event).

Now the thing is, when I am supposed to redirect using below code,

 {% for code, name in locales %}

      {{ name |upper }}

I am able to redirect, however, my url looses its hash tag and it becomes something like http://localhost/ibis/fr/whats-on/details (fr is my selected french language).

Here below  is my overwrite code in my layout's code tab to onSwitchLocale method which is  provided by Translate plugin.

use RainLab\Translate\Models\Locale as LocaleModel;
use RainLab\Translate\Classes\Translator;
use October\Rain\Router\Router as RainRouter;

function onSwitchLocale()
{
    $this->translator = Translator::instance();
    $locale = post('locale');

    if (!$locale = post('locale')) {
            return;
    }
    $this->translator->setLocale($locale);

    $pageUrl = $this->translator->withPreservedQueryString($this->translator->makeLocaleUrlFromPage($locale), $locale);
    if ($this->property('forceUrl')) {
        return Redirect::to($this->translator->getPathInLocale($pageUrl, $locale));
    }

    return Redirect::to($pageUrl);
}

As you can see I am trying to accomplish url redirect with hash, but I am getting error here saying

Call to undefined method RainLab\Translate\Classes\Translator::withPreservedQueryString()

And unable to proceed this request. I researched further and found withPreservedQueryString has protected method and I tried various ways to execute this method but unable to do so.

So first I need to accomplish this and second I want to append that hash tag in my url.

Can someone guide me from here on how can I achieve this ?

Thanks

Body:
I am not sure $this->translator [ Translator::instance(); ] has this method there ! its just method of LocalePicker component.

This is implemented code there, so use this and define your own method

protected function withPreservedQueryString($pageUrl, $locale)
{
    $page = $this->getPage();
    $query = request()->query();

    /**
     * @event translate.localePicker.translateQuery
     * Enables manipulating the URL query parameters
     *
     * You will have access to the page object, the old and new locale and the URL query parameters.
     *
     * Example usage:
     *
     *     Event::listen('translate.localePicker.translateQuery', function($page, $params, $oldLocale, $newLocale) {
     *        if ($page->baseFileName == 'your-page-filename') {
     *             return YourModel::translateParams($params, $oldLocale, $newLocale);
     *         }
     *     });
     *
     */
    $translatedQuery = Event::fire('translate.localePicker.translateQuery',
                                    [$page, $query, $this->oldLocale, $locale], true);

    $query = http_build_query($translatedQuery ?: $query);

    return $query ? $pageUrl . '?' . $query : $pageUrl;
}

Use it like this

$pageUrl = $this->
    withPreservedQueryString(  // <- this call
        $this->translator->makeLocaleUrlFromPage($locale),
        $locale
    );
if ($this->property('forceUrl')) {
    return Redirect::to($this->translator->getPathInLocale($pageUrl, $locale));
}

it should work, if any doubt please comment.


答:
Index on the columns of interest and check which are greater or equal (ge) than a threshold:

```<code>df['bignum_count'] = df[check_columns].ge(50).sum(1)
</code>```

```<code>print(df)

 1column  2column  3column  4column  5column  6column  bignum_count
0       11       32       33       99       20       10             0
1       22       42       77       11       64       77             3
2       33       15       26      110       55       77             2
3       44       35       64       22       33       10             1
check_columns
df1 = df.copy()
</code>```

Title: pythonic way to count multiple columns conditionaly check

Body:
Index on the columns of interest and check which are greater or equal (ge) than a threshold:

df['bignum_count'] = df[check_columns].ge(50).sum(1)

print(df)

 1column  2column  3column  4column  5column  6column  bignum_count
0       11       32       33       99       20       10             0
1       22       42       77       11       64       77             3
2       33       15       26      110       55       77             2
3       44       35       64       22       33       10             1
check_columns
df1 = df.copy()


问:
How to determine exact type in union type in typescript in runtime?
In typescript, union type is defined as ParsedValue, which consists of some basic type and interface Template.

After some parsing code as shown below, the parsedValue's type is decided based on type. Now I want to do something based on parsedValue's exact type, which is a subtype in the union type.

However, I found as keyword doesn't work due to Template is an intrface rather that a class implementation.

Any solution to bypass this problem?

type ParsedValue = string | number | boolean | Template | null

interface Visitor {
    visit(template: Template)
}

class BasicVisitor implements Visitor {
    visit(template: Template) {
    }
}

interface Template {
    accept(visitor: Visitor)
}

function parse(value: string, type: string): ParsedValue {
    if (type == 'template') {
        // return a template instance
    } else if (type === 'string') {
        // return some string
    } else {
        // return null
    }
}

class Field {
    type: string
    value: string
    parsedValue: ParsedValue

    constructor(json any) {
        this.value = json.value.toString()
        this.type = json.type.toString()
        this.parsedValue = parse(this.value, this.type)
    }
}

const field = new Field({
    type: 'template',
    value: 'some template string'
})

const visitor = new BasicVisitor()

if (field.parsedValue !== null && field.parsedValue as Template) {
    // how to bypass this type judgement
    field.parsedValue.accept(visitor)
}

```

答: You should try out User-Defined Type Guards for run-time type checks and type assertions: https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards</p>


问:
How to convert to camel casing after a symbol?
```<code>Input #2: profile.Address.AddressLine1
Result: profile.address.addressLine1

Input #2: MyName
Result: myName
</code>```

<hr>

```<code>using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputText = "profile.Business.AddressLine1"; //profile.business.addressLine1
            //string inputText = "MyName"; //myName
            string result = null;

            if (inputText.Contains('.'))
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);

                //Loop to find period symbol
                //make the next character after the period symbol lowercase
            }
            else
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);
            }
        }
    }
}
</code>```

答:
You can try below code:</p>

```<code>    static void Main(string[] args)
    {
        string inputText = "profile.Business.AddressLine1";
        convertToCamelCase(inputText); //profile.business.addressLine1
    }

    static string convertToCamelCase(string inputText)
    {
        string result = string.Empty;

        if (inputText.Contains('.'))
        {
            var inputs = inputText.Split('.');

            for (int i = 0; i < inputs.Length; i++)
            {
                inputs[i] = inputs[i].Substring(0, 1).ToLower() + inputs[i].Substring(1);
            }

            result = string.Join(".", inputs);
        }
        else
        {
            result = convertToCamelCase(inputText);
        }

        return result;
    }
</code>```

Body:
Input #2: profile.Address.AddressLine1
Result: profile.address.addressLine1

Input #2: MyName
Result: myName

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputText = "profile.Business.AddressLine1"; //profile.business.addressLine1
            //string inputText = "MyName"; //myName
            string result = null;

            if (inputText.Contains('.'))
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);

                //Loop to find period symbol
                //make the next character after the period symbol lowercase
            }
            else
            {
                //make first character lowercase
                result = inputText.Substring(0, 1).ToLower() + inputText.Substring(1);
            }
        }
    }
}

Body:
You can try below code:

    static void Main(string[] args)
    {
        string inputText = "profile.Business.AddressLine1";
        convertToCamelCase(inputText); //profile.business.addressLine1
    }

    static string convertToCamelCase(string inputText)
    {
        string result = string.Empty;

        if (inputText.Contains('.'))
        {
            var inputs = inputText.Split('.');

            for (int i = 0; i < inputs.Length; i++)
            {
                inputs[i] = inputs[i].Substring(0, 1).ToLower() + inputs[i].Substring(1);
            }

            result = string.Join(".", inputs);
        }
        else
        {
            result = convertToCamelCase(inputText);
        }

        return result;
    }


问:
Linq 2 Sql - Repository isn't working unless query is done inside controller
I'm really struggling to understand an issue I'm facing.  I have a very simple repository with the following code:

```<code>public class ProductRepository : IProductRepository
{
    private Table<Product> productTable;

    public Product GetProductById(int id)
    {
         return productTable.Where(p => p.ProductId == id).Single();
    }

    public IQueryable<Product> GetProducts()
    {
        return productTable;
    }
 }
</code>```

I have a controller called AddToCart().  The repository class above is passed into the controller via DI.  I pass a productId into this controller, and the repository method is called.  The problem is that a null value is returned when a Product does exist.

```<code>    public void AddToCart(int productId)
    {
        //Returns Null value
        Product product = productRepository.GetProductById(productId);
        ...
    }
</code>```

I thought the issue may be that I need the IQueryable<> around the class that I'm returning.  I also modified my AddToCart method in various ways to try to get it to work.

```<code>public IQueryable<Product> GetProductById(int id)
{
    return productTable.Where(p => p.ProductId == id);
}

public void AddToCart(int productId)
{
    //Throws error / Returns Null value
    Product product = productRepository.GetProductById(productId).Single();
    //Returns Null value
    Product product = productRepository.GetProductById(productId).FirstOrDefault();
}
</code>```

However, the following works and I have no reason why!  It's basically the same code, just being done in the controller.  Anyone have any ideas? :/

```<code>    public void AddToCart(int productId)
    {
        Product product = productRepository.GetProducts().FirstOrDefault(p => p.ProductId == productId);
    }
</code>```

答:
I wonder if you may be having an issue with your Dependency Injection. You are using .Single() which, according to the docs, will throw an exception if there is not exactly one item in the collection that satisfies your condition. </p>

<p>I would try implementing this without using Dependency Injection and see if you get the same results. You can also try instantiating and returning a product item directly from the GetProductById method (instead of pulling from the database) to rule out anything weird happening with your DI. </p>

Body:
I'm really struggling to understand an issue I'm facing.  I have a very simple repository with the following code:

public class ProductRepository : IProductRepository
{
    private Table<Product> productTable;

    public Product GetProductById(int id)
    {
         return productTable.Where(p => p.ProductId == id).Single();
    }

    public IQueryable<Product> GetProducts()
    {
        return productTable;
    }
 }

I have a controller called AddToCart().  The repository class above is passed into the controller via DI.  I pass a productId into this controller, and the repository method is called.  The problem is that a null value is returned when a Product does exist.

    public void AddToCart(int productId)
    {
        //Returns Null value
        Product product = productRepository.GetProductById(productId);
        ...
    }

I thought the issue may be that I need the IQueryable<> around the class that I'm returning.  I also modified my AddToCart method in various ways to try to get it to work.

public IQueryable<Product> GetProductById(int id)
{
    return productTable.Where(p => p.ProductId == id);
}

public void AddToCart(int productId)
{
    //Throws error / Returns Null value
    Product product = productRepository.GetProductById(productId).Single();
    //Returns Null value
    Product product = productRepository.GetProductById(productId).FirstOrDefault();
}

However, the following works and I have no reason why!  It's basically the same code, just being done in the controller.  Anyone have any ideas? :/

    public void AddToCart(int productId)
    {
        Product product = productRepository.GetProducts().FirstOrDefault(p => p.ProductId == productId);
    }

Body:
I wonder if you may be having an issue with your Dependency Injection. You are using .Single() which, according to the docs, will throw an exception if there is not exactly one item in the collection that satisfies your condition.

I would try implementing this without using Dependency Injection and see if you get the same results. You can also try instantiating and returning a product item directly from the GetProductById method (instead of pulling from the database) to rule out anything weird happening with your DI.


问:
Usage of fmemopen
I don't understand an example of fmemopen from APUE

#include <stdio.h>
#include <string.h>

#define BSZ 48

int
main()
{
    FILE *fp;
    char buf[BSZ];

    memset(buf, 'a', BSZ-2);
    buf[BSZ-2] = '\0';
    buf[BSZ-1] = 'X';
    if ((fp = fmemopen(buf, BSZ, "w+")) == NULL)  //"w+" truncate the file by setting the first byte to null byte
        printf("fmemopen failed\n");
    printf("initial buffer contents: %s\n", buf); //print nothing cause the first byte is null byte.
    fprintf(fp, "hello, world"); //write format string to the stream, so the buffer should change and be rewritten.
    printf("before flush: %s\n", buf); //should print "hello, world". Why not?
    fflush(fp);
    printf("after fflush: %s\n", buf);
    printf("len of string in buf = %ld\n", (long)strlen(buf));

    memset(buf, 'b', BSZ-2);
    buf[BSZ-2] = '\0';
    buf[BSZ-1] = 'X';
    fprintf(fp, "hello, world");
    fseek(fp, 0, SEEK_SET);
    printf("after  fseek: %s\n", buf);
    printf("len of string in buf = %ld\n", (long)strlen(buf));

    memset(buf, 'c', BSZ-2);
    buf[BSZ-2] = '\0';
    buf[BSZ-1] = 'X';
    fprintf(fp, "hello, world");
    fclose(fp);
    printf("after fclose: %s\n", buf);
    printf("len of string in buf = %ld\n", (long)strlen(buf));

    return(0);
}
```

I use Clion to debug and when it finishes fprintf(fp, "hello, world"); and comes to printf("before flush: %s\n", buf);, I see the content of char array buf does not change and print nothing. Why!?

A debug screenshot for better description:

Also, quoted from the book:

Third, a null byte is written at the current position in the stream whenever we
  increase the amount of data in the stream’s buffer and call fclose, fflush, fseek,
  fseeko, or fsetpos.

What does this mean?

Update:

From the book and it seems that buffer is unchanged until stream is flushed is the expected result.

答:
change the allocated buf array in the stack

```<code>char buf[BSZ];
</code>```

to this

```<code>char* buf = new(std::nothrow) chr[BSZ];
</code>```

and freed buf after close the stream

delete[] buf

and test again.

Title: Usage of fmemopen

Body:
I don't understand an example of fmemopen from APUE

#include <stdio.h>
#include <string.h>

#define BSZ 48

int
main()
{
    FILE *fp;
    char buf[BSZ];

    memset(buf, 'a', BSZ-2);
    buf[BSZ-2] = '\0';
    buf[BSZ-1] = 'X';
    if ((fp = fmemopen(buf, BSZ, "w+")) == NULL)  //"w+" truncate the file by setting the first byte to null byte
        printf("fmemopen failed\n");
    printf("initial buffer contents: %s\n", buf); //print nothing cause the first byte is null byte.
    fprintf(fp, "hello, world"); //write format string to the stream, so the buffer should change and be rewritten.
    printf("before flush: %s\n", buf); //should print "hello, world". Why not?
    fflush(fp);
    printf("after fflush: %s\n", buf);
    printf("len of string in buf = %ld\n", (long)strlen(buf));

    memset(buf, 'b', BSZ-2);
    buf[BSZ-2] = '\0';
    buf[BSZ-1] = 'X';
    fprintf(fp, "hello, world");
    fseek(fp, 0, SEEK_SET);
    printf("after  fseek: %s\n", buf);
    printf("len of string in buf = %ld\n", (long)strlen(buf));

    memset(buf, 'c', BSZ-2);
    buf[BSZ-2] = '\0';
    buf[BSZ-1] = 'X';
    fprintf(fp, "hello, world");
    fclose(fp);
    printf("after fclose: %s\n", buf);
    printf("len of string in buf = %ld\n", (long)strlen(buf));

    return(0);
}

I use Clion to debug and when it finishes fprintf(fp, "hello, world"); and comes to printf("before flush: %s\n", buf);, I see the content of char array buf does not change and print nothing. Why!?

A debug screenshot for better description:

Also, quoted from the book:

Third, a null byte is written at the current position in the stream whenever we
  increase the amount of data in the stream’s buffer and call fclose, fflush, fseek,
  fseeko, or fsetpos.

What does this mean?

Update:

From the book and it seems that buffer is unchanged until stream is flushed is the expected result.

Body:
change the allocated buf array in the stack

char buf[BSZ];

to this

char* buf = new(std::nothrow) chr[BSZ];

and freed buf after close the stream

delete[] buf

and test again.


问:
Change class on scrolling through div
I have a sticky sidebar like this:

```<code><ul class = "cars">
       <li class=""><a href="javascript:void(0)" class="model" data-id="1"> BMW </a></li>
    ......
        <li class=""><a href="javascript:void(0)" class="model" data-id="2"> Mersedes </a></li>
</ul>
</code>```

And table like this:

```<code>     <div class="element-title" id="car-category-1">BMW</div>
.....
     <div class="element-title" id="car-category-2">Mersedes</div>
</code>```

Now what I am trying to do:

 Scrolling through the
 should change the class of
 of BMW to .active

 Same for Mersedes, if scroll through
 then change
 with Mersedes to active.

this is jquery for click scroll

```<code>  $(document).on('click', '.model', function () {
        var this_id = $(this).data('id');
        var gotom = setInterval(function () {
            cars_go_to_navtab(this_id);
            clearInterval(gotom);
        }, 400);

        $('.cars li').removeClass('active');
        $(this).parent().addClass('active');
    });
function cars_go_to_navtab(id) {
    var scrolling_div = $('#car-category-' + id);
    $('html, body').animate({
        scrollTop: scrolling_div.offset().top - 70
    }, 500);
}
</code>```

答:
There is a great article of CSS-Tricks for a pure CSS solution (not sure that it is suitable to your use-case) which also has a link to another great article that uses Intersection Observer. In short, place something like this in your code:

```<code>const observer = new IntersectionObserver(entries =>
{
  for (const entry of entries) {
    if (entry.isIntersecting) {
      // add css style here
    }
    else {
      // remove css style here
  }
});
observer.observe(document.querySelector('#your-element-selector'));
</code>```

Also, please mind support table over different browsers (canIuse to the rescue)

Title: Change class on scrolling through div

Body:
I have a sticky sidebar like this:

 BMW

    ......

 Mersedes

And table like this:

BMW

.....

Mersedes

Now what I am trying to do:

 Scrolling through the
 should change the class of
 of BMW to .active

 Same for Mersedes, if scroll through
 then change
 with Mersedes to active.

this is jquery for click scroll

  $(document).on('click', '.model', function () {
        var this_id = $(this).data('id');
        var gotom = setInterval(function () {
            cars_go_to_navtab(this_id);
            clearInterval(gotom);
        }, 400);

        $('.cars li').removeClass('active');
        $(this).parent().addClass('active');
    });
function cars_go_to_navtab(id) {
    var scrolling_div = $('#car-category-' + id);
    $('html, body').animate({
        scrollTop: scrolling_div.offset().top - 70
    }, 500);
}

Body:
There is a great article of CSS-Tricks for a pure CSS solution (not sure that it is suitable to your use-case) which also has a link to another great article that uses Intersection Observer. In short, place something like this in your code:

const observer = new IntersectionObserver(entries =>
{
  for (const entry of entries) {
    if (entry.isIntersecting) {
      // add css style here
    }
    else {
      // remove css style here
  }
});
observer.observe(document.querySelector('#your-element-selector'));

Also, please mind support table over different browsers (canIuse to the rescue)