问:
Android Toast showing too late after clicking on a button
Please i need your help !!

when i finished my Android app i discovered that all my Toast in the app doesn't show at the moment when i click on the button but too late!

i didn't know why !
and i didn't know which part of code to screen to you !

this some of code :

```<code>envoyer.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
                v.startAnimation(buttonClick);

                if (nom_compte.getText().toString().equals("") || num_compte.getText().toString().equals("") || num_tel.getText().toString().equals("") || (dropdown.getSelectedItem().toString().equals("Votre banque..")) ) {
                    Toast.makeText(Get_My_Money_Activity.this, "remplir tous les champs !", Toast.LENGTH_SHORT).show();
                }else{
                    MyAsyncTaskresources2 attemptLogin2= new MyAsyncTaskresources2();
                    attemptLogin2.execute("http://example.com/demandes_de_paiement.php?id_user="+session.getId()+"&nom_compte="+URLEncoder.encode(nom_compte.getText().toString())+"&num_compte="+URLEncoder.encode(num_compte.getText().toString())+"&num_tel="+URLEncoder.encode(num_tel.getText().toString())+"&nom_banque="+URLEncoder.encode(dropdown.getSelectedItem().toString()));
                }

            }
        });
</code>```

答:
You can set time as you want-

Try this

```<code>Toast.makeText(getApplicationContext(),"clicked",1000).show();
</code>```

or watever value you want to set.

Body:
Please i need your help !!

when i finished my Android app i discovered that all my Toast in the app doesn't show at the moment when i click on the button but too late!

i didn't know why !
and i didn't know which part of code to screen to you !

this some of code :

envoyer.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
                v.startAnimation(buttonClick);

                if (nom_compte.getText().toString().equals("") || num_compte.getText().toString().equals("") || num_tel.getText().toString().equals("") || (dropdown.getSelectedItem().toString().equals("Votre banque..")) ) {
                    Toast.makeText(Get_My_Money_Activity.this, "remplir tous les champs !", Toast.LENGTH_SHORT).show();
                }else{
                    MyAsyncTaskresources2 attemptLogin2= new MyAsyncTaskresources2();
                    attemptLogin2.execute("http://example.com/demandes_de_paiement.php?id_user="+session.getId()+"&nom_compte="+URLEncoder.encode(nom_compte.getText().toString())+"&num_compte="+URLEncoder.encode(num_compte.getText().toString())+"&num_tel="+URLEncoder.encode(num_tel.getText().toString())+"&nom_banque="+URLEncoder.encode(dropdown.getSelectedItem().toString()));
                }

            }
        });

Body:
You can set time as you want-

Try this

Toast.makeText(getApplicationContext(),"clicked",1000).show();

or watever value you want to set.


来源: stackexchange

问:
npm not reading .npmrc file
I'm trying to install a library from a private repository, and I keep getting an error in trying to use npm.

I'm using:
OSX Mavericks 10.9.3
Node v0.10.28
npm 1.4.10 (this was installed after trying with 1.4.13 and it still not working)

I am running this from my home directory, and the ~/.npmrc file is in the directory.

whenever I run the command: npm install 'library name here'

I get the following error:

```<code>npm http GET https://registry.npmjs.org/dslib-js
npm http 404 https://registry.npmjs.org/dslib-js
npm ERR! 404 404 Not Found: dslib-js
npm ERR! 404
npm ERR! 404 'dslib-js' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404
npm ERR! 404 Maybe try 'npm search dslib'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.

npm ERR! System Darwin 13.2.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "dslib-js"
npm ERR! cwd /Users/marcos.pedreiro
npm ERR! node -v v0.10.28
npm ERR! npm -v 1.4.10
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/marcos.pedreiro/npm-debug.log
npm ERR! not ok code 0
</code>```

Edits:

When I run ls -a (in the home directory) this is the output:

```<code>.           .ssh            Music
..          .subversion     Pictures
.CFUserTextEncoding .vagrant.d      Public
.DS_Store       Applications        VirtualBox VMs
.Trash          Desktop         clients
.bash_history       Documents       dev
.gradle         Downloads       npm-debug.log
.matlab         Google Drive        ~:.npmrc
.npm            Library         ~:.npmrc.template
.npmrc.bak      Movies
</code>```

This is the output of the command npm config ls -l | grep config

```<code>; cli configs
globalconfig = "/usr/local/etc/npmrc"
userconfig = "/Users/marcos.pedreiro/.npmrc"
</code>```

:End Edits

Any help would be greatly appreciated. Thanks!

答:
I missed a couple of things to download my packages published in my private repository.

First The file name was .npmrc.txt instead of .npmrc. In windows, you can't create file name directly. So I opened command prompt then fired

```<code>echo "auth_token" > .npmrc
</code>```

Second I was just pasting my auth_token in .npmrc file. You have to append the registry address also.

```<code>//**.**.visualstudio.com/_packaging/**/npm/registry/:_authToken=token_here
</code>```

ContentLicense: CC BY-SA 3.0

Title: npm not reading .npmrc file

Body:
I'm trying to install a library from a private repository, and I keep getting an error in trying to use npm.

I'm using:
OSX Mavericks 10.9.3
Node v0.10.28
npm 1.4.10 (this was installed after trying with 1.4.13 and it still not working)

I am running this from my home directory, and the ~/.npmrc file is in the directory.

whenever I run the command: npm install 'library name here'

I get the following error:

npm http GET https://registry.npmjs.org/dslib-js
npm http 404 https://registry.npmjs.org/dslib-js
npm ERR! 404 404 Not Found: dslib-js
npm ERR! 404
npm ERR! 404 'dslib-js' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404
npm ERR! 404 Maybe try 'npm search dslib'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.

npm ERR! System Darwin 13.2.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "dslib-js"
npm ERR! cwd /Users/marcos.pedreiro
npm ERR! node -v v0.10.28
npm ERR! npm -v 1.4.10
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/marcos.pedreiro/npm-debug.log
npm ERR! not ok code 0

Edits:

When I run ls -a (in the home directory) this is the output:

.           .ssh            Music
..          .subversion     Pictures
.CFUserTextEncoding .vagrant.d      Public
.DS_Store       Applications        VirtualBox VMs
.Trash          Desktop         clients
.bash_history       Documents       dev
.gradle         Downloads       npm-debug.log
.matlab         Google Drive        ~:.npmrc
.npm            Library         ~:.npmrc.template
.npmrc.bak      Movies

This is the output of the command npm config ls -l | grep config

; cli configs
globalconfig = "/usr/local/etc/npmrc"
userconfig = "/Users/marcos.pedreiro/.npmrc"

:End Edits

Any help would be greatly appreciated. Thanks!

Body:
I missed a couple of things to download my packages published in my private repository.

First The file name was .npmrc.txt instead of .npmrc. In windows, you can't create file name directly. So I opened command prompt then fired

echo "auth_token" > .npmrc

Second I was just pasting my auth_token in .npmrc file. You have to append the registry address also.

//**.**.visualstudio.com/_packaging/**/npm/registry/:_authToken=token_here


问:
OpenMP reduction on older version without overloading

#pragma omp parallel for    // I want reduction but overloading doesn't work on the version used
for (int i = 0; i <500; i++)
    #pragma omp critical
    for (j=i; j < 102342; j++)
    {
        Output[j] += staticConstant[i] * data[j-i];
    }
}
```

Is there a way to get reduction to work here? making local private copies doesn't speed it up.

答:
in this case, your best bet is to swap the loops

```<code>#pragma omp parallel for
for (j=0; j < 102342; j++)
   for (int i = 0; i <= min(j,499); i++)
        Output[j] += staticConstant[i] * data[j-i];
</code>```

an other (but sub-optimal) option is to use atomics

```<code>#pragma omp parallel for
for (int i = 0; i <500; i++)
   for (j=i; j < 102342; j++)
    {
      #pragma omp atomic
      Output[j] += staticConstant[i] * data[j-i];
    }
