问:
How to use .properties file in Spring using the Environment object?
I have the following doubt about how works external property in Spring.

For example consider this bean definition (into a Java configuration class):

```<code>@Bean
public DataSource dataSource() {
    DataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.postgresql.Driver");
    ds.setUrl("jdbc:postgresql://localhost/transfer" );
    ds.setUser("transfer-app");
    ds.setPassword("secret45" );
    return ds;
}
</code>```

Ok, as you can see the connection paramethers are hard coded and this is not good so I can externalize these to a properties file.

Reading the documentation I see that I can use also the Environment object to obtain properties from runtime environment, such as:

JVM System Properties

Java Properties Files

Servlet Context Parameters

System Environment Variables

JNDI

So it seems to me that I can use this Environment object to obtain information from my properties file without having to worry about the procedures for accessing to it. Is it right?

So, for example if I have the following bean configurations into a Java configuration class:

```<code>@Configuration
public class ApplicationConfig {

    @Autowired public Environment env;

    @Bean public DataSource dataSource() {
        DataSource ds = new BasicDataSource();
        ds.setDriverClassName( env.getProperty( "db.driver" ));
        ds.setUrl( env.getProperty( "db.url" ));
        ds.setUser( env.getProperty( "db.user" ));
        ds.setPassword( env.getProperty( "db.password" ));

        return ds;
     }
}
</code>```

it means that I obtain the Environment object using the @Autowired (Spring search the matching object for me) and then I use this object to access to a properties file named db.properties that I have putted somewhere into my code.

Is it right?

Now my doubts are:

1) Exist a standard location for my .properties file into my project or can I put these in any location?

2) In the previous code snippet I don't specify a specific .properties file. How work the Environment object? It automatically load all the .properties file in my project?

答:
```<code>@PropertySources({
 @PropertySource("file:/absolutepath/app.properties"),//IF you want to load from file system using absolute path
 @PropertySource("classpath:app.properties"),   //IF you want to load from classpath
 @PropertySource("file:{environment_Variable}/app.properties"),   //IF you want to load using envirment varibale
})
</code>```

Body:
I have the following doubt about how works external property in Spring.

For example consider this bean definition (into a Java configuration class):

@Bean
public DataSource dataSource() {
    DataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.postgresql.Driver");
    ds.setUrl("jdbc:postgresql://localhost/transfer" );
    ds.setUser("transfer-app");
    ds.setPassword("secret45" );
    return ds;
}

Ok, as you can see the connection paramethers are hard coded and this is not good so I can externalize these to a properties file.

Reading the documentation I see that I can use also the Environment object to obtain properties from runtime environment, such as:

JVM System Properties

Java Properties Files

Servlet Context Parameters

System Environment Variables

JNDI

So it seems to me that I can use this Environment object to obtain information from my properties file without having to worry about the procedures for accessing to it. Is it right?

So, for example if I have the following bean configurations into a Java configuration class:

@Configuration
public class ApplicationConfig {

    @Autowired public Environment env;

    @Bean public DataSource dataSource() {
        DataSource ds = new BasicDataSource();
        ds.setDriverClassName( env.getProperty( "db.driver" ));
        ds.setUrl( env.getProperty( "db.url" ));
        ds.setUser( env.getProperty( "db.user" ));
        ds.setPassword( env.getProperty( "db.password" ));

        return ds;
     }
}

it means that I obtain the Environment object using the @Autowired (Spring search the matching object for me) and then I use this object to access to a properties file named db.properties that I have putted somewhere into my code.

Is it right?

Now my doubts are:

1) Exist a standard location for my .properties file into my project or can I put these in any location?

2) In the previous code snippet I don't specify a specific .properties file. How work the Environment object? It automatically load all the .properties file in my project?


来源: stackexchange

问:
How to stop browser redrawing until DOM manipulation complete?
At various points in my 1-page web app I want to do some fairly heavy DOM manipulation, moving various divs around (which each have lots of sub-elements). I don't want the browser trying to repeatedly redraw the page mid-manipulation. Is there a way to say to the browser "pause redrawing until I give the go ahead"?

requestAnimationFrame() seems like one candidate, but is that suitable for DOM rearranging, or just for animation? Are there any other things I could do?

Thanks

答:
You can try using documentFragment.

Create the documentFragment.

Write everything into a documentFragment first.

When done, replace DOM content with documentFragment.

Then the manipulation does not take place on-the-fly, you use the documentFragment as a sort of buffer.

ContentLicense: CC BY-SA 3.0


问:
How to run kafka on different machines
From last 10 days i am trying to set Kafka on different machine:

Server32

Server56

Below are the list of task which i have done so far

Configured Zookeeper and started on both server  with

server.1=Server32_IP:2888:3888

server.2=Server56_IP:2888:3888

I also changed server and server-1 properties as below

broker.id=0   port=9092   log.dir=/tmp/kafka0-logs

  host.name=Server32

  zookeeper.connect=Server32_IP:9092,Server56_IP:9062

& server-1

broker.id=1   port=9062   log.dir=/tmp/kafka1-logs

  host.name=Server56

  zookeeper.connect=Server32_IP:9092,Server56_IP:9062

Server.property i ran in Server32

Server-1.property i ran in Server56

The Problem is : when i start producer in both the servers and if i try to consume from any one then it is working BUT

  When i stop any one server then another one is not able to send the details

Please help me in explaining the process

答:
There's a lot of information missing here like the Kafka version and whether or not you're using the new consumer APIs or the old APIs. I'm assuming you're probably using a new version of Kafka like 0.10.x along with the new client APIs. In the new version of the client APIs the log data is stored on the Kafka brokers and not Zookeeper as in the older versions. I think your issue here is that you created your topics with a replication factor of 1 and coincidently the Kafka broker server you shutdown was hosting the only replica, so you won't be able to produce or consume messages. You can confirm the health of your topics by running the command:

```<code>kafka-topics.sh --zookeeper ZHOST:2181 --describe
</code>```

You might want to increase the replication factor to 2. That way you might be able to get away with one broker failing. Ideally you would have 3 or more Kafka Broker servers with a replication factor of 2 or higher (obviously not more than the number of brokers in your cluster). Refer to the link below:

https://kafka.apache.org/documentation/#basic_ops_increase_replication_factor

For a topic with replication factor N, we will tolerate up to N-1 server >failures without losing any records committed to the log."

Title: How to run kafka on different machines

Body:
There's a lot of information missing here like the Kafka version and whether or not you're using the new consumer APIs or the old APIs. I'm assuming you're probably using a new version of Kafka like 0.10.x along with the new client APIs. In the new version of the client APIs the log data is stored on the Kafka brokers and not Zookeeper as in the older versions. I think your issue here is that you created your topics with a replication factor of 1 and coincidently the Kafka broker server you shutdown was hosting the only replica, so you won't be able to produce or consume messages. You can confirm the health of your topics by running the command:

kafka-topics.sh --zookeeper ZHOST:2181 --describe

You might want to increase the replication factor to 2. That way you might be able to get away with one broker failing. Ideally you would have 3 or more Kafka Broker servers with a replication factor of 2 or higher (obviously not more than the number of brokers in your cluster). Refer to the link below:

https://kafka.apache.org/documentation/#basic_ops_increase_replication_factor

For a topic with replication factor N, we will tolerate up to N-1 server >failures without losing any records committed to the log."


问:
How can I close a modal popup on hitting escape?
I have made a modal box popup functionality and I want to close this modal popup up box when someone hits the escape key, in all browsers. I have used the file modal-window.min.js for these popups.

How can I close these in response to this key?

答:
With the keydown function:

```<code>$(document).keydown(function(event) {
  if (event.keyCode == 27) {
    $('#modal_id').hide();
  }
});
</code>```

Note: Prefer using keydown for the Escape key as in some browsers the keypress event is only fired if the key outputs a character

Body:
With the keydown function:

$(document).keydown(function(event) {
  if (event.keyCode == 27) {
    $('#modal_id').hide();
  }
});

Note: Prefer using keydown for the Escape key as in some browsers the keypress event is only fired if the key outputs a character

ContentLicense: CC BY-SA 4.0


问:
how to avoid duplication users in my db with php
How are you all,

hope every one here is OK,

now I have a form that the admin can create users and he can delete users as will let me display the code first

this is my code

