问:
reading file to a list
i have a text file  like this

```<code>a1,b1,30.04.2017
c1,d1,30.05.2017
</code>```

i want to add every line to a list, the first two columns will be string variables s1 and s2 and the third one will be converted to a variable showing a date

i am not experienced at all and usually i find my answers searching here. i can only find examples reading  lines containing the name of the variable and the value,

i think i will need to use the code below

```<code> List<string> fileLines = new List<string>();

using (var reader = new StreamReader(fileName))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {

    }
}
</code>```

i cannot do the things inside the bracket, namely ,
parse the line ,
assign first column  to variable s1
assign second column to variable s2
convert the third to date and assign it to d1
then add line to list

thanks in advance

答:
Keep it simple.

var text = File.ReadAllText(@"[FILEPATH]");

var fileLines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();

But again, this could have been easily googled.

Just in case, if you need the complete code: Here is my version

```<code>private static void TestReader()
    {
        var text = File.ReadAllText(@"D:\sample.txt");
        var fileLines = new List<SampleData>();
        foreach (var fileLine in text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
        {
            var lineData = fileLine.Split(',');

            // Make sure all the keys are present / do a separate check
            if (lineData.Length <= 2)
            {
                continue;
            }

            fileLines.Add(new SampleData
            {
                Code = Convert.ToString(lineData[0]),
                Description = Convert.ToString(lineData[1]),
                SelectedDate = lineData.Length >= 3 ? DateTime.ParseExact(lineData[2], "dd.MM.yyyy", null) : DateTime.MinValue
            });
        }
    }

    public class SampleData
    {
        public string Code { get; set; }
        public string Description { get; set; }
        public DateTime SelectedDate { get; set; }
    }
</code>```

Title: reading file to a list

Body:
i have a text file  like this

a1,b1,30.04.2017
c1,d1,30.05.2017

i want to add every line to a list, the first two columns will be string variables s1 and s2 and the third one will be converted to a variable showing a date

i am not experienced at all and usually i find my answers searching here. i can only find examples reading  lines containing the name of the variable and the value,

i think i will need to use the code below

 List<string> fileLines = new List<string>();

using (var reader = new StreamReader(fileName))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {

    }
}

i cannot do the things inside the bracket, namely ,
parse the line ,
assign first column  to variable s1
assign second column to variable s2
convert the third to date and assign it to d1
then add line to list

thanks in advance

Body:
Keep it simple.

var text = File.ReadAllText(@"[FILEPATH]");

var fileLines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();

But again, this could have been easily googled.

Just in case, if you need the complete code: Here is my version

private static void TestReader()
    {
        var text = File.ReadAllText(@"D:\sample.txt");
        var fileLines = new List<SampleData>();
        foreach (var fileLine in text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
        {
            var lineData = fileLine.Split(',');

            // Make sure all the keys are present / do a separate check
            if (lineData.Length <= 2)
            {
                continue;
            }

            fileLines.Add(new SampleData
            {
                Code = Convert.ToString(lineData[0]),
                Description = Convert.ToString(lineData[1]),
                SelectedDate = lineData.Length >= 3 ? DateTime.ParseExact(lineData[2], "dd.MM.yyyy", null) : DateTime.MinValue
            });
        }
    }

    public class SampleData
    {
        public string Code { get; set; }
        public string Description { get; set; }
        public DateTime SelectedDate { get; set; }
    }


来源: stackexchange

问:
WPF c# XAML ismouseover animation
In my project when program starts polygon is moving on set path
What should I change to stop polygon moving, when the mouse cursor on it (when mouse cursor out of polygon, polygon must continue it's moving)

```<code><Window x:Class="aqua3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:aqua3"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <PathGeometry x:Key="pathg">
        <PathFigure IsClosed="True">
            <PolyLineSegment Points="0,0 200,0 200,80 0,80" />
        </PathFigure>
    </PathGeometry>
</Window.Resources>
<Grid Background="LightBlue">
    <Canvas Margin="10" Background="LightBlue">
        <Path Stroke="Red" Data="{StaticResource pathg}" Canvas.Top="10" Canvas.Left="10" />
        <Polygon Name="polygon1" Stroke="Yellow" Fill="Yellow"  Points="100,150 120,140 120,120 165,150 120,180 120,160 ">
            <Polygon.Triggers>
                <EventTrigger RoutedEvent="Window.Loaded">
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimationUsingPath Storyboard.TargetProperty="(Canvas.Top)"
                                   Duration="0:0:15" RepeatBehavior="Forever"
                                   PathGeometry="{StaticResource pathg}" Source="Y" >
                            </DoubleAnimationUsingPath>
                            <DoubleAnimationUsingPath Storyboard.TargetProperty="(Canvas.Left)"
                                   Duration="0:0:15" RepeatBehavior="Forever"
                                   PathGeometry="{StaticResource pathg}" Source="X" >
                            </DoubleAnimationUsingPath>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Polygon.Triggers>
        </Polygon>
    </Canvas>
</Grid>
</code>```

答:
Assign a name to your BeginStoryboard

```<code><BeginStoryboard x:Name="Move">
</code>```

To pause, add this

```<code><EventTrigger RoutedEvent="MouseEnter">
     <PauseStoryboard BeginStoryboardName="Move"/>
</EventTrigger>
</code>```

To resume, add this

```<code><EventTrigger RoutedEvent="MouseLeave">
     <ResumeStoryboard BeginStoryboardName="Move"/>
</EventTrigger>
</code>```

ContentLicense: CC BY-SA 3.0

Title: WPF c# XAML ismouseover animation

Body:
In my project when program starts polygon is moving on set path
What should I change to stop polygon moving, when the mouse cursor on it (when mouse cursor out of polygon, polygon must continue it's moving)

<Window x:Class="aqua3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:aqua3"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <PathGeometry x:Key="pathg">
        <PathFigure IsClosed="True">
            <PolyLineSegment Points="0,0 200,0 200,80 0,80" />
        </PathFigure>
    </PathGeometry>
</Window.Resources>
<Grid Background="LightBlue">
    <Canvas Margin="10" Background="LightBlue">
        <Path Stroke="Red" Data="{StaticResource pathg}" Canvas.Top="10" Canvas.Left="10" />
        <Polygon Name="polygon1" Stroke="Yellow" Fill="Yellow"  Points="100,150 120,140 120,120 165,150 120,180 120,160 ">
            <Polygon.Triggers>
                <EventTrigger RoutedEvent="Window.Loaded">
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimationUsingPath Storyboard.TargetProperty="(Canvas.Top)"
                                   Duration="0:0:15" RepeatBehavior="Forever"
                                   PathGeometry="{StaticResource pathg}" Source="Y" >
                            </DoubleAnimationUsingPath>
                            <DoubleAnimationUsingPath Storyboard.TargetProperty="(Canvas.Left)"
                                   Duration="0:0:15" RepeatBehavior="Forever"
                                   PathGeometry="{StaticResource pathg}" Source="X" >
                            </DoubleAnimationUsingPath>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Polygon.Triggers>
        </Polygon>
    </Canvas>
</Grid>

Body:
Assign a name to your BeginStoryboard

<BeginStoryboard x:Name="Move">

To pause, add this

<EventTrigger RoutedEvent="MouseEnter">
     <PauseStoryboard BeginStoryboardName="Move"/>
</EventTrigger>

To resume, add this

<EventTrigger RoutedEvent="MouseLeave">
     <ResumeStoryboard BeginStoryboardName="Move"/>
</EventTrigger>


答:
In code below i write the parsed data, and you can use them how you want:</p>

```<code>List<string> fileLines = new List<string>();
using (var reader = new StreamReader(fileName))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (line == "") continue; // refuse bare lines...
                string a = line.Split(',')[0];
                string b = line.Split(',')[1];
                DateTime dt = DateTime.ParseExact(line.Split(',')[2], "dd.MM.yyyy", null);
                fileLines.Add(line); // if you want....
            }
        }
</code>```

Title: reading file to a list

Body:
In code below i write the parsed data, and you can use them how you want:

List<string> fileLines = new List<string>();
using (var reader = new StreamReader(fileName))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (line == "") continue; // refuse bare lines...
                string a = line.Split(',')[0];
                string b = line.Split(',')[1];
                DateTime dt = DateTime.ParseExact(line.Split(',')[2], "dd.MM.yyyy", null);
                fileLines.Add(line); // if you want....
            }
        }


问:
Change color of items in appbar
I want to change the color of my app name, search icon and overflow menu in the appbar to white. I used textColorPrimary but its not working, it is all black.

Here is my code

colors.xml

```<code><resources>
    <color name="colorPrimary">#9C27B0</color>
    <color name="colorPrimaryDark">#CE93D8</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#FFFFFF</color>
    <color name="colorAccent">#FF80AB</color>
</resource>
</code>```

styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="textColorPrimary">@color/textColorPrimary</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
</code>```

AndroidManifest.xml

```<code>     <activity
        android:name=".MainActivity"
        android:theme="@style/AppTheme"
        android:label="@string/title_activity_welcome">
    </activity>
</code>```

menumain.xml

```<code>   <menu 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"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:showAsAction="always" />

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />

    </menu>
</code>```

This is what I want - A white text(app name), search icon(fixed,i used a white search icon so no problem) and white overflow menu

答: FIXED...Strangely it was rendering with black but when I run on a real device it was white.!!</p>

Title: Change color of items in appbar

Body:
I want to change the color of my app name, search icon and overflow menu in the appbar to white. I used textColorPrimary but its not working, it is all black.

Here is my code

colors.xml

<resources>
    <color name="colorPrimary">#9C27B0</color>
    <color name="colorPrimaryDark">#CE93D8</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#FFFFFF</color>
    <color name="colorAccent">#FF80AB</color>
</resource>

styles.xml

AndroidManifest.xml

     <activity
        android:name=".MainActivity"
        android:theme="@style/AppTheme"
        android:label="@string/title_activity_welcome">
    </activity>

menumain.xml

   <menu 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"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:showAsAction="always" />

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />

    </menu>

This is what I want - A white text(app name), search icon(fixed,i used a white search icon so no problem) and white overflow menu


问:
CreateFile returns invalid handle value
I'm trying to read file from the directory the exe file is located. The data.txt file is in VS Project directory and when I specify the full path everything works fine.    </p>

```<code>char curDirectory[MAX_PATH];
GetCurrentDirectory(MAX_PATH, curDirectory);

char filePath[MAX_PATH];

char *name = "\\data.txt";

memcpy(filePath, curDirectory, sizeof(curDirectory));
memcpy(filePath + strlen(curDirectory), name, strlen(name));

HANDLE hFile = CreateFile(filePath, GENERIC_ALL, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
</code>```

答:
You don't null terminate the string. Do so by passing strlen(name) + 1 in the second call to memcpy.

Some other observations:

When CreateFile fails, you should call GetLastError to obtain an error code.

Use strcpy and strcat rather than memcpy when working with strings.

That said, your code asks to overrun the buffer. If this really is C++, use std::string and have that class manage buffers.

There is no real reason to believe that the executable file is located in the current working directory.

Title: CreateFile returns invalid handle value

Body:
I'm trying to read file from the directory the exe file is located. The data.txt file is in VS Project directory and when I specify the full path everything works fine.

char curDirectory[MAX_PATH];
GetCurrentDirectory(MAX_PATH, curDirectory);

char filePath[MAX_PATH];

char *name = "\\data.txt";

memcpy(filePath, curDirectory, sizeof(curDirectory));
memcpy(filePath + strlen(curDirectory), name, strlen(name));

HANDLE hFile = CreateFile(filePath, GENERIC_ALL, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);


问:
How to rotate this rectangle over Ox, Oy and Oz axis in java?
I created a rectangle in java using graphics2D and I want to rotate it over all axis, Ox, Oy and Oz in origin (0,0). How to do that ?

Because it's 2D, z = 0. So can you help me to rotate this rectangle over all axis ?

Thank you!

This is my code, I created a rectangle and I want to save it as image.

```<code>import java.awt.Canvas;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class DrawShape_SaveAsImage extends Canvas {

    public static void main(String[] args) {
        Frame f=new Frame("Draw shape and text on Canvas");
        final Canvas canvas=new DrawShape_SaveAsImage();

        f.add(canvas);

        f.setSize(600,600);
        f.setVisible(true);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent event) {
                saveCanvas(canvas);
                System.exit(0);
            }
        });

    }

    public void paint(Graphics g) {
        Graphics2D g2=(Graphics2D)g;
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, this.getWidth(), this.getHeight());
        g2.setColor(Color.BLACK);
        g2.fillRect(100, 100, 200, 200);
    }

    public static void saveCanvas(Canvas canvas) {

        BufferedImage image=new BufferedImage(canvas.getWidth(), canvas.getHeight(),BufferedImage.TYPE_INT_RGB);

        Graphics2D g2=(Graphics2D)image.getGraphics();

        canvas.paint(g2);
        try {
            ImageIO.write(image, "png", new File("canvas.png"));
        } catch (Exception e) {

        }
    }
}
</code>```

答:
This is 2D so you can rotate around OZ only. First of all you should use Vectors for any coordinates (it makes math easy ;) ) Here you have the example of Vector class and rotation. You can check demo coded by me here: http://ideone.com/ZZjm6l

```<code>import java.util.*;
import java.lang.*;
import java.io.*;
import static java.lang.Math.*;
class Vector
{
    double x;
    double y;

