问:
Run PHP File In Terminal/Powershell without .php extension
I've seen numerous posts of running php files without extensions on the browser.My question is,is it possible to do the same when running a file in cli?Example scenario:I have a file called Test.php
that contains this simple code:

class Test
{
    public function action()
    {
        global $argv;
        $script = array_shift($argv);

        print($argv[0]);
    }
}
(new Test)->action();
```

<p>Now on the terminal,instead of doing</p>

```$ php Test.php -calltoAction
```

<p>I'd like to do:</p>

<pre class="lang-sh prettyprint-override"><code>$ php Test -calltoAction
</code>```

and get calltoAction printed out.How do I accomplish this.

答:
It is certainly possible. PHP CLI does not care about the file extensions.

Trying to pass argv to your function as a global is not the way to go. Pass it as a function argument instead.

```<code>class Test
{
    public function action($args)
    {
        $script = array_shift($args);

        print($args[0]);
    }
}
(new Test)->action($argv);
</code>```

~

Body:
I've seen numerous posts of running php files without extensions on the browser.My question is,is it possible to do the same when running a file in cli?Example scenario:I have a file called Test.php
that contains this simple code:

class Test
{
    public function action()
    {
        global $argv;
        $script = array_shift($argv);

        print($argv[0]);
    }
}
(new Test)->action();

Now on the terminal,instead of doing

$ php Test.php -calltoAction

I'd like to do:

$ php Test -calltoAction

and get calltoAction printed out.How do I accomplish this.

Body:
It is certainly possible. PHP CLI does not care about the file extensions.

Trying to pass argv to your function as a global is not the way to go. Pass it as a function argument instead.

class Test
{
    public function action($args)
    {
        $script = array_shift($args);

        print($args[0]);
    }
}
(new Test)->action($argv);

~


来源: stackexchange

问:
Is there a way to get all facebook ads?
I need to get all ads from Facebook API. Is there a way to do it?

Here a example of what i need https://adspyhub.com/

This is for a app that i'm developing in React JS.
I'd already read the docs, but i'm not finding anything.
I'm using react-facebook-login to Facebook Login

```<code> <FacebookLogin
        appId="************"
        autoLoad={true}
        fields="name,email,picture"
        scope="public_profile,user_friends,user_actions.books"
        onClick={() => {
          console.log("clic");
        }}
        callback={response => {
          const axios = require("axios");
          axios.get(
            `https://graph.facebook.com/v3.3/ads_archive?access_token=${
              response.accessToken
            }&ad_reached_countries=${["US"]}`
          );
        }}
      />
</code>```

This error appears as response for Axios Request. What permissions I need to do this?

```<code>{
   "error": {
      "message": "Application does not have permission for this action",
      "type": "OAuthException",
      "code": 10,
      "error_subcode": 2332002,
      "is_transient": false,
      "error_user_title": "Authorization and login needed",
      "error_user_msg": "For access to the API you need to be authorized and logged into Facebook.To begin authorization, you can visit facebook.com/ID.",
      "fbtrace_id": "*********"
   }
}
</code>```

答:
I cannot find any "ads_archive" endpoint in the API reference, you may want to take at the existing ones: https://developers.facebook.com/docs/marketing-api/reference/v3.3

The first endpoint i would try is /adaccounts to get all Ad Accounts. For every Ad Account, you can get Campaigns, AdSets, Ads, ... for example: /ad-account-id/adsets

Also, you do not ask for permissions related to Ads: ads_read and ads_management.

ContentLicense: CC BY-SA 4.0

Title: Is there a way to get all facebook ads?

Body:
I need to get all ads from Facebook API. Is there a way to do it?

Here a example of what i need https://adspyhub.com/

This is for a app that i'm developing in React JS.
I'd already read the docs, but i'm not finding anything.
I'm using react-facebook-login to Facebook Login

 <FacebookLogin
        appId="************"
        autoLoad={true}
        fields="name,email,picture"
        scope="public_profile,user_friends,user_actions.books"
        onClick={() => {
          console.log("clic");
        }}
        callback={response => {
          const axios = require("axios");
          axios.get(
            `https://graph.facebook.com/v3.3/ads_archive?access_token=${
              response.accessToken
            }&ad_reached_countries=${["US"]}`
          );
        }}
      />

This error appears as response for Axios Request. What permissions I need to do this?

{
   "error": {
      "message": "Application does not have permission for this action",
      "type": "OAuthException",
      "code": 10,
      "error_subcode": 2332002,
      "is_transient": false,
      "error_user_title": "Authorization and login needed",
      "error_user_msg": "For access to the API you need to be authorized and logged into Facebook.To begin authorization, you can visit facebook.com/ID.",
      "fbtrace_id": "*********"
   }
}


问:
For loop to read file names
I am new to python. I want to create a for loop that prints all the file names in my folder.

This is what I have :

```<code>import cf
f = cf.read('/home/cd_files')
for i in f:
  print f
</code>```

The file names are string values. I am guessing what I failed to include in my code.

答:
```<code>import os
files = os.listdir('your_directory/')
for file in files:
    print(file)
</code>```

Title: For loop to read file names

Body:
I am new to python. I want to create a for loop that prints all the file names in my folder.

This is what I have :

import cf
f = cf.read('/home/cd_files')
for i in f:
  print f

The file names are string values. I am guessing what I failed to include in my code.


问:
Different type showing for Pandas Series
When i hardcode a Series to see its type, i see it as below

```<code>type(qs_raw_document[1])

str
</code>```

But when i put this in a loop, i see the output as

```<code>n = qs_raw_document.shape[0]
for i in range(0,3):
    text = qs_raw_document[i]
    print(type(qs_raw_document[i]))

<class 'str'>
<class 'str'>
<class 'str'>
</code>```

The reason i am asking this query is that some of my function expects the input as str only.

I am trying to do some Pre-processing in NLP text.

```<code>    type(qs_raw_document[1])

    n = qs_raw_document.shape[0]
    for i in range(0,3):
        text = qs_raw_document[i]
        print(type(qs_raw_document[i]))
</code>```

I am expecting both to give the same result

答:
<class 'str'> is how str is printed:

```<code>In [11]: print(str)
<type 'str'>

In [12]: str(str)
Out[12]: "<type 'str'>"

In [13]: repr(str)
Out[13]: "<type 'str'>"

In [14]: str.__name__
Out[14]: 'str'
</code>```

Note: ipython prints the __name__ rather than the str/repr.

Body:
When i hardcode a Series to see its type, i see it as below

type(qs_raw_document[1])

str

But when i put this in a loop, i see the output as

n = qs_raw_document.shape[0]
for i in range(0,3):
    text = qs_raw_document[i]
    print(type(qs_raw_document[i]))

<class 'str'>
<class 'str'>
<class 'str'>

The reason i am asking this query is that some of my function expects the input as str only.

I am trying to do some Pre-processing in NLP text.

    type(qs_raw_document[1])

    n = qs_raw_document.shape[0]
    for i in range(0,3):
        text = qs_raw_document[i]
        print(type(qs_raw_document[i]))

I am expecting both to give the same result

Body:
<class 'str'> is how str is printed:

In [11]: print(str)
<type 'str'>

In [12]: str(str)
Out[12]: "<type 'str'>"

In [13]: repr(str)
Out[13]: "<type 'str'>"

In [14]: str.__name__
Out[14]: 'str'

Note: ipython prints the __name__ rather than the str/repr.


问:
Haskell Function to Clojure function conversion
Trying to convert Haskell function to Clojure. But facing difficulties. Not sure what's happening.

Here's recursive Haskell function.

```<code>  mapWidth :: [[Char]] -> Int
  mapWidth [] = 0
  mapWidth (x:xs)
  | length xs == 0 = length x
  | length x /= length (xs!!0) = -1
  | otherwise = mapWidth(xs)
</code>```

Here's what I've tried so far :

```<code>(defn mapWidth [data_list]
    (def data 0)
    ([[x & xs](seq data_list)](if (= (count x) 0)
    (data 0)
    (data -1))))
    ([[x & xs](seq data_list)](if not(= (count xs) length (xs!!0))
    (data 0)
    (data -1)
    mapWidth(xs)))
</code>```

Any help is appreciated. I'm pretty new to both the languages.

答:
as far as i can see, this function returns length of an element, if all elements have the equal length. In this case it could look like this:

```<code>(defn map-len [[x & [y :as xs]]]
  (cond (empty? xs) (count x)
        (not= (count x) (count y)) -1
        :else (recur xs)))
</code>```

which is almost the exact rewrite of haskell variant (replacing straight recursive call with recur)

```<code>(map-len [[1 2] [3 4] [5 6]])
;;=> 2

(map-len [[1 2] [3 4 5] [5 6]])
;;=> -1
</code>```

bot since clojure is about operations on sequences, you can do it in a more idiomatic way (as for me, it is):

```<code>(defn map-len2 [data]
  (cond (empty? data) 0
        (apply = (map count data)) (count (first data))
        :else -1))

(defn map-len3 [[x & xs]]
  (let [c (count x)]
    (if (every? #(= c (count %)) xs)
      c
      -1)))
</code>```

Body:
Trying to convert Haskell function to Clojure. But facing difficulties. Not sure what's happening.

Here's recursive Haskell function.

  mapWidth :: [[Char]] -> Int
  mapWidth [] = 0
  mapWidth (x:xs)
  | length xs == 0 = length x
  | length x /= length (xs!!0) = -1
  | otherwise = mapWidth(xs)

Here's what I've tried so far :

(defn mapWidth [data_list]
    (def data 0)
    ([[x & xs](seq data_list)](if (= (count x) 0)
    (data 0)
    (data -1))))
    ([[x & xs](seq data_list)](if not(= (count xs) length (xs!!0))
    (data 0)
    (data -1)
    mapWidth(xs)))

Any help is appreciated. I'm pretty new to both the languages.

Body:
as far as i can see, this function returns length of an element, if all elements have the equal length. In this case it could look like this:

(defn map-len [[x & [y :as xs]]]
  (cond (empty? xs) (count x)
        (not= (count x) (count y)) -1
        :else (recur xs)))

which is almost the exact rewrite of haskell variant (replacing straight recursive call with recur)

(map-len [[1 2] [3 4] [5 6]])
;;=> 2

(map-len [[1 2] [3 4 5] [5 6]])
;;=> -1

bot since clojure is about operations on sequences, you can do it in a more idiomatic way (as for me, it is):

(defn map-len2 [data]
  (cond (empty? data) 0
        (apply = (map count data)) (count (first data))
        :else -1))

(defn map-len3 [[x & xs]]
  (let [c (count x)]
    (if (every? #(= c (count %)) xs)
      c
      -1)))


问:
How to add a null value in the group_concat if the record does not exist?
I have this SQL query with substring_index and group_concat but the results I get does not give the right location of the values because the values does not exist.

I need to add a null or zero value in order to have the right location of the values in the sql result.

In the table there are three lid (1, 2, 3). The lid should be the basis count of the P's (P1, P2, P3) for the substring_index.

This is the table:

```<code>lid   class_id   class          total
-----  -------    -----        -----
  1     73       Leader         10000
  1     77       Consultant     8000
  1     83       Coordinator    6000
  2     73       Leader         20000
  2     76       Staff          8000
  2     77       Consultant     10000
  3     73       Leader         30000
  3     78       Team Leader    8000
</code>```

This is the SQL query I used to group_concat for the totals and substring_index to separate the grouped values with their each column (P1, P2, P3)

```<code>SELECT *, GROUP_CONCAT(lid) as lids, GROUP_CONCAT(pyear) as pyears,
 COUNT(DISTINCT lib_id) AS total_count,
 CASE WHEN COUNT(*)>=1 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',1),' ',-1) END AS P1,
 CASE WHEN COUNT(*)>=2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',2),' ',-1) END AS P2,
 CASE WHEN COUNT(*)>=3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',3),' ',-1) END AS P3
 FROM (
  SELECT * FROM view_items WHERE lid='1'
  UNION
  SELECT * FROM view_items WHERE lid='2'
  UNION
  SELECT * FROM view_items WHERE lid='3'
 ) AS AZ GROUP BY class_id
</code>```

This is the result of the above query:

```<code>class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          2       8000
   77      Consultant     1,2     8000    10000
   78      Team Leader    3       8000
   83      Coordinator    1       6000
</code>```

The lids should always have three count even though the record does not exists, a zero or null value should be added. How to do the adding of null value?

This is the expected result I need.

```<code> class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          0,2,0     0     8000      0
   77      Consultant     1,2,0    8000   10000     0
   78      Team Leader    0,0,3     0       0      8000
   83      Coordinator    1,0,0    6000     0       0
</code>```

答:
To get 0 values where no lid is present in the table, you need to generate a list of all lid values for all class_id values, which you can do with a CROSS JOIN of two SELECT DISTINCT queries (one for lid, one for class_id). This can then be LEFT JOINed to the table, to get the required total value for each P group using conditional aggregation:

```<code>SELECT c.class_id,
       MAX(v.class),
       GROUP_CONCAT(COALESCE(v.lid, 0) ORDER BY l.lid) AS lids,
       MAX(CASE WHEN v.lid=1 THEN total ELSE 0 END) AS P1,
       MAX(CASE WHEN v.lid=2 THEN total ELSE 0 END) AS P2,
       MAX(CASE WHEN v.lid=3 THEN total ELSE 0 END) AS P3
FROM (SELECT DISTINCT lid FROM view_items) l
CROSS JOIN (SELECT DISTINCT class_id FROM view_items) c
LEFT JOIN view_items v ON v.lid = l.lid AND v.class_id = c.class_id
GROUP BY c.class_id
</code>```

Output:

```<code>class_id    class       lids    P1      P2      P3
73          Leader      1,2,3   10000   20000   30000
76          Staff       0,2,0   0       8000    0
77          Consultant  1,2,0   8000    10000   0
78          Team Leader 0,0,3   0       0       8000
83          Coordinator 1,0,0   6000    0       0
</code>```

Demo on dbfiddle

Body:
I have this SQL query with substring_index and group_concat but the results I get does not give the right location of the values because the values does not exist.

I need to add a null or zero value in order to have the right location of the values in the sql result.

In the table there are three lid (1, 2, 3). The lid should be the basis count of the P's (P1, P2, P3) for the substring_index.

This is the table:

lid   class_id   class          total
-----  -------    -----        -----
  1     73       Leader         10000
  1     77       Consultant     8000
  1     83       Coordinator    6000
  2     73       Leader         20000
  2     76       Staff          8000
  2     77       Consultant     10000
  3     73       Leader         30000
  3     78       Team Leader    8000

This is the SQL query I used to group_concat for the totals and substring_index to separate the grouped values with their each column (P1, P2, P3)

SELECT *, GROUP_CONCAT(lid) as lids, GROUP_CONCAT(pyear) as pyears,
 COUNT(DISTINCT lib_id) AS total_count,
 CASE WHEN COUNT(*)>=1 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',1),' ',-1) END AS P1,
 CASE WHEN COUNT(*)>=2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',2),' ',-1) END AS P2,
 CASE WHEN COUNT(*)>=3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',3),' ',-1) END AS P3
 FROM (
  SELECT * FROM view_items WHERE lid='1'
  UNION
  SELECT * FROM view_items WHERE lid='2'
  UNION
  SELECT * FROM view_items WHERE lid='3'
 ) AS AZ GROUP BY class_id

This is the result of the above query:

class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          2       8000
   77      Consultant     1,2     8000    10000
   78      Team Leader    3       8000
   83      Coordinator    1       6000

The lids should always have three count even though the record does not exists, a zero or null value should be added. How to do the adding of null value?

This is the expected result I need.

 class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          0,2,0     0     8000      0
   77      Consultant     1,2,0    8000   10000     0
   78      Team Leader    0,0,3     0       0      8000
   83      Coordinator    1,0,0    6000     0       0

Body:
To get 0 values where no lid is present in the table, you need to generate a list of all lid values for all class_id values, which you can do with a CROSS JOIN of two SELECT DISTINCT queries (one for lid, one for class_id). This can then be LEFT JOINed to the table, to get the required total value for each P group using conditional aggregation:

SELECT c.class_id,
       MAX(v.class),
       GROUP_CONCAT(COALESCE(v.lid, 0) ORDER BY l.lid) AS lids,
       MAX(CASE WHEN v.lid=1 THEN total ELSE 0 END) AS P1,
       MAX(CASE WHEN v.lid=2 THEN total ELSE 0 END) AS P2,
       MAX(CASE WHEN v.lid=3 THEN total ELSE 0 END) AS P3
FROM (SELECT DISTINCT lid FROM view_items) l
CROSS JOIN (SELECT DISTINCT class_id FROM view_items) c
LEFT JOIN view_items v ON v.lid = l.lid AND v.class_id = c.class_id
GROUP BY c.class_id

Output:

class_id    class       lids    P1      P2      P3
73          Leader      1,2,3   10000   20000   30000
76          Staff       0,2,0   0       8000    0
77          Consultant  1,2,0   8000    10000   0
78          Team Leader 0,0,3   0       0       8000
83          Coordinator 1,0,0   6000    0       0

Demo on dbfiddle


问:
Getting error "variable veryFar might not have been initialized" with BigInteger
I am making a converter which will convert numbers to text. I did everything as said in this website and edited for using big Integers but it is then showing a variable is not initialized.

I edited some things to make it compatible with big integers for bigger numbers, but it just shows variable veryFar maybe not initialized. (I edited the variable name to try fix it!).

package com.example.convertnumbertotext;

import java.math.BigInteger;
import java.text.DecimalFormat;

public class EnglishNumberToWords {

    private static BigInteger bi = new BigInteger("100");
    private static BigInteger bi2 = new BigInteger("20");
    private static BigInteger bi3 = new BigInteger("10");
    private static final String[] tensNames = { "", " ten", " twenty", " thirty", " forty",
            " fifty", " sixty", " seventy", " eighty", " ninety" };

    private static final String[] numNames = { "", " one", " two", " three", " four", " five",
            " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen",
            " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen" };

    private static String convertLessThanOneThousand(BigInteger number) {
        String veryFar;
        BigInteger[] bii = number.divideAndRemainder(bi);
        BigInteger[] bii2 = number.divideAndRemainder(bi3);
        int resut = bii[1].compareTo(bi2);

        if (resut == -1) {
            veryFar = numNames[bii[1].intValue()];

            number = number.divide(bi);
        } else if (resut == 1 || resut == 0) {
            veryFar = numNames[bii2[1].intValue()];
            number = number.divide(bi3);

            veryFar = tensNames[bii2[1].intValue()] + veryFar;
            number = number.divide(bi3);
        }
        if (number.compareTo(BigInteger.valueOf(0)) == 0)
            return veryFar;
            return numNames[number.intValue()] + " hundred" + veryFar;
    }

}
```

It shows 2 same error messages-
error: variable veryFar might not have been initialized
error: variable veryFar might not have been initialized

答:
Trimmed down, you have this code:

```<code>String veryFar;
...
if (resut == -1) {
    veryFar = numNames[bii[1].intValue()];
    ...
} else if (resut == 1 || resut == 0) {
    veryFar = numNames[bii2[1].intValue()];
    ...
}
</code>```

If result is not -1, 0, or 1, neither of these blocks will be executed. In that case, veryFar will never be assigned a value.

Either initialize it when you declare it (like String veryFar = null) or add an else case that assigns a value to it.

Body:
I am making a converter which will convert numbers to text. I did everything as said in this website and edited for using big Integers but it is then showing a variable is not initialized.

I edited some things to make it compatible with big integers for bigger numbers, but it just shows variable veryFar maybe not initialized. (I edited the variable name to try fix it!).

package com.example.convertnumbertotext;

import java.math.BigInteger;
import java.text.DecimalFormat;

public class EnglishNumberToWords {

    private static BigInteger bi = new BigInteger("100");
    private static BigInteger bi2 = new BigInteger("20");
    private static BigInteger bi3 = new BigInteger("10");
    private static final String[] tensNames = { "", " ten", " twenty", " thirty", " forty",
            " fifty", " sixty", " seventy", " eighty", " ninety" };

    private static final String[] numNames = { "", " one", " two", " three", " four", " five",
            " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen",
            " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen" };

    private static String convertLessThanOneThousand(BigInteger number) {
        String veryFar;
        BigInteger[] bii = number.divideAndRemainder(bi);
        BigInteger[] bii2 = number.divideAndRemainder(bi3);
        int resut = bii[1].compareTo(bi2);

        if (resut == -1) {
            veryFar = numNames[bii[1].intValue()];

            number = number.divide(bi);
        } else if (resut == 1 || resut == 0) {
            veryFar = numNames[bii2[1].intValue()];
            number = number.divide(bi3);

            veryFar = tensNames[bii2[1].intValue()] + veryFar;
            number = number.divide(bi3);
        }
        if (number.compareTo(BigInteger.valueOf(0)) == 0)
            return veryFar;
            return numNames[number.intValue()] + " hundred" + veryFar;
    }

}

It shows 2 same error messages-
error: variable veryFar might not have been initialized
error: variable veryFar might not have been initialized

Body:
Trimmed down, you have this code:

String veryFar;
...
if (resut == -1) {
    veryFar = numNames[bii[1].intValue()];
    ...
} else if (resut == 1 || resut == 0) {
    veryFar = numNames[bii2[1].intValue()];
    ...
}

If result is not -1, 0, or 1, neither of these blocks will be executed. In that case, veryFar will never be assigned a value.

Either initialize it when you declare it (like String veryFar = null) or add an else case that assigns a value to it.


问:
Spring batch read from xml write to csv file
Hi I have a spring batch job to read from xml file and write to Csv file , I have an issue to change this working example works with  xml file with a nested tag  :

in the working example xml is :

```<code><?xml version="1.0" encoding="UTF-8" ?>
<company>
    <record >
        <name>ben</name>
        <age>31</age>
        <dob>31/8/1982</dob>
        <income>200,000</income>
    </record>
    <record >
        <name>aya</name>
        <age>30</age>
        <dob>26/7/1983</dob>
        <income>100,999</income>
    </record>
   </company>
</code>```

I want it to work with  xml file like this :

```<code><company>
    <record >
        <name>ben</name>
        <age>31</age>
        <dob>31/8/1982</dob>
        **<income>
           <Gross> 2000<Gross/>
           <Net>1000</Net>
        </income>**
    </record>
    <record >
        <name>aya</name>
        <age>30</age>
        <dob>26/7/1983</dob>
        <income>100,999</income>
    </record>
   </company>

  <batch:job id="reportJob">
    <batch:step id="step1">
    <batch:tasklet>
        <batch:chunk reader="xmlItemReader"
            writer="cvsFileItemWriter" processor="filterReportProcessor"
            commit-interval="1">
        </batch:chunk>
    </batch:tasklet>
    </batch:step>
  </batch:job>

  <!-- Filtering process -->
  <bean id="filterReportProcessor" class="com.mkyong.processor.FilterReportProcessor" />

  <bean id="xmlItemReader"
        class="org.springframework.batch.item.xml.StaxEventItemReader">
    <property name="fragmentRootElementName" value="record" />
    <property name="resource" value="classpath:xml/report.xml" />
    <property name="unmarshaller" ref="reportUnmarshaller" />
  </bean>

  <!-- Read and map values to object, via jaxb2 -->
  <bean id="reportUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
    <list>
        <value>com.ben.model.Report</value>
    </list>
    </property>
  </bean>

  <bean id="cvsFileItemWriter" class="org.springframework.batch.item.file.FlatFileItemWriter">
    <!-- write to this csv file -->
    <property name="resource" value="file:cvs/report.csv" />
    <property name="shouldDeleteIfExists" value="true" />

    <property name="lineAggregator">
      <bean
        class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
        <property name="delimiter" value="," />
        <property name="fieldExtractor">
          <bean
            class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
            <property name="names" value="refId, name, age, csvDob, income" />
           </bean>
        </property>
       </bean>
    </property>
  </bean>

</beans>
</code>```

the POJO is like this :

```<code>@XmlRootElement(name = "record")
public class Report {

    private int refId;
    private String name;
    private int age;
    private Date dob;
    private BigDecimal income;

    @XmlAttribute(name = "refId")
    public int getRefId() {
        return refId;
    }

    public void setRefId(int refId) {
        this.refId = refId;
    }

    @XmlElement(name = "age")
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @XmlElement
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlJavaTypeAdapter(JaxbDateAdapter.class)
    @XmlElement
    public Date getDob() {
        return dob;
    }

    @XmlJavaTypeAdapter(JaxbDateAdapter.class)
    public void setDob(Date dob) {
        this.dob = dob;
    }

    @XmlJavaTypeAdapter(JaxbBigDecimalAdapter.class)
    @XmlElement
    public BigDecimal getIncome() {
        return income;
    }

    public void setIncome(BigDecimal income) {
        this.income = income;
    }

    // for csv demo only
    public String getCsvDob() {

        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        return dateFormat.format(getDob());

    }

}
</code>```

so far I tried to create a class Income in the record  and added Gross and Net in the XML config file like this :  <property name="names" value="refId, name, age, csvDob, Gross,Net" />,but that didn t work , I didn t got the values of Gross and Net . what I should do to get it working please.

答:
This is more a JAXB question rather than Spring Batch question. Your issue is how to map this XML snippet:

```<code><record >
    <name>ben</name>
    <age>31</age>
    <dob>31/8/1982</dob>
    <income>
       <Gross> 2000<Gross/>
       <Net>1000</Net>
    </income>
</record>
</code>```

to your domain object of type Report. As defined in your example, the mapping does not work because the field income is of type BigDecimal.

so far I tried to create a class Income

You need to update the income field type from BigDecimal to Income.

Body:
Hi I have a spring batch job to read from xml file and write to Csv file , I have an issue to change this working example works with  xml file with a nested tag  :

in the working example xml is :

<?xml version="1.0" encoding="UTF-8" ?>
<company>
    <record >
        <name>ben</name>
        <age>31</age>
        <dob>31/8/1982</dob>
        <income>200,000</income>
    </record>
    <record >
        <name>aya</name>
        <age>30</age>
        <dob>26/7/1983</dob>
        <income>100,999</income>
    </record>
   </company>

I want it to work with  xml file like this :

<company>
    <record >
        <name>ben</name>
        <age>31</age>
        <dob>31/8/1982</dob>
        **<income>
           <Gross> 2000<Gross/>
           <Net>1000</Net>
        </income>**
    </record>
    <record >
        <name>aya</name>
        <age>30</age>
        <dob>26/7/1983</dob>
        <income>100,999</income>
    </record>
   </company>

  <batch:job id="reportJob">
    <batch:step id="step1">
    <batch:tasklet>
        <batch:chunk reader="xmlItemReader"
            writer="cvsFileItemWriter" processor="filterReportProcessor"
            commit-interval="1">
        </batch:chunk>
    </batch:tasklet>
    </batch:step>
  </batch:job>

  <bean id="filterReportProcessor" class="com.mkyong.processor.FilterReportProcessor" />

  <bean id="xmlItemReader"
        class="org.springframework.batch.item.xml.StaxEventItemReader">
    <property name="fragmentRootElementName" value="record" />
    <property name="resource" value="classpath:xml/report.xml" />
    <property name="unmarshaller" ref="reportUnmarshaller" />
  </bean>

  <bean id="reportUnmarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
    <list>
        <value>com.ben.model.Report</value>
    </list>
    </property>
  </bean>

  <bean id="cvsFileItemWriter" class="org.springframework.batch.item.file.FlatFileItemWriter">

    <property name="resource" value="file:cvs/report.csv" />
    <property name="shouldDeleteIfExists" value="true" />

    <property name="lineAggregator">
      <bean
        class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
        <property name="delimiter" value="," />
        <property name="fieldExtractor">
          <bean
            class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
            <property name="names" value="refId, name, age, csvDob, income" />
           </bean>
        </property>
       </bean>
    </property>
  </bean>

</beans>

the POJO is like this :

@XmlRootElement(name = "record")
public class Report {

    private int refId;
    private String name;
    private int age;
    private Date dob;
    private BigDecimal income;

    @XmlAttribute(name = "refId")
    public int getRefId() {
        return refId;
    }

    public void setRefId(int refId) {
        this.refId = refId;
    }

    @XmlElement(name = "age")
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @XmlElement
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlJavaTypeAdapter(JaxbDateAdapter.class)
    @XmlElement
    public Date getDob() {
        return dob;
    }

    @XmlJavaTypeAdapter(JaxbDateAdapter.class)
    public void setDob(Date dob) {
        this.dob = dob;
    }

    @XmlJavaTypeAdapter(JaxbBigDecimalAdapter.class)
    @XmlElement
    public BigDecimal getIncome() {
        return income;
    }

    public void setIncome(BigDecimal income) {
        this.income = income;
    }

    // for csv demo only
    public String getCsvDob() {

        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        return dateFormat.format(getDob());

    }

}

so far I tried to create a class Income in the record  and added Gross and Net in the XML config file like this :  <property name="names" value="refId, name, age, csvDob, Gross,Net" />,but that didn t work , I didn t got the values of Gross and Net . what I should do to get it working please.

Body:
This is more a JAXB question rather than Spring Batch question. Your issue is how to map this XML snippet:

<record >
    <name>ben</name>
    <age>31</age>
    <dob>31/8/1982</dob>
    <income>
       <Gross> 2000<Gross/>
       <Net>1000</Net>
    </income>
</record>

to your domain object of type Report. As defined in your example, the mapping does not work because the field income is of type BigDecimal.

so far I tried to create a class Income

You need to update the income field type from BigDecimal to Income.


问:
How to sort an Observable Array based on a certain item inside each Array
I have an Observable array in knockout with arrays inside, there is an item inside each of the arrays called 'time'. How would I order the arrays inside my observable array so that they are in order, from low to high, based on the value of the item. The values are in Hour:Minute:Second format.

function viewModel() {
  var self = this;

  self.myObservable = ko.observableArray([
  {time: "01:00:00", name: 'frank'},
  {time: "05:30:00", name: 'bob'},
  {time: "03:00:00", name: 'bill'},
  {time: "00:00:21", name: 'john'},
  {time: "00:12:00", name: 'paul'}
  ])
}```

答:
Knockout has built-in methods for observableArray which work similar to Array.prototype. You can sort it by using localeCompare

function viewModel() {
  var self = this;

  self.myObservable = ko.observableArray([
      { time: "01:00:00", name: 'frank' },
      { time: "05:30:00", name: 'bob' },
      { time: "03:00:00", name: 'bill' },
      { time: "00:00:21", name: 'john' },
      { time: "00:12:00", name: 'paul' }
    ]);

  self.sort = function() {
    self.myObservable.sort((a, b) => a.time.localeCompare(b.time))
  }
}

ko.applyBindings(new viewModel)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<!-- ko foreach: myObservable -->
  <span data-bind="text: time"></span><br>
<!-- /ko -->

<button data-bind="click: sort">Sort</button></code>```

Body:
Knockout has built-in methods for observableArray which work similar to Array.prototype. You can sort it by using localeCompare

function viewModel() {
  var self = this;

  self.myObservable = ko.observableArray([
      { time: "01:00:00", name: 'frank' },
      { time: "05:30:00", name: 'bob' },
      { time: "03:00:00", name: 'bill' },
      { time: "00:00:21", name: 'john' },
      { time: "00:12:00", name: 'paul' }
    ]);

  self.sort = function() {
    self.myObservable.sort((a, b) => a.time.localeCompare(b.time))
  }
}

ko.applyBindings(new viewModel)

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<!-- ko foreach: myObservable -->
  <span data-bind="text: time"></span><br>
<!-- /ko -->

<button data-bind="click: sort">Sort</button>


问:
How to export a DataGrid to Excel in WPF
I am working on a project and I have not been able to export the information that I have in my DataGrid to excel.

how can I do it?

答:
Install Microsoft.Office.Interop.Excel Nuget package in your application. Right-click on your project -> "References" and choose "Manage NuGet Packages...", then just search for Excel. Otherwise, select Tools -> Nuget Package Manager -> Package Manager Console -> then install the Excel nuget (https://www.nuget.org/packages/Microsoft.Office.Interop.Excel/).

Bind the items in DataGrid and then export data to excel as like below,

```<code>        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application excel = null;
            Microsoft.Office.Interop.Excel.Workbook wb = null;
            object missing = Type.Missing;
            Microsoft.Office.Interop.Excel.Worksheet ws = null;
            Microsoft.Office.Interop.Excel.Range rng = null;

            // collection of DataGrid Items
            var dtExcelDataTable = ExcelTimeReport(txtFrmDte.Text, txtToDte.Text, strCondition);

            excel = new Microsoft.Office.Interop.Excel.Application();
            wb = excel.Workbooks.Add();
            ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;
            ws.Columns.AutoFit();
            ws.Columns.EntireColumn.ColumnWidth = 25;

            // Header row
            for (int Idx = 0; Idx < dtExcelDataTable.Columns.Count; Idx++)
            {
                ws.Range["A1"].Offset[0, Idx].Value = dtExcelDataTable.Columns[Idx].ColumnName;
            }

            // Data Rows
            for (int Idx = 0; Idx < dtExcelDataTable.Rows.Count; Idx++)
            {
                ws.Range["A2"].Offset[Idx].Resize[1, dtExcelDataTable.Columns.Count].Value = dtExcelDataTable.Rows[Idx].ItemArray;
            }

            excel.Visible = true;
            wb.Activate();
        }
</code>```

Body:
Install Microsoft.Office.Interop.Excel Nuget package in your application. Right-click on your project -> "References" and choose "Manage NuGet Packages...", then just search for Excel. Otherwise, select Tools -> Nuget Package Manager -> Package Manager Console -> then install the Excel nuget (https://www.nuget.org/packages/Microsoft.Office.Interop.Excel/).

Bind the items in DataGrid and then export data to excel as like below,

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application excel = null;
            Microsoft.Office.Interop.Excel.Workbook wb = null;
            object missing = Type.Missing;
            Microsoft.Office.Interop.Excel.Worksheet ws = null;
            Microsoft.Office.Interop.Excel.Range rng = null;

            // collection of DataGrid Items
            var dtExcelDataTable = ExcelTimeReport(txtFrmDte.Text, txtToDte.Text, strCondition);

            excel = new Microsoft.Office.Interop.Excel.Application();
            wb = excel.Workbooks.Add();
            ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;
            ws.Columns.AutoFit();
            ws.Columns.EntireColumn.ColumnWidth = 25;

            // Header row
            for (int Idx = 0; Idx < dtExcelDataTable.Columns.Count; Idx++)
            {
                ws.Range["A1"].Offset[0, Idx].Value = dtExcelDataTable.Columns[Idx].ColumnName;
            }

            // Data Rows
            for (int Idx = 0; Idx < dtExcelDataTable.Rows.Count; Idx++)
            {
                ws.Range["A2"].Offset[Idx].Resize[1, dtExcelDataTable.Columns.Count].Value = dtExcelDataTable.Rows[Idx].ItemArray;
            }

            excel.Visible = true;
            wb.Activate();
        }


问:
numpy slice assign to another value
Suppose I have a 1D numpy array:

```<code> arr = np.arange(10)
</code>```

Then I slice arr and assign to another variable:

```<code> arr2 = arr[5:8]
</code>```

And I want to change arr :

```<code> arr2 *= 10
</code>```

or:

```<code> arr2 = arr2 * 10
</code>```

The results are different. Why are they different?

```<code> arr
</code>```

array([ 0,  1,  2,  3,  4, 50, 60, 70,  8,  9])

```<code> arr
</code>```

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

答:
```<code>In [639]: arr = np.arange(10)
</code>```

By indexing with a slice (basic indexing), arr2 is a view of arr.  It shares the data buffer with arr:

```<code>In [640]: arr2 = arr[5:8]
In [641]: arr2
Out[641]: array([5, 6, 7])
</code>```

If we make a copy, values are copied, not shared:

```<code>In [642]: arr3 = arr[5:8].copy()     # arr[[5,6,7]] is also a copy
</code>```

By modifying arr2 in-place, we also modify part of arr:

```<code>In [643]: arr2 *= 10
In [644]: arr2
Out[644]: array([50, 60, 70])
In [645]: arr
Out[645]: array([ 0,  1,  2,  3,  4, 50, 60, 70,  8,  9])
</code>```

But not arr3:

```<code>In [646]: arr3
Out[646]: array([5, 6, 7])
</code>```

arr2 = arr2*10 does not modify the arr2 array, but rather assigns a whole new array to the arr2 variable.

So you need to understand what it means to assign an object to a variable.  The difference between assign a variable, and modifying a mutable object.  And the difference between array copy and view (and between basic and advanced indexing).  This last one is specific to numpy, the rest to Python as well.

Title: numpy slice assign to another value

Body:
Suppose I have a 1D numpy array:

 arr = np.arange(10)

Then I slice arr and assign to another variable:

 arr2 = arr[5:8]

And I want to change arr :

 arr2 *= 10

or:

 arr2 = arr2 * 10

The results are different. Why are they different?

 arr

array([ 0,  1,  2,  3,  4, 50, 60, 70,  8,  9])

 arr

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Body:
In [639]: arr = np.arange(10)

By indexing with a slice (basic indexing), arr2 is a view of arr.  It shares the data buffer with arr:

In [640]: arr2 = arr[5:8]
In [641]: arr2
Out[641]: array([5, 6, 7])

If we make a copy, values are copied, not shared:

In [642]: arr3 = arr[5:8].copy()     # arr[[5,6,7]] is also a copy

By modifying arr2 in-place, we also modify part of arr:

In [643]: arr2 *= 10
In [644]: arr2
Out[644]: array([50, 60, 70])
In [645]: arr
Out[645]: array([ 0,  1,  2,  3,  4, 50, 60, 70,  8,  9])

But not arr3:

In [646]: arr3
Out[646]: array([5, 6, 7])

arr2 = arr2*10 does not modify the arr2 array, but rather assigns a whole new array to the arr2 variable.

So you need to understand what it means to assign an object to a variable.  The difference between assign a variable, and modifying a mutable object.  And the difference between array copy and view (and between basic and advanced indexing).  This last one is specific to numpy, the rest to Python as well.


答:
I think the problem is, that you say count >= 1, but count >= 3 is also count >=1 so your code never reaches this line. You have to say,
CASE WHEN COUNT() >=1 AND COUNT () < 2...
CASE WHEN COUNT() >=2 AND COUNT () < 3...

Title: How to add a null value in the group_concat if the record does not exist?


问:
How to print stringgrid to Rave report in Delphi
How to print the content of a stringgrid using Rave report in Delphi?</p>

答:
the help provided by Nevrona is very good.

As a general idea:

1) you fill a clientdataset with the data from the string grid.

2) set the rvproject, rvsystem, rvdatasetconnection components

3) create the rave report, create the data view and connect it to the rvdatasetconnection

4) put a region on the report

5) in the region put a databand

6) on the databand put datatext components for each column from the dataview

7) link all the datatext components to the dataview elements

or you can create the report dynamic.

best regards,

 Radu

ContentLicense: CC BY-SA 3.0


问:
What all should an expert C#/.Net/WPF developer know?
I have some 5+ years' background in C++/Unix development. I have been trying my hand at C#/.Net/WPF based software development for some time now. I am at a stage where I can write functioning applications fluently, but am not sure how to take my skills to the next level.

So, my question(s) to you all, especially to those who are experienced in C#/.Net/WPF:

What are the component skills and knowledge that an expert developer on this platform should have?

What technology-specific books would you expect a would-be expert to have read?

What other deliberate steps can I take to become really good at application development using C#/.Net/WPF?

Many thanks in advance! I would be especially grateful for comprehensive answers - I'm pretty sure many other developers have similar questions.

答: I really like WPF in Action and Programming .NET Components is essential reading for any .NET developer. </p>

ContentLicense: CC BY-SA 2.5


问:
JSONObject.toString("variable") claims field is not there even when copy pasted from browser api call
I'm trying to make a program that makes use of an MLB information API located here. I can retrieve all of the information about a player, but can't seem to get the toString() method to pull more specific information from the json response.

Response:

```<code>{"search_player_all":{"copyRight":" Copyright 2019 MLB Advanced Media, L.P.  Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt  ","queryResults":{"totalSize":"1","created":"2019-05-28T12:34:47","row":{"college":"","pro_debut_date":"2012-09-05T00:00:00","birth_city":"Amsterdam","name_display_first_last":"Didi Gregorius","birth_date":"1990-02-18T00:00:00","height_inches":"3","team_id":"147","birth_state":"","name_last":"Gregorius","active_sw":"Y","birth_country":"Netherlands","bats":"L","player_id":"544369","service_years":"","name_display_last_first":"Gregorius, Didi","name_first":"Didi","league":"AL","weight":"205","name_use":"Didi","sport_code":"mlb","throws":"R","high_school":"","team_code":"nya","team_full":"New York Yankees","team_abbrev":"NYY","height_feet":"6","position":"SS","name_display_roster":"Gregorius","position_id":"6"}}}}
</code>```

My code to process json:

```<code>JSONObject responsejson = response.getBody().getObject();
String test = responsejson.getString("copyRight");
</code>```

Note: I am using org.json.JSONObject to process.

I would hope that it would return:

```<code>Copyright 2019 MLB Advanced Media, L.P.  Use of any content on this
page acknowledges agreement to the terms posted here
http://gdx.mlb.com/components/copyright.txt
</code>```

but instead I just get:

```<code>Exception in thread "main" org.json.JSONException: JSONObject["copyRight"] not found.
</code>```

Any help appreciated.

Edit: As others have noted, copyRight isn't a top level entry, however, when I try getString("search_player_all") I get this error:

```<code>Exception in thread "main" org.json.JSONException: JSONObject["search_player_all"] not a string.
</code>```

Solution: I used .getJSONObject() to navigate down to the row level. Thank you for the help

答:
Your top-level object doesn't have a copyRight property, it has a search_player_all property whose value is an object with a copyRight property. You need to get that first:

```<code>JSONObject responsejson = response.getBody().getObject();
JSONObject search_player_all = responsejson.getJSONObject("search_player_all"); // Or maybe .getObject("search_player_all") with the lib you're using...?
String test = search_player_all.getString("copyRight");
</code>```

Body:
I'm trying to make a program that makes use of an MLB information API located here. I can retrieve all of the information about a player, but can't seem to get the toString() method to pull more specific information from the json response.

Response:

{"search_player_all":{"copyRight":" Copyright 2019 MLB Advanced Media, L.P.  Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt  ","queryResults":{"totalSize":"1","created":"2019-05-28T12:34:47","row":{"college":"","pro_debut_date":"2012-09-05T00:00:00","birth_city":"Amsterdam","name_display_first_last":"Didi Gregorius","birth_date":"1990-02-18T00:00:00","height_inches":"3","team_id":"147","birth_state":"","name_last":"Gregorius","active_sw":"Y","birth_country":"Netherlands","bats":"L","player_id":"544369","service_years":"","name_display_last_first":"Gregorius, Didi","name_first":"Didi","league":"AL","weight":"205","name_use":"Didi","sport_code":"mlb","throws":"R","high_school":"","team_code":"nya","team_full":"New York Yankees","team_abbrev":"NYY","height_feet":"6","position":"SS","name_display_roster":"Gregorius","position_id":"6"}}}}

My code to process json:

JSONObject responsejson = response.getBody().getObject();
String test = responsejson.getString("copyRight");

Note: I am using org.json.JSONObject to process.

I would hope that it would return:

Copyright 2019 MLB Advanced Media, L.P.  Use of any content on this
page acknowledges agreement to the terms posted here
http://gdx.mlb.com/components/copyright.txt

but instead I just get:

Exception in thread "main" org.json.JSONException: JSONObject["copyRight"] not found.

Any help appreciated.

Edit: As others have noted, copyRight isn't a top level entry, however, when I try getString("search_player_all") I get this error:

Exception in thread "main" org.json.JSONException: JSONObject["search_player_all"] not a string.

Solution: I used .getJSONObject() to navigate down to the row level. Thank you for the help

Body:
Your top-level object doesn't have a copyRight property, it has a search_player_all property whose value is an object with a copyRight property. You need to get that first:

JSONObject responsejson = response.getBody().getObject();
JSONObject search_player_all = responsejson.getJSONObject("search_player_all"); // Or maybe .getObject("search_player_all") with the lib you're using...?
String test = search_player_all.getString("copyRight");


问:
React-native-camera in Ios not working not appearing
Making a demo for text Recognition with camera using library react-native-camera but camera is not opening

DONE ALL THESE STEPS:

```<code>npm install react-native-camera --save
react-native link react-native-camera
</code>```

Go to node_modules ➜ react-native-camera and add RNCamera.xcodeproj

Expand the RNCamera.xcodeproj ➜ Products folder

In XCode, in the project navigator, select your project. Add libRNCamera.a to your project's Build Phases ➜ Link Binary With
Libraries

Click RNCamera.xcodeproj in the project navigator and go the Build Settings tab. Make sure 'All' is toggled on (instead of
'Basic').

In the Search Paths section, look for Header Search Paths and make sure it contains both $(SRCROOT)/../../react-native/React and
$(SRCROOT)/../../../React - mark both as recursive

```<code>import { RNCamera } from 'react-native-camera';

camerascan(){
 console.log("camscan=====")
 return(

   <RNCamera
   ref={ref => {
     this.camera = ref;
   }}
   defaultTouchToFocus
   mirrorImage={false}
   captureAudio={false}
   style={{
     flex: 1,
     justifyContent: 'space-between',
     alignItems: 'center',
     height: Dimensions.get('window').height,
     width: Dimensions.get('window').width,
   }}

   permissionDialogTitle={'Permission to use camera'}
   permissionDialogMessage={'We need your permission to use your camera phone'}

 >
      <View
           style={{
             height: 56,
             backgroundColor: 'transparent',
             alignSelf: 'flex-end',
           }}
         >
  <TouchableOpacity onPress={this.takePicture.bind(this)}>
     <Text style={styles.capture}> [CAPTURE CARD]</Text>
     </TouchableOpacity>
     </View>
 </RNCamera>

 );

}
   takePicture = async function() {
     console.log("takePicture=====")
     if (this.camera) {
      // const options = { quality: 0.5, base64: true };
       // const data = await this.camera.takePictureAsync(options)
       const data = await this.camera.takePictureAsync();
       console.warn('takePicture ', data);
       // this.detectText(data.base64)
     }
   };
</code>```

No error but camera is not opening.

答:
```<code>Done gave the  runtime permissions for camera

import Permissions from 'react-native-permissions'

 componentDidMount()
 {
    this.determinePermission();
  }
  determinePermission(){
    Permissions.request('camera', { type: 'always' }).then(response => {
      this.setState({ locationPermission: response })

    })

  }
</code>```

Body:
Making a demo for text Recognition with camera using library react-native-camera but camera is not opening

DONE ALL THESE STEPS:

npm install react-native-camera --save
react-native link react-native-camera

Go to node_modules ➜ react-native-camera and add RNCamera.xcodeproj

Expand the RNCamera.xcodeproj ➜ Products folder

In XCode, in the project navigator, select your project. Add libRNCamera.a to your project's Build Phases ➜ Link Binary With
Libraries

Click RNCamera.xcodeproj in the project navigator and go the Build Settings tab. Make sure 'All' is toggled on (instead of
'Basic').

In the Search Paths section, look for Header Search Paths and make sure it contains both $(SRCROOT)/../../react-native/React and
$(SRCROOT)/../../../React - mark both as recursive

import { RNCamera } from 'react-native-camera';

camerascan(){
 console.log("camscan=====")
 return(

   <RNCamera
   ref={ref => {
     this.camera = ref;
   }}
   defaultTouchToFocus
   mirrorImage={false}
   captureAudio={false}
   style={{
     flex: 1,
     justifyContent: 'space-between',
     alignItems: 'center',
     height: Dimensions.get('window').height,
     width: Dimensions.get('window').width,
   }}

   permissionDialogTitle={'Permission to use camera'}
   permissionDialogMessage={'We need your permission to use your camera phone'}

 >
      <View
           style={{
             height: 56,
             backgroundColor: 'transparent',
             alignSelf: 'flex-end',
           }}
         >
  <TouchableOpacity onPress={this.takePicture.bind(this)}>
     <Text style={styles.capture}> [CAPTURE CARD]</Text>
     </TouchableOpacity>
     </View>
 </RNCamera>

 );

}
   takePicture = async function() {
     console.log("takePicture=====")
     if (this.camera) {
      // const options = { quality: 0.5, base64: true };
       // const data = await this.camera.takePictureAsync(options)
       const data = await this.camera.takePictureAsync();
       console.warn('takePicture ', data);
       // this.detectText(data.base64)
     }
   };

No error but camera is not opening.


问:
ProxyPass with apache to work with node js, framework adonis.js
I have 4 projects developed in laravel in Apache, now I finish a development in node.js with frmework adonis.js, I want to host that app in Apache as well, since all domain requests enter through port 80 or 443 with ssl, the case is that it creates directories to enter the applications

```<code><VirtualHost *:80>
DocumentRoot /var/www/html
ServerName localhost

Alias /app1 /var/www/html/app1/public
Alias /app2 /var/www/html/app2/public
Alias /app3 /var/www/html/app3/public

<Directory /var/www/html/app1/public/>
    Order deny,allow
    Allow from all
    Options FollowSymLinks
</Directory>

<Directory /var/www/html/app2/public/>
    AllowOverride All
    Require all granted
    Options FollowSymLinks
</Directory>

<Directory /var/www/html/app3/public/>
    AllowOverride All
    Require all granted
    Options FollowSymLinks
</Directory>
</code>```

the three directories work fine, but those are the 3 project directories in laravel, what should I do to create a 4 directory with the node application js - adonis.js that listens for http: // localhost: 3333 /

答:
You don't need directory for nodejs app. Just start it on any port (I suggest running your app with process manager like pm2) and add proxypass to site config. In your case for port 3333 just add this:

```<code>ProxyPass / http://localhost:3333/
ProxyPassReverse / http://localhost:3333/
</code>```

Of course mod_proxy must be enabled in your apache config.

Body:
I have 4 projects developed in laravel in Apache, now I finish a development in node.js with frmework adonis.js, I want to host that app in Apache as well, since all domain requests enter through port 80 or 443 with ssl, the case is that it creates directories to enter the applications

<VirtualHost *:80>
DocumentRoot /var/www/html
ServerName localhost

Alias /app1 /var/www/html/app1/public
Alias /app2 /var/www/html/app2/public
Alias /app3 /var/www/html/app3/public

<Directory /var/www/html/app1/public/>
    Order deny,allow
    Allow from all
    Options FollowSymLinks
</Directory>

<Directory /var/www/html/app2/public/>
    AllowOverride All
    Require all granted
    Options FollowSymLinks
</Directory>

<Directory /var/www/html/app3/public/>
    AllowOverride All
    Require all granted
    Options FollowSymLinks
</Directory>

the three directories work fine, but those are the 3 project directories in laravel, what should I do to create a 4 directory with the node application js - adonis.js that listens for http: // localhost: 3333 /

Body:
You don't need directory for nodejs app. Just start it on any port (I suggest running your app with process manager like pm2) and add proxypass to site config. In your case for port 3333 just add this:

ProxyPass / http://localhost:3333/
ProxyPassReverse / http://localhost:3333/

Of course mod_proxy must be enabled in your apache config.


问:
Download old version of package with NuGet
Is there a way to download a previous version of a package with NuGet, not the latest one?

答:
Bring up the Package Manager Console in Visual Studio - it's in Tools / NuGet Package Manager / Package Manager Console. Then run the Install-Package command:

```<code>Install-Package Common.Logging -Version 1.2.0
</code>```

See the command reference for details.

Edit:
In order to list versions of a package you can use the Get-Package command with the remote argument and a filter:

```<code>Get-Package -ListAvailable -Filter Common.Logging -AllVersions
</code>```

By pressing tab after the version option in the Install-Package command, you get a list of the latest available versions.

Body:
Bring up the Package Manager Console in Visual Studio - it's in Tools / NuGet Package Manager / Package Manager Console. Then run the Install-Package command:

Install-Package Common.Logging -Version 1.2.0

See the command reference for details.

Edit:
In order to list versions of a package you can use the Get-Package command with the remote argument and a filter:

Get-Package -ListAvailable -Filter Common.Logging -AllVersions

By pressing tab after the version option in the Install-Package command, you get a list of the latest available versions.


问:
How to use Microsoft SEAL library for homomorphic encryption?
I want to use Microsoft SEAL library for homomorphic encryption in a university project. I have no prior experience on Visual Studio 2017 (15.9). After cloning SEAL from github, I opened the solution file and tried to build the projects. But it shows about 1954 errors. The first errors are -

E1696 cannot open source file "stddef.h"  SEALExamples    E:\Visual Studio Enterprise 2017\VC\Tools\MSVC\14.16.27023\include\atomic   15

E1696 cannot open source file "stdlib.h"  SEALExamples    E:\Visual Studio Enterprise 2017\VC\Tools\MSVC\14.16.27023\include\atomic   17

There are many other errors like this for "errno.h", "float.h", "time.h" etc.
I think if I solved this errors, other errors will be gone. When I open an empty project, "stdlib.h" has no issue to be used.
So, am I doing something wrong? How can this be solved?

答: Apparently it needed a specific version of windows SDK (10.0.16299). After installing it and selecting release mode instead of debug, everything worked.</p>


问:
withContext() in Jenkins pipeline script is hiding console output
I have this jenkins pipeline script (you should be able to just paste it directly into a blank pipeline build)

```<code>import hudson.console.LineTransformationOutputStream
import hudson.console.ConsoleLogFilter
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets

class MyConsoleLogFilter extends ConsoleLogFilter {

    OutputStream decorateLogger(AbstractBuild build, OutputStream logger)
            throws IOException, InterruptedException {
        return new MyOutputStream(logger, StandardCharsets.UTF_8)
    }
}

class MyOutputStream extends LineTransformationOutputStream {
    def logger
    def charset

    MyOutputStream(OutputStream logger, Charset charset) {
        this.logger = logger
        this.charset = charset
    }

    void close() throws IOException {
        super.close();
        logger.close();
    }

    void eol(byte[] bytes, int len) throws IOException {
        String line = charset.decode(ByteBuffer.wrap(bytes, 0, len)).toString();
        logger.write("xxx ".getBytes(charset))
        logger.write(line.getBytes(charset));
    }
}

node {
    withContext(new MyConsoleLogFilter()) {
        echo 'Hello World'
    }
    echo 'Hello World'
}
</code>```

I expect to see the first Hello World prefixed by xxx, because of the wrapping by MyConsoleLogFilter.

But all I see is greyed out console output as follows:

```<code>Started by user Admin
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/mike-learning
[Pipeline] {
[Pipeline] withContext
[Pipeline] {
[Pipeline] echo
[Pipeline] }
[Pipeline] // withContext
[Pipeline] echo
Hello World
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
</code>```

Why is the console output from within the withContext() block being hidden?

答:
An alternative is to implement this with a Java plugin, you don't need the NonCPS annotation but to implement the Serializable interface:</p>

```<code>@Extension
public class MyConsoleLogFilter extends ConsoleLogFilter implements Serializable {
    private static final long serialVersionUID = 1;

    @Override
    public OutputStream decorateLogger(Run build, final OutputStream logger) {
        return new MyOutputStream(logger, StandardCharsets.UTF_8);
    }

    private class MyOutputStream extends LineTransformationOutputStream {
        private OutputStream logger;
        private Charset charset;

        MyOutputStream(OutputStream logger, Charset charset) {
            this.logger = logger;
            this.charset = charset;
        }

        public void close() throws IOException {
            super.close();
            logger.close();
        }

        public void eol(byte[] bytes, int len) throws IOException {
            String line = charset.decode(java.nio.ByteBuffer.wrap(bytes, 0, len)).toString();
            logger.write("xxx ".getBytes(charset));
            logger.write(line.getBytes(charset));
        }
    }

}
</code>```

Body:
I have this jenkins pipeline script (you should be able to just paste it directly into a blank pipeline build)

import hudson.console.LineTransformationOutputStream
import hudson.console.ConsoleLogFilter
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets

class MyConsoleLogFilter extends ConsoleLogFilter {

    OutputStream decorateLogger(AbstractBuild build, OutputStream logger)
            throws IOException, InterruptedException {
        return new MyOutputStream(logger, StandardCharsets.UTF_8)
    }
}

class MyOutputStream extends LineTransformationOutputStream {
    def logger
    def charset

    MyOutputStream(OutputStream logger, Charset charset) {
        this.logger = logger
        this.charset = charset
    }

    void close() throws IOException {
        super.close();
        logger.close();
    }

    void eol(byte[] bytes, int len) throws IOException {
        String line = charset.decode(ByteBuffer.wrap(bytes, 0, len)).toString();
        logger.write("xxx ".getBytes(charset))
        logger.write(line.getBytes(charset));
    }
}

node {
    withContext(new MyConsoleLogFilter()) {
        echo 'Hello World'
    }
    echo 'Hello World'
}

I expect to see the first Hello World prefixed by xxx, because of the wrapping by MyConsoleLogFilter.

But all I see is greyed out console output as follows:

Started by user Admin
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/mike-learning
[Pipeline] {
[Pipeline] withContext
[Pipeline] {
[Pipeline] echo
[Pipeline] }
[Pipeline] // withContext
[Pipeline] echo
Hello World
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

Why is the console output from within the withContext() block being hidden?

Body:
An alternative is to implement this with a Java plugin, you don't need the NonCPS annotation but to implement the Serializable interface:

@Extension
public class MyConsoleLogFilter extends ConsoleLogFilter implements Serializable {
    private static final long serialVersionUID = 1;

    @Override
    public OutputStream decorateLogger(Run build, final OutputStream logger) {
        return new MyOutputStream(logger, StandardCharsets.UTF_8);
    }

    private class MyOutputStream extends LineTransformationOutputStream {
        private OutputStream logger;
        private Charset charset;

        MyOutputStream(OutputStream logger, Charset charset) {
            this.logger = logger;
            this.charset = charset;
        }

        public void close() throws IOException {
            super.close();
            logger.close();
        }

        public void eol(byte[] bytes, int len) throws IOException {
            String line = charset.decode(java.nio.ByteBuffer.wrap(bytes, 0, len)).toString();
            logger.write("xxx ".getBytes(charset));
            logger.write(line.getBytes(charset));
        }
    }

}


问:
add value in IndexedDB using Angular 7
Firstly, I tried all the questions & answers related to this topic. Additionally and I tried related questions and try to solve it but no success. So please read my question thoroughly.

Prefer Links

ngx-indexed-db

Search related to Links

Getting error while adding value to indexedDB using angular2

I want to add data in indexeddb but somehow database connection open error is display. I have attached a screenshot.so I request put on answer one small example add value in indexeddb.

My code

app.components.js

```<code>import { Component, OnInit } from '@angular/core';
import { NgxIndexedDB } from 'ngx-indexed-db';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'indexDb-Angular';

  ngOnInit() {
    let  db = new NgxIndexedDB('DVdb', 1);
    db.openDatabase(1, evt => {
      let objectStore = evt.currentTarget.result.createObjectStore('people', { keyPath: 'id', autoIncrement: true });

      objectStore.createIndex('name', 'name', { unique: false });
      objectStore.createIndex('email', 'email', { unique: true });

    });

    db.add('people', { name: 'Sumit', email: 'Sumit@test.com' }).then(
      () => {
          // Do something after the value was added
      },
      error => {
          console.log(error);
      }
  );
  }

}
</code>```

答:
Make openDatabase() an async method so that it waits for database to open up before adding a value. You can make it async by using .then(function() {

```<code>ngOnInit() {
    let  db = new NgxIndexedDB('DVdb', 1);
    db.openDatabase(1, evt => {
      let objectStore = evt.currentTarget.result.createObjectStore('people', { keyPath: 'id', autoIncrement: true });

      objectStore.createIndex('name', 'name', { unique: false });
      objectStore.createIndex('email', 'email', { unique: true });

    }).then(function () {
        db.add('people', { name: 'Sumit', email: 'Sumit@test.com' }).then(
          () => {
              // Do something after the value was added
          },
          error => {
              console.log(error);
          }
        );
    });
}
</code>```

Title: add value in IndexedDB using Angular 7

Body:
Firstly, I tried all the questions & answers related to this topic. Additionally and I tried related questions and try to solve it but no success. So please read my question thoroughly.

Prefer Links

ngx-indexed-db

Search related to Links

Getting error while adding value to indexedDB using angular2

I want to add data in indexeddb but somehow database connection open error is display. I have attached a screenshot.so I request put on answer one small example add value in indexeddb.

My code

app.components.js

import { Component, OnInit } from '@angular/core';
import { NgxIndexedDB } from 'ngx-indexed-db';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'indexDb-Angular';

  ngOnInit() {
    let  db = new NgxIndexedDB('DVdb', 1);
    db.openDatabase(1, evt => {
      let objectStore = evt.currentTarget.result.createObjectStore('people', { keyPath: 'id', autoIncrement: true });

      objectStore.createIndex('name', 'name', { unique: false });
      objectStore.createIndex('email', 'email', { unique: true });

    });

    db.add('people', { name: 'Sumit', email: 'Sumit@test.com' }).then(
      () => {
          // Do something after the value was added
      },
      error => {
          console.log(error);
      }
  );
  }

}

Body:
Make openDatabase() an async method so that it waits for database to open up before adding a value. You can make it async by using .then(function() {

ngOnInit() {
    let  db = new NgxIndexedDB('DVdb', 1);
    db.openDatabase(1, evt => {
      let objectStore = evt.currentTarget.result.createObjectStore('people', { keyPath: 'id', autoIncrement: true });

      objectStore.createIndex('name', 'name', { unique: false });
      objectStore.createIndex('email', 'email', { unique: true });

    }).then(function () {
        db.add('people', { name: 'Sumit', email: 'Sumit@test.com' }).then(
          () => {
              // Do something after the value was added
          },
          error => {
              console.log(error);
          }
        );
    });
}


问:
PHP Warning: Module 'imagick' already loaded in Unknown on line 0
I have a simple test file where the only php codes are:

```<code>if (isset($_REQUEST['back']) && ($back != '')) { $back = $_REQUEST['back']; }
$filename = 'images/'.$back.'.jpg';
$file = (file_exists($filename)) ? $back : 'back1';
</code>```

Now each time I run the file, I get this line added PHP Warning:  Module 'imagick' already loaded in Unknown on line 0 in my error log. Any suggestion please ?

答:
open your php.ini file and comment this

```<code>;extension=imagick.so
</code>```

this resolved my problem

Body:
I have a simple test file where the only php codes are:

if (isset($_REQUEST['back']) && ($back != '')) { $back = $_REQUEST['back']; }
$filename = 'images/'.$back.'.jpg';
$file = (file_exists($filename)) ? $back : 'back1';

Now each time I run the file, I get this line added PHP Warning:  Module 'imagick' already loaded in Unknown on line 0 in my error log. Any suggestion please ?

Body:
open your php.ini file and comment this

;extension=imagick.so

this resolved my problem


问:
How to write a http REST service asynchronously
What is the recommended way in vert.x to write an Asynchronous request handler?

In this service, a request processing typically involves calling DB, calling external services, etc. I do not want to block the request handling thread however. What is the recommended way to achieve this using vet.x? In a typical asynchronous processing chain, I would use the request handling thread to emit a message to the message bus with the request object. Another handler will pick this message and do some processing such as checking request params. This handler can then emit a new message to the bus which can be picked up by the next handler which will do a remote call. This handler emits a new message with the result of the call which can be picked up by the next handler which will do error checking etc. Next handler would be responsible for creating the response and sending it to the client.

How one can create a similar pipeline using vert.x?

答:
Everything, comprising request handlers for HttpServer, is asynchronous, isn't it?

```<code>var server = vertx.createHttpServer(HttpServerOptions())
server.requestHandler { req ->
    req.setExpectMultipart(true) // for handling forms
    var totalBuffer = Buffer.buffer()
    req.handler { buff -> b.appendBuffer(buff) }
        .endHandler { // the body has now been fully read
            var formAttributes = request.formAttributes()
            req.response().putHeader("Content-type","text/html");
            req.response().end("Hello HTTP!");
        }
    // the above is so common that Vertx provides: bodyHandler{totalbuff->..}
}.listen(8080, "127.0.0.1", { res -> if(res.succeeded()) ... });
</code>```

You just need to (end) write on req.response() on your final handler of your pipeline.

For a more stream-like implementation (i.e., not callback-based), you may use Vert.x Rx/ReactiveStreams API. E.g., you may use Vert.x Web Client for making requests, possibly using its Rx-fied API.

Body:
Everything, comprising request handlers for HttpServer, is asynchronous, isn't it?

var server = vertx.createHttpServer(HttpServerOptions())
server.requestHandler { req ->
    req.setExpectMultipart(true) // for handling forms
    var totalBuffer = Buffer.buffer()
    req.handler { buff -> b.appendBuffer(buff) }
        .endHandler { // the body has now been fully read
            var formAttributes = request.formAttributes()
            req.response().putHeader("Content-type","text/html");
            req.response().end("Hello HTTP!");
        }
    // the above is so common that Vertx provides: bodyHandler{totalbuff->..}
}.listen(8080, "127.0.0.1", { res -> if(res.succeeded()) ... });

You just need to (end) write on req.response() on your final handler of your pipeline.

For a more stream-like implementation (i.e., not callback-based), you may use Vert.x Rx/ReactiveStreams API. E.g., you may use Vert.x Web Client for making requests, possibly using its Rx-fied API.


问:
How to use DbModelBuilder with Database First Approach to implement Soft Delete
I'm trying to implement a soft delete in our EF 6 project. We are using the database first approach and I noticed that you cannot override OnModelCreating.

When using the Code-First approach it's possible to apply a global filter for a particular entity as described in this blog post.

How can I recreate this using the Database First approach?

```<code>public class MyContext : DbContext
{
    public virtual IDbSet<Company> Companies { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>()
            .Map(m => m.Requires("IsDeleted").HasValue(false))
            .Ignore(m => m.IsDeleted);
    }
}
</code>```

答:
```<code>public class MyContext : DbContext
{
    public virtual IDbSet<Company> Companies { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>()
            .Map(m => m.Requires("IsDeleted").HasValue(false))
            .Ignore(m => m.IsDeleted);

        base.OnModelCreating(modelBuilder);
    }
}
</code>```

You need to write the base.OnModelCreating(modelBuilder); build you query & i have also highlighted line in the post.

Body:
I'm trying to implement a soft delete in our EF 6 project. We are using the database first approach and I noticed that you cannot override OnModelCreating.

When using the Code-First approach it's possible to apply a global filter for a particular entity as described in this blog post.

How can I recreate this using the Database First approach?

public class MyContext : DbContext
{
    public virtual IDbSet<Company> Companies { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>()
            .Map(m => m.Requires("IsDeleted").HasValue(false))
            .Ignore(m => m.IsDeleted);
    }
}

Body:
public class MyContext : DbContext
{
    public virtual IDbSet<Company> Companies { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>()
            .Map(m => m.Requires("IsDeleted").HasValue(false))
            .Ignore(m => m.IsDeleted);

        base.OnModelCreating(modelBuilder);
    }
}

You need to write the base.OnModelCreating(modelBuilder); build you query & i have also highlighted line in the post.


问:
Mocking base interface properties does not work through a mock of a derived interface
I have these interfaces:

public interface IBase
{
    int Value { get; }
}

public interface IDerived : IBase
{
    new int Value { get; set; }
}
```

<p>The following test works correctly:</p>

```var mock = new Mock<IDerived>( MockBehavior.Strict );
mock.SetupGet( m => m.Value ).Returns( 0 );

IDerived o = mock.Object;

Assert.That( o.Value, Is.EqualTo( 0 ) );
```

<p>However, when I change the type of <code>o</code> to <code>IBase</code>, I get the following error:</p>

```Message: Moq.MockException : IBase.Value invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup.
```

Is that by design? Do I need to remove the Strict flag in order to access the base interface property (which is hidden by the derived interface)? Or is there some other kind of setup which I could use?

As a side note, there was an issue dealing with the base/derived read-only/read-write properties but the declared type of the mock object was not considered there. Could this be another issue in Moq?

答:
The Value property of IBase interface and IDerived interface are not the same. For example you can do this:

```<code>public interface IBase
{
    string Value { get; }
}

public interface IDerived : IBase
{
    new string Value { get; }
}

public class Implementation : IDerived
{
    string IBase.Value { get; } = "Base";

    string IDerived.Value { get; } = "Derived";
}
</code>```

To mock the IDerived interface correctly, you should setup return value for both properties. Mock.As method is useful here to cast IDerived interface to IBase.

```<code>Mock<IDerived> mock = new Mock<IDerived>( MockBehavior.Strict );
mock.Setup( obj => obj.Value ).Returns( "Derived" );
mock.As<IBase>().Setup( obj => obj.Value ).Returns( "Base" );
</code>```

Body:
I have these interfaces:

public interface IBase
{
    int Value { get; }
}

public interface IDerived : IBase
{
    new int Value { get; set; }
}

The following test works correctly:

var mock = new Mock<IDerived>( MockBehavior.Strict );
mock.SetupGet( m => m.Value ).Returns( 0 );

IDerived o = mock.Object;

Assert.That( o.Value, Is.EqualTo( 0 ) );

However, when I change the type of o to IBase, I get the following error:

Message: Moq.MockException : IBase.Value invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup.

Is that by design? Do I need to remove the Strict flag in order to access the base interface property (which is hidden by the derived interface)? Or is there some other kind of setup which I could use?

As a side note, there was an issue dealing with the base/derived read-only/read-write properties but the declared type of the mock object was not considered there. Could this be another issue in Moq?

Body:
The Value property of IBase interface and IDerived interface are not the same. For example you can do this:

public interface IBase
{
    string Value { get; }
}

public interface IDerived : IBase
{
    new string Value { get; }
}

public class Implementation : IDerived
{
    string IBase.Value { get; } = "Base";

    string IDerived.Value { get; } = "Derived";
}

To mock the IDerived interface correctly, you should setup return value for both properties. Mock.As method is useful here to cast IDerived interface to IBase.

Mock<IDerived> mock = new Mock<IDerived>( MockBehavior.Strict );
mock.Setup( obj => obj.Value ).Returns( "Derived" );
mock.As<IBase>().Setup( obj => obj.Value ).Returns( "Base" );


问:
Drop down selector with selenium and python
I'm trying to select a value from drop down list. I have checked all posts related to it but not able to find solution.

Here is my HTML code for drop down list:

```<code><select class="paginado-select" onchange="javascript:paginadoListado(1);" name="registros_pagina">
<option></option>
<option>25</option>
<option selected="">50</option>
<option>75</option>
<option>100</option>
<option>125</option>
<option>150</option>
<option>175</option>
<option>200</option>
<option>225</option>
<option>250</option>
</select>
</code>```

I've tried with this code but it doesn't set anything in the variable select.

```<code># third-party imports
from selenium import webdriver

driver = webdriver.Chrome("C:/Users/PycharmProjects/Tennis-Ranking/chromedriver.exe")
driver.get("http://www.rfet.es/clubes/prov/Madrid/28.html")
select = driver.find_element_by_xpath('//*[@id="paginacion-busqueda-abajo"]/form/table/tbody/tr/td[2]/select').click()
print(select)
select.selectByVisibleText('250');

driver.close()
</code>```

I would like to select the option 250 to show all the clubs in one page avoding to move to all pages of the table in order to use beautifulsoap to catch the html code.

答:
Try this:

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time

driver = webdriver.Chrome('C:/Users/PycharmProjects/Tennis-Ranking/chromedriver.exe')
driver.get('http://www.rfet.es/clubes/prov/Madrid/28.html')
time.sleep(1)

selectPageNo = Select(driver.find_element_by_class_name("paginado-select"))
selectPageNo.select_by_visible_text('250')
</code>```

See also:

What is the correct way to select an using Selenium's Python WebDriver?

Body:
I'm trying to select a value from drop down list. I have checked all posts related to it but not able to find solution.

Here is my HTML code for drop down list:

<select class="paginado-select" onchange="javascript:paginadoListado(1);" name="registros_pagina">
<option></option>
<option>25</option>
<option selected="">50</option>
<option>75</option>
<option>100</option>
<option>125</option>
<option>150</option>
<option>175</option>
<option>200</option>
<option>225</option>
<option>250</option>
</select>

I've tried with this code but it doesn't set anything in the variable select.

# third-party imports
from selenium import webdriver

driver = webdriver.Chrome("C:/Users/PycharmProjects/Tennis-Ranking/chromedriver.exe")
driver.get("http://www.rfet.es/clubes/prov/Madrid/28.html")
select = driver.find_element_by_xpath('//*[@id="paginacion-busqueda-abajo"]/form/table/tbody/tr/td[2]/select').click()
print(select)
select.selectByVisibleText('250');

driver.close()

I would like to select the option 250 to show all the clubs in one page avoding to move to all pages of the table in order to use beautifulsoap to catch the html code.

Body:
Try this:

from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time

driver = webdriver.Chrome('C:/Users/PycharmProjects/Tennis-Ranking/chromedriver.exe')
driver.get('http://www.rfet.es/clubes/prov/Madrid/28.html')
time.sleep(1)

selectPageNo = Select(driver.find_element_by_class_name("paginado-select"))
selectPageNo.select_by_visible_text('250')

See also:

What is the correct way to select an using Selenium's Python WebDriver?


问:
How to apply "to_f" to a column for all results in an active record query inside rails console
I have this query:
p = Payment.where(:client_id => 1)

Then only some fields, so I execute this:
p.select(:id, :created_at, :amount)

The issue is that every amount in the result comes as BigDecimal, and it's not readable. I need to apply to_f function inside rails console to have a readable set of results.

I tried map,like this:
p.map {|p| p.amount.to_f}
But it returns to me an array only with the amounts, and I need it to be along with the other attributes.

答:
To solve you problem and get all fields:

```<code>p.map { |i| [i.id, i.created_at, i.amount.to_f] }
</code>```

Also you can take a look on this article. Maybe you just need float type for amount field in your DB

Body:
To solve you problem and get all fields:

p.map { |i| [i.id, i.created_at, i.amount.to_f] }

Also you can take a look on this article. Maybe you just need float type for amount field in your DB


问:
How to transform key to value and value to key in json using jolt spec?
I need to transform (multiple) keys to value and values to keys in JSON using jolt spec. What should be the right spec to do it?

Input :

```<code>{
  "k1": "v1",
  "k2": "v2"
}
</code>```

Required Output :

```<code>{
  "v1": "k1",
  "v2": "k2"
}
</code>```

答:
This should reverse key with value:  </p>

```<code>[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "$": "@(0)"
      }
    }
  }
]
</code>```

Body:
I need to transform (multiple) keys to value and values to keys in JSON using jolt spec. What should be the right spec to do it?

Input :

{
  "k1": "v1",
  "k2": "v2"
}

Required Output :

{
  "v1": "k1",
  "v2": "k2"
}

Body:
This should reverse key with value:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "$": "@(0)"
      }
    }
  }
]


问:
Docker - CTRL+P CTRL+Q
I'm using Docker on windows 10 Home, so docker uses the virtual machine box.

When I run the container below and want to leave the commnand CTRL + P CTRL + Q does not work.

docker run -i -t ubuntu /bin/bash

答:
it had work.
first ctrl+P+Q, perhaps you feel no work,
then ctrl+c,
last docker ps,
you will see result.

Title: Docker - CTRL+P CTRL+Q


问:
Uncaught TypeError: Cannot read property 'init' of undefined in Javascript while submitting form
I'm trying to make a social networking mini web app using python web.py module.
I made a registration form in html, but when I fill the details and submit them, the browser console shows the following output:

```<code>Uncaught TypeError: $(...).ready(...) is not a function
at scripty.js:22
loaded
jquery-3.4.1.min.js:2 Uncaught TypeError: Cannot read property 'init' of undefined
at HTMLDocument.<anonymous> (scripty.js:4)
at e (jquery-3.4.1.min.js:2)
at t (jquery-3.4.1.min.js:2)
</code>```

I've searched for similar problems but their solutions doesn't seem to work for this case.

Here is my "scripty.js" file code

```<code>$(document).ready(function () {
    console.log("loaded");

    $.material.init();

    $(document).on("submit", "#register-form", function (e) {
        e.preventDefault();
        console.log("form submitted");

        let form = $('#register-form').serialize(); //get the form data

        //send an ajax request over to the route /postregisteration
        $.ajax({
            url: '/postregisteration',
            type: 'POST',
            data: form,
            success: function (response) {
                console.log(response);
            }
        });
    });
})();

</code>```

And here is the controller.py file code in python

```<code>import web
from Models import RegisterModel

urls = (
    '/', 'Home',
    '/register', 'Register',
    '/postregistration', 'PostRegistration'
)

render =  web.template.render("Views/Templates", base="MainLayout")

app = web.application(urls, globals())

# Classes/Routes
# Each class will be controlling a route

class Home:
    def GET(self):
        return render.Home()

class Register:
    def GET(self):
        return render.Register()

class PostRegistration:
    def POST(self):
        data = web.input()
        print(data.username)

        reg_model = RegisterModel.RegisterModel.insert_user(data)
        return data.username

if __name__=="__main__":
    app.run()
</code>```

After clicking submit, it just prints
"loaded" and shows the error on browser console.

But it must also show
"form submitted".

Any help would be appreciable.

答:
Change the last line of the JS you've shown:

From

```<code>})();
</code>```

to

```<code>});
</code>```

That fixes your first error ... is not a function.

For the second error, that means $.material is undefined. Either remove it (if you're not using material design) or make sure the corresponding plugin is available.

Body:
I'm trying to make a social networking mini web app using python web.py module.
I made a registration form in html, but when I fill the details and submit them, the browser console shows the following output:

Uncaught TypeError: $(...).ready(...) is not a function
at scripty.js:22
loaded
jquery-3.4.1.min.js:2 Uncaught TypeError: Cannot read property 'init' of undefined
at HTMLDocument.<anonymous> (scripty.js:4)
at e (jquery-3.4.1.min.js:2)
at t (jquery-3.4.1.min.js:2)

I've searched for similar problems but their solutions doesn't seem to work for this case.

Here is my "scripty.js" file code

$(document).ready(function () {
    console.log("loaded");

    $.material.init();

    $(document).on("submit", "#register-form", function (e) {
        e.preventDefault();
        console.log("form submitted");

        let form = $('#register-form').serialize(); //get the form data

        //send an ajax request over to the route /postregisteration
        $.ajax({
            url: '/postregisteration',
            type: 'POST',
            data: form,
            success: function (response) {
                console.log(response);
            }
        });
    });
})();

And here is the controller.py file code in python

import web
from Models import RegisterModel

urls = (
    '/', 'Home',
    '/register', 'Register',
    '/postregistration', 'PostRegistration'
)

render =  web.template.render("Views/Templates", base="MainLayout")

app = web.application(urls, globals())

# Classes/Routes
# Each class will be controlling a route

class Home:
    def GET(self):
        return render.Home()

class Register:
    def GET(self):
        return render.Register()

class PostRegistration:
    def POST(self):
        data = web.input()
        print(data.username)

        reg_model = RegisterModel.RegisterModel.insert_user(data)
        return data.username

if __name__=="__main__":
    app.run()

After clicking submit, it just prints
"loaded" and shows the error on browser console.

But it must also show
"form submitted".

Any help would be appreciable.

Body:
Change the last line of the JS you've shown:

From

})();

to

});

That fixes your first error ... is not a function.

For the second error, that means $.material is undefined. Either remove it (if you're not using material design) or make sure the corresponding plugin is available.


问:
Unit Test multi target frameworks: Test all frameworks
I create a MS Test Unit test project with these targets

<TargetFrameworks>netcoreapp2.2;net472</TargetFrameworks>
```

<p>If I use this code in one my tests:</p>

<pre class="lang-cs prettyprint-override"><code>#if NET472
            Assert.Fail();
#endif
</code>```

and then run the test, it will be successful. It means the tests are executed with netcoreapp target framework.

I want to do tests in both frameworks. How can I do that with a SINGLE test project?

答: I found that if using command line dotnet test it will run tests for each framework separately.

Body:
I create a MS Test Unit test project with these targets

<TargetFrameworks>netcoreapp2.2;net472</TargetFrameworks>

If I use this code in one my tests:

#if NET472
            Assert.Fail();
#endif

and then run the test, it will be successful. It means the tests are executed with netcoreapp target framework.

I want to do tests in both frameworks. How can I do that with a SINGLE test project?


问:
Returning 404 Error ASP.NET MVC 3
I have tried the following 2 things to have a page return a 404 error:

```<code>public ActionResult Index()
{
    return new HttpStatusCodeResult(404);
}

public ActionResult NotFound()
{
    return HttpNotFound();
}
</code>```

but both of them just render a blank page.  How can I manually return a 404 error from within ASP.NET MVC 3?

答: throw new HttpException(404, "NotFound"); along with a custom error handler works fine for me.

Title: Returning 404 Error ASP.NET MVC 3

Body:
I have tried the following 2 things to have a page return a 404 error:

public ActionResult Index()
{
    return new HttpStatusCodeResult(404);
}

public ActionResult NotFound()
{
    return HttpNotFound();
}

but both of them just render a blank page.  How can I manually return a 404 error from within ASP.NET MVC 3?