问:
How to show Snackbar above Bottombar?
I'm using roughike's BottomBar 2.0: https://github.com/roughike/BottomBar/

When I display a SnackBar, it shows up on the BottomBar itself.

I want it to be drawn above the BottomBar.

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_activity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/here"
        android:background="#fff">

        <FrameLayout
            android:id="@+id/contentContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/bottomBar">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Three Buttons Bar"
                android:id="@+id/textView"
                android:layout_centerVertical="true"
                android:layout_centerHorizontal="true"
                android:textColor="@color/colorPrimary"
                android:textSize="35sp" />

        </FrameLayout>

        <com.roughike.bottombar.BottomBar
            android:id="@+id/bottomBar"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_alignParentBottom="true"
            app:bb_tabXmlResource="@xml/bottombar_tabs" />
    </RelativeLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomBar bottomBar = (BottomBar) findViewById(R.id.bottomBar);
        bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelected(int tabId) {
                switch (tabId) {
                    case R.id.recent_item:
                        Snackbar.make(findViewById(R.id.main_activity), "Recent Item Selected", Snackbar.LENGTH_LONG).show();
                        break;
                    case R.id.favorite_item:
                        Snackbar.make(findViewById(R.id.main_activity), "Favorite Item Selected", Snackbar.LENGTH_LONG).show();
                        break;
                    case R.id.location_item:
                        Snackbar.make(findViewById(R.id.main_activity), "Location Item Selected", Snackbar.LENGTH_LONG).show();
                        break;
                }
            }
        });
    }
}
</code>```

Screenshots:

Is anything wrong with the layout file??

What am I missing??

I also checked this: Move snackbar above the bottom bar, but it didn't help..

EDIT:

I tried as Abtin said:

```<code>Snackbar.make(bottomBar, "Location Item Selected", Snackbar.LENGTH_LONG).show();
</code>```

and

```<code><com.roughike.bottombar.BottomBar
            android:id="@+id/bottomBar"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_alignParentBottom="true"
            app:bb_tabXmlResource="@xml/bottombar_tabs"
            app:bb_behavior="underNavbar"/>
</code>```

Now it has become like this:

As you can see, there's this unused space below the BottomBar when I set app:bb_behavior="underNavbar", which is not I want..

答:
You should create CoordinatorLayout in xml, from his bottom you wish will be shown SnackBar and give id of the CoordinatorLayout as id of View at fun. make of SnackBar.

```<code>    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/viewSnack"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="50dp"/>
</code>```

inside activity:

```<code>Snackbar.make(findViewById(R.id.viewSnack), "Text of the SnackBar", Snackbar.LENGTH_LONG).show();
</code>```

Title: How to show Snackbar above Bottombar?

Body:
I'm using roughike's BottomBar 2.0: https://github.com/roughike/BottomBar/

When I display a SnackBar, it shows up on the BottomBar itself.

I want it to be drawn above the BottomBar.

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_activity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/here"
        android:background="#fff">

        <FrameLayout
            android:id="@+id/contentContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/bottomBar">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Three Buttons Bar"
                android:id="@+id/textView"
                android:layout_centerVertical="true"
                android:layout_centerHorizontal="true"
                android:textColor="@color/colorPrimary"
                android:textSize="35sp" />

        </FrameLayout>

        <com.roughike.bottombar.BottomBar
            android:id="@+id/bottomBar"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_alignParentBottom="true"
            app:bb_tabXmlResource="@xml/bottombar_tabs" />
    </RelativeLayout>

</android.support.design.widget.CoordinatorLayout>

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomBar bottomBar = (BottomBar) findViewById(R.id.bottomBar);
        bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelected(int tabId) {
                switch (tabId) {
                    case R.id.recent_item:
                        Snackbar.make(findViewById(R.id.main_activity), "Recent Item Selected", Snackbar.LENGTH_LONG).show();
                        break;
                    case R.id.favorite_item:
                        Snackbar.make(findViewById(R.id.main_activity), "Favorite Item Selected", Snackbar.LENGTH_LONG).show();
                        break;
                    case R.id.location_item:
                        Snackbar.make(findViewById(R.id.main_activity), "Location Item Selected", Snackbar.LENGTH_LONG).show();
                        break;
                }
            }
        });
    }
}

Screenshots:

Is anything wrong with the layout file??

What am I missing??

I also checked this: Move snackbar above the bottom bar, but it didn't help..

EDIT:

I tried as Abtin said:

Snackbar.make(bottomBar, "Location Item Selected", Snackbar.LENGTH_LONG).show();

and

<com.roughike.bottombar.BottomBar
            android:id="@+id/bottomBar"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_alignParentBottom="true"
            app:bb_tabXmlResource="@xml/bottombar_tabs"
            app:bb_behavior="underNavbar"/>

Now it has become like this:

As you can see, there's this unused space below the BottomBar when I set app:bb_behavior="underNavbar", which is not I want..

Body:
You should create CoordinatorLayout in xml, from his bottom you wish will be shown SnackBar and give id of the CoordinatorLayout as id of View at fun. make of SnackBar.

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/viewSnack"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="50dp"/>

inside activity:

Snackbar.make(findViewById(R.id.viewSnack), "Text of the SnackBar", Snackbar.LENGTH_LONG).show();


来源: stackexchange

问:
Read query parameter from URL in Kibana-5.1 search query i.e as a placeholder
I am new to Kibana and using it for visualising the data present in Elastic Search.
I am trying to create dynamic dashboard i.e. by using saved search indexes having field values as variable.

What I want

Want to use place holders in the query which can be populated from URL parameters and then search results rendered in dashboard.
So that user can search results by providing some input instead of fixed query.
Can it be done in Kibana? If not, is there any better visualisation tool other than Kibana to serve this purpose.

答:
In the Dashboard View there is actually a searchbar where you can just fire normal Matchqueries and its easy to filter i.e:

Create a table with terms aggregation for one of the fields a user might be interested in.

Click on one of the Terms in the Dashboard

A filter can be seen under the searchbar and all elements in the dashboard will be filtered with it.

If you have line charts users can zoom into the charts to see only information of the zoomed in timeframe

Barcharts are interactive like tables

Play around a bit. Kibana is very powerful you just have to find the right visualizations.

ContentLicense: CC BY-SA 3.0


问:
How to display submenu on dropdown using positioning and CSS?
I have this simple navigation menu for my design. But the problem is I can't display the sub menu when hovered. Is there any way to solve this? Or does my CSS has some missing styles?

nav ul {list-style-type: none; overflow: hidden; background: #000; position: relative;}
nav li {float: left;}
nav li > a {padding: 15px 15px; display: inline-block; text-decoration: none; color: white; text-align: center;}
nav li > a:hover {background: violet;}

nav ul ul { position: absolute; background: green; top: 100%;}
nav ul ul li > a:hover {color: red;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>sample UL</title>
    <style media="screen">

    </style>
  </head>
  <body>
    <nav>
      <ul>
        <li>Home</li>
        <li>Menu 1</li>
        <ul>
          <li>submenu 1</li>
          <li>submenu 2</li>
        </ul>
      </ul>
    </nav>
  </body>
</html></code>```