</code>```

Body:
#pragma omp parallel for    // I want reduction but overloading doesn't work on the version used
for (int i = 0; i <500; i++)
    #pragma omp critical
    for (j=i; j < 102342; j++)
    {
        Output[j] += staticConstant[i] * data[j-i];
    }
}

Is there a way to get reduction to work here? making local private copies doesn't speed it up.

Body:
in this case, your best bet is to swap the loops

#pragma omp parallel for
for (j=0; j < 102342; j++)
   for (int i = 0; i <= min(j,499); i++)
        Output[j] += staticConstant[i] * data[j-i];

an other (but sub-optimal) option is to use atomics

#pragma omp parallel for
for (int i = 0; i <500; i++)
   for (j=i; j < 102342; j++)
    {
      #pragma omp atomic
      Output[j] += staticConstant[i] * data[j-i];
    }


问:
create a function for action creator in redux
this is my action, I straight away dispatch an object in getMsgList

```<code>export function getMsgList(){
    dispatch=>{
        axios.get('/user/getmsglist')
        .then(res=>{
            if(res.state===200 && res.data.code===0){
                dispatch({type:MSG_LIST, payload:res.data.data})
            }
        })
    }
}
</code>```

but I've seen some people create a function instead, they'll do it like this.

```<code>...
dispatch(getMsg(res.data.data)
...

getMsg(msg){
    return{type:MSG_LIST,payload:msg}
}
</code>```

What is the purpose of that 'extra function'?

答:
[Redux] (https://redux.js.org/docs/basics/Actions.html) explains this. This is called an Action Creator.

In a real app, it is wiser to generate a unique ID every time something new is created. It's a good idea to pass as little data in each action as possible. For example, it's better to pass index than the whole todo object. Action creators are exactly that—functions that create actions.

Essentially it reduces copy and paste for the type string, save code, and clarify logic using an Action Creator

Body:
this is my action, I straight away dispatch an object in getMsgList

export function getMsgList(){
    dispatch=>{
        axios.get('/user/getmsglist')
        .then(res=>{
            if(res.state===200 && res.data.code===0){
                dispatch({type:MSG_LIST, payload:res.data.data})
            }
        })
    }
}

but I've seen some people create a function instead, they'll do it like this.

...
dispatch(getMsg(res.data.data)
...

getMsg(msg){
    return{type:MSG_LIST,payload:msg}
}

What is the purpose of that 'extra function'?


问:
Printing items from a list in Python
I am trying to write a function in Python where I am given a list, l = [[2,3],[5,6],[4,8]], which contains other lists. I am supposed to print the first item in every list on one line with three spaces in between and the second item in every list in another line with also three spaces in between. I have made the following code - however it seems to print everything on one line, and I am not sure what I am doing wrong.

```<code>l = [[2,3],[5,6],[4,8]]
for item in l:
    print(item[0], end = '  ')
for obj in l:
    print(obj[1], end = '  ')
</code>```

Title: Printing items from a list in Python

Body:
I am trying to write a function in Python where I am given a list, l = [[2,3],[5,6],[4,8]], which contains other lists. I am supposed to print the first item in every list on one line with three spaces in between and the second item in every list in another line with also three spaces in between. I have made the following code - however it seems to print everything on one line, and I am not sure what I am doing wrong.

l = [[2,3],[5,6],[4,8]]
for item in l:
    print(item[0], end = '  ')
for obj in l:
    print(obj[1], end = '  ')

Body:
>>> ''.join([str(l[i][0])+str("   ") if i!=len(l)-1 else str(l[i][0]) for i in range(len(l))])
'2   5   4'
 >>> ''.join([str(l[i][1])+str("   ") if i!=len(l)-1 else str(l[i][1]) for i in range(len(l))])
'3   6   8'


问:
PHP signup system won't work (phpmyadmin, wampserver)
My php signup system won't connect to my locally hosted phpmyadmin database even though I've checked through spelling errors and everything seems like it should work. The header wont change even though it's stated in the PHP sign up script. Nothing is being transferred into my database(which has no errors with it). If someone could tell me what I'm doing wrong that would be great. (P.S. footer.php and header.php are correct and included in the form)

Sign up error handlers and sign up script:

```<code><?php

if (isset($_POST['submit'])) {

include_once 'dbh.inc.php';

$first = mysqli_real_escape_string($conn, $_POST)$_POST['first'];
$last = mysqli_real_escape_string($conn, $_POST)$_POST['last'];
$email = mysqli_real_escape_string($conn, $_POST)$_POST['email'];
$username = mysqli_real_escape_string($conn, $_POST)$_POST['username'];
$password = mysqli_real_escape_string($conn, $_POST)$_POST['password'];

//Error handlers
//Check for empty fields
if (empty($first)) || (empty($last)) || (empty($email)) ||
(empty($username)) || (empty($password)) {
    header("Location: ../signup.php?signup=empty");
    exit();
} else {
    //Check is input characters are valid
    if (!preg_match("/^[a-zA-Z]*$/", $first) || (!preg_match("/^[a-zA-
Z]*$/", $last)) {
        header("Location: ../signup.php?signup=invalid");
        exit();
    } else {
        //Check if email is valid
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            header("Location: ../signup.php?signup=empty");
            exit();
        } else {
            $sql = "SELECT * FROM users WHERE user_username='username'";
            $result = mysqli_query($conn, $sql);
            $resultCheck = mysqli_num_rows($result);

            if ($resultCheck > 0) {
                header("Location: ../signup.php?signup=usertaken");
                exit();
            } else {
                //Hashing the password
                $hashedPassword = password_hash($password,
PASSWORD_DEFAULT);
                //Insert the user into the database
                $sql = "INSERT INTO users (user_first, user_last,
 user_email, user_username, user_password) VALUES ('$first', '$last',
'$email', '$username' '$hashedPassword');";
                mysqli_query($conn, $sql);
                header("Location: ../signup.php?signup=success");
                exit();
            }
        }
    }
 }

} else {
header("Location: ../signup.php");
exit();
}
</code>```

Database connection:

```<code><?php

$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbServername = "loginsystem";

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword,
$dbServername);
</code>```

Sign up form(html in a php file):

```<code><?php include_once 'header.php';?>

<section class="main-container">
<div class="wrapper">
    <h2>Sign Up</h2>
    <form class="Sign" action="includes/signup.inc.php" method="POST">
        <input type="text" name="first" placeholder="First Name"><br>
        <input type="text" name="last" placeholder="Last Name"><br>
        <input type="email" name="email" placeholder="E-mail"><br>
        <input type="text" name="username" placeholder="Username"><br>
        <input type="password" name="password" placeholder="Password"><br>
        <button type="submit" name="">Sign Up!</button><br>
    </form>
</div>
</section>

