问:
How to get individual values from JSON object
I'm using PubNub API in android to fetch real time data but I need some particular value instead of whole. How can I get value for example c7 & c9. I want them to plot a real time graph.

```<code> @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            System.out.println(message);
        }
</code>```

The result I'm getting :-

PNMessageResult (message={"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}`

答:
```<code>String s="{
"c1":27,
"c2":3,
"c3":2017,
"c4":15,
"c5":56,
"c6":52,
"c7":15.07,
"c8":"P&Q",
"c9":24.86,
"c10":82,
"c11":32.74`
}";

try{
  JSONObject jsonObject = new JSONObject(s);
  double c7 = jsonObject.getDouble("c6");
  double c9 = jsonObject.getDouble("c2");
}
catch(JSONException e){
  e.printStackTrace()
}
</code>```

Body:
I'm using PubNub API in android to fetch real time data but I need some particular value instead of whole. How can I get value for example c7 & c9. I want them to plot a real time graph.

 @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            System.out.println(message);
        }

The result I'm getting :-

PNMessageResult (message={"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}`


来源: stackexchange

问:
Running from command line-writing to file
I'm kinda new here. I'm trying to run a java program through the command line but I need to output to a file. So, in the command line I run:

[my filepath]> javac filename.java

And then I run

[my filepath]> javac filename.java > outputfileIneed.txt

In filename.java, I use System.out.println(), and the computer creates a text file in the appropriate location, but the file is blank. What do I write to fix this? This seems to be more of a java problem; is there a command other than System.out.println() to print to a text file from commmand line?

Please ask for more information if you need.

答:
The command:

```<code>javac filename.java
</code>```

is used to compile your java code.

If your code has no compile errors, it means your file outputfileIneed.txt will not contain anything.

After you have run your javac filename.java command, you need to run the following command.

```<code>java filename > outputfileIneed.txt
</code>```

this will redirect the output of your java program to the outputfileIneed.txt file.

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
The command:

javac filename.java

is used to compile your java code.

If your code has no compile errors, it means your file outputfileIneed.txt will not contain anything.

After you have run your javac filename.java command, you need to run the following command.

java filename > outputfileIneed.txt

this will redirect the output of your java program to the outputfileIneed.txt file.

Hope this helps!


问:
react-native-device-detection not working with Nexus 7
I had created an imageGallery application built over React-Native.
The basic requirement is

Mobile View shows 3 images per row.

Tablet View shows 5 images per row.

Device detection is done using react-native-device-detection

The number of images per row is limited using Dimensions object.

```<code>const Device = require('react-native-device-detection');
 if(Device.isTablet) {
 Object.assign(styles, {
  image: {
    width: Dimensions.get('window').width / 5 - 10 ,
    height: Dimensions.get('window').width / 5 - 10,
  }
 });
}
if(Device.isPhone) {
 Object.assign(styles, {
  image: {
    width: Dimensions.get('window').width / 3 - 10 ,
    height: Dimensions.get('window').width / 3 - 10,
  }
 });
}
</code>```

This works fine in mobile and also in the simulator (Nexus 7).
Checked with https://material.io/devices/. Nexus 7 comes under Tablet.
Nexus 7 Emulator Screenshot

Nexus 7 Device Screenshot

But in the device (Nexus 7) it shows 3 images per row.(Mobile behavior).

How can this be fixed?

答:
Nexus 7 is actually a mini tablet as per manufacturer. react-native-device-detection identifies the device on the basis of their height/width and pixelDensity like this.

```<code>  isPhoneOrTablet() {
    if(this.pixelDensity < 2 && (this.adjustedWidth >= 1000 || this.adjustedHeight >= 1000)) {
      this.isTablet = true;
      this.isPhone = false;
    } else if(this.pixelDensity === 2 && (this.adjustedWidth >= 1920 || this.adjustedHeight >= 1920)) {
      this.isTablet = true;
      this.isPhone = false;
    } else {
      this.isTablet = false;
      this.isPhone = true;
    }
  }
</code>```

There is a chance for wrong info if the device has unorthodox sizes, you can add your own custom calculations to make it more accurate.

Body:
I had created an imageGallery application built over React-Native.
The basic requirement is

Mobile View shows 3 images per row.

Tablet View shows 5 images per row.

Device detection is done using react-native-device-detection

The number of images per row is limited using Dimensions object.

const Device = require('react-native-device-detection');
 if(Device.isTablet) {
 Object.assign(styles, {
  image: {
    width: Dimensions.get('window').width / 5 - 10 ,
    height: Dimensions.get('window').width / 5 - 10,
  }
 });
}
if(Device.isPhone) {
 Object.assign(styles, {
  image: {
    width: Dimensions.get('window').width / 3 - 10 ,
    height: Dimensions.get('window').width / 3 - 10,
  }
 });
}

This works fine in mobile and also in the simulator (Nexus 7).
Checked with https://material.io/devices/. Nexus 7 comes under Tablet.
Nexus 7 Emulator Screenshot

Nexus 7 Device Screenshot

But in the device (Nexus 7) it shows 3 images per row.(Mobile behavior).

How can this be fixed?

Body:
Nexus 7 is actually a mini tablet as per manufacturer. react-native-device-detection identifies the device on the basis of their height/width and pixelDensity like this.

  isPhoneOrTablet() {
    if(this.pixelDensity < 2 && (this.adjustedWidth >= 1000 || this.adjustedHeight >= 1000)) {
      this.isTablet = true;
      this.isPhone = false;
    } else if(this.pixelDensity === 2 && (this.adjustedWidth >= 1920 || this.adjustedHeight >= 1920)) {
      this.isTablet = true;
      this.isPhone = false;
    } else {
      this.isTablet = false;
      this.isPhone = true;
    }
  }

There is a chance for wrong info if the device has unorthodox sizes, you can add your own custom calculations to make it more accurate.


问:
Disable SQL_CALC_FOUND_ROWS with Pagination
I want to disable Disable SQL_CALC_FOUND_ROWS with Pagination. For that purpose, i am using the following code from SQL_CALC_FOUND_ROWS but due to that code pagination not working. How i do this or how to improve below code? </p>

```<code>if ( ! function_exists( 'oz_optimized_get_posts' ) ):
function oz_optimized_get_posts() {
    global $wp_query, $wpdb;

    $wp_query->query_vars['no_found_rows'] = 1;
    $wp_query->found_posts = $wpdb->get_var( "SELECT COUNT(*) FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')" );
    $wp_query->found_posts = apply_filters_ref_array( 'found_posts', array( $wp_query->found_posts, &$wp_query ) );

    $posts_per_page = ( ! empty( $wp_query->query_vars['posts_per_page'] ) ? $wp_query->query_vars['posts_per_page'] : get_option( 'posts_per_page' ) );
    $wp_query->max_num_pages = ceil( $wp_query->found_posts / $posts_per_page );

    return $wp_query;
}
add_filter( 'pre_get_posts', 'oz_optimized_get_posts', 100 );
endif;
</code>```

答:
Edwar D author of the post "WordPress: SQL_CALC_FOUND_ROWS, why it’s slow and what to do about it" updated his code on my request and updated code works 110%.

Bundle of Thanks

Body:
I want to disable Disable SQL_CALC_FOUND_ROWS with Pagination. For that purpose, i am using the following code from SQL_CALC_FOUND_ROWS but due to that code pagination not working. How i do this or how to improve below code?

if ( ! function_exists( 'oz_optimized_get_posts' ) ):
function oz_optimized_get_posts() {
    global $wp_query, $wpdb;

    $wp_query->query_vars['no_found_rows'] = 1;
    $wp_query->found_posts = $wpdb->get_var( "SELECT COUNT(*) FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')" );
    $wp_query->found_posts = apply_filters_ref_array( 'found_posts', array( $wp_query->found_posts, &$wp_query ) );

    $posts_per_page = ( ! empty( $wp_query->query_vars['posts_per_page'] ) ? $wp_query->query_vars['posts_per_page'] : get_option( 'posts_per_page' ) );
    $wp_query->max_num_pages = ceil( $wp_query->found_posts / $posts_per_page );

    return $wp_query;
}
add_filter( 'pre_get_posts', 'oz_optimized_get_posts', 100 );
endif;


问:
MySql database doesn't submit the values of my form
My database doesn't submit my values of my form, when I enter values into my form it shows nothing at all the varchar value columns and at the integer value columns there is a 0.   After I submit values

database

I'm using xampp.

```<code>   <?php
 error_reporting(0);

$con = mysqli_connect("localhost","root",'',"bwl_db");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$dbhost = 'localhost';
$user = 'root';
$password = 'root123';
$database = 'bwl_db';

$Name =  $_POST['Name'];
$Surname =  $_POST['Surname'];
$Email =  $_POST['Email'];
$Telephone = $_POST['Telephone'];
$ID_Number = $_POST['ID_Number'];

$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)
VALUES ('$Name','$Surname','$Email','$Telephone','$ID_Number')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}

mysqli_close($con);

error_reporting(0);
ini_set('display_errors', 0)

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <title>BWL | Registration </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Fonts -->
    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>
    <!-- favicon -->
    <link rel="icon" type="image/png" href="images/favicon.png">
    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <!-- Fontawesome  -->
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <!-- responsive css -->
    <link rel="stylesheet" type="text/css" href="css/responsive.css"> </head>

<body>

    <div class="registaration-logo">
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
        <img src="images/translogo.png" alt=" ">
            </div>
        </div>
    </div>

    <form class="form-registration" action="reg_db.php" method="post">
              <h2> Registration </h2>
        <div class="form-group-row">
            <label for="Name" class="col-2 col-form-label">Name</label>
            <div class="col-10">
                <input class="form-control" name="Name" type="text" id="Name" placeholder="Enter Name"> </div>
        </div>
        <div class="form-group-row">
            <label for="Surname" class="col-2 col-form-label">Surname</label>
            <div class="col-10">
                <input class="form-control" name="Surname"  type="text" id="Surname" placeholder="Enter Surname"> </div>
        </div>
        <div class="form-group-row">
            <label for="Email" class="col-2 col-form-label">Email</label>
            <div class="col-10">
                <input class="form-control" name="Email"  type="email" id="Email" placeholder="Enter email"> </div>
        </div>
        <div class="form-group-row">
            <label for="Confirm Email" class="col-2 col-form-label"> Confirm Email</label>
            <div class="col-10">
                <input class="form-control"  type="email" id="Confirm Email" placeholder="Confirm email"> </div>
        </div>
        <div class="form-group-row">
            <label for="Telephone" class="col-2 col-form-label">Telephone Number</label>
            <div class="col-10">
                <input class="form-control" name="Telephone"  type="tel" id="telephone" placeholder="Enter Telephone Number"> </div>
        </div>
        <div class="form-group-row">
            <label for="ID_Number" class="col-2 col-form-label">ID Number</label>
            <div class="col-10">
                <input class="form-control" name="ID_Number"  type="text" id="id-number" placeholder="Enter ID Number"> </div>
        </div>
        <div class="form-group-row">
            <div class="col-sm-10">
                    <a href="verify.html" class="btn btn-default1" role="button" type="submit">Submit</a>
            </div>
        </div>

        <div class="panel panel-default">
  <div class="panel-body">
    <h3> Disclaimer</h3>
      <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
  </div>
        </div>
 </form>

</body>

</html>

 VERIFY.HTML PAGE
    <!DOCTYPE html>
<html lang="en">

<head>
    <title>BWL | Verify </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Fonts -->
    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>
    <!-- favicon -->
    <link rel="icon" type="image/png" href="images/favicon.png">
    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <!-- Fontawesome  -->
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <!-- responsive css -->
    <link rel="stylesheet" type="text/css" href="css/responsive.css"> </head>

<body>

   <div class="verify">
  <div class="jumbotron">
    <h2>Thank You</h2>
    <p>We will send you your login information when you are verified.</p>
  </div>
       </div>
</body>

</html>
</code>```

答:
Problems:

You should have a if statement to check if the form is submitted or not

Your submit link is not for submitting your form, You should have a submit button to send your form data to the current page

You have some values which didn't use those in your connection, like $dbhost, $user, $password, $database - Try using those values or clear them for your mysqli_connect

I recommend you to read this example:

Insert Data Into MySQL Using MySQLi and PDO

Body:
My database doesn't submit my values of my form, when I enter values into my form it shows nothing at all the varchar value columns and at the integer value columns there is a 0.   After I submit values

database

I'm using xampp.

   <?php
 error_reporting(0);

$con = mysqli_connect("localhost","root",'',"bwl_db");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$dbhost = 'localhost';
$user = 'root';
$password = 'root123';
$database = 'bwl_db';

$Name =  $_POST['Name'];
$Surname =  $_POST['Surname'];
$Email =  $_POST['Email'];
$Telephone = $_POST['Telephone'];
$ID_Number = $_POST['ID_Number'];

$sql="INSERT INTO reg_db (Name,Surname,Email,Telephone,ID_Number)
VALUES ('$Name','$Surname','$Email','$Telephone','$ID_Number')";

if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}

