问:
Animation completion block goes haywire after dismissing view

I have a detail viewcontroller that contains a repeating carousel with an  animating image view like so:

```<code>func animateCarousel1(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 1 complete")
        self.animateCarousel2()
                  })
    }
func animateCarousel2(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 2 complete")
        self.animateCarousel1()
                  })
    }
</code>```

Upon popping this view and returning to the parent view, I see that in the debug console, the functions are continuing to be called in the background, repeatedly and simultaneously, infinitely.

CPU usage also jumps to 90% in the simulator as well.

Is there some sort of deinit I need to do before popping the viewcontroller? I can't seem to wrap my head around this one.

答:
It's possible this solve the problem you can see this post link here

Use on deinit() controller method or viewDidDissapear(), try the following code

```<code>deinit {
    print("deinit \(NSStringFromClass(self.classForCoder).components(separatedBy: ".").last ?? "")") // print viewcontroller deallocated
    self.view_for_remove_animations.layer.removeAllAnimations() // Forze delete animations
}
</code>```

OR

```<code> override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    print("viewDidDisappear \(NSStringFromClass(self.classForCoder).components(separatedBy: ".").last ?? "")") // print viewcontroller deallocated
    self.view_for_remove_animations.layer.removeAllAnimations() // Forze delete animations
}
</code>```

Try it, and send feedback

Body:
I have a detail viewcontroller that contains a repeating carousel with an  animating image view like so:

func animateCarousel1(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 1 complete")
        self.animateCarousel2()
                  })
    }
func animateCarousel2(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 2 complete")
        self.animateCarousel1()
                  })
    }

Upon popping this view and returning to the parent view, I see that in the debug console, the functions are continuing to be called in the background, repeatedly and simultaneously, infinitely.

CPU usage also jumps to 90% in the simulator as well.

Is there some sort of deinit I need to do before popping the viewcontroller? I can't seem to wrap my head around this one.

Body:
It's possible this solve the problem you can see this post link here

Use on deinit() controller method or viewDidDissapear(), try the following code

deinit {
    print("deinit \(NSStringFromClass(self.classForCoder).components(separatedBy: ".").last ?? "")") // print viewcontroller deallocated
    self.view_for_remove_animations.layer.removeAllAnimations() // Forze delete animations
}

OR

 override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    print("viewDidDisappear \(NSStringFromClass(self.classForCoder).components(separatedBy: ".").last ?? "")") // print viewcontroller deallocated
    self.view_for_remove_animations.layer.removeAllAnimations() // Forze delete animations
}

Try it, and send feedback


来源: stackexchange

问:
How can I access database mysql on the server staging?
Mysql gui tools that I use to connect to my database is sql yog

I connect use data from env laravel

If I connect with data from env localhost, it works

If I connect with data from staging server, it does not works

My env localhost like this :

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myshop
DB_USERNAME=root
DB_PASSWORD=secret
</code>```

I try in sql yog like this :

I use db host, db port, username and password from env to connect in sql yog like that

It works

My env server staging like this :

```<code>DB_CONNECTION=mysql
DB_HOST=xx.xxx.xx.xx
DB_PORT=3306
DB_DATABASE=myshop
DB_USERNAME=forge
DB_PASSWORD=xxxxxxxxxxxxxxx
</code>```

I use the data to connect with sql yog

There exist error like this :

How can I solve this error?

答:
if mysql-server on the remote server, the firstly you must be add your ip mysql conf

https://support.rackspace.com/how-to/mysql-connect-to-your-database-remotely/

ContentLicense: CC BY-SA 3.0

Body:
Mysql gui tools that I use to connect to my database is sql yog

I connect use data from env laravel

If I connect with data from env localhost, it works

If I connect with data from staging server, it does not works

My env localhost like this :

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myshop
DB_USERNAME=root
DB_PASSWORD=secret

I try in sql yog like this :

I use db host, db port, username and password from env to connect in sql yog like that

It works

My env server staging like this :

DB_CONNECTION=mysql
DB_HOST=xx.xxx.xx.xx
DB_PORT=3306
DB_DATABASE=myshop
DB_USERNAME=forge
DB_PASSWORD=xxxxxxxxxxxxxxx

I use the data to connect with sql yog

There exist error like this :

How can I solve this error?


问:
SQL : Limit the results of one table
I have a simple query:

```<code>SELECT
    c.nom AS race_name,
    r.nom_coureur AS player_name,
    r.prenom_coureur AS player_name_first
FROM pourvelobsx.calendrier AS c
INNER JOIN pourvelobsx.resultat_autre AS r
    ON r.identifiant_epreuve = c.identifiant
WHERE nom_etape = "final"
ORDER BY c.id DESC
LIMIT 5
</code>```

The query returns 5 rows:

```<code>+------------------+-------------+-------------------+
| race_name        | player_name | player_name_first |
+------------------+-------------+-------------------+
| Watashi wa Alex  | BARBAS      | Yoann             |
| Watashi wa Alex  | AHLSTRAND   | Jonas             |
| Watashi wa Alex  | ACEVEDO     | Janier Alexis     |
| Tour de La Baule | CHAVANEL    | Sylvain           |
| Tour de La Baule | SANCHEZ     | Samuel            |
+------------------+-------------+-------------------+
</code>```

I was wondering, how can I limit the result of races ("calendrier" table) and not the global row result ?

Like this:

```<code>+------------------+-------------+-------------------+
| race_name        | player_name | player_name_first |
+------------------+-------------+-------------------+
| Watashi wa Alex  | BARBAS      | Yoann             |
| Watashi wa Alex  | AHLSTRAND   | Jonas             |
| Watashi wa Alex  | ACEVEDO     | Janier Alexis     |
| Tour de La Baule | CHAVANEL    | Sylvain           |
| Tour de La Baule | SANCHEZ     | Samuel            |
| Tour de La Groin | HELLO       | Calvin            |
| Tour de La Groin | ESTEBEZ     | Millo             |
| Tour de France   | SANCHEZ     | Samuel            |
| Tour de France   | SICKED      | Alex              |
| Tour d'Espagne   | VILLIOD     | Fred              |
| Tour d'Espagne   | CRACHER     | Jordan            |
| Tour d'Espagne   | ELBANTI     | Maxime            |
| Tour d'Espagne   | BOKEDRON    | Yohan             |
+------------------+-------------+-------------------+
</code>```

So I only have 5 races not limiting row. I tried DISTINCT but unsuccessfully.

答:
I believe you want something like this</p>

```<code>SELECT
  c.nom AS race_name,
  r.nom_coureur AS player_name,
  r.prenom_coureur AS player_name_first
FROM pourvelobsx.calendrier AS c
INNER JOIN pourvelobsx.resultat_autre AS r ON r.identifiant_epreuve = c.identifiant
INNER JOIN
(
  SELECT c.nom
  FROM pourvelobsx.calendrier AS c
  INNER JOIN pourvelobsx.resultat_autre AS r ON r.identifiant_epreuve = c.identifiant
  WHERE nom_etape = "final"
  GROUP BY c.nom
  ORDER BY c.id DESC
  LIMIT 5
) t ON t.nom = c.nom
WHERE nom_etape = "final"
</code>```

Title: SQL : Limit the results of one table

Body:
I have a simple query:

SELECT
    c.nom AS race_name,
    r.nom_coureur AS player_name,
    r.prenom_coureur AS player_name_first
FROM pourvelobsx.calendrier AS c
INNER JOIN pourvelobsx.resultat_autre AS r
    ON r.identifiant_epreuve = c.identifiant
WHERE nom_etape = "final"
ORDER BY c.id DESC
LIMIT 5

The query returns 5 rows:

+------------------+-------------+-------------------+
| race_name        | player_name | player_name_first |
+------------------+-------------+-------------------+
| Watashi wa Alex  | BARBAS      | Yoann             |
| Watashi wa Alex  | AHLSTRAND   | Jonas             |
| Watashi wa Alex  | ACEVEDO     | Janier Alexis     |
| Tour de La Baule | CHAVANEL    | Sylvain           |
| Tour de La Baule | SANCHEZ     | Samuel            |
+------------------+-------------+-------------------+

I was wondering, how can I limit the result of races ("calendrier" table) and not the global row result ?

Like this:

+------------------+-------------+-------------------+
| race_name        | player_name | player_name_first |
+------------------+-------------+-------------------+
| Watashi wa Alex  | BARBAS      | Yoann             |
| Watashi wa Alex  | AHLSTRAND   | Jonas             |
| Watashi wa Alex  | ACEVEDO     | Janier Alexis     |
| Tour de La Baule | CHAVANEL    | Sylvain           |
| Tour de La Baule | SANCHEZ     | Samuel            |
| Tour de La Groin | HELLO       | Calvin            |
| Tour de La Groin | ESTEBEZ     | Millo             |
| Tour de France   | SANCHEZ     | Samuel            |
| Tour de France   | SICKED      | Alex              |
| Tour d'Espagne   | VILLIOD     | Fred              |
| Tour d'Espagne   | CRACHER     | Jordan            |
| Tour d'Espagne   | ELBANTI     | Maxime            |
| Tour d'Espagne   | BOKEDRON    | Yohan             |
+------------------+-------------+-------------------+

So I only have 5 races not limiting row. I tried DISTINCT but unsuccessfully.

Body:
I believe you want something like this

SELECT
  c.nom AS race_name,
  r.nom_coureur AS player_name,
  r.prenom_coureur AS player_name_first
FROM pourvelobsx.calendrier AS c
INNER JOIN pourvelobsx.resultat_autre AS r ON r.identifiant_epreuve = c.identifiant
INNER JOIN
(
  SELECT c.nom
  FROM pourvelobsx.calendrier AS c
  INNER JOIN pourvelobsx.resultat_autre AS r ON r.identifiant_epreuve = c.identifiant
  WHERE nom_etape = "final"
  GROUP BY c.nom
  ORDER BY c.id DESC
  LIMIT 5
) t ON t.nom = c.nom
WHERE nom_etape = "final"


问:
React-Native I keep getting "Your binary is not optimized for iPhone 5" but I have the correct images?
I keep getting "Your binary is not optimized for iPhone 5,  New iPhone apps and app updates submitted must support the 4-inch display on iPhone 5 and must include a launch image referenced in the Info.plist under UILaunchImages with a UILaunchImageSize value set to {320, 568}" but I have the correct images, really not sure what is going on here.

Here are my images

答:
I fixed this issue by adding a storyboard as the LaunchScreen.

Follow this link https://stackoverflow.com/a/37952587/3946689


问:
How to get the row where it's value has a continuous decrease compared to the last two rows in python

I have a data frame create by pandas like this:

```<code>import pandas as pd
df = pd.DataFrame({'name':['q1','q2','q3','q4','q5'],'vlue':[17,20,16,13,17]})

   name vlue