<?php include_once 'footer.php';?>
</code>```

Please help if you can. It would be much appreciated. Thanks!

答:
Give the name 'submit' to submit button of your HTML Signup Page:

```<code> <button type="submit" name="submit">Sign Up!</button>
</code>```

Change PHP Signup Page POST:

```<code>$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
</code>```

Change empty values checking of stmt to:

```<code>if ( (empty($first)) || (empty($last)) or (empty($email)) || (empty($username)) || (empty($password)) )
</code>```

Change input characters validity checking if stmt to:

```<code>if ( (!preg_match("/^[a-zA-Z]*$/", $first)) || ((!preg_match("/^[a-zA-Z]*$/", $last)) ) )
</code>```

Body:
My php signup system won't connect to my locally hosted phpmyadmin database even though I've checked through spelling errors and everything seems like it should work. The header wont change even though it's stated in the PHP sign up script. Nothing is being transferred into my database(which has no errors with it). If someone could tell me what I'm doing wrong that would be great. (P.S. footer.php and header.php are correct and included in the form)

Sign up error handlers and sign up script:

<?php

if (isset($_POST['submit'])) {

include_once 'dbh.inc.php';

$first = mysqli_real_escape_string($conn, $_POST)$_POST['first'];
$last = mysqli_real_escape_string($conn, $_POST)$_POST['last'];
$email = mysqli_real_escape_string($conn, $_POST)$_POST['email'];
$username = mysqli_real_escape_string($conn, $_POST)$_POST['username'];
$password = mysqli_real_escape_string($conn, $_POST)$_POST['password'];

//Error handlers
//Check for empty fields
if (empty($first)) || (empty($last)) || (empty($email)) ||
(empty($username)) || (empty($password)) {
    header("Location: ../signup.php?signup=empty");
    exit();
} else {
    //Check is input characters are valid
    if (!preg_match("/^[a-zA-Z]*$/", $first) || (!preg_match("/^[a-zA-
Z]*$/", $last)) {
        header("Location: ../signup.php?signup=invalid");
        exit();
    } else {
        //Check if email is valid
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            header("Location: ../signup.php?signup=empty");
            exit();
        } else {
            $sql = "SELECT * FROM users WHERE user_username='username'";
            $result = mysqli_query($conn, $sql);
            $resultCheck = mysqli_num_rows($result);

            if ($resultCheck > 0) {
                header("Location: ../signup.php?signup=usertaken");
                exit();
            } else {
                //Hashing the password
                $hashedPassword = password_hash($password,
PASSWORD_DEFAULT);
                //Insert the user into the database
                $sql = "INSERT INTO users (user_first, user_last,
 user_email, user_username, user_password) VALUES ('$first', '$last',
'$email', '$username' '$hashedPassword');";
                mysqli_query($conn, $sql);
                header("Location: ../signup.php?signup=success");
                exit();
            }
        }
    }
 }

} else {
header("Location: ../signup.php");
exit();
}

Database connection:

<?php

$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbServername = "loginsystem";

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword,
$dbServername);

Sign up form(html in a php file):

<?php include_once 'header.php';?>

Sign Up

    <form class="Sign" action="includes/signup.inc.php" method="POST">
        <input type="text" name="first" placeholder="First Name">

        <input type="text" name="last" placeholder="Last Name">

        <input type="email" name="email" placeholder="E-mail">

        <input type="text" name="username" placeholder="Username">

        <input type="password" name="password" placeholder="Password">

        <button type="submit" name="">Sign Up!</button>

    </form>

<?php include_once 'footer.php';?>

Please help if you can. It would be much appreciated. Thanks!

Body:
Give the name 'submit' to submit button of your HTML Signup Page:

 <button type="submit" name="submit">Sign Up!</button>

Change PHP Signup Page POST:

$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);

Change empty values checking of stmt to:

if ( (empty($first)) || (empty($last)) or (empty($email)) || (empty($username)) || (empty($password)) )

Change input characters validity checking if stmt to:

if ( (!preg_match("/^[a-zA-Z]*$/", $first)) || ((!preg_match("/^[a-zA-Z]*$/", $last)) ) )


问:
How to open a new window using MVVM Light Toolkit
I am using MVVM Light toolkit in my WPF application. I would like to know what is the best approach for opening a new window from an existing window. I have got this MainViewModel, which is responsible for MainWindow of my application. Now in the MainView, on a button click, I would like to open a second window on top of it. I have got RelayCommmand binded to the Button's Command. In the RelayCommand's method, I can create a new window object and simply call Show(), something like this:

```<code>var view2 = new view2()
view2.Show()
</code>```

but I don't think the ViewModel should be responsible for creating the new view2 object. I have read this post WPF MVVM Get Parent from VIEW MODEL where Bugnion has suggested to pass message to the view1 from the viewmodel1 and then view1 should create the new view2. But I am not sure what does he actually mean by passing the message to the view1? How should the view1 handle the message? In it's code behind or what?

Regards,
Nabeel

答:
Why do you go this route? Its simple. If you replace your button with a toggleButton, or a hyperlink, or any other number of button-like controls, you don't need to update your "code behind" - its a basic principle of the MVVM pattern. In your new toggleButton (or whatever), you still end up binding to the same exact Command.

For example, I'm creating a project for a client who wants to have 2 UI's - one is going to be fundamentally different in every way, in terms of presentation. Horizontal tabs vs Vertical RadPanelBar (think Accordion) for navigation. Both of these views can point to the same viewModel - when a user clicks the Work Order tab in View 1, it fires the same "WorkOrderCommand" that's fired in the Work Order Header in the panel bar.

In a code-behind model, you'd have to code two separate events. Here you only have to code one.

Furthermore, it allows a designer using Blend to create any layout they want. As long as they have the hooks (EventToCommand control) in place, myself (as a developer) couldn't care less what the final product looks like.

Loose coupling is incredibly powerful.

Body:
I am using MVVM Light toolkit in my WPF application. I would like to know what is the best approach for opening a new window from an existing window. I have got this MainViewModel, which is responsible for MainWindow of my application. Now in the MainView, on a button click, I would like to open a second window on top of it. I have got RelayCommmand binded to the Button's Command. In the RelayCommand's method, I can create a new window object and simply call Show(), something like this:

var view2 = new view2()
view2.Show()

but I don't think the ViewModel should be responsible for creating the new view2 object. I have read this post WPF MVVM Get Parent from VIEW MODEL where Bugnion has suggested to pass message to the view1 from the viewmodel1 and then view1 should create the new view2. But I am not sure what does he actually mean by passing the message to the view1? How should the view1 handle the message? In it's code behind or what?

Regards,
Nabeel

ContentLicense: CC BY-SA 2.5


问:
Graph with no 3-clique that needs at least 4 colors
Give an example of a graph that has the following properties.  (Note that you need to give a single graph as the answer.)

The graph does not contain a triangle (that is, a clique of 3 vertices) as a subgraph.
Graph needs at least 4 colors for a proper vertex coloring
[If you think that such a graph is not possible, then prove that statement.]

1.Tomorrow we have a final exam, and this question may on the exam paper.
2.I think it is impossible to draw such a graph. But how to prove? Thank u very much.

答:
A web search finds https://en.wikipedia.org/wiki/Gr%C3%B6tzsch_graph

The Grötzsch graph is a member of an infinite sequence of triangle-free graphs, each the Mycielskian of the previous graph in the sequence, starting from the null graph; this sequence of graphs was used by Mycielski (1955) to show that there exist triangle-free graphs with arbitrarily large chromatic number. Therefore, the Grötzsch graph is sometimes also called the Mycielski graph or the Mycielski–Grötzsch graph. Unlike later graphs in this sequence, the Grötzsch graph is the smallest triangle-free graph with its chromatic number (Chvátal 1974).


问:
How do I add files to an existing zip archive
How can I add some file (almost always a single .csv file) to an existing zip file?</p>

答:
For creating, extracting, and opening zip archives, we can use ZipFile Class with reference: System.IO.Compression.FileSystem. For .NET 4.5.2 and below, we also need to add reference: System.IO.Compression. Here's the method for adding files to zip:</p>

```<code>    public static void AddFilesToZip(string zipPath, string[] files)
    {
        if (files == null || files.Length == 0)
        {
            return;
        }

        using (var zipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
        {
            foreach (var file in files)
            {
                var fileInfo = new FileInfo(file);
                zipArchive.CreateEntryFromFile(fileInfo.FullName,  fileInfo.Name);
            }
        }
    }
</code>```

Body:
For creating, extracting, and opening zip archives, we can use ZipFile Class with reference: System.IO.Compression.FileSystem. For .NET 4.5.2 and below, we also need to add reference: System.IO.Compression. Here's the method for adding files to zip:

    public static void AddFilesToZip(string zipPath, string[] files)
    {
        if (files == null || files.Length == 0)
        {
            return;
        }

        using (var zipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
        {
            foreach (var file in files)
            {
                var fileInfo = new FileInfo(file);
                zipArchive.CreateEntryFromFile(fileInfo.FullName,  fileInfo.Name);
            }
        }
    }

ContentLicense: CC BY-SA 4.0


问:
window.print() doesn't show updated div
This post obviously wasn't well presented but rather than delete and re-post, I've edited it to try to make it clearer.

Putting it simply, there are a number of elements on my page where I want to be able to print content only within a particular div where all other divs are hidden. I found a post that describes defining a style as per below:

```<code><style>
    @media print {
        body.printing * { display: none; }
        body.printing #print-me { display: block; }
    }

    @media screen {
        #print-me { display: none; }
    }
</style>
</code>```

In the body I have a div as below:

```<code><div id='print-me'>
      <h1>Hello Plunker!</h1>
</div>
</code>```

When the document has loaded, I'm trying to change the content in the print-me div to something else as per below, and using information kindly provided by eddie who responded to this post. The printing class is added to hide all other elements from the body of the document with the print-me div now set to display in a print window.

```<code>$(document).ready(function() {
  $("body").addClass("printing");
  document.getElementById('print-me').innerHTML = '<p>crikey</p>';

  var htmlText = '<p>HTML TO PRINT</p>';

     $( "#print-me" ).html( htmlText ).promise().done(function() {
            window.print();
    });
});
</code>```

However, if you view the Plunker example at the below link

enter link description here

you'll see that the print window opens up and the text that I'm setting the print-me div to doesn't display. The code in question looks as per below:

```<code>  $("body").addClass("printing");

  var htmlText = '<p>HTML TO PRINT</p>';

     $( "#print-me" ).html( htmlText ).promise().done(function() {
            window.print();
    });
</code>```

if I change that to:

```<code>  $("body").addClass("printing");

  var htmlText = '<p>HTML TO PRINT</p>';

     $( "#print-me" ).text( htmlText ).promise().done(function() {
            window.print();
    });
</code>```

then that does update the print-me div and displays in the print window. However, the htmlText displays literally and not as html.

Why does the former not display whereas the latter does, albeit as plain text.

I hope this better explains the problem, thank you for any help/suggestions on what is going on and how to solve the problem and/or how to improve the post.

答:
This works on me.

HTML

```<code><div id='print-section'></div>
<div id='print-btn'></div>
</code>```

CSS: On print, you should set all as hidden except for the print div on print

```<code>@media print {
    body * {
        visibility: hidden;
    }

    @page {size: portrait}

    #print-section {
        visibility: visible;
        width : 100%;
        height : auto;
    }
}
</code>```

JS: On the button, you should wait for the html to fully added the dynamic content and call window.print();

```<code>$("#print-btn").click(function(){
     var htmlText = '<p>HTML TO PRINT</p>';

     $( "#print-section" ).html( htmlText ).promise().done(function() {
            window.print();
    });
});
</code>```

Title: window.print() doesn't show updated div

Body:
This post obviously wasn't well presented but rather than delete and re-post, I've edited it to try to make it clearer.

Putting it simply, there are a number of elements on my page where I want to be able to print content only within a particular div where all other divs are hidden. I found a post that describes defining a style as per below:

In the body I have a div as below:

Hello Plunker!

When the document has loaded, I'm trying to change the content in the print-me div to something else as per below, and using information kindly provided by eddie who responded to this post. The printing class is added to hide all other elements from the body of the document with the print-me div now set to display in a print window.

$(document).ready(function() {
  $("body").addClass("printing");
  document.getElementById('print-me').innerHTML = '
crikey
';

  var htmlText = '
HTML TO PRINT
';

     $( "#print-me" ).html( htmlText ).promise().done(function() {
            window.print();
    });
});

However, if you view the Plunker example at the below link

enter link description here

you'll see that the print window opens up and the text that I'm setting the print-me div to doesn't display. The code in question looks as per below:

  $("body").addClass("printing");

  var htmlText = '
HTML TO PRINT
';

     $( "#print-me" ).html( htmlText ).promise().done(function() {
            window.print();
    });

if I change that to:

  $("body").addClass("printing");

  var htmlText = '
HTML TO PRINT
';

     $( "#print-me" ).text( htmlText ).promise().done(function() {
            window.print();
    });

then that does update the print-me div and displays in the print window. However, the htmlText displays literally and not as html.

Why does the former not display whereas the latter does, albeit as plain text.

I hope this better explains the problem, thank you for any help/suggestions on what is going on and how to solve the problem and/or how to improve the post.

Body:
This works on me.

HTML

<div id='print-section'></div>
<div id='print-btn'></div>

CSS: On print, you should set all as hidden except for the print div on print

@media print {
    body * {
        visibility: hidden;
    }

    @page {size: portrait}

    #print-section {
        visibility: visible;
        width : 100%;
        height : auto;
    }
}

JS: On the button, you should wait for the html to fully added the dynamic content and call window.print();

$("#print-btn").click(function(){
     var htmlText = '<p>HTML TO PRINT</p>';

     $( "#print-section" ).html( htmlText ).promise().done(function() {
            window.print();
    });
});


问:
Module Resolution in TypeScript using Globbing Pattern with multiple wildcards
I'm working on an Angular project with the following folder structure (hypothetical):

```<code>src
└── app
    ├── component1
    │   └── component1.component.ts
    └── component2
        └── component2.component.ts