mysqli_close($con);

error_reporting(0);
ini_set('display_errors', 0)

?>

<!DOCTYPE html>

    <title>BWL | Registration </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>

    <link rel="icon" type="image/png" href="images/favicon.png">

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <link rel="stylesheet" href="css/font-awesome.min.css">

    <link rel="stylesheet" type="text/css" href="css/responsive.css">

    <form class="form-registration" action="reg_db.php" method="post">

 Registration

            Name

                <input class="form-control" name="Name" type="text" id="Name" placeholder="Enter Name">

            Surname

                <input class="form-control" name="Surname"  type="text" id="Surname" placeholder="Enter Surname">

            Email

                <input class="form-control" name="Email"  type="email" id="Email" placeholder="Enter email">

             Confirm Email

                <input class="form-control"  type="email" id="Confirm Email" placeholder="Confirm email">

            Telephone Number

                <input class="form-control" name="Telephone"  type="tel" id="telephone" placeholder="Enter Telephone Number">

            ID Number

                <input class="form-control" name="ID_Number"  type="text" id="id-number" placeholder="Enter ID Number">

                    Submit

 Disclaimer

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

 </form>

 VERIFY.HTML PAGE
    <!DOCTYPE html>

    <title>BWL | Verify </title>
    <meta charset="utf-8">
    <meta name="description" content="Simple, clean, responsive website built with html5, CSS3, Js, jQuery and Bootstrap">
    <meta name="keywords" content="web, design, html, css, html5, css3, javascript, jquery, bootstrap, development">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href='https://fonts.googleapis.com/css?family=Raleway:500italic,600italic,600,700,700italic,300italic,300,400,400italic,800,900' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,300italic,400italic,600italic,700,900' rel='stylesheet' type='text/css'>

    <link rel="icon" type="image/png" href="images/favicon.png">

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <link rel="stylesheet" href="css/font-awesome.min.css">

    <link rel="stylesheet" type="text/css" href="css/responsive.css">

Thank You

We will send you your login information when you are verified.


问:
How do you update float data type in SQL column to hold numbers with upto 20 scale
I have a SQL table with a column having float data type with default precision.
I want this column to hold data with upto 20 digits after the decimal point.

How do I update existing column to do this?

答:
try it

```<code> ALTER TABLE MyTable ALTER COLUMN MyColumndecimal decimal(38,20)

decimal(precision, scale)
</code>```

its mean left side = 18, right side = 20

Body:
try it

 ALTER TABLE MyTable ALTER COLUMN MyColumndecimal decimal(38,20)

decimal(precision, scale)

its mean left side = 18, right side = 20


问:
Additional parameters with MongoDB $sample
I've successfully used db.collection('example').aggregate({$sample: {size: 1}}) in Node.js to retrieve a random sample from my collection, however, I'd like to put in an additional parameter to only sample an item from a certain subset.  I've tried adding an additional parameter (e.g., db.collection('example').aggregate({sampleParam: {$gte: 1}}, {$sample: {size: 1}}), which did not work.

I also understand that .skip could achieve this but that it is inefficient.

答:
just add a $match stage before using $sample like this:

```<code>db.collection('example').aggregate([
  {$match:
      {sampleParam: {$gte: 1}}
  },
  {$sample: {size: 1}}
]);
</code>```

Body:
just add a $match stage before using $sample like this:

db.collection('example').aggregate([
  {$match:
      {sampleParam: {$gte: 1}}
  },
  {$sample: {size: 1}}
]);


问:
How to format the date in HTML in dd-MM-YYYY format using ng-model
I would like to format the date in HTML as dd-mm-yyyy format in ng-model but the result which I am getting is in the form of mm-dd-yyyy.I have tried using interpolator where it worked fine and I would like to know to get the output in a dd-mm-yyyy format in HTML itself using ng-model.</p>

```<code><label class="item item-input">
  <input placeholder="Date" type="date" date="dd-MM-yyyy" ng-model="vm.advance.date"></input>
</label>
</code>```

答:
Javascript way of doing this using $filter, but the type would be of string not the Date even if you use html or js way of filter ('|' pipe)

angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', '$filter', function($scope,$filter) {
     $scope.advance = $filter('date')(new Date(), 'dd-MM-yyyy');
   }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="inputExample">

<form name="testForm" ng-controller="ExampleController">
  <input placeholder="Date" ng-model="advance"/>