```<code>> > <?php error_reporting(E_ALL);
>
> session_start();
>   if(!isset($_SESSION['login']) ||
> $_SESSION['login']!='1' )         {
>       header("Location:loginpage.php");
>       } ?>
>
> <!DOCTYPE html PUBLIC "-//W3C//DTD
> XHTML 1.0 Transitional//EN"
> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
> <html
> xmlns="http://www.w3.org/1999/xhtml">
> <head> <meta http-equiv="Content-Type"
> content="text/html; charset=utf-8" />
> <title>My Control panel</title> <link
> href="../css_style.css"
> rel="stylesheet" type="text/css" />
> </head>
>
>
>
> <body> <div id="werpper"> <div
> id="content">
>
> <div id="header">My control -
> Panel</div> <div id="body_cntent">
> <div id="left_side">   <p>Home and
> instructions</p>   <p><a
> href="../control_panel.php">main
> directory</a></p>   <p><a
> href="add_event.php">Add new
> event</a></p>   <p><a
> href="../editoccasion.php">Control
> Occasion's</a></p>   <p><a
> href="add_photos_and_occasion.php">Add
> Photos_occasion</a></p>   <p><a
> href="../signout.php">Sign out</a></p>
> </div> <div id="right_side">
>
> <h2>Add new user</h2>
>
> <form action="" method="post">
>
> <table width="600" border="0"
> cellpadding="5" cellspacing="0">
> <tr>
>     <td width="78">User name</td>
>     <td width="2"> </td>
>     <td width="149"><input type="text" name="uname" value="" /></td>
>     <td width="332" rowspan="5" align="left" valign="top"><p
> class="red">For Administration use
> only.</p>
>       <p>You can add or delete users from <a
> href="edit_users.php">here</a><br />
>         You can't edit any user if you like to change any user account you
> can delete the user and create it
> again with the new
> information.</p></td>   </tr>   <tr>
>     <td>Password</td>
>     <td> </td>
>     <td><input type="text" name="pass" value="" /></td>
>     </tr>   <tr>
>     <td> </td>
>     <td> </td>
>     <td><input type="submit" name="submit" value="Add user" /></td>
>     </tr>   <tr>
>     <td> </td>
>     <td> </td>
>     <td> </td>
>     </tr>   <tr>
>     <td> </td>
>     <td> </td>
>     <td align="right"> </td>
>     </tr> </table> </form>
>
> </div> </div>
>
> <div id="footer"></div> </div> </div>
>
> <?php
>       if (isset($_POST['submit'])) {
>               include_once "../config/config.php";
>               $uname = $_POST['uname'];       $pass =$_POST['pass'];
>               $check = "select * from users where id = {$uname}";         $result_check
> = $db->query($check)or die($db->error);
>
>               while ($row = $result_check -> fetch_object()) {
>                       if(num_rows == 1){
>
>               echo "error";
>
>               }else{
>               $add_user = "insert into users (id, uname, pass) values ('',
> '$uname', '$pass')";
>               $result = $db -> query($add_user) or die ("$db->error");
>               if ($result) {
>                       echo "user added successfuly";
>                       }else{
>
>               echo "There was an error please try again later";
>
>               }           }       }   } ?>
>
> </body> </html>
</code>```

all I need here to know is how to solve the problem of this code

```<code>$check = "select * from users where id = {$uname}";
        $result_check = $db->query($check)or die($db->error);

        while ($row = $result_check -> fetch_object()) {

            if(num_rows == 1){

                echo "error";

                }
</code>```

how can I avoid duplication users in my db

答:
I'm not sure which database library you're using and what all its methods are, so I made this with plain mySQL for if you went the route of making the uname (username) field a UNIQUE INDEX --

```<code>// instantiate database connection
$db = mysql_connect( .. );

// assuming the id field is auto incrementing, it can be left out of the query
$add_user  = "INSERT INTO users (uname, pass) ";
$add_user .= "VALUES ('" . mysql_real_escape_string($uname) . "', ";
$add_user .= "'" . mysql_real_escape_string($pass) . "')";

if (mysql_query($add_user, $db))
{
    if (mysql_affected_rows($db) == 1)
    {
        // New user added, do something
    }
}
else
{
    if (mysql_errno($db) == 1062)
    {
        // Duplicate username, do something
    }
    else
    {
        // A different database error occurred
        die('Error: ' . mysql_error());
    }
}
</code>```

Body:
How are you all,

hope every one here is OK,

now I have a form that the admin can create users and he can delete users as will let me display the code first

this is my code

> > <?php error_reporting(E_ALL);
>
> session_start();
>   if(!isset($_SESSION['login']) ||
> $_SESSION['login']!='1' )         {
>       header("Location:loginpage.php");
>       } ?>
>
> <!DOCTYPE html PUBLIC "-//W3C//DTD
> XHTML 1.0 Transitional//EN"
> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
>  xmlns="http://www.w3.org/1999/xhtml">
>  <meta http-equiv="Content-Type"
> content="text/html; charset=utf-8" />
> <title>My Control panel</title> <link
> href="../css_style.css"
> rel="stylesheet" type="text/css" />
>
>
>
>
>

 id="content">
>
>
My control -
> Panel

>

Home and
> instructions

 href="../control_panel.php">main
> directory

 href="add_event.php">Add new
> event

 href="../editoccasion.php">Control
> Occasion's

 href="add_photos_and_occasion.php">Add
> Photos_occasion

 href="../signout.php">Sign out

>

>
>
Add new user

>
> <form action="" method="post">
>
>
 cellpadding="5" cellspacing="0">
>

>     User name
>
>     <input type="text" name="uname" value="" />
>
 class="red">For Administration use
> only.

>
You can add or delete users from  href="edit_users.php">here

>         You can't edit any user if you like to change any user account you
> can delete the user and create it
> again with the new
> information.

>     Password
>
>     <input type="text" name="pass" value="" />
>

>
>
>     <input type="submit" name="submit" value="Add user" />
>

>
>
>
>

>
>
>
>

 </form>
>
>

>
>

>
> <?php
>       if (isset($_POST['submit'])) {
>               include_once "../config/config.php";
>               $uname = $_POST['uname'];       $pass =$_POST['pass'];
>               $check = "select * from users where id = {$uname}";         $result_check
> = $db->query($check)or die($db->error);
>
>               while ($row = $result_check -> fetch_object()) {
>                       if(num_rows == 1){
>
>               echo "error";
>
>               }else{
>               $add_user = "insert into users (id, uname, pass) values ('',
> '$uname', '$pass')";
>               $result = $db -> query($add_user) or die ("$db->error");
>               if ($result) {
>                       echo "user added successfuly";
>                       }else{
>
>               echo "There was an error please try again later";
>
>               }           }       }   } ?>
>
>

all I need here to know is how to solve the problem of this code

$check = "select * from users where id = {$uname}";
        $result_check = $db->query($check)or die($db->error);

        while ($row = $result_check -> fetch_object()) {

            if(num_rows == 1){

                echo "error";

                }

how can I avoid duplication users in my db

Body:
I'm not sure which database library you're using and what all its methods are, so I made this with plain mySQL for if you went the route of making the uname (username) field a UNIQUE INDEX --

// instantiate database connection
$db = mysql_connect( .. );

// assuming the id field is auto incrementing, it can be left out of the query
$add_user  = "INSERT INTO users (uname, pass) ";
$add_user .= "VALUES ('" . mysql_real_escape_string($uname) . "', ";
$add_user .= "'" . mysql_real_escape_string($pass) . "')";

if (mysql_query($add_user, $db))
{
    if (mysql_affected_rows($db) == 1)
    {
        // New user added, do something
    }
}
else
{
    if (mysql_errno($db) == 1062)
    {
        // Duplicate username, do something
    }
    else
    {
        // A different database error occurred
        die('Error: ' . mysql_error());
    }
}


问:
Xcode 8.3.3 Auto Layout on Random Positioned UI Buttons
I am currently making an UI that involves multiple UIButtons in random positions. Please see the photos, I basically want the buttons to stay at where they are suppose to be (aka Pikachu's ear, Pikachu's cheek...) But when I change to a smaller device such as the iPhone SE, the buttons aren't at where I want.

I know that Auto Layout is probably the way out, and I tried adding leading, trailing, top and bottom constraints, but they never work out. I also tried setting suggested constraints, did not work. Some buttons were stretched after setting constraints...

So it really caused headache for me. Can anyone please help?

Desired Layout

UPDATE:
I have found a really easy way to achieve such layout. By unclicking default autoresizing and only select the inner constraints, the buttons can now be at where I want them to be.
Storyboard Edit

答:
You need to add as minimum constraints like

1.) Leading

2.) Top

3.) Height, Width

The key is to change the values either programmatically.

For example,
Suppose, the screen is 320 * 480 and the button Position is to be at (100,250),