tsconfig.json
</code>```

In my tsconfig.json I'm trying to define a path with globbing patterns in a way that importing from @components/component1 would resolve to src/app/component1/component1.component.

This is my tsconfig.json:

```<code>OTHER STUFF...

"baseUrl": "src",
"paths": {
  "@components/*": ["app/*/*.component"]
}
</code>```

With this in place, I have the following import in some module/service/etc.:

import { Component1 } from '@components/component1';

The error I'm getting at compile time is:

```<code>ERROR in error TS5062: Substitution 'app/*/*.component' in pattern '@components/*' in can have at most one '*' character.
</code>```

How can I achieve this without causing errors in the TypeScript compiler? What would be the proper way to write the globbing pattern in tsconfig.json?

Any help is appreciated.

Note

I don't want to do @components/component1/component1.

答:
As compiler error says, there cannot be more than one * in paths entry.

This can potentially be solved with Webpack aliases, possibly via third-party plugin. If the project uses Angular CLI, Webpack configuration has to be ejected.

The problem with importing separate files like @components/component1/component1 is commonly solved with barrels, which are index.ts files that re-export directory contents:

```<code>export * from './component1.component';
</code>```

Body:
I'm working on an Angular project with the following folder structure (hypothetical):

src
└── app
    ├── component1
    │   └── component1.component.ts
    └── component2
        └── component2.component.ts
tsconfig.json

In my tsconfig.json I'm trying to define a path with globbing patterns in a way that importing from @components/component1 would resolve to src/app/component1/component1.component.

This is my tsconfig.json:

OTHER STUFF...

"baseUrl": "src",
"paths": {
  "@components/*": ["app/*/*.component"]
}

With this in place, I have the following import in some module/service/etc.:

import { Component1 } from '@components/component1';

The error I'm getting at compile time is:

ERROR in error TS5062: Substitution 'app/*/*.component' in pattern '@components/*' in can have at most one '*' character.

How can I achieve this without causing errors in the TypeScript compiler? What would be the proper way to write the globbing pattern in tsconfig.json?

Any help is appreciated.

Note

I don't want to do @components/component1/component1.

Body:
As compiler error says, there cannot be more than one * in paths entry.

This can potentially be solved with Webpack aliases, possibly via third-party plugin. If the project uses Angular CLI, Webpack configuration has to be ejected.

The problem with importing separate files like @components/component1/component1 is commonly solved with barrels, which are index.ts files that re-export directory contents:

export * from './component1.component';


问:
Bootstrap Element 100% Width
I want to create alternating 100% colored blocks. An "ideal" situation is illustrated as an attachment, as well as the current situation.

Desired setup:

Currently:

My first idea was to create an div class, give it a background color, and give it 100% width.

```<code>.block {
    width: 100%;
    background: #fff;
}
</code>```

However, you can see that this obviously doesn't work. It's confined to a container area. I tried to close the container and that didn't work either.

答:
Instead of

```<code>style="width:100%"
</code>```

try using

```<code>class="col-xs-12"
</code>```

it will save you 1 character :)

Title: Bootstrap Element 100% Width

Body:
I want to create alternating 100% colored blocks. An "ideal" situation is illustrated as an attachment, as well as the current situation.

Desired setup:

Currently:

My first idea was to create an div class, give it a background color, and give it 100% width.

.block {
    width: 100%;
    background: #fff;
}

However, you can see that this obviously doesn't work. It's confined to a container area. I tried to close the container and that didn't work either.

Body:
Instead of

style="width:100%"

try using

class="col-xs-12"

it will save you 1 character :)


问:
How to convert dynamic to unknown class in runtime
I have a dynamic rule engine and i want to pass class to this and each time the class is sent differently.

For example:

```<code>Order MyOrder = new Order()
{
  OrderId = 1,
  Customer = new Customer()
  {
    FirstName = "John",
    LastName = "Doe",
    Country = new Country()
    {
      CountryCode = "AUS"
    }
  },
  Items = new List<Item>(){
    new Item(){ ItemCode = "MM23", Cost=5.25M},
    new Item(){ ItemCode = "LD45", Cost=5.25M},
    new Item(){ ItemCode = "Test", Cost=3.33M},
  }
};
</code>```

I want to change this:

```<code>var compiledRule = engine.CompileRule<Order>(rule);
</code>```

to :

```<code>dynamic obj = MyOrder;
var compiledRule = engine.CompileRule<?????>(rule);
</code>```

how can I get Type of obj and put instead of  "????"

答:
I found solution after search a lot

```<code>var engine = new MRE();
var compiledRule = engine.CompileRule<Order>(rule);
</code>```

change to:

```<code>var engine = new MRE();
var compiledRule = typeof(MRE).GetMethod("CompileRule").MakeGenericMethod(myOrder.GetType())
                        .Invoke(engine, new object[] { rule}) as dynamic;
</code>```

Body:
I have a dynamic rule engine and i want to pass class to this and each time the class is sent differently.

For example:

Order MyOrder = new Order()
{
  OrderId = 1,
  Customer = new Customer()
  {
    FirstName = "John",
    LastName = "Doe",
    Country = new Country()
    {
      CountryCode = "AUS"
    }
  },
  Items = new List<Item>(){
    new Item(){ ItemCode = "MM23", Cost=5.25M},
    new Item(){ ItemCode = "LD45", Cost=5.25M},
    new Item(){ ItemCode = "Test", Cost=3.33M},
  }
};

I want to change this:

var compiledRule = engine.CompileRule<Order>(rule);

to :

dynamic obj = MyOrder;
var compiledRule = engine.CompileRule<?????>(rule);

how can I get Type of obj and put instead of  "????"

Body:
I found solution after search a lot

var engine = new MRE();
var compiledRule = engine.CompileRule<Order>(rule);

change to:

var engine = new MRE();
var compiledRule = typeof(MRE).GetMethod("CompileRule").MakeGenericMethod(myOrder.GetType())
                        .Invoke(engine, new object[] { rule}) as dynamic;


问:
Laravel artisan serve error
I get this error when I run the php artisan serve command to launch laravel am a beginner in laravel

PHP Warning:  require(/home/matynjr/events/vendor/autoload.php): failed to open stream: No such file or directory in /home/matynjr/events/artisan on line 18

PHP Fatal error:  require(): Failed opening required '/home/matynjr/events/vendor/autoload.php' (include_path='.:/usr/share/php') in /home/matynjr/events/artisan on line 18

答:
You need to go to your project room and install dependencies. It says that there is no vendor folder. Vendor folder is a part of composer. It holds dependency files inside.

Run composer install in the project root. It is a good idea to run composer update after that.

Title: Laravel artisan serve error


问:
Pass URL as request String
I am trying to pass URL as a request parameter to a Spring Rest controller but I am getting an empty string.</p>

```<code>@RequestMapping(value = "/create", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})
    public Response getMessage(HttpServletRequest request, @RequestParam("url") String url){}