</form>
</body></code>```

Body:
I would like to format the date in HTML as dd-mm-yyyy format in ng-model but the result which I am getting is in the form of mm-dd-yyyy.I have tried using interpolator where it worked fine and I would like to know to get the output in a dd-mm-yyyy format in HTML itself using ng-model.

  <input placeholder="Date" type="date" date="dd-MM-yyyy" ng-model="vm.advance.date"></input>

Body:
Javascript way of doing this using $filter, but the type would be of string not the Date even if you use html or js way of filter ('|' pipe)

angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', '$filter', function($scope,$filter) {
     $scope.advance = $filter('date')(new Date(), 'dd-MM-yyyy');
   }]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="inputExample">

<form name="testForm" ng-controller="ExampleController">
  <input placeholder="Date" ng-model="advance"/>
</form>
</body>


问:
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 4294967296 bytes) in /home/news-insert.php on line 140
I am working on a project and am working on a page that should do updates and regular inserts.  I found the code elsewhere and have been modifying it to work on my project.  Anyway I fixed many errors but I keep getting a memory leak at line 140.

Here is the code:

```<code>    <?php
     /*
     Allows the user to both create new records and edit existing records
     */

     // connect to the database
     include("includes/dbconnect.inc.php");

     // creates the new/edit record form
     // since this form is used multiple times in this file, I have made it a function that is easily reusable
     function renderForm($title = '', $summary ='', $entry = '', $error = '', $id = '')
     { ?>
     <?php
     include("includes/header.inc.php");
     ?>
     <body>
     <table>
     <tr>
     <td>
     <img src="images/zombie_minions.png"/> <!--  Logo  -->
     </td>
     <td>
     <div id="nav"><ul>
     <li><a href="index.php">Home</a></li>
     <li><a href="news.php">News</a></li>
     <li><a href="about.php">About Us</a></li>
     <li><a href="signup.php">Sign Up</a></li>
     <li><a href="contact.php">Contact Us</a></li>
     <li><a  class="active"  href="news-insert.php">New/Update News Entry</a></li>
     <li><a href="/admin/">Admin Panel</a></li>
     <li><a href="/staff/">Staff Admin Panel</a></li>
     <li><a href="/client/">Client Panel</a></li>
     <li><a href="login.php">Login</a></li>
     <li><a href="logout.php">Log Out</a></li>
     </ul></div>
     </td>
     </tr>
     <tr>
     <?php
     include("includes/calendar.inc.php");
     ?>
     <td>
     <h1><?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
     <?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
     } ?>

     <form action="" method="post">
       <h2><strong>Edit News Item:</strong></h2><br><br>
       <input type="hidden" name="id" value="<?php echo $id; ?>" />
       <p>ID: <?php echo $id; ?></p>
      <!-- Date:<br>
       <input type="text" name="date" value="<?php echo $date; ?>"/><br>  -->
       Post Title:<br>
       <input type="text" name="title" min="0" max="100" value="<?php echo $title; ?>" required /><br>
       Post Summary:<br>
       <input type="text" name="summary" min="0" max="100" value="<?php echo $summary; ?>" required /><br>
       Post Entry:<br>
       <textarea type="text" name="entry" rows="4" cols="50" min="0" max="650" value="<?php echo $entry; ?>" required /></textarea><br>

       <input type="submit" value="Submit" name="submit" />
     </form>

     <?php }

     /*

     EDIT RECORD

     */
     // if the 'id' variable is set in the URL, we know that we need to edit a record
     if (isset($_GET['id']))
    {
     // if the form's submit button is clicked, we need to process the form
     if (isset($_POST['submit']))
     {
     // make sure the 'id' in the URL is valid
     if (is_numeric($_POST['id']))
     {
     // get variables from the URL/form
     $id = $_POST['ID'];
     $title = htmlentities($_POST['title'], ENT_QUOTES);
     $summary = htmlentities($_POST['summary'], ENT_QUOTES);
     $entry = htmlentities($_POST['entry'], ENT_QUOTES);
     //$date=date('y.m.d h:i:s');

     // check that title and summary are both not empty
     if ($title == '' || $summary == '' || $entry == '')
     {
     // if they are empty, show an error message and display the form
     $error = 'ERROR: Please fill in all required fields!';
     renderForm($title, $summary, $entry, $error, $id);
     }
     else
     {
     // if everything is fine, update the record in the database
     if ($stmt = $conn->prepare("UPDATE news SET title = ?, summary = ?, entry - ?
     WHERE id=?"))
     {
     $stmt->bind_param("sssi", $title, $summary, $entry, $id);
     $stmt->execute();
     $stmt->close();
     }
     // show an error message if the query has an error
     else
     {
     echo "ERROR: could not prepare SQL statement.";
     }

     // redirect the user once the form is updated
     header("Location: news.php");
     }
     }
     // if the 'id' variable is not valid, show an error message
     else
     {
     echo "Error!";
     }
     }
     // if the form hasn't been submitted yet, get the info from the database and show the form
     else
     {
     // make sure the 'id' value is valid
     if (is_numeric($_GET['id']) && $_GET['id'] > 0)
     {
     // get 'id' from URL
     $id = $_GET['id'];

     // get the recod from the database
     if($stmt = $conn->prepare("SELECT ID, title, summary, entry FROM news WHERE ID=?"))
     {
     $stmt->bind_param("i", $id);
     $stmt->execute();

     $stmt->bind_result($id, $title, $summary, $entry);
     $stmt->fetch();

     // show the form
     renderForm($title, $summary, $entry, NULL, $id);

     $stmt->close();
     }
     // show an error if the query has an error
     else
     {
     echo "Error: could not prepare SQL statement";
     }
     }
     // if the 'id' value is not valid, redirect the user back to the news.php page
     else
     {
     header("Location: news.php");
     }
     }
     }

     /*

     NEW RECORD

     */
     // if the 'id' variable is not set in the URL, we must be creating a new record
     else
     {
     // if the form's submit button is clicked, we need to process the form
     if (isset($_POST['submit']))
     {
     // get the form data
     $title = htmlentities($_POST['title'], ENT_QUOTES);
     $summary = htmlentities($_POST['summary'], ENT_QUOTES);
     $entry = htmlentities($_POST['entry'], ENT_QUOTES);

     // check that title and summary are both not empty
     if ($title == '' || $summary == '' || $entry == '')
     {
     // if they are empty, show an error message and display the form
     $error = 'ERROR: Please fill in all required fields!';
     renderForm($title, $summary, $entry, $error);
     }
     else
     {
     // insert the new record into the database
     if ($stmt = $conn->prepare("INSERT news (title, summary, entry) VALUES (?, ?, ?)"))
     {
     $stmt->bind_param("sss", $title, $summary, $entry);
     $stmt->execute();
     $stmt->close();
     }
     // show an error if the query has an error
     else
     {
     echo "ERROR: Could not prepare SQL statement.";
     }

     // redirect the user
     header("Location: news.php");
    }

     }
     // if the form hasn't been submitted yet, show the form
     else
     {
     renderForm();
     }
     }

     // close the mysqli connection
     $conn->close();
     ?>
     </td>
     </tr>
     <?php
     include("includes/footer.inc.php");
     ?>
</code>```

答:
Make sure your entry column isn't longtext. I changed mine from longtext to mediumtext and it solved this same issue.

MySQL v5.6.33

Body:
I am working on a project and am working on a page that should do updates and regular inserts.  I found the code elsewhere and have been modifying it to work on my project.  Anyway I fixed many errors but I keep getting a memory leak at line 140.

Here is the code:

    <?php
     /*
     Allows the user to both create new records and edit existing records
     */

     // connect to the database
     include("includes/dbconnect.inc.php");

     // creates the new/edit record form
     // since this form is used multiple times in this file, I have made it a function that is easily reusable
     function renderForm($title = '', $summary ='', $entry = '', $error = '', $id = '')
     { ?>
     <?php
     include("includes/header.inc.php");
     ?>

Home

News

About Us

Sign Up

Contact Us

New/Update News Entry

Admin Panel

Staff Admin Panel

Client Panel

Login

Log Out

     <?php
     include("includes/calendar.inc.php");
     ?>

<?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?>

     <?php if ($error != '') {
echo "
" . $error
. "
";
     } ?>

     <form action="" method="post">

Edit News Item:

       <input type="hidden" name="id" value="<?php echo $id; ?>" />

ID: <?php echo $id; ?>

       Post Title:

       <input type="text" name="title" min="0" max="100" value="<?php echo $title; ?>" required />

       Post Summary:

       <input type="text" name="summary" min="0" max="100" value="<?php echo $summary; ?>" required />

       Post Entry:

       <textarea type="text" name="entry" rows="4" cols="50" min="0" max="650" value="<?php echo $entry; ?>" required /></textarea>

       <input type="submit" value="Submit" name="submit" />
     </form>

     <?php }

     /*

     EDIT RECORD

     */
     // if the 'id' variable is set in the URL, we know that we need to edit a record
     if (isset($_GET['id']))
    {
     // if the form's submit button is clicked, we need to process the form
     if (isset($_POST['submit']))
     {
     // make sure the 'id' in the URL is valid
     if (is_numeric($_POST['id']))
     {
     // get variables from the URL/form
     $id = $_POST['ID'];
     $title = htmlentities($_POST['title'], ENT_QUOTES);
     $summary = htmlentities($_POST['summary'], ENT_QUOTES);
     $entry = htmlentities($_POST['entry'], ENT_QUOTES);
     //$date=date('y.m.d h:i:s');

     // check that title and summary are both not empty
     if ($title == '' || $summary == '' || $entry == '')
     {
     // if they are empty, show an error message and display the form
     $error = 'ERROR: Please fill in all required fields!';
     renderForm($title, $summary, $entry, $error, $id);
     }
     else
     {
     // if everything is fine, update the record in the database
     if ($stmt = $conn->prepare("UPDATE news SET title = ?, summary = ?, entry - ?
     WHERE id=?"))
     {
     $stmt->bind_param("sssi", $title, $summary, $entry, $id);
     $stmt->execute();
     $stmt->close();
     }
     // show an error message if the query has an error
     else
     {
     echo "ERROR: could not prepare SQL statement.";
     }

     // redirect the user once the form is updated
     header("Location: news.php");
     }
     }
     // if the 'id' variable is not valid, show an error message
     else
     {
     echo "Error!";
     }
     }
     // if the form hasn't been submitted yet, get the info from the database and show the form
     else
     {
     // make sure the 'id' value is valid
     if (is_numeric($_GET['id']) && $_GET['id'] > 0)
     {
     // get 'id' from URL
     $id = $_GET['id'];

     // get the recod from the database
     if($stmt = $conn->prepare("SELECT ID, title, summary, entry FROM news WHERE ID=?"))
     {
     $stmt->bind_param("i", $id);
     $stmt->execute();

     $stmt->bind_result($id, $title, $summary, $entry);
     $stmt->fetch();

     // show the form
     renderForm($title, $summary, $entry, NULL, $id);

     $stmt->close();
     }
     // show an error if the query has an error
     else
     {
     echo "Error: could not prepare SQL statement";
     }
     }
     // if the 'id' value is not valid, redirect the user back to the news.php page
     else
     {
     header("Location: news.php");
     }
     }
     }

     /*

     NEW RECORD

     */
     // if the 'id' variable is not set in the URL, we must be creating a new record
     else
     {
     // if the form's submit button is clicked, we need to process the form
     if (isset($_POST['submit']))
     {
     // get the form data
     $title = htmlentities($_POST['title'], ENT_QUOTES);
     $summary = htmlentities($_POST['summary'], ENT_QUOTES);
     $entry = htmlentities($_POST['entry'], ENT_QUOTES);

     // check that title and summary are both not empty
     if ($title == '' || $summary == '' || $entry == '')
     {
     // if they are empty, show an error message and display the form
     $error = 'ERROR: Please fill in all required fields!';
     renderForm($title, $summary, $entry, $error);
     }
     else
     {
     // insert the new record into the database
     if ($stmt = $conn->prepare("INSERT news (title, summary, entry) VALUES (?, ?, ?)"))
     {
     $stmt->bind_param("sss", $title, $summary, $entry);
     $stmt->execute();
     $stmt->close();
     }
     // show an error if the query has an error
     else
     {
     echo "ERROR: Could not prepare SQL statement.";
     }

     // redirect the user
     header("Location: news.php");
    }

     }
     // if the form hasn't been submitted yet, show the form
     else
     {
     renderForm();
     }
     }

     // close the mysqli connection
     $conn->close();
     ?>

     <?php
     include("includes/footer.inc.php");
     ?>


问:
Quartus 12 Hours Clock (Synchronous)
I'm trying to build a 12 hour clock in Quartus using multiple LPM counters, with the requirement that it be run synchronously, with all lpm counters being driving by a single clock source.

I put together a BDF with two counters to test out the seconds, with one mod-10 counter handling the 'ones' digit, and another mod-6 counter handling the 'tens' digit. A carry out from the mod-10 drives a clock enable pin on the mod-6 counter. Everything work as expected in simulation.

I tried to duplicate this module to work as the minutes counter, except that I'm getting very strange results with the minutes 'ones' mod-10 counter. Whenever the seconds 'tens' counter hits 5, the minutes 'ones' starts counting on every clock pulse, until the previous counter rolls over to zero again.

Here's a picture of my BDF, along with a waveform simulation:

I'm not sure what's causing the issue, because as I understand it, the cout from the second tens should only be asserted when it rolls over to 0, and only long enough so that the minute ones increments a single time.

Just for curiosities sake, I swapped around two middle counters, to see if the issue was related to how the mod6 cout was driving the mod10, but arrive at the same results, (except the mod ten hits 9, then triggers the mod6 to count on every clk pulse until the mod10 rolls over to 0)

Any help would be appreciated, thanks.

答:
Your condition for incrementing the ones digit in the minute is effectively:

Is the ten digits of the seconds equal to 5?

Thus, you'll increment the minute every second from :50 to :59.

You need to make the state of the ones digit in the seconds a factor as well -- the simplest way to do this will be to AND the carry out with the carry in from the previous stage.

Title: Quartus 12 Hours Clock (Synchronous)


问:
DLL Method Not Working After Creating Exe Of Project
I have calling display method from dll file This works when I run my java project . But it stop working after creating of project exe file. My Code is as follow ..    </p>

```<code>static {

    try {
        Bridge.setVerbose(true);
        try {
            Bridge.init();
        } catch (IOException e) {
                  e.printStackTrace();
        }
         File dll_File = new File("helloworld.j4n.dll");
        Bridge.LoadAndRegisterAssemblyFrom(dll_File);

         helloworld.Hello.display(str)

    } catch (Exception exception) {

          exception.printStackTrace();
    }

}
</code>```

答: Have you signed the dll? Please sign the dll and then check.</p>

Body:
I have calling display method from dll file This works when I run my java project . But it stop working after creating of project exe file. My Code is as follow ..

static {

    try {
        Bridge.setVerbose(true);
        try {
            Bridge.init();
        } catch (IOException e) {
                  e.printStackTrace();
        }
         File dll_File = new File("helloworld.j4n.dll");
        Bridge.LoadAndRegisterAssemblyFrom(dll_File);

         helloworld.Hello.display(str)

    } catch (Exception exception) {

          exception.printStackTrace();
    }

}


问:
Move database from elastic pool to single database in Azure
I believe I'm getting charged the elastic pool rates for a database in Azure instead of the single database rate (something like 16 times as much). How can I change the database to single database and change the payment plan?</p>

答:
You would need to move the database out of an elastic pool.

For detailed instructions on how you can do it on Azure Portal, please see this link: https://learn.microsoft.com/en-us/azure/sql-database/sql-database-elastic-pool-manage-portal#move-a-database-out-of-an-elastic-pool.

Also, from your question it seems that you only have one database in the pool. If that's the case, after you move your database out of the pool you can simply delete that pool.


问:
Share React Native build
What options are available for sharing a react native build privately?</p>

答: You could just push the build's code to a remote repo and make sure the compiled folders aren't ignored (can't recall if it's ignored by default or not, check your .gitignore file if using GitHub). I think private repo's are only part of GitHub premium, but if you share the code anywhere then someone would be able to open it in Xcode/Android Studio and then use those SDK's to run on a simulator or device.</p>

Title: Share React Native build


问:
PHPUnit assert that an exception was thrown?
Does anyone know whether there is an assert or something like that which can test whether an exception was thrown in the code being tested?

答:
An alternative way can be the following:

```<code>$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Expected Exception Message');
</code>```

Please ensure that your test class extends \PHPUnit_Framework_TestCase.

Body:
An alternative way can be the following:

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Expected Exception Message');

Please ensure that your test class extends \PHPUnit_Framework_TestCase.

ContentLicense: CC BY-SA 4.0


问:
left join not getting expected data - returns inaccurate result
I am facing issue when trying retrieve some fields from table using left join.

Table 1 has - column reportno, slno, and desc
Table 2 has - Column report no, slno and parameters

Now i would like to retrieve all values from table1 for specific report no and and corresponding  parameters from table2. My expected result is shown below.
that means it should get all row for matching repno from table 1 and also get paramaters by matching repno and slno

/*table2 data*/
repno   slno  parameter
M100001 2     TypeRating
M100001 1     Type&Rating```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>select
qc_item_list.i_rep_no,
qc_item_list.slno,
qc_item_list.ITEM_DESC,
qc_insp.parameters
from qc_item_list
left join qc_insp
on qc_item_list.I_REP_NO = qc_insp.I_REP_NO
WHERE qc_item_list.i_rep_no = 'M100001'
ORDER BY qc_item_list.slno</code>```

答:
You should be joining on the slno column, not the i_rep_no column:

```<code>SELECT t1.i_rep_no,
       t1.slno,
       t1.ITEM_DESC,
       COALESCE(t2.parameters, 'NA') AS parameter
FROM qc_item_list t1
LEFT JOIN qc_insp t2
    ON t1.slno     = t2.slno AND
       t1.i_rep_no = t2.i_rep_no
WHERE t1.i_rep_no = 'M100001'
ORDER BY t1.slno
</code>```

If you're never seen/working with COALESCE() before, the way it works is to use the first parameter if it be not NULL, and to use the second parameter as a backup should the first parameter be NULL.  In this case, for those records in your first table which did not have a matching slno in the second table, the parameter would be displayed as NA for "not available."

Body:
I am facing issue when trying retrieve some fields from table using left join.

Table 1 has - column reportno, slno, and desc
Table 2 has - Column report no, slno and parameters

Now i would like to retrieve all values from table1 for specific report no and and corresponding  parameters from table2. My expected result is shown below.
that means it should get all row for matching repno from table 1 and also get paramaters by matching repno and slno

/*table2 data*/
repno   slno  parameter
M100001 2     TypeRating
M100001 1     Type&Rating

select
qc_item_list.i_rep_no,
qc_item_list.slno,
qc_item_list.ITEM_DESC,
qc_insp.parameters
from qc_item_list
left join qc_insp
on qc_item_list.I_REP_NO = qc_insp.I_REP_NO
WHERE qc_item_list.i_rep_no = 'M100001'
ORDER BY qc_item_list.slno

Body:
You should be joining on the slno column, not the i_rep_no column:

SELECT t1.i_rep_no,
       t1.slno,
       t1.ITEM_DESC,
       COALESCE(t2.parameters, 'NA') AS parameter
FROM qc_item_list t1
LEFT JOIN qc_insp t2
    ON t1.slno     = t2.slno AND
       t1.i_rep_no = t2.i_rep_no
WHERE t1.i_rep_no = 'M100001'
ORDER BY t1.slno

If you're never seen/working with COALESCE() before, the way it works is to use the first parameter if it be not NULL, and to use the second parameter as a backup should the first parameter be NULL.  In this case, for those records in your first table which did not have a matching slno in the second table, the parameter would be displayed as NA for "not available."


问:
How to add dividers in Bottom Navigation View
I'm trying to add divider in menu items of BottomNavigationView

All items are showing horizontally in the bottom but I'm not able to add dividers into it.

Bottom Navigation View xml:

```<code><android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:focusable="false"
        app:itemBackground="@color/colorPrimaryDark"
        app:itemIconTint="@color/bottom_navigation_selector"
        app:itemTextColor="@color/bottom_navigation_selector"
        app:layout_anchor="@id/container"
        app:layout_anchorGravity="bottom"
        app:menu="@menu/bottom_nav_items" />
</code>```

And bottom_nav_items.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/menu_family"
    android:checked="false"
    android:icon="@drawable/family"
    android:title="@string/family" />
<item
    android:id="@+id/menu_me"
    android:checked="false"
    android:icon="@drawable/me"
    android:title="@string/me" />

<item
    android:id="@+id/menu_blank"
    android:checkable="false"
    android:enabled="false"
    android:title="" />
<item
    android:id="@+id/menu_event"
    android:checked="false"
    android:icon="@drawable/event"
    android:title="@string/event" />
<item
    android:id="@+id/menu_more"
    android:checked="false"
    android:icon="@drawable/more"
    android:title="@string/more" />
</code>```

Thanks for your support.

答:
Try this way...</p>

```<code>BottomNavigationView mBottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
NavigationMenuView navMenuView = (NavigationMenuView) mBottomNavigationView.getChildAt(0);
navMenuView.addItemDecoration(new DividerItemDecoration(MainActivity.this,DividerItemDecoration.VERTICAL));
</code>```

Body:
I'm trying to add divider in menu items of BottomNavigationView

All items are showing horizontally in the bottom but I'm not able to add dividers into it.

Bottom Navigation View xml:

<android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:focusable="false"
        app:itemBackground="@color/colorPrimaryDark"
        app:itemIconTint="@color/bottom_navigation_selector"
        app:itemTextColor="@color/bottom_navigation_selector"
        app:layout_anchor="@id/container"
        app:layout_anchorGravity="bottom"
        app:menu="@menu/bottom_nav_items" />

And bottom_nav_items.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/menu_family"
    android:checked="false"
    android:icon="@drawable/family"
    android:title="@string/family" />
<item
    android:id="@+id/menu_me"
    android:checked="false"
    android:icon="@drawable/me"
    android:title="@string/me" />

<item
    android:id="@+id/menu_blank"
    android:checkable="false"
    android:enabled="false"
    android:title="" />
<item
    android:id="@+id/menu_event"
    android:checked="false"
    android:icon="@drawable/event"
    android:title="@string/event" />
<item
    android:id="@+id/menu_more"
    android:checked="false"
    android:icon="@drawable/more"
    android:title="@string/more" />

Thanks for your support.

Body:
Try this way...

BottomNavigationView mBottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
NavigationMenuView navMenuView = (NavigationMenuView) mBottomNavigationView.getChildAt(0);
navMenuView.addItemDecoration(new DividerItemDecoration(MainActivity.this,DividerItemDecoration.VERTICAL));


问:
UISearchBar button
I was working on the UISearchBar in Xcode and while running the app, this button appeared in the search text field and it's still there since.

Did anybody face this problem before? How to delete this button.

答: Unselect the Shows Search Results Button attribute in Attributes Inspector.

Title: UISearchBar button


问:
NodeJS Express JS - MongoError: failed to connect to server
What does this error mean?

```<code>$ pm2 logs
[TAILING] Tailing last 15 lines for [all] processes (change the value with --lines option)
/home/tealou/.pm2/pm2.log last 15 lines:
PM2        | 2017-03-29 07:25:45: App [www] with id [0] and pid [29444], exited with code [1] via signal [SIGINT]
PM2        | 2017-03-29 07:25:45: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:25:45: App name:www id:0 online
PM2        | 2017-03-29 07:25:46: App [www] with id [0] and pid [29460], exited with code [1] via signal [SIGINT]
PM2        | 2017-03-29 07:25:46: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:25:46: App name:www id:0 online
PM2        | 2017-03-29 07:25:47: App [www] with id [0] and pid [29477], exited with code [1] via signal [SIGINT]
PM2        | 2017-03-29 07:25:47: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:25:47: App name:www id:0 online
PM2        | 2017-03-29 07:25:48: App [www] with id [0] and pid [29487], exited with code [1] via signal [SIGINT]
PM2        | 2017-03-29 07:25:48: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:25:48: App name:www id:0 online
PM2        | 2017-03-29 07:25:49: App [www] with id [0] and pid [29497], exited with code [1] via signal [SIGINT]
PM2        | 2017-03-29 07:25:49: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:25:49: App name:www id:0 online

/home/tealou/.pm2/logs/www-out-0.log last 15 lines:
0|www      | POST /input/XnCuYLP72jGwMt25bPVuuM81uq2 200 233.304 ms - 9
0|www      | Successfully connected to mongodb
0|www      | POST /input/2psLUE6VB7tEdC0sACCl8Yn1oC6 200 133.400 ms - 9
0|www      | Successfully connected to mongodb
0|www      | POST /input/2IcNjH69dLyMhrCSi0voaM5OLW8 200 87.776 ms - 9
0|www      | Successfully connected to mongodb
0|www      | POST /input/lJOVksaP8LMhgOl8XOCofV6ZeZZ 200 117.275 ms - 9
0|www      | POST /input/YbJriPtV1FZWUDwgZq46zFqL7BC 200 147.066 ms - 9
0|www      | Successfully connected to mongodb
0|www      | POST /input/lb8BbtOobixWcfI4dItIaS0U2KZ 200 196.825 ms - 9
0|www      | POST /input/97PWLQquQIFxTgpSLZa4rgvXSLR 200 42.662 ms - 9
0|www      | POST /input/G4ZrX1Wz88Kx1gcDBN8bw4exi3M 200 127.855 ms - 9
0|www      | Successfully connected to mongodb
0|www      | POST /input/D2wBHNc4BX19tDkGqXfD8ClY6E0 200 126.571 ms - 9
0|www      | Successfully connected to mongodb

/home/tealou/.pm2/logs/www-error-0.log last 15 lines:
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)

[STREAMING] Now streaming realtime logs for [all] processes
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)
PM2        | App [www] with id [0] and pid [29513], exited with code [1] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:www id:0
PM2        | App name:www id:0 online
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)
PM2        | App [www] with id [0] and pid [29527], exited with code [1] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:www id:0
PM2        | App name:www id:0 online
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)
PM2        | App [www] with id [0] and pid [29544], exited with code [1] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:www id:0
PM2        | App name:www id:0 online
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)
PM2        | App [www] with id [0] and pid [29554], exited with code [1] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:www id:0
PM2        | App name:www id:0 online
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)
PM2        | App [www] with id [0] and pid [29564], exited with code [1] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:www id:0
PM2        | App name:www id:0 online
</code>```

It is fine on my localhost, but it breaks on my production server.

Any ideas?

EDIT:

```<code>$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/root        23G   23G   43M 100% /
devtmpfs        7.9G     0  7.9G   0% /dev
tmpfs           7.EDIT:9G     0  7.9G   0% /dev/shm
tmpfs           7.9G  1.5M  7.9G   1% /run
tmpfs           7.9G     0  7.9G   0% /sys/fs/cgroup
tmpfs           1.6G     0  1.6G   0% /run/user/1002
</code>```

EDIT 2:

```<code>$ mongo
MongoDB shell version: 3.2.6
connecting to: test
2017-03-29T07:21:59.231+0100 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
2017-03-29T07:21:59.237+0100 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:229:14
@(connect):1:6

exception: connect failed
</code>```

Edit 3:

```<code>$ pm2 logs
[TAILING] Tailing last 15 lines for [all] processes (change the value with --lines option)
/home/tealou/.pm2/pm2.log last 15 lines:
PM2        | 2017-03-29 07:29:48: Time                 : Wed Mar 29 2017 07:29:48 GMT+0100 (BST)
PM2        | 2017-03-29 07:29:48: PM2 version          : 2.4.2
PM2        | 2017-03-29 07:29:48: Node.js version      : 6.2.2
PM2        | 2017-03-29 07:29:48: Current arch         : x64
PM2        | 2017-03-29 07:29:48: PM2 home             : /home/citizensense/.pm2
PM2        | 2017-03-29 07:29:48: PM2 PID file         : /home/tealou/.pm2/pm2.pid
PM2        | 2017-03-29 07:29:48: RPC socket file      : /home/tealou/.pm2/rpc.sock
PM2        | 2017-03-29 07:29:48: BUS socket file      : /home/tealou/.pm2/pub.sock
PM2        | 2017-03-29 07:29:48: Application log path : /home/tealou/.pm2/logs
PM2        | 2017-03-29 07:29:48: Process dump file    : /home/tealou/.pm2/dump.pm2
PM2        | 2017-03-29 07:29:48: Concurrent actions   : 2
PM2        | 2017-03-29 07:29:48: SIGTERM timeout      : 1600
PM2        | 2017-03-29 07:29:48: ===============================================================================
PM2        | 2017-03-29 07:29:49: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:29:49: App name:www id:0 online

/home/tealou/.pm2/logs/www-error-0.log last 15 lines:
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)
</code>```

EDIT 4:

```<code>$ pm2 logs
[PM2] Spawning PM2 daemon with pm2_home=/home/tealou/.pm2
</code>```

What is this!??

答: Just judging by the port number (27017), which is the default port for MongoDB, it seems as if you are not able to connect to MongoDB on your server. Try installing it and make sure it's running on port 27017.</p>

Body:
What does this error mean?

$ pm2 logs
[TAILING] Tailing last 15 lines for [all] processes (change the value with --lines option)
/home/tealou/.pm2/pm2.log last 15 lines:
PM2        | 2017-03-29 07:25:45: App [www] with id [0] and pid [29444], exited with code [1] via signal [SIGINT]
PM2        | 2017-03-29 07:25:45: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:25:45: App name:www id:0 online
PM2        | 2017-03-29 07:25:46: App [www] with id [0] and pid [29460], exited with code [1] via signal [SIGINT]
PM2        | 2017-03-29 07:25:46: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:25:46: App name:www id:0 online
PM2        | 2017-03-29 07:25:47: App [www] with id [0] and pid [29477], exited with code [1] via signal [SIGINT]
PM2        | 2017-03-29 07:25:47: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:25:47: App name:www id:0 online
PM2        | 2017-03-29 07:25:48: App [www] with id [0] and pid [29487], exited with code [1] via signal [SIGINT]
PM2        | 2017-03-29 07:25:48: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:25:48: App name:www id:0 online
PM2        | 2017-03-29 07:25:49: App [www] with id [0] and pid [29497], exited with code [1] via signal [SIGINT]
PM2        | 2017-03-29 07:25:49: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:25:49: App name:www id:0 online

/home/tealou/.pm2/logs/www-out-0.log last 15 lines:
0|www      | POST /input/XnCuYLP72jGwMt25bPVuuM81uq2 200 233.304 ms - 9
0|www      | Successfully connected to mongodb
0|www      | POST /input/2psLUE6VB7tEdC0sACCl8Yn1oC6 200 133.400 ms - 9
0|www      | Successfully connected to mongodb
0|www      | POST /input/2IcNjH69dLyMhrCSi0voaM5OLW8 200 87.776 ms - 9
0|www      | Successfully connected to mongodb
0|www      | POST /input/lJOVksaP8LMhgOl8XOCofV6ZeZZ 200 117.275 ms - 9
0|www      | POST /input/YbJriPtV1FZWUDwgZq46zFqL7BC 200 147.066 ms - 9
0|www      | Successfully connected to mongodb
0|www      | POST /input/lb8BbtOobixWcfI4dItIaS0U2KZ 200 196.825 ms - 9
0|www      | POST /input/97PWLQquQIFxTgpSLZa4rgvXSLR 200 42.662 ms - 9
0|www      | POST /input/G4ZrX1Wz88Kx1gcDBN8bw4exi3M 200 127.855 ms - 9
0|www      | Successfully connected to mongodb
0|www      | POST /input/D2wBHNc4BX19tDkGqXfD8ClY6E0 200 126.571 ms - 9
0|www      | Successfully connected to mongodb

/home/tealou/.pm2/logs/www-error-0.log last 15 lines:
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)

[STREAMING] Now streaming realtime logs for [all] processes
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)
PM2        | App [www] with id [0] and pid [29513], exited with code [1] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:www id:0
PM2        | App name:www id:0 online
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)
PM2        | App [www] with id [0] and pid [29527], exited with code [1] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:www id:0
PM2        | App name:www id:0 online
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)
PM2        | App [www] with id [0] and pid [29544], exited with code [1] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:www id:0
PM2        | App name:www id:0 online
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)
PM2        | App [www] with id [0] and pid [29554], exited with code [1] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:www id:0
PM2        | App name:www id:0 online
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)
PM2        | App [www] with id [0] and pid [29564], exited with code [1] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:www id:0
PM2        | App name:www id:0 online