the ratios we get will be PositionX = 100/320 = 0.3125
                         & PositionY = 250/480 = 0.520 then programmatically set

```<code>leadingConstraint.constant = 0.312 * self.view.bounds.size.width
topConstraint.constant = 0.520 * self.view.bounds.size.height
</code>```

You need to calculate these values for each button and set them accordingly.

Body:
You need to add as minimum constraints like

1.) Leading

2.) Top

3.) Height, Width

The key is to change the values either programmatically.

For example,
Suppose, the screen is 320 * 480 and the button Position is to be at (100,250),

the ratios we get will be PositionX = 100/320 = 0.3125
                         & PositionY = 250/480 = 0.520 then programmatically set

leadingConstraint.constant = 0.312 * self.view.bounds.size.width
topConstraint.constant = 0.520 * self.view.bounds.size.height

You need to calculate these values for each button and set them accordingly.


问:
Extracting a HTML tag from a string
Can anyone please explain how would I extract a substring from an input string.

Input:

```<code>'<h3>freedom machines.</h3><p>dom.</p><br/><p>The robust display.</p>'
</code>```

Output :

```<code>'<h3>freedom machines.</h3>'
</code>```

I am trying to do it with regex, but no luck.
Do you have any suggestions?

I need to check whether my string starts from any header tag (
,
 or
), and if it does, I will extract that header tag.

I tried with startswith, but with no success:

```<code>if input.startswith("<h"):
  ** Code to extract that h tag.
</code>```

答:
You can use re.search to extract the text between the
 tag.

The
.*?
 pattern means match anything between the
 tag.

```<code>>>> import re
>>> text = '<h3>freedom machines.</h3><p>dom.</p><br/><p>The robust display.</p>'
>>> match = re.search("<h3>.*?</h3>", text, re.IGNORECASE | re.MULTILINE)
>>> print(match.group())

'<h3>freedom machines.</h3>'
</code>```

Title: Extracting a HTML tag from a string

Body:
Can anyone please explain how would I extract a substring from an input string.

Input:

'
freedom machines.

dom.

The robust display.
'

Output :

'
freedom machines.
'

I am trying to do it with regex, but no luck.
Do you have any suggestions?

I need to check whether my string starts from any header tag (
,
 or
), and if it does, I will extract that header tag.

I tried with startswith, but with no success:

if input.startswith("<h"):
  ** Code to extract that h tag.

Body:
You can use re.search to extract the text between the <h3> tag.

The <h3>.*?</h3> pattern means match anything between the <h3> tag.

>>> import re
>>> text = '<h3>freedom machines.</h3><p>dom.</p><br/><p>The robust display.</p>'
>>> match = re.search("<h3>.*?</h3>", text, re.IGNORECASE | re.MULTILINE)
>>> print(match.group())

'<h3>freedom machines.</h3>'


问:
is Swift generic protocol injection possible?
I am trying to use generic protocols and inject a concrete implementation but I get the following error: Protocol 'Repo' can only be used as a generic constraint because it has Self or associated type requirements at let repo: Repo

My code

```<code>protocol Repo{
    associatedtype T

    func doSomething() -> T

}

class MyRepo: Repo{

    func doSomething() -> String{
        return "hi"
    }
}

class SomeClass {
    let repo: Repo
    init(repo: Repo) {
        self.repo = repo
        repo.doSomething()
    }
}

class EntryPoint{
    let someClass: SomeClass
    init(){
        someClass = SomeClass(repo: MyRepo)
    }
}
</code>```

Entry point is called first and sets up the dependency tree.

答:
I think what you are looking for is something like this:</p>

```<code>    protocol Repo {
      associatedtype T

      func doSomething() -> T

    }

    class MyRepo: Repo{
      func doSomething() -> String{
        return "hi"
      }
    }

    class SomeClass<A: Repo> {
      let repo: A
      init(repo: A) {
        self.repo = repo
        _ = repo.doSomething()
      }
    }

    class EntryPoint{
      let someClass: SomeClass<MyRepo>
      init(){
        someClass = SomeClass<MyRepo>(repo: MyRepo())
      }
    }
</code>```

Body:
I am trying to use generic protocols and inject a concrete implementation but I get the following error: Protocol 'Repo' can only be used as a generic constraint because it has Self or associated type requirements at let repo: Repo

My code

protocol Repo{
    associatedtype T

    func doSomething() -> T

}

class MyRepo: Repo{

    func doSomething() -> String{
        return "hi"
    }
}

class SomeClass {
    let repo: Repo
    init(repo: Repo) {
        self.repo = repo
        repo.doSomething()
    }
}

class EntryPoint{
    let someClass: SomeClass
    init(){
        someClass = SomeClass(repo: MyRepo)
    }
}

Entry point is called first and sets up the dependency tree.

Body:
I think what you are looking for is something like this:

    protocol Repo {
      associatedtype T

      func doSomething() -> T

    }

    class MyRepo: Repo{
      func doSomething() -> String{
        return "hi"
      }
    }

    class SomeClass<A: Repo> {
      let repo: A
      init(repo: A) {
        self.repo = repo
        _ = repo.doSomething()
      }
    }

    class EntryPoint{
      let someClass: SomeClass<MyRepo>
      init(){
        someClass = SomeClass<MyRepo>(repo: MyRepo())
      }
    }


问:
Ndb strong consistency and frequent writes
I'm trying to achieve strong consistency with ndb using python.
And looks like I'm missing something as my reads behave like they're not strongly consistent.

The query is:

```<code>links = Link.query(ancestor=lead_key).filter(Link.last_status ==
None).fetch(keys_only=True)

if links:
    do_action()
</code>```

The key structure is:

```<code>Lead root (generic key) -> Lead -> Website (one per lead) -> Link
</code>```

I have many tasks that are executed concurrently using TaskQueue and this query is performed at the end of every task. Sometimes I'm getting "too much contention" exception when updating the last_status field but I deal with it using retries. Can it break strong consistency?

The expected behavior is having do_action() called when there are no links left with last_status equal to None. The actual behavior is inconsistent: sometimes do_action() is called twice and sometimes not called at all.

答:
Adding to Dave's answer which is the 1st thing to check.

One thing which isn't well documented and can be a bit surprising is that the contention can be caused by read operations as well, not only by the write ones.