    Vector(double a, double b)
    {
        x = a;
        y = b;
    }

    void add(Vector v)
    {
        x += v.x;
        y += v.y;
    }

    //other useful methods like multiply should be here

    void rotate(double angle) //https://en.wikipedia.org/wiki/Rotation_(mathematics)
    {
        double s = sin(angle);
        double c = cos(angle);

        x = x * c - y * s;
        y = x * s + y * c;
    }

}

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Vector v = new Vector(1,1);
        v.rotate(Math.PI / 2);
        System.out.println(v.x + " " + v.y);
    }
}
</code>```

So your fillRect should look like this after all:

```<code>g2.fillRect(v.x, v.y, 200, 200);
</code>```

Good luck!

Body:
I created a rectangle in java using graphics2D and I want to rotate it over all axis, Ox, Oy and Oz in origin (0,0). How to do that ?

Because it's 2D, z = 0. So can you help me to rotate this rectangle over all axis ?

Thank you!

This is my code, I created a rectangle and I want to save it as image.

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class DrawShape_SaveAsImage extends Canvas {

    public static void main(String[] args) {
        Frame f=new Frame("Draw shape and text on Canvas");
        final Canvas canvas=new DrawShape_SaveAsImage();

        f.add(canvas);

        f.setSize(600,600);
        f.setVisible(true);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent event) {
                saveCanvas(canvas);
                System.exit(0);
            }
        });

    }

    public void paint(Graphics g) {
        Graphics2D g2=(Graphics2D)g;
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, this.getWidth(), this.getHeight());
        g2.setColor(Color.BLACK);
        g2.fillRect(100, 100, 200, 200);
    }

    public static void saveCanvas(Canvas canvas) {

        BufferedImage image=new BufferedImage(canvas.getWidth(), canvas.getHeight(),BufferedImage.TYPE_INT_RGB);

        Graphics2D g2=(Graphics2D)image.getGraphics();

        canvas.paint(g2);
        try {
            ImageIO.write(image, "png", new File("canvas.png"));
        } catch (Exception e) {

        }
    }
}

Body:
This is 2D so you can rotate around OZ only. First of all you should use Vectors for any coordinates (it makes math easy ;) ) Here you have the example of Vector class and rotation. You can check demo coded by me here: http://ideone.com/ZZjm6l

import java.util.*;
import java.lang.*;
import java.io.*;
import static java.lang.Math.*;
class Vector
{
    double x;
    double y;

    Vector(double a, double b)
    {
        x = a;
        y = b;
    }

    void add(Vector v)
    {
        x += v.x;
        y += v.y;
    }

    //other useful methods like multiply should be here

    void rotate(double angle) //https://en.wikipedia.org/wiki/Rotation_(mathematics)
    {
        double s = sin(angle);
        double c = cos(angle);

        x = x * c - y * s;
        y = x * s + y * c;
    }

}

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Vector v = new Vector(1,1);
        v.rotate(Math.PI / 2);
        System.out.println(v.x + " " + v.y);
    }
}

So your fillRect should look like this after all:

g2.fillRect(v.x, v.y, 200, 200);

Good luck!


问:
What is the difference between find with grep?
What is the difference between these command:

```<code>find . –type f –name '*txt*'
</code>```

and

```<code>find . –type f | grep 'txt'
</code>```

I tried to run this and there is a difference but I want to know why?

答:
In your first example, you are using the find utility to list the filenames of regular files where the filename includes the string txt.

In your second example, you are using the find utility to list the filenames of regular files and feeding the resultant filenames via a pipe to the grep utility which searches the contents of the pipe (a list of filenames, one per line) for the string txt. Each time this string is found, the corresponding line (which is a filename) is outputted.

Body:
What is the difference between these command:

find . –type f –name '*txt*'

and

find . –type f | grep 'txt'

I tried to run this and there is a difference but I want to know why?

ContentLicense: CC BY-SA 4.0


问:
How to get all rows from multi tables using 1 query
I have 4 tables (movies, series, lists and list_titles), the question is: How to do to get all movies, series attached to particular list in list_titles table?

Here is what I have done sqlfiddle.

Query:

```<code>select *
from (
    select srs.*
    from series srs
    left join list_titles lt on lt.type_id = srs.id
    where lt.list_id = 7
        and lt.type_name = 'series'
        and lt.user_id = 1
    ) as a,
    (
        select mo.*
        from movies mo
        left join list_titles tl on tl.type_id = mo.id
        where tl.list_id = 7
            and tl.type_name = 'series'
            and tl.user_id = 1
        ) as b
</code>```

答:
You want to use UNION ALL between the two queries:

```<code>select s.id,
    s.title_name,
    ...
from series s
left join list_titles lt on lt.type_id = s.id
where lt.list_id = 7
    and lt.type_name = 'series'
    and lt.user_id = 1

union all

select m.id,
    m.title_name,
    ...
from movies m
left join list_titles tl on tl.type_id = m.id
where tl.list_id = 7
    and tl.type_name = 'series'
    and tl.user_id = 1