</code>```

答:
Use the getRequestURL() method of your HttpServletRequest object, i.e. request to get the URL of your request.
If you are trying to pass another URL as a parameter, revisit your view file and ensure that the correct parameter is being passed to your controller method.

Title: Pass URL as request String

Body:
I am trying to pass URL as a request parameter to a Spring Rest controller but I am getting an empty string.

@RequestMapping(value = "/create", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})
    public Response getMessage(HttpServletRequest request, @RequestParam("url") String url){}


问:
Model query function for Controller :: how do I call w/ pagination in Controller?
I cannot resolve how to call a model query function into a controller. I've been through too much documentation to count. Maybe I am wrong in what I am trying to do altogether? Continue to get MySQL errors (errors below).

Plan :: Model:

```<code>function getActive()
{
$findParameters = array(
    'limit' => 10,
    'order' => array('Plan.monthly_cost' => 'asc'),
    'conditions' => array('PlanDetail.active' => 1)
);
return $this->find('all', $findParameters);
}
</code>```

Plan :: Controller:

```<code>function search() {
    $this->Plan->recursive = 2; //*** Modified by Jason: Recursion needs to be corrected with better method. ***//
    $active = $this->Plan->getActive();
    $this->set('plans', $this->paginate($active));
}
</code>```

Notice (8): Array to string conversion [ROOT....
Warning (512): SQL Error: 1054: Unknown column 'Plan' in 'where clause'

答:
Basically $this->paginate doesn't accept result of the query as first parameter. If you so much like to have your DB logic in the model do it this way:

Model

```<code>function getActiveConditions() {
    retrun array(
       'limit' => 10,
       'order' => array('Plan.monthly_cost' => 'asc'),
       'conditions' => array('PlanDetail.active' => 1)
    );
}
</code>```

in your Controller:

```<code>function search() {
    $this->Plan->recursive = 2;
    $activeConditions = $this->Plan->getActiveConditions();
    $this->set('plans', $this->paginate($this->Plan, $activeConditions));
}
</code>```

The explanation: paginate method paginates a model passed as first argument (or if it's null get's the controller's default model) and uses second parameter to apply some restrictions for the result.

Check Containable behaviour for this recursive=2, or at least unbind these relations which are not necessary.

Body:
I cannot resolve how to call a model query function into a controller. I've been through too much documentation to count. Maybe I am wrong in what I am trying to do altogether? Continue to get MySQL errors (errors below).

Plan :: Model:

function getActive()
{
$findParameters = array(
    'limit' => 10,
    'order' => array('Plan.monthly_cost' => 'asc'),
    'conditions' => array('PlanDetail.active' => 1)
);
return $this->find('all', $findParameters);
}

Plan :: Controller:

function search() {
    $this->Plan->recursive = 2; //*** Modified by Jason: Recursion needs to be corrected with better method. ***//
    $active = $this->Plan->getActive();
    $this->set('plans', $this->paginate($active));
}

Notice (8): Array to string conversion [ROOT....
Warning (512): SQL Error: 1054: Unknown column 'Plan' in 'where clause'

Body:
Basically $this->paginate doesn't accept result of the query as first parameter. If you so much like to have your DB logic in the model do it this way:

Model

function getActiveConditions() {
    retrun array(
       'limit' => 10,
       'order' => array('Plan.monthly_cost' => 'asc'),
       'conditions' => array('PlanDetail.active' => 1)
    );
}

in your Controller:

function search() {
    $this->Plan->recursive = 2;
    $activeConditions = $this->Plan->getActiveConditions();
    $this->set('plans', $this->paginate($this->Plan, $activeConditions));
}

The explanation: paginate method paginates a model passed as first argument (or if it's null get's the controller's default model) and uses second parameter to apply some restrictions for the result.

Check Containable behaviour for this recursive=2, or at least unbind these relations which are not necessary.


问:
Show a custom 403 error page in ASP.NET MVC 2
I want to show a custom 403 page in my ASP.NET MVC 2 application. I added following to my config file:

<httpErrors>
      <remove statusCode="403" subStatusCode="-1"/>
      <error statusCode="403" path="/403.htm" responseMode="ExecuteURL"/>
</httpErrors>
```

I am still seeing the default ASP.NET 403 error page. What's wrong?

答:
Many good suggestions here; for me, it was occurring under visual studio and visual studio started a different web project into the same port as my web project was specified to load in it's config, so it was just refreshing the error on my other projet (which doesn't have a global.asax) no matter what change I made to the second web project.

The underlying issue turned out to be that my other site had the same port configured in visual studio so it kept loading first due to the solution project order and using up the port.  I changed it to another port and the issue went away.

Body:
I want to show a custom 403 page in my ASP.NET MVC 2 application. I added following to my config file:

<httpErrors>
      <remove statusCode="403" subStatusCode="-1"/>
      <error statusCode="403" path="/403.htm" responseMode="ExecuteURL"/>
</httpErrors>

I am still seeing the default ASP.NET 403 error page. What's wrong?


问:
Accessing a stateless EJB from another instance of Glassfish
there is an issue that troubles me and I cannot find any uniform way to solve it around the internet. I am developing an enterprise application using Java EE, Glassfish and Netbeans.

I have two instances of Glassfish set up, and I am building an enterprise application split among the two. I have a web page (with a couple of JSPs and a couple of HttpServlets) running on one instance of Glassfish. On the other instance, I want to implement the business logic of the app. That is, I have some Java Entity Beans in it, and also an EJB with a remote interface that uses these entity beans.

My goal is to be able to access the EJB remotely from the servlets on the first instance of glassfish. I have followed the instructions found in this post but unsuccessfully. I am providing code snippets to get more specific...

On one instance of Glassfish, EJB's remote Interface:

```<code>@Remote
public interface MyEjbRemote {
     //...
}
</code>```

and the stateless bean:

```<code>@Stateless(name="ejb/MyEjb")
public class MyEjb implements MyEjbRemote {
     //...
}
</code>```

On the other instance:

```<code>public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        MyEjbRemote = lookupEjb();
        //...
    }

    private MyEjbRemote lookupEjb() {
        Properties props = new Properties();
        props.setProperty("java.naming.factory.initial",
            "com.sun.enterprise.naming.SerialInitContextFactory");
        props.setProperty("java.naming.factory.url.pkgs",
            "com.sun.enterprise.naming");
        props.setProperty("java.naming.factory.state",
            "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");

        //default: localhost
        props.setProperty("org.omg.CORBA.ORBInitialHost",
            "localhost");
        //default: 3700
        props.setProperty("org.omg.CORBA.ORBInitialPort", "2037");

        InitialContext ic = new InitialContext(props);
        return (MyEjbRemote) ic.lookup("ejb/MyEjb");
    }
}
</code>```

Unfortunately when I launch my website and try to lookup the remote ejb I get the following exception:

```<code>WARNING: Internal error flushing the buffer in release()
WARNING: StandardWrapperValve[jsp]: PWC1406: Servlet.service() for servlet jsp threw exception
java.io.IOException: Stream closed
    at org.apache.jasper.runtime.JspWriterImpl.ensureOpen(JspWriterImpl.java:277)
    at org.apache.jasper.runtime.JspWriterImpl.clearBuffer(JspWriterImpl.java:222)
    at org.apache.jsp.home_jsp._jspService(home_jsp.java from :76)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:109)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:406)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:483)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:373)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
    at java.lang.Thread.run(Thread.java:662)
</code>```

What is missing from my implementation?Any suggestions/ideas? Please ask if something is missing from the description of my problem, it's my first time posting in this site. I appreciate your time!

Ilias

答:
I see a few wrongs here.

The most practical is probably that the exception is from a JSP page and seemingly has nothing to do with the Servlet nor the EJB access. Both of these do not appear in the stack trace. You probably have a JSP called home.jsp. It's trying to write to the response, but the stream that represents it has already been closed. Somewhere you're doing something nasty, but it's very probably unrelated to EJB.

A more theoretical wrong is that your design looks like a big anti-pattern. Using remote EJB calls for the sole sake of "separating business logic" is an EXTREMELY bad idea. If you want to separate your business logic, just put your EJBs in an EJB module, your Servlets and JSPs in a WEB (war) module and bundle the two together in an EAR. Use local interfaces. Creating a project supporting this is typically only a few clicks in IDEs like Netbeans or Eclipse, and the performance and sanity of your design is much, much better.

Note that remote EJBs most definitely have their use, but they should be used very sparingly. Use them to control coarse grained jobs or so on a remote server, where the particular instance of that server has a specific meaning. E.g. you might have a single gateway server in your cluster where messages (via JMS) are queued and processed in batch to be send to the external network. Use remote EJBs here to administrate that remote server.

From your problem description I taste that you want to use this second Glassfish instance for 'regular' fine-grained business logic. Unless you are 100% certain about what you are doing and you are 100% certain that your specific problem absolutely requires remote communication, I strongly advice you to drop this idea.

Body:
there is an issue that troubles me and I cannot find any uniform way to solve it around the internet. I am developing an enterprise application using Java EE, Glassfish and Netbeans.

I have two instances of Glassfish set up, and I am building an enterprise application split among the two. I have a web page (with a couple of JSPs and a couple of HttpServlets) running on one instance of Glassfish. On the other instance, I want to implement the business logic of the app. That is, I have some Java Entity Beans in it, and also an EJB with a remote interface that uses these entity beans.

My goal is to be able to access the EJB remotely from the servlets on the first instance of glassfish. I have followed the instructions found in this post but unsuccessfully. I am providing code snippets to get more specific...

On one instance of Glassfish, EJB's remote Interface:

@Remote
public interface MyEjbRemote {
     //...
}

and the stateless bean:

@Stateless(name="ejb/MyEjb")
public class MyEjb implements MyEjbRemote {
     //...
}

On the other instance:

public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        MyEjbRemote = lookupEjb();
        //...
    }

    private MyEjbRemote lookupEjb() {
        Properties props = new Properties();
        props.setProperty("java.naming.factory.initial",
            "com.sun.enterprise.naming.SerialInitContextFactory");
        props.setProperty("java.naming.factory.url.pkgs",
            "com.sun.enterprise.naming");
        props.setProperty("java.naming.factory.state",
            "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");

        //default: localhost
        props.setProperty("org.omg.CORBA.ORBInitialHost",
            "localhost");
        //default: 3700
        props.setProperty("org.omg.CORBA.ORBInitialPort", "2037");

        InitialContext ic = new InitialContext(props);
        return (MyEjbRemote) ic.lookup("ejb/MyEjb");
    }
}