答:
nav ul {
            list-style-type: none;
            overflow: hidden;
            background: #000;
            position: relative;
        }

        nav li {
            float: left;
        }

        nav li > a {
            padding: 15px 15px;
            display: inline-block;
            text-decoration: none;
            color: white;
            text-align: center;
        }

        nav li > a:hover {
            background: violet;
        }

        nav ul ul {
            background: green;
            top: 100%;
        }

        nav ul li a + ul {
            display: none;
        }

        nav ul li a:hover + ul {
            display: block;
        }

        .sub-menu:hover {
            display: block;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>sample UL</title>
</head>
<body>
<nav>
    <ul>
        <li>Home</li>
        <li>Menu 1
            <ul class="sub-menu">
                <li>submenu 1</li>
                <li>submenu 2</li>
            </ul>
        </li>
    </ul>

</nav>
</body>
</html></code>```

Body:
I have this simple navigation menu for my design. But the problem is I can't display the sub menu when hovered. Is there any way to solve this? Or does my CSS has some missing styles?

nav ul {list-style-type: none; overflow: hidden; background: #000; position: relative;}
nav li {float: left;}
nav li > a {padding: 15px 15px; display: inline-block; text-decoration: none; color: white; text-align: center;}
nav li > a:hover {background: violet;}

nav ul ul { position: absolute; background: green; top: 100%;}
nav ul ul li > a:hover {color: red;}

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>sample UL</title>

Home

Menu 1

submenu 1

submenu 2

Body:
nav ul {
            list-style-type: none;
            overflow: hidden;
            background: #000;
            position: relative;
        }

        nav li {
            float: left;
        }

        nav li > a {
            padding: 15px 15px;
            display: inline-block;
            text-decoration: none;
            color: white;
            text-align: center;
        }

        nav li > a:hover {
            background: violet;
        }

        nav ul ul {
            background: green;
            top: 100%;
        }

        nav ul li a + ul {
            display: none;
        }

        nav ul li a:hover + ul {
            display: block;
        }

        .sub-menu:hover {
            display: block;
        }

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>sample UL</title>
</head>
<body>
<nav>
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Menu 1</a>
            <ul class="sub-menu">
                <li><a href="#">submenu 1</a></li>
                <li><a href="#">submenu 2</a></li>
            </ul>
        </li>
    </ul>

</nav>
</body>
</html>


问:
PHP resize image before save to mysql database?
After I got the post, how to resize to a smaller width (maximum width is 80, min also 80) and what should I check for security purposes?

My current code:

```<code>if(!empty($_FILES)) {
# Resize Image function
$return=true;
function resizeImage($originalImage,$toWidth,$toHeight){
    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;

    // Recalculate new size with default ratio
    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }

    // Resize the original image
    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    return $imageResized;
}

// Get the file information
$userfile_name = $_FILES['profile_picture']['name'];
$userfile_tmp  = $_FILES['profile_picture']['tmp_name'];
$userfile_size = $_FILES['profile_picture']['size'];
$userfile_type = $_FILES['profile_picture']['type'];
$filename = basename($_FILES['profile_picture']['name']);
$file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

//Only process if the file is a JPG and below the allowed limit
if((!empty($_FILES["profile_picture"])) && ($_FILES['profile_picture']['error'] == 0)) {
    $allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
    $allowed_image_ext = array_unique($allowed_image_types); // Do not change this
    foreach ($allowed_image_types as $mime_type => $ext) {
        if($file_ext==$ext ){
            $return=false;
            break;
        } else {
            $return=true;
        }
    }

    if ($userfile_size > (7*1048576)) { # 7 means 7 mb
        $return=false;
    }
} else {
    $return=false;
}

//Everything is ok, so we can upload the image.
if (strlen($return)==0){
    $widthAndHeight = getimagesize($userfile_tmp . "." . $file_ext); //EDITED QUESTION
    $width  = $widthAndHeight[0];
    $height = $widthAndHeight[1];

    if ($width > 80){
        $scale = 80/$width;
        $height = $height * $scale;
        $data = resizeImage($userfile_name,80,$height,$scale);
        $data = mysql_real_escape_string($data);
    } else {
        $data = mysql_real_escape_string($userfile_name);
    }

    $update = mysql_query("UPDATE `avatar` set image = '{$data}' WHERE userid = '" .  $_SESSION['userid'] . " . '");
} else {
    $return=false;
}
</code>```

The datatype in mysql database is MediumBlob since it only store small file

Sorry for not mention my problem, the code its not working. The error is:

```<code>Warning: getimagesize(C:\wamp\tmp\php991B.tmp.png) [function.getimagesize]: failed to open stream: No such file or directory in C:\wamp\www\XXX\avatar.php on line 82**strong text**
</code>```

答:
Better way will be - to store the image in file system and store a ref to the file in the database. (For the resizing you can use GD library)

Try this link: http://www.php.net/manual/en/function.imagecopyresized.php

ContentLicense: CC BY-SA 2.5

Body:
After I got the post, how to resize to a smaller width (maximum width is 80, min also 80) and what should I check for security purposes?

My current code:

if(!empty($_FILES)) {
# Resize Image function
$return=true;
function resizeImage($originalImage,$toWidth,$toHeight){
    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;

    // Recalculate new size with default ratio
    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }

    // Resize the original image
    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    return $imageResized;
}

// Get the file information
$userfile_name = $_FILES['profile_picture']['name'];
$userfile_tmp  = $_FILES['profile_picture']['tmp_name'];
$userfile_size = $_FILES['profile_picture']['size'];
$userfile_type = $_FILES['profile_picture']['type'];
$filename = basename($_FILES['profile_picture']['name']);
$file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

//Only process if the file is a JPG and below the allowed limit
if((!empty($_FILES["profile_picture"])) && ($_FILES['profile_picture']['error'] == 0)) {
    $allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
    $allowed_image_ext = array_unique($allowed_image_types); // Do not change this
    foreach ($allowed_image_types as $mime_type => $ext) {
        if($file_ext==$ext ){
            $return=false;
            break;
        } else {
            $return=true;
        }
    }

    if ($userfile_size > (7*1048576)) { # 7 means 7 mb
        $return=false;
    }
} else {
    $return=false;
}

//Everything is ok, so we can upload the image.
if (strlen($return)==0){
    $widthAndHeight = getimagesize($userfile_tmp . "." . $file_ext); //EDITED QUESTION
    $width  = $widthAndHeight[0];
    $height = $widthAndHeight[1];

    if ($width > 80){
        $scale = 80/$width;
        $height = $height * $scale;
        $data = resizeImage($userfile_name,80,$height,$scale);
        $data = mysql_real_escape_string($data);
    } else {
        $data = mysql_real_escape_string($userfile_name);
    }

    $update = mysql_query("UPDATE `avatar` set image = '{$data}' WHERE userid = '" .  $_SESSION['userid'] . " . '");
} else {
    $return=false;
}

The datatype in mysql database is MediumBlob since it only store small file

Sorry for not mention my problem, the code its not working. The error is:

Warning: getimagesize(C:\wamp\tmp\php991B.tmp.png) [function.getimagesize]: failed to open stream: No such file or directory in C:\wamp\www\XXX\avatar.php on line 82**strong text**


问:
How to set specific Java version to Maven?
On my machine I have two Java versions installed: (1.6 and 1.7 installed manually by me).  I need both of them for different projects. But for Maven I need 1.7, but my Maven uses the 1.6 Java version.

How can I set Maven to use 1.7?

答:
In the POM, you can set the compiler properties, e.g. for 1.8:</p>

```<code><project>
...
 <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
...
</project>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In the POM, you can set the compiler properties, e.g. for 1.8:

<project>
...
 <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
...
</project>


问:
Java: Using a double variable to call a double method
The error I'm getting is:

```<code>"Cannot invoke yearlyPay() on the primitive type double"
</code>```

I'm trying to call the method: yearlyPay() on the variable calcPay.
I've created yearlyPay() and it looks as so:

```<code>public double yearlyPay(double pay)
{
    double yearlyPay = hourlyRate * HOURS_YEAR;
    System.out.println("public double yearlyPay(double pay): " + yearlyPay);
    System.out.println("");
    return yearlyPay;
}
</code>```

then I have another method where calcPay is located

```<code>public double localTax(double calcPay)
{
    double pay = calcPay;
    double localTax;

    if (pay.yearlyPay() < 45000)
    {
        localTax = (1.15 / 100) * pay;
    }
    else
        localTax = (1.15 / 100) * 45000;

    return localTax;
}
</code>```

I also figured that having

```<code>double pay = calcPay
</code>```

is kinda redundant, so I changed it to

```<code>public double localTax(double calcPay)
{   //removed double pay = calcPay
    double localTax;

    if (calcPay.yearlyPay() < 45000)
    {
        localTax = (1.15 / 100) * pay;
    }
    else
        localTax = (1.15 / 100) * 45000;

    return localTax;
}
</code>```

But...same thing happened.

I googled the problem (with the error message) but I didn't find anything that helped.

There was a place that said to change double to Double, but I didn't know which ones where to change. So I tried each one, one by one...needless to say that didn't work either.

Any help would be appreciated. There is more to the code (which is homework). I didn't post it all cuz I don't think it's useful. Ask if you need specific though.

Also if this question is similar to this one, let me know, I'll delete this and look at that one. I probably missed it in the 3,000,000+ search results on google.

答:
Only objects have methods.

A double is a primitive not an object.

Your yearlyPay() method is a method of the class you are writing, not of double.

So if yearlyPay() is defined in the same class as the call, you call it as:

```<code>double n = yearlyPay(calcPay);
</code>```

... or if you wrote the method in another class (say, PayCalculator):

```<code>PayCalculator payCalculator = new PayCalculator();
...
double n = payCalculator.yearlyPay(calcPay);
</code>```

... or if the method is in PayCalculator as a static method:

```<code>double n = PayCalculator.yearlyPay(calcPay);
</code>```

Incidentally, it's not a good idea to use floating-point number types for money calculations. Google for reasons.

Body:
The error I'm getting is:

"Cannot invoke yearlyPay() on the primitive type double"

I'm trying to call the method: yearlyPay() on the variable calcPay.
I've created yearlyPay() and it looks as so:

public double yearlyPay(double pay)
{
    double yearlyPay = hourlyRate * HOURS_YEAR;
    System.out.println("public double yearlyPay(double pay): " + yearlyPay);
    System.out.println("");
    return yearlyPay;
}

then I have another method where calcPay is located

public double localTax(double calcPay)
{
    double pay = calcPay;
    double localTax;

    if (pay.yearlyPay() < 45000)
    {
        localTax = (1.15 / 100) * pay;
    }
    else
        localTax = (1.15 / 100) * 45000;

    return localTax;
}

I also figured that having

double pay = calcPay

is kinda redundant, so I changed it to

public double localTax(double calcPay)
{   //removed double pay = calcPay
    double localTax;

    if (calcPay.yearlyPay() < 45000)
    {
        localTax = (1.15 / 100) * pay;
    }
    else
        localTax = (1.15 / 100) * 45000;

    return localTax;
}

But...same thing happened.

I googled the problem (with the error message) but I didn't find anything that helped.

There was a place that said to change double to Double, but I didn't know which ones where to change. So I tried each one, one by one...needless to say that didn't work either.

Any help would be appreciated. There is more to the code (which is homework). I didn't post it all cuz I don't think it's useful. Ask if you need specific though.

Also if this question is similar to this one, let me know, I'll delete this and look at that one. I probably missed it in the 3,000,000+ search results on google.

Body:
Only objects have methods.

A double is a primitive not an object.

Your yearlyPay() method is a method of the class you are writing, not of double.

So if yearlyPay() is defined in the same class as the call, you call it as:

double n = yearlyPay(calcPay);

... or if you wrote the method in another class (say, PayCalculator):

PayCalculator payCalculator = new PayCalculator();
...
double n = payCalculator.yearlyPay(calcPay);

... or if the method is in PayCalculator as a static method:

double n = PayCalculator.yearlyPay(calcPay);

Incidentally, it's not a good idea to use floating-point number types for money calculations. Google for reasons.


问:
Setting up OpenGL on Mac and use it on Windows
For a project at university I need OpenGL. Since we need to run our program on a windows PC I have to code it accordingly (although I have a Mac).

So is there a better tool than XCode (since frameworks like glew are not intended there) ?

And if not - do I only have to include glew- and SDK2-lib?

答:
You need: (A) How to create a gl context. (B) How to get function-pointers to gl functions. (C) How to handle user actions (mouse, keyboard). And perhaps (D) some GUI.
<p> (B) is achieved by glew or similar. Not needed on MAC OS, but using it makes no effect at all.
<p> For the rest use SDL, GLFW, etc. Or more complex and featured wxWidgets or Qt.</p>

Body:
You need: (A) How to create a gl context. (B) How to get function-pointers to gl functions. (C) How to handle user actions (mouse, keyboard). And perhaps (D) some GUI.

 (B) is achieved by glew or similar. Not needed on MAC OS, but using it makes no effect at all.

 For the rest use SDL, GLFW, etc. Or more complex and featured wxWidgets or Qt.


问:
How do I only keep the rows with the lowest and highest value in a certain column, by groups?
In a nutshell, how do I go from this

```<code>structure(list(id = c(1, 2, 3, 4, 5, 6), user = c(1, 1, 1, 2,
2, 2), value = c(1, 3, 5, 2, 5, 9)), .Names = c("id", "user",
"value"), row.names = c(NA, -6L), class = "data.frame")
</code>```

to this?

```<code>structure(list(id = c(1, 3, 4, 6), user = c(1, 1, 2, 2), value = c(1,
5, 2, 9)), .Names = c("id", "user", "value"), row.names = c(NA,
-4L), class = "data.frame")
</code>```

Meaning, for each user, need to keep only the two rows corresponding to the lowest and highest value.

I'd like a solution using dplyr, if possible. Otherwise, any solution is fine.

答:
We can use slice with which.min/which.max after grouping by 'user'

```<code>library(dplyr)
df1 %>%
   group_by(user) %>%
   slice(c(which.min(value), which.max(value)))
#   id  user value
#  <dbl> <dbl> <dbl>
#1     1     1     1
#2     3     1     5
#3     4     2     2
#4     6     2     9
</code>```

Or another option is arrange with slice.  After grouping by 'user', arrange the 'value' in ascending for each 'user' and slice the first and last row

```<code>df1 %>%
     group_by(user) %>%
     arrange(value) %>%
     slice(c(1, n()))
</code>```

If there are ties for min and/or max 'value' and wanted to keep all the min and max rows, use filter

```<code>df1 %>%
     group_by(user) %>%
     filter(value %in% c(min(value), max(value)))
</code>```

Body:
In a nutshell, how do I go from this

structure(list(id = c(1, 2, 3, 4, 5, 6), user = c(1, 1, 1, 2,
2, 2), value = c(1, 3, 5, 2, 5, 9)), .Names = c("id", "user",
"value"), row.names = c(NA, -6L), class = "data.frame")

to this?

structure(list(id = c(1, 3, 4, 6), user = c(1, 1, 2, 2), value = c(1,
5, 2, 9)), .Names = c("id", "user", "value"), row.names = c(NA,
-4L), class = "data.frame")

Meaning, for each user, need to keep only the two rows corresponding to the lowest and highest value.

I'd like a solution using dplyr, if possible. Otherwise, any solution is fine.

Body:
We can use slice with which.min/which.max after grouping by 'user'

library(dplyr)
df1 %>%
   group_by(user) %>%
   slice(c(which.min(value), which.max(value)))
#   id  user value
#  <dbl> <dbl> <dbl>
#1     1     1     1
#2     3     1     5
#3     4     2     2
#4     6     2     9

Or another option is arrange with slice.  After grouping by 'user', arrange the 'value' in ascending for each 'user' and slice the first and last row

df1 %>%
     group_by(user) %>%
     arrange(value) %>%
     slice(c(1, n()))

If there are ties for min and/or max 'value' and wanted to keep all the min and max rows, use filter

df1 %>%
     group_by(user) %>%
     filter(value %in% c(min(value), max(value)))


问:
Webpack Hot Module Replacement does not inject the updated code
I've been trying to configure the Webpack 2 Hot Module Replacement by using Webpack-Dev-Server.

webpack.config.js is the following:

```<code>  const path = require('path');
  const Webpack = require('webpack');
  const ExtractTextPlugin = require('extract-text-webpack-plugin');

  const HotModuleReplacement = new Webpack.HotModuleReplacementPlugin();
  const NamedModulesPlugin = new Webpack.NamedModulesPlugin();
  const NoEmitOnErrorsPlugin = new Webpack.NoEmitOnErrorsPlugin();

  const extractCSS = new ExtractTextPlugin('main.css');
  const extractSCSS = new ExtractTextPlugin('styles.css');

  const config = {
      entry: [
          'webpack-dev-server/client?http://localhost:8080',
          // bundle the client for webpack-dev-server
          // and connect to the provided endpoint
         'webpack/hot/only-dev-server',
         // bundle the client for hot reloading
         // only- means to only hot reload for successful updates
         './src/index.js',
      ],
      output: {
          path: path.resolve(__dirname, 'dist'),
          filename: 'bundle.js',
          publicPath: 'http://localhost:8080/',
          hotUpdateChunkFilename: 'hot/hot-update.js',
          hotUpdateMainFilename: 'hot/hot-update.json',
      },
      module: {
          rules: [
              {
                  test: /\.(js|jsx)$/,
                  exclude: [
                      path.resolve(__dirname, 'node_modules'),
                  ],
                  loader: 'babel-loader',
                  options: {
                      presets: ['react', 'es2015', 'stage-2'],
                  },
              },
              {
                  test: /\.scss$/,
                  loader: extractSCSS.extract({
                      fallback: 'style-loader',
                      use: ['css-loader', 'postcss-loader', 'sass-loader'],
                  }),
              },
              {
                  test: /\.css$/,
                  loader: extractCSS.extract({
                      fallback: 'style-loader',
                      use: ['css-loader', 'postcss-loader'],
                  }),
              },
          ],
      },
      plugins: [
          extractCSS,
          extractSCSS,
          HotModuleReplacement,
          NamedModulesPlugin,
          NoEmitOnErrorsPlugin,
      ],

      devtool: 'source-map',
      devServer: {
          publicPath: 'http://localhost:8080/',
          contentBase: './',
          inline: true,
          hot: true,
          historyApiFallback: true,
          stats: {
              colors: true,
          },
      },
   };

   module.exports = config;
</code>```

I've got this folder structure:

```<code>/
/src
/src/index.js
/src/index.scss
</code>```

and I thought that I needed to use the HMR API in the index.js like so:

```<code>import MockComponent from './MockComponent/MockComponent';

export default class App {
    constructor() {
        this.mock = new MockComponent();
    }
    render() {
        return `<div class="element">${this.mock.render()}</div>`;
    }
}

let app = {};
app = new App();
const mainDiv = document.querySelector('#root');
mainDiv.innerHTML = app.render();

// Hot Module Replacement API
if (module.hot) {
    module.hot.accept();
}
</code>```

The is issue is that when I do a change in the code in the console I got:

but then the HMR seems it's not doing any change on the rendered.

Could anybody please help me out on this?

Many Thanks

答:
This has been solved (please refer to this repo https://github.com/andrixb/WebpackSassStarter):

Added in webpack.config.js HtmlWebpackPlugin with the following configuration:

new HtmlWebpackPlugin({
        title: 'FE Build Setup',
        hash: true,
        template: './src/index.html',
    }),

Moved inside the src folder the index.html that was outside and removed static script and link tag (index.html now is used just a template)

Removed from webpack.config.js
in entry

'webpack-dev-server/client?    http://localhost:8080',
// bundle the client for webpack-dev-server
// and connect to the provided endpoint
'webpack/hot/only-dev-server',
// bundle the client for hot reloading
// only- means to only hot reload for successful updates

and in output:

publicPath: 'http://localhost:8080/',
hotUpdateChunkFilename: 'hot/hot-update.js',
hotUpdateMainFilename: 'hot/hot-update.json',

Removed (in webpack.config.js) ExtractTextPlugin from dev environment as suggested by @Skip Jack

Edited the devServer configuration in webpack.config.js

Body:
I've been trying to configure the Webpack 2 Hot Module Replacement by using Webpack-Dev-Server.

webpack.config.js is the following:

  const path = require('path');
  const Webpack = require('webpack');
  const ExtractTextPlugin = require('extract-text-webpack-plugin');

  const HotModuleReplacement = new Webpack.HotModuleReplacementPlugin();
  const NamedModulesPlugin = new Webpack.NamedModulesPlugin();
  const NoEmitOnErrorsPlugin = new Webpack.NoEmitOnErrorsPlugin();

  const extractCSS = new ExtractTextPlugin('main.css');
  const extractSCSS = new ExtractTextPlugin('styles.css');

  const config = {
      entry: [
          'webpack-dev-server/client?http://localhost:8080',
          // bundle the client for webpack-dev-server
          // and connect to the provided endpoint
         'webpack/hot/only-dev-server',
         // bundle the client for hot reloading
         // only- means to only hot reload for successful updates
         './src/index.js',
      ],
      output: {
          path: path.resolve(__dirname, 'dist'),
          filename: 'bundle.js',
          publicPath: 'http://localhost:8080/',
          hotUpdateChunkFilename: 'hot/hot-update.js',
          hotUpdateMainFilename: 'hot/hot-update.json',
      },
      module: {
          rules: [
              {
                  test: /\.(js|jsx)$/,
                  exclude: [
                      path.resolve(__dirname, 'node_modules'),
                  ],
                  loader: 'babel-loader',
                  options: {
                      presets: ['react', 'es2015', 'stage-2'],
                  },
              },
              {
                  test: /\.scss$/,
                  loader: extractSCSS.extract({
                      fallback: 'style-loader',
                      use: ['css-loader', 'postcss-loader', 'sass-loader'],
                  }),
              },
              {
                  test: /\.css$/,
                  loader: extractCSS.extract({
                      fallback: 'style-loader',
                      use: ['css-loader', 'postcss-loader'],
                  }),
              },
          ],
      },
      plugins: [
          extractCSS,
          extractSCSS,
          HotModuleReplacement,
          NamedModulesPlugin,
          NoEmitOnErrorsPlugin,
      ],

      devtool: 'source-map',
      devServer: {
          publicPath: 'http://localhost:8080/',
          contentBase: './',
          inline: true,
          hot: true,
          historyApiFallback: true,
          stats: {
              colors: true,
          },
      },
   };

   module.exports = config;

I've got this folder structure:

/
/src
/src/index.js
/src/index.scss

and I thought that I needed to use the HMR API in the index.js like so:

import MockComponent from './MockComponent/MockComponent';

export default class App {
    constructor() {
        this.mock = new MockComponent();
    }
    render() {
        return `<div class="element">${this.mock.render()}</div>`;
    }
}

let app = {};
app = new App();
const mainDiv = document.querySelector('#root');
mainDiv.innerHTML = app.render();

// Hot Module Replacement API
if (module.hot) {
    module.hot.accept();
}

The is issue is that when I do a change in the code in the console I got:

but then the HMR seems it's not doing any change on the rendered.

Could anybody please help me out on this?

Many Thanks


问:
Interpolate ruby if statement in haml javascript block
This is the code I currently have:

```<code>:javascript
    // do something
- if current_user.role? :client
    :javascript
        //do something else
</code>```

It's obviously not very clean since I'm repeating the :javascript haml filter. I'd like to avoid that, but I don't know how to properly write a Ruby "if" statement inside a HAML :javascript block.

I know how to interpolate variables with #{}, but how do you do the same for whole if/for/etc. statements?

答:
I've interpolated the Ruby/HAML variable into explicit JS true or false for JS condition like this:

```<code>$("#cancel").click( function() {
  if (#{ !!my_flag_variable })
    window.location.href = "./";
  else
    $("#dialog").hide();
} );
</code>```

Body:
This is the code I currently have:

:javascript
    // do something
- if current_user.role? :client
    :javascript
        //do something else

It's obviously not very clean since I'm repeating the :javascript haml filter. I'd like to avoid that, but I don't know how to properly write a Ruby "if" statement inside a HAML :javascript block.

I know how to interpolate variables with #{}, but how do you do the same for whole if/for/etc. statements?

Body:
I've interpolated the Ruby/HAML variable into explicit JS true or false for JS condition like this:

$("#cancel").click( function() {
  if (#{ !!my_flag_variable })
    window.location.href = "./";
  else
    $("#dialog").hide();
} );


问:
Check if key exists in memcache cluster using PHP
I'm debugging the caching layer of a PHP application. It uses a cluster of memcache servers to cache values. I want to verify that a specific object gets purged correctly.

My idea was to connect to the right memcache server with telnet and check manually if the key exists.
I know the key that is passed to Memcache::set, but not which server to connect to. How do I know on which memcache server the data gets stored?

答: I just referenced the docs. Memcached clients hash the key to determine which sever to query.  So, I guess Memcached IS sharded.  You will probably have to look at the source of a client (or maybe the docs) to see how the hashing->sever is done.  Otherwise you could just use a client from command line to query for the value.</p>


问:
Storing data obtained from cassandra in spark Memory and make it available to other spark job server jobs in same context
I  am using spark job server and using spark-sql to get data from a cassandra table as follows

```<code>public Object runJob(JavaSparkContext jsc, Config config) {
  CassandraSQLContext sq = new CassandraSQLContext(JavaSparkContext.toSparkContext(jsc));
  sq.setKeyspace("rptavlview");
  DataFrame vadevent = sq.sql("SELECT username,plan,plate,ign,speed,datetime,odo,gd,seat,door,ac from rptavlview.vhistory ");
  vadevent.registerTempTable("history");
  sq.cacheTable("history");
  DataFrame vadevent1 = sq.sql("SELECT plate,ign,speed,datetime FROM history where username='"+params[0]+"' and plan='"+params[1]+"'");
  long count =  vadevent.rdd().count();
  }
</code>```

But I am getting table not found history.
Can anybody mention how to cache cassandra data in spark memory and reuse the same data either in concurrent requests of same job or as two jobs one for caching and other for querying.

I am using dse5.0.4  so spark version is 1.6.1

答: You can allow spark jobs to share the state of other contexts.  This link goes more in depth.</p>

Body:
I  am using spark job server and using spark-sql to get data from a cassandra table as follows

public Object runJob(JavaSparkContext jsc, Config config) {
  CassandraSQLContext sq = new CassandraSQLContext(JavaSparkContext.toSparkContext(jsc));
  sq.setKeyspace("rptavlview");
  DataFrame vadevent = sq.sql("SELECT username,plan,plate,ign,speed,datetime,odo,gd,seat,door,ac from rptavlview.vhistory ");
  vadevent.registerTempTable("history");
  sq.cacheTable("history");
  DataFrame vadevent1 = sq.sql("SELECT plate,ign,speed,datetime FROM history where username='"+params[0]+"' and plan='"+params[1]+"'");
  long count =  vadevent.rdd().count();
  }

But I am getting table not found history.
Can anybody mention how to cache cassandra data in spark memory and reuse the same data either in concurrent requests of same job or as two jobs one for caching and other for querying.

I am using dse5.0.4  so spark version is 1.6.1


问:
Django Form csrf_token
whenever we want to perform a POST request in django we need to add a csrf_token. For example if you want to create a form:

```<code><form action="#" method="POST"> {% csrf_token %}
</code>```

This is pretty simple if you do it in HTML. However, I want to create forms dynamically using jQuery. I have the following code:

```<code>                   $div = $('<form/>')   // First I am creating the `form` div
                       .attr("method","POST") //POST method
                       .attr("action","#");
                   ($div).appendTo('#team_notification_'+index); //Appending it
                   var $button  = $('<button/>') //Creating the buttons
                       .attr("type","submit")
                       .attr("name","Accept")
                       .attr("value", invite[0].pk); //Setting some value
                   $($button).appendTo($div);
</code>```

But how can I append the csrf_token using jQuery?

Thanks

答:
Try something like</p>

```<code>var $csrf = $('<input/>')
               .attr("type", "hidden")
               .attr("name", "csrfmiddlewaretoken")
               .attr("value", "{{csrf_token}}");
$($csrf).appendTo($div);
</code>```

Title: Django Form csrf_token

Body:
whenever we want to perform a POST request in django we need to add a csrf_token. For example if you want to create a form:

<form action="#" method="POST"> {% csrf_token %}

This is pretty simple if you do it in HTML. However, I want to create forms dynamically using jQuery. I have the following code:

                   $div = $('<form/>')   // First I am creating the `form` div
                       .attr("method","POST") //POST method
                       .attr("action","#");
                   ($div).appendTo('#team_notification_'+index); //Appending it
                   var $button  = $('<button/>') //Creating the buttons
                       .attr("type","submit")
                       .attr("name","Accept")
                       .attr("value", invite[0].pk); //Setting some value
                   $($button).appendTo($div);

But how can I append the csrf_token using jQuery?

Thanks

Body:
Try something like

var $csrf = $('<input/>')
               .attr("type", "hidden")
               .attr("name", "csrfmiddlewaretoken")
               .attr("value", "{{csrf_token}}");
$($csrf).appendTo($div);


问:
How do I build a UK postcode area map in R?

Input

I have count data by first 2 letter UK postcode in this form:

```<code>Postcode Count
BD       45
DE       123
L8       90
</code>```

Desired output

I would like to create a postcode map using a shapefile based on the 2 letter postcode, and colour the map based on count, similar to this:

My question is, how would I be able to produce a map like this in R?

答:
Is this what you had in mind? Make sure that you have a value for every postal code and that the column containing the name of each postal code is called name.

```<code>library(tidyverse)
library(maptools)
library(raster)
library(plotrix)

# Generate dummy data
dta <-
  tibble(
    name = c(
      "AB",
      "AL",
      "B",
      "BA",
      "BB",
      "BD",
      "BH",
      "BL",
      "BN",
      "BR",
      "BS",
      "CA",
      "CB",
      "CF",
      "CH",
      "CM",
      "CO",
      "CR",
      "CT",
      "CV",
      "CW",
      "DA",
      "DD",
      "DE",
      "DG",
      "DH",
      "DL",
      "DN",
      "DT",
      "DY",
      "E",
      "EC",
      "EH",
      "EN",
      "EX",
      "FK",
      "FY",
      "G",
      "GL",
      "GU",
      "HA",
      "HD",
      "HG",
      "HP",
      "HR",
      "HS",
      "HU",
      "HX",
      "IG",
      "IP",
      "IV",
      "KA",
      "KT",
      "KW",
      "KY",
      "L",
      "LA",
      "LD",
      "LE",
      "LL",
      "LN",
      "LS",
      "LU",
      "M",
      "ME",
      "MK",
      "ML",
      "N",
      "NE",
      "NG",
      "NN",
      "NP",
      "NR",
      "NW",
      "OL",
      "OX",
      "PA",
      "PE",
      "PH",
      "PL",
      "PO",
      "PR",
      "RG",
      "RH",
      "RM",
      "S",
      "SA",
      "SE",
      "SG",
      "SK",
      "SL",
      "SM",
      "SN",
      "SO",
      "SP",
      "SR",
      "SS",
      "ST",
      "SW",
      "SY",
      "TA",
      "TD",
      "TF",
      "TN",
      "TQ",
      "TR",
      "TS",
      "TW",
      "UB",
      "W",
      "WA",
      "WC",
      "WD",
      "WF",
      "WN",
      "WR",
      "WS",
      "WV",
      "YO",
      "ZE",
      "BT",
      "GY",
      "IM",
      "JE"
    ),
    value = rnorm(124)
  )

# Make sure your postal codes are stored in a column called name
# Example:
# dta <- rename(dta, name = name)

# OPTIONAL: Depending on your data, you may need to rescale it for the color ramp to work
dta$value <- rescale(dta$value, newrange = c(0, 1))

# Download a shapefile of postal codes into your working directory
download.file(
  "http://www.opendoorlogistics.com/wp-content/uploads/Data/UK-postcode-boundaries-Jan-2015.zip",
  "postal_shapefile"
)

# Unzip the shapefile
unzip("postal_shapefile")

# Read the shapefile
postal <- readShapeSpatial("./Distribution/Areas")

# Join your data to the shapefile
postal <- raster::merge(postal, dta, by = "name")

# Use the gray function to determine the proper black-and-white color for each postal code
plot(postal, col = gray(postal$value))
</code>```

Body:
Input

I have count data by first 2 letter UK postcode in this form:

Postcode Count
BD       45
DE       123
L8       90

Desired output

I would like to create a postcode map using a shapefile based on the 2 letter postcode, and colour the map based on count, similar to this:

My question is, how would I be able to produce a map like this in R?

Body:
Is this what you had in mind? Make sure that you have a value for every postal code and that the column containing the name of each postal code is called name.

library(tidyverse)
library(maptools)
library(raster)
library(plotrix)

# Generate dummy data
dta <-
  tibble(
    name = c(
      "AB",
      "AL",
      "B",
      "BA",
      "BB",
      "BD",
      "BH",
      "BL",
      "BN",
      "BR",
      "BS",
      "CA",
      "CB",
      "CF",
      "CH",
      "CM",
      "CO",
      "CR",
      "CT",
      "CV",
      "CW",
      "DA",
      "DD",
      "DE",
      "DG",
      "DH",
      "DL",
      "DN",
      "DT",
      "DY",
      "E",
      "EC",
      "EH",
      "EN",
      "EX",
      "FK",
      "FY",
      "G",
      "GL",
      "GU",
      "HA",
      "HD",
      "HG",
      "HP",
      "HR",
      "HS",
      "HU",
      "HX",
      "IG",
      "IP",
      "IV",
      "KA",
      "KT",
      "KW",
      "KY",
      "L",
      "LA",
      "LD",
      "LE",
      "LL",
      "LN",
      "LS",
      "LU",
      "M",
      "ME",
      "MK",
      "ML",
      "N",
      "NE",
      "NG",
      "NN",
      "NP",
      "NR",
      "NW",
      "OL",
      "OX",
      "PA",
      "PE",
      "PH",
      "PL",
      "PO",
      "PR",
      "RG",
      "RH",
      "RM",
      "S",
      "SA",
      "SE",
      "SG",
      "SK",
      "SL",
      "SM",
      "SN",
      "SO",
      "SP",
      "SR",
      "SS",
      "ST",
      "SW",
      "SY",
      "TA",
      "TD",
      "TF",
      "TN",
      "TQ",
      "TR",
      "TS",
      "TW",
      "UB",
      "W",
      "WA",
      "WC",
      "WD",
      "WF",
      "WN",
      "WR",
      "WS",
      "WV",
      "YO",
      "ZE",
      "BT",
      "GY",
      "IM",
      "JE"
    ),
    value = rnorm(124)
  )

# Make sure your postal codes are stored in a column called name
# Example:
# dta <- rename(dta, name = name)

# OPTIONAL: Depending on your data, you may need to rescale it for the color ramp to work
dta$value <- rescale(dta$value, newrange = c(0, 1))

# Download a shapefile of postal codes into your working directory
download.file(
  "http://www.opendoorlogistics.com/wp-content/uploads/Data/UK-postcode-boundaries-Jan-2015.zip",
  "postal_shapefile"
)

# Unzip the shapefile
unzip("postal_shapefile")

# Read the shapefile
postal <- readShapeSpatial("./Distribution/Areas")

# Join your data to the shapefile
postal <- raster::merge(postal, dta, by = "name")

# Use the gray function to determine the proper black-and-white color for each postal code
plot(postal, col = gray(postal$value))


问:
Array multiplying the answer and returning it
This is what I am trying to do. I would like my code to return the following:

"The volume of the small box is: 300"

But I cannot seem to figure out what to do:

```<code><?php
    $box = array(
       "Small box" => array("length" => 12, "width" => 10, "depth" => 2.5),
       "Medium box" => array("length" => 30, "width" => 20, "depth" => 4),
       "Large box" => array("length" => 60, "width" => 40, "depth" => 11.5)

    );
    foreach ($box as $number => $boxes)
    {
        echo "The volume of the "."$number"." is: \t";
        foreach ($boxes as $value)
        {
            if (is_numeric($value))
            {
               $sum = array_product($boxes);
               echo "$sum";
            }
        }
        echo "<br />";
    }
    ?>
</code>```

答:
you can get size of box into index array

```<code> $sum = 1;/*set variable sum to 1 so if it's * in another numerics it's not 0*/
 $i = 0; /*set i condition to reset value of condition*/
    foreach ($box as $number => $boxes) {
        foreach ($boxes as $value)
        {
            if (is_numeric($value)){
               $sum = $sum*$value; /*it's product length*width*depth */
            }
            /*cek the condition if count of boxes is limit lengt so define variable data["box type"]*/
            if(($i+1) == count($boxes)){
              $data[$number] = $sum; /*give value for $data["box type"]*/
            }
            $i++;
        }
        $sum = 1;/*reset sum to 1*/
        $i   =0;/*reset i to 0*/
    }
</code>```

this the result of print_r($data);

```<code>Array
(
    [Small box] => 300
    [Medium box] => 2400
    [Large box] => 27600
)
</code>```

and you can access the variable to any type of box using.

```<code>echo "sample : The volume of the Medium Box is ". $data["Medium box"]." : \t";
</code>```

and the result will be like

```<code>sample : The volume of the Medium Box is 2400
</code>```

let me know if this you looking for.

Body:
This is what I am trying to do. I would like my code to return the following:

"The volume of the small box is: 300"

But I cannot seem to figure out what to do:

<?php
    $box = array(
       "Small box" => array("length" => 12, "width" => 10, "depth" => 2.5),
       "Medium box" => array("length" => 30, "width" => 20, "depth" => 4),
       "Large box" => array("length" => 60, "width" => 40, "depth" => 11.5)

    );
    foreach ($box as $number => $boxes)
    {
        echo "The volume of the "."$number"." is: \t";
        foreach ($boxes as $value)
        {
            if (is_numeric($value))
            {
               $sum = array_product($boxes);
               echo "$sum";
            }
        }
        echo "
";
    }
    ?>

Body:
you can get size of box into index array

 $sum = 1;/*set variable sum to 1 so if it's * in another numerics it's not 0*/
 $i = 0; /*set i condition to reset value of condition*/
    foreach ($box as $number => $boxes) {
        foreach ($boxes as $value)
        {
            if (is_numeric($value)){
               $sum = $sum*$value; /*it's product length*width*depth */
            }
            /*cek the condition if count of boxes is limit lengt so define variable data["box type"]*/
            if(($i+1) == count($boxes)){
              $data[$number] = $sum; /*give value for $data["box type"]*/
            }
            $i++;
        }
        $sum = 1;/*reset sum to 1*/
        $i   =0;/*reset i to 0*/
    }

this the result of print_r($data);

Array
(
    [Small box] => 300
    [Medium box] => 2400
    [Large box] => 27600
)

and you can access the variable to any type of box using.

echo "sample : The volume of the Medium Box is ". $data["Medium box"]." : \t";

and the result will be like

sample : The volume of the Medium Box is 2400

let me know if this you looking for.


问:
Ansible - Playbook returning error on bash command
I am running a bash command using Ansible.

```<code>kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2
</code>```

The output is supposed to be

```<code>   v1.2.0
</code>```

Playbook is ::

```<code>   - name: version of minion before upgrade.
     command: 'kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2'

     register: version
</code>```

I have also used

```<code>     command: "kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2"
</code>```

But it keeps returning me the ERROR.

```<code># ansible-playbook upgrade_k8s.yaml -i ../env/platform
ERROR! Syntax Error while loading YAML.

The error appears to have been in '/root/ejusnub/ansible/playbook/upgrade_k8s.yaml': line 40, column 50, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

   - name: version of minion before upgrade.
     command: 'kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2'
                                                 ^ here
</code>```

Ive even tried to escape every symbol but the same error occurs.

答:
Try this:

```<code>- shell: kubectl version | head -1 | awk '{ print $5 }' | cut -d'"' -f2
</code>```

Use shell module instead of command to work with pipes.

P.S. and carefully read error messages, in every case in your example (with single quotes and with double quotes), you have misplaced quotes.

Body:
I am running a bash command using Ansible.

kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2

The output is supposed to be

   v1.2.0

Playbook is ::

   - name: version of minion before upgrade.
     command: 'kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2'

     register: version

I have also used

     command: "kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2"

But it keeps returning me the ERROR.

# ansible-playbook upgrade_k8s.yaml -i ../env/platform
ERROR! Syntax Error while loading YAML.

The error appears to have been in '/root/ejusnub/ansible/playbook/upgrade_k8s.yaml': line 40, column 50, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

   - name: version of minion before upgrade.
     command: 'kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2'
                                                 ^ here

Ive even tried to escape every symbol but the same error occurs.

Body:
Try this:

- shell: kubectl version | head -1 | awk '{ print $5 }' | cut -d'"' -f2

Use shell module instead of command to work with pipes.

P.S. and carefully read error messages, in every case in your example (with single quotes and with double quotes), you have misplaced quotes.


问:
Recoding varied length variable in SAS where every observation is a different value
Please help me, a novice SAS user, figure this one out!

I have a variable (PERMITCL) that I need to recode.  There are a few problems, however.  First, the variable is different for almost every observation.  Second, the length of the variable is also different in some cases.

Here are a few examples of observations:

```<code>01-01IIP
05-04
19-06ID
07-05
IIP
</code>```

I want to know how many observations contain IIP.

I've tried using:

```<code>where prxmatch("m/IIP/oi", PERMITCL);
</code>```

This is fine to some extent, but I'm still not happy with it. First, it doesn't keep any of the other observations; I'd prefer to keep them as zeroes or another identifier for later.  Second, I still can't easily see how many total IIPs there are; a table yields a different line for each ##-##IIP and plain IIP.

How can I fix my issues?

答:
The purpose of a WHERE statement is to subset.  Sounds like instead you want to calculate a new variable that you then sum or use for other things.

```<code>data want ;
  set have ;
  flag = prxmatch("m/IIP/oi",PERMITCL);
run;

proc freq ;
  tables flag ;
run;
</code>```

The PRXMATCH() will return the location of the text in the string. If you want to convert it to a binary result then you could add more code. So you could do this instead:

```<code>  flag = (0 ne prxmatch("m/IIP/oi",PERMITCL)) ;
</code>```

Body:
Please help me, a novice SAS user, figure this one out!

I have a variable (PERMITCL) that I need to recode.  There are a few problems, however.  First, the variable is different for almost every observation.  Second, the length of the variable is also different in some cases.

Here are a few examples of observations:

01-01IIP
05-04
19-06ID
07-05
IIP

I want to know how many observations contain IIP.

I've tried using:

where prxmatch("m/IIP/oi", PERMITCL);

This is fine to some extent, but I'm still not happy with it. First, it doesn't keep any of the other observations; I'd prefer to keep them as zeroes or another identifier for later.  Second, I still can't easily see how many total IIPs there are; a table yields a different line for each ##-##IIP and plain IIP.

How can I fix my issues?

Body:
The purpose of a WHERE statement is to subset.  Sounds like instead you want to calculate a new variable that you then sum or use for other things.

data want ;
  set have ;
  flag = prxmatch("m/IIP/oi",PERMITCL);
run;

proc freq ;
  tables flag ;
run;

The PRXMATCH() will return the location of the text in the string. If you want to convert it to a binary result then you could add more code. So you could do this instead:

  flag = (0 ne prxmatch("m/IIP/oi",PERMITCL)) ;


问:
git pull says up-to-date but git push rejects non-fast forward
I've just pulled a new branch, made some local changes, committed and tried to push. I was given this error: ! [rejected] groups -> groups (non-fast forward)
So I tried a to pull but was told Already up-to-date.

Here's what I get pulling then pushing.

```<code>~/dev$ git pull origin groups
Already up-to-date.
~/dev$ git push origin groups
To /mnt/ebs/git/repo.git
 ! [rejected]        groups -> groups (non-fast forward)
error: failed to push some refs to '/mnt/ebs/git/repo.git'
</code>```

Can anyone explain how this can be happening and how I can fix it?

答:
When you pulled the branch, did you use the "--track" option (in order to keep you local branch tracking the remote branch). If you did not, it can explain that the "merge" command that does not work.

You can do the merge manually:

```<code>git fetch
git merge origin/groups
</code>```

To compare local and remote repos, I suggest you this command (add it in an alias, it is usefull):

```<code>git log --graph --oneline --all --decorate
</code>```

It will print the project history tree, showing the branch labels. So you will see where your branch and the origin branch diverge.

Note: if you want to preserve a linear history, instead of a "merge", you can do a "rebase" of your local branch on the remote before pushing:

```<code>git rebase origin/groups
git push origin groups
</code>```

Body:
I've just pulled a new branch, made some local changes, committed and tried to push. I was given this error: ! [rejected] groups -> groups (non-fast forward)
So I tried a to pull but was told Already up-to-date.

Here's what I get pulling then pushing.

~/dev$ git pull origin groups
Already up-to-date.
~/dev$ git push origin groups
To /mnt/ebs/git/repo.git
 ! [rejected]        groups -> groups (non-fast forward)
error: failed to push some refs to '/mnt/ebs/git/repo.git'

Can anyone explain how this can be happening and how I can fix it?

Body:
When you pulled the branch, did you use the "--track" option (in order to keep you local branch tracking the remote branch). If you did not, it can explain that the "merge" command that does not work.

You can do the merge manually:

git fetch
git merge origin/groups

To compare local and remote repos, I suggest you this command (add it in an alias, it is usefull):

git log --graph --oneline --all --decorate

It will print the project history tree, showing the branch labels. So you will see where your branch and the origin branch diverge.

Note: if you want to preserve a linear history, instead of a "merge", you can do a "rebase" of your local branch on the remote before pushing:

git rebase origin/groups
git push origin groups


问:
Gitlab: Issue Weight not settable after upgrade to 9.0.2
I've learned yesterday in their webcast that Gitlab 9.0.2 will support issue weights for instance for sprint planning purposes and also found related screenshots out there. However, after upgrading our local Gitlab installation from 8.x (can remember the exact version) to 9.0.2 on a Debian system (Omnibus installation) I didn't get the issue weights.
Is it necessary to enable something on system or project base? Unfortunately, Gitlab documentation is not very helpful here.</p>

答:
Issue weights are only available in the enterprise editions of GitLab, so if you use the community edition, you are out of luck.

Check the comparison chart out here.


问:
MySql convert nested SELECT IN queries into JOINs
I read that using IN in MySql queries causes a slowdown in performance, unlike in Oracle and that a JOIN should be used instead. I am able to convert simple queries, but I am struggling with more complex ones that contain nested SELECTs. For example:

```<code>update Records set ActiveStatus=0, TransactionStatus=0, LastUpdated=&
where ActiveStatus!=5 and LastUpdated!=&
and Pk in (select RecordPk from GroupRecordLink
where GroupPk in (select Pk from Groups where ActiveStatus!=5 and
DateTimeStamp>&))
</code>```

I had a go rewriting it by following this post , but I am not sure my result is correct.

```<code>update Records r join (select distinct RecordPk from GroupRecordLink grl join
Groups g on grl.Pk = g.Pk where g.ActiveStatus!=5 and g.DateTimeStamp>&) s
using (Pk) set ActiveStatus=0, TransactionStatus=0, LastUpdated=&
where ActiveStatus!=5 and DateTimeStamp>&
</code>```

Thanks

答:
In Mysql you could use an explicit join for update   (you must change & witha proper value )  </p>

```<code>    update Records
    INNER JOIN GroupRecordLink on GroupRecordLink.RecordPk = Records.PK
    INNER JOIN Groups on ( GroupRecordLink.GroupPk = Groups.Pk
                  and  Groups.ActiveStatus!=5
                         and Groups.DateTimeStamp>&)
    set ActiveStatus=0,
    TransactionStatus=0,
    LastUpdated=&
</code>```

Body:
I read that using IN in MySql queries causes a slowdown in performance, unlike in Oracle and that a JOIN should be used instead. I am able to convert simple queries, but I am struggling with more complex ones that contain nested SELECTs. For example:

update Records set ActiveStatus=0, TransactionStatus=0, LastUpdated=&
where ActiveStatus!=5 and LastUpdated!=&
and Pk in (select RecordPk from GroupRecordLink
where GroupPk in (select Pk from Groups where ActiveStatus!=5 and
DateTimeStamp>&))

I had a go rewriting it by following this post , but I am not sure my result is correct.

update Records r join (select distinct RecordPk from GroupRecordLink grl join
Groups g on grl.Pk = g.Pk where g.ActiveStatus!=5 and g.DateTimeStamp>&) s
using (Pk) set ActiveStatus=0, TransactionStatus=0, LastUpdated=&
where ActiveStatus!=5 and DateTimeStamp>&

Thanks

Body:
In Mysql you could use an explicit join for update   (you must change & witha proper value )

    update Records
    INNER JOIN GroupRecordLink on GroupRecordLink.RecordPk = Records.PK
    INNER JOIN Groups on ( GroupRecordLink.GroupPk = Groups.Pk
                  and  Groups.ActiveStatus!=5
                         and Groups.DateTimeStamp>&)
    set ActiveStatus=0,
    TransactionStatus=0,
    LastUpdated=&


问:
Dart Test client- side HTML configuration
I understand that the package:unittest/unittest.dart is deprecated and the new package is package:test/test.dart.

Which are the equivalent of the library package:unittest/html_config.dart and the useHtmlConfiguration() function in the new test.dart framework.

Thanks.

Note: I am reading an outdated book ("Dart in Action"). So far I have been able to match the deprecated parts with the new standard parts of Dart.
Except now that I am reading the section of Unit-Test.

source code

```<code>.
├── PackList.dart
├── PackList.html
├── pubspec.lock
├── pubspec.yaml
├── styles.css
└── test
    ├── PackList_test.dart
    └── PackList_test.html
</code>```

I am trying to check if the value that the constructor return is not NULL.

```<code>import "package:test/test.dart";
import "../PackList.dart" as packListApp;

main() {
  test("PackItem constructor", () {
    var item = new packListApp.PackItem("Towel");
    expect(item, isNotNull);
  });
}
</code>```

The source code works.

This is just an excersice to understand how the test framework works.

I expect item to be a new object.

With this properties initialized after var item = new packListApp.PackItem("Towel");

```<code> print(packItem.uiElement); //Towel
 print(packItem.itemText);  //div
</code>```

The problem is that I don't know how do related the html part of my source code with the test.

When I run this test, I got this errors.

```<code> pub run test
00:00 +0 -1: loading test/PackList_test.dart [E]
  Failed to load "test/PackList_test.dart":
  Unable to spawn isolate: The built-in library 'dart:html' is not available on the stand-alone VM.
  PackList.dart: line 1 pos 1: library handler failed
  import "dart:html";
  ^
00:00 +0 -1: Some tests failed.
</code>```

If I add @TestOn("dartium"), I got this message.

```<code>pub run test
No tests ran.
</code>```

答:
pub run test just runs VM tests. If you want to run browser tests, you need to explicitly tell it like

```<code>pub run test -pdartium
</code>```

The my_test.html needs to contain

```<code><link rel="x-dart-test" href="my_test.dart">
</code>```

instead of a normal Dart script tag

Body:
I understand that the package:unittest/unittest.dart is deprecated and the new package is package:test/test.dart.

Which are the equivalent of the library package:unittest/html_config.dart and the useHtmlConfiguration() function in the new test.dart framework.

Thanks.

Note: I am reading an outdated book ("Dart in Action"). So far I have been able to match the deprecated parts with the new standard parts of Dart.
Except now that I am reading the section of Unit-Test.

source code

.
├── PackList.dart
├── PackList.html
├── pubspec.lock
├── pubspec.yaml
├── styles.css
└── test
    ├── PackList_test.dart
    └── PackList_test.html

I am trying to check if the value that the constructor return is not NULL.

import "package:test/test.dart";
import "../PackList.dart" as packListApp;

main() {
  test("PackItem constructor", () {
    var item = new packListApp.PackItem("Towel");
    expect(item, isNotNull);
  });
}

The source code works.

This is just an excersice to understand how the test framework works.

I expect item to be a new object.

With this properties initialized after var item = new packListApp.PackItem("Towel");

 print(packItem.uiElement); //Towel
 print(packItem.itemText);  //div

The problem is that I don't know how do related the html part of my source code with the test.

When I run this test, I got this errors.

 pub run test
00:00 +0 -1: loading test/PackList_test.dart [E]
  Failed to load "test/PackList_test.dart":
  Unable to spawn isolate: The built-in library 'dart:html' is not available on the stand-alone VM.
  PackList.dart: line 1 pos 1: library handler failed
  import "dart:html";
  ^
00:00 +0 -1: Some tests failed.

If I add @TestOn("dartium"), I got this message.

pub run test
No tests ran.

Body:
pub run test just runs VM tests. If you want to run browser tests, you need to explicitly tell it like

pub run test -pdartium

The my_test.html needs to contain

<link rel="x-dart-test" href="my_test.dart">

instead of a normal Dart script tag


问:
Reporting Services 2005 - Conditional Date Formatting not working
...so my sql view returns nvarchar as '123456' or 'JAN 11 2008 12:00AM' (view does a union on two tables and casts date to nvarchar).

I'm trying to apply some conditional date formatting i.e. I want to format the date by checking the "Type" column as:

```<code>=IIf(Fields!Type.Value = "COS", Fields!CosNoOrDateToContractor.Value, FormatDateTime  (Fields!CosNoOrDateToContractor.Value, vbShortDate))
</code>```

So basically if the type is a "COS" then just return the data as is, otherwise format it to a date.

When previewing the report if its a COS then I get #Error in the textbox (Conversion from string "123456" to type 'Date' is not valid.

It's anything else then data is formatted as date.

Does this make sense?

Anything wrong with the syntax or is what I'm trying to do not possible?

答: Have modified the view instead so I'm not casting dates to nvarchar.</p>

Body:
...so my sql view returns nvarchar as '123456' or 'JAN 11 2008 12:00AM' (view does a union on two tables and casts date to nvarchar).

I'm trying to apply some conditional date formatting i.e. I want to format the date by checking the "Type" column as:

=IIf(Fields!Type.Value = "COS", Fields!CosNoOrDateToContractor.Value, FormatDateTime  (Fields!CosNoOrDateToContractor.Value, vbShortDate))

So basically if the type is a "COS" then just return the data as is, otherwise format it to a date.

When previewing the report if its a COS then I get #Error in the textbox (Conversion from string "123456" to type 'Date' is not valid.

It's anything else then data is formatted as date.

Does this make sense?

Anything wrong with the syntax or is what I'm trying to do not possible?


问:
'/usr/include/mysql/mysql/plugin.h.dpkg-new': No such file or directory
when I install libmysqlclient-dev on ubuntu 14.04, I get this error:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  libmysqlclient-dev
0 upgraded, 1 newly installed, 0 to remove and 96 not upgraded.
Need to get 0 B/866 kB of archives.
After this operation, 5,604 kB of additional disk space will be used.
(Reading database ... 63461 files and directories currently installed.)
Preparing to unpack .../libmysqlclient-dev_5.5.52-0ubuntu0.14.04.1_amd64.deb ...
Unpacking libmysqlclient-dev (5.5.52-0ubuntu0.14.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/libmysqlclient-dev_5.5.52-0ubuntu0.14.04.1_amd64.deb (--unpack):
 unable to open '/usr/include/mysql/mysql/plugin.h.dpkg-new': No such file or directory
No apport report written because the error message indicates an issue on the local system
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Errors were encountered while processing:
 /var/cache/apt/archives/libmysqlclient-dev_5.5.52-0ubuntu0.14.04.1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

there is a mysql server installed on this machine.
I use this cammond: sudo apt-get install libmysqlclient-dev

Any suggestions are thankful!

答:
i also met this error which confused me a lot.

```<code>root@ubuntu:~# ll  /usr/local/mysql/include/mysql
总用量 248
drwxr-xr-x 3 root mysql  4096  3月 30 23:10 ./
drwxr-xr-x 3 root mysql  4096  3月 30 14:44 ../
-rw-r--r-- 1 root mysql  1077  2月  2  2016 client_authentication.h
-rw-r--r-- 1 root mysql  1986  2月  2  2016 client_plugin.h.pp
-rw-r--r-- 1 root mysql  3105  2月  2  2016 com_data.h
-rw-r--r-- 1 root mysql  1198  2月  2  2016 get_password.h
-rw-r--r-- 1 root mysql  4281  2月  2  2016 group_replication_priv.h
-rw-r--r-- 1 root mysql  2167  2月  2  2016 innodb_priv.h
lrwxrwxrwx 1 root root     30  3月 30 18:31 mysql -> /usr/local/mysql/include/mysql/
</code>```

Please fix the circular soft link with a true headers directory.

```<code>root@ubuntu:~# ls /usr/local/mysql/include/mysql -d
/usr/local/mysql/include/mysql
root@ubuntu:~# ls /usr/local/mysql/include/mysql
client_authentication.h   my_compiler.h       mysqld_error.h        plugin_ftparser.h.pp        service_mysql_password_policy.h      service_thread_scheduler.h
client_plugin.h           my_config.h         mysql_embed.h         plugin_group_replication.h  service_mysql_string.h               sql_common.h
client_plugin.h.pp        my_config_x86_64.h  mysql.h               plugin.h                    service_parser.h                     sql_state.h
com_data.h                my_dbug.h           mysql_lex_string.h    plugin_keyring.h            service_rpl_transaction_ctx.h        sslopt-case.h
decimal.h                 my_dir.h            mysql_time.h          plugin_keyring.h.pp         service_rpl_transaction_write_set.h  sslopt-longopts.h
errmsg.h                  my_getopt.h         mysql_version.h       plugin_trace.h              service_rules_table.h                sslopt-vars.h
get_password.h            my_global.h         my_sys.h              plugin_validate_password.h  service_security_context.h           thread_pool_priv.h
group_replication_priv.h  my_list.h           my_xml.h              psi                         services.h                           thread_type.h
innodb_priv.h             my_net.h            plugin_audit.h        service_command.h           services.h.pp                        typelib.h
keycache.h                my_no_pthread.h     plugin_audit.h.pp     service_locking.h           service_srv_session.h
m_ctype.h                 my_pthread.h        plugin_auth_common.h  service_my_plugin_log.h     service_srv_session_info.h
m_string.h                mysql               plugin_auth.h         service_my_snprintf.h       service_thd_alloc.h
my_alloc.h                mysql_com.h         plugin_auth.h.pp      service_mysql_alloc.h       service_thd_engine_lock.h
my_attribute.h            mysqld_ername.h     plugin_ftparser.h     service_mysql_keyring.h     service_thd_wait.h
</code>```

Then, libmysqlclient-dev will be installed successfully.

Body:
when I install libmysqlclient-dev on ubuntu 14.04, I get this error:

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  libmysqlclient-dev
0 upgraded, 1 newly installed, 0 to remove and 96 not upgraded.
Need to get 0 B/866 kB of archives.
After this operation, 5,604 kB of additional disk space will be used.
(Reading database ... 63461 files and directories currently installed.)
Preparing to unpack .../libmysqlclient-dev_5.5.52-0ubuntu0.14.04.1_amd64.deb ...
Unpacking libmysqlclient-dev (5.5.52-0ubuntu0.14.04.1) ...
dpkg: error processing archive /var/cache/apt/archives/libmysqlclient-dev_5.5.52-0ubuntu0.14.04.1_amd64.deb (--unpack):
 unable to open '/usr/include/mysql/mysql/plugin.h.dpkg-new': No such file or directory
No apport report written because the error message indicates an issue on the local system
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Errors were encountered while processing:
 /var/cache/apt/archives/libmysqlclient-dev_5.5.52-0ubuntu0.14.04.1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

there is a mysql server installed on this machine.
I use this cammond: sudo apt-get install libmysqlclient-dev

Any suggestions are thankful!

Body:
i also met this error which confused me a lot.

root@ubuntu:~# ll  /usr/local/mysql/include/mysql
总用量 248
drwxr-xr-x 3 root mysql  4096  3月 30 23:10 ./
drwxr-xr-x 3 root mysql  4096  3月 30 14:44 ../
-rw-r--r-- 1 root mysql  1077  2月  2  2016 client_authentication.h
-rw-r--r-- 1 root mysql  1986  2月  2  2016 client_plugin.h.pp
-rw-r--r-- 1 root mysql  3105  2月  2  2016 com_data.h
-rw-r--r-- 1 root mysql  1198  2月  2  2016 get_password.h
-rw-r--r-- 1 root mysql  4281  2月  2  2016 group_replication_priv.h
-rw-r--r-- 1 root mysql  2167  2月  2  2016 innodb_priv.h
lrwxrwxrwx 1 root root     30  3月 30 18:31 mysql -> /usr/local/mysql/include/mysql/

Please fix the circular soft link with a true headers directory.

root@ubuntu:~# ls /usr/local/mysql/include/mysql -d
/usr/local/mysql/include/mysql
root@ubuntu:~# ls /usr/local/mysql/include/mysql
client_authentication.h   my_compiler.h       mysqld_error.h        plugin_ftparser.h.pp        service_mysql_password_policy.h      service_thread_scheduler.h
client_plugin.h           my_config.h         mysql_embed.h         plugin_group_replication.h  service_mysql_string.h               sql_common.h
client_plugin.h.pp        my_config_x86_64.h  mysql.h               plugin.h                    service_parser.h                     sql_state.h
com_data.h                my_dbug.h           mysql_lex_string.h    plugin_keyring.h            service_rpl_transaction_ctx.h        sslopt-case.h
decimal.h                 my_dir.h            mysql_time.h          plugin_keyring.h.pp         service_rpl_transaction_write_set.h  sslopt-longopts.h
errmsg.h                  my_getopt.h         mysql_version.h       plugin_trace.h              service_rules_table.h                sslopt-vars.h
get_password.h            my_global.h         my_sys.h              plugin_validate_password.h  service_security_context.h           thread_pool_priv.h
group_replication_priv.h  my_list.h           my_xml.h              psi                         services.h                           thread_type.h
innodb_priv.h             my_net.h            plugin_audit.h        service_command.h           services.h.pp                        typelib.h
keycache.h                my_no_pthread.h     plugin_audit.h.pp     service_locking.h           service_srv_session.h
m_ctype.h                 my_pthread.h        plugin_auth_common.h  service_my_plugin_log.h     service_srv_session_info.h
m_string.h                mysql               plugin_auth.h         service_my_snprintf.h       service_thd_alloc.h
my_alloc.h                mysql_com.h         plugin_auth.h.pp      service_mysql_alloc.h       service_thd_engine_lock.h
my_attribute.h            mysqld_ername.h     plugin_ftparser.h     service_mysql_keyring.h     service_thd_wait.h

Then, libmysqlclient-dev will be installed successfully.


问:
Search file for zip code in bash grep/sed
Trying to find each line containing a zip code using sed/grep
can't figure out what im missing, and cant find anything like what i am after.

zip code is 4 digits.

答:
UPDATE, wasn't far away, quite simple... grep '[0-9][0-9][0-9][0-9]'
probably is other ways as well.</p>


问:
Swift and params method default values
In the A.swift file I have

```<code>class A {
    func c(d: String = "abc") {
        // (1)
    }
}
</code>```

and in the B.swift file I have

```<code>class B {
   func z() {
      let aaa = A()
      aaa.c()
   }
}

extension A {
    func c(d: String = "abc", e: String = "123") {
        // (2)
    }
}
</code>```

Now, I'd like to know: in z()is called (1) or (2)? And how is it decided?

答:
Your class A has two functions, c(d:), and c(d:e:). In Swift, two functions can share the same “first name”, but be distinguished by their arguments. Hence, the “full name” of a function consists of its name and all of its parameter labels.

Replace the line

```<code>aaa.c()
</code>```

with

```<code>aaa.c(d:e:)()
</code>```

which calls the function c(d:e:) by its full name, and (2) will execute.

Note that aaa.c() is equivalent to aaa.c(d:)(). Swift appears to default to the function with the fewest parameters when the call is ambiguous; this may be the subject of a future Swift Evolution proposal, if it is not already.

Title: Swift and params method default values

Body:
In the A.swift file I have

class A {
    func c(d: String = "abc") {
        // (1)
    }
}

and in the B.swift file I have

class B {
   func z() {
      let aaa = A()
      aaa.c()
   }
}

extension A {
    func c(d: String = "abc", e: String = "123") {
        // (2)
    }
}

Now, I'd like to know: in z()is called (1) or (2)? And how is it decided?

Body:
Your class A has two functions, c(d:), and c(d:e:). In Swift, two functions can share the same “first name”, but be distinguished by their arguments. Hence, the “full name” of a function consists of its name and all of its parameter labels.

Replace the line

aaa.c()

with

aaa.c(d:e:)()

which calls the function c(d:e:) by its full name, and (2) will execute.

Note that aaa.c() is equivalent to aaa.c(d:)(). Swift appears to default to the function with the fewest parameters when the call is ambiguous; this may be the subject of a future Swift Evolution proposal, if it is not already.


问:
Visual Studio Text Box Wrap Function
How can I make my text wrap automatically to the next line when I am writing text in a textbox rather than keeps on typing in one line?</p>

答: I've done that but although the textbox grows the typing keeps going in a straight line!</p>

OwnerDisplayName: David Bonnici

Title: Visual Studio Text Box Wrap Function

LastEditorDisplayName: DanHerbert


问:
iphone Scrolling of tableview with custom cells is too slow
I have this problem when deploying my application on iphone, which wasn't detected on the simulator.

this the code of the cellforrow...

```<code>    - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSLog(@"beginning cellforRowAtIndexPath for section %d, and cell %d",[indexPath indexAtPosition:0],[indexPath indexAtPosition:1]);

    static NSString *MyIdentifier = @"MyIdentifier";
    NSString *fieldTitle;
    NSString*fieldDescription;
    [_stopWatch start];
    [PersonalSection GetField:&fieldTitle AndValue:&fieldDescription UsingIndexPath:indexPath AndPersonalInformation:_personalInfo];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"ViewContent" owner:self options:nil];
        cell = tvCell;
        self.tvCell=nil;

        ((UILabel*) [cell.contentView viewWithTag:1]).layer.cornerRadius=11;
        ((UILabel*) [cell.contentView viewWithTag:2]).layer.cornerRadius=11;
    }

    UILabel*mainLabel=(UILabel*) [cell.contentView viewWithTag:1];
    mainLabel.text=fieldTitle;
    //mainLabel.textColor = [UIColor colorWithRed:0.745 green:0.116 blue:0.176 alpha:1.0];

    UILabel*detailLabel=(UILabel*)[cell.contentView viewWithTag:2];
    detailLabel.text=fieldDescription;
    [_stopWatch stop];
    NSLog(@"---------End cellforRowAtIndexPath");

    return cell;
}
</code>```

the rest is for sections and it's like return 3 or 5 no real bottleneck there.
so i'm wondering what's slowing it so much.
now the data fetching "[PersonalSection GetField:&fieldTitle..." is rather fast, it takes on the iphone maximum 0.1 ms. The problem is somewhere else, i'm guessing there's a way for optimizing this code, and i'm wondering about the custom cell influence it's only a cell with label and textfield linked to this ViewController.
Any ideas.

答:
Ok, the main performance issue was rounding the corners of the subviews of the contentview.
using QuartzCore:

```<code>#import <QuartzCore/QuartzCore.h>
((UILabel*) [cell.contentView viewWithTag:1]).layer.cornerRadius=11;
</code>```

I removed those and decreased the sizes of the controls to fit inside the cell of a sectioned table. and now they look round but the textfield and label are not.
this has fixed my scrolling performance noticeably.
Thank you all for your help.

Body:
I have this problem when deploying my application on iphone, which wasn't detected on the simulator.

this the code of the cellforrow...

    - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSLog(@"beginning cellforRowAtIndexPath for section %d, and cell %d",[indexPath indexAtPosition:0],[indexPath indexAtPosition:1]);

    static NSString *MyIdentifier = @"MyIdentifier";
    NSString *fieldTitle;
    NSString*fieldDescription;
    [_stopWatch start];
    [PersonalSection GetField:&fieldTitle AndValue:&fieldDescription UsingIndexPath:indexPath AndPersonalInformation:_personalInfo];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"ViewContent" owner:self options:nil];
        cell = tvCell;
        self.tvCell=nil;

        ((UILabel*) [cell.contentView viewWithTag:1]).layer.cornerRadius=11;
        ((UILabel*) [cell.contentView viewWithTag:2]).layer.cornerRadius=11;
    }

    UILabel*mainLabel=(UILabel*) [cell.contentView viewWithTag:1];
    mainLabel.text=fieldTitle;
    //mainLabel.textColor = [UIColor colorWithRed:0.745 green:0.116 blue:0.176 alpha:1.0];

    UILabel*detailLabel=(UILabel*)[cell.contentView viewWithTag:2];
    detailLabel.text=fieldDescription;
    [_stopWatch stop];
    NSLog(@"---------End cellforRowAtIndexPath");

    return cell;
}

the rest is for sections and it's like return 3 or 5 no real bottleneck there.
so i'm wondering what's slowing it so much.
now the data fetching "[PersonalSection GetField:&fieldTitle..." is rather fast, it takes on the iphone maximum 0.1 ms. The problem is somewhere else, i'm guessing there's a way for optimizing this code, and i'm wondering about the custom cell influence it's only a cell with label and textfield linked to this ViewController.
Any ideas.

Body:
Ok, the main performance issue was rounding the corners of the subviews of the contentview.
using QuartzCore:

#import <QuartzCore/QuartzCore.h>
((UILabel*) [cell.contentView viewWithTag:1]).layer.cornerRadius=11;

I removed those and decreased the sizes of the controls to fit inside the cell of a sectioned table. and now they look round but the textfield and label are not.
this has fixed my scrolling performance noticeably.
Thank you all for your help.


答:
Try this: </p>

```<code>UPDATE Records
INNER JOIN GroupRecordLink ON Records.Pk = GroupRecordLink.RecordPk
INNER JOIN Groups ON GroupRecordLink.GroupPk = Groups.Pk AND Groups.ActiveStatus != 5
SET Records.ActiveStatus = 0,
    Records.TransactionStatus = 0,
    Records.LastUpdated = &
WHERE Records.ActiveStatus != 5
  AND Records.LastUpdated != &;
</code>```

Title: MySql convert nested SELECT IN queries into JOINs

Body:
Try this:

UPDATE Records
INNER JOIN GroupRecordLink ON Records.Pk = GroupRecordLink.RecordPk
INNER JOIN Groups ON GroupRecordLink.GroupPk = Groups.Pk AND Groups.ActiveStatus != 5
SET Records.ActiveStatus = 0,
    Records.TransactionStatus = 0,
    Records.LastUpdated = &
WHERE Records.ActiveStatus != 5
  AND Records.LastUpdated != &;


问:
Rails: Can't verify CSRF token authenticity when making a POST request
I want to make POST request to my local dev, like this:

```<code>  HTTParty.post('http://localhost:3000/fetch_heroku',
                :body => {:type => 'product'},)
</code>```

However, from the server console it reports

```<code>Started POST "/fetch_heroku" for 127.0.0.1 at 2016-02-03 23:33:39 +0800
  ActiveRecord::SchemaMigration Load (0.0ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by AdminController#fetch_heroku as */*
  Parameters: {"type"=>"product"}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 1ms
</code>```

Here is my controller and routes setup, it's quite simple.

```<code>  def fetch_heroku
    if params[:type] == 'product'
      flash[:alert] = 'Fetch Product From Heroku'
      Heroku.get_product
    end
  end

  post 'fetch_heroku' => 'admin#fetch_heroku'
</code>```

I'm not sure what I need to do? To turn off the CSRF would certainly work, but I think it should be my mistake when creating such an API.

Is there any other setup I need to do?

答:
Another way to turn off CSRF that won't render a null session is to add:

```<code>skip_before_action :verify_authenticity_token
</code>```

in your Rails Controller. This will ensure you still have access to session info.

Again, make sure you only do this in API controllers or in other places where CSRF protection doesn't quite apply.

Body:
I want to make POST request to my local dev, like this:

  HTTParty.post('http://localhost:3000/fetch_heroku',
                :body => {:type => 'product'},)

However, from the server console it reports

Started POST "/fetch_heroku" for 127.0.0.1 at 2016-02-03 23:33:39 +0800
  ActiveRecord::SchemaMigration Load (0.0ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by AdminController#fetch_heroku as */*
  Parameters: {"type"=>"product"}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 1ms

Here is my controller and routes setup, it's quite simple.

  def fetch_heroku
    if params[:type] == 'product'
      flash[:alert] = 'Fetch Product From Heroku'
      Heroku.get_product
    end
  end

  post 'fetch_heroku' => 'admin#fetch_heroku'

I'm not sure what I need to do? To turn off the CSRF would certainly work, but I think it should be my mistake when creating such an API.

Is there any other setup I need to do?

Body:
Another way to turn off CSRF that won't render a null session is to add:

skip_before_action :verify_authenticity_token

in your Rails Controller. This will ensure you still have access to session info.

Again, make sure you only do this in API controllers or in other places where CSRF protection doesn't quite apply.


问:
Kafka Consumer default Group Id
I'm working with Apache Kafka and its Java client and I see that messages are load balanced across different Kafka Consumers belonging to the same group (i.e. sharing the same group id).

In my application I need all consumers to read all messages.

So I have several questions:

if I don't set any group id in the Consumer Properties, what group id will the Kafka Consumer be given?

Is there a single default value?

Does the client create a random value each time?

Do I need to create a different id for each consumer to be sure that each one receives all messages?

EDIT:
Thank you for your answers.

You are correct: if one doesn't set the consumer group id, Kafka should complain.

However, I have found out that if the group id is null, the Java client sets it to the empty string "" to avoid problems.
So apparently that is the default value I was looking for.

Surprising all my consumers, even if I don't set their groupIds (and so they are all with groupId == "") seem to receive all the messages the producer writes.

I still can't explain this: any suggestions?

答:
if I don't set any group id in the Consumer Properties, what group id will the Kafka Consumer be given?

The kafka consumer will not have any consumer group. Instead you will get this error : The configured groupId is invalid

Is there a single default value?

Yes, you can see the consumer.properties file of kafka for reference. The default consumer group id is: group.id=test-consumer-group

Does the client create a random value each time?

No, groupId seems to be mandatory for Java client starting Kafka 0.9.0.x consumers. You can refer to this JIRA: https://issues.apache.org/jira/browse/KAFKA-2648

Do I need to create a different id for each consumer to be sure that each one receives all messages?

Yes, if all consumers use the same group id, messages in a topic are distributed among those consumers. In other words, each consumer will get a non-overlapping subset of the messages. Having more consumers in the same group increases the degree of parallelism and the overall throughput of consumption. On the other hand, if each consumer is in its own group, each consumer will get a full copy of all messages.

Title: Kafka Consumer default Group Id


问:
how to get Repeated character from String and how many times it repeated
Hello I'm new in programming, and sorry for my English.
So question is, for example: we have string "cabbaa"
and I should get 1c1a2b2a

which means: 1 times'c', 1 times'a', 2 times'b', 2 times'a'

I could write code which gets 1c3a2b:

```<code>public class test {

    static int i,j,k,c=0,w;
    static char m;

    public static void main(String[] args) {
        frequencycount("cabbaa");
    }

    static void frequencycount(String s)

    {

        char[] z=new char[s.length()];
        for(w=0;w<s.length();w++)
        z[w]=s.charAt(w);
        for(i=0;i<w;i++)
        {
            char ch=z[i];
            for(j=i+1;j<w;j++)
            {
                if(z[j]==ch)
                {
                    for(k=j;k<(w-1);k++)
                    z[k]=z[k+1];
                    w--;
                    j=i;
                }
            }
        }

        int[] t=new int[w];
        for(i=0;i<w;i++)
        {
            for(j=0,c=0;j<s.length();j++)
            {
                if(z[i]==s.charAt(j))
                c++;
            }
            t[i]=c ;
            System.out.print(c+""+z[i]);
        }
    }

}
</code>```

in this code I guess I compared all characters overall from string and got 1c3a2b, but I should get 1c1a2b2a.

Any help appreciated.

答:
This should do the job:</p>

```<code>public class test {
    public static void main(String[] args) {
        frequencycount("cabbaa");
    }

    static void frequencycount(String s) {
        StringBuilder output = new StringBuilder();
        Character previousCharacter = null;
        int counter = -1;

        for (Character c : s.toCharArray()) {
            if (c.equals(previousCharacter)) {
                counter++;
            } else {
                if (previousCharacter != null) {
                    output.append(counter);
                    output.append(previousCharacter);
                }
                counter = 1;
                previousCharacter = c;
            }
        }

        if (previousCharacter != null) {
            output.append(counter);
            output.append(previousCharacter);
        }

        System.out.println("Res: " + output);
    }
}
</code>```

Body:
Hello I'm new in programming, and sorry for my English.
So question is, for example: we have string "cabbaa"
and I should get 1c1a2b2a

which means: 1 times'c', 1 times'a', 2 times'b', 2 times'a'

I could write code which gets 1c3a2b:

public class test {

    static int i,j,k,c=0,w;
    static char m;

    public static void main(String[] args) {
        frequencycount("cabbaa");
    }

    static void frequencycount(String s)

    {

        char[] z=new char[s.length()];
        for(w=0;w<s.length();w++)
        z[w]=s.charAt(w);
        for(i=0;i<w;i++)
        {
            char ch=z[i];
            for(j=i+1;j<w;j++)
            {
                if(z[j]==ch)
                {
                    for(k=j;k<(w-1);k++)
                    z[k]=z[k+1];
                    w--;
                    j=i;
                }
            }
        }

        int[] t=new int[w];
        for(i=0;i<w;i++)
        {
            for(j=0,c=0;j<s.length();j++)
            {
                if(z[i]==s.charAt(j))
                c++;
            }
            t[i]=c ;
            System.out.print(c+""+z[i]);
        }
    }

}

in this code I guess I compared all characters overall from string and got 1c3a2b, but I should get 1c1a2b2a.

Any help appreciated.

Body:
This should do the job:

public class test {
    public static void main(String[] args) {
        frequencycount("cabbaa");
    }

    static void frequencycount(String s) {
        StringBuilder output = new StringBuilder();
        Character previousCharacter = null;
        int counter = -1;

        for (Character c : s.toCharArray()) {
            if (c.equals(previousCharacter)) {
                counter++;
            } else {
                if (previousCharacter != null) {
                    output.append(counter);
                    output.append(previousCharacter);
                }
                counter = 1;
                previousCharacter = c;
            }
        }

        if (previousCharacter != null) {
            output.append(counter);
            output.append(previousCharacter);
        }

        System.out.println("Res: " + output);
    }
}