</code>```

Demo

Body:
I have 4 tables (movies, series, lists and list_titles), the question is: How to do to get all movies, series attached to particular list in list_titles table?

Here is what I have done sqlfiddle.

Query:

select *
from (
    select srs.*
    from series srs
    left join list_titles lt on lt.type_id = srs.id
    where lt.list_id = 7
        and lt.type_name = 'series'
        and lt.user_id = 1
    ) as a,
    (
        select mo.*
        from movies mo
        left join list_titles tl on tl.type_id = mo.id
        where tl.list_id = 7
            and tl.type_name = 'series'
            and tl.user_id = 1
        ) as b

Body:
You want to use UNION ALL between the two queries:

select s.id,
    s.title_name,
    ...
from series s
left join list_titles lt on lt.type_id = s.id
where lt.list_id = 7
    and lt.type_name = 'series'
    and lt.user_id = 1

union all

select m.id,
    m.title_name,
    ...
from movies m
left join list_titles tl on tl.type_id = m.id
where tl.list_id = 7
    and tl.type_name = 'series'
    and tl.user_id = 1

Demo


问:
how to add int and int[ ] in java using var args method?
This is my first question so I might sound stupid, so please don't mind !
I was working on a concept which is var args and I come up with a program as follows :

```<code>package Method;
public class VariableArguments {
public static void main(String[] args) {
    m1();
    m1(10);
    m1(10,20);
    m1(10,20,30,40);
    m1(10,20,30,40,50);
}
public static void m1(int... x)
{
    int total = 0;
    for(int i:x)
    {
        total = total + x;
    }
    System.out.println("Sum is: "+total);
 }
}
</code>```

While I was running this program, I was getting an error which is-

Error:(15, 27) java: bad operand types for binary operator '+'

first type:  int   second type: int[]

In line 15 it says "Operator '+' cannot be applied on int, int[]"

So can anybody give me the solution for this problem ?
Thanks !!

答:
Avoid silly mistakes , you need to learn the for-each method :

```<code>for(int i : x) // this means for every integer value *i* in array *x*
{
      total = total + i ;// this line add the i to total ,
     //total = total + x ;//here array is bad operand for '+' operator .
}
</code>```

change your code by the above snnipet , or you can also use simple for loop.

Body:
This is my first question so I might sound stupid, so please don't mind !
I was working on a concept which is var args and I come up with a program as follows :

package Method;
public class VariableArguments {
public static void main(String[] args) {
    m1();
    m1(10);
    m1(10,20);
    m1(10,20,30,40);
    m1(10,20,30,40,50);
}
public static void m1(int... x)
{
    int total = 0;
    for(int i:x)
    {
        total = total + x;
    }
    System.out.println("Sum is: "+total);
 }
}

While I was running this program, I was getting an error which is-

Error:(15, 27) java: bad operand types for binary operator '+'

first type:  int   second type: int[]

In line 15 it says "Operator '+' cannot be applied on int, int[]"

So can anybody give me the solution for this problem ?
Thanks !!

Body:
Avoid silly mistakes , you need to learn the for-each method :

for(int i : x) // this means for every integer value *i* in array *x*
{
      total = total + i ;// this line add the i to total ,
     //total = total + x ;//here array is bad operand for '+' operator .
}

change your code by the above snnipet , or you can also use simple for loop.


问:
How do I select distinct values from multiple mysql columns and put them in one PHP array?
I have a table for songs, where each song can have up to 3 different genres. So in my table, for each song I have column genre1, genre2, and genre3. I'm trying to display all the genres available in a list.

Here's a random example set:

```<code>genre1    genre2    genre3
metal     jazz
metal     country   pop
oldies    metal
rap
jazz      hip-hop   choir
choir     metal     jazz
</code>```

I want the list, done in php, to display in alphabetical order the available distinct genres to choose from. So it should list this:

Choir

Country

Hip-hop

Jazz

Metal

Oldies

Pop

Rap

All help is appreciated. Perhaps I'm not going about this the smartest way, but I couldn't think of a better way.

答:
SELECT DISTINCT genre1, genre2, genre3 FROM tabel

Description

Maybe you need a better database design...
songs | genres | [song_id|genre_id]

Body:
I have a table for songs, where each song can have up to 3 different genres. So in my table, for each song I have column genre1, genre2, and genre3. I'm trying to display all the genres available in a list.

Here's a random example set:

genre1    genre2    genre3
metal     jazz
metal     country   pop
oldies    metal
rap
jazz      hip-hop   choir
choir     metal     jazz

I want the list, done in php, to display in alphabetical order the available distinct genres to choose from. So it should list this:

Choir

Country

Hip-hop

Jazz

Metal

Oldies

Pop

Rap

All help is appreciated. Perhaps I'm not going about this the smartest way, but I couldn't think of a better way.

ContentLicense: CC BY-SA 2.5


问:
inserting data into related tables in postgres
I want to insert all the data for one object (which spans one main table and two related tables) in one statement if possible. If I were to only have one related table, I assume I could do something like this using Common Table Expressions:

```<code>WITH foo AS (INSERT INTO foos VALUES (....) RETURNING id)
INSERT INTO bar VALUES (foo.id....)
</code>```

Am I able to do something like this but for more than one related table?

答:
You can extend your format to as many tables as needed. Here is an example with one main table and two related tables, and several ways of getting back the end results:

These are the tables used:

```<code> CREATE TABLE main
 (
     main_id serial PRIMARY KEY,
     main_text text
 ) ;
 CREATE TABLE age
 (
     main_id integer REFERENCES main(main_id) PRIMARY KEY,
     birthdate date NOT NULL,
     CHECK(birthdate <= now())
 ) ;
 CREATE TABLE preferred_colours
 (
     main_id integer NOT NULL REFERENCES main(main_id),
     colour text NOT NULL,
     PRIMARY KEY(main_id, colour)
 ) ;
</code>```

This is one CTE where you insert in three tables, and get out some results:

```<code> WITH insert_main AS
 (
     INSERT INTO main (main_text)
     VALUES ('Main text')
     RETURNING main_text, main_id
 )
 , insert_age AS
 (
     INSERT INTO age (main_id, birthdate)
     VALUES ( (SELECT main_id FROM insert_main), '2017-01-01')
     RETURNING main_id, birthdate
 )
 , insert_colours AS
 (
     INSERT INTO preferred_colours (main_id, colour)
     SELECT
         main_id, colour
     FROM
         insert_main
         CROSS JOIN
         (SELECT 'blue' AS colour
          UNION
          SELECT 'red'
          UNION
          SELECT 'green'
         ) AS colours
     RETURNING
         *
 )
 SELECT
      insert_main.main_id
     ,insert_main.main_text
     ,insert_age.birthdate
     ,(SELECT string_agg(colour, ', ' ORDER BY colour)
       FROM insert_colours
      ) AS preferred_colours_list
 FROM
     insert_main
     CROSS JOIN insert_age
</code>```

```
 main_id | main_text | birthdate  | preferred_colours_list
 ------: | :-------- | :--------- | :---------------------
       1 | Main text | 2017-01-01 | blue, green, red<br>
 ```

dbfiddle here

Body:
I want to insert all the data for one object (which spans one main table and two related tables) in one statement if possible. If I were to only have one related table, I assume I could do something like this using Common Table Expressions:

WITH foo AS (INSERT INTO foos VALUES (....) RETURNING id)
INSERT INTO bar VALUES (foo.id....)

Am I able to do something like this but for more than one related table?

Body:
You can extend your format to as many tables as needed. Here is an example with one main table and two related tables, and several ways of getting back the end results:

These are the tables used:

 CREATE TABLE main
 (
     main_id serial PRIMARY KEY,
     main_text text
 ) ;
 CREATE TABLE age
 (
     main_id integer REFERENCES main(main_id) PRIMARY KEY,
     birthdate date NOT NULL,
     CHECK(birthdate <= now())
 ) ;
 CREATE TABLE preferred_colours
 (
     main_id integer NOT NULL REFERENCES main(main_id),
     colour text NOT NULL,
     PRIMARY KEY(main_id, colour)
 ) ;

This is one CTE where you insert in three tables, and get out some results:

 WITH insert_main AS
 (
     INSERT INTO main (main_text)
     VALUES ('Main text')
     RETURNING main_text, main_id
 )
 , insert_age AS
 (
     INSERT INTO age (main_id, birthdate)
     VALUES ( (SELECT main_id FROM insert_main), '2017-01-01')
     RETURNING main_id, birthdate
 )
 , insert_colours AS
 (
     INSERT INTO preferred_colours (main_id, colour)
     SELECT
         main_id, colour
     FROM
         insert_main
         CROSS JOIN
         (SELECT 'blue' AS colour
          UNION
          SELECT 'red'
          UNION
          SELECT 'green'
         ) AS colours
     RETURNING
         *
 )
 SELECT
      insert_main.main_id
     ,insert_main.main_text
     ,insert_age.birthdate
     ,(SELECT string_agg(colour, ', ' ORDER BY colour)
       FROM insert_colours
      ) AS preferred_colours_list
 FROM
     insert_main
     CROSS JOIN insert_age

 main_id | main_text | birthdate  | preferred_colours_list
 ------: | :-------- | :--------- | :---------------------
       1 | Main text | 2017-01-01 | blue, green, red

dbfiddle here


问:
attach file to PHP contact form
i have created a contact for with html and using PHP code to send it my email and its working fine but i have one problem that i want to attach file and to be sent also but i don't know how so anyone can help me with that .... and the php code is below just want to add the attachment of files
thanks in advance

<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

<?php
error_reporting(E_ALL);
 ini_set('display_errors', 1);
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = $result =  "" ;
if(isset($_POST['submit']))
{
// define contact form variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$design = $_POST['design'];
$country = $_POST['country'];
$comment = $_POST['comment'];
$human = $_POST['human'];
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = "" ;
// define Checks variables
$check1 = $check2 = $check3  = $check4 = "";
// define email variables
$to = 'eng.bolaraafat@gmail.com';
$subject = 'Contact Form';
$message = 'From: '.$fname .$lname."\r\n".
           'E-mail: '.$email."\r\n".
           'Telephone: '.$tel."\r\n".
           'Designation: '.$design."\r\n".
           'Country Appled From: '.$country."\r\n".
           'Message: '.$comment."\r\n";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers = "From:" .$email. "\n" ;

// Let's do some checks
// Checking the First Name
if(empty($_POST["fname"])){
 $fnameErr = "Name is Required";
}else{
 $fname = test_input($_POST["fname"]);
 // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
      $fnameErr = "Only letters and white space allowed";
    }else{
  $check1 = 1;
 }
}
// Checking the Last Name
if(empty($_POST["lname"])){
 $lnameErr = "Name is Required";
}else{
 $lname = test_input($_POST["lname"]);
 // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
      $lnameErr = "Only letters and white space allowed";
    }else{
  $check2 = 1;
 }
}
//Checking the Email Adress
if(empty($_POST["email"])){
 $emailErr = "Email is Required";
}else{
 $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
    }else{
  $check3 = 1;
 }
}
//Checking the Anti-Spam Question
if(empty($_POST["human"])){
 $humanErr = "Please Enter the Answer";
}else{
 if ($human != 4){
  $humanErr = "Please check your answer";
 }else{
  $check4 = 1;
 }
}

// Emailing the Contents if all Checks are correct
if($check1 && $check2 && $check3 && $check4 == 1){
 mail($to, $subject, $message, $headers);
 $result =  "Message Sent Sucessfully";
}else{
 $result = "Message Can't be sent";
}
}
 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

Contact Form

*Required field

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
 First Name:<input type="text" name="fname">*  <?php echo $fnameErr ?>

 Last Name:<input type="text" name="lname">* <?php echo $lnameErr ?>

 E-mail:<input type="text" name="email">* <?php echo $emailErr ?>

 Telephone:<input type="text" name="tel">

 Designation:<select name="design">
    <option value="Architectural Engineer">Architectural Engineer</option>
    <option value="Structural Engineer">Structural Engineer</option>
    <option value="Draughts-man">Draughts-man</option>
    <option value="Receptionist">Receptionist</option>
    <option value="Secertary">Secertary</option>
   </select>

   Country Applied From:<select name="country">
  <option value="">Country...</option>
  <option value="Afganistan">Afghanistan</option>
  <option value="Albania">Albania</option>
</select>

 Message:<textarea name="comment"></textarea>

 Upload Your Resume:*<input type="file" name="uploaded_file">

 *What is 2+2? (Anti-spam)
 <input name="human" placeholder="Type Here">*<?php echo $humanErr ?>

 <input type="submit" name="submit" value="Submit">
 <input type="reset" value="Clear">
<?php echo $result ?>
</form>

```