It is fine on my localhost, but it breaks on my production server.

Any ideas?

EDIT:

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/root        23G   23G   43M 100% /
devtmpfs        7.9G     0  7.9G   0% /dev
tmpfs           7.EDIT:9G     0  7.9G   0% /dev/shm
tmpfs           7.9G  1.5M  7.9G   1% /run
tmpfs           7.9G     0  7.9G   0% /sys/fs/cgroup
tmpfs           1.6G     0  1.6G   0% /run/user/1002

EDIT 2:

$ mongo
MongoDB shell version: 3.2.6
connecting to: test
2017-03-29T07:21:59.231+0100 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
2017-03-29T07:21:59.237+0100 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:229:14
@(connect):1:6

exception: connect failed

Edit 3:

$ pm2 logs
[TAILING] Tailing last 15 lines for [all] processes (change the value with --lines option)
/home/tealou/.pm2/pm2.log last 15 lines:
PM2        | 2017-03-29 07:29:48: Time                 : Wed Mar 29 2017 07:29:48 GMT+0100 (BST)
PM2        | 2017-03-29 07:29:48: PM2 version          : 2.4.2
PM2        | 2017-03-29 07:29:48: Node.js version      : 6.2.2
PM2        | 2017-03-29 07:29:48: Current arch         : x64
PM2        | 2017-03-29 07:29:48: PM2 home             : /home/citizensense/.pm2
PM2        | 2017-03-29 07:29:48: PM2 PID file         : /home/tealou/.pm2/pm2.pid
PM2        | 2017-03-29 07:29:48: RPC socket file      : /home/tealou/.pm2/rpc.sock
PM2        | 2017-03-29 07:29:48: BUS socket file      : /home/tealou/.pm2/pub.sock
PM2        | 2017-03-29 07:29:48: Application log path : /home/tealou/.pm2/logs
PM2        | 2017-03-29 07:29:48: Process dump file    : /home/tealou/.pm2/dump.pm2
PM2        | 2017-03-29 07:29:48: Concurrent actions   : 2
PM2        | 2017-03-29 07:29:48: SIGTERM timeout      : 1600
PM2        | 2017-03-29 07:29:48: ===============================================================================
PM2        | 2017-03-29 07:29:49: Starting execution sequence in -fork mode- for app name:www id:0
PM2        | 2017-03-29 07:29:49: App name:www id:0 online