0   q1  17
1   q2  20
2   q3  16
3   q4  13
4   q5  17
</code>```

I want the row that has a continuous decrease compared to the last two rows.

In this case, the value of q4 is 13, it's decreased compared to q3's value 16 and q2's  value 20.
so the answer should be q4.

what's an efficient way to do this?

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

```<code>df.loc[(df.vlue<df.vlue.shift(1))&(df.vlue.shift(1)<df.vlue.shift(2)), 'name']
#3    q4
#Name: name, dtype: object
</code>```

Body:
I have a data frame create by pandas like this:

import pandas as pd
df = pd.DataFrame({'name':['q1','q2','q3','q4','q5'],'vlue':[17,20,16,13,17]})

   name vlue
0   q1  17
1   q2  20
2   q3  16
3   q4  13
4   q5  17

I want the row that has a continuous decrease compared to the last two rows.

In this case, the value of q4 is 13, it's decreased compared to q3's value 16 and q2's  value 20.
so the answer should be q4.

what's an efficient way to do this?

Body:
This should do the trick:

df.loc[(df.vlue<df.vlue.shift(1))&(df.vlue.shift(1)<df.vlue.shift(2)), 'name']
#3    q4
#Name: name, dtype: object


问:
Is it possible to remove the Contents heading in RMarkdown .pdf?
I am using RStudio and RMarkdown to generate reports. I now wish to edit parts of the document. My RMarkdown document is as follows:

```<code>--
title: <center> <h1>Call Centre Report</h1> </center>
mainfont: Arial
output:
  pdf_document:
    latex_engine: xelatex
sansfont: Arial
fig_crop: false
toc: true
classoption: landscape
fontsize: 14pt
geometry: margin=0.5in
header-includes:
- \usepackage{booktabs}
---
<style>
  .main-container {
    max-width: 1200px !important;
  }
</style>

```{r global_options, R.options=knitr::opts_chunk$set(warning=FALSE, message=FALSE)}
```
\newpage
# Iris
```{r fig.width=18, fig.height=7, echo=FALSE, comment=" "}
library(ggplot2)
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
   geom_point() +
   theme_classic()
```
<br>
<br>
```{r, echo=FALSE, results='asis'}
library(knitr)
library(xtable)

t1 <- kable(subset(iris, Sepal.Length=="5.1", select = Petal.Length:Species),
            format = "latex", booktabs = TRUE, row.names = FALSE)
t2 <- kable(subset(chickwts, feed=="horsebean", select = weight:feed),
            format = "latex", booktabs = TRUE, row.names = FALSE)
t3 <- kable(subset(mtcars, gear=="4", select = disp:wt),
            format = "latex", booktabs = TRUE, row.names = FALSE, digits=2)

cat(c("\\begin{table}[!htb]
    \\begin{minipage}{.35\\linewidth}
      \\centering",
        t1,
    "\\end{minipage}%
    \\begin{minipage}{.35\\linewidth}
      \\centering",
        t2,
    "\\end{minipage}%
    \\begin{minipage}{.35\\linewidth}
      \\centering",
        t3,
    "\\end{minipage}
\\end{table}"
))
```
</code>```

Is it possible to remove the heading "Contents" on the TOC page? I wish to keep all other headings on this page but remove only the "Contents" heading.

I know that I can edit the "Table of Contents" by the following line:

```<code>- \renewcommand{\contentsname}{Some Text Here}
</code>```

But simply leaving it blank (below), still takes up space:

```<code>- \renewcommand{\contentsname}{}
</code>```

答: you could try to delete the line toc:true in your YAML metadata. It worked on my case.

Body:
I am using RStudio and RMarkdown to generate reports. I now wish to edit parts of the document. My RMarkdown document is as follows:

--
title:
Call Centre Report

mainfont: Arial
output:
  pdf_document:
    latex_engine: xelatex
sansfont: Arial
fig_crop: false
toc: true
classoption: landscape
fontsize: 14pt
geometry: margin=0.5in
header-includes:
- \usepackage{booktabs}
---

```{r global_options, R.options=knitr::opts_chunk$set(warning=FALSE, message=FALSE)}
```
\newpage
# Iris
```{r fig.width=18, fig.height=7, echo=FALSE, comment=" "}
library(ggplot2)
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
   geom_point() +
   theme_classic()
```

```{r, echo=FALSE, results='asis'}
library(knitr)
library(xtable)

t1 <- kable(subset(iris, Sepal.Length=="5.1", select = Petal.Length:Species),
            format = "latex", booktabs = TRUE, row.names = FALSE)
t2 <- kable(subset(chickwts, feed=="horsebean", select = weight:feed),
            format = "latex", booktabs = TRUE, row.names = FALSE)
t3 <- kable(subset(mtcars, gear=="4", select = disp:wt),
            format = "latex", booktabs = TRUE, row.names = FALSE, digits=2)

cat(c("\\begin{table}[!htb]
    \\begin{minipage}{.35\\linewidth}
      \\centering",
        t1,
    "\\end{minipage}%
    \\begin{minipage}{.35\\linewidth}
      \\centering",
        t2,
    "\\end{minipage}%
    \\begin{minipage}{.35\\linewidth}
      \\centering",
        t3,
    "\\end{minipage}
\\end{table}"
))
```

Is it possible to remove the heading "Contents" on the TOC page? I wish to keep all other headings on this page but remove only the "Contents" heading.

I know that I can edit the "Table of Contents" by the following line:

- \renewcommand{\contentsname}{Some Text Here}

But simply leaving it blank (below), still takes up space:

- \renewcommand{\contentsname}{}


问:
Why I user imageview and Change Recurce it,I get "out of memory"Error
I Change Image view  For 19 Times In switch And Get This Error
I Change It with Button Click And Change Resource of Image view
When I Debug It I Get Out Of Memory Error</p>

答:
Glide

Use this for loading and displaying Images in ImageView. It will load the images efficiently and you wont get any OutOfMemoryError


问:
WordPress: Subquery with table join
A query sorts posts by pageviews - this works perfectly. But I need to join wp_term_taxonomy.term_taxonomy_id too. Like this:

```<code>WHERE wp_term_taxonomy.term_taxonomy_id ='2'
</code>```

the code:

```<code>$qstr = "
    SELECT wposts.*
    FROM $wpdb->posts wposts,
    (select postid, sum(pageviews) pageviews
    from $pageviews_table
    group by postid) pv
    WHERE wposts.post_status = 'publish'
    AND wposts.post_type = 'post'
    AND wposts.ID = pv.postid
    ORDER BY pv.pageviews DESC
    LIMIT 10
 ";
</code>```

I tried this:

```<code>$qstr = "
    SELECT wposts.*, wp_term_taxonomy.term_taxonomy_id
    FROM $wpdb->posts wposts,
    (select postid, sum(pageviews) pageviews
     from $pageviews_table
     group by postid) pv
    WHERE wposts.post_status = 'publish'

    INNER JOIN
             wp_term_taxonomy
             AND xxxx // dont know
    WHERE    wp_term_taxonomy.term_taxonomy_id = '13'

    AND wposts.post_type = 'post'
    AND wposts.ID = pv.postid
    ORDER BY pv.pageviews DESC
    LIMIT 10
 ";
</code>```

答:
Why are you using join? Won't this work for you:</p>

```<code>$qstr = "
SELECT wposts.*, wp_term_taxonomy.term_taxonomy_id
FROM $wpdb->posts wposts,
(select postid, sum(pageviews) pageviews
 from $pageviews_table
 group by postid) pv, wp_term_taxonomy