Whenever a transaction starts the entity groups being accessed (by read or write ops, doesn't matter) are marked as such. The too much contention error indicates that too many parallel transactions simultaneously try to access the same entity group. It can happen even if none of the transactions actually attempts to write!

Note: this contention is NOT emulated by the development server, it can only be seen when deployed on GAE, with the real datastore!

What can add to the confusion is the automatic re-tries of the transactions, which can happen after both actual write conflicts or just plain access contention. These retries may appear to the end-user as suspicious repeated execution of some  code paths - which I suspect could explain your reports of do_action() being called twice.

Usually when you run into such problems you have to re-visit your data structures and/or the way you're accessing them (your transactions). In addition to solutions maintaining the strong consistency (which can be quite expensive) you may want to re-check if consistency is actually a must. In some cases it's added as a blanket requirement just because appears to simplify things. From my experience it doesn't :)

Body:
I'm trying to achieve strong consistency with ndb using python.
And looks like I'm missing something as my reads behave like they're not strongly consistent.

The query is:

links = Link.query(ancestor=lead_key).filter(Link.last_status ==
None).fetch(keys_only=True)

if links:
    do_action()

The key structure is:

Lead root (generic key) -> Lead -> Website (one per lead) -> Link

I have many tasks that are executed concurrently using TaskQueue and this query is performed at the end of every task. Sometimes I'm getting "too much contention" exception when updating the last_status field but I deal with it using retries. Can it break strong consistency?

The expected behavior is having do_action() called when there are no links left with last_status equal to None. The actual behavior is inconsistent: sometimes do_action() is called twice and sometimes not called at all.


问:
Connection is established, but status code is 404 error in Talend tJIRAInput
I have talend big Data & JIRA. Now,trying to get issue details from JIRA using talend tJIRAInput. The below added my JIRA job.

If run this job, In tJIRAInput component throwing error

```<code>Exception in component tJIRAInput_1 (TestJob)
java.lang.RuntimeException: Host validation failed for URL: http://54.213.97.89:7340/secure/Dashboard.jspa
Connection is established, but status code is 404
    at local_project.testjob_0_1.TestJob.tJIRAInput_1Process(TestJob.java:1039)
    at local_project.testjob_0_1.TestJob.tMongoDBConnection_1Process(TestJob.java:432)
    at local_project.testjob_0_1.TestJob.runJobInTOS(TestJob.java:1726)
    at local_project.testjob_0_1.TestJob.main(TestJob.java:1575)
</code>```

Did i missed anything in the job? How can i resolve this issue?

答:
Couple of things for troubleshooting:

Make sure your host URL is similar to JIRA Base URL. Means, that you should remove "Dashboard.jspa" from your HOST URL.

Make sure your user has proper permissions against projects.

Body:
I have talend big Data & JIRA. Now,trying to get issue details from JIRA using talend tJIRAInput. The below added my JIRA job.

If run this job, In tJIRAInput component throwing error

Exception in component tJIRAInput_1 (TestJob)
java.lang.RuntimeException: Host validation failed for URL: http://54.213.97.89:7340/secure/Dashboard.jspa
Connection is established, but status code is 404
    at local_project.testjob_0_1.TestJob.tJIRAInput_1Process(TestJob.java:1039)
    at local_project.testjob_0_1.TestJob.tMongoDBConnection_1Process(TestJob.java:432)
    at local_project.testjob_0_1.TestJob.runJobInTOS(TestJob.java:1726)
    at local_project.testjob_0_1.TestJob.main(TestJob.java:1575)

Did i missed anything in the job? How can i resolve this issue?


问:
Loading .mdf database in vscode on mac
I am currently learning t-sql. I downloaded AdventureWorksLT.mdf file to run some tests. However, I do not know how to load the mdf file in vscode on mac.
Any suggestions?</p>

答: you need to install SQL Server (Express), and attach the MDF to that. Subsequently you can use a SQL connection to connect and access the database.</p>

Title: Loading .mdf database in vscode on mac


问:
how to make it docker image for node application
I have an one node application. An application is working in my system. Now I want to run same application in others environments/machine using docker. I am new to the Docker. Can u suggest any idea or link to run the application in all the environments using docker

Thanks in advance

答:
You have barely given any information about the application and what you are trying to achieve, so based on what you have given, I can briefly say what you should do.

First create the container by placing a Dockerfile in your (or outside) application's folder. You have to choose a base for your docker container and a great place to look for this, is in the docker hub. An example base is the alpine image. You can also install all the dependencies of your application by using RUN apk add --update --no-cache \ in the Dockerfile (if you use the alpine image that is) and last but not least, use a command or entrypoint as a starter of the container.

I would recommend you look at some guides on how to dockerize a node application, as there are plenty out there and from what you have given in your question, I doubt that someone would be able to help you more.


问:
Calculating powers of integers
Is there any other way in Java to calculate a power of an integer?

I use Math.pow(a, b) now, but it returns a double, and that is usually a lot of work, and looks less clean when you just want to use ints (a power will then also always result in an int).

Is there something as simple as a**b like in Python?

答:
Well you can simply use Math.pow(a,b) as you have used earlier and just convert its value by using (int) before it. Below could be used as an example to it.

```<code>int x = (int) Math.pow(a,b);
</code>```

where a and b could be double or int values as you want.
This will simply convert its output to an integer value as you required.

Title: Calculating powers of integers

Body:
Well you can simply use Math.pow(a,b) as you have used earlier and just convert its value by using (int) before it. Below could be used as an example to it.

int x = (int) Math.pow(a,b);

where a and b could be double or int values as you want.
This will simply convert its output to an integer value as you required.


问:
Most Efficient way to Add Multiple Children to Parent by ID in Many to Many in Entity Framework Application (create multiple mappings)
Take the code in this example:
http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

What would be the most efficient way to add multiple courses to a student when I have the course IDs?

So, for example, the function may look like this:

```<code> private static void AddCoursesToStudent(SchoolDBContext context, Student student, List<int> CourseIds)
    {}
</code>```

And my current attempt looks like this:

```<code>public static async Task AddCoursesToStudentAsync(SchoolDBContext context, Student student, List<int> CourseIds)
    {
        await context.Courses.Where(x => CourseIds.Contains(x.CourseId)).ForEachAsync(x => x.Students.Add(student));
        context.SaveChanges();
    }

    private static void AddCoursesToStudent(SchoolDBContext context, Student student, List<int> CourseIds)
    {
        var task = AddCoursesToStudentAsync(context,student,CourseIds);
        task.Wait();
    }
</code>```

Which works, but seems a bit sloppy, especially mixing in the async. I am also thinking the "Where" combined with the "ForEach" will pull up all the records somewhere.

In other projects where it wasn't code first we would usually have a manually created "MappingTable" which in this case would look like:

```<code>public class StudentCourse
{
    [Key] [Column(Order = 0)]
    private int StudentId;
    [Key]
    [Column(Order = 1)]
    private int CourseId;

    public StudentCourse(int courseIde, int studentId)
    {
        StudentId = studentId;
        CourseId = courseIde;
    }
}
</code>```

And you would go something like:

```<code> public static  void AddCoursesToStudentMaps(SchoolDBContext context, Student student, List<int> CourseIds)
    {
        List<StudentCourse> maps = CourseIds.ConvertAll(courseId => new StudentCourse(courseId, student.StudentId)).ToList();
        context.StudentCourses.AddRange(maps);
    }
</code>```

It would be nice to do this in a way that Entity Framework manages this, perhaps I could just create the student Courses class and add it to the context? But that seems to defeat the point, especially as we have a lot of many to many and having EF create the mapping table for us would cut down the code. I just think if EF is capable of creating the mapping automatically, it must have a way of efficiently creating new links without redoing the work it has done?

In order to test this I have created this example code, with a lazy setup function, so if anyone wants to have a bash, this should get you up and running:

```<code> static void Main(string[] args)
    {
        Run();
    }

    private static void Run()
    {
        using (SchoolDBContext context = new SchoolDBContext())
        {
            /* Run once
             * SetUp(context);
             */
            Test(context);
            Output(context);
        }
    }

    static void SetUp(SchoolDBContext context)
    {
        context.Students.Add(new Student() { StudentName = "Gerry" });
        context.Students.Add( new Student() { StudentName = "Bob" }  );
        context.Students.Add( new Student() { StudentName = "Jane" } );

        context.Courses.Add( new Course() { CourseName = "Science" });
        context.Courses.Add( new Course() { CourseName = "Math" }  );
        context.Courses.Add( new Course() { CourseName = "History" } );
        context.Courses.Add(new Course() { CourseName = "Other History" });
        context.Courses.Add(new Course() { CourseName = "Roman History" });
        context.Courses.Add(new Course() { CourseName = "English History" });
        context.Courses.Add(new Course() { CourseName = "Super History" });
        context.Courses.Add(new Course() { CourseName = "Tudor History" });
        context.Courses.Add(new Course() { CourseName = "Queen History" });
        context.Courses.Add(new Course() { CourseName = "King History" });
        context.SaveChanges();
    }

    public static void Test(SchoolDBContext context)
    {

        var ids = context.Courses.Where(x => x.CourseName.Contains("History")).Select(x => x.CourseId).ToList();
        var student = context.Students.FirstOrDefault(x => x.StudentName == "Bob");
        AddCoursesToStudent(context, student, ids);
    }

    private static void Output(SchoolDBContext context)
    {
        OutputStudents(context);
    }

    private static void OutputStudents(SchoolDBContext context)
    {
        var allStudents = context.Students.ToList();
        foreach (var student in allStudents)
        {
            Console.WriteLine($"Student: {student.StudentName}");
            if (student.Courses.Any())
            {
                Console.WriteLine("is enrolled on");
                Console.WriteLine("**************************");
                foreach (var contextCourseStudent in student.Courses)
                {
                    Console.WriteLine("     " + contextCourseStudent.CourseName);
                }
                Console.WriteLine("************************ ");
            }
            Console.WriteLine("-------------------------");
        }
        Console.WriteLine("Press enter to close...");
        Console.ReadLine();
    }
    private static void OutputCourse(SchoolDBContext context)
</code>```

p.s. the reason for not just having a list of courses is due to the fact we have forms/apps etc already set up that send id lists and as mentioned it seems silly and inefficient to then pull those models out of the database, purely to add them to the parent.

答:
I don't think many-to-many with implicit link table is Code First specific. Also while it makes querying easier and more natural, as you already have seen it has obvious drawbacks when with link modifications.

It's possible to implement the adding new links efficiently by using stub entities:

```<code>static void AddCoursesToStudent(SchoolDBContext context, Student student, List<int> CourseIds)
{
    student.Courses = CourseIds.Select(id => context.Courses.Attach(new Course { CourseId = id })).ToList();
    context.SaveChanges();
}
</code>```

This works, but under the following constraints:

(1) The context has been created specifically for this call

(2) student is already attached to the context

(3) All the CourseIds exist in the database

(4) There are no Course entities loaded in the context with some of the CourseIds

(5) The initial student.Courses collection is not eager or lazy loaded. This is specifically to enforce add link operation (vs replace all links by determining the added and removed items)

(6) You don't use afterwards the context or any of the Course objects, because all their properties except the PK are not real.

An example considering all the constraints:

```<code>public void AddCoursesToStudent(int studentId, List<int> coursesIds)
{
    using (var context = new SchoolDBContext())
    {
        var student = context.Students.Find(studentId);
        AddCoursesToStudent(context, student, coursesIds);
    }
}
</code>```

Body:
Take the code in this example:
http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

What would be the most efficient way to add multiple courses to a student when I have the course IDs?

So, for example, the function may look like this:

 private static void AddCoursesToStudent(SchoolDBContext context, Student student, List<int> CourseIds)
    {}

And my current attempt looks like this:

public static async Task AddCoursesToStudentAsync(SchoolDBContext context, Student student, List<int> CourseIds)
    {
        await context.Courses.Where(x => CourseIds.Contains(x.CourseId)).ForEachAsync(x => x.Students.Add(student));
        context.SaveChanges();
    }

    private static void AddCoursesToStudent(SchoolDBContext context, Student student, List<int> CourseIds)
    {
        var task = AddCoursesToStudentAsync(context,student,CourseIds);
        task.Wait();
    }

Which works, but seems a bit sloppy, especially mixing in the async. I am also thinking the "Where" combined with the "ForEach" will pull up all the records somewhere.

In other projects where it wasn't code first we would usually have a manually created "MappingTable" which in this case would look like:

public class StudentCourse
{
    [Key] [Column(Order = 0)]
    private int StudentId;
    [Key]
    [Column(Order = 1)]
    private int CourseId;

    public StudentCourse(int courseIde, int studentId)
    {
        StudentId = studentId;
        CourseId = courseIde;
    }
}

And you would go something like:

 public static  void AddCoursesToStudentMaps(SchoolDBContext context, Student student, List<int> CourseIds)
    {
        List<StudentCourse> maps = CourseIds.ConvertAll(courseId => new StudentCourse(courseId, student.StudentId)).ToList();
        context.StudentCourses.AddRange(maps);
    }

It would be nice to do this in a way that Entity Framework manages this, perhaps I could just create the student Courses class and add it to the context? But that seems to defeat the point, especially as we have a lot of many to many and having EF create the mapping table for us would cut down the code. I just think if EF is capable of creating the mapping automatically, it must have a way of efficiently creating new links without redoing the work it has done?

In order to test this I have created this example code, with a lazy setup function, so if anyone wants to have a bash, this should get you up and running:

 static void Main(string[] args)
    {
        Run();
    }

    private static void Run()
    {
        using (SchoolDBContext context = new SchoolDBContext())
        {
            /* Run once
             * SetUp(context);
             */
            Test(context);
            Output(context);
        }
    }

    static void SetUp(SchoolDBContext context)
    {
        context.Students.Add(new Student() { StudentName = "Gerry" });
        context.Students.Add( new Student() { StudentName = "Bob" }  );
        context.Students.Add( new Student() { StudentName = "Jane" } );

        context.Courses.Add( new Course() { CourseName = "Science" });
        context.Courses.Add( new Course() { CourseName = "Math" }  );
        context.Courses.Add( new Course() { CourseName = "History" } );
        context.Courses.Add(new Course() { CourseName = "Other History" });
        context.Courses.Add(new Course() { CourseName = "Roman History" });
        context.Courses.Add(new Course() { CourseName = "English History" });
        context.Courses.Add(new Course() { CourseName = "Super History" });
        context.Courses.Add(new Course() { CourseName = "Tudor History" });
        context.Courses.Add(new Course() { CourseName = "Queen History" });
        context.Courses.Add(new Course() { CourseName = "King History" });
        context.SaveChanges();
    }

    public static void Test(SchoolDBContext context)
    {

        var ids = context.Courses.Where(x => x.CourseName.Contains("History")).Select(x => x.CourseId).ToList();
        var student = context.Students.FirstOrDefault(x => x.StudentName == "Bob");
        AddCoursesToStudent(context, student, ids);
    }

    private static void Output(SchoolDBContext context)
    {
        OutputStudents(context);
    }

    private static void OutputStudents(SchoolDBContext context)
    {
        var allStudents = context.Students.ToList();
        foreach (var student in allStudents)
        {
            Console.WriteLine($"Student: {student.StudentName}");
            if (student.Courses.Any())
            {
                Console.WriteLine("is enrolled on");
                Console.WriteLine("**************************");
                foreach (var contextCourseStudent in student.Courses)
                {
                    Console.WriteLine("     " + contextCourseStudent.CourseName);
                }
                Console.WriteLine("************************ ");
            }
            Console.WriteLine("-------------------------");
        }
        Console.WriteLine("Press enter to close...");
        Console.ReadLine();
    }
    private static void OutputCourse(SchoolDBContext context)

p.s. the reason for not just having a list of courses is due to the fact we have forms/apps etc already set up that send id lists and as mentioned it seems silly and inefficient to then pull those models out of the database, purely to add them to the parent.

Body:
I don't think many-to-many with implicit link table is Code First specific. Also while it makes querying easier and more natural, as you already have seen it has obvious drawbacks when with link modifications.

It's possible to implement the adding new links efficiently by using stub entities:

static void AddCoursesToStudent(SchoolDBContext context, Student student, List<int> CourseIds)
{
    student.Courses = CourseIds.Select(id => context.Courses.Attach(new Course { CourseId = id })).ToList();
    context.SaveChanges();
}

This works, but under the following constraints:

(1) The context has been created specifically for this call

(2) student is already attached to the context

(3) All the CourseIds exist in the database

(4) There are no Course entities loaded in the context with some of the CourseIds

(5) The initial student.Courses collection is not eager or lazy loaded. This is specifically to enforce add link operation (vs replace all links by determining the added and removed items)

(6) You don't use afterwards the context or any of the Course objects, because all their properties except the PK are not real.

An example considering all the constraints:

public void AddCoursesToStudent(int studentId, List<int> coursesIds)
{
    using (var context = new SchoolDBContext())
    {
        var student = context.Students.Find(studentId);
        AddCoursesToStudent(context, student, coursesIds);
    }
}


问:
spring ignoreResourceNotFound is not working
I have configured a property file like below

```<code><bean id="applicationHostProperties"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="ignoreResourceNotFound" value="true"></property>
        <property name="locations">
            <list>
                <value>classpath:applicationHost.properties</value>
            </list>
        </property>
</bean>
</code>```

From my spring bean I am injecting the property file

```<code>@Value("#{appsDeployedProperties}")
private Properties appsDeployedProperties;
</code>```

Since I have set ignoreResourceNotFound=true, I am not expecting any error if the property file is not found.

But my spring context initialization fails, if the property file is missing. Am I doing something wrong here ? Thanks for your help.

Error Stack Trace:

```<code>> Error creating bean with name 'instanceConfigurati
>     on': Unsatisfied dependency expressed through field 'appsDeployedProperties': Ex
>     pression parsing failed; nested exception is org.springframework.expression.spel
>     .SpelEvaluationException: EL1008E:(pos 0): Property or field 'appsDeployedProper
>     ties' cannot be found on object of type 'org.springframework.beans.factory.confi
>     g.BeanExpressionContext' - maybe not public?; nested exception is org.springfram
>     ework.beans.factory.BeanExpressionException: Expression parsing failed; nested e
>     xception is org.springframework.expression.spel.SpelEvaluationException: EL1008E
>     :(pos 0): Property or field 'appsDeployedProperties' cannot be found on object o
>     f type 'org.springframework.beans.factory.config.BeanExpressionContext' -
> maybe
>     not public?; nested exception is org.springframework.beans.factory.UnsatisfiedDe
>     pendencyException: Error creating bean with name 'instanceConfiguration': Unsati
>     sfied dependency expressed through field 'appsDeployedProperties': Expression pa
>     rsing failed; nested exception is org.springframework.expression.spel.SpelEvalua
>     tionException: EL1008E:(pos 0): Property or field 'appsDeployedProperties' canno
>     t be found on object of type 'org.springframework.beans.factory.config.BeanExpre
>     ssionContext' - maybe not public?; nested exception is org.springframework.beans
>     .factory.BeanExpressionException: Expression parsing failed; nested exception is
>      org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): P
>     roperty or field 'appsDeployedProperties' cannot be found on object of type 'org
>     .springframework.beans.factory.config.BeanExpressionContext' - maybe not public?at
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanP
>     ostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.j
>     ava:569) ~[spring-beans-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
>             at org.springframework.beans.factory.annotation.InjectionMetadata.inject
>     (InjectionMetadata.java:88) ~[spring-beans-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
>             at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanP
>     ostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java
>     :349) ~[spring-beans-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
</code>```

答:
You have to bind keys from applicationHost.properties as String rather than Properties. For example, if you have key appsDeployedProperties in applicationHost.properties, as follows:

applicationHost.properties

```<code>appsDeployedProperties=hello
</code>```

In Spring Bean, you have to use as String, like:

```<code>@Value("#{appsDeployedProperties}")
private String appsDeployedProperties;
</code>```

P.S: You can add ignoreUnresolvablePlaceholders key with value as true to tell Spring to ignore keys used in bean which are not mentioned in any property file, as follows:

```<code><bean id="applicationHostProperties"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="ignoreResourceNotFound" value="true"></property>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:applicationHost.properties</value>
            </list>
        </property>
</bean>
</code>```

Body:
I have configured a property file like below

<bean id="applicationHostProperties"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="ignoreResourceNotFound" value="true"></property>
        <property name="locations">
            <list>
                <value>classpath:applicationHost.properties</value>
            </list>
        </property>
</bean>

From my spring bean I am injecting the property file

@Value("#{appsDeployedProperties}")
private Properties appsDeployedProperties;

Since I have set ignoreResourceNotFound=true, I am not expecting any error if the property file is not found.

But my spring context initialization fails, if the property file is missing. Am I doing something wrong here ? Thanks for your help.

Error Stack Trace:

> Error creating bean with name 'instanceConfigurati
>     on': Unsatisfied dependency expressed through field 'appsDeployedProperties': Ex
>     pression parsing failed; nested exception is org.springframework.expression.spel
>     .SpelEvaluationException: EL1008E:(pos 0): Property or field 'appsDeployedProper
>     ties' cannot be found on object of type 'org.springframework.beans.factory.confi
>     g.BeanExpressionContext' - maybe not public?; nested exception is org.springfram
>     ework.beans.factory.BeanExpressionException: Expression parsing failed; nested e
>     xception is org.springframework.expression.spel.SpelEvaluationException: EL1008E
>     :(pos 0): Property or field 'appsDeployedProperties' cannot be found on object o
>     f type 'org.springframework.beans.factory.config.BeanExpressionContext' -
> maybe
>     not public?; nested exception is org.springframework.beans.factory.UnsatisfiedDe
>     pendencyException: Error creating bean with name 'instanceConfiguration': Unsati
>     sfied dependency expressed through field 'appsDeployedProperties': Expression pa
>     rsing failed; nested exception is org.springframework.expression.spel.SpelEvalua
>     tionException: EL1008E:(pos 0): Property or field 'appsDeployedProperties' canno
>     t be found on object of type 'org.springframework.beans.factory.config.BeanExpre
>     ssionContext' - maybe not public?; nested exception is org.springframework.beans
>     .factory.BeanExpressionException: Expression parsing failed; nested exception is
>      org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): P
>     roperty or field 'appsDeployedProperties' cannot be found on object of type 'org
>     .springframework.beans.factory.config.BeanExpressionContext' - maybe not public?at
> org.springframework.beans.factory.annotation.AutowiredAnnotationBeanP
>     ostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.j
>     ava:569) ~[spring-beans-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
>             at org.springframework.beans.factory.annotation.InjectionMetadata.inject
>     (InjectionMetadata.java:88) ~[spring-beans-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
>             at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanP
>     ostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java
>     :349) ~[spring-beans-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]

Body:
You have to bind keys from applicationHost.properties as String rather than Properties. For example, if you have key appsDeployedProperties in applicationHost.properties, as follows:

applicationHost.properties

appsDeployedProperties=hello

In Spring Bean, you have to use as String, like:

@Value("#{appsDeployedProperties}")
private String appsDeployedProperties;

P.S: You can add ignoreUnresolvablePlaceholders key with value as true to tell Spring to ignore keys used in bean which are not mentioned in any property file, as follows:

<bean id="applicationHostProperties"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="ignoreResourceNotFound" value="true"></property>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:applicationHost.properties</value>
            </list>
        </property>
</bean>


问:
C program crashes sometimes and sometimes not
I'm only a few days into C programming. I wanted to rewrite a small program for computing prime numbers in C to see how much faster it would run in comparison to Java (the programming language I'm coming from).