/home/tealou/.pm2/logs/www-error-0.log last 15 lines:
0|www      | MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/topologies/server.js:327:35)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at emit (events.js:188:7)
0|www      |     at .<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/pool.js:274:12)
0|www      |     at g (events.js:286:16)
0|www      |     at emitTwo (events.js:106:13)
0|www      |     at emit (events.js:191:7)
0|www      |     at Socket.<anonymous> (/usr/local/chroot/project-1/node_modules/mongodb-core/lib/connection/connection.js:177:49)
0|www      |     at Socket.g (events.js:286:16)
0|www      |     at emitOne (events.js:96:13)
0|www      |     at Socket.emit (events.js:188:7)
0|www      |     at emitErrorNT (net.js:1272:8)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:74:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:122:9)

EDIT 4:

$ pm2 logs
[PM2] Spawning PM2 daemon with pm2_home=/home/tealou/.pm2

What is this!??


问:
How to parse TCP packet payload
I'm using pcap to capture TCP packets for which I would like to parse the payload. My strategy is as follows:

Get the ethernet header and check if it has type ETHERTYPE_IP (IP packet)

Check if the IP packet has protocol IPPROTO_TCP (TCP packet)

Check for payload size > 0 (size = ntohs(ip_header->total_length - ip->header_length*4 - sizeof(struct tcp_header)).

parse payload (grab the host url)

I haven't begun parsing the payload yet because I am getting discrepancies. Below is a printout of the payload of 10 captured TCP packets, using filter "host = www.google.com".

packet number: 3 : TCP Packet: Source Port: 80 Dest Port: 58723
No Data in packet

packet number: 4 : TCP Packet: Source Port: 58723 Dest Port: 80
No Data in packet

packet number: 5 : TCP Packet: Source Port: 58723 Dest Port: 80 Payload :
GET / HTTP/1.1
Host: www.google.com
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-us) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4
Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,/;q=0.5
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Cookie: THICNT=25; SID=DQAAAKIAAAB2ktMrEftADifGm05WkZmlHQsiy1Z2v-
Connection: keep-alive