WHERE wposts.post_status = 'publish'
AND    wp_term_taxonomy.term_taxonomy_id = '13'
AND wposts.post_type = 'post'
AND wposts.ID = pv.postid
ORDER BY pv.pageviews DESC
LIMIT 10 ";
</code>```

ContentLicense: CC BY-SA 2.5

Title: WordPress: Subquery with table join

Body:
A query sorts posts by pageviews - this works perfectly. But I need to join wp_term_taxonomy.term_taxonomy_id too. Like this:

WHERE wp_term_taxonomy.term_taxonomy_id ='2'

the code:

$qstr = "
    SELECT wposts.*
    FROM $wpdb->posts wposts,
    (select postid, sum(pageviews) pageviews
    from $pageviews_table
    group by postid) pv
    WHERE wposts.post_status = 'publish'
    AND wposts.post_type = 'post'
    AND wposts.ID = pv.postid
    ORDER BY pv.pageviews DESC
    LIMIT 10
 ";

I tried this:

$qstr = "
    SELECT wposts.*, wp_term_taxonomy.term_taxonomy_id
    FROM $wpdb->posts wposts,
    (select postid, sum(pageviews) pageviews
     from $pageviews_table
     group by postid) pv
    WHERE wposts.post_status = 'publish'

    INNER JOIN
             wp_term_taxonomy
             AND xxxx // dont know
    WHERE    wp_term_taxonomy.term_taxonomy_id = '13'

    AND wposts.post_type = 'post'
    AND wposts.ID = pv.postid
    ORDER BY pv.pageviews DESC
    LIMIT 10
 ";

Body:
Why are you using join? Won't this work for you:

$qstr = "
SELECT wposts.*, wp_term_taxonomy.term_taxonomy_id
FROM $wpdb->posts wposts,
(select postid, sum(pageviews) pageviews
 from $pageviews_table
 group by postid) pv, wp_term_taxonomy
WHERE wposts.post_status = 'publish'
AND    wp_term_taxonomy.term_taxonomy_id = '13'
AND wposts.post_type = 'post'
AND wposts.ID = pv.postid
ORDER BY pv.pageviews DESC
LIMIT 10 ";


问:
Laravel Route based on query string
Currently in my routes.php file I've got the following:

```<code>Route::get('import', 'Controller@import');
</code>```

But as for the requests they'd be sent in the following way:

```<code>/import?flag=0&data={} //flag could be anything from 0-4 & data is json encoded info
/import?flag=5&data={}
/import?flag=6&data={}
</code>```

These are the only 3 requests that I'd have, I'm aware that Laravel supports where method on the route but only regular expressions but not on query parameters, is there a solution for this that I'm overlooking?

The expression method would be something like so:

```<code>Route::get('import?flag={id}&data={data}', 'Controller@importFlag0-4')->where('id', '<=', '4');
Route::get('import?flag={id}&data={data}', 'Controller@importFlag5')->where('id', '5');
Route::get('import?flag={id}&data={data}', 'Controller@importFlag6')->where('id', '6');
</code>```

答:
As mentioned by @lagbox, why would you need different routes, when you could handle all those routes conditionals in the import() method

```<code>public function import(Request $request)
{
    $flag = $request->get('flag');
    $data = $request->get('data');
    if ($flag <= 4) {
        $this->importFlagTillFour($flag, $data)
    }
    if ($flag == 5) {
        $this->importFlagFive($flag, $data)
    }
    if ($flag == 6) {
        $this->importFlagSix($flag, $data)
    }
}
</code>```

and declare the called methods in the same class

```<code>public function importFlagTillFour($flag, $data) {}
public function importFlagFive($flag, $data) {}
public function importFlagSix($flag, $data) {}
</code>```

Title: Laravel Route based on query string

Body:
Currently in my routes.php file I've got the following:

Route::get('import', 'Controller@import');

But as for the requests they'd be sent in the following way:

/import?flag=0&data={} //flag could be anything from 0-4 & data is json encoded info
/import?flag=5&data={}
/import?flag=6&data={}

These are the only 3 requests that I'd have, I'm aware that Laravel supports where method on the route but only regular expressions but not on query parameters, is there a solution for this that I'm overlooking?

The expression method would be something like so:

Route::get('import?flag={id}&data={data}', 'Controller@importFlag0-4')->where('id', '<=', '4');
Route::get('import?flag={id}&data={data}', 'Controller@importFlag5')->where('id', '5');
Route::get('import?flag={id}&data={data}', 'Controller@importFlag6')->where('id', '6');

Body:
As mentioned by @lagbox, why would you need different routes, when you could handle all those routes conditionals in the import() method

public function import(Request $request)
{
    $flag = $request->get('flag');
    $data = $request->get('data');
    if ($flag <= 4) {
        $this->importFlagTillFour($flag, $data)
    }
    if ($flag == 5) {
        $this->importFlagFive($flag, $data)
    }
    if ($flag == 6) {
        $this->importFlagSix($flag, $data)
    }
}

and declare the called methods in the same class

public function importFlagTillFour($flag, $data) {}
public function importFlagFive($flag, $data) {}
public function importFlagSix($flag, $data) {}


问:
InputMismatchException when scanning
I'm doing an assignment trying to manipulate an array of ints (grades). It's crashing and I can't figure out why. I don't know if it has something to do with the file input, output? the error log seems to be saying it isn't even getting past running the method onclick.

main activity code:

```<code>package com.example.brandon.lab5;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
import android.content.res.*;
import java.io.*;
import java.util.*;
import java.util.Scanner;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void arrayChange(View view)
        throws IOException {
            EditText et;
            TextView tv;
            String fileName;
            tv = (TextView) findViewById(R.id.text_main);
            et = (EditText) findViewById(R.id.edit_infile);
            int n=0;

            AssetManager assetManager = getAssets();
            fileName = (et.getText().toString());
            Scanner fsc = new Scanner(assetManager.open(fileName));
            int grades[] = new int[100];
            while(fsc.hasNext()) {
                grades[n] = fsc.nextInt();
                n++;
            }
            int fromIndex = 0;
            int toIndex = grades.length;
            int size = grades.length;

            double cubicMean = 0;
            double num = 0;
            double deno = size;
            while(size>0) {
                num+=Math.pow(grades[size], 3);
                size--;
            }
            cubicMean = Math.cbrt((num/deno));

            Arrays.sort(grades, fromIndex, toIndex);

            double med = 0;
            double temp = Math.ceil(grades[(toIndex/2)]);
            if(toIndex%2==0) {
                med = ((grades[toIndex/2] + grades[(toIndex/2)+1])/2);
            }
            else {
                med = temp;
            }

            tv.append("Number of grades: " + grades.length);
            tv.append("Highest grade: " + grades[0]);
            tv.append("Cubed root of the grades: " + cubicMean);
            tv.append("Median grade: " + med);

            File outfile = new File(getExternalFilesDir(null), "out.txt");
            FileWriter fw = new FileWriter(outfile);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
            while(size>0) {
                pw.println(grades[size]);
                size--;
            }
            pw.close();
        }
    }
</code>```

manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.brandon.lab5">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</code>```

XML

```<code><?xml version="1.0" encoding="utf-8"?>

<!-- your context in the "tools:context" field below.  See YYY -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.brandon.lab5.MainActivity"
    tools:showIn="@layout/activity_main">

    <EditText
        android:id="@+id/edit_infile"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="@string/edit_infile" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="arrayChange"
        android:text="Start" />

    <!-- Spacing and horizontal rule (line) to separate Button from TextView -->

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="0.5dp"
        android:background="#000000" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <ScrollView
        android:id="@+id/SCROLLER_ID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:fillViewport="true">

        <TextView
            android:id="@+id/text_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="..." />

    </ScrollView>

</LinearLayout>
</code>```

logcat:

```<code>       --------- beginning of crash
12-04 23:16:22.456 3056-3056/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.brandon.lab5, PID: 3056
                                                 java.lang.IllegalStateException: Could not execute method for android:onClick
                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                     at android.view.View.performClick(View.java:4780)
                                                     at android.view.View$PerformClick.run(View.java:19866)
                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                  Caused by: java.lang.reflect.InvocationTargetException
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                     at android.view.View.performClick(View.java:4780)
                                                     at android.view.View$PerformClick.run(View.java:19866)
                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                  Caused by: java.util.InputMismatchException
                                                     at java.util.Scanner.next(Scanner.java:973)
                                                     at java.util.Scanner.nextInt(Scanner.java:1318)
                                                     at java.util.Scanner.nextInt(Scanner.java:1282)
                                                     at com.example.brandon.lab5.MainActivity.arrayChange(MainActivity.java:72)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                     at android.view.View.performClick(View.java:4780)
                                                     at android.view.View$PerformClick.run(View.java:19866)
                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
12-04 23:16:22.457 1514-1646/system_process W/ActivityManager:
</code>```

答:
Here's the problematic code:

```
<code>
    while(fsc.hasNext()) {
        grades[n] = fsc.nextInt();
        n++;
    }
</code>
```

From the docs of Scanner#nextInt():

Throws

InputMismatchException if the next token does not match the Integer regular expression, or is out of range

Double-check your file content.

Title: InputMismatchException when scanning

Body:
I'm doing an assignment trying to manipulate an array of ints (grades). It's crashing and I can't figure out why. I don't know if it has something to do with the file input, output? the error log seems to be saying it isn't even getting past running the method onclick.

main activity code:

package com.example.brandon.lab5;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
import android.content.res.*;
import java.io.*;
import java.util.*;
import java.util.Scanner;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void arrayChange(View view)
        throws IOException {
            EditText et;
            TextView tv;
            String fileName;
            tv = (TextView) findViewById(R.id.text_main);
            et = (EditText) findViewById(R.id.edit_infile);
            int n=0;

            AssetManager assetManager = getAssets();
            fileName = (et.getText().toString());
            Scanner fsc = new Scanner(assetManager.open(fileName));
            int grades[] = new int[100];
            while(fsc.hasNext()) {
                grades[n] = fsc.nextInt();
                n++;
            }
            int fromIndex = 0;
            int toIndex = grades.length;
            int size = grades.length;

            double cubicMean = 0;
            double num = 0;
            double deno = size;
            while(size>0) {
                num+=Math.pow(grades[size], 3);
                size--;
            }
            cubicMean = Math.cbrt((num/deno));

            Arrays.sort(grades, fromIndex, toIndex);

            double med = 0;
            double temp = Math.ceil(grades[(toIndex/2)]);
            if(toIndex%2==0) {
                med = ((grades[toIndex/2] + grades[(toIndex/2)+1])/2);
            }
            else {
                med = temp;
            }

            tv.append("Number of grades: " + grades.length);
            tv.append("Highest grade: " + grades[0]);
            tv.append("Cubed root of the grades: " + cubicMean);
            tv.append("Median grade: " + med);

            File outfile = new File(getExternalFilesDir(null), "out.txt");
            FileWriter fw = new FileWriter(outfile);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
            while(size>0) {
                pw.println(grades[size]);
                size--;
            }
            pw.close();
        }
    }

manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.brandon.lab5">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

XML

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.brandon.lab5.MainActivity"
    tools:showIn="@layout/activity_main">

    <EditText
        android:id="@+id/edit_infile"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="@string/edit_infile" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="arrayChange"
        android:text="Start" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="0.5dp"
        android:background="#000000" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="10dp" />

    <ScrollView
        android:id="@+id/SCROLLER_ID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:fillViewport="true">

        <TextView
            android:id="@+id/text_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="..." />

    </ScrollView>

</LinearLayout>

logcat:

       --------- beginning of crash
12-04 23:16:22.456 3056-3056/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.brandon.lab5, PID: 3056
                                                 java.lang.IllegalStateException: Could not execute method for android:onClick
                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                     at android.view.View.performClick(View.java:4780)
                                                     at android.view.View$PerformClick.run(View.java:19866)
                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                  Caused by: java.lang.reflect.InvocationTargetException
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                     at android.view.View.performClick(View.java:4780)
                                                     at android.view.View$PerformClick.run(View.java:19866)
                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                  Caused by: java.util.InputMismatchException
                                                     at java.util.Scanner.next(Scanner.java:973)
                                                     at java.util.Scanner.nextInt(Scanner.java:1318)
                                                     at java.util.Scanner.nextInt(Scanner.java:1282)
                                                     at com.example.brandon.lab5.MainActivity.arrayChange(MainActivity.java:72)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                     at android.view.View.performClick(View.java:4780)
                                                     at android.view.View$PerformClick.run(View.java:19866)
                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
12-04 23:16:22.457 1514-1646/system_process W/ActivityManager:

Body:
Here's the problematic code:

    while(fsc.hasNext()) {
        grades[n] = fsc.nextInt();
        n++;
    }

From the docs of Scanner#nextInt():

Throws

InputMismatchException if the next token does not match the Integer regular expression, or is out of range

Double-check your file content.


问:
Zeppelin [0.7.2]: NullPointerException on executing paragraph from a new Notebook
Whenever I create a new notebook and run a paragraph, I get the NullPointerException error. If I run from an existing notebook then no problem.

```<code>java.lang.NullPointerException
    at org.apache.zeppelin.spark.Utils.invokeMethod(Utils.java:38)
    at org.apache.zeppelin.spark.Utils.invokeMethod(Utils.java:33)
    at org.apache.zeppelin.spark.SparkInterpreter.createSparkContext_2(SparkInterpreter.java:391)
    at org.apache.zeppelin.spark.SparkInterpreter.createSparkContext(SparkInterpreter.java:380)
    at org.apache.zeppelin.spark.SparkInterpreter.getSparkContext(SparkInterpreter.java:146)
    at org.apache.zeppelin.spark.SparkInterpreter.open(SparkInterpreter.java:828)
</code>```

I workaround the problem by restarting the Zeppelin daemon. Saw other instances of this error but resolution given was it is fixed in 0.7.2 version which is what I am using. Anybody else facing the same problem? Have I missed something in configuration? Thanks.

答:
My problem was resolved after setting useHiveContext to false in Spark interpreter settings.

zeppelin.spark.useHiveContext => false

Body:
Whenever I create a new notebook and run a paragraph, I get the NullPointerException error. If I run from an existing notebook then no problem.

java.lang.NullPointerException
    at org.apache.zeppelin.spark.Utils.invokeMethod(Utils.java:38)
    at org.apache.zeppelin.spark.Utils.invokeMethod(Utils.java:33)
    at org.apache.zeppelin.spark.SparkInterpreter.createSparkContext_2(SparkInterpreter.java:391)
    at org.apache.zeppelin.spark.SparkInterpreter.createSparkContext(SparkInterpreter.java:380)
    at org.apache.zeppelin.spark.SparkInterpreter.getSparkContext(SparkInterpreter.java:146)
    at org.apache.zeppelin.spark.SparkInterpreter.open(SparkInterpreter.java:828)

I workaround the problem by restarting the Zeppelin daemon. Saw other instances of this error but resolution given was it is fixed in 0.7.2 version which is what I am using. Anybody else facing the same problem? Have I missed something in configuration? Thanks.


问:
Java: How can I compile an entire directory structure of code ?
The use case is simple. I got the source files that were created using Eclipse. So, there is a deep directory structure, where any Java class could be referring to another Java class in the same, child, sibling or parent folder.

How do I compile this whole thing from the terminal using javac ?

答:
I would take Jon's suggestion and use Ant, since this is a pretty complex task.

However, if you are determined to get it all in one line in the Terminal, on Linux you could use the find command. But I don't recommend this at all, since there's no guarantee that, say, Foo.java will be compiled after Bar.java, even though Foo uses Bar. An example would be:

find . -type f -name "*.java" -exec javac {} \;

If all of your classes haven't been compiled yet, if there's one main harness or driver class (basically the one containing your main method), compiling that main class individually should compile most of project, even if they are in different folders, since Javac will try to the best of its abilities to resolve dependency issues.


问:
Printing an Array List full of a new type of object
I am working on a Java program, where I have an ArrayList called "CD" and inside this CD there are "Songs", and each song is an object in my Song class, and it has the arguments: String artist, String album, and int year. Any general suggestions about how to print this such that it also prints the contents of each song?

P.S. I know there are similar questions on here but I am still having trouble getting it to print exactly what I am wanting it to, and I have tried using iterator.

Thanks for all help in advance!

答: You can also use Lombok @ToString annotation over your Songs class. Incase you feel too lazy to write your own toString method.</p>


问:
Expected end of statement error when using & to concatenate variables into a file name saveas
I'm trying to place a date into a filename but keep getting an "expected end of statement" error. Here is what I have so far:

```<code>Sub FileName()

Dim DateFileName As Variant
Dim SaveNewName As Variant

DateFileName = Format(Date, "mm.dd.yyyy")

SaveNewName = "C:\users\matt\desktop\" & "All States #1" & DateFileName & ".xls"

End Sub
</code>```

The file name should read All states #1 3.19.2016, but anytime I use the & symbol to concatenate the .xls I get the expected end of statement error! In fact anytime I try to use it to put three things into a variable I get that error. What am I doing wrong???

答: When concatenating strings in VBA, space is required before and after ampersand operator (string1 & string2).

Body:
I'm trying to place a date into a filename but keep getting an "expected end of statement" error. Here is what I have so far:

Sub FileName()

Dim DateFileName As Variant
Dim SaveNewName As Variant

DateFileName = Format(Date, "mm.dd.yyyy")

SaveNewName = "C:\users\matt\desktop\" & "All States #1" & DateFileName & ".xls"

End Sub

The file name should read All states #1 3.19.2016, but anytime I use the & symbol to concatenate the .xls I get the expected end of statement error! In fact anytime I try to use it to put three things into a variable I get that error. What am I doing wrong???


问:
Yii: how to find and remove duplicated entry from two different cdbcriteria
I would like to find the users who liked my products and the users who are following me. However, there might be users that who liked my products and also followed me, which then I will retrieve the same user id for two times.
is there anyway to only record the same user id once instead of two times?

Below are the codes that I used to identify the users who liked my products and the users who followed me.

```<code>$userid = $productModel->userId;
$followCriteria = new CDbCriteria;
$followCriteria->addCondition("follow_userId = $userid");
$followers = Followers::model()->findAll($followCriteria);
foreach ($followers as $follower) {
$followuserid = $follower->userId;

$productid = $productModel->productId;
$favoriteCriteria = new CDbCriteria;
$favoriteCriteria->addCondition("productId = $productid");
$favoritee = Favorites::model()->findAll($favoriteCriteria);
foreach ($favoritee as $favoriteer) {
$favoriteuserid = $favoriteer->userId;
</code>```

答:
You can put the ids from first query in an array like this:

```<code>...
foreach ($followers as $follower) {
    $idsAlreadyDiscovered[] = $followuserid = $follower->userId;
...
</code>```

and after you can add a NOT IN condition in second criteria

```<code>...
$productid = $productModel->productId;
$favoriteCriteria = new CDbCriteria;
$favoriteCriteria->addCondition("productId = $productid");

// Remove user ids from first query
$favoriteCriteria->addNotInCondition('userId', $idsAlreadyDiscovered);

$favoritee = Favorites::model()->findAll($favoriteCriteria);
foreach ($favoritee as $favoriteer) {
    $favoriteuserid = $favoriteer->userId;
}
</code>```

[Edit]

Or you can use your $favoriteuserid and $followuserid as arrays and after merge it in a unique.

```<code>...
foreach ($followers as $follower) {
    $followuserid[] = $follower->userId;
}
...
foreach ($favoritee as $favoriteer) {
    $favoriteuserid[] = $favoriteer->userId;
}
...
$uniqueIds = array_unique(array_merge($followuserid, $favoriteuserid));
</code>```