Unfortunately when I launch my website and try to lookup the remote ejb I get the following exception:

WARNING: Internal error flushing the buffer in release()
WARNING: StandardWrapperValve[jsp]: PWC1406: Servlet.service() for servlet jsp threw exception
java.io.IOException: Stream closed
    at org.apache.jasper.runtime.JspWriterImpl.ensureOpen(JspWriterImpl.java:277)
    at org.apache.jasper.runtime.JspWriterImpl.clearBuffer(JspWriterImpl.java:222)
    at org.apache.jsp.home_jsp._jspService(home_jsp.java from :76)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:109)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:406)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:483)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:373)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
    at java.lang.Thread.run(Thread.java:662)

What is missing from my implementation?Any suggestions/ideas? Please ask if something is missing from the description of my problem, it's my first time posting in this site. I appreciate your time!

Ilias


问:
VB Excel Macro Millisecond Timing
I am trying to write a macro in VB for an Excel spreadsheet which is executed in specific intervals which are defined by a value (in Hz) contained in the spreadsheet itself. My problem is that the code I found for accomplishing an automatic macro in this way appears to only allow for second accuracy, so any frequencies above 1Hz are not possible. I would like to be able to get up to around 10Hz if possible, which would require millisecond accuracy.

I am new to VB, so I do not know much about it. Here is the code:

```<code>Sub Macro2()
    Range("K1").Select
    Dim f As Single
    f = ActiveCell.Value
    Dim t As Integer
    t = 1 / f
    dTime = Now + TimeSerial(0, 0, t)
    Application.OnTime dTime, "Macro2"
    Range("J1").Select
    Dim c As Integer
    c = ActiveCell.Value
    c = c Xor 1
    ActiveCell.Value = c
End Sub
</code>```

Is there any way to get Millisecond accuracy using this method?

答: if there is no need to use the exact value of milliseconds, but only "as soon as possible", you can use TimeSerial(0, 0, 0)

Title: VB Excel Macro Millisecond Timing

Body:
I am trying to write a macro in VB for an Excel spreadsheet which is executed in specific intervals which are defined by a value (in Hz) contained in the spreadsheet itself. My problem is that the code I found for accomplishing an automatic macro in this way appears to only allow for second accuracy, so any frequencies above 1Hz are not possible. I would like to be able to get up to around 10Hz if possible, which would require millisecond accuracy.

I am new to VB, so I do not know much about it. Here is the code:

Sub Macro2()
    Range("K1").Select
    Dim f As Single
    f = ActiveCell.Value
    Dim t As Integer
    t = 1 / f
    dTime = Now + TimeSerial(0, 0, t)
    Application.OnTime dTime, "Macro2"
    Range("J1").Select
    Dim c As Integer
    c = ActiveCell.Value
    c = c Xor 1
    ActiveCell.Value = c
End Sub

Is there any way to get Millisecond accuracy using this method?


问:
Where is the digital signature stored when code signing a exe file in windows?
As stated in the question title. However, I am using a "trick" where i store extra data after the executable to be used at runtime (see here).

Signing my executable appears to break this 'trick' however, so my question is where is the signature stored in the exe (PE) file?

I am usingsigntool from microsoft to sign my executable.

答:
The format of a signed PE file is documented by Microsoft:

Windows Authenticode Portable Executable Signature Format [This link downloads a WORD doc]


问:
remove the delete button ⛔ on table rows in edit mode
I am trying to learn Swift, but there is a problem in my project that drives me nuts.
I have a working list of data in a ViewController fed by parse.com. I managed to implement a swipe-feature that reveals buttons for both deleting and editing. That is working fine. Now I want the user to be able to reorder the cells. So I successfully implemented a button to put the table into editing-mode. My 2 problems with that are:

When I enter edit-mode I just want to be able to reorder the cells since editing and deleting is done via swipe (via "tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath)". How can I achive that the user doesn't see the 2 buttons for deleting and editing when in editing-mode and touching the delete-circle that is provided automatically?

Is it possible to remove the delete-circle altogether? Using "UITableViewCellEditingStyle.None" also disables the swipe-functionality.

Thanks in advance!

答:
To avoid the round red delete button that appears when you put set UITableView isEditing to true at the left and does nothing when you click it, the minimum that worked for me was this (Swift 4, iOS 11)

// Avoid the round red delete button on the left of the cell:

```<code>func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
    return false
}

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    return .none
}
</code>```

I also have these functions, which probably interact:

```<code>func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return savedTempTable.isEditing
}

// Including this function in the delegate enable left-swipe deleting
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
    if editingStyle == .delete {
        savedConversions.remove(at: indexPath.row)
    }
}

// Including this function enables reordering
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath,to destinationIndexPath: IndexPath)
{
    let elem = savedConversions.remove(at: sourceIndexPath.row)
    savedConversions.insert(elem, at: destinationIndexPath.row)
}
</code>```

Body:
To avoid the round red delete button that appears when you put set UITableView isEditing to true at the left and does nothing when you click it, the minimum that worked for me was this (Swift 4, iOS 11)

// Avoid the round red delete button on the left of the cell:

func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
    return false
}

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    return .none
}

I also have these functions, which probably interact:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return savedTempTable.isEditing
}

// Including this function in the delegate enable left-swipe deleting
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
    if editingStyle == .delete {
        savedConversions.remove(at: indexPath.row)
    }
}

// Including this function enables reordering
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath,to destinationIndexPath: IndexPath)
{
    let elem = savedConversions.remove(at: sourceIndexPath.row)
    savedConversions.insert(elem, at: destinationIndexPath.row)
}


问:
How do I record and play back sound on the iPhone?
In my app I've got certain buttons which use the following code:

```<code>SystemSoundID beep;

CFStringRef beepPath = (CFStringRef) [NSString stringWithFormat: @"%@/SoundFile.aif", [[NSBundle mainBundle] bundlePath]];
AudioServicesCreateSystemSoundID (CFURLCreateWithFileSystemPath (NULL, beepPath, kCFURLPOSIXPathStyle, false), &beep);
CFRelease(beepPath);

AudioServicesPlaySystemSound (beep);
</code>```

I would like the user to start recording and be able to record any sounds made by the app and then have the ability to play the recorded sound after a certain time limit, or have a stop recording button and then a 'Play' button to play the recorded clip.

Any ideas on how I can implement this?

答: The obvious solution would be to save the sequence of user actions in an NSArray, and play them back to recreate the sounds. I'm not sure that you can record the output sound channel into another file, if that's what you're trying to do.</p>

Body:
In my app I've got certain buttons which use the following code:

SystemSoundID beep;

CFStringRef beepPath = (CFStringRef) [NSString stringWithFormat: @"%@/SoundFile.aif", [[NSBundle mainBundle] bundlePath]];
AudioServicesCreateSystemSoundID (CFURLCreateWithFileSystemPath (NULL, beepPath, kCFURLPOSIXPathStyle, false), &beep);
CFRelease(beepPath);

AudioServicesPlaySystemSound (beep);

I would like the user to start recording and be able to record any sounds made by the app and then have the ability to play the recorded sound after a certain time limit, or have a stop recording button and then a 'Play' button to play the recorded clip.

Any ideas on how I can implement this?

OwnerDisplayName: Mark Bessey


问:
Immediately resolve an activity
From my MainActivity I'm calling a function that may or may not need to start another activity (a popup dialog) to return a result. In the case that it doesn't need to start another activity, how can I trigger onActivityResult without creating another window?

The use case is that, before performing certain activities, the user needs to have clicked an "I know what I'm doing." button at least 5 minutes before the app lets them do it. I'm trying to extract this into a function.

An analogy would be Promise.resolve in JavaScript.

答:
The pattern you want to follow here is to abstract your logic from onActivityResult(). In the below example, the activity wants to make sure that the user is signed in. The result handling logic is in handleSignInResult(). If the user is not signed in, then the activity for sign-in will be launched. If the user is signed in, then handleSignInResult() is called immediately.</p>

```<code>private void init() {
    if(Foo.isSignedIn()) {
        this.handleSignInResult(true);
    } else {
        // TODO Launch the activity which will later cause onActivityResult() to be invoked
    }
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // TODO Check intent data to determine how to call handleSignInResult()
    boolean success = true;
    this.handleSignInResult(success);
}

private void handleSignInResult(boolean isSignedIn) {
    // Do the stuff
}
</code>```

Title: Immediately resolve an activity

Body:
The pattern you want to follow here is to abstract your logic from onActivityResult(). In the below example, the activity wants to make sure that the user is signed in. The result handling logic is in handleSignInResult(). If the user is not signed in, then the activity for sign-in will be launched. If the user is signed in, then handleSignInResult() is called immediately.

private void init() {
    if(Foo.isSignedIn()) {
        this.handleSignInResult(true);
    } else {
        // TODO Launch the activity which will later cause onActivityResult() to be invoked
    }
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // TODO Check intent data to determine how to call handleSignInResult()
    boolean success = true;
    this.handleSignInResult(success);
}

private void handleSignInResult(boolean isSignedIn) {
    // Do the stuff
}