packet number: 6 : TCP Packet: Source Port: 80 Dest Port: 58723
No Data in packet

packet number: 7 : TCP Packet: Source Port: 80 Dest Port: 58723 Payload:
\272نu\243\255\375\375}\336H\221\227\206\312~\322\317N\236\255A\343#\226\370֤\245[\327`\306ըnE\263\204\313\356\3268 )p\344\301_Y\255\267\240\222x\364

packet number: 8 : TCP Packet: Source Port: 58723 Dest Port: 80
No Data in packet

packet number: 9 : TCP Packet: Source Port: 80 Dest Port: 58723 Payload:
HTTP/1.1 200 OK
Date: Mon, 29 Nov 2010 10:11:36 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=UTF-8
Content-Encoding: gzip
Server: gws
Content-Length: 8806
X-XSS-Protection: 1; mode=block
\213

Why is there a discrepancy in the payloads and the ports? Ideally I would like to only parse packets like packet 5. How do I ignore packets like 7 and 9?

答: Like the IP header, the TCP header is variable-length as well.  You are not taking that into account.  Rather than blindly subtracting sizeof(struct tcp_header)) from the total packet size, you need to locate the TCP header within the IP data, then use its length field (which needs to be multiplied by 4, just like the IP header length field does) to know where the actual data payload is located.