I now encountered a (to me) very strange problem. Sometimes the program works fine, compiles and terminates, but sometimes it crashes somewhere in the "calculateNewPrimes()" function. Eclipse doesn't display any error-messages and the compilation seems also to work fine. Does anybody see the mistake and could point it out for a c-newbie like me? :) Previous research on this site and other web-pages didn't brought any result.

Global variables:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

void prepareSession();
void calculateNewPrimes();
void saveResults();

// you can modify the filepath here if you're on a new machine
char filePath[] = "/home/userName/Eclipse/workspace/PrimeNumbers/primes.txt";

// the available system memory or the maxAmount of memory you would like
// to use for the storage of the prime-numbers in BYTES
long long int memorySize = 7000000000LL;

//The file where the prime numbers will be saved
FILE *file;

// We begin with the number 3, so that we only have to check odd numbers.
// 2 is therefore already discovered (amount = 1)
long long int oldAmount = 1;
long long int current = 3;

// a pointer to the array with the already known primes
long long int *knownPrimes;
long long int *newPrimes;
</code>```

The program consists of 3 functions. The first one reads primes from previous calculations in the memory, the second one calculates the new primes and the last function saves the newly calculated primes back into the file.

```<code>int main(){
    prepareSession();
    calculateNewPrimes();
    saveResults();
}
</code>```

The function prepareSession() seems to work just fine. You can assume that the file doesn't exist yet and the start conditions are used.

```<code>void prepareSession(){
    // try to open the file, if the file doesn't exist it will be created
    file = fopen(filePath,"a+");
    long long int temp = -1;
    fscanf(file,"%lli",&temp);
    // if the file isn't empty, read the amount and the highest number in their variables
    if(temp != -1){
        /*some code */
    }
    else{
        // the file was newly created so the only known prime is 2
        printf("File doesn't yet exist. \n");
        long long int temp[1] = {2};
        knownPrimes = temp;
    }
    fclose (file);
}
</code>```

The critical function. Somewhere here the error occurs.

```<code>void calculateNewPrimes(){
        long long int newAmount;
        long long int primesFound = 0;

        printf("How many new primes would you like to calculate? \n");
        scanf("%lli",&newAmount);
        printf("I will calculate %lli new primes. \n",newAmount);
        long long int temp[newAmount];
        newPrimes = temp;

        //prepare measuring
        double progress=0.0;
        int oldProgress=0;
        time_t start = time(0);

        long long int currentNumber,oldNumber;
        // start the calculations
        while(primesFound < newAmount){
            oldNumber = 2;
            for(long long int i = 1; i < oldAmount + newAmount; i++){
                if(i < oldAmount){currentNumber = *(knownPrimes + i);}
                else{ currentNumber = *(newPrimes + (i-oldAmount));}

                if(current % currentNumber == 0){
                    break;
                }
                else if(currentNumber > current/oldNumber || i == oldAmount + primesFound-1){
                    *(newPrimes + primesFound++) = current;
                    printf("Found Nr.%lli: %lli \n",primesFound,current);
                    progress = (primesFound)/(double) newAmount;
                    while(oldProgress/100.0 < progress){
                            printf("%d \n",++oldProgress);
                    }
                    break;
                }
            }
            current+=2;
        }
        double timeDifference = difftime( time(0), start);
        printf("It took %g to calculate %lli new Primes \n",timeDifference, newAmount);
    }