答:
You can use the PHPMailer library to send email with attachment's easily

```<code>$email = new PHPMailer();
$email->From      = 'fromemail@domain.com';
$email->FromName  = 'From Name';
$email->Subject   = 'Your Email Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'toemail@gmail.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();
</code>```

Make sure to include PHPMailer library. You can get this library from here (https://github.com/PHPMailer/PHPMailer)

As per comment request, adding upload code and email code with full example below:

```<code><?php
error_reporting(E_ALL);
 ini_set('display_errors', 1);
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = $result =  "" ;
if(isset($_POST['submit']))
{
//checking attached file and uploading it to folder
$upload_file_path = '';
if (isset($_FILES['uploaded_file']) && !empty($_FILES['uploaded_file']))
{
    $dir_path = getcwd();//getting current working directory path
    $upload_dir = $dir_path . 'uploads/';
    if (!file_exists($upload_dir))
    {
        mkdir($upload_dir, 0777, true);
    }
    $file_name = $_FILES['uploaded_file']['name'];
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);

    //validating uploaded file extension
    $valid_extensions = array('pdf', 'doc');//You can customize extension's here

    if (!in_array($ext, $valid_extensions))
    {
        exit('Please use .pdf or .doc file to upload CV.');
    }
    $upload_file_path = $upload_dir . $file_name;

    move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $upload_file_path);

}

// Let's do some checks
// Checking the First Name
if(empty($_POST["fname"])){
    $fnameErr = "Name is Required";
}else{
    $fname = test_input($_POST["fname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
      $fnameErr = "Only letters and white space allowed";
    }else{
        $check1 = 1;
    }
}
// Checking the Last Name
if(empty($_POST["lname"])){
    $lnameErr = "Name is Required";
}else{
    $lname = test_input($_POST["lname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
      $lnameErr = "Only letters and white space allowed";
    }else{
        $check2 = 1;
    }
}
//Checking the Email Adress
if(empty($_POST["email"])){
    $emailErr = "Email is Required";
}else{
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
    }else{
        $check3 = 1;
    }
}
//Checking the Anti-Spam Question
if(empty($_POST["human"])){
    $humanErr = "Please Enter the Answer";
}else{
    if ($human != 4){
        $humanErr = "Please check your answer";
    }else{
        $check4 = 1;
    }
}

// Emailing the Contents if all Checks are correct
if($check1 && $check2 && $check3 && $check4 == 1){
    mail($to, $subject, $message, $headers);
    $result =  "Message Sent Sucessfully";
}else{
    $result = "Message Can't be sent";
}
}
 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

// define contact form variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$design = $_POST['design'];
$country = $_POST['country'];
$comment = $_POST['comment'];
$human = $_POST['human'];
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = "" ;
// define Checks variables
$check1 = $check2 = $check3  = $check4 = "";
// define email variables
$to = 'eng.bolaraafat@gmail.com';
$subject = 'Contact Form';
$message = 'From: '.$fname .$lname."\r\n".
           'E-mail: '.$email."\r\n".
           'Telephone: '.$tel."\r\n".
           'Designation: '.$design."\r\n".
           'Country Appled From: '.$country."\r\n".
           'Message: '.$comment."\r\n";

$email = new PHPMailer();
$email->From      = 'fromemail@domain.com';//Your From Email
$email->FromName  = $fname;
$email->Subject   = $subject;
$email->Body      = $message;
$email->AddAddress( $email );

if (!empty($upload_file_path))
{
    $email->AddAttachment( $upload_file_path , 'CV_'.time().'.pdf' );
}

return $email->Send();

?>
</code>```

Try this and let me know if you are having any issue. Also please make sure to include phpmailer library on top of your php file.

Title: attach file to PHP contact form

Body:
You can use the PHPMailer library to send email with attachment's easily

$email = new PHPMailer();
$email->From      = 'fromemail@domain.com';
$email->FromName  = 'From Name';
$email->Subject   = 'Your Email Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'toemail@gmail.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();

Make sure to include PHPMailer library. You can get this library from here (https://github.com/PHPMailer/PHPMailer)

As per comment request, adding upload code and email code with full example below:

<?php
error_reporting(E_ALL);
 ini_set('display_errors', 1);
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = $result =  "" ;
if(isset($_POST['submit']))
{
//checking attached file and uploading it to folder
$upload_file_path = '';
if (isset($_FILES['uploaded_file']) && !empty($_FILES['uploaded_file']))
{
    $dir_path = getcwd();//getting current working directory path
    $upload_dir = $dir_path . 'uploads/';
    if (!file_exists($upload_dir))
    {
        mkdir($upload_dir, 0777, true);
    }
    $file_name = $_FILES['uploaded_file']['name'];
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);

    //validating uploaded file extension
    $valid_extensions = array('pdf', 'doc');//You can customize extension's here

    if (!in_array($ext, $valid_extensions))
    {
        exit('Please use .pdf or .doc file to upload CV.');
    }
    $upload_file_path = $upload_dir . $file_name;

    move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $upload_file_path);

}

// Let's do some checks
// Checking the First Name
if(empty($_POST["fname"])){
    $fnameErr = "Name is Required";
}else{
    $fname = test_input($_POST["fname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
      $fnameErr = "Only letters and white space allowed";
    }else{
        $check1 = 1;
    }
}
// Checking the Last Name
if(empty($_POST["lname"])){
    $lnameErr = "Name is Required";
}else{
    $lname = test_input($_POST["lname"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
      $lnameErr = "Only letters and white space allowed";
    }else{
        $check2 = 1;
    }
}
//Checking the Email Adress
if(empty($_POST["email"])){
    $emailErr = "Email is Required";
}else{
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
    }else{
        $check3 = 1;
    }
}
//Checking the Anti-Spam Question
if(empty($_POST["human"])){
    $humanErr = "Please Enter the Answer";
}else{
    if ($human != 4){
        $humanErr = "Please check your answer";
    }else{
        $check4 = 1;
    }
}

// Emailing the Contents if all Checks are correct
if($check1 && $check2 && $check3 && $check4 == 1){
    mail($to, $subject, $message, $headers);
    $result =  "Message Sent Sucessfully";
}else{
    $result = "Message Can't be sent";
}
}
 function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

// define contact form variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$design = $_POST['design'];
$country = $_POST['country'];
$comment = $_POST['comment'];
$human = $_POST['human'];
// define Errors variables
$fnameErr = $lnameErr = $emailErr = $humanErr = "" ;
// define Checks variables
$check1 = $check2 = $check3  = $check4 = "";
// define email variables
$to = 'eng.bolaraafat@gmail.com';
$subject = 'Contact Form';
$message = 'From: '.$fname .$lname."\r\n".
           'E-mail: '.$email."\r\n".
           'Telephone: '.$tel."\r\n".
           'Designation: '.$design."\r\n".
           'Country Appled From: '.$country."\r\n".
           'Message: '.$comment."\r\n";

$email = new PHPMailer();
$email->From      = 'fromemail@domain.com';//Your From Email
$email->FromName  = $fname;
$email->Subject   = $subject;
$email->Body      = $message;
$email->AddAddress( $email );

if (!empty($upload_file_path))
{
    $email->AddAttachment( $upload_file_path , 'CV_'.time().'.pdf' );
}

return $email->Send();

?>

Try this and let me know if you are having any issue. Also please make sure to include phpmailer library on top of your php file.


问:
ClassNotFoundException when submitting JAR to Spark via spark-submit
I'm struggling to submit a JAR to Apache Spark using spark-submit.

To make things easier, I've experimented using this blog post. The code is

```<code>import org.apache.spark.SparkContext
import org.apache.spark.SparkConf

object SimpleScalaSpark {
  def main(args: Array[String]) {
    val logFile = "/Users/toddmcgrath/Development/spark-1.6.1-bin-hadoop2.4/README.md" // I've replaced this with the path to an existing file
    val conf = new SparkConf().setAppName("Simple Application").setMaster("local[*]")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
  }
}
</code>```

I'm running building this with Intellij Idea 2017.1 and running on Spark 2.1.0. Everything is running fine when I run it in the IDE.

I then build it as a JAR and attempt to use spark-submit as follows

```<code>./spark-submit --class SimpleScalaSpark --master local[*] ~/Documents/Spark/Scala/supersimple/out/artifacts/supersimple_jar/supersimple.jar
</code>```

This results in the following error

```<code>java.lang.ClassNotFoundException: SimpleScalaSpark
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:229)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:695)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

I'm at a loss as to what I'm missing...especially given that it runs as expected in the IDE.

答:
Looks like there is an issue with your jar. You can check what classes are present in your jar by using the command:
vi supersimple.jar

If SimpleScalaSpark class does not appear in the output of the previous command, that means your jar is not built properly.

Body:
I'm struggling to submit a JAR to Apache Spark using spark-submit.

To make things easier, I've experimented using this blog post. The code is

import org.apache.spark.SparkContext
import org.apache.spark.SparkConf

object SimpleScalaSpark {
  def main(args: Array[String]) {
    val logFile = "/Users/toddmcgrath/Development/spark-1.6.1-bin-hadoop2.4/README.md" // I've replaced this with the path to an existing file
    val conf = new SparkConf().setAppName("Simple Application").setMaster("local[*]")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
  }
}

I'm running building this with Intellij Idea 2017.1 and running on Spark 2.1.0. Everything is running fine when I run it in the IDE.

I then build it as a JAR and attempt to use spark-submit as follows

./spark-submit --class SimpleScalaSpark --master local[*] ~/Documents/Spark/Scala/supersimple/out/artifacts/supersimple_jar/supersimple.jar

This results in the following error

java.lang.ClassNotFoundException: SimpleScalaSpark
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:229)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:695)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

I'm at a loss as to what I'm missing...especially given that it runs as expected in the IDE.


问:
JAVA: non-static variable randomNums cannot be referenced from a static context
```<code>import java.util.Random;
public class Enemy extends Character{
Random randomNums = new Random();

public Enemy (Type enemyType){
    super(enemyType);
}

public int dropCoins(){
    return randomNums.nextInt((50-30)+1)+30;
}

public static int getNumGoblins(){
    return randomNums.nextInt((5-2)+1)+2;
}
public static int getNumSkeletons(){
    return randomNums.nextInt((7-3)+1)+3;
}
</code>```

}

```<code>import java.util.Random;
public class Player extends Character{
// attributes for the plauer class
// initilizes the fields
private int coins;
private Potion[] inventory;
Random randomNums = new Random();

//methods

public Player(Type playerType){
    super(playerType);
    coins = 0;
    inventory = new Potion[5];
}

public void increaseStrength(int strengthIncrease){

}
public int getCoins(){
    return coins;
}
public void increaseCoins(int coins){

}
public void decreaseCoins(int coins){

}
public void addToInventory(String a, Type potion){

}
public void removeFromInventory(int index){

}
public void displayInventory(){

}
/*public int getNumOpenSlots(){
    return numOpenSlots;
}*/

public void battleMinion(Enemy enemy){

    Enemy goblin = new Enemy(Character.Type.GOBLIN);

    if (enemy.getName() == "Goblin"){
        for (int i = 1; i <= goblin.getNumGoblins(); i++)
        {
          System.out.printf("***%s vs %s %d***\n", getName(), enemy.getName(), i);

public abstract class Character{

public enum Type{ ROGUE, PALADIN, JACKIE_CHEN, SKELETON, GOBLIN, WIZARD}

private String name;
private int hitPoints;
private int strength;
private Weapon weapon;
//other attributes

//methods

public Character(Type characterType){
    switch(characterType){
        case ROGUE:
            //set the attributes for a Rogue
            name = "Rogue";
            // TODO: set other attributes
            hitPoints = 55;
            strength = 8;
            Weapon rogue = new Weapon("Short Sword", 1, 4);

            break;
        case PALADIN:
            //set the attributes for a Rogue
            name = "Paladin";
            // TODO: set other attributes
            hitPoints = 35;
            strength = 14;
            Weapon paladin = new Weapon("Long Sword",3,7);
            break;
        case JACKIE_CHEN:
            name = "Jackie Chen";
            hitPoints =45;
            strength = 10;
            Weapon jackie = new Weapon("Jump Kick",2, 6);
            break;
        case SKELETON:
            name = "Skeleton";
            hitPoints = 25;
            strength = 3;
            Weapon skeleton = new Weapon("Short Sword" ,1, 4);
            break;
        case GOBLIN:
            name = "Goblin";
            hitPoints = 25;
            strength = 4;
            Weapon goblin = new Weapon("Axe",2,6);
            break;
        case WIZARD:
            name = "Wizard";
            hitPoints = 40;
            strength = 8;
            Weapon wizard = new Weapon("Fire Blast", 4, 10);
            break;
    }
}

public String getName(){
    return name;
}

public int getHitPoints(){
    return hitPoints;
}
public int getStrength(){
    return strength;
}
public void setStrength(int _strength){
    this.strength =_strength;
}
public void setWeapon(Weapon _weapon){
    this.weapon = _weapon;

}

public void attack(){

}

public void increaseHitPoints(){

}
public void decreaseHitPoints(){

}
</code>```

get error message

```<code>./Enemy.java:14: error: non-static variable randomNums cannot be referenced from a static context
        return randomNums.nextInt((5-2)+1)+2;
               ^
./Enemy.java:17: error: non-static variable randomNums cannot be referenced from a static context
        return randomNums.nextInt((7-3)+1)+3;
               ^
</code>```

2 errors

No idea how to figure it out...

答:
You are trying to refer non-static member inside static method, which is not allowed.

```<code>public static int getNumGoblins(){
    return randomNums.nextInt((5-2)+1)+2;
}
public static int getNumSkeletons(){
    return randomNums.nextInt((7-3)+1)+3;
}
</code>```

You need to declare randomNums as static

```<code>static Random randomNums = new Random();
</code>```

Body:
import java.util.Random;
public class Enemy extends Character{
Random randomNums = new Random();

public Enemy (Type enemyType){
    super(enemyType);
}

public int dropCoins(){
    return randomNums.nextInt((50-30)+1)+30;
}

public static int getNumGoblins(){
    return randomNums.nextInt((5-2)+1)+2;
}
public static int getNumSkeletons(){
    return randomNums.nextInt((7-3)+1)+3;
}

}

import java.util.Random;
public class Player extends Character{
// attributes for the plauer class
// initilizes the fields
private int coins;
private Potion[] inventory;
Random randomNums = new Random();

//methods

public Player(Type playerType){
    super(playerType);
    coins = 0;
    inventory = new Potion[5];
}

public void increaseStrength(int strengthIncrease){

}
public int getCoins(){
    return coins;
}
public void increaseCoins(int coins){

}
public void decreaseCoins(int coins){

}
public void addToInventory(String a, Type potion){

}
public void removeFromInventory(int index){

}
public void displayInventory(){

}
/*public int getNumOpenSlots(){
    return numOpenSlots;
}*/

public void battleMinion(Enemy enemy){

    Enemy goblin = new Enemy(Character.Type.GOBLIN);

    if (enemy.getName() == "Goblin"){
        for (int i = 1; i <= goblin.getNumGoblins(); i++)
        {
          System.out.printf("***%s vs %s %d***\n", getName(), enemy.getName(), i);

public abstract class Character{

public enum Type{ ROGUE, PALADIN, JACKIE_CHEN, SKELETON, GOBLIN, WIZARD}

private String name;
private int hitPoints;
private int strength;
private Weapon weapon;
//other attributes

//methods

public Character(Type characterType){
    switch(characterType){
        case ROGUE:
            //set the attributes for a Rogue
            name = "Rogue";
            // TODO: set other attributes
            hitPoints = 55;
            strength = 8;
            Weapon rogue = new Weapon("Short Sword", 1, 4);

            break;
        case PALADIN:
            //set the attributes for a Rogue
            name = "Paladin";
            // TODO: set other attributes
            hitPoints = 35;
            strength = 14;
            Weapon paladin = new Weapon("Long Sword",3,7);
            break;
        case JACKIE_CHEN:
            name = "Jackie Chen";
            hitPoints =45;
            strength = 10;
            Weapon jackie = new Weapon("Jump Kick",2, 6);
            break;
        case SKELETON:
            name = "Skeleton";
            hitPoints = 25;
            strength = 3;
            Weapon skeleton = new Weapon("Short Sword" ,1, 4);
            break;
        case GOBLIN:
            name = "Goblin";
            hitPoints = 25;
            strength = 4;
            Weapon goblin = new Weapon("Axe",2,6);
            break;
        case WIZARD:
            name = "Wizard";
            hitPoints = 40;
            strength = 8;
            Weapon wizard = new Weapon("Fire Blast", 4, 10);
            break;
    }
}

public String getName(){
    return name;
}

public int getHitPoints(){
    return hitPoints;
}
public int getStrength(){
    return strength;
}
public void setStrength(int _strength){
    this.strength =_strength;
}
public void setWeapon(Weapon _weapon){
    this.weapon = _weapon;

}

public void attack(){

}

public void increaseHitPoints(){

}
public void decreaseHitPoints(){

}

get error message

./Enemy.java:14: error: non-static variable randomNums cannot be referenced from a static context
        return randomNums.nextInt((5-2)+1)+2;
               ^
./Enemy.java:17: error: non-static variable randomNums cannot be referenced from a static context
        return randomNums.nextInt((7-3)+1)+3;
               ^

2 errors

No idea how to figure it out...

Body:
You are trying to refer non-static member inside static method, which is not allowed.

public static int getNumGoblins(){
    return randomNums.nextInt((5-2)+1)+2;
}
public static int getNumSkeletons(){
    return randomNums.nextInt((7-3)+1)+3;
}

You need to declare randomNums as static

static Random randomNums = new Random();


问:
Resource leak: 'sc' is never closed
Program to count how many times a particular character, letter or number occur in a sentence.

However I keep getting message:

Resource leak: 'sc' is never closed

I am using Java and Eclipse. What should I do?

import java.util.Scanner;
class Number-count {
    public static void number - count(String args[]) {
        String s;
        char ch;
        int count = 0;
        Scanner SC = new Scanner(System. in );
        System.out.println("Enter a sentence");
        String str = sc.nextLine();
        System.out.println("Enter a character to be searched for occurence");
        s = sc.nextLine();
        char c = s.charAt(0);
        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);
            if (ch == c) {
                count++;
            }
        }
        System.out.println("Character " + c + " occur " + count + " times");
    }
}
```

答:
Scanner objects need to be closed after one is done using them. So, after you're done with it you should call the following before the end of your main method</p>

```<code>SC.close();
</code>```

Title: Resource leak: 'sc' is never closed

Body:
Scanner objects need to be closed after one is done using them. So, after you're done with it you should call the following before the end of your main method

SC.close();


问:
Using TTPhotoViewController without the Three20's URL system?
Whenever I add the TTPhotoViewController to my window , it appears without a top navigation bar and once I tap the image, the bottom navigation overlay and the status bar (the springboard one) will disappear permanently. How do I create a top navigation bar so I can add a button to hide the view after it was shown and how do I restore the overlays/toolbars after a tap?

```<code>[window addSubview:viewController.view];
</code>```

I am not using Three20's URL mapping system because I see no point in doing that. I think that might be causing the problem but I think there is a sensible solution. Using the URL system is not a solution for me.

答:
Why not just like this:
- Create a ViewController inheriting from TTPhotViewController

```<code>MGSPhotoViewController *photoViewController = [[MGSPhotoViewController alloc] init];
[self.navigationController pushViewController:photoViewController animated:YES];
[photoViewController release];
</code>```

it works like a charm.

One thing you need to consider:

If you com back to the previous view controller you'll need to change the tintColor of the NavigationBar because it remains black somehow.

Body:
Whenever I add the TTPhotoViewController to my window , it appears without a top navigation bar and once I tap the image, the bottom navigation overlay and the status bar (the springboard one) will disappear permanently. How do I create a top navigation bar so I can add a button to hide the view after it was shown and how do I restore the overlays/toolbars after a tap?

[window addSubview:viewController.view];

I am not using Three20's URL mapping system because I see no point in doing that. I think that might be causing the problem but I think there is a sensible solution. Using the URL system is not a solution for me.

Body:
Why not just like this:
- Create a ViewController inheriting from TTPhotViewController

MGSPhotoViewController *photoViewController = [[MGSPhotoViewController alloc] init];
[self.navigationController pushViewController:photoViewController animated:YES];
[photoViewController release];

it works like a charm.

One thing you need to consider:

If you com back to the previous view controller you'll need to change the tintColor of the NavigationBar because it remains black somehow.


问:
SSRS Charts: solution for better assignment of colors to the legend
If you have a line chart in SSRS with many lines, it is nearly impossible to identify which line belongs to which item in the legend, as the colors are nearly the same. Is there a better solution?

bad example of line chart legend

答:
Some suggestions that may help:

Group some of the values into an Other group. It looks like you have
some values that come and go, or don't run for the full timeframe of the
report, lumping these into an Other group will mean less legend items.

Move the legend to the bottom of the chart. This can sometimes make
the legend easier to see; this is not a good option when have a lot
more legend items than what you have now.

Use more than one chart; one chart for each line is possible. This
may be a good option for you. Use more than one chart, and only
display certain values in each. Perhaps you have some natural
grouping in the data that isn’t obvious from what you have provided
in the question. If you do, use that to separate the values into
different charts.

Use a different color theme. The theme you are using now would leave
any color-blind person wondering what was in the chart at all.

Make the chart larger. You just never know, this may work.

Use a column chart rather than a line chart. The bars are wider, and
can be easier to see. Plus, with the way your values come and go, it
may be a better way to visualize the data.

Limit the timeframe of the data being displayed. Having less data may
make this look better, but that may defeat the purpose of the report.
Still, it’s an option.

Good luck.


问:
CallInst constructor is private?
I am trying to build a simple version of a code analysis tool with LLVM.I have a few .ll files that contain the intermediate LLVM representation of certain programs and I'm trying to get the list of function calls that are performed in each function of the program.

This is my code, obtained thanks to the answers from my previous post here.

```<code>void getFunctionCalls(const Module *M)
{

   for (const Function &F : *M) {
      for (const BasicBlock &BB : F) {
        for (const Instruction &I : BB) {
          if (CallInst callInst = dyn_cast<CallInst>(I)) {
            if (Function *calledFunction = callInst->getCalledFunction())     {
              if (calledFunction->getName().startswith("llvm.dbg.declare")) {

                // Do something

              }
            }
          }
        }
      }
    }

}
</code>```

When I compile it, I get an error saying :

```<code>home/kike/llvm-3.9.0.src/include/llvm/IR/Instructions.h: In function ‘void getFunctionCalls(const llvm::Module*)’:

/home/kike/llvm-3.9.0.src/include/llvm/IR/Instructions.h:1357:3: error: ‘llvm::CallInst::CallInst(const llvm::CallInst&)’ is private
</code>```

It means that the CallInst constructor is private? In this case, How can I do to get the list of function calls?

[Edit 1]:

I have also tried to pass I as a reference, like this:

```<code>void getFunctionCalls(const Module *M)
{

   for (const Function &F : *M) {
      for (const BasicBlock &BB : F) {
        for (const Instruction &I : BB) {
          if (CallInst * callInst = dyn_cast<CallInst>(&I)) {
            if (Function *calledFunction = callInst->getCalledFunction())     {
              if (calledFunction->getName().startswith("llvm.dbg.declare")) {

                // Do something

              }
            }
          }
        }
      }
    }

}
</code>```

And I get this error:

```<code>invalid conversion from ‘llvm::cast_retty<llvm::CallInst, const llvm::Instruction*>::ret_type {aka const llvm::CallInst*}’ to ‘llvm::CallInst*’
</code>```

答:
CallInst does not have a copy constructor because it was not meant to be passed by value. Use </p>

```<code>const CallInst* callInst = dyn_cast<CallInst>(&I)
</code>```

<p>instead of </p>

```<code>CallInst callInst = dyn_cast<CallInst>(I)
</code>```

Title: CallInst constructor is private?

Body:
I am trying to build a simple version of a code analysis tool with LLVM.I have a few .ll files that contain the intermediate LLVM representation of certain programs and I'm trying to get the list of function calls that are performed in each function of the program.

This is my code, obtained thanks to the answers from my previous post here.

void getFunctionCalls(const Module *M)
{

   for (const Function &F : *M) {
      for (const BasicBlock &BB : F) {
        for (const Instruction &I : BB) {
          if (CallInst callInst = dyn_cast<CallInst>(I)) {
            if (Function *calledFunction = callInst->getCalledFunction())     {
              if (calledFunction->getName().startswith("llvm.dbg.declare")) {

                // Do something

              }
            }
          }
        }
      }
    }

}

When I compile it, I get an error saying :

home/kike/llvm-3.9.0.src/include/llvm/IR/Instructions.h: In function ‘void getFunctionCalls(const llvm::Module*)’:

/home/kike/llvm-3.9.0.src/include/llvm/IR/Instructions.h:1357:3: error: ‘llvm::CallInst::CallInst(const llvm::CallInst&)’ is private

It means that the CallInst constructor is private? In this case, How can I do to get the list of function calls?

[Edit 1]:

I have also tried to pass I as a reference, like this:

void getFunctionCalls(const Module *M)
{

   for (const Function &F : *M) {
      for (const BasicBlock &BB : F) {
        for (const Instruction &I : BB) {
          if (CallInst * callInst = dyn_cast<CallInst>(&I)) {
            if (Function *calledFunction = callInst->getCalledFunction())     {
              if (calledFunction->getName().startswith("llvm.dbg.declare")) {

                // Do something

              }
            }
          }
        }
      }
    }

}

And I get this error:

invalid conversion from ‘llvm::cast_retty<llvm::CallInst, const llvm::Instruction*>::ret_type {aka const llvm::CallInst*}’ to ‘llvm::CallInst*’

Body:
CallInst does not have a copy constructor because it was not meant to be passed by value. Use

const CallInst* callInst = dyn_cast<CallInst>(&I)

instead of

CallInst callInst = dyn_cast<CallInst>(I)


问:
Converting Java 1.8 lambdas to Java 1.7 on gs-uploading-files Spring Boot example
I am running through some exercises on https://spring.io/ Spring Boot.

Doing example https://spring.io/guides/gs/uploading-files/ and it works fine when I use Java 8, but unfortunately the code I am wrapping in a web service requires Java 7.  I have listed all of the erroring code, can someone help me convert the lambdas to 1.7 compliant code and replace the new libraries (java.util.stream.Stream and java.util.stream.Collectors).

Application.java

```<code>@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();
        };
    }
}
</code>```

return (args) -> errors out saying "use source -8 or higher to enable
  lambda expressions"

FileUploadController.java

```<code>import java.util.stream.Collectors

//..

@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {

    model.addAttribute("files", storageService
            .loadAll()
            .map(path ->
                    MvcUriComponentsBuilder
                            .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                            .build().toString())
            .collect(Collectors.toList()));

    return "uploadForm";
}
</code>```

package java.util.stream does not exist

type loadAll() is erroneous

errors out saying "use source -8 or higher to enable
  lambda expressions"

FileSystemStorageService.java

```<code>@Override
public Stream<Path> loadAll() {
    try {
        return Files.walk(this.rootLocation, 1)
                .filter(path -> !path.equals(this.rootLocation))
                .map(path -> this.rootLocation.relativize(path));
    } catch (IOException e) {
        throw new StorageException("Failed to read stored files", e);
    }

}
</code>```

cannot find symbol walk

errors out saying "use source -8 or higher to enable
  lambda expressions"

StorageService.java

```<code>import java.util.stream.Stream;

public interface StorageService {

    void init();

    void store(MultipartFile file);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}
</code>```

package java.util.stream does not exist

答:
Building on SergGr's and Veeram's excellent answers I'll show an alternative implementation of the two critical methods that depend on the Java 8 Stream API (loadAll() and listUploadedFiles()) using the streamsupport backport of the Stream API already mentioned in SergGr's answer.

This implementation doesn't use lambdas (though that could easily be done using retrolambda) because it is probably overkill to introduce retrolambda for only a couple of lambda expressions.

FileSystemStorageService.java

```<code>import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;

import java8.util.Spliterator;
import java8.util.Spliterators;
import java8.util.function.Function;
import java8.util.function.Predicate;
import java8.util.stream.Stream;
import java8.util.stream.StreamSupport;

public class FileSystemStorageService implements StorageService {

    @Override
    public Stream<Path> loadAll() {
        try {
            final DirectoryStream<Path> ds = Files.newDirectoryStream(rootLocation);
            return StreamSupport
                    .stream(Spliterators.spliteratorUnknownSize(
                            ds.iterator(), Spliterator.DISTINCT), false)
                    .onClose(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ds.close();
                            } catch (IOException e) {
                                throw new StorageException(
                                        "Failed to close stream", e);
                            }
                        }
                    })
                    .filter(new Predicate<Path>() {
                        @Override
                        public boolean test(Path path) {
                            return !path.equals(rootLocation);
                        }
                    }).map(new Function<Path, Path>() {
                        @Override
                        public Path apply(Path path) {
                            return rootLocation.relativize(path);
                        }
                    });
        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }
    }
}
</code>```

FileUploadController.java

```<code>import java.io.IOException;
import java.nio.file.Path;

import java8.util.function.Function;
import java8.util.stream.Collectors;
import java8.util.stream.Stream;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;

public class FileUploadController {

    @GetMapping("/")
    public String listUploadedFiles(Model model) throws IOException {

        Stream<Path> stream = null;
        try {
            stream = storageService.loadAll();
            model.addAttribute("files",
                    stream.map(new Function<Path, String>() {
                        public String apply(Path path) {
                            return MvcUriComponentsBuilder
                                    .fromMethodName(FileUploadController.class,
                                            "serveFile",
                                            path.getFileName().toString()).build()
                                    .toString();
                        }
                    }).collect(Collectors.toList()));
        } finally {
            if (stream != null) {
                stream.close();
            }
        }

        return "uploadForm";
    }
}
</code>```

pom.xml

```<code><dependency>
    <groupId>net.sourceforge.streamsupport</groupId>
    <artifactId>streamsupport</artifactId>
    <version>1.5.4</version>
</dependency>
</code>```

Hope this helps you get going. Disclaimer: Note that I haven't tested this!

Body:
I am running through some exercises on https://spring.io/ Spring Boot.

Doing example https://spring.io/guides/gs/uploading-files/ and it works fine when I use Java 8, but unfortunately the code I am wrapping in a web service requires Java 7.  I have listed all of the erroring code, can someone help me convert the lambdas to 1.7 compliant code and replace the new libraries (java.util.stream.Stream and java.util.stream.Collectors).

Application.java

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();
        };
    }
}

return (args) -> errors out saying "use source -8 or higher to enable
  lambda expressions"

FileUploadController.java

import java.util.stream.Collectors

//..

@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {

    model.addAttribute("files", storageService
            .loadAll()
            .map(path ->
                    MvcUriComponentsBuilder
                            .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                            .build().toString())
            .collect(Collectors.toList()));

    return "uploadForm";
}

package java.util.stream does not exist

type loadAll() is erroneous

errors out saying "use source -8 or higher to enable
  lambda expressions"

FileSystemStorageService.java

@Override
public Stream<Path> loadAll() {
    try {
        return Files.walk(this.rootLocation, 1)
                .filter(path -> !path.equals(this.rootLocation))
                .map(path -> this.rootLocation.relativize(path));
    } catch (IOException e) {
        throw new StorageException("Failed to read stored files", e);
    }

}

cannot find symbol walk

errors out saying "use source -8 or higher to enable
  lambda expressions"

StorageService.java

import java.util.stream.Stream;

public interface StorageService {

    void init();

    void store(MultipartFile file);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}

package java.util.stream does not exist

Body:
Building on SergGr's and Veeram's excellent answers I'll show an alternative implementation of the two critical methods that depend on the Java 8 Stream API (loadAll() and listUploadedFiles()) using the streamsupport backport of the Stream API already mentioned in SergGr's answer.

This implementation doesn't use lambdas (though that could easily be done using retrolambda) because it is probably overkill to introduce retrolambda for only a couple of lambda expressions.

FileSystemStorageService.java

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;

import java8.util.Spliterator;
import java8.util.Spliterators;
import java8.util.function.Function;
import java8.util.function.Predicate;
import java8.util.stream.Stream;
import java8.util.stream.StreamSupport;

public class FileSystemStorageService implements StorageService {

    @Override
    public Stream<Path> loadAll() {
        try {
            final DirectoryStream<Path> ds = Files.newDirectoryStream(rootLocation);
            return StreamSupport
                    .stream(Spliterators.spliteratorUnknownSize(
                            ds.iterator(), Spliterator.DISTINCT), false)
                    .onClose(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ds.close();
                            } catch (IOException e) {
                                throw new StorageException(
                                        "Failed to close stream", e);
                            }
                        }
                    })
                    .filter(new Predicate<Path>() {
                        @Override
                        public boolean test(Path path) {
                            return !path.equals(rootLocation);
                        }
                    }).map(new Function<Path, Path>() {
                        @Override
                        public Path apply(Path path) {
                            return rootLocation.relativize(path);
                        }
                    });
        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }
    }
}

FileUploadController.java

import java.io.IOException;
import java.nio.file.Path;

import java8.util.function.Function;
import java8.util.stream.Collectors;
import java8.util.stream.Stream;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;

public class FileUploadController {

    @GetMapping("/")
    public String listUploadedFiles(Model model) throws IOException {

        Stream<Path> stream = null;
        try {
            stream = storageService.loadAll();
            model.addAttribute("files",
                    stream.map(new Function<Path, String>() {
                        public String apply(Path path) {
                            return MvcUriComponentsBuilder
                                    .fromMethodName(FileUploadController.class,
                                            "serveFile",
                                            path.getFileName().toString()).build()
                                    .toString();
                        }
                    }).collect(Collectors.toList()));
        } finally {
            if (stream != null) {
                stream.close();
            }
        }

        return "uploadForm";
    }
}

pom.xml

<dependency>
    <groupId>net.sourceforge.streamsupport</groupId>
    <artifactId>streamsupport</artifactId>
    <version>1.5.4</version>
</dependency>

Hope this helps you get going. Disclaimer: Note that I haven't tested this!


问:
Collection view Cell crashing
I was connecting my Collection view cell to a custom one but it crashes, I already wrote the classname of the custom cell and created the class, but when I am casting the dequeueReusableCell it crashes

```<code>override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PlatformCollectionViewCell
    if let platformCell = cell as? PlatformCollectionViewCell {
        platformCell.backgroundColor = UIColor.blue
        platformCell.titleLabel.text = "Hola"
        return cell
    }
    cell.backgroundColor = UIColor.green
    return cell
}
</code>```

The only possible error that I found is when it gives me the error it says something like

Could not cast value of type 'UICollectionViewCell' (0x1b12070b0) to 'Quote.PlatformCollectionViewCell' (0x1000bba00).
2017-04-02 13:24:32.711435+0200 Quote[1219:351279] Could not cast value of type 'UICollectionViewCell' (0x1b12070b0) to 'Quote.PlatformCollectionViewCell' (0x1000bba00).

I don't know if is okay that it says "NameOfTheProject.Class" in the last line. I think it should say just the class but I don't know how to fix this, in the case this is the error

the class PlatformCollectionViewCell is this

//

```<code>import UIKit

class PlatformCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var titleLabel: UILabel!

}
</code>```

答:
The error message is telling you exactly what's wrong. The call to collectionView.dequeueReusableCell() is returning a normal UICollectionViewCell, not an instance of your custom cell.

You need to open our view controller in IB, select the cell prototype with your identifier, and use the "identity inspector" to check the class of that cell. My guess is that you forgot to switch the class to your custom cell class, PlatformCollectionViewCell. If so, simply change UICollectionViewCell``UICollectionViewCell toPlatformCollectionViewCell` in the identity inspector.

Alternately, you can call register(_:forCellWithReuseIdentifier:) to register an XIB or a class name for your reuse identifier.

Title: Collection view Cell crashing

Body:
I was connecting my Collection view cell to a custom one but it crashes, I already wrote the classname of the custom cell and created the class, but when I am casting the dequeueReusableCell it crashes

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PlatformCollectionViewCell
    if let platformCell = cell as? PlatformCollectionViewCell {
        platformCell.backgroundColor = UIColor.blue
        platformCell.titleLabel.text = "Hola"
        return cell
    }
    cell.backgroundColor = UIColor.green
    return cell
}

The only possible error that I found is when it gives me the error it says something like

Could not cast value of type 'UICollectionViewCell' (0x1b12070b0) to 'Quote.PlatformCollectionViewCell' (0x1000bba00).
2017-04-02 13:24:32.711435+0200 Quote[1219:351279] Could not cast value of type 'UICollectionViewCell' (0x1b12070b0) to 'Quote.PlatformCollectionViewCell' (0x1000bba00).

I don't know if is okay that it says "NameOfTheProject.Class" in the last line. I think it should say just the class but I don't know how to fix this, in the case this is the error

the class PlatformCollectionViewCell is this

//

import UIKit

class PlatformCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var titleLabel: UILabel!

}


问:
How to add a default value to EditText: android
I have an EditText which returns an empty string on calling edittext.getText().toString(). Instead of returning an empty string, I want to set a default value for this result and i don't want that value to be shown in EditText. Is it possible to do so? If yes then how can i do that?

答:
While it's not something EditText can do for you, you can always extend EditText and add this behavior:

```<code>public class MyOwnEditText extends EditText { ... }
</code>```

Override getText() to return the default value, if there's en empty String returned by default implementation:

```<code>@Override
public Editable getText() {
  Editable text = super.getText();
  if (!TextUtils.isEmpty(text)) {
    return text;
  }
  return new SpannableStringBuilder("default-text");
}
</code>```

Body:
While it's not something EditText can do for you, you can always extend EditText and add this behavior:

public class MyOwnEditText extends EditText { ... }

Override getText() to return the default value, if there's en empty String returned by default implementation:

@Override
public Editable getText() {
  Editable text = super.getText();
  if (!TextUtils.isEmpty(text)) {
    return text;
  }
  return new SpannableStringBuilder("default-text");
}


问:
In what ways is Mercurial better/worse than TFS?
I've just joined a new company and at the moment we're using Microsoft SourceSafe as our repository. The settings aren't ideal and it's proving to be a big pain in the neck.

I've recently used Mercurial and thought it was amazing, so I'm advocating switching to that, but it looks like the company already has a Team Foundation Server licence and wants to use that instead.

Can anyone give me a list of points where one is better than the other? I've not used TFS and so I don't know what it's good/bad at.

答:
I have found a few gotchas with TFS that make it a little different than other CVCS.

TFS is very difficult to use outside of Visual Studio. Even diffing versions is done inside VS. Personally I only like to use VS for writing code.

We have had lots of issues with dll's and other binary files not updating to the latest version.

TFS makes all your files under version control read-only. This makes modifying files outside of VS very painful. In fact, this is still causing issues with out Silverlight projects in our Continuous Integration build in TFS.

The command line tool for TFS is not easy to use from the command line. (Personally, I like to use the command line)

Background:
My company switched from SVN and TFS and I use Mercurial/Git for my side projects. I also followed this blog about using Mercurial with TFS and it has made my work with TFS much more enjoyable.


问:
Adding a ReadOnly property to MaterialSingleLineTextField
How to add a ReadOnly property to this control?

The control doesn't have a ReadOnly property.
I'm a beginner in C# and all I can think for now is this:

```<code>public class MaterialSingleLineTextFieldRO : MaterialSingleLineTextField
{
    public bool ReadOnly { ... };
}
</code>```

答:
Define it like any other property, but in setter, put desired behavior.

Since the MaterialSingleLineTextFieldRO uses a private baseTextBox field, you need to use reflection to find it and make it read only:

```<code>public class MyControl : MaterialSingleLineTextField
{
    bool readOnly;
    public bool ReadOnly
    {
        get { return readOnly; }
        set
        {
            readOnly = value;
            GetTextBoxControl().ReadOnly = value;
        }
    }
    private TextBox GetTextBoxControl()
    {
        var f = typeof(MaterialSingleLineTextField).GetField("baseTextBox",
                    System.Reflection.BindingFlags.NonPublic |
                    System.Reflection.BindingFlags.Instance);
        return (TextBox)f.GetValue(this);
    }
}
</code>```

Body:
How to add a ReadOnly property to this control?

The control doesn't have a ReadOnly property.
I'm a beginner in C# and all I can think for now is this:

public class MaterialSingleLineTextFieldRO : MaterialSingleLineTextField
{
    public bool ReadOnly { ... };
}

Body:
Define it like any other property, but in setter, put desired behavior.

Since the MaterialSingleLineTextFieldRO uses a private baseTextBox field, you need to use reflection to find it and make it read only:

public class MyControl : MaterialSingleLineTextField
{
    bool readOnly;
    public bool ReadOnly
    {
        get { return readOnly; }
        set
        {
            readOnly = value;
            GetTextBoxControl().ReadOnly = value;
        }
    }
    private TextBox GetTextBoxControl()
    {
        var f = typeof(MaterialSingleLineTextField).GetField("baseTextBox",
                    System.Reflection.BindingFlags.NonPublic |
                    System.Reflection.BindingFlags.Instance);
        return (TextBox)f.GetValue(this);
    }
}


问:
how to use this element of edittext in android

when input is not valid, instead of toast or sth else this kind of new thing appears to warn the user . Does anyone know how I can use it in my own app  ?
Image is attached . Tnx in advance .

答:
You need to call myEditText.setError("insert error message here")
One gotcha is that ifmyEditText is not the one that is currently focused you will not see the error message itself, just the exclamation mark like in the below example.

To avoid this you should always call myEditText.requestFocus() before calling setError

Lastly, to clear the error just call myEditText.setError(null)


问:
-webkit-box-orient: vertical; in sass is not compiled in gulp
In sass file

```<code>h3 {
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                line-height: 24px;
                max-height: 24px;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
            }
</code>```

After running gulp task, getting in css as

```<code> .article-list.search .article-listings__item h3 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  line-height: 24px;
  max-height: 24px;
  -webkit-line-clamp: 1;
}
</code>```

The style -webkit-box-orient: vertical; is missing in css file.

My gulp task for sass compilation is

```<code>gulp.task('styles', function() {
  return sass('src/assets/stylesheets/index.scss', { style: 'expanded' })
    .pipe(autoprefixer('last 2 version'))
    .pipe(gulp.dest('dist/styles'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(cleanCSS())
    .pipe(gulp.dest('dist/styles'))
    .pipe(notify({ message: 'Styles task complete' }));
});
</code>```

答:
Look this issus on Github.

config autoprefixer like this. Hope it can help you.

```<code>autoprefixer({
  remove: false,
  browsers: ['last 2 versions']
})
</code>```

Body:
In sass file

h3 {
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                line-height: 24px;
                max-height: 24px;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
            }

After running gulp task, getting in css as

 .article-list.search .article-listings__item h3 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  line-height: 24px;
  max-height: 24px;
  -webkit-line-clamp: 1;
}

The style -webkit-box-orient: vertical; is missing in css file.

My gulp task for sass compilation is

gulp.task('styles', function() {
  return sass('src/assets/stylesheets/index.scss', { style: 'expanded' })
    .pipe(autoprefixer('last 2 version'))
    .pipe(gulp.dest('dist/styles'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(cleanCSS())
    .pipe(gulp.dest('dist/styles'))
    .pipe(notify({ message: 'Styles task complete' }));
});

Body:
Look this issus on Github.

config autoprefixer like this. Hope it can help you.

autoprefixer({
  remove: false,
  browsers: ['last 2 versions']
})


问:
Randomly generate more proportion of zeroes python
I want to simulate a variable which can have values between 0 and 1. But I also want that this random variable to have 80% zeroes. Currently I ma doing the following:

```<code>data['response']=np.random.uniform(0,1,15000)#simulate response
data['response']=data['response'].apply(lambda x:0 if x<0.85 else x)
</code>```

But this results in only the extreme values(0 and .8+) in the variable. I want to have 80 percent zeroes and rest 20% rows to have values between zero and one. This has to be done randomly.

答:
Here's one approach with np.random.choice, which would suit here with its optional input argument replace set as False or 0 to generate unique indices along the entire length of 15000 and then generate those random numbers with np.random.uniform and assign.

Thus, the implementation would look something along these lines -

```<code># Parameters
s = 15000 # Length of array
zeros_ratio = 0.8 # Ratio of zeros expected in the array

out = np.zeros(s) # Initialize output array
nonzeros_count = int(np.rint(s*(1-zeros_ratio))) # Count of nonzeros in array

# Generate unique indices where nonzeros are to be placed
idx = np.random.choice(s, nonzeros_count, replace=0)

# Generate nonzeros between 0 and 1
nonzeros_num = np.random.uniform(0,1,nonzeros_count)

# Finally asssign into those unique positions
out[idx] = nonzeros_num
</code>```

Sample run results -

```<code>In [233]: np.isclose(out, 0).sum()
Out[233]: 12000

In [234]: (~np.isclose(out, 0)).sum()
Out[234]: 3000
</code>```

Body:
I want to simulate a variable which can have values between 0 and 1. But I also want that this random variable to have 80% zeroes. Currently I ma doing the following:

data['response']=np.random.uniform(0,1,15000)#simulate response
data['response']=data['response'].apply(lambda x:0 if x<0.85 else x)

But this results in only the extreme values(0 and .8+) in the variable. I want to have 80 percent zeroes and rest 20% rows to have values between zero and one. This has to be done randomly.

Body:
Here's one approach with np.random.choice, which would suit here with its optional input argument replace set as False or 0 to generate unique indices along the entire length of 15000 and then generate those random numbers with np.random.uniform and assign.

Thus, the implementation would look something along these lines -

# Parameters
s = 15000 # Length of array
zeros_ratio = 0.8 # Ratio of zeros expected in the array

out = np.zeros(s) # Initialize output array
nonzeros_count = int(np.rint(s*(1-zeros_ratio))) # Count of nonzeros in array

# Generate unique indices where nonzeros are to be placed
idx = np.random.choice(s, nonzeros_count, replace=0)

# Generate nonzeros between 0 and 1
nonzeros_num = np.random.uniform(0,1,nonzeros_count)

# Finally asssign into those unique positions
out[idx] = nonzeros_num

Sample run results -

In [233]: np.isclose(out, 0).sum()
Out[233]: 12000

In [234]: (~np.isclose(out, 0)).sum()
Out[234]: 3000