ContentLicense: CC BY-SA 2.5

Title: How to parse TCP packet payload


问:
Can I use one Bootstrap column width (not equaling 12) in separate rows?
I have been trying to create two separate Bootstrap rows, each with a width of 8.

Unfortunately, both rows overlap each other.  I've tried various approaches to solving the problem but nothing is working.

I'm curious if this is a problem with the way I'm using column widths.

Sorry for such a simple question - I'm fairly new to all of this.

 HTML

```<code><div class="container">

  <!-- HEADLINE -->

<div class="row">
    <div class="short-description col-xs-8">

      <div class="listing-headline">
          {{ adContent?.headline }}
      </div>

      <div class="location-info">
          {{ location?.city }}, {{ location?.state }}, {{ location?.country }}
      </div>

  <hr>
    </div>

</div>

<!-- DETAILS OVERVIEW -->
<div class="row">
      <div class="details-overview col-xs-8" *ngFor="let info of unitContent">

          <div class="rental-type">
              {{ info?.unitContent.propertyType }}
          </div>

          <div class="guest-allowance">

          </div>

          <div class="space-type">

          </div>

          <div class="bed-number">

          </div>

          <hr>
        </div>
</div>

</div>
</code>```

 CSS

```<code>.short-description {
  height: 80px;
  padding: auto;
  margin-top: 20px;
}

.listing-headline {
  font-style: bold;
  font-size: 3em;
  line-height: 120%;
}

.location-info {
  margin-top: 15px;
  font-weight: 300;
  font-size: 1.4em;
}

.details-overview {
}
</code>```

答:
Nothings wrong with your code. I think overlapping of  both rows  with each other is because of some codes missing with bootstrap stylesheets (either of bootstrap.css or bootstrap.min.css) you are using. It's better to get a new copy of it.</p>

```<code><div class="container">
    <div class="row">
        <div class="col-xs-8">
            <div class="listing-headline">
                HEADLINE 1
            </div>
            <!--/col-xs-8-->
            <div class="location-info">
                CITY, STATE, COUNTRY
            </div>
            <!--/col-xs-8-->
            <hr>
        </div>
        <!--/col-xs-8-->
    </div>
    <!--/row-->

    <div class="row">
        <div class="col-xs-8">
            <div class="rental-type">
                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </div>
            <!--/rental-type-->
            <div class="guest-allowance">
            </div>
            <!--/guest-allowance-->

            <div class="space-type">
            </div>
            <!--/space-type-->

            <div class="bed-number">
            </div>
            <!--/bed-number-->
            <hr>
        </div>
        <!--/col-xs-8-->
    </div>
    <!--/row-->
</div>
<!--/container-->

<style type="text/css">
    .short-description {
        height: 80px;
        padding: auto;
        margin-top: 20px;
    }
    .listing-headline {
        font-style: bold;
        font-size: 3em;
        line-height: 120%;
    }
    .location-info {
        margin-top: 5px;
        font-weight: 300;
        font-size: 1.4em;
    }
</style>
</code>```

Body:
I have been trying to create two separate Bootstrap rows, each with a width of 8.

Unfortunately, both rows overlap each other.  I've tried various approaches to solving the problem but nothing is working.

I'm curious if this is a problem with the way I'm using column widths.

Sorry for such a simple question - I'm fairly new to all of this.

 HTML

          {{ adContent?.headline }}

          {{ location?.city }}, {{ location?.state }}, {{ location?.country }}

              {{ info?.unitContent.propertyType }}

 CSS

.short-description {
  height: 80px;
  padding: auto;
  margin-top: 20px;
}

.listing-headline {
  font-style: bold;
  font-size: 3em;
  line-height: 120%;
}

.location-info {
  margin-top: 15px;
  font-weight: 300;
  font-size: 1.4em;
}

.details-overview {
}

Body:
Nothings wrong with your code. I think overlapping of  both rows  with each other is because of some codes missing with bootstrap stylesheets (either of bootstrap.css or bootstrap.min.css) you are using. It's better to get a new copy of it.

<div class="container">
    <div class="row">
        <div class="col-xs-8">
            <div class="listing-headline">
                HEADLINE 1
            </div>
            <!--/col-xs-8-->
            <div class="location-info">
                CITY, STATE, COUNTRY
            </div>
            <!--/col-xs-8-->
            <hr>
        </div>
        <!--/col-xs-8-->
    </div>
    <!--/row-->

    <div class="row">
        <div class="col-xs-8">
            <div class="rental-type">
                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </div>
            <!--/rental-type-->
            <div class="guest-allowance">
            </div>
            <!--/guest-allowance-->

            <div class="space-type">
            </div>
            <!--/space-type-->

            <div class="bed-number">
            </div>
            <!--/bed-number-->
            <hr>
        </div>
        <!--/col-xs-8-->
    </div>
    <!--/row-->
</div>
<!--/container-->

<style type="text/css">
    .short-description {
        height: 80px;
        padding: auto;
        margin-top: 20px;
    }
    .listing-headline {
        font-style: bold;
        font-size: 3em;
        line-height: 120%;
    }
    .location-info {
        margin-top: 5px;
        font-weight: 300;
        font-size: 1.4em;
    }
</style>


问:
Apache - Proxy external files to download
Consider this:

we have an external server for files that can be downloaded

our website (plone based) is the interface for downloading them and we try to hide the direct links as much as possible

jquery.fileDownload plugin needs a cookie set on file on download

I'm trying to set our Apache configuration to replace links like this:

original: data-files-example.com/folder/subfolder/file.zip

replaced: our-website-example.com/_downloads/folder/subfolder/file.zip

So, the missing part in my case is: how to set Apache to work like this?

I'm trying:

```<code>NameVirtualHost *:80
<VirtualHost :80>
    ServerAdmin email@our-website-example.com
    ServerName our-website-example.com

    RewriteEngine On
    RewriteRule "^/_downloads(.)$" "https://data-files-example.com/$1" [P]

    RewriteCond %{REQUEST_METHOD} ^(PUT|DELETE|PROPFIND|OPTIONS|TRACE|PROPFIND|PROPPATCH|MKCOL|COPY|MOVE|LOCK|UNLOCK)$

    RewriteRule .* - [F,L]
    RewriteRule ^/(.*) http://127.0.0.1:/VirtualHostBase/http/data-files-example.com:80/my_plone_website/VirtualHostRoot/$1 [L,P]

</VirtualHost>
</code>```

I receive 503 Service Unavailable.

How to fix this?

答:
Try a reverse proxy. Just make sure that mod_proxy and mod_proxy_http are enabled in your Apache configuration and that your proxy rule is set before the VirtualHostBase rule for Plone, if the pattern is the root slash. </p>

```<code>ProxyPass         /_downloads     http://data-files-example.com
ProxyPassReverse  /_downloads     http://data-files-example.com
</code>```

<p>When proxying to a https backend you'll also need mod_ssl installed and the directive SSLProxyEngine On.  </p>

```<code>SSLProxyEngine On
ProxyPass         /_downloads     https://data-files-example.com
ProxyPassReverse  /_downloads     https://data-files-example.com
</code>```

Body:
Consider this:

we have an external server for files that can be downloaded

our website (plone based) is the interface for downloading them and we try to hide the direct links as much as possible

jquery.fileDownload plugin needs a cookie set on file on download

I'm trying to set our Apache configuration to replace links like this:

original: data-files-example.com/folder/subfolder/file.zip

replaced: our-website-example.com/_downloads/folder/subfolder/file.zip

So, the missing part in my case is: how to set Apache to work like this?

I'm trying:

NameVirtualHost *:80
<VirtualHost :80>
    ServerAdmin email@our-website-example.com
    ServerName our-website-example.com

    RewriteEngine On
    RewriteRule "^/_downloads(.)$" "https://data-files-example.com/$1" [P]

    RewriteCond %{REQUEST_METHOD} ^(PUT|DELETE|PROPFIND|OPTIONS|TRACE|PROPFIND|PROPPATCH|MKCOL|COPY|MOVE|LOCK|UNLOCK)$

    RewriteRule .* - [F,L]
    RewriteRule ^/(.*) http://127.0.0.1:/VirtualHostBase/http/data-files-example.com:80/my_plone_website/VirtualHostRoot/$1 [L,P]

</VirtualHost>

I receive 503 Service Unavailable.

How to fix this?

Body:
Try a reverse proxy. Just make sure that mod_proxy and mod_proxy_http are enabled in your Apache configuration and that your proxy rule is set before the VirtualHostBase rule for Plone, if the pattern is the root slash.

ProxyPass         /_downloads     http://data-files-example.com
ProxyPassReverse  /_downloads     http://data-files-example.com

When proxying to a https backend you'll also need mod_ssl installed and the directive SSLProxyEngine On.

SSLProxyEngine On
ProxyPass         /_downloads     https://data-files-example.com
ProxyPassReverse  /_downloads     https://data-files-example.com


问:
"Clickable" textblock?
I have a WP7 app where I would like to have a "clickable" TextBlock area, that when a user clicks on the TextBlock, it puts it into edit mode (a different control).
This would add another explicit step for a user before editing text.

