问:
Functor with wrong type argument
I have following datatype and had apply to Functor instance:

```<code>data Company a b c =
    DeepBlue a c
  | Something b

instance Functor (Company a b) where
  fmap f (Something b) = Something b
  fmap f (DeepBlue a c) = DeepBlue a (f c)
</code>```

It gets compiled without any complains.

Then I played a bit around(I know it does not work), because of beginner curiosity:

```<code>data Company a b c =
    DeepBlue a c
  | Something b

instance Functor (Company a b) where
  fmap f (Something b) = Something (f b)
  fmap f (DeepBlue a c) = DeepBlue a (f c)
</code>```

Then the compiler complains:

```<code>D:\haskell\chapter16\src\ChapterExercises.hs:18:26: error:
    * Couldn't match type `b1' with `b'
      `b1' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a1 b1.
                  (a1 -> b1) -> Company a b a1 -> Company a b b1
        at D:\haskell\chapter16\src\ChapterExercises.hs:18:3
      `b' is a rigid type variable bound by
        the instance declaration
        at D:\haskell\chapter16\src\ChapterExercises.hs:17:10
      Expected type: Company a b b1
        Actual type: Company a b1 b1
    * In the expression: Something (f b)
      In an equation for `fmap': fmap f (Something b) = Something (f b)
      In the instance declaration for `Functor (Company a b)'
    * Relevant bindings include
        b :: b
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:21)
        f :: a1 -> b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:8)
        fmap :: (a1 -> b1) -> Company a b a1 -> Company a b b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:3)

D:\haskell\chapter16\src\ChapterExercises.hs:18:39: error:
    * Couldn't match expected type `a1' with actual type `b'
      `b' is a rigid type variable bound by
        the instance declaration
        at D:\haskell\chapter16\src\ChapterExercises.hs:17:10
      `a1' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a1 b1.
                  (a1 -> b1) -> Company a b a1 -> Company a b b1
        at D:\haskell\chapter16\src\ChapterExercises.hs:18:3
    * In the first argument of `f', namely `b'
      In the first argument of `Something', namely `(f b)'
      In the expression: Something (f b)
    * Relevant bindings include
        b :: b
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:21)
        f :: a1 -> b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:8)
        fmap :: (a1 -> b1) -> Company a b a1 -> Company a b b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:3)
Failed, modules loaded: none.
</code>```

What does the compiler try say?

答:
Your definition of fmap has type

```<code>fmap :: Company a b c -> (c -> d) -> Company a b d
</code>```

so the function takes a value of type c. In

```<code>fmap f (Something b) = Something (f b)
</code>```

you are attempting to apply a function c -> d to a value of type b which causes the error. The actual type variables in the message have different names: a1 is  c and b1 is d

Title: Functor with wrong type argument

Body:
I have following datatype and had apply to Functor instance:

data Company a b c =
    DeepBlue a c
  | Something b

instance Functor (Company a b) where
  fmap f (Something b) = Something b
  fmap f (DeepBlue a c) = DeepBlue a (f c)

It gets compiled without any complains.

Then I played a bit around(I know it does not work), because of beginner curiosity:

data Company a b c =
    DeepBlue a c
  | Something b

instance Functor (Company a b) where
  fmap f (Something b) = Something (f b)
  fmap f (DeepBlue a c) = DeepBlue a (f c)

Then the compiler complains:

D:\haskell\chapter16\src\ChapterExercises.hs:18:26: error:
    * Couldn't match type `b1' with `b'
      `b1' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a1 b1.
                  (a1 -> b1) -> Company a b a1 -> Company a b b1
        at D:\haskell\chapter16\src\ChapterExercises.hs:18:3
      `b' is a rigid type variable bound by
        the instance declaration
        at D:\haskell\chapter16\src\ChapterExercises.hs:17:10
      Expected type: Company a b b1
        Actual type: Company a b1 b1
    * In the expression: Something (f b)
      In an equation for `fmap': fmap f (Something b) = Something (f b)
      In the instance declaration for `Functor (Company a b)'
    * Relevant bindings include
        b :: b
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:21)
        f :: a1 -> b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:8)
        fmap :: (a1 -> b1) -> Company a b a1 -> Company a b b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:3)

D:\haskell\chapter16\src\ChapterExercises.hs:18:39: error:
    * Couldn't match expected type `a1' with actual type `b'
      `b' is a rigid type variable bound by
        the instance declaration
        at D:\haskell\chapter16\src\ChapterExercises.hs:17:10
      `a1' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a1 b1.
                  (a1 -> b1) -> Company a b a1 -> Company a b b1
        at D:\haskell\chapter16\src\ChapterExercises.hs:18:3
    * In the first argument of `f', namely `b'
      In the first argument of `Something', namely `(f b)'
      In the expression: Something (f b)
    * Relevant bindings include
        b :: b
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:21)
        f :: a1 -> b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:8)
        fmap :: (a1 -> b1) -> Company a b a1 -> Company a b b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:3)
Failed, modules loaded: none.

What does the compiler try say?

Body:
Your definition of fmap has type

fmap :: Company a b c -> (c -> d) -> Company a b d

so the function takes a value of type c. In

fmap f (Something b) = Something (f b)

you are attempting to apply a function c -> d to a value of type b which causes the error. The actual type variables in the message have different names: a1 is  c and b1 is d


来源: stackexchange

问:
Error when connecting to SQLite using SqlConnection, why?
I'm trying to connect to a local database (a ".db" file in my computer) but I get an error when I try to open the connection.

I'm using Sharp Develop (I can't use the connection wizard of Visual Studio to get the con. String).

```<code>    String connectionString = @"Data Source=C:\Users\Adl\Documents\BBDD_Test.db";
    var c = new SqlConnection(connectionString);
    c.Open();
</code>```

The error :

System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

What's happening ?

答:
You are using SqlConnection for SQLite database file(.db).

You will have to download an ADO.NET provider for SQLite or just add System.Data.SQLite.dll to your solution. Now you use certain classes of SQLite viz. SQLiteConnection, SQLiteCommand and SQLiteDataAdapter.

```<code>String connectionString = @"Data Source=D:\Users\wkhan2\Downloads\chinook\chinook.db";

        System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection(connectionString);
        System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand("select * from table");
        cmd.Connection = conn;

        conn.Open();
        cmd.ExecuteScalar();
        System.Data.SQLite.SQLiteDataAdapter da = new System.Data.SQLite.SQLiteDataAdapter(cmd);
        System.Data.DataSet ds = new System.Data.DataSet();

        da.Fill(ds);
</code>```

The rest is similar to ado.net i.e for binding DataSet.

Well I did not use SharpDevelop rather used visual studio, hope it works

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to connect to a local database (a ".db" file in my computer) but I get an error when I try to open the connection.

I'm using Sharp Develop (I can't use the connection wizard of Visual Studio to get the con. String).

    String connectionString = @"Data Source=C:\Users\Adl\Documents\BBDD_Test.db";
    var c = new SqlConnection(connectionString);
    c.Open();

The error :

System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

What's happening ?

Body:
You are using SqlConnection for SQLite database file(.db).

You will have to download an ADO.NET provider for SQLite or just add System.Data.SQLite.dll to your solution. Now you use certain classes of SQLite viz. SQLiteConnection, SQLiteCommand and SQLiteDataAdapter.

String connectionString = @"Data Source=D:\Users\wkhan2\Downloads\chinook\chinook.db";

        System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection(connectionString);
        System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand("select * from table");
        cmd.Connection = conn;

        conn.Open();
        cmd.ExecuteScalar();
        System.Data.SQLite.SQLiteDataAdapter da = new System.Data.SQLite.SQLiteDataAdapter(cmd);
        System.Data.DataSet ds = new System.Data.DataSet();

        da.Fill(ds);

The rest is similar to ado.net i.e for binding DataSet.

Well I did not use SharpDevelop rather used visual studio, hope it works


问:
date_select in rails
i have an issue,
when i post the date in date_select it post the today's date, although i select the future date but it keeps giving me the current date.

<%= form.date_select :starts_at %>

does anyone help me out...
thanks in advance.

答:
Check your model.

Are some attributes attr_accessible while this isn't? Is it attr_protected?

ContentLicense: CC BY-SA 2.5

Title: date_select in rails


问:
tempdb.sys.columns where object_id = object_id('tempdb..#TempTable') getting error in Azure database
I am getting error while using below statement.

```<code>Select name as ColumnName From
tempdb.sys.columns
where object_id = object_id('tempdb..#TempTable').
</code>```

while using tempdb.sys.columns ,I am getting error if removed database name(sys.columns) it is  not showing any error in Azure SQL Database.Is there any solution to fetch tempdb.sys.columns in Azure SQL Database?

答:
I have used below statement and got result.