Body:
I would like to find the users who liked my products and the users who are following me. However, there might be users that who liked my products and also followed me, which then I will retrieve the same user id for two times.
is there anyway to only record the same user id once instead of two times?

Below are the codes that I used to identify the users who liked my products and the users who followed me.

$userid = $productModel->userId;
$followCriteria = new CDbCriteria;
$followCriteria->addCondition("follow_userId = $userid");
$followers = Followers::model()->findAll($followCriteria);
foreach ($followers as $follower) {
$followuserid = $follower->userId;

$productid = $productModel->productId;
$favoriteCriteria = new CDbCriteria;
$favoriteCriteria->addCondition("productId = $productid");
$favoritee = Favorites::model()->findAll($favoriteCriteria);
foreach ($favoritee as $favoriteer) {
$favoriteuserid = $favoriteer->userId;

Body:
You can put the ids from first query in an array like this:

...
foreach ($followers as $follower) {
    $idsAlreadyDiscovered[] = $followuserid = $follower->userId;
...

and after you can add a NOT IN condition in second criteria

...
$productid = $productModel->productId;
$favoriteCriteria = new CDbCriteria;
$favoriteCriteria->addCondition("productId = $productid");

// Remove user ids from first query
$favoriteCriteria->addNotInCondition('userId', $idsAlreadyDiscovered);

$favoritee = Favorites::model()->findAll($favoriteCriteria);
foreach ($favoritee as $favoriteer) {
    $favoriteuserid = $favoriteer->userId;
}

[Edit]

Or you can use your $favoriteuserid and $followuserid as arrays and after merge it in a unique.

...
foreach ($followers as $follower) {
    $followuserid[] = $follower->userId;
}
...
foreach ($favoritee as $favoriteer) {
    $favoriteuserid[] = $favoriteer->userId;
}
...
$uniqueIds = array_unique(array_merge($followuserid, $favoriteuserid));


问:
How to setup a JTA data source in EclipseLink/JPA 2.0 in an Java EE 6 application for derby embedded database?
I am not able to find ecbDB JTA data source in the unit test.

For RESOURCE_LOCAL the same persistence.xml works. Only within an EJB container it fails to locate a JTA data source.

I get the following exception when the unit test is executed..

```<code>SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
java.lang.RuntimeException: javax.naming.NamingException: Lookup failed for 'ecbDB' in SerialContext  [Root exception is javax.naming.NameNotFoundException: ecbDB not found]
 at org.glassfish.persistence.jpa.PersistenceUnitInfoImpl.<init>(PersistenceUnitInfoImpl.java:111)
</code>```

Here is persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence
  xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">

    <persistence-unit name="ecbPU" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>ecbDB</jta-data-source>
        <mapping-file>META-INF/orm.xml</mapping-file>

        <properties>
            <property
              name="javax.persistence.jdbc.driver"
              value="org.apache.derby.jdbc.EmbeddedDriver" />
            <property
              name="javax.persistence.jdbc.url"
              value="jdbc:derby:target/ecbDB;create=true" />

            <!-- EclipseLink 2.0 properties -->
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
            <property name="eclipselink.ddl-generation.output-mode"
                      value="sql-script" />
            <!-- <property name="eclipselink.ddl-generation.output-mode" value="database"
             /> -->
            <property name="eclipselink.application-location" value="./target/ddl" />
            <property name="eclipselink.create-ddl-jdbc-file-name"
                      value="create.sql" />
            <property name="eclipselink.drop-ddl-jdbc-file-name" value="drop.sql" />
            <property name="eclipselink.logging.level" value="ALL" />
            <property name="eclipselink.logging.file" value="./target/eclipselink.logs" />
        </properties>
    </persistence-unit>
</persistence>
</code>```

答: First make sure your derby configuration have a suitable JDBC resource (with the shell command "asadmin list-jdbc-resources"). If not, make one with "asadmin create-jdbc-resource". For help type "asadmin list-commands".</p>

Body:
I am not able to find ecbDB JTA data source in the unit test.

For RESOURCE_LOCAL the same persistence.xml works. Only within an EJB container it fails to locate a JTA data source.

I get the following exception when the unit test is executed..

SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
java.lang.RuntimeException: javax.naming.NamingException: Lookup failed for 'ecbDB' in SerialContext  [Root exception is javax.naming.NameNotFoundException: ecbDB not found]
 at org.glassfish.persistence.jpa.PersistenceUnitInfoImpl.<init>(PersistenceUnitInfoImpl.java:111)

Here is persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence
  xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">

    <persistence-unit name="ecbPU" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>ecbDB</jta-data-source>
        <mapping-file>META-INF/orm.xml</mapping-file>

        <properties>
            <property
              name="javax.persistence.jdbc.driver"
              value="org.apache.derby.jdbc.EmbeddedDriver" />
            <property
              name="javax.persistence.jdbc.url"
              value="jdbc:derby:target/ecbDB;create=true" />

            <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
            <property name="eclipselink.ddl-generation.output-mode"
                      value="sql-script" />

            <property name="eclipselink.application-location" value="./target/ddl" />
            <property name="eclipselink.create-ddl-jdbc-file-name"
                      value="create.sql" />
            <property name="eclipselink.drop-ddl-jdbc-file-name" value="drop.sql" />
            <property name="eclipselink.logging.level" value="ALL" />
            <property name="eclipselink.logging.file" value="./target/eclipselink.logs" />
        </properties>
    </persistence-unit>
</persistence>


问:
Flex menu on more rows without lonely last element?
Easy row menu with flex. In some viewport width (~600px) is menu splited with one lonely element on own second row. How to split that menu better?

Screenshot:

"Better" means for example 4 elements on first row and 3 elements on second row. Or 5 element on first row and 2 elements on second row. Just not this 6:1.

Here is my code

* {
  box-sizing: border-box;
}

html {
  font: Georgia, serif;
  color: #333;
  background: #a0522d;
  line-height: 1.5;
}

ul {
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  margin: 0 auto;
  font-family: helvetica;
  padding: 0
}

ul li {
  list-style: none;
  flex-grow: 1;
  /*max-width:16rem*/
}

ul li a {
  line-height: 1.5;
  padding: 0.2em 0.2em;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 0.063em;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="content">
  <li>Site name</li>
  <li>Next link</li>
  <li>Another link</li>
  <li>Something else</li>
  <li>Contact</li>
  <li>Almost last link</li>
  <li>Last link</li>
</ul></code>```

答:
Here is my solution using flex-basis combined with media queries to achieve the desired result, the flex-basis values can be changed based on your requirement!

* {
  box-sizing: border-box;
}

html {
  font: Georgia, serif;
  color: #333;
  background: #a0522d;
  line-height: 1.5;
}

ul {
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  margin: 0 auto;
  font-family: helvetica;
  padding: 0;
}

ul li {
  list-style: none;
  flex-grow: 1;
  /*max-width:16rem*/
  margin-bottom: 2px;
}

ul li a {
  line-height: 1.5;
  padding: 0.2em 0.2em;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 0.063em;
  text-decoration: none;
  height: 100%;
}

@media only screen and (max-width: 630px) {
  ul li {
    flex-basis: 20%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="content">
  <li>Site name</li>
  <li>Next link</li>
  <li>Another link</li>
  <li>Something else</li>
  <li>Contact</li>
  <li>Almost last link</li>
  <li>Last link</li>
</ul></code>```

Body:
Easy row menu with flex. In some viewport width (~600px) is menu splited with one lonely element on own second row. How to split that menu better?

Screenshot:

"Better" means for example 4 elements on first row and 3 elements on second row. Or 5 element on first row and 2 elements on second row. Just not this 6:1.

Here is my code

* {
  box-sizing: border-box;
}

html {
  font: Georgia, serif;
  color: #333;
  background: #a0522d;
  line-height: 1.5;
}

ul {
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  margin: 0 auto;
  font-family: helvetica;
  padding: 0
}

ul li {
  list-style: none;
  flex-grow: 1;
  /*max-width:16rem*/
}

ul li a {
  line-height: 1.5;
  padding: 0.2em 0.2em;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 0.063em;
  text-decoration: none;
}

Site name

Next link

Another link

Something else

Contact

Almost last link

Last link

Body:
Here is my solution using flex-basis combined with media queries to achieve the desired result, the flex-basis values can be changed based on your requirement!

* {
  box-sizing: border-box;
}

html {
  font: Georgia, serif;
  color: #333;
  background: #a0522d;
  line-height: 1.5;
}

ul {
  display: flex;
  flex-wrap: wrap;
  max-width: 75em;
  margin: 0 auto;
  font-family: helvetica;
  padding: 0;
}

ul li {
  list-style: none;
  flex-grow: 1;
  /*max-width:16rem*/
  margin-bottom: 2px;
}

ul li a {
  line-height: 1.5;
  padding: 0.2em 0.2em;
  display: block;
  text-align: center;
  border-radius: 0.313em;
  background: PaleGoldenrod;
  margin: 0.063em;
  text-decoration: none;
  height: 100%;
}

@media only screen and (max-width: 630px) {
  ul li {
    flex-basis: 20%;
  }
}

<ul class="content">
  <li><a href="#">Site name</a></li>
  <li><a href="#">Next link</a></li>
  <li><a href="#">Another link</a></li>
  <li><a href="#">Something else</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">Almost last link</a></li>
  <li><a href="#">Last link</a></li>
</ul>


问:
Hyperlink to ID - HTML
I have a contact div in my home page.

```<code><div id="contact">....</div>
</code>```

In my Menu, I have link to #contact that scrolls down smoothly to contact div.

```<code><a href="#contact">Contact Us</a>
</code>```

While on another page, I have to use

```<code><a href="www.mywebsite.com/#contact">
</code>```

While working with wordpress where I have single menu for all pages, can I have both functionalities simultaneously or I have to create 2 different menus, one for home, one for the rest of the pages?

答:
Solution #1 - interchangeable menu items

Add x2 menu items:

Select "Screen Options" in the top-right of the screen

Select "CSS Classes" under Show advanced menu properties

Add x2 custom links ("Custom Links box"), e.g:

#contact

/#contact

Once the menu item has been added, click on it to expand it, add a
custom class in the input field below the label "CSS Classes
(optional)", e.g:

anchor-link for menu item #contact

internal-link for menu item /#contact

Declare custom styles:

```<code>/* for the home page */
.home .anchor-link {
   display: block; /* or inline-block, whichever is applicable */
}
.home .internal-link {
  display: none; /* hide on home page */
}

/* for every other page */
.anchor-link {
   display: none; /* hide on every other page */
}
.internal-link {
  display: block; /* or inline-block, whichever is applicable */
}
</code>```

Note: Wordpress has a body class for the home page, appropriately called home - you can use this as a base selector for any home page specific style rules you need to declare.

Solution #2 - jQuery .attr() method

Wordpress links to jQuery CDN libraries, so we can leverage the benefits of jQuery and how it suits the requirements of a situation such as the one we have here.

Using the jQuery .attr() method, we can write a script that checks if the element in question, the url is anchoring to, already exists on the page, if it does we remove the preceding forward slash from the url of the menu item to make it an anchor link rather than an internal link.

Add the menu item and script:

Follow the methods mentioned in solution #1 to see how to enable
CSS Classes for menu items - we will need this class as a selector to target with the
jQuery script

Add the menu item as an internal link with a relative url
(better to keep it as a link initially since more often than not,
it'll need to be one - you only have the element with the id
#contact on the home page, so the script we are writing will only
have to run on the home page)

Write the script, then add it to your theme files, like the
header.php or footer.php*

*Here I would advise against editing core theme files, your customisations will be lost with any theme updates, it's also an easy way to wreck a theme if you are not wholly sure what you are doing. I would highly recommend installing a plugin for these customisations, a plugin like "Insert Headers & Footers" by WP Beginner will work perfectly, you should also find this plugin useful for future customisations of this nature and not only applicable for this "once-off use-case" - about the only time you will find me advocating the use of a plugin, otherwise it's just code bloat and another addon to maintain.

The jQuery script:

Untested but should suffice to demonstrate the intention

```<code>jQuery(document).ready(function(){
  if(jQuery('#contact').length) { /* if '#contact' exists length will be greater than 0 */
    /* update the href attribute for the anchor link in question */
    jQuery('.dynamic-link a').attr('href','#contact');
  }
});
</code>```

The above script will run when the document is ready to check if the element with the id "contact" already exists on the page, if it does, it'll update the href attribute on the menu item we added the custom class to (.dynamic-link). Note that this custom class is added to the list item (li) and not the nested anchor link (a).

Title: Hyperlink to ID - HTML

Body:
I have a contact div in my home page.

....

In my Menu, I have link to #contact that scrolls down smoothly to contact div.

Contact Us

While on another page, I have to use

While working with wordpress where I have single menu for all pages, can I have both functionalities simultaneously or I have to create 2 different menus, one for home, one for the rest of the pages?

Body:
Solution #1 - interchangeable menu items

Add x2 menu items:

Select "Screen Options" in the top-right of the screen

Select "CSS Classes" under Show advanced menu properties

Add x2 custom links ("Custom Links box"), e.g:

#contact

/#contact

Once the menu item has been added, click on it to expand it, add a
custom class in the input field below the label "CSS Classes
(optional)", e.g:

anchor-link for menu item #contact

internal-link for menu item /#contact

Declare custom styles:

/* for the home page */
.home .anchor-link {
   display: block; /* or inline-block, whichever is applicable */
}
.home .internal-link {
  display: none; /* hide on home page */
}

/* for every other page */
.anchor-link {
   display: none; /* hide on every other page */
}
.internal-link {
  display: block; /* or inline-block, whichever is applicable */
}

Note: Wordpress has a body class for the home page, appropriately called home - you can use this as a base selector for any home page specific style rules you need to declare.

Solution #2 - jQuery .attr() method

Wordpress links to jQuery CDN libraries, so we can leverage the benefits of jQuery and how it suits the requirements of a situation such as the one we have here.

Using the jQuery .attr() method, we can write a script that checks if the element in question, the url is anchoring to, already exists on the page, if it does we remove the preceding forward slash from the url of the menu item to make it an anchor link rather than an internal link.

Add the menu item and script:

Follow the methods mentioned in solution #1 to see how to enable
CSS Classes for menu items - we will need this class as a selector to target with the
jQuery script

Add the menu item as an internal link with a relative url
(better to keep it as a link initially since more often than not,
it'll need to be one - you only have the element with the id
#contact on the home page, so the script we are writing will only
have to run on the home page)

Write the script, then add it to your theme files, like the
header.php or footer.php*

*Here I would advise against editing core theme files, your customisations will be lost with any theme updates, it's also an easy way to wreck a theme if you are not wholly sure what you are doing. I would highly recommend installing a plugin for these customisations, a plugin like "Insert Headers & Footers" by WP Beginner will work perfectly, you should also find this plugin useful for future customisations of this nature and not only applicable for this "once-off use-case" - about the only time you will find me advocating the use of a plugin, otherwise it's just code bloat and another addon to maintain.

The jQuery script:

Untested but should suffice to demonstrate the intention

jQuery(document).ready(function(){
  if(jQuery('#contact').length) { /* if '#contact' exists length will be greater than 0 */
    /* update the href attribute for the anchor link in question */
    jQuery('.dynamic-link a').attr('href','#contact');
  }
});

The above script will run when the document is ready to check if the element with the id "contact" already exists on the page, if it does, it'll update the href attribute on the menu item we added the custom class to (.dynamic-link). Note that this custom class is added to the list item (li) and not the nested anchor link (a).


问:
Angular 4, convert from component to module
I have a component DfqComponent that I want to turn into a module, but it should keep its routing behavoir. These are the routes I want to keep, defined in the module ProductionLineRoutingModule, that has its own outlet:

```<code>const routes: Routes = [
  { path: 'line', component: ProductionLineListComponent },
  { path: 'line/:name', component: ProductionLineDetailsComponent,
  children: [
    { path: 'dfq', component: DfqComponent },
    // other modules planed
    { path: '', pathMatch: 'full', redirectTo: 'dfq' }
  ]
}];
</code>```

To turn DfqComponent to DfqModule and call it as before, I used the following routing in DfqRoutingModule:

```<code>const routes: Routes = [
  { path: 'line/:name/dfq', component: DfqComponent }
];
</code>```

This showed me the desired html (actually only simply the word DFQ), but in my opinion there are two drawbacks:

1. The outlet now is the primary outlet of the AppComponent.

2. The route definition is coupled with the ProductionLineModule ('line/:name/dfq' instead of 'dfq').

So how can I achieve this?

The project actually looks like this:

答:
The way I do that is through loadChildren. In the parent Routing

```<code>[{
    path: 'line/:name',
    loadChildren: './dfq/Dfq.module#DfqModule'
}]
</code>```

And in the dfq routing

```<code> [{
      path: 'dfq', component: DfqComponent
 }]
</code>```

And on the DfqModule in imports

```<code>    RouterModule.forChild(dfqRoutes),
</code>```

Body:
I have a component DfqComponent that I want to turn into a module, but it should keep its routing behavoir. These are the routes I want to keep, defined in the module ProductionLineRoutingModule, that has its own outlet:

const routes: Routes = [
  { path: 'line', component: ProductionLineListComponent },
  { path: 'line/:name', component: ProductionLineDetailsComponent,
  children: [
    { path: 'dfq', component: DfqComponent },
    // other modules planed
    { path: '', pathMatch: 'full', redirectTo: 'dfq' }
  ]
}];

To turn DfqComponent to DfqModule and call it as before, I used the following routing in DfqRoutingModule:

const routes: Routes = [
  { path: 'line/:name/dfq', component: DfqComponent }
];

This showed me the desired html (actually only simply the word DFQ), but in my opinion there are two drawbacks:

1. The outlet now is the primary outlet of the AppComponent.

2. The route definition is coupled with the ProductionLineModule ('line/:name/dfq' instead of 'dfq').

So how can I achieve this?

The project actually looks like this:

Body:
The way I do that is through loadChildren. In the parent Routing

[{
    path: 'line/:name',
    loadChildren: './dfq/Dfq.module#DfqModule'
}]

And in the dfq routing

 [{
      path: 'dfq', component: DfqComponent
 }]

And on the DfqModule in imports

    RouterModule.forChild(dfqRoutes),


问:
How to handle a Findbugs "Non-transient non-serializable instance field in serializable class"?
Consider the class below. If I run Findbugs against it it will give me an error ("Non-transient non-serializable instance field in serializable class") on line 5 but not on line 7.

```<code>1 public class TestClass implements Serializable {
2
3  private static final long serialVersionUID = 1905162041950251407L;
4
5  private Set<Integer> mySet;      // Findbugs error
6
7  private HashSet<Integer> myOtherSet;
8
9 }
</code>```

That's correct because java.util.Set never implements Serializable in its hierarchy and java.util.HashSet does.
However it is best practice to code against interfaces instead of concrete implementations.

How can I best handle this?

I can add a @Suppresswarnings(justification="No bug", values="SE_BAD_FIELD") on line 3. I have quite a lot of Sets and Lists in my actual code and I'm afraid it will litter my code too much.

Are there better ways?

答:
In case you are using findbugs-maven-plugin and have to persist a field, and that field is a class not implementing Serializable interface, for example, a field that has a class defined in a 3rd party. You can manually configure exclude file for findbugs,

If this is the only case, add it in an exclude file:
pom:

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>findbugs-maven-plugin</artifactId>
    <version>3.0.3</version>
    <configuration>
          <xmlOutput>true</xmlOutput>
          <xmlOutputDirectory>target/findbugs/</xmlOutputDirectory>
          <excludeFilterFile>findbugs-exclude.xml</excludeFilterFile>
          <includeFilterFile>findbugs-include.xml</includeFilterFile>
          <failOnError>true</failOnError>
    </configuration>
...
</code>```

exclude.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
    <Match>
        <Class name="com.xxx.Foo" />
        <Field type="org.springframework.statemachine.StateMachineContext"/>
    </Match>
</code>```

Entity:

```<code>@Entity
public class Foo extends Boo {
    StateMachineContext<A, B> stateMachineContext;
</code>```

Although I don't understand why adding <Bug category="SE_BAD_FIELD"/> would not work. Besides, I don't agree with the solution of adding annotation on the field like @edu.umd.cs.findbugs.annotations.SuppressWarnings(justification="No bug", values="SE_BAD_FIELD"), because building tools better not penetrate business code.maven plugin usage & findbugs filters both include and exclude

About SE_BAD_FIELD: Non-transient non-serializable instance field in serializable class, I think it should not check on entities. Because, javax.persistence.AttributeConverter offers methods to serialize a field out side (implements Serializable is an inside method to serialize).

Body:
Consider the class below. If I run Findbugs against it it will give me an error ("Non-transient non-serializable instance field in serializable class") on line 5 but not on line 7.

1 public class TestClass implements Serializable {
2
3  private static final long serialVersionUID = 1905162041950251407L;
4
5  private Set<Integer> mySet;      // Findbugs error
6
7  private HashSet<Integer> myOtherSet;
8
9 }

That's correct because java.util.Set never implements Serializable in its hierarchy and java.util.HashSet does.
However it is best practice to code against interfaces instead of concrete implementations.

How can I best handle this?

I can add a @Suppresswarnings(justification="No bug", values="SE_BAD_FIELD") on line 3. I have quite a lot of Sets and Lists in my actual code and I'm afraid it will litter my code too much.

Are there better ways?

Body:
In case you are using findbugs-maven-plugin and have to persist a field, and that field is a class not implementing Serializable interface, for example, a field that has a class defined in a 3rd party. You can manually configure exclude file for findbugs,

If this is the only case, add it in an exclude file:
pom:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>findbugs-maven-plugin</artifactId>
    <version>3.0.3</version>
    <configuration>
          <xmlOutput>true</xmlOutput>
          <xmlOutputDirectory>target/findbugs/</xmlOutputDirectory>
          <excludeFilterFile>findbugs-exclude.xml</excludeFilterFile>
          <includeFilterFile>findbugs-include.xml</includeFilterFile>
          <failOnError>true</failOnError>
    </configuration>
...

exclude.xml:

<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
    <Match>
        <Class name="com.xxx.Foo" />
        <Field type="org.springframework.statemachine.StateMachineContext"/>
    </Match>

Entity:

@Entity
public class Foo extends Boo {
    StateMachineContext<A, B> stateMachineContext;

Although I don't understand why adding <Bug category="SE_BAD_FIELD"/> would not work. Besides, I don't agree with the solution of adding annotation on the field like @edu.umd.cs.findbugs.annotations.SuppressWarnings(justification="No bug", values="SE_BAD_FIELD"), because building tools better not penetrate business code.maven plugin usage & findbugs filters both include and exclude

About SE_BAD_FIELD: Non-transient non-serializable instance field in serializable class, I think it should not check on entities. Because, javax.persistence.AttributeConverter offers methods to serialize a field out side (implements Serializable is an inside method to serialize).


问:
Excel insert rows without conditional formatting
I am working on a macro to insert a specific number of rows. I'm struggling with clearing the format of the inserted cells because the inserted rows currently use the conditional formatting of the row above.

```<code>Sub RijInsert()
'
' RijInsert Macro
'
' Sneltoets: Ctrl+Shift+R
'
Dim Rng As Integer
Dim k As Integer
Dim rRange As Range

Set rRange = Selection

Rng = InputBox("Aantal in te voegen rijen?")
For k = 1 To Rng
    Rows(rRange.Row).Insert Shift:=xlDown, _
          CopyOrigin:=xlFormatFromLeftOrAbove
Next
End Sub
</code>```

How can I insert rows without using the conditional formatting from the preceding rows?

答:
First, you need to store a row number of selected row rather Range object (since inserting rows shifts the reference). Then you can just clear the formatting:</p>

```<code>Sub RijInsert()

    Dim Rng As Integer
    Dim k As Integer
    Dim r As Long

    r = Selection.Row + 1

    Rng = InputBox("Aantal in te voegen rijen?")
    For k = 1 To Rng
        Rows(r).Insert Shift:=xlDown
        Rows(r).FormatConditions.Delete
    Next

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on a macro to insert a specific number of rows. I'm struggling with clearing the format of the inserted cells because the inserted rows currently use the conditional formatting of the row above.

Sub RijInsert()
'
' RijInsert Macro
'
' Sneltoets: Ctrl+Shift+R
'
Dim Rng As Integer
Dim k As Integer
Dim rRange As Range

Set rRange = Selection

Rng = InputBox("Aantal in te voegen rijen?")
For k = 1 To Rng
    Rows(rRange.Row).Insert Shift:=xlDown, _
          CopyOrigin:=xlFormatFromLeftOrAbove
Next
End Sub

How can I insert rows without using the conditional formatting from the preceding rows?

Body:
First, you need to store a row number of selected row rather Range object (since inserting rows shifts the reference). Then you can just clear the formatting:

Sub RijInsert()

    Dim Rng As Integer
    Dim k As Integer
    Dim r As Long

    r = Selection.Row + 1

    Rng = InputBox("Aantal in te voegen rijen?")
    For k = 1 To Rng
        Rows(r).Insert Shift:=xlDown
        Rows(r).FormatConditions.Delete
    Next

End Sub


问:
how to know if a $string ends with ','?

Possible Duplicate:

Find last character in a string in PHP

How can I know if the last char of a $string is ',' ?

答:
You can use regular expressions for this in PHP:

```<code>if (preg_match("/,$/", $string)) {
    #DO THIS
} else {
    #DO THAT
}
</code>```

This says to check for a match of a comma at the end of the $string.

Title: how to know if a $string ends with ','?

Body:
You can use regular expressions for this in PHP:

if (preg_match("/,$/", $string)) {
    #DO THIS
} else {
    #DO THAT
}

This says to check for a match of a comma at the end of the $string.


问:
evenDigits in Java
Write a method evenDigits that accepts an integer parameter n and that returns the integer formed by removing the odd digits from n. The following table shows several calls and their expected return values:
If a negative number with even digits other than 0 is passed to the method, the result should also be negative, as shown above when -34512 is passed. Leading zeros in the result should be ignored and if there are no even digits other than 0 in the number, the method should return 0, as shown in the last three outputs.
Sample calls: evenDigits(8342116) Value returned: 8426
evenDigits(35179) Value returned: 0
evenDigits(-163505) Value returned: -60

```<code>public int evenDigits(int n){
    int result = 0;
    int a = n%10;
    if(n==0){
        return 0;
    }
    if(a%2==0){
        result = a + 10*evenDigits(n/10);
    } else {
        result = evenDigits(n/10);
    }
    return result;
}
</code>```

I came up with the solution but I was getting a number format error exception if I remove the this if statement at the starting which is

```<code>if(n==0){
    return 0;
}
</code>```

Can someone please explain me what is the purpose of that if statement, I am confused about it. What exactly is that doing ?
Thanks a lot in advance.

答:
The if (n == 0) blocks the otherwise infinite recursion: notice how in all other cases, evenDigits is called yet again.

Once n is zero, the job is done, and all the calling stacks can unwind. See for yourself with your favourite debugger.

Title: evenDigits in Java

Body:
Write a method evenDigits that accepts an integer parameter n and that returns the integer formed by removing the odd digits from n. The following table shows several calls and their expected return values:
If a negative number with even digits other than 0 is passed to the method, the result should also be negative, as shown above when -34512 is passed. Leading zeros in the result should be ignored and if there are no even digits other than 0 in the number, the method should return 0, as shown in the last three outputs.
Sample calls: evenDigits(8342116) Value returned: 8426
evenDigits(35179) Value returned: 0
evenDigits(-163505) Value returned: -60

public int evenDigits(int n){
    int result = 0;
    int a = n%10;
    if(n==0){
        return 0;
    }
    if(a%2==0){
        result = a + 10*evenDigits(n/10);
    } else {
        result = evenDigits(n/10);
    }
    return result;
}

I came up with the solution but I was getting a number format error exception if I remove the this if statement at the starting which is

if(n==0){
    return 0;
}

Can someone please explain me what is the purpose of that if statement, I am confused about it. What exactly is that doing ?
Thanks a lot in advance.


问:
How to enforce static imports for some methods using checkstyle?
How to enforce static imports for some methods using checkstyle?

For example

I want the following method to be used only from static import:

```<code>import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
</code>```

So code like this shouldn't be allowed:

```<code>if (Objects.nonNull(varName)) {
</code>```

Any ideas how to achieve that with (preferably) standard or non standard tools?

答:
You could forbid the String that imports Objects:</p>

```<code><module name="RegexpSinglelineJava">
    <!-- Please statically import methods -->
    <property name="format" value="import java.util.Objects;"/>
</module>
</code>```

Body:
How to enforce static imports for some methods using checkstyle?

For example

I want the following method to be used only from static import:

import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;

So code like this shouldn't be allowed:

if (Objects.nonNull(varName)) {

Any ideas how to achieve that with (preferably) standard or non standard tools?

Body:
You could forbid the String that imports Objects:

<module name="RegexpSinglelineJava">
    <!-- Please statically import methods -->
    <property name="format" value="import java.util.Objects;"/>
</module>


问:
How to put file to HDFS with Snappy compression
I am working for a client where I should put some files to HDFS with Snappy compression. My problem is snappy codec is not defined in mapred-site.xml or hdfs-site.xml

Somehow I have to put files preferably using hdfs put command and they should be compressed. There is no chance to change configuration files since it is a production machine and other people using it actively.

Another suggested solution was to import files to HDFS without compression then create hive external tables with compression and use its source files while deleting the uncompressed files. But this is a long way to go and it is not guaranteed to work.

Any suggestions will be appreciated about using hdfs put with some kind of parameters to compress files.

答:
Say you have a Spark log file in hdfs that isn't compressed but you wanted to turn on spark.eventLog.compress true in the spark-defaults.conf and go ahead and compress the old logs. The map-reduce approach would make the most sense, but as a one off you can also use:

```<code>snzip -t hadoop-snappy local_file_will_end_in_dot_snappy
</code>```

And then upload put it directly.

Installing snzip may look similar to this:

```<code>sudo yum install snappy snappy-devel
curl -O https://dl.bintray.com/kubo/generic/snzip-1.0.4.tar.gz
tar -zxvf snzip-1.0.4.tar.gz
cd snzip-1.0.4
./configure
make
sudo make install
</code>```

Your round trip for a single file could be:

```<code>hdfs dfs -copyToLocal /var/log/spark/apps/application_1512353561403_50748_1 .
snzip -t hadoop-snappy application_1512353561403_50748_1
hdfs dfs -copyFromLocal application_1512353561403_50748_1.snappy /var/log/spark/apps/application_1512353561403_50748_1.snappy
</code>```

Or with gohdfs:

```<code>hdfs cat /var/log/spark/apps/application_1512353561403_50748_1 \
| snzip -t hadoop-snappy > zzz
hdfs put zzz /var/log/spark/apps/application_1512353561403_50748_1.snappy
rm zzz
</code>```

Body:
Say you have a Spark log file in hdfs that isn't compressed but you wanted to turn on spark.eventLog.compress true in the spark-defaults.conf and go ahead and compress the old logs. The map-reduce approach would make the most sense, but as a one off you can also use:

snzip -t hadoop-snappy local_file_will_end_in_dot_snappy

And then upload put it directly.

Installing snzip may look similar to this:

sudo yum install snappy snappy-devel
curl -O https://dl.bintray.com/kubo/generic/snzip-1.0.4.tar.gz
tar -zxvf snzip-1.0.4.tar.gz
cd snzip-1.0.4
./configure
make
sudo make install

Your round trip for a single file could be:

hdfs dfs -copyToLocal /var/log/spark/apps/application_1512353561403_50748_1 .
snzip -t hadoop-snappy application_1512353561403_50748_1
hdfs dfs -copyFromLocal application_1512353561403_50748_1.snappy /var/log/spark/apps/application_1512353561403_50748_1.snappy

Or with gohdfs:

hdfs cat /var/log/spark/apps/application_1512353561403_50748_1 \
| snzip -t hadoop-snappy > zzz
hdfs put zzz /var/log/spark/apps/application_1512353561403_50748_1.snappy
rm zzz


问:
How can I make attribute, which will manage an access to controller?
everyone. I have met the problem. What from should my attribute's class be derived and what method should I override, if I want to make an attribute, which will manage an access to controller for users.
I've already made the attribute, that inherits AuthorizeAttribute. It works fine, but I got an opinion that this way is wrong.
Please, show me right example of such attribute :)</p>

答:
I have found answer to my question. For solve this problem you should use ActionFilterAttribute

Links:
https://learn.microsoft.com/en-us/dotnet/standard/attributes/writing-custom-attributes

https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-custom-action-filters


问:
How to get contents of a webpage with PHP
I'm working with PHP to manage my Telegram Bot. Basically Telegram had added a feature which can lets users to get updates from their bots within this url:

https://api.telegram.org/bot[TOKEN_NUMBER]

Now I want to know, the bot that I'm going to search for, does exist or not.

So whenever you type the wrong Token Number of the bot, the API page returns this:

```<code>{"ok":false,"error_code":401,"description":"Unauthorized"}
</code>```

And if exists the page returns this instead:

```<code>{"ok":true,"result":[]}
</code>```

As you can see I have to get contents of a this page and determine some variables in order to know the existence of a bot. So, how can I do that with PHP ?

答:
Quick and easy two liner using get_headers

```<code>$headers=get_headers('https://api.telegram.org/bot/12345');
$active=$headers[0]=='HTTP/1.1 404 Not Found' ? false : true;
</code>```

You can then use $active in a boolean logic test to either continue processing or abort.

```<code>if( $active ){/* do stuff */} else {/* go to the pub */}
</code>```

Body:
I'm working with PHP to manage my Telegram Bot. Basically Telegram had added a feature which can lets users to get updates from their bots within this url:

https://api.telegram.org/bot[TOKEN_NUMBER]

Now I want to know, the bot that I'm going to search for, does exist or not.

So whenever you type the wrong Token Number of the bot, the API page returns this:

{"ok":false,"error_code":401,"description":"Unauthorized"}

And if exists the page returns this instead:

{"ok":true,"result":[]}

As you can see I have to get contents of a this page and determine some variables in order to know the existence of a bot. So, how can I do that with PHP ?

Body:
Quick and easy two liner using get_headers

$headers=get_headers('https://api.telegram.org/bot/12345');
$active=$headers[0]=='HTTP/1.1 404 Not Found' ? false : true;

You can then use $active in a boolean logic test to either continue processing or abort.

if( $active ){/* do stuff */} else {/* go to the pub */}


问:
Getting particular property value from particular page in episerver
I need to get the property value for user given property of user given page in episerver...
for that i write a method..

```<code> public string GetContent(string pageName, string propertyName)
    {
        var contentTypeRepo = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
        IEnumerable<ContentType> allPageTypes = contentTypeRepo.List();
        var currentpage = allPageTypes.Where(x => x.Name.ToLower() == pageName);
        var pageId = currentpage.First().ID;
        var pageRef = new PageReference(pageId);
        var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
        var page = contentRepository.Get<PageData>(pageRef);
        var content = page.GetPropertyValue(propertyName);
        return content;
    }
</code>```

But I can not get the correct page by pageType ID...it is get some other page ....so this is what my requirement...
user given page name and property name and the get method will return corresponding property value...
Thanks.....

答:
This question has also been asked on Episerver World and I also write my answer here.
_pageCriteriaQueryService is injected through constructor injection in the class.

Even though this will get you the property value from a page by its pagename and propertyname, it is not recommended to code like this.

First I would have gone back to find out why this demand exist, where and how are you going to use your function?

```<code>public string GetPropertyValueByPageNameAndPropertyName(string pageName, string propertyName)
    {
        var criteria = new PropertyCriteriaCollection
        {
            new PropertyCriteria()
            {
                Name = "PageName",
                Type = PropertyDataType.String,
                Condition = CompareCondition.Equal,
                Value = pageName
            }
        };

        var pages = _pageCriteriaQueryService.FindPagesWithCriteria(ContentReference.StartPage, criteria);

        if (pages != null && pages.Count > 0)
        {
            return pages[0].GetPropertyValue(propertyName);
        }

        return string.Empty;
    }
</code>```

Body:
I need to get the property value for user given property of user given page in episerver...
for that i write a method..

 public string GetContent(string pageName, string propertyName)
    {
        var contentTypeRepo = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
        IEnumerable<ContentType> allPageTypes = contentTypeRepo.List();
        var currentpage = allPageTypes.Where(x => x.Name.ToLower() == pageName);
        var pageId = currentpage.First().ID;
        var pageRef = new PageReference(pageId);
        var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
        var page = contentRepository.Get<PageData>(pageRef);
        var content = page.GetPropertyValue(propertyName);
        return content;
    }

But I can not get the correct page by pageType ID...it is get some other page ....so this is what my requirement...
user given page name and property name and the get method will return corresponding property value...
Thanks.....

Body:
This question has also been asked on Episerver World and I also write my answer here.
_pageCriteriaQueryService is injected through constructor injection in the class.

Even though this will get you the property value from a page by its pagename and propertyname, it is not recommended to code like this.

First I would have gone back to find out why this demand exist, where and how are you going to use your function?

public string GetPropertyValueByPageNameAndPropertyName(string pageName, string propertyName)
    {
        var criteria = new PropertyCriteriaCollection
        {
            new PropertyCriteria()
            {
                Name = "PageName",
                Type = PropertyDataType.String,
                Condition = CompareCondition.Equal,
                Value = pageName
            }
        };

        var pages = _pageCriteriaQueryService.FindPagesWithCriteria(ContentReference.StartPage, criteria);

        if (pages != null && pages.Count > 0)
        {
            return pages[0].GetPropertyValue(propertyName);
        }

        return string.Empty;
    }