</code>```

答:
OK, a few pointers to get started here.

You say, "it seems to get stuck", sometimes.  Let's break this down:

Do you mean the program hangs?  How do you know it is in this
function?  Have you broken into the debugger?

Does the "sometimes" have any relationship to the input?  Or is it random?  "Input" would include both the file and the number you input.

Does the program ever crash?

Suggestion #1: If the program hangs, you should be able to break into it in the debugger, and then step through the code to see where it is going wrong.  Otherwise, some print statements in key places can give you debugging hints.

Now to the code itself.

You have a clear bug in the code as mentioned in – GAURANG VYAS's   comment
.  You are referencing a local variable through a global
pointer (temp) after the function has exited.   This alone could
cause inconsistent behaviour, crashes, etc.

You've got an else if with a somewhat complex condition.  If you aren't a whiz in C operator precedence, you may or may not be doing what you think you are.  (Even if you have it right, the next person reading the code may not!).  I suggest using parentheses.

OK, I copied, compiled, and ran your code.  You are going into an infinite loop, and it does seem to be related to the number you input.  5 always seems to work, 6 does not.  This is a useful clue; your conditions to exit the loop are failing when the number gets larger. Again, since you are referencing freed memory you may be using invalid data here.

Try adding the line -

printf("current is %d\n", current); immediately after current+=2;

and you will see that you are in an infinite loop; it just keeps increasing.

This is hopefully enough information for you to continue the debugging.

Body:
I'm only a few days into C programming. I wanted to rewrite a small program for computing prime numbers in C to see how much faster it would run in comparison to Java (the programming language I'm coming from).

I now encountered a (to me) very strange problem. Sometimes the program works fine, compiles and terminates, but sometimes it crashes somewhere in the "calculateNewPrimes()" function. Eclipse doesn't display any error-messages and the compilation seems also to work fine. Does anybody see the mistake and could point it out for a c-newbie like me? :) Previous research on this site and other web-pages didn't brought any result.

Global variables:

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

void prepareSession();
void calculateNewPrimes();
void saveResults();

// you can modify the filepath here if you're on a new machine
char filePath[] = "/home/userName/Eclipse/workspace/PrimeNumbers/primes.txt";

// the available system memory or the maxAmount of memory you would like
// to use for the storage of the prime-numbers in BYTES
long long int memorySize = 7000000000LL;

//The file where the prime numbers will be saved
FILE *file;

// We begin with the number 3, so that we only have to check odd numbers.
// 2 is therefore already discovered (amount = 1)
long long int oldAmount = 1;
long long int current = 3;

// a pointer to the array with the already known primes
long long int *knownPrimes;
long long int *newPrimes;

The program consists of 3 functions. The first one reads primes from previous calculations in the memory, the second one calculates the new primes and the last function saves the newly calculated primes back into the file.

int main(){
    prepareSession();
    calculateNewPrimes();
    saveResults();
}

The function prepareSession() seems to work just fine. You can assume that the file doesn't exist yet and the start conditions are used.

void prepareSession(){
    // try to open the file, if the file doesn't exist it will be created
    file = fopen(filePath,"a+");
    long long int temp = -1;
    fscanf(file,"%lli",&temp);
    // if the file isn't empty, read the amount and the highest number in their variables
    if(temp != -1){
        /*some code */
    }
    else{
        // the file was newly created so the only known prime is 2
        printf("File doesn't yet exist. \n");
        long long int temp[1] = {2};
        knownPrimes = temp;
    }
    fclose (file);
}

The critical function. Somewhere here the error occurs.

void calculateNewPrimes(){
        long long int newAmount;
        long long int primesFound = 0;

        printf("How many new primes would you like to calculate? \n");
        scanf("%lli",&newAmount);
        printf("I will calculate %lli new primes. \n",newAmount);
        long long int temp[newAmount];
        newPrimes = temp;

        //prepare measuring
        double progress=0.0;
        int oldProgress=0;
        time_t start = time(0);

        long long int currentNumber,oldNumber;
        // start the calculations
        while(primesFound < newAmount){
            oldNumber = 2;
            for(long long int i = 1; i < oldAmount + newAmount; i++){
                if(i < oldAmount){currentNumber = *(knownPrimes + i);}
                else{ currentNumber = *(newPrimes + (i-oldAmount));}

                if(current % currentNumber == 0){
                    break;
                }
                else if(currentNumber > current/oldNumber || i == oldAmount + primesFound-1){
                    *(newPrimes + primesFound++) = current;
                    printf("Found Nr.%lli: %lli \n",primesFound,current);
                    progress = (primesFound)/(double) newAmount;
                    while(oldProgress/100.0 < progress){
                            printf("%d \n",++oldProgress);
                    }
                    break;
                }
            }
            current+=2;
        }
        double timeDifference = difftime( time(0), start);
        printf("It took %g to calculate %lli new Primes \n",timeDifference, newAmount);
    }


问:
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

```<code>int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}
</code>```

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

```<code>int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
</code>```

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

答: Really either is fine, but you need to do what your professor wants.  You'll find it is the same in industry as well.  Some companies may have a coding standard that dictates curly braces go on a new line, while others want them to start on the line that begins the block.  There is no real reason to prefer one over the other, so it is best to just go with what the lead wants.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?


问:
How to access Scope value outside the method in angularjs
In below AngularJS controller:

Initially I declared 2 global variables, x and y

Then I perform an AJAX call using $http.get() and I got the correct response from the backend, and kept the required response values in variables x and y.

In an alert message I am trying to print the values of x and y.

I have gone through other question and answers in Stack Overflow and it is a duplicate question, but it's not successful here.

```<code>app.controller('MyController', function($scope, $http, $rootScope) {
    $scope.x = '';
    $scope.y = '';
    $http.get('javaAngularJS').then(function (response) {
        var data = response.data;
        $scope.smsresult = data;
        //need to print following x and y values in below alert message
        $scope.x = $scope.smsresult.failure;
        $scope.y = $scope.smsresult.success;
    });

    alert(x+"   "+y);
});
</code>```

But in the alert message, the values of x* and y are not printing.  What's my mistake  in above code?

答:
try to set 'x' and 'y' inside of response function  like

```<code>$http.get('javaAngularJS').then(function (response)
{
  var data = response.data;
  $scope.smsresult = data;
  //need to print following x and y values in below alert message
  $scope.x = $scope.smsresult.failure;
  $scope.y = $scope.smsresult.success;
 alert($scope.x+"   "+$scope.y);
 });