There is no click event for the TextBlock (which doesn't surprise me).

Is there any way to do this?  Wrapped in another control, or something similar?

答:
You can associate a click event using gesture support.

edit: by doing it this way your behaviour will be consistant with a Click (tap) with respect to the user moving their finger across the display during the operation. Click will not fire under mousedown, move off control, mouseup. Tap gesture works the same. Not all users know they can abort a click by moving their mouse/finger, but some do and you'll get caught out on this if not handling it correctly. MouseLeftButtonUp handling works the same way, but I wouldn't recommend relying on this as it's not by design and there may be unanticipated changes or conflicts with other controls.

Title: "Clickable" textblock?


问:
Map some input value to a custom type
Imagine I have some type MyType, that is a union, like:

```<code>MyType.StringValue("a string")
MyType.LongValue(100L)
MyType.DoubleValue(200.09)
</code>```

I need to map values of some type T to MyType.

What I want to avoid is a very long pattern match like:

```<code>def convert(x: Any) = x match {
  case x: Long => MyType.LongValue(x)
  ...
  ...
}
</code>```

What options are available to me? I have heard/seen some stuff about traits and implicits. I'm curious if anyone has dealt with a problem like this, and if so, what worked well.

答:
DISCLAIMER: This answer deals with type T (known at the compilation stage) unlike Any in your convert. Otherwise you would have to use reflection in order to call appropriate constructor and it wouldn't return you an actual type. Using Java reflection it's something like (pseudo-code):

```<code> def convert(x: Any): MyType = {
   val clazz = x.getClass.getName
   val caseClassCompanionName = ...
   Class.forName(caseClassCompanionName).getMethod("apply").invoke(null, x).asInstanceOf[MyType]
 }
</code>```

or you can use ClassTag/TypeTag from Scala-reflection or write a macro that will generate appropriate convert() code for you.

Anyways, reflection-based approach doesn't bring much type-safety (and might easily break after Scala updates), so my answer is intended to show how to wrap a known type without using pattern-matching:

I need to map values of some type T to MyType.

Yes you can use implicit classes in many ways, one approach:

```<code>trait MyType //represents your union (sum) of types

case class StringValue(s: String) extends MyType
implicit class ToStringValue(s: String){
   def toMyType = StringValue(s)
}

case class IntValue(i: Int) extends MyType
implicit class ToIntValue(i: Int){
   def toMyType = IntValue(i)
}

scala> "aaa".toMyType
res0: StringValue = StringValue(aaa)

scala> 1.toMyType
res1: IntValue = IntValue(1)
</code>```

You could notice that it requires even more code than pattern matching, BUT it returns you an actual type instead general MyType unlike your convert.

Shorter way to do that is overloading:

```<code>object Converter{
   def toMyType(s: String) = StringValue(s)
   def toMyType(i: Int) = IntValue(i)
}
scala> Converter.toMyType("aaa")
res2: StringValue = StringValue(aaa)

scala> Converter.toMyType(1)
res3: IntValue = IntValue(1)
</code>```

If you just wanna wrap any possible type, the easiest way is

```<code>case class MyValue[T](value: T) //represents your union (sum) of types
</code>```

Then you can define type-specific operations over your MyValue in a type-class style

```<code>implicit class RichMyInt(myValue: MyValue[Int]){
  def inc = myValue.copy(value = myValue.value + 1)
}

implicit class RichMyString(myValue: MyValue[String]){
  def inc = myValue.copy(value = myValue.value + " ")
}

scala> MyValue(5).inc
res4: MyValue[Int] = MyValue(6)

scala> MyValue("5").inc
res5: MyValue[String] = MyValue(5 )

scala> MyValue(1.0).inc
<console>:18: error: value inc is not a member of MyValue[Double]
   MyValue(1.0).inc
                ^
scala> MyValue(1.0) //unlike previous solutions, it allows any type to be wrapped
res7: MyValue[Double] = MyValue(1.0)
</code>```

P.S. You can restrict types for MyValue[T] constructor using overloading (or even evidences):

```<code>trait MyValue[T]{
  def value: T
}
object Factory{
  private case class MyValueImpl[T] (value: T) extends MyValue[T]
  def create(t: String): MyValue[String] = MyValueImpl(t)
  def create(t: Int): MyValue[Int] = MyValueImpl(t)
}

scala> Factory.create(1)
res1: MyValue[Int] = MyValueImpl(1)

scala> Factory.create("a")
res2: MyValue[String] = MyValueImpl(a)

scala> Factory.create(1.0)
<console>:13: error: overloaded method value create with alternatives:
  (t: Int)MyValue[Int] <and>
  (t: String)MyValue[String]
 cannot be applied to (Double)
       Factory.create(1.0)
               ^
</code>```

You could also try private constructor's , like class MyValue[T] private(value: T) (instead of private case class) but for case classes apply escapes that restriction (at least in my REPL)

Of course you can do case class MyValue[T <: AnyVal](value: T) if you just want a wrapper around atomic types. You can even increase performance of your wrapper by doing case class MyValue[T](value: T) extends AnyVal which produces a value class, so no addtional reference is created when you do MyValue(1) - in byte-code it's just going to be the same Int.

Title: Map some input value to a custom type

Body:
Imagine I have some type MyType, that is a union, like:

MyType.StringValue("a string")
MyType.LongValue(100L)
MyType.DoubleValue(200.09)

I need to map values of some type T to MyType.

What I want to avoid is a very long pattern match like:

def convert(x: Any) = x match {
  case x: Long => MyType.LongValue(x)
  ...
  ...
}

What options are available to me? I have heard/seen some stuff about traits and implicits. I'm curious if anyone has dealt with a problem like this, and if so, what worked well.

Body:
DISCLAIMER: This answer deals with type T (known at the compilation stage) unlike Any in your convert. Otherwise you would have to use reflection in order to call appropriate constructor and it wouldn't return you an actual type. Using Java reflection it's something like (pseudo-code):

 def convert(x: Any): MyType = {
   val clazz = x.getClass.getName
   val caseClassCompanionName = ...
   Class.forName(caseClassCompanionName).getMethod("apply").invoke(null, x).asInstanceOf[MyType]
 }

or you can use ClassTag/TypeTag from Scala-reflection or write a macro that will generate appropriate convert() code for you.

Anyways, reflection-based approach doesn't bring much type-safety (and might easily break after Scala updates), so my answer is intended to show how to wrap a known type without using pattern-matching:

I need to map values of some type T to MyType.

Yes you can use implicit classes in many ways, one approach:

trait MyType //represents your union (sum) of types

case class StringValue(s: String) extends MyType
implicit class ToStringValue(s: String){
   def toMyType = StringValue(s)
}

case class IntValue(i: Int) extends MyType
implicit class ToIntValue(i: Int){
   def toMyType = IntValue(i)
}

scala> "aaa".toMyType
res0: StringValue = StringValue(aaa)

scala> 1.toMyType
res1: IntValue = IntValue(1)

You could notice that it requires even more code than pattern matching, BUT it returns you an actual type instead general MyType unlike your convert.

Shorter way to do that is overloading:

object Converter{
   def toMyType(s: String) = StringValue(s)
   def toMyType(i: Int) = IntValue(i)
}
scala> Converter.toMyType("aaa")
res2: StringValue = StringValue(aaa)

scala> Converter.toMyType(1)
res3: IntValue = IntValue(1)

If you just wanna wrap any possible type, the easiest way is

case class MyValue[T](value: T) //represents your union (sum) of types

Then you can define type-specific operations over your MyValue in a type-class style

implicit class RichMyInt(myValue: MyValue[Int]){
  def inc = myValue.copy(value = myValue.value + 1)
}

implicit class RichMyString(myValue: MyValue[String]){
  def inc = myValue.copy(value = myValue.value + " ")
}

scala> MyValue(5).inc
res4: MyValue[Int] = MyValue(6)

scala> MyValue("5").inc
res5: MyValue[String] = MyValue(5 )

scala> MyValue(1.0).inc
<console>:18: error: value inc is not a member of MyValue[Double]
   MyValue(1.0).inc
                ^
scala> MyValue(1.0) //unlike previous solutions, it allows any type to be wrapped
res7: MyValue[Double] = MyValue(1.0)

P.S. You can restrict types for MyValue[T] constructor using overloading (or even evidences):

trait MyValue[T]{
  def value: T
}
object Factory{
  private case class MyValueImpl[T] (value: T) extends MyValue[T]
  def create(t: String): MyValue[String] = MyValueImpl(t)
  def create(t: Int): MyValue[Int] = MyValueImpl(t)
}

scala> Factory.create(1)
res1: MyValue[Int] = MyValueImpl(1)

scala> Factory.create("a")
res2: MyValue[String] = MyValueImpl(a)

scala> Factory.create(1.0)
<console>:13: error: overloaded method value create with alternatives:
  (t: Int)MyValue[Int] <and>
  (t: String)MyValue[String]
 cannot be applied to (Double)
       Factory.create(1.0)
               ^

You could also try private constructor's , like class MyValue[T] private(value: T) (instead of private case class) but for case classes apply escapes that restriction (at least in my REPL)

Of course you can do case class MyValue[T <: AnyVal](value: T) if you just want a wrapper around atomic types. You can even increase performance of your wrapper by doing case class MyValue[T](value: T) extends AnyVal which produces a value class, so no addtional reference is created when you do MyValue(1) - in byte-code it's just going to be the same Int.