问:
Positioning of footer text
I am trying to add a footer similar to the Airbnb one. I have been able to do the first two columns. However the third one is always slightly below the rest. I've tried:
Position: Absolute (however this makes it disappear)
Position: relative (this works fine however it remove the links from the other two columns).
Float: right and left but doesn't let me move it up.

I'm running out of ideas of what to do so if someone could help me that would be great. here is my code and a image of what I have made.

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 550px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display: table;
  float: left;
  positi
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>

  <div class="col-1">
    Revel
    <hr>
    <span> About us       </span>
    <span> Contact us     </span>
    <span> FAQ            </span>
    <span> Careers        </span>
  </div>

  <div class="col-2">
    Event Host
    <hr>
    <span>  Why use Revel  </span>
    <span>  test           </span>
    <span>  test           </span>
    <span>  Join Revel     </span>
  </div>

  <div class="col-3">
    Event Service
    <hr>
    <span> Why partner with Revel  </span>
    <span> Guidebooks              </span>
    <span> FAQ                     </span>
    <span> Partner with Revel      </span>
  </div>

</footer></code>```

enter image description here

答:
These are the things causing problems:

positi instead of position:relative in col-3

float:left to col-2 as well

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  border: 10px solid green;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
  float: left;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
  float: left;
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>

  <div class="col-1">
    Revel
    <hr>
    <span> About us       </span>
    <span> Contact us     </span>
    <span> FAQ            </span>
    <span> Careers        </span>
  </div>

  <div class="col-2">
    Event Host
    <hr>
    <span>  Why use Revel  </span>
    <span>  test           </span>
    <span>  test           </span>
    <span>  Join Revel     </span>
  </div>

  <div class="col-3">
    Event Service
    <hr>
    <span> Why partner with Revel  </span>
    <span> Guidebooks              </span>
    <span> FAQ                     </span>
    <span> Partner with Revel      </span>
  </div>

</footer></code>```

Title: Positioning of footer text

Body:
I am trying to add a footer similar to the Airbnb one. I have been able to do the first two columns. However the third one is always slightly below the rest. I've tried:
Position: Absolute (however this makes it disappear)
Position: relative (this works fine however it remove the links from the other two columns).
Float: right and left but doesn't let me move it up.

I'm running out of ideas of what to do so if someone could help me that would be great. here is my code and a image of what I have made.

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 550px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display: table;
  float: left;
  positi
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

    Revel

     About us
     Contact us
     FAQ
     Careers

    Event Host

      Why use Revel
      test
      test
      Join Revel

    Event Service

     Why partner with Revel
     Guidebooks
     FAQ
     Partner with Revel

enter image description here

Body:
These are the things causing problems:

positi instead of position:relative in col-3

float:left to col-2 as well

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  border: 10px solid green;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
  float: left;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
  float: left;
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

<footer>

  <div class="col-1">
    Revel
    <hr>
    <span><a href="#" class="footer-links"> About us       </a></span>
    <span><a href="#" class="footer-links"> Contact us     </a></span>
    <span><a href="#" class="footer-links"> FAQ            </a></span>
    <span><a href="#" class="footer-links"> Careers        </a></span>
  </div>

  <div class="col-2">
    Event Host
    <hr>
    <span> <a href="#" class="footer-links"> Why use Revel  </a></span>
    <span> <a href="#" class="footer-links"> test           </a></span>
    <span> <a href="#" class="footer-links"> test           </a></span>
    <span> <a href="#" class="footer-links"> Join Revel     </a></span>
  </div>

  <div class="col-3">
    Event Service
    <hr>
    <span><a href="#" class="footer-links"> Why partner with Revel  </a></span>
    <span><a href="#" class="footer-links"> Guidebooks              </a></span>
    <span><a href="#" class="footer-links"> FAQ                     </a></span>
    <span><a href="#" class="footer-links"> Partner with Revel      </a></span>
  </div>

</footer>


问:
why if condition is working in a weird way
I am just trying to search the key in a binary search Tree.
Here is what I did.

```<code>int searchBST(int key,node *root){

    if(root->data == key){
        printf("The key %d is in the tree.\n",key);
        return 1;
    }
    if(root->left != NULL){
        searchBST(key,root->left);
        return 0;
    }
    if(root->right != NULL){
        searchBST(key,root->right);
        return 0;
    }
}
</code>```

In the main function,check if function return 1, if it does, the key is in the tree.

```<code>printf("Please enter the key value you wish to search for: ");
scanf("%d",&key);
if((searchBST(key,root)) != 1)
    printf("The key %d is not in the tree.\n",key);
</code>```

if the key is not in the tree it will print :

```<code>The key %d is not in the tree.
</code>```

which is correct. So here comes the weird part, if the key is in the tree, sometime system will print out :

```<code>The key %d is in the tree.
</code>```

and other time system will print both:

```<code>The key %d is in the tree.
The key %d is not in the tree.
</code>```

So what can I do to fix it?

Here is my entire code

```<code>#include<stdio.h>
#include<malloc.h>
// This program will create a binary search tree or a max-heap, as chosen from a menu.
typedef struct BSTNode{
int data;
struct Node *left;
struct Node *right;
}node;
node* getNewNode(int data){
    node *new = (node*)malloc(sizeof(node));
    new->data = data;
    new->left = new->right = NULL;
    return new;
}
void heapPreOrder(int heapRootIndex,int array[],int numOfNodes){
int i = heapRootIndex;
printf("%d\t",array[i]);
if( 2*i+1<numOfNodes)
    heapPreOrder(2*i+1,array,numOfNodes);
if(2*i+2<numOfNodes)
    heapPreOrder(2*i+2,array,numOfNodes);
}
void disLevelOrder(int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    printf("%d\t",array[i]);
}
printf("\n");
}
node* insertBST(int data,node *root){
if(root == NULL){
    root = getNewNode(data);
}
else{
    if(data <= root->data){
        root->left = insertBST(data,root->left);
    }
        else if(data >= root->data)
        root->right= insertBST(data,root->right);
    }
    return root;

}

int searchBST(int key,node *root){

 if (!root) return 0;
if (root->data == key) return 1;
if (root->data > key) return searchBST(root->left, key);
return searchBST(root->right, key);
}
void levelOrder(node* root, int level){
if (root == NULL)
    return;
if (level == 1)
    printf("%d\t", root->data);
else if (level > 1)
{
    levelOrder(root->left, level-1);
    levelOrder(root->right, level-1);
}
}
int findHeight(node* root)
{
if (root==NULL)
    return 0;
else
{
    int leftHeight = findHeight(root->left);
    int rightHeight = findHeight(root->right);

    if(leftHeight >= rightHeight)
        return leftHeight+1;
    else
        return rightHeight+1;
}

}
void insertHeap(int key,int numOfNodes,int array[]){
int i,j;
i = numOfNodes-1;
if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){//if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
}
void searchHeap(int key,int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    if(key == array[i]){
        printf("The key %d is in the heap.\n",key);
        return;
    }
}
printf("The key %d is not in the heap.\n",key);
}
void preorder(node *root){
if(root!=NULL){
    printf("%d\t",root->data);
    preorder(root->left);
    preorder(root->right);
}
}
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;

}
int main(){
int i,j,numOfNodes,key,height;
char choice,option;
node *root = (node*)malloc(sizeof(node));       //initialize root;
root = NULL;
printf("Enter the number of nodes in the linked list to be initially created: ");
scanf("%d",&numOfNodes);
int array[numOfNodes];           //store all the data in the array first
printf("Enter the data value to be placed in the node: ");
scanf("%d",&array[0]);
root = insertBST(array[0],root);           //create the root
//root->left = getNewNode(array[0]);
for(i = 1;i < numOfNodes;i++){
    printf("Enter the data value to be placed in the node: ");                 //put each data into array, leave the index 0 empty
    scanf("%d",&array[i]);
}
printf("What do you wish to create a Binary search Tree (B) or a Max-Heap (H)?: ");
scanf(" %c",&choice);
if(choice == 'B' || choice == 'b'){         //if user wants to build a Binary search Tree
    for(i = 1;i<numOfNodes;i++){
        insertBST(array[i],root);
    }
        printf("Binary search tree build successfully.\n");
}

if(choice == 'H'|| choice == 'h'){         //if user wants to build a Max-Heap
        for(i = 1;i<numOfNodes;i++){          //build the max heap
        if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){  //if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
    }
        printf("Heap successfully created.\n");
    }
while(choice == 'B'||choice == 'b'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
        if(option == 'p'||option == 'P'){
        preorder(root);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        height = findHeight(root);
        for(i = 1;i <= height;i++){
            levelOrder(root,i);
        }
        printf("\n");
    }
    if(option == 'S'||option == 's'){     //This is the part I have trouble with
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        if((searchBST(key,root)) != 1)
        printf("The key %d is not in the tree.\n",key);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        insertBST(key,root);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}
while(choice == 'H'|| choice == 'h'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
    if(option == 'p'||option == 'P'){
        heapPreOrder(0,array,numOfNodes);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        disLevelOrder(array,numOfNodes);
        printf("\n");
    }
    if(option == 'S'||option == 's'){
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        searchHeap(key,array,numOfNodes);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        numOfNodes++;
        array[numOfNodes-1] = key;
        insertHeap(key,numOfNodes,array);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}
</code>```

}

答:
Edited Answer-:

The issue was regarding the return values. Even if you found the key, in the next iteration loop you are returning value 0. This will be checked in you main function and will be reported as key not found.

Second the search was not done in the right links of the node.

Duplicate entry in root linked list while adding entries especially the first entry.

Just change your code like this,

```<code>   int searchBST(int key,node *root){

       int bRet = 1;  /// 1 means error
       if(root->data == key){
           printf("The key %d is in the tree.\n",key);
           bRet = 0;  /// 0 means success
           return bRet;
       }
       if(root->left != NULL){
           bRet = searchBST(key,root->left);
           if(!bRet)
           {
               return bRet;
           }
       }
       if(root->right != NULL){
           bRet = searchBST(key,root->right);
           if(!bRet)
           {
               return bRet;
           }
       }

       return bRet;
  }
</code>```

Main function,

```<code>  printf("Please enter the key value you wish to search for: ");
  scanf("%d",&key);
  if(0 != searchBST(key,root))
     printf("The key %d is not in the tree.\n",key);
</code>```

Return value 0 means success, any other value including 1 means error/key not found.

I found minor issues as well but i think those should be found in compilation time itself like,

int array[numOfNodes]; array declaration needs a const number not a variable.

Usage of Node instead of node.

Using "new" keyword as a variable.

Swap function to be defined above its usage.

Body:
I am just trying to search the key in a binary search Tree.
Here is what I did.

int searchBST(int key,node *root){

    if(root->data == key){
        printf("The key %d is in the tree.\n",key);
        return 1;
    }
    if(root->left != NULL){
        searchBST(key,root->left);
        return 0;
    }
    if(root->right != NULL){
        searchBST(key,root->right);
        return 0;
    }
}

In the main function,check if function return 1, if it does, the key is in the tree.

printf("Please enter the key value you wish to search for: ");
scanf("%d",&key);
if((searchBST(key,root)) != 1)
    printf("The key %d is not in the tree.\n",key);

if the key is not in the tree it will print :

The key %d is not in the tree.

which is correct. So here comes the weird part, if the key is in the tree, sometime system will print out :

The key %d is in the tree.

and other time system will print both:

The key %d is in the tree.
The key %d is not in the tree.

So what can I do to fix it?

Here is my entire code

#include<stdio.h>
#include<malloc.h>
// This program will create a binary search tree or a max-heap, as chosen from a menu.
typedef struct BSTNode{
int data;
struct Node *left;
struct Node *right;
}node;
node* getNewNode(int data){
    node *new = (node*)malloc(sizeof(node));
    new->data = data;
    new->left = new->right = NULL;
    return new;
}
void heapPreOrder(int heapRootIndex,int array[],int numOfNodes){
int i = heapRootIndex;
printf("%d\t",array[i]);
if( 2*i+1<numOfNodes)
    heapPreOrder(2*i+1,array,numOfNodes);
if(2*i+2<numOfNodes)
    heapPreOrder(2*i+2,array,numOfNodes);
}
void disLevelOrder(int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    printf("%d\t",array[i]);
}
printf("\n");
}
node* insertBST(int data,node *root){
if(root == NULL){
    root = getNewNode(data);
}
else{
    if(data <= root->data){
        root->left = insertBST(data,root->left);
    }
        else if(data >= root->data)
        root->right= insertBST(data,root->right);
    }
    return root;

}

int searchBST(int key,node *root){

 if (!root) return 0;
if (root->data == key) return 1;
if (root->data > key) return searchBST(root->left, key);
return searchBST(root->right, key);
}
void levelOrder(node* root, int level){
if (root == NULL)
    return;
if (level == 1)
    printf("%d\t", root->data);
else if (level > 1)
{
    levelOrder(root->left, level-1);
    levelOrder(root->right, level-1);
}
}
int findHeight(node* root)
{
if (root==NULL)
    return 0;
else
{
    int leftHeight = findHeight(root->left);
    int rightHeight = findHeight(root->right);

    if(leftHeight >= rightHeight)
        return leftHeight+1;
    else
        return rightHeight+1;
}

}
void insertHeap(int key,int numOfNodes,int array[]){
int i,j;
i = numOfNodes-1;
if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){//if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
}
void searchHeap(int key,int array[],int numOfNodes){
int i;
for(i = 0;i < numOfNodes;i++){
    if(key == array[i]){
        printf("The key %d is in the heap.\n",key);
        return;
    }
}
printf("The key %d is not in the heap.\n",key);
}
void preorder(node *root){
if(root!=NULL){
    printf("%d\t",root->data);
    preorder(root->left);
    preorder(root->right);
}
}
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;

}
int main(){
int i,j,numOfNodes,key,height;
char choice,option;
node *root = (node*)malloc(sizeof(node));       //initialize root;
root = NULL;
printf("Enter the number of nodes in the linked list to be initially created: ");
scanf("%d",&numOfNodes);
int array[numOfNodes];           //store all the data in the array first
printf("Enter the data value to be placed in the node: ");
scanf("%d",&array[0]);
root = insertBST(array[0],root);           //create the root
//root->left = getNewNode(array[0]);
for(i = 1;i < numOfNodes;i++){
    printf("Enter the data value to be placed in the node: ");                 //put each data into array, leave the index 0 empty
    scanf("%d",&array[i]);
}
printf("What do you wish to create a Binary search Tree (B) or a Max-Heap (H)?: ");
scanf(" %c",&choice);
if(choice == 'B' || choice == 'b'){         //if user wants to build a Binary search Tree
    for(i = 1;i<numOfNodes;i++){
        insertBST(array[i],root);
    }
        printf("Binary search tree build successfully.\n");
}

if(choice == 'H'|| choice == 'h'){         //if user wants to build a Max-Heap
        for(i = 1;i<numOfNodes;i++){          //build the max heap
        if(i%2 == 1 && array[i] > array[(i-1)/2]){  //if left child is greater than parent
            swap(&array[i],&array[(i-1)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
        if(i%2 == 0 && array[i] > array[(i-2)/2]){  //if right child is greater than parent
            swap(&array[i],&array[(i-2)/2]);
            for(j = (i-1)/2;j > 0,array[j]>array[(j- 1)/2]; j = (j- 1)/2){
                swap(&array[j],&array[(j-1)/2]);
            }
        }
    }
        printf("Heap successfully created.\n");
    }
while(choice == 'B'||choice == 'b'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
        if(option == 'p'||option == 'P'){
        preorder(root);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        height = findHeight(root);
        for(i = 1;i <= height;i++){
            levelOrder(root,i);
        }
        printf("\n");
    }
    if(option == 'S'||option == 's'){     //This is the part I have trouble with
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        if((searchBST(key,root)) != 1)
        printf("The key %d is not in the tree.\n",key);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        insertBST(key,root);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}
while(choice == 'H'|| choice == 'h'){
    printf("What do you wish to do?\n");
    printf("Show Preorder Traversal(P)\tShow Level order Traversal(L)\tSearch(S)\tInsert(I)\tQuit(Q)\n");
    printf("Please enter a choice: ");
    scanf(" %c",&option);
    if(option == 'p'||option == 'P'){
        heapPreOrder(0,array,numOfNodes);
        printf("\n");
    }
    if(option == 'L'||option == 'l'){
        disLevelOrder(array,numOfNodes);
        printf("\n");
    }
    if(option == 'S'||option == 's'){
        printf("Please enter the key value you wish to search for: ");
        scanf("%d",&key);
        searchHeap(key,array,numOfNodes);
    }
    if(option == 'I'||option == 'i'){       //if user wants to insert a number
        printf("please enter the key value you wish to insert: ");
        scanf("%d",&key);
        numOfNodes++;
        array[numOfNodes-1] = key;
        insertHeap(key,numOfNodes,array);
        printf("The key value %d was successfully inserted.\n",key);
    }
    if(option == 'q'||option == 'Q'){
        printf("Thanks for using my program, please rate 100 as feedback! Have a wonderful day :)");
        return 0;
    }
    printf("\n");
}

}

Body:
Edited Answer-:

The issue was regarding the return values. Even if you found the key, in the next iteration loop you are returning value 0. This will be checked in you main function and will be reported as key not found.

Second the search was not done in the right links of the node.

Duplicate entry in root linked list while adding entries especially the first entry.

Just change your code like this,

   int searchBST(int key,node *root){

       int bRet = 1;  /// 1 means error
       if(root->data == key){
           printf("The key %d is in the tree.\n",key);
           bRet = 0;  /// 0 means success
           return bRet;
       }
       if(root->left != NULL){
           bRet = searchBST(key,root->left);
           if(!bRet)
           {
               return bRet;
           }
       }
       if(root->right != NULL){
           bRet = searchBST(key,root->right);
           if(!bRet)
           {
               return bRet;
           }
       }

       return bRet;
  }

Main function,

  printf("Please enter the key value you wish to search for: ");
  scanf("%d",&key);
  if(0 != searchBST(key,root))
     printf("The key %d is not in the tree.\n",key);

Return value 0 means success, any other value including 1 means error/key not found.

I found minor issues as well but i think those should be found in compilation time itself like,

int array[numOfNodes]; array declaration needs a const number not a variable.

Usage of Node instead of node.

Using "new" keyword as a variable.

Swap function to be defined above its usage.