</code>```

Ajax call is async so when you print alert ajax is not done yet.

If you want to have processing logic outside success block you can put it in separate function and call it in success section :

```<code>$http.get('javaAngularJS').then(function (response)
{
  $scope.processSmsResponse(response);
});

$scope.processSmsResponse = function (response){
//your logic here
}
</code>```

Body:
In below AngularJS controller:

Initially I declared 2 global variables, x and y

Then I perform an AJAX call using $http.get() and I got the correct response from the backend, and kept the required response values in variables x and y.

In an alert message I am trying to print the values of x and y.

I have gone through other question and answers in Stack Overflow and it is a duplicate question, but it's not successful here.

app.controller('MyController', function($scope, $http, $rootScope) {
    $scope.x = '';
    $scope.y = '';
    $http.get('javaAngularJS').then(function (response) {
        var data = response.data;
        $scope.smsresult = data;
        //need to print following x and y values in below alert message
        $scope.x = $scope.smsresult.failure;
        $scope.y = $scope.smsresult.success;
    });

    alert(x+"   "+y);
});

But in the alert message, the values of x* and y are not printing.  What's my mistake  in above code?

Body:
try to set 'x' and 'y' inside of response function  like

$http.get('javaAngularJS').then(function (response)
{
  var data = response.data;
  $scope.smsresult = data;
  //need to print following x and y values in below alert message
  $scope.x = $scope.smsresult.failure;
  $scope.y = $scope.smsresult.success;
 alert($scope.x+"   "+$scope.y);
 });

Ajax call is async so when you print alert ajax is not done yet.

If you want to have processing logic outside success block you can put it in separate function and call it in success section :

$http.get('javaAngularJS').then(function (response)
{
  $scope.processSmsResponse(response);
});

$scope.processSmsResponse = function (response){
//your logic here
}


问:
Are add-ins going to disappear if I re-install office 2010?
I am wondering if Office add-ins will disappear if I re-install office 2010 on my work computer. I work with finance so the add-ins are very important for my job. I have been searching the web a lot but can't find any answers.</p>

答:
This depends on what kind of Add-Ins you use.

STARUP Add-Ins

If you have "Macro" type add ins sitting in your STARTUP folder or even maybe in your Normal.dotm they will be gone. Because the STARTUP folder is usually set to the Office installation directory.
It could also be changed by your company to a central folder. Then they would remain.

COM-Add-Ins

If you have COM-Add-Ins it depends on their installation location. Normally Add-Ins won't install into the Office installation directory (you'll need to check). After a re-installation of Office 2010 you probably have to repair them so they are registered properly again. It depends on the Add-In maybe you have to reinstall them as well.

Actions/XML-Schema

If you have actions installed I can't really tell you what happens to them. I've no experience. Maybe another answer or person can help here (feel free to edit or comment on it).

How to proceed?

As a start you need to investigate your installed Add-Ins follow this Microsoft link here. After you know what you have you can come back or decide what Add-Ins are critical for you to keep. Figure out their installation location and/or installers and backup them.


问:
Button added to custom section header view disappears when row is deleted
Just came across some very strange behavior in my app. I've recreated the problem in a simplest-case scenario:

```<code>NSMutableArray *data;

- (void)viewDidLoad {
    [super viewDidLoad];
    data = [[NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil] retain];
}

- (UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 32.0)];
    header.backgroundColor = [UIColor lightGrayColor];
    [header addSubview:self.button];
    return header;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [data removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
    cell.textLabel.text = [data objectAtIndex:indexPath.row];
    return cell;
}

- (void)dealloc {
    [super dealloc];
}
</code>```

Every time I delete a row; the button in my header disappears! This happens no matter what type of rowAnimation I use. If I scroll the table up so that the header scrolls off; the button returns when the header returns. The button is created in the xib file.

I can work around it in one of 2 ways:

Reloading the tableView data after the delete; with a delay so that the deletion animation completes first.

Creating the button in viewForHeaderInSection instead of in the interfaceBuilder.

I'd really like to understand what's going on here. Where is the button going? I've confirmed that viewForHeaderInSection is called when I delete a row.

Edit I tried changing it so that the button is created in viewForHeader, instead of in the xib, but it's causing other strange issues... when I create or delete the button, I am setting certain properties such as the title and enabled depending on how many items there are in the table. When I delete the last row in the table, I don't see the update in text and enabled status until I scroll the button off the screen and back on again.

答:
Where is your implementation of the delegate method  tableView:heightForHeaderInSection: ? That is necessary for tableView:viewForHeaderInSection: to work correctly. Check the docs.
Reference for UITableView delegate

I've confirmed that
  viewForHeaderInSection is called when
  I delete a row.

Have you confirmed that viewForHeaderInSection is called for the particular header with the added button?
Then, try adding

```<code>[header bringSubviewToFront:self.button];
</code>```

after adding the button.

Body:
Just came across some very strange behavior in my app. I've recreated the problem in a simplest-case scenario:

NSMutableArray *data;

- (void)viewDidLoad {
    [super viewDidLoad];
    data = [[NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil] retain];
}

- (UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 32.0)];
    header.backgroundColor = [UIColor lightGrayColor];
    [header addSubview:self.button];
    return header;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [data removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
    cell.textLabel.text = [data objectAtIndex:indexPath.row];
    return cell;
}

- (void)dealloc {
    [super dealloc];
}

Every time I delete a row; the button in my header disappears! This happens no matter what type of rowAnimation I use. If I scroll the table up so that the header scrolls off; the button returns when the header returns. The button is created in the xib file.

I can work around it in one of 2 ways:

Reloading the tableView data after the delete; with a delay so that the deletion animation completes first.

Creating the button in viewForHeaderInSection instead of in the interfaceBuilder.

I'd really like to understand what's going on here. Where is the button going? I've confirmed that viewForHeaderInSection is called when I delete a row.

Edit I tried changing it so that the button is created in viewForHeader, instead of in the xib, but it's causing other strange issues... when I create or delete the button, I am setting certain properties such as the title and enabled depending on how many items there are in the table. When I delete the last row in the table, I don't see the update in text and enabled status until I scroll the button off the screen and back on again.

Body:
Where is your implementation of the delegate method  tableView:heightForHeaderInSection: ? That is necessary for tableView:viewForHeaderInSection: to work correctly. Check the docs.
Reference for UITableView delegate

I've confirmed that
  viewForHeaderInSection is called when
  I delete a row.

Have you confirmed that viewForHeaderInSection is called for the particular header with the added button?
Then, try adding

[header bringSubviewToFront:self.button];

after adding the button.


问:
WebSocket Server Application with an extensible (multi layered) architecture
Now that I have a back-end server which accepts websocket connections, I need to implement an extensible & testable architecture.

What [https://github.com/websockets/ws] ws provides me is a simple websocket server than listens to new messages. If I go on implementing 50+ different types of messages within the same switch statement, it rapidly goes out of control.

I would like to have some recommendations/ideas on how I can divide and conquer this flow of messages in a more architectural way.

答:
The easiest way to solve you problem is to use a framework combined with routing module. This will make managing your message managing code readable without extra effort.

A good example of such a combination is express with express-ws module. Express-ws is a Syntactic sugar build on top of ws module that among other things allows you to use router middleware to manage your messages.

```<code>const expressWs = require('express-ws')(app);

const router = express.Router();

router.ws('/echo', function(ws, req) {
  ws.on('message', function(msg) {
    ws.send(msg);
  });
});

app.use("/ws-stuff", router);
</code>```

Also you can move the message handling logic to "controllers" like this:

```<code>ws.on('message', function(msg) {
   MessageController.handler(msg);
});
</code>```

The next step would be breaking your routes on separate files depending on business domains to not have one huge file with all the routing

Body:
The easiest way to solve you problem is to use a framework combined with routing module. This will make managing your message managing code readable without extra effort.

A good example of such a combination is express with express-ws module. Express-ws is a Syntactic sugar build on top of ws module that among other things allows you to use router middleware to manage your messages.

const expressWs = require('express-ws')(app);

const router = express.Router();

router.ws('/echo', function(ws, req) {
  ws.on('message', function(msg) {
    ws.send(msg);
  });
});

app.use("/ws-stuff", router);

Also you can move the message handling logic to "controllers" like this:

ws.on('message', function(msg) {
   MessageController.handler(msg);
});

The next step would be breaking your routes on separate files depending on business domains to not have one huge file with all the routing


问:
How to edit default page in wordpress?(index page)
How to edit default page in WordPress site?(index page).
I am inspecting the current page, and find that the code is in index page.
But there is no way to find where is the file located.
The site hosted on hostinger. Then I am trying to edit other pages other than default page? Is there is a way to find the index page?</p>

答:
Option one:
Download the theme. Then open any file of that theme in file editor. Then search for/find (Ctrl+F) that code/text you are looking for. Select option in which file or folder search for. It will locate the code with file location.

Option Two:
If you have FTP access by using FileZilla you will be able to find the file by searching for the code/text.


答:
With BeautifulSoup:

```<code>html = '<h3>freedom machines.</h3><p>dom.</p><br/><p>The robust display.</p>'
soup = BeautifulSoup(html)
text = soup.find("h3").string
</code>```

This is a basic use of BeautifulSoup.
Create a BeautifulSoup object with your string as parameter.
Then use its find method to find the tag with the name you're looking for.
Finally, get the text the tag surrounds with its string attribute.

If you know that your text is in a
,
 or
 but you don't know which, just try all of them.
You can even check the three at once:

```<code>tag = soup.find("h1") or soup.find("h2") or soup.find("h3")
text = tag.string
</code>```

The or operator will return the first member that evaluates as True Boolean-wise.
In this case, it means the first soup.find result that is not None.
The find method accepts an iterator as well, so you can pass it a static tuple.
The result will be a tag object (if any) that matches any of the asked types.

```<code>tag = soup.find(("h1", "h2", "h3"))
</code>```

Of course, it is better to know exactly in advance what tag will contain what you want...
If there are both
 and
 tags on the page, you won't know what to do...

Title: Extracting a HTML tag from a string

Body:
Can anyone please explain how would I extract a substring from an input string.

Input:

'
freedom machines.

dom.

The robust display.
'

Output :

'
freedom machines.
'

I am trying to do it with regex, but no luck.
Do you have any suggestions?

I need to check whether my string starts from any header tag (
,
 or
), and if it does, I will extract that header tag.

I tried with startswith, but with no success:

if input.startswith("<h"):
  ** Code to extract that h tag.

Body:
With BeautifulSoup:

html = '<h3>freedom machines.</h3><p>dom.</p><br/><p>The robust display.</p>'
soup = BeautifulSoup(html)
text = soup.find("h3").string

This is a basic use of BeautifulSoup.
Create a BeautifulSoup object with your string as parameter.
Then use its find method to find the tag with the name you're looking for.
Finally, get the text the tag surrounds with its string attribute.

If you know that your text is in a <h1>, <h2> or <h3> but you don't know which, just try all of them.
You can even check the three at once:

tag = soup.find("h1") or soup.find("h2") or soup.find("h3")
text = tag.string

The or operator will return the first member that evaluates as True Boolean-wise.
In this case, it means the first soup.find result that is not None.
The find method accepts an iterator as well, so you can pass it a static tuple.
The result will be a tag object (if any) that matches any of the asked types.

tag = soup.find(("h1", "h2", "h3"))

Of course, it is better to know exactly in advance what tag will contain what you want...
If there are both <h1> and <h2> tags on the page, you won't know what to do...