```<code>SELECT name FROM sys.dm_exec_describe_first_result_set
('select * FROM #TempTable',NULL,0);
</code>```

Please check this link

Body:
I am getting error while using below statement.

Select name as ColumnName From
tempdb.sys.columns
where object_id = object_id('tempdb..#TempTable').

while using tempdb.sys.columns ,I am getting error if removed database name(sys.columns) it is  not showing any error in Azure SQL Database.Is there any solution to fetch tempdb.sys.columns in Azure SQL Database?

Body:
I have used below statement and got result.

SELECT name FROM sys.dm_exec_describe_first_result_set
('select * FROM #TempTable',NULL,0);

Please check this link


问:
pandas fillna datetime column with timezone now
I have a pandas datetime column with None values which I would like to fill with datetime.now() in a specific timezone.

This is my MWE dataframe:

```<code>df = pd.DataFrame([
    {'end': "2017-07-01 12:00:00"},
    {'end': "2017-07-02 18:13:00"},
    {'end': None},
    {'end': "2017-07-04 10:45:00"}
])
</code>```

If I fill with fillna:

```<code>pd.to_datetime(df['end']).fillna(datetime.now())
</code>```

The result is a series with expected dtype: datetime64[ns]. But when I specify the timezone, for example:

```<code>pd.to_datetime(df['end']).fillna(
    datetime.now(pytz.timezone('US/Pacific')))
</code>```

This returns a series with dtype: object

答:
It seems you need convert date to to_datetime in fillna:

```<code>df['end'] = pd.to_datetime(df['end'])
df['end'] = df['end'].fillna(pd.to_datetime(pd.datetime.now(pytz.timezone('US/Pacific'))))
print (df)
                                end
0               2017-07-01 12:00:00
1               2017-07-02 18:13:00
2  2017-07-04 03:35:08.499418-07:00
3               2017-07-04 10:45:00

print (df['end'].apply(type))
0    <class 'pandas._libs.tslib.Timestamp'>
1    <class 'pandas._libs.tslib.Timestamp'>
2    <class 'pandas._libs.tslib.Timestamp'>
3    <class 'pandas._libs.tslib.Timestamp'>
Name: end, dtype: object
</code>```

But still dtype is not datetime64:

```<code>print (df['end'].dtype)
object
</code>```

I think solution is pass paramter utc to to_datetime:

utc : boolean, default None

Return UTC DatetimeIndex if True (converting any tz-aware datetime.datetime objects as well).

```<code>df['end'] = df['end'].fillna(pd.datetime.now(pytz.timezone('US/Pacific')))
df['end'] = pd.to_datetime(df['end'], utc=True)

#print (df)

print (df['end'].apply(type))
0    <class 'pandas._libs.tslib.Timestamp'>
1    <class 'pandas._libs.tslib.Timestamp'>
2    <class 'pandas._libs.tslib.Timestamp'>
3    <class 'pandas._libs.tslib.Timestamp'>
Name: end, dtype: object

print (df['end'].dtypes)
datetime64[ns]
</code>```

And final solution from comment of OP:

```<code>df['end'] = pd.to_datetime(df['end']).dt.tz_localize('US/Pacific')
df['end'] = df['end'].fillna(pd.datetime.now(pytz.timezone('US/Pacific')))

print (df.end.dtype)
datetime64[ns, US/Pacific]
</code>```

Body:
I have a pandas datetime column with None values which I would like to fill with datetime.now() in a specific timezone.

This is my MWE dataframe:

df = pd.DataFrame([
    {'end': "2017-07-01 12:00:00"},
    {'end': "2017-07-02 18:13:00"},
    {'end': None},
    {'end': "2017-07-04 10:45:00"}
])

If I fill with fillna:

pd.to_datetime(df['end']).fillna(datetime.now())

The result is a series with expected dtype: datetime64[ns]. But when I specify the timezone, for example:

pd.to_datetime(df['end']).fillna(
    datetime.now(pytz.timezone('US/Pacific')))

This returns a series with dtype: object

Body:
It seems you need convert date to to_datetime in fillna:

df['end'] = pd.to_datetime(df['end'])
df['end'] = df['end'].fillna(pd.to_datetime(pd.datetime.now(pytz.timezone('US/Pacific'))))
print (df)
                                end
0               2017-07-01 12:00:00
1               2017-07-02 18:13:00
2  2017-07-04 03:35:08.499418-07:00
3               2017-07-04 10:45:00

print (df['end'].apply(type))
0    <class 'pandas._libs.tslib.Timestamp'>
1    <class 'pandas._libs.tslib.Timestamp'>
2    <class 'pandas._libs.tslib.Timestamp'>
3    <class 'pandas._libs.tslib.Timestamp'>
Name: end, dtype: object

But still dtype is not datetime64:

print (df['end'].dtype)
object

I think solution is pass paramter utc to to_datetime:

utc : boolean, default None

Return UTC DatetimeIndex if True (converting any tz-aware datetime.datetime objects as well).

df['end'] = df['end'].fillna(pd.datetime.now(pytz.timezone('US/Pacific')))
df['end'] = pd.to_datetime(df['end'], utc=True)

#print (df)

print (df['end'].apply(type))
0    <class 'pandas._libs.tslib.Timestamp'>
1    <class 'pandas._libs.tslib.Timestamp'>
2    <class 'pandas._libs.tslib.Timestamp'>
3    <class 'pandas._libs.tslib.Timestamp'>
Name: end, dtype: object

print (df['end'].dtypes)
datetime64[ns]

And final solution from comment of OP:

df['end'] = pd.to_datetime(df['end']).dt.tz_localize('US/Pacific')
df['end'] = df['end'].fillna(pd.datetime.now(pytz.timezone('US/Pacific')))

print (df.end.dtype)
datetime64[ns, US/Pacific]


问:
How to import a pure Groovy Script to a Spock Test without Classes
I have the following Groovy Script:

TheScript.groovy

```<code>package groovy

def sayHi = "hi"
</code>```

And the test spec for it. Note: This is just a theory not a serious approach by me. Just want to show you what I tried to achieve.

TheScriptSpec

```<code>import spock.lang.Specification
import spock.lang.Unroll
import groovy.TheScript // what to do instead?

class TheScriptTest extends Specification {
    def "Test One"() {
        expect:
        sayHi() == "hi" // sayHi() does not exist - how to call the field?
    }
}
</code>```

The error thrown tell me surely that there is nothing defined for TheScriptTest.sayHi() - and that's just fine. I understand that error

答:
You need to create script sayHi.groovy

```<code>package groovy

//
def call() {
 return "hi"
}
</code>```

In Groovy we can add a method named call to the script and then invoke the method without using the name call. We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: ()

```<code>import spock.lang.Specification
import spock.lang.Unroll
import groovy.TheScript

class TheScriptTest extends Specification {
    def "Test One"() {
        expect:
        sayHi() == "hi"
    }
}
</code>```

Body:
I have the following Groovy Script:

TheScript.groovy

package groovy

def sayHi = "hi"

And the test spec for it. Note: This is just a theory not a serious approach by me. Just want to show you what I tried to achieve.

TheScriptSpec

import spock.lang.Specification
import spock.lang.Unroll
import groovy.TheScript // what to do instead?

class TheScriptTest extends Specification {
    def "Test One"() {
        expect:
        sayHi() == "hi" // sayHi() does not exist - how to call the field?
    }
}

The error thrown tell me surely that there is nothing defined for TheScriptTest.sayHi() - and that's just fine. I understand that error

Body:
You need to create script sayHi.groovy

package groovy

//
def call() {
 return "hi"
}

In Groovy we can add a method named call to the script and then invoke the method without using the name call. We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: ()

import spock.lang.Specification
import spock.lang.Unroll
import groovy.TheScript

class TheScriptTest extends Specification {
    def "Test One"() {
        expect:
        sayHi() == "hi"
    }
}


问:
Find all combinations matching certain criteria in an array in Ruby
I have the following array:

```<code>a = ["melon | apple", "kiwi | melon", "apple | orange", "pineapple | kiwi"]
</code>```

I want all strings of yielded by connecting the latter part (after "|") of a string element and the former part (before "|") of the following string element. a.combination_with_criteria(3).to_a should output:

```<code>["kiwi | melon", "melon | apple", "apple | orange"]
["pineapple | kiwi", "kiwi | melon", "melon | apple"]
</code>```

a.combination(3).to_a gives all possible combinations but in random order.

Maybe it's better to work with hashes for this purpose.

答:
This seems to work:</p>

```<code>def find_chains(input)
  # Split input into usable value pairs.
  pairs = input.map { |s| s.split(" | ") }

  pairs.permutation(3).select do |ar|
    ar[0][1] == ar[1][0] && ar[1][1] == ar[2][0]
  end
end

input = ["melon | apple", "kiwi | melon", "apple | orange", "pineapple | kiwi"]

find_chains(input).each do |match|
  puts "match: " + match.map { |ar| ar.join(" | ")}.join(", ")
end

# Output:
#
# match: kiwi | melon, melon | apple, apple | orange
# match: pineapple | kiwi, kiwi | melon, melon | apple
</code>```

Body:
I have the following array:

a = ["melon | apple", "kiwi | melon", "apple | orange", "pineapple | kiwi"]

I want all strings of yielded by connecting the latter part (after "|") of a string element and the former part (before "|") of the following string element. a.combination_with_criteria(3).to_a should output:

["kiwi | melon", "melon | apple", "apple | orange"]
["pineapple | kiwi", "kiwi | melon", "melon | apple"]

a.combination(3).to_a gives all possible combinations but in random order.

Maybe it's better to work with hashes for this purpose.

Body:
This seems to work:

def find_chains(input)
  # Split input into usable value pairs.
  pairs = input.map { |s| s.split(" | ") }

  pairs.permutation(3).select do |ar|
    ar[0][1] == ar[1][0] && ar[1][1] == ar[2][0]
  end
end

input = ["melon | apple", "kiwi | melon", "apple | orange", "pineapple | kiwi"]

find_chains(input).each do |match|
  puts "match: " + match.map { |ar| ar.join(" | ")}.join(", ")
end

# Output:
#
# match: kiwi | melon, melon | apple, apple | orange
# match: pineapple | kiwi, kiwi | melon, melon | apple


问:
I want to move 100 out of 1Million files of a particular extension to a target folder in linux
I have a folder(/DIR/SRC) containing 1 Million files with different types of extensions.
I would like to pick a particular extension files from the SRC folder, may be 1000 at a time and move to a target folder which is at /DIR/TGT.
The file name has the format 1234_XXXX-XXXX_TIMESTAMP.ext</p>

答:
Try this one:

```<code>mv `ls -1 *.your_ext|tail -n 100` /TARGETDIR
</code>```

I didn't test it, but in this way it should work.

If you want the latest 100 or alphabetically the first 100 (or, or, or,...) you can change the ls-command.

Body:
Try this one:

mv `ls -1 *.your_ext|tail -n 100` /TARGETDIR

I didn't test it, but in this way it should work.

If you want the latest 100 or alphabetically the first 100 (or, or, or,...) you can change the ls-command.


问:
Call and receive output from Python script in Java?
What's the easiest way to execute a Python script from Java, and receive the output of that script? I've looked for different libraries like Jepp or Jython, but most appear out of date. Another problem with the libraries is that I need to be able to easily include a library with the source code (though I don't need to source for the library itself) if I use a library.

Because of this, would the easiest/most effective way be to simply do something like call the script with runtime.exec, and then somehow capture printed output? Or, even though it would be very painful for me, I could also just have the Python script output to a temporary text file, then read the file in Java.

Note: the actual communication between Java and Python is not a requirement of the problem I am trying to solve. This is, however, the only way I can think of to easily perform what needs to be done.

答:
Jep is anther option. It embeds CPython in Java through JNI.

```<code>import jep.Jep;
//...
    try(Jep jep = new Jep(false)) {
        jep.eval("s = 'hello world'");
        jep.eval("print(s)");
        jep.eval("a = 1 + 2");
        Long a = (Long) jep.getValue("a");
    }
</code>```

Body:
Jep is anther option. It embeds CPython in Java through JNI.

import jep.Jep;
//...
    try(Jep jep = new Jep(false)) {
        jep.eval("s = 'hello world'");
        jep.eval("print(s)");
        jep.eval("a = 1 + 2");
        Long a = (Long) jep.getValue("a");
    }


问:
how to chose the positions text and buttons in Android studio?
In the preview I made my app to look like this.

Picture from the preview:

unfortunately when I launch the app its look like this

picture from the test

And this my page code

```<code><android.support.constraint.ConstraintLayout
    android:layout_width="315dp"
    android:layout_height="66dp"
    tools:layout_editor_absoluteX="48dp"
    tools:layout_editor_absoluteY="287dp">

</android.support.constraint.ConstraintLayout>

<android.support.constraint.ConstraintLayout
    android:layout_width="212dp"
    android:layout_height="36dp"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="232dp">

</android.support.constraint.ConstraintLayout>

<android.support.constraint.ConstraintLayout
    android:layout_width="271dp"
    android:layout_height="66dp"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="153dp">

</android.support.constraint.ConstraintLayout>

<android.support.constraint.ConstraintLayout
    android:layout_width="218dp"
    android:layout_height="51dp"
    tools:layout_editor_absoluteX="2dp"
    tools:layout_editor_absoluteY="4dp">

</android.support.constraint.ConstraintLayout>

<android.support.constraint.ConstraintLayout
    android:layout_width="271dp"
    android:layout_height="66dp"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="77dp">

</android.support.constraint.ConstraintLayout>

<TextView
    android:id="@+id/textView8"
    android:layout_width="218dp"
    android:layout_height="51dp"
    android:text="Se connecter"
    android:textSize="30sp"
    android:textStyle="bold"
    tools:layout_editor_absoluteX="2dp"
    tools:layout_editor_absoluteY="4dp" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="270dp"
    android:layout_height="67dp"
    android:ems="10"
    android:hint="Numero de telephone"
    android:inputType="phone"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="77dp" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="274dp"
    android:layout_height="66dp"
    android:ems="10"
    android:hint="Mot de pass"
    android:inputType="textPassword"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="153dp" />

<CheckBox
    android:id="@+id/checkBox6"
    android:layout_width="214dp"
    android:layout_height="36dp"
    android:text="rester connecte"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="232dp" />

<Button
    android:id="@+id/button3"
    android:layout_width="313dp"
    android:layout_height="64dp"
    android:text="Se connecter"
    tools:layout_editor_absoluteX="48dp"
    tools:layout_editor_absoluteY="287dp" />
</code>```

答:
When you use ConstraintLayout you have to add constraints between elements. When you simply drag and drop them using the layout editor it only creates the keys "tools:layout_editor_absoluteX" and "tools:layout_editor_absoluteY" which are only used within android studio so it knows how to show them in the layout editor.

You can follow this link, to understand how to use ConstraintLayout
https://developer.android.com/training/constraint-layout/index.html

Body:
In the preview I made my app to look like this.

Picture from the preview:

unfortunately when I launch the app its look like this

picture from the test

And this my page code

<android.support.constraint.ConstraintLayout
    android:layout_width="315dp"
    android:layout_height="66dp"
    tools:layout_editor_absoluteX="48dp"
    tools:layout_editor_absoluteY="287dp">

</android.support.constraint.ConstraintLayout>

<android.support.constraint.ConstraintLayout
    android:layout_width="212dp"
    android:layout_height="36dp"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="232dp">

</android.support.constraint.ConstraintLayout>

<android.support.constraint.ConstraintLayout
    android:layout_width="271dp"
    android:layout_height="66dp"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="153dp">

</android.support.constraint.ConstraintLayout>

<android.support.constraint.ConstraintLayout
    android:layout_width="218dp"
    android:layout_height="51dp"
    tools:layout_editor_absoluteX="2dp"
    tools:layout_editor_absoluteY="4dp">

</android.support.constraint.ConstraintLayout>

<android.support.constraint.ConstraintLayout
    android:layout_width="271dp"
    android:layout_height="66dp"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="77dp">

</android.support.constraint.ConstraintLayout>

<TextView
    android:id="@+id/textView8"
    android:layout_width="218dp"
    android:layout_height="51dp"
    android:text="Se connecter"
    android:textSize="30sp"
    android:textStyle="bold"
    tools:layout_editor_absoluteX="2dp"
    tools:layout_editor_absoluteY="4dp" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="270dp"
    android:layout_height="67dp"
    android:ems="10"
    android:hint="Numero de telephone"
    android:inputType="phone"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="77dp" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="274dp"
    android:layout_height="66dp"
    android:ems="10"
    android:hint="Mot de pass"
    android:inputType="textPassword"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="153dp" />

<CheckBox
    android:id="@+id/checkBox6"
    android:layout_width="214dp"
    android:layout_height="36dp"
    android:text="rester connecte"
    tools:layout_editor_absoluteX="70dp"
    tools:layout_editor_absoluteY="232dp" />

<Button
    android:id="@+id/button3"
    android:layout_width="313dp"
    android:layout_height="64dp"
    android:text="Se connecter"
    tools:layout_editor_absoluteX="48dp"
    tools:layout_editor_absoluteY="287dp" />


问:
Why do java programs start with a class definition?
It is said that a java program itself is a class, but I just don't get the logic behind this.

The java program itself starts of by the definition of a class (after importing the packages...etc) and the main method itself is defined inside a class.

Why is it this way?

Why does a main method have to be included within a class rather than outside as a separate method/function like in the languages such as c, c++...etc.

For example a simple hello world program in java:-

```<code>public class HelloWorld
{
    public static void main(String[] args)
    {
        System.out.println("Hello world!"+"Hello again");
    }
}
</code>```

Why is it necessary that a program should start with a class and the main method included within it?

答: The Java Virtual Machine (JVM) has to start the application somewhere. As Java does not have a concept of “things outside of a class” the method that is called by the JVM has to be in a class. And because it is static, no instance of that class is created yet.</p>

Body:
It is said that a java program itself is a class, but I just don't get the logic behind this.

The java program itself starts of by the definition of a class (after importing the packages...etc) and the main method itself is defined inside a class.

Why is it this way?

Why does a main method have to be included within a class rather than outside as a separate method/function like in the languages such as c, c++...etc.

For example a simple hello world program in java:-

public class HelloWorld
{
    public static void main(String[] args)
    {
        System.out.println("Hello world!"+"Hello again");
    }
}

Why is it necessary that a program should start with a class and the main method included within it?


问:
Retrieve the current view name in ASP.NET MVC?
I have a partial view (control) that's used across several view pages, and I need to pass the name of the current view back to the controller - so if there's e.g. validation errors, I can re-draw the original view.

A workaround way to do it would be (in the controller methods)

```<code>var viewName = "Details"; // or whatever
ViewData["viewName"] = viewName;
return(View(viewName, customer));
</code>```

and then in the partial itself, render it as

```<code><input type="hidden" name="viewName"
    value="<%=Html.Encode(ViewData["viewName"])%>" />
</code>```

Question is - is there some property or syntax I can use to retrieve this directly instead of setting it from the controller? I've tried the obvious:

```<code><input type="hidden" name="viewName"
    value="<%=Html.Encode(this.Name)%>" />
</code>```

but this doesn't work. What am I missing here?

Thanks.

答:
Easiest solution is using ViewBag.

```<code>public ActionResult Index()
    {
        ViewBag.CurrentView = "Index";
        return View();
    }
</code>```

On the cshtml page

```<code>@{
var viewName = ViewBag.CurrentView;
}
</code>```

Or,

```<code>((RazorView)ViewContext.View).ViewPath
</code>```

Body:
I have a partial view (control) that's used across several view pages, and I need to pass the name of the current view back to the controller - so if there's e.g. validation errors, I can re-draw the original view.

A workaround way to do it would be (in the controller methods)

var viewName = "Details"; // or whatever
ViewData["viewName"] = viewName;
return(View(viewName, customer));

and then in the partial itself, render it as

<input type="hidden" name="viewName"
    value="<%=Html.Encode(ViewData["viewName"])%>" />

Question is - is there some property or syntax I can use to retrieve this directly instead of setting it from the controller? I've tried the obvious:

<input type="hidden" name="viewName"
    value="<%=Html.Encode(this.Name)%>" />

but this doesn't work. What am I missing here?

Thanks.

Body:
Easiest solution is using ViewBag.

public ActionResult Index()
    {
        ViewBag.CurrentView = "Index";
        return View();
    }

On the cshtml page

@{
var viewName = ViewBag.CurrentView;
}

Or,

((RazorView)ViewContext.View).ViewPath


问:
Paypal webhooks events are not triggered in sandbox
Hello I am using the following setup

Created paypal merchant and customer sandbox accounts

Configured paypal REST API app

Added a webhook url to my server and have validated that it works using the webhook simulator

Used the Express Checkout javascript implementation found here

I am able to make successful payments when viewing the notifications in sandbox but no webhook is ever triggered???

Below is a sample of my javascript implementation that I have used, please not that it's embedded in a coldfusion script file hence the use hashtags.

`

```<code>var items = #paypalItems#;

// Render the PayPal button
paypal.Button.render({

    env: '#application.config.paypal.bSandbox ? "sandbox" : "production"#', // sandbox | production
    commit: true,

    //style the button
    style: {
        label: 'pay'
    },

    // PayPal Client IDs - replace with your own
    client: {
        sandbox:    '#application.config.paypal.sandbox_key#',
        production: '#application.config.paypal.live_key#'
    },

    // Wait for the PayPal button to be clicked
    payment: function(data, actions) {

        // Make a client-side call to the REST api to create the payment
        return actions.payment.create({
            payment: {
                transactions: [{
                    amount: {
                        total: #trim(numberFormat( application.oCart.getTotal(bDiscount=1,bShipping=1) , "99999999.99" ))#,
                        currency: "AUD",
                        details: {
                        subtotal: #trim(numberFormat( application.oCart.getTotal() - application.oCart.getAmountGST( amount=application.oCart.getTotal(bDiscount=1), addGST=false ), "99999999.99" ))#,
                        tax: #trim(numberFormat(application.oCart.getAmountGST( amount=application.oCart.getTotal(bDiscount=1), addGST=false ), "99999999.99" ))#,
                        shipping: #trim(numberFormat( application.oCart.oShipping.getCartShippingAmount(country=session.fcbshoppingCart.order.shippingCountry), "99999999.99" ))#
                        }
                    },
                    invoice_number: "#orderNumber#",
                    item_list: {
                        items:  items,
                        shipping_address: {
                        recipient_name: "#session.fcbshoppingCart.customer.firstName# #session.fcbshoppingCart.customer.lastName#",
                        line1: "#session.fcbshoppingCart.order.shippingAddress1#",
                        line2: "#session.fcbshoppingCart.order.shippingAddress2#",
                        city: "#session.fcbshoppingCart.order.shippingSuburb#",
                        country_code: "#paypalCountryCode#",
                        postal_code: "#session.fcbshoppingCart.order.shippingPostCode#",
                        state: "#session.fcbshoppingCart.order.shippingState#"
                        }
                    }
                }]
            }
        });
    },

    // Wait for the payment to be authorized by the customer
    onAuthorize: function(data, actions) {

      console.log( "Paypal Authorize:", data );

        // Execute the payment
        return actions.payment.execute().then(function(payment) {

            console.log( "Paypal Response:", payment );

            //payment has been accepted so we can now generate an order
            $.ajax({
                type: "get",
                url: "/apps/paypal/createOrder.cfm",
                data: {
                    transactionNumber: "#orderNumber#",
                    payPalPaymentId: data.paymentID
                },
                dataType: "json",
                success: function( res ) {
                    console.log('edharry create order data', res);

                    if( res.BPAYMENTPROCEED ) {
                        $('##paypal-message').addClass("show success").text('Payment Successfully Complete!');
                        //lets redirect to the checkout success page.
                        window.location.href = window.location.origin + '/shop/checkout/confirmation?productOrder=' + res.PRODUCTORDER.OBJECTID;
                    } else {
                        //need to handle a failed transaction
                        $('##paypal-message').addClass("show failure").text('Payment did not complete on server!');
                    }
                },
                error: function() {
                    //lets show an error
                    $('##paypal-message').addClass("show failure").text('Payment did not complete on server!');
                }
            })

            $('##paypal-message').addClass("show success").text('Payment Successfully Complete!');
        });
    },

    onCancel: function(data) {
        console.log('The payment was cancelled!');
    }

}, '##paypal-button-container');`
</code>```

答: This is an ongoing issue with Paypal. They are aware of this issue and are currently working to resolve this. </p>

Body:
Hello I am using the following setup

Created paypal merchant and customer sandbox accounts

Configured paypal REST API app

Added a webhook url to my server and have validated that it works using the webhook simulator

Used the Express Checkout javascript implementation found here

I am able to make successful payments when viewing the notifications in sandbox but no webhook is ever triggered???

Below is a sample of my javascript implementation that I have used, please not that it's embedded in a coldfusion script file hence the use hashtags.

`

var items = #paypalItems#;

// Render the PayPal button
paypal.Button.render({

    env: '#application.config.paypal.bSandbox ? "sandbox" : "production"#', // sandbox | production
    commit: true,

    //style the button
    style: {
        label: 'pay'
    },

    // PayPal Client IDs - replace with your own
    client: {
        sandbox:    '#application.config.paypal.sandbox_key#',
        production: '#application.config.paypal.live_key#'
    },

    // Wait for the PayPal button to be clicked
    payment: function(data, actions) {

        // Make a client-side call to the REST api to create the payment
        return actions.payment.create({
            payment: {
                transactions: [{
                    amount: {
                        total: #trim(numberFormat( application.oCart.getTotal(bDiscount=1,bShipping=1) , "99999999.99" ))#,
                        currency: "AUD",
                        details: {
                        subtotal: #trim(numberFormat( application.oCart.getTotal() - application.oCart.getAmountGST( amount=application.oCart.getTotal(bDiscount=1), addGST=false ), "99999999.99" ))#,
                        tax: #trim(numberFormat(application.oCart.getAmountGST( amount=application.oCart.getTotal(bDiscount=1), addGST=false ), "99999999.99" ))#,
                        shipping: #trim(numberFormat( application.oCart.oShipping.getCartShippingAmount(country=session.fcbshoppingCart.order.shippingCountry), "99999999.99" ))#
                        }
                    },
                    invoice_number: "#orderNumber#",
                    item_list: {
                        items:  items,
                        shipping_address: {
                        recipient_name: "#session.fcbshoppingCart.customer.firstName# #session.fcbshoppingCart.customer.lastName#",
                        line1: "#session.fcbshoppingCart.order.shippingAddress1#",
                        line2: "#session.fcbshoppingCart.order.shippingAddress2#",
                        city: "#session.fcbshoppingCart.order.shippingSuburb#",
                        country_code: "#paypalCountryCode#",
                        postal_code: "#session.fcbshoppingCart.order.shippingPostCode#",
                        state: "#session.fcbshoppingCart.order.shippingState#"
                        }
                    }
                }]
            }
        });
    },

    // Wait for the payment to be authorized by the customer
    onAuthorize: function(data, actions) {

      console.log( "Paypal Authorize:", data );

        // Execute the payment
        return actions.payment.execute().then(function(payment) {

            console.log( "Paypal Response:", payment );

            //payment has been accepted so we can now generate an order
            $.ajax({
                type: "get",
                url: "/apps/paypal/createOrder.cfm",
                data: {
                    transactionNumber: "#orderNumber#",
                    payPalPaymentId: data.paymentID
                },
                dataType: "json",
                success: function( res ) {
                    console.log('edharry create order data', res);

                    if( res.BPAYMENTPROCEED ) {
                        $('##paypal-message').addClass("show success").text('Payment Successfully Complete!');
                        //lets redirect to the checkout success page.
                        window.location.href = window.location.origin + '/shop/checkout/confirmation?productOrder=' + res.PRODUCTORDER.OBJECTID;
                    } else {
                        //need to handle a failed transaction
                        $('##paypal-message').addClass("show failure").text('Payment did not complete on server!');
                    }
                },
                error: function() {
                    //lets show an error
                    $('##paypal-message').addClass("show failure").text('Payment did not complete on server!');
                }
            })

            $('##paypal-message').addClass("show success").text('Payment Successfully Complete!');
        });
    },

    onCancel: function(data) {
        console.log('The payment was cancelled!');
    }

}, '##paypal-button-container');`


问:
Create new list from list created from api response
I have some api request, I get response and parse some data in new list. List which I print is:

```<code>[u'2.40', u'2.35', u'2.67']
</code>```

I need clear list as value:

```<code>[2.40, 2.35, 2.67]
</code>```

How to do that ?

答:
I found resolution for this. If someone need:   </p>

```<code>lista_a = {u'total': 33455710208, u'free': 2834251776, u'used': 30621458432}

list = [list_a[key] for key in list_a]
</code>```

Body:
I have some api request, I get response and parse some data in new list. List which I print is:

[u'2.40', u'2.35', u'2.67']

I need clear list as value:

[2.40, 2.35, 2.67]

How to do that ?

Body:
I found resolution for this. If someone need:

lista_a = {u'total': 33455710208, u'free': 2834251776, u'used': 30621458432}

list = [list_a[key] for key in list_a]


问:
Why does: string st = "" + 12; work in c# without conversion?
This is super dumb, but I've googled and checked references and I just cannot find an answer... Why can an int or float etc be added as part of a string without converstion but not on it's own? that is:

while this work fine:

```<code> string st = "" + 12;
</code>```

this doesn't (of course):

```<code> string st = 12;
</code>```

Where is the magic here? I know it works I just want to know WHY it works and how I control HOW the conversion is done?

答: Because the compiler will call .ToString() on all objects if one of the parameters is a string.

Body:
This is super dumb, but I've googled and checked references and I just cannot find an answer... Why can an int or float etc be added as part of a string without converstion but not on it's own? that is:

while this work fine:

 string st = "" + 12;

this doesn't (of course):

 string st = 12;

Where is the magic here? I know it works I just want to know WHY it works and how I control HOW the conversion is done?


问:
Android AsyncTask Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
i have some problem when i parse the JSON in asyncTask Android Studio
its showed: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

this my code:

```<code>@Override
protected Response doInBackground(String... objects) {
    try {
        String stringResponse = loadJSON(objects[0]);
        Gson gson = new Gson();
        return gson.fromJson(stringResponse, Response.class);

    }catch (IOException e) {
        e.printStackTrace();
        return null;
        } catch (JsonSyntaxException e) {
        e.printStackTrace();
        return null;
    }

}
</code>```

and this is my JSON

```<code>   [{"Code":"ascascasd",
    "SKU":"asd",
    "Name":"asd",
    "Description":"d",
    ...
    ...
   }]
</code>```

答:
stringResponse should contain

```<code>{"Code":"ascascasd",
    "SKU":"asd",
    "Name":"asd",
    "Description":"d",
    ...
    ...
   }
</code>```

and not

```<code>[{"Code":"ascascasd",
    "SKU":"asd",
    "Name":"asd",
    "Description":"d",
    ...
    ...
   }]
</code>```

Or add another class that contains list of "Response" objects and pass the new class to gson.fromJson()

Body:
i have some problem when i parse the JSON in asyncTask Android Studio
its showed: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

this my code:

@Override
protected Response doInBackground(String... objects) {
    try {
        String stringResponse = loadJSON(objects[0]);
        Gson gson = new Gson();
        return gson.fromJson(stringResponse, Response.class);

    }catch (IOException e) {
        e.printStackTrace();
        return null;
        } catch (JsonSyntaxException e) {
        e.printStackTrace();
        return null;
    }

}

and this is my JSON

   [{"Code":"ascascasd",
    "SKU":"asd",
    "Name":"asd",
    "Description":"d",
    ...
    ...
   }]

Body:
stringResponse should contain

{"Code":"ascascasd",
    "SKU":"asd",
    "Name":"asd",
    "Description":"d",
    ...
    ...
   }

and not

[{"Code":"ascascasd",
    "SKU":"asd",
    "Name":"asd",
    "Description":"d",
    ...
    ...
   }]

Or add another class that contains list of "Response" objects and pass the new class to gson.fromJson()


问:
how to install python package on azure hdinsight pyspark3 kernel?
I would like to install python 3.5 packages so they would be available in Jupyter notebook with pyspark3 kernel.

I've tried to run the following script action:

#!/bin/bash
source /usr/bin/anaconda/envs/py35/bin/activate py35
sudo /usr/bin/anaconda/envs/py35/bin/conda install -y keras tensorflow theano gensim

but the packages get installed on python 2.7 and not in 3.5

答:
Have you tried installing using pip?

In some cases where you have both Python 2 and Python 3, you have to run pip3 instead of just pip to invoke pip for Python 3.


问:
Is there a way to back up all files with AccuRev in a directory?
I'm new to AccuRev and not super familiar with it. I'm used to GitHub and a little confused about saving versions with AccuRev and how to use it.

In GitHub, I would work on some files in a directory and then use add * to add all the files to the staging area then do commit -m <message> to move them to the Head. Finally, I would use push to push all my changes and save them to my GitHub repository for others to see and for that version to save so I can go back one day.

I'm a little confused about this process with AccuRev. I have some directories that I have files in that I have modified. I want to save them onto AccuRev and have them backed up as a version.

I thought that I use the keep command to save them to AccuRev, but I can only do this with individual files and not with an entire directory. Or do I use something like accurev keep -c <comment> -m to keep all files in the directory and keep them recursively? Do I need to do anything else to push the changes?

答:
In the GUI, you will click on the "Outgoing" tab, in this view you will see all your modified files, select -> right click -> Keep or Promote (which will first keep).

If you are a CLI user, you can use "keep -m or -n" (see man page), this will keep all modified files in your workspace.  If you want to limit that to a certain directory, you can run a "stat -m" command and generate a list of files in that directory which you can use in the keep command (keep -l list.txt)

Once done, you will promote the changes.


问:
@ExceptionHandler doesn't catch HttpMessageNotReadableException
I have the following exception handler:

```<code>@ControllerAdvice
public class MyExceptionHandler {
  private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {
        logger.warn("HttpMessageNotReadableException occurred.", e);
        throw e;
    }
</code>```

But it doesn't catch HttpMessageNotReadableException?! In my logs I see (it prints spring itself):

```<code>2017-07-04 13:26:38,699 DEBUG org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.getMethodArgumentValues:164 - Failed to resolve argument 0 of type 'com.finvale.model.Client'
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:240)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:225)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:201)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:128)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
</code>```

Is it possible to catch this exception in my ExceptionHandler ?

P.S.

I agree that my code contains mistake. I neeed to specify type in annotation.
I changed it like this:

```<code> @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {
</code>```

but I still see same behaviour.

handle method doesn't invoke

答:
Change @ExceptionHandler to @ExceptionHandler(value = HttpMessageNotReadableException.class)

And instead of re-throwing same exception, its better to return a custom object containing that error message in meaningful way

Body:
I have the following exception handler:

@ControllerAdvice
public class MyExceptionHandler {
  private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {
        logger.warn("HttpMessageNotReadableException occurred.", e);
        throw e;
    }

But it doesn't catch HttpMessageNotReadableException?! In my logs I see (it prints spring itself):

2017-07-04 13:26:38,699 DEBUG org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.getMethodArgumentValues:164 - Failed to resolve argument 0 of type 'com.finvale.model.Client'
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.time.LocalDate from String "Invalid date": Text 'Invalid date' could not be parsed at index 0
 at [Source: java.io.PushbackInputStream@4f30395; line: 1, column: 103] (through reference chain: com.finvale.model.Client["birthDay"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:240)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:225)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:201)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:128)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

Is it possible to catch this exception in my ExceptionHandler ?

P.S.

I agree that my code contains mistake. I neeed to specify type in annotation.
I changed it like this:

 @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void handle(HttpMessageNotReadableException e) {

but I still see same behaviour.

handle method doesn't invoke


问:
What are the best steps to install ZeroMQ in Windows 10 64 bit?
I am trying to install ZeroMQ in my windows.

I have xampp and php version 7.0, so what are the best steps to install this library?

答:
Have you tried official ZeroMQ recipe?

Windows

  Download the latest snapshot from http://snapshot.zero.mq/

  Copy libzmq.dll into your php directory (e.g. C:\wamp\bin\php\php5.3.8)

  Copy the appropriate version of php_zmq.dll to your php extension directory (e.g. C:\wamp\bin\php\php5.3.8\ext)

  Add the following line to your php.ini:

      extension=php_zmq.dll

  Restart your web server to pickup the ini changes

Another way to have ZeroMQ / php up and running w/o installing:

Next, you may opt to use a pre-installed VM-image, with ZeroMQ already setup and RTO.


问:
Combine vectors of list in R
I have a list contains number of vectors with different length as below:

```<code>lst <- list(c(1,2), c(1,2), c(4,5,10,11,12,13), c(7,8,9))
lst

[[1]]
[1] 1 2

[[2]]
[1] 1 2

[[3]]
[1]  4  5 10 11 12 13

[[4]]
[1] 7 8 9

[[5]]
[1] 7 8 9
</code>```

how can I combine and remove repeated vectors to be  similar to the list below:

```<code>[[1]]
[1] 1 2

[[2]]
[1]  4  5 10 11 12 13

[[3]]
[1] 7 8 9
</code>```

for repeated vectors I can use unique function.

答:
I have edited your answer to give a reproducible example. Please let me know if this does not correctly illustrate your problem anymore. If it does, this is trivial:</p>

```<code>unique(lst)
</code>```

Title: Combine vectors of list in R

Body:
I have a list contains number of vectors with different length as below:

lst <- list(c(1,2), c(1,2), c(4,5,10,11,12,13), c(7,8,9))
lst

[[1]]
[1] 1 2

[[2]]
[1] 1 2

[[3]]
[1]  4  5 10 11 12 13

[[4]]
[1] 7 8 9

[[5]]
[1] 7 8 9

how can I combine and remove repeated vectors to be  similar to the list below:

[[1]]
[1] 1 2

[[2]]
[1]  4  5 10 11 12 13

[[3]]
[1] 7 8 9

for repeated vectors I can use unique function.

Body:
I have edited your answer to give a reproducible example. Please let me know if this does not correctly illustrate your problem anymore. If it does, this is trivial:

unique(lst)


问:
Using pyWin32 without installing it
Is it possible to use pyWin32 without installing it?
I would like to include it into python's interpreter folder.
I have managed to use Python interpreter without installing it (simply installing it and copy&pasting installed directory into my product).
I need also the same with pyWin32.

My objective is:
Client receives a folder with a script (batch) which will run python program in a console. The client does not have to install python, pywin32, nothing. What he needs is to copy and paste my product and run the console-based program.

Is it possible?

答:
My objective is: Client receives a folder with a script (batch) which
  will run python program in a console. The client does not have to
  install python, pywin32, nothing. What he needs is to copy and paste
  my product and run the console-based program.

I would suggest something along the lines of using pyinstaller or any other python code to executable converter.

http://www.pyinstaller.org/

PyInstaller is a program that freezes (packages) Python programs into
  stand-alone executables, under Windows, Linux, Mac OS X, FreeBSD,
  Solaris and AIX. Its main advantages over similar tools are that
  PyInstaller works with Python 2.7 and 3.3—3.5, it builds smaller
  executables thanks to transparent compression, it is fully
  multi-platform, and use the OS support to load the dynamic libraries,
  thus ensuring full compatibility.

To me it seems this would suit your/your clients needs quite well. Furthermore pyinstaller is easy to use.

Title: Using pyWin32 without installing it


问:
How to install jenkins offline?
I could successfully install the jenkins online over my laptop. But while trying to install the jenkins offline (on my office workstation which cannot be connected to internet) the hell breaks loose.
After running the jenkins.war over command line although the jenkins was successfully installed yet some of the plugins were missing.I managed to get some help from the post How to install a plugin in Jenkins manually?

But then each of the plugins have to be individually downloaded and then copied over to my offline machine. So I had a trick.
I copied all the folders under .jenkins directory (in my online installation machine) and then copied them to my offline machine. Whoa!
It worked!
But I still get one single error:

```<code>Maven Integration Plugin V2.16 .javadoc 1.0 is missing. To fix, install v1.0 or later
</code>```

So is there a way/website/pdf/repository which is a one stop solution/steps to smoothly install (read has all the required dependencies as a zip) Jenkins in offline mode. (If not, to the creators of Jenkins: Would it be a good idea to have one?)

答:
I'm also searching for an easy way to manage the dependencies between the plugins but as far as I know there is no official tool for that.

Either you have a .zip file with all the plugins which you prepare one time or you fix the errors manually.

For your problem it should be enough to install the following .hpi file: https://updates.jenkins-ci.org/latest/javadoc.hpi (javadoc has no dependencies to other plugins)

Title: How to install jenkins offline?

Body:
I could successfully install the jenkins online over my laptop. But while trying to install the jenkins offline (on my office workstation which cannot be connected to internet) the hell breaks loose.
After running the jenkins.war over command line although the jenkins was successfully installed yet some of the plugins were missing.I managed to get some help from the post How to install a plugin in Jenkins manually?

But then each of the plugins have to be individually downloaded and then copied over to my offline machine. So I had a trick.
I copied all the folders under .jenkins directory (in my online installation machine) and then copied them to my offline machine. Whoa!
It worked!
But I still get one single error:

Maven Integration Plugin V2.16 .javadoc 1.0 is missing. To fix, install v1.0 or later

So is there a way/website/pdf/repository which is a one stop solution/steps to smoothly install (read has all the required dependencies as a zip) Jenkins in offline mode. (If not, to the creators of Jenkins: Would it be a good idea to have one?)


问:
Functor with wrong type argument
I have following datatype and had apply to Functor instance:

```<code>data Company a b c =
    DeepBlue a c
  | Something b

instance Functor (Company a b) where
  fmap f (Something b) = Something b
  fmap f (DeepBlue a c) = DeepBlue a (f c)
</code>```

It gets compiled without any complains.

Then I played a bit around(I know it does not work), because of beginner curiosity:

```<code>data Company a b c =
    DeepBlue a c
  | Something b

instance Functor (Company a b) where
  fmap f (Something b) = Something (f b)
  fmap f (DeepBlue a c) = DeepBlue a (f c)
</code>```

Then the compiler complains:

```<code>D:\haskell\chapter16\src\ChapterExercises.hs:18:26: error:
    * Couldn't match type `b1' with `b'
      `b1' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a1 b1.
                  (a1 -> b1) -> Company a b a1 -> Company a b b1
        at D:\haskell\chapter16\src\ChapterExercises.hs:18:3
      `b' is a rigid type variable bound by
        the instance declaration
        at D:\haskell\chapter16\src\ChapterExercises.hs:17:10
      Expected type: Company a b b1
        Actual type: Company a b1 b1
    * In the expression: Something (f b)
      In an equation for `fmap': fmap f (Something b) = Something (f b)
      In the instance declaration for `Functor (Company a b)'
    * Relevant bindings include
        b :: b
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:21)
        f :: a1 -> b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:8)
        fmap :: (a1 -> b1) -> Company a b a1 -> Company a b b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:3)

D:\haskell\chapter16\src\ChapterExercises.hs:18:39: error:
    * Couldn't match expected type `a1' with actual type `b'
      `b' is a rigid type variable bound by
        the instance declaration
        at D:\haskell\chapter16\src\ChapterExercises.hs:17:10
      `a1' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a1 b1.
                  (a1 -> b1) -> Company a b a1 -> Company a b b1
        at D:\haskell\chapter16\src\ChapterExercises.hs:18:3
    * In the first argument of `f', namely `b'
      In the first argument of `Something', namely `(f b)'
      In the expression: Something (f b)
    * Relevant bindings include
        b :: b
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:21)
        f :: a1 -> b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:8)
        fmap :: (a1 -> b1) -> Company a b a1 -> Company a b b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:3)
Failed, modules loaded: none.
</code>```

What does the compiler try say?

答:
You've declared Company as type with three generic types, a, b, and c. When you create an instance instance Functor (Company a b) you've said that for any a and b, there should exist a function fmap with the type:

```<code>(c -> d) -> Company a b c -> Company a b d
</code>```

The function f has the type c -> d, so you can't use b as input for it, because it doesn't have the correct type.

Title: Functor with wrong type argument

Body:
I have following datatype and had apply to Functor instance:

data Company a b c =
    DeepBlue a c
  | Something b

instance Functor (Company a b) where
  fmap f (Something b) = Something b
  fmap f (DeepBlue a c) = DeepBlue a (f c)

It gets compiled without any complains.

Then I played a bit around(I know it does not work), because of beginner curiosity:

data Company a b c =
    DeepBlue a c
  | Something b

instance Functor (Company a b) where
  fmap f (Something b) = Something (f b)
  fmap f (DeepBlue a c) = DeepBlue a (f c)

Then the compiler complains:

D:\haskell\chapter16\src\ChapterExercises.hs:18:26: error:
    * Couldn't match type `b1' with `b'
      `b1' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a1 b1.
                  (a1 -> b1) -> Company a b a1 -> Company a b b1
        at D:\haskell\chapter16\src\ChapterExercises.hs:18:3
      `b' is a rigid type variable bound by
        the instance declaration
        at D:\haskell\chapter16\src\ChapterExercises.hs:17:10
      Expected type: Company a b b1
        Actual type: Company a b1 b1
    * In the expression: Something (f b)
      In an equation for `fmap': fmap f (Something b) = Something (f b)
      In the instance declaration for `Functor (Company a b)'
    * Relevant bindings include
        b :: b
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:21)
        f :: a1 -> b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:8)
        fmap :: (a1 -> b1) -> Company a b a1 -> Company a b b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:3)

D:\haskell\chapter16\src\ChapterExercises.hs:18:39: error:
    * Couldn't match expected type `a1' with actual type `b'
      `b' is a rigid type variable bound by
        the instance declaration
        at D:\haskell\chapter16\src\ChapterExercises.hs:17:10
      `a1' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a1 b1.
                  (a1 -> b1) -> Company a b a1 -> Company a b b1
        at D:\haskell\chapter16\src\ChapterExercises.hs:18:3
    * In the first argument of `f', namely `b'
      In the first argument of `Something', namely `(f b)'
      In the expression: Something (f b)
    * Relevant bindings include
        b :: b
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:21)
        f :: a1 -> b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:8)
        fmap :: (a1 -> b1) -> Company a b a1 -> Company a b b1
          (bound at D:\haskell\chapter16\src\ChapterExercises.hs:18:3)
Failed, modules loaded: none.

What does the compiler try say?

Body:
You've declared Company as type with three generic types, a, b, and c. When you create an instance instance Functor (Company a b) you've said that for any a and b, there should exist a function fmap with the type:

(c -> d) -> Company a b c -> Company a b d

The function f has the type c -> d, so you can't use b as input for it, because it doesn't have the correct type.


问:
Sending multiple params through selector?
I want to use a selector to get to my controller and pass 2 values, the sender and a number.

Issue is that i get the crash:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CDCFaderController changeView:]: unrecognised selector sent to instance 0x109db6f40'

The code makes sense to me so not sure why, anyone able to help?

```<code>[self.viewController performSelector:@selector(changeView:) withObject:self withObject:[NSNumber numberWithInteger: channel.channelNumber]];
</code>```

Receiver:

```<code>- (void)changeView:(UIButton *)sender chanToPush:(NSNumber*)channel
</code>```

答:
Selector is wrong. @selector(changeView:) should be this @selector(changeView:chanToPush:).

Try this.

```<code>[self.viewController performSelector:@selector(changeView:chanToPush:) withObject:self withObject:[NSNumber numberWithInteger: channel.channelNumber]];
</code>```

Body:
I want to use a selector to get to my controller and pass 2 values, the sender and a number.

Issue is that i get the crash:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CDCFaderController changeView:]: unrecognised selector sent to instance 0x109db6f40'

The code makes sense to me so not sure why, anyone able to help?

[self.viewController performSelector:@selector(changeView:) withObject:self withObject:[NSNumber numberWithInteger: channel.channelNumber]];

Receiver:

- (void)changeView:(UIButton *)sender chanToPush:(NSNumber*)channel

Body:
Selector is wrong. @selector(changeView:) should be this @selector(changeView:chanToPush:).

Try this.

[self.viewController performSelector:@selector(changeView:chanToPush:) withObject:self withObject:[NSNumber numberWithInteger: channel.channelNumber]];


答: The JVM doesn't understand the concept methods outside of a class. Fundamentally any method called by the JVM will have to be in a class. The main method is static as at the start of a java application nothing will have been initialised, so making it static allows the JVM to call it as a starting point.</p>

Title: Why do java programs start with a class definition?

Body:
It is said that a java program itself is a class, but I just don't get the logic behind this.

The java program itself starts of by the definition of a class (after importing the packages...etc) and the main method itself is defined inside a class.

Why is it this way?

Why does a main method have to be included within a class rather than outside as a separate method/function like in the languages such as c, c++...etc.

For example a simple hello world program in java:-

public class HelloWorld
{
    public static void main(String[] args)
    {
        System.out.println("Hello world!"+"Hello again");
    }
}

Why is it necessary that a program should start with a class and the main method included within it?


问:
Deleting certain rows without a loop
I have a dataframe with car repair data. It also tells me if a car broke down (and got repaired). I would like to get rid of all rows with repair events after the car broke down.

```<code>Car <- c('A','A','B')
Damage <-c("Wheels","Motor","Motor")
date <-c('01-01-2015','01-01-2016','01-01-2016')
Broke_down <-c(1,0,1)

df <- as.data.frame(cbind(Car,date,Damage,Broke_down))
</code>```

Basically, I want to remove all lines that occur for a car after the dummy was 1.

So in this case the output would have to be:

```<code>"Car"        "date"          "Damage"     "Broke_down"
 A           01-01-2015       Wheels         1
 B           01-01-2016       Motor          1
</code>```

Best,
Felix

答:
There might be a more elegant way, but lapply and do.call do the trick:

```<code>df_out <- do.call(rbind,lapply(unique(df$Car),function(x){

  df_sub <- df[df$Car==x,]
  df_sub[1:which(df_sub$Broke_down == 1)[1],]

}))

> df_out
  Car       date Damage Broke_down
1   A 01-01-2015 Wheels          1
3   B 01-01-2016  Motor          1
</code>```

Title: Deleting certain rows without a loop

Body:
I have a dataframe with car repair data. It also tells me if a car broke down (and got repaired). I would like to get rid of all rows with repair events after the car broke down.

Car <- c('A','A','B')
Damage <-c("Wheels","Motor","Motor")
date <-c('01-01-2015','01-01-2016','01-01-2016')
Broke_down <-c(1,0,1)

df <- as.data.frame(cbind(Car,date,Damage,Broke_down))

Basically, I want to remove all lines that occur for a car after the dummy was 1.

So in this case the output would have to be:

"Car"        "date"          "Damage"     "Broke_down"
 A           01-01-2015       Wheels         1
 B           01-01-2016       Motor          1

Best,
Felix

Body:
There might be a more elegant way, but lapply and do.call do the trick:

df_out <- do.call(rbind,lapply(unique(df$Car),function(x){

  df_sub <- df[df$Car==x,]
  df_sub[1:which(df_sub$Broke_down == 1)[1],]

}))

> df_out
  Car       date Damage Broke_down
1   A 01-01-2015 Wheels          1
3   B 01-01-2016  Motor          1


问:
Can I Pass value from form to popup window, display something based on what was passed, then pass something back?
I need to do this using PHP and Javascript.

I have one form, with a few inputs. One of them is gender.

When they click a link/button I need to pass the value of the gender drop down to a popup.

Based on that value I show either male or females portraits.

I'd like to pass the value back to the parent window once they select a portrait and then click a button.

I have the code to display the portaits. But how do I pass the values back and forth, and how do I make a value passed from the parent window available to my PHP code in the new popup?

Any help greatly appreciated.

答:
The problem is well defined, but the question itself is still somewhat vague.  I'll give it a shot though.  If you really mean a pop-up (separate window) rather than an on-page dialog (such as jQuery UI elements and so forth), then the communication channel you'll want to use is the object returned from window.open() to communicate from parent page to child page, and window.opener to communicate from child to parent.  For example:

```<code>var genderPicker = document.getElementById('genderSelect');
var gender = genderPicker.options[genderPicker.selectedIndex].value;
var portraitChooserWindow = window.open("path/to/script.ext?gender=" + gender);
// portraitChooserWindow is now a reference to the newly opened pop-up (or null if the browser blocked pop-ups)
</code>```

From the child window, window.opener is now a reference to the parent window.

Body:
The problem is well defined, but the question itself is still somewhat vague.  I'll give it a shot though.  If you really mean a pop-up (separate window) rather than an on-page dialog (such as jQuery UI elements and so forth), then the communication channel you'll want to use is the object returned from window.open() to communicate from parent page to child page, and window.opener to communicate from child to parent.  For example:

var genderPicker = document.getElementById('genderSelect');
var gender = genderPicker.options[genderPicker.selectedIndex].value;
var portraitChooserWindow = window.open("path/to/script.ext?gender=" + gender);
// portraitChooserWindow is now a reference to the newly opened pop-up (or null if the browser blocked pop-ups)

From the child window, window.opener is now a reference to the parent window.


问:
how to create two rounded bordered uiimage in swift
Could anyone suggest me how could I create two rounded border uiimage like shown in this picture.

Is there any available library that I could use?

答:
You dont need to add any library, just add UIView and in that UIImage and make it round.

You can used it below code for that.

```<code>IBBackgroundView.layer.cornerRadius = (IBBackgroundView.frame.width / 2)
        IBBackgroundView.layer.borderColor = UIColor.white.cgColor
        IBBackgroundView.layer.borderWidth = 5.0
        IBBackgroundView.clipsToBounds = true
        IBImageView.layer.cornerRadius = IBImageView.frame.width / 2
        IBImageView.layer.borderColor = UIColor.blue.cgColor
        IBImageView.layer.borderWidth = 3.0
        IBImageView.clipsToBounds = true
</code>```

Body:
You dont need to add any library, just add UIView and in that UIImage and make it round.

You can used it below code for that.

IBBackgroundView.layer.cornerRadius = (IBBackgroundView.frame.width / 2)
        IBBackgroundView.layer.borderColor = UIColor.white.cgColor
        IBBackgroundView.layer.borderWidth = 5.0
        IBBackgroundView.clipsToBounds = true
        IBImageView.layer.cornerRadius = IBImageView.frame.width / 2
        IBImageView.layer.borderColor = UIColor.blue.cgColor
        IBImageView.layer.borderWidth = 3.0
        IBImageView.clipsToBounds = true


问:
Connecting to postgresql from lapis
I decided to play with lapis - https://github.com/leafo/lapis, but the application drops when I try to query the database (PostgreSQL) with the output:

2017/07/01 16:04:26 [error] 31284#0: *8 lua entry thread aborted: runtime error: attempt to yield across C-call boundary
  stack traceback:
  coroutine 0:
          [C]: in function 'require'
          /usr/local/share/lua/5.1/lapis/init.lua:15: in function 'serve'
          content_by_lua(nginx.conf.compiled:22):2: in function , client: 127.0.0.1, server: , request: "GET / HTTP/1.1", host: "localhost:8080"

The code that causes the error:

```<code>local db = require("lapis.db")
local res = db.query("SELECT * FROM users");
</code>```

config.lua:

```<code>config({ "development", "production" }, {
    postgres = {
        host = "0.0.0.0",
        port = "5432",
        user = "wars_base",
        password = "12345",
        database = "wars_base"
    }
})
</code>```

The database is running, the table is created, in table 1 there is a record.

What could be the problem?

Decision: https://github.com/leafo/lapis/issues/556

答:
You need to specify the right server IP in the host parameter.

The IP you have specified 0.0.0.0 is not a valid one, and normally it is used when you specify a listen address, with the meaning of "every address".

Usually you can use the '127.0.0.1' address during development.

Title: Connecting to postgresql from lapis

Body:
I decided to play with lapis - https://github.com/leafo/lapis, but the application drops when I try to query the database (PostgreSQL) with the output:

2017/07/01 16:04:26 [error] 31284#0: *8 lua entry thread aborted: runtime error: attempt to yield across C-call boundary
  stack traceback:
  coroutine 0:
          [C]: in function 'require'
          /usr/local/share/lua/5.1/lapis/init.lua:15: in function 'serve'
          content_by_lua(nginx.conf.compiled:22):2: in function , client: 127.0.0.1, server: , request: "GET / HTTP/1.1", host: "localhost:8080"

The code that causes the error:

local db = require("lapis.db")
local res = db.query("SELECT * FROM users");

config.lua:

config({ "development", "production" }, {
    postgres = {
        host = "0.0.0.0",
        port = "5432",
        user = "wars_base",
        password = "12345",
        database = "wars_base"
    }
})

The database is running, the table is created, in table 1 there is a record.

What could be the problem?

Decision: https://github.com/leafo/lapis/issues/556


问:
How to check recref.field(Integer) is empty or exists in Navision Development ( C/ALL )?
RecRef is datatype of RecRef, and by this i access to table and can select the field of the table;

```<code>RecRef.OPEN(IDTABLE);
RecRef.field(2); // RETURN THE FIELD DATA OF THE IDTABLE.
</code>```

but if this is empty navision send error so;

How to check if RecRef.field(Integer) is empty or exists in Navision Development (C/ALL)?

Thanks in advance,

答:
You may use virtual table Field to check which field numbers exist in a table, as well as their data types and other properties.

https://msdn.microsoft.com/en-us/library/dd301354(v=nav.90).aspx

You may also reference fields using RecRef.FIELDINDEX(i), where i is between 1 and RecRef.FIELDCOUNT. By this you do not need to guess field numbers if you do not know them.

I would also advise to look at Codeunits 423 Change Log Management and 8617 Config. Validate Management for advanced examples and scenarios of working with RecordRefs and FieldRefs.

Body:
RecRef is datatype of RecRef, and by this i access to table and can select the field of the table;

RecRef.OPEN(IDTABLE);
RecRef.field(2); // RETURN THE FIELD DATA OF THE IDTABLE.

but if this is empty navision send error so;

How to check if RecRef.field(Integer) is empty or exists in Navision Development (C/ALL)?

Thanks in advance,


问:
I have this code below and I want the console to display the text
I have this code below and I want to use the underscore in order to display the text below...

```<code>var log = function(contents) {
        if(_.isArray(contents)) {
            _.each(contents, function(e, i, l) {
                log(e);
              $('#result');
                $('#result').append('</br></br>');
            });
        } else {
            $('#result').append(contents);
        }
    };

    var out = [];
    _.each(ty, function(v,k){
    var hold = {};
    hold.o = {
        l: {
        s:{
            t: 'Trying this for first time...'
        }
      }
    };

    out.push(hold);
    });

    Console.log(out.l.s);
</code>```

I want to display the text 'Trying this for the first time...'

答:
Thank a lot for your answer, but actually, what i want is something similar to what is below:</p>

```<code>hold.options (tooltips object) = {
 (property based on the section generated automatically): {
  (properly based on the itemName generated automatically): {
       t: item.Texts,
    }
  }
</code>```

Body:
I have this code below and I want to use the underscore in order to display the text below...

var log = function(contents) {
        if(_.isArray(contents)) {
            _.each(contents, function(e, i, l) {
                log(e);
              $('#result');
                $('#result').append('

');
            });
        } else {
            $('#result').append(contents);
        }
    };

    var out = [];
    _.each(ty, function(v,k){
    var hold = {};
    hold.o = {
        l: {
        s:{
            t: 'Trying this for first time...'
        }
      }
    };

    out.push(hold);
    });

    Console.log(out.l.s);

I want to display the text 'Trying this for the first time...'

Body:
Thank a lot for your answer, but actually, what i want is something similar to what is below:

hold.options (tooltips object) = {
 (property based on the section generated automatically): {
  (properly based on the itemName generated automatically): {
       t: item.Texts,
    }
  }