问:
Working with generated classes and Jackson to read stream of JSON data to objects
I have generated classes from a Swagger definition. There are 4 different classes with one field in common op (there is no class hierarchy, the field is replicated in each class).

I want to deserialise a stream of JSON data into one of the 4 different classes depending on the value of the op field.

For example:

```<code>{"op": "typeA", ...} -> generates TypeA
{"op": "typeB", ...} -> generates TypeB
</code>```

I want to use Jackson for this. The problem Im having is that all examples I find assumes that you are able to modify the original classes so that you can make a class hierarchy to solve the problem. However my question is how can I solve this without having to modify the original classes?

The original example assumes a hierarchy and is done like this:

```<code>@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "op",
        visible = true)
@JsonSubTypes({
        @JsonSubTypes.Type(value = ConnectionMessage.class, name = "connection"),
        @JsonSubTypes.Type(value = StatusMessage.class, name = "status"),
        @JsonSubTypes.Type(value = MarketChangeMessage.class, name = "mcm"),
        @JsonSubTypes.Type(value = OrderChangeMessage.class, name = "ocm"),
})
public interface MixInResponseMessage {

}
</code>```

答:
This can be done with a custom deserializer with a switch - case statement to parse the correct type according to the value of "op" field:

```<code>class OpDeserializer extends JsonDeserializer {
    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        final JsonNode node = jsonParser.readValueAsTree();
        final String op = node.get("op").asText();
        switch (op) {
            case "typeA": return mapper.treeToValue(node, TypeA.class);
            case "typeB": return mapper.treeToValue(node, TypeB.class);
            default: return mapper.treeToValue(node, Object.class);
        }
    }
}
</code>```

Note how an ObjectMapper field is used to convert a TreeNode to an object of required type.

This doesn't require TypeA, TypeB etc to have any other common parent except Object.

It'll be necessary to specify this deserializer as used for each JSON element with an "op" field. I tested by parsing this class:

```<code>class Ops {
    @JsonDeserialize(contentUsing = OpDeserializer.class)
    Object[] ops;
}
</code>```

Body:
I have generated classes from a Swagger definition. There are 4 different classes with one field in common op (there is no class hierarchy, the field is replicated in each class).

I want to deserialise a stream of JSON data into one of the 4 different classes depending on the value of the op field.

For example:

{"op": "typeA", ...} -> generates TypeA
{"op": "typeB", ...} -> generates TypeB

I want to use Jackson for this. The problem Im having is that all examples I find assumes that you are able to modify the original classes so that you can make a class hierarchy to solve the problem. However my question is how can I solve this without having to modify the original classes?

The original example assumes a hierarchy and is done like this:

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "op",
        visible = true)
@JsonSubTypes({
        @JsonSubTypes.Type(value = ConnectionMessage.class, name = "connection"),
        @JsonSubTypes.Type(value = StatusMessage.class, name = "status"),
        @JsonSubTypes.Type(value = MarketChangeMessage.class, name = "mcm"),
        @JsonSubTypes.Type(value = OrderChangeMessage.class, name = "ocm"),
})
public interface MixInResponseMessage {

}

Body:
This can be done with a custom deserializer with a switch - case statement to parse the correct type according to the value of "op" field:

class OpDeserializer extends JsonDeserializer {
    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        final JsonNode node = jsonParser.readValueAsTree();
        final String op = node.get("op").asText();
        switch (op) {
            case "typeA": return mapper.treeToValue(node, TypeA.class);
            case "typeB": return mapper.treeToValue(node, TypeB.class);
            default: return mapper.treeToValue(node, Object.class);
        }
    }
}

Note how an ObjectMapper field is used to convert a TreeNode to an object of required type.

This doesn't require TypeA, TypeB etc to have any other common parent except Object.

It'll be necessary to specify this deserializer as used for each JSON element with an "op" field. I tested by parsing this class:

class Ops {
    @JsonDeserialize(contentUsing = OpDeserializer.class)
    Object[] ops;
}


来源: stackexchange

问:
How can I know my iOS app crashed?
I am developing an iOS app with swift 3-4 and I have to know the time when my app crashed. How do I achieve that? I don't use firebase.</p>

答:
You may have these notifications inside UIApplicationDelegate class:

applicationDidFinishLaunchingWithOptions:

applicationWillResignActive:

applicationDidEnterBackground:

applicationWillEnterForeground:

applicationDidBecomeActive:

applicationWillTerminate:

There are also more inside here.

You can do what you want inside the implementation of these delegates, including record time. Note still you don't run short in time, some evwnta give you only limited time to react.

ContentLicense: CC BY-SA 3.0

Title: How can I know my iOS app crashed?


问:
Not able to bind Amchart piechart Legend outside the div and also help me for Custom legend as given in description
I was working on Amcharts PIE chart, and i got problem in binding
 legend outside div and also i need custom Legend for Pie chart

Here I have updated code working of PIE chart CODE PEN

and I am not able bind as per given style in the ID #PieDivID " ,as soon as i remove this style, Legend will appear but not in a right place

```<code> `#PieDivID {
  position: absolute;
  right:0px;
  top:25px;
}`
</code>```

 and also
Can someone help me to arrange those legends in this way

Total:4

Pending:4

OnGoing:3

Completed:6

var tripPieChart1 = AmCharts.makeChart( "tripPieChart1",
      {
        "hideCredits" : true,
        "color":"#000000",
        "labelsEnabled": true,
        "type": "pie",
        "theme": "light",
        "bold": true,
        "dataProvider": [ {
         "status": "Total",
         "count":4,
         "color": "#FF0F00",
         "bold": true,
        }, {
         "status": "Pending",
         "count":7,"color" : "#9C27B0"
        }, {
         "status": "OnGoing",
         "count":3,  "color": "#FFBE01"
        }, {
         "status": "Completed",
         "count":6, "color": "#00C853"
        }],
        "valueField": "count",
        "titleField": "status",
        "colorField": "color",
        "depth3D": 15,
        "angle": 25,
        "legend":{
           "divId": "PieDivID",
           "autoMargins": false,
          "enabled" : true,
          "maxColumns": 1,
          "generateFromData": true,
         },
        "export": {
          "enabled": false,

        }
      } );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#tripPieChart1 {
  width: 100%;
  height: 500px;
  font-size: 11px;
}
#PieDivID {
  position: absolute;
  right:0px;
  top:25px;
}
/*I am not able bind as per given style in this #PieDivID , as soon as i remove this style, Legend will appear but not in a right place</code>```

<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />

```

答:
You need to give a width to the div containing your external legend for it to show up. Adding min-width: 200px; was sufficient but adjust as needed.

The order of the legend markers is dependent on the order of the data provider. If you want the legend markers to show up in that order, sort your dataProvider in that order. In your example it's already in the desired order so no additional work is needed.

Demo:

var tripPieChart1 = AmCharts.makeChart("tripPieChart1", {
  "hideCredits": true,
  "color": "#000000",
  "labelsEnabled": true,
  "type": "pie",
  "theme": "light",
  "bold": true,
  "dataProvider": [{
    "status": "Total",
    "count": 4,
    "color": "#FF0F00",
    "bold": true,
  }, {
    "status": "Pending",
    "count": 7,
    "color": "#9C27B0"
  }, {
    "status": "OnGoing",
    "count": 3,
    "color": "#FFBE01"
  }, {
    "status": "Completed",
    "count": 6,
    "color": "#00C853"
  }],
  "valueField": "count",
  "titleField": "status",
  "colorField": "color",
  "depth3D": 15,
  "angle": 25,
  "legend": {
    "divId": "PieDivID",
    "autoMargins": false,
    "enabled": true,
    "maxColumns": 1,
    //"generateFromData": true, //this is a custom property - not sure what this is for.
  },
  "export": {
    "enabled": false,

  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#tripPieChart1 {
  width: 100%;
  height: 500px;
  font-size: 11px;
}

#PieDivID {
  position: absolute;
  right: 0px;
  min-width: 200px;
  top: 25px;
}</code>```

<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />

```

If you need a custom legend, look at this example from AmCharts and modify it to work with your code. You can pretty much copy and paste the code and modify the variable/div references.

ContentLicense: CC BY-SA 4.0

Body:
I was working on Amcharts PIE chart, and i got problem in binding
 legend outside div and also i need custom Legend for Pie chart

Here I have updated code working of PIE chart CODE PEN

and I am not able bind as per given style in the ID #PieDivID " ,as soon as i remove this style, Legend will appear but not in a right place

 `#PieDivID {
  position: absolute;
  right:0px;
  top:25px;
}`

 and also
Can someone help me to arrange those legends in this way

Total:4

Pending:4

OnGoing:3

Completed:6

var tripPieChart1 = AmCharts.makeChart( "tripPieChart1",
      {
        "hideCredits" : true,
        "color":"#000000",
        "labelsEnabled": true,
        "type": "pie",
        "theme": "light",
        "bold": true,
        "dataProvider": [ {
         "status": "Total",
         "count":4,
         "color": "#FF0F00",
         "bold": true,
        }, {
         "status": "Pending",
         "count":7,"color" : "#9C27B0"
        }, {
         "status": "OnGoing",
         "count":3,  "color": "#FFBE01"
        }, {
         "status": "Completed",
         "count":6, "color": "#00C853"
        }],
        "valueField": "count",
        "titleField": "status",
        "colorField": "color",
        "depth3D": 15,
        "angle": 25,
        "legend":{
           "divId": "PieDivID",
           "autoMargins": false,
          "enabled" : true,
          "maxColumns": 1,
          "generateFromData": true,
         },
        "export": {
          "enabled": false,

        }
      } );

#tripPieChart1 {
  width: 100%;
  height: 500px;
  font-size: 11px;
}
#PieDivID {
  position: absolute;
  right:0px;
  top:25px;
}
/*I am not able bind as per given style in this #PieDivID , as soon as i remove this style, Legend will appear but not in a right place

<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />

Body:
You need to give a width to the div containing your external legend for it to show up. Adding min-width: 200px; was sufficient but adjust as needed.

The order of the legend markers is dependent on the order of the data provider. If you want the legend markers to show up in that order, sort your dataProvider in that order. In your example it's already in the desired order so no additional work is needed.

Demo:

var tripPieChart1 = AmCharts.makeChart("tripPieChart1", {
  "hideCredits": true,
  "color": "#000000",
  "labelsEnabled": true,
  "type": "pie",
  "theme": "light",
  "bold": true,
  "dataProvider": [{
    "status": "Total",
    "count": 4,
    "color": "#FF0F00",
    "bold": true,
  }, {
    "status": "Pending",
    "count": 7,
    "color": "#9C27B0"
  }, {
    "status": "OnGoing",
    "count": 3,
    "color": "#FFBE01"
  }, {
    "status": "Completed",
    "count": 6,
    "color": "#00C853"
  }],
  "valueField": "count",
  "titleField": "status",
  "colorField": "color",
  "depth3D": 15,
  "angle": 25,
  "legend": {
    "divId": "PieDivID",
    "autoMargins": false,
    "enabled": true,
    "maxColumns": 1,
    //"generateFromData": true, //this is a custom property - not sure what this is for.
  },
  "export": {
    "enabled": false,

  }
});

#tripPieChart1 {
  width: 100%;
  height: 500px;
  font-size: 11px;
}

#PieDivID {
  position: absolute;
  right: 0px;
  min-width: 200px;
  top: 25px;
}

<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/pie.js"></script>
<script src="https://www.amcharts.com/lib/3/plugins/export/export.min.js"></script>
<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />
<script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
<div id="PieDivID"></div>
<div id="tripPieChart1"></div>

If you need a custom legend, look at this example from AmCharts and modify it to work with your code. You can pretty much copy and paste the code and modify the variable/div references.


问:
Numerically sorting the String Arrays
I already know that we can sort string arrays numerically, by converting them to integer array then using Arrays.sort() or using any comparator.

So my question is if those strings are beyond the limit of integer or long int then how can we sort them. For example consider the following string array:

```<code>14829435897932384626433832795
4159265358979323846264338327
1937286535897932384626433832795296523
23746289
</code>```

in those cases traditional comparator or any sorting method won't work because in turn they use integer (or any other datatype).

答:
As suggested by Eran: Convert to BigInteger and do the comparison:

```<code>Collections.sort(list, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        BigInteger bi1 = new BigInteger(o1);
        BigInteger bi2 = new BigInteger(o2);
        return bi1.compareTo(bi2);
    }
});
</code>```

And because @tobias_k doesn't care about karma:

If you're running Java 8, you can use the many new default methods of the Comparator interface to do it in one line:

```<code>Arrays.sort(arr, Comparator.comparing(BigInteger::new))
</code>```

Just added a counter to the Comparator to see how many times a String was converted to a BigInteger. It counted 10 conversions in my simple run of 4 strings.

This made me think that there might be a performance gain by converting each string once, sorting the BigInteger instances and converting them back. Something like this:

```<code>List<BigInteger> list1 = list.stream().map(BigInteger::new)
     .sorted().collect(Collectors.toList());
</code>```

Title: Numerically sorting the String Arrays

Body:
I already know that we can sort string arrays numerically, by converting them to integer array then using Arrays.sort() or using any comparator.

So my question is if those strings are beyond the limit of integer or long int then how can we sort them. For example consider the following string array:

14829435897932384626433832795
4159265358979323846264338327
1937286535897932384626433832795296523
23746289

in those cases traditional comparator or any sorting method won't work because in turn they use integer (or any other datatype).

Body:
As suggested by Eran: Convert to BigInteger and do the comparison:

Collections.sort(list, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        BigInteger bi1 = new BigInteger(o1);
        BigInteger bi2 = new BigInteger(o2);
        return bi1.compareTo(bi2);
    }
});

And because @tobias_k doesn't care about karma:

If you're running Java 8, you can use the many new default methods of the Comparator interface to do it in one line:

Arrays.sort(arr, Comparator.comparing(BigInteger::new))

Just added a counter to the Comparator to see how many times a String was converted to a BigInteger. It counted 10 conversions in my simple run of 4 strings.

This made me think that there might be a performance gain by converting each string once, sorting the BigInteger instances and converting them back. Something like this:

List<BigInteger> list1 = list.stream().map(BigInteger::new)
     .sorted().collect(Collectors.toList());


问:
Where can I get a simple table of time zones for use in SQL server?
I just need to make a SQL table of time zones - at this point, my only need is to populate a drop-down list on an online form. I'm envisioning something simple with columns for ISO code, name, UTC offset, and perhaps a list of representative cities. I thought I would be able to easily find something online to copy-and-paste, but haven't been able to locate anything.

I was directed by this question to the tz database, which is in binary form and seems like overkill for what I need. Alternatively I could piece this together from sites like TimeAndDate.com, but that seems like more work than should be necessary.

Or am I going about this the wrong way - e.g. should I be getting this information from the server's OS?

答:
the list of all timezone are here:

```<code>select * from sys.time_zone_info
</code>```

Enjoy!

ContentLicense: CC BY-SA 2.5

Body:
the list of all timezone are here:

select * from sys.time_zone_info

Enjoy!


问:
Specified argument was out of the range of valid values. Parameter name: site - Error Due To Creators Update
After a installing the creators update I ended up getting this error:

```<code>Specified argument was out of the range of valid values. Parameter name: site error.
</code>```

I was able to repair IIS by downloading IIS 10 from Microsoft. Unfortunately, in addition to breaking IIS the Creators update borked my user permissions on my dev folders and git was unable to add and remove folders. For the life of me I couldn't figure out how to fix that. So, I decided to roll windows back.

Guess what? It broke IIS again. This time though the IIS 10 installer would not let me repair IIS, I couldn't repair it from Add/Remove programs, and I can't uninstall it to start over. I tried uninstalling it from the VS2017 installer and reinstalling it that also did not work.

答:
I found these SO questions:

Specified Argument was out of the range of valid values Parameter name : site

Specified argument was out of the range of valid values (Parameter name: site)

Specified argument was out of the range of valid values. Parameter name: site

None of the accepted answers fixed my error, on the third SO post I found what saved me. I don't have enough rep to comment but I wanted to share this in case anyone else runs into this extremely frustrating bug.

From Sikandar Amla's answer:

I had the same issue with VS2017. Following solved the issue.

Run Command prompt as Administrator.

Write following two commands which will update your registry.

reg add HKLM\Software\WOW6432Node\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f

reg add HKLM\Software\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f

This should solve your problem. Refer to this link for more details.

Body:
After a installing the creators update I ended up getting this error:

Specified argument was out of the range of valid values. Parameter name: site error.

I was able to repair IIS by downloading IIS 10 from Microsoft. Unfortunately, in addition to breaking IIS the Creators update borked my user permissions on my dev folders and git was unable to add and remove folders. For the life of me I couldn't figure out how to fix that. So, I decided to roll windows back.

Guess what? It broke IIS again. This time though the IIS 10 installer would not let me repair IIS, I couldn't repair it from Add/Remove programs, and I can't uninstall it to start over. I tried uninstalling it from the VS2017 installer and reinstalling it that also did not work.


问:
Localizing a website
Which should you rather use for a medium-sized web site (I don't know the exact number of pages, words, and so on yet):

A) PHP files with static resources:

en.php

```<code>    $lang_welcome = 'Welcome';
</code>```

de.php

```<code>    $lang_welcome = 'Willkommen';
</code>```

B) MySQL table containing translations:

```<code>+------+-----------+---------+-------------+
| lang |   path    |  term   | translation |
+------+-----------+---------+-------------+
|  en  | index.php | welcome |   Welcome   |
+------+-----------+---------+-------------+
|  de  | index.php | welcome |  Willkommen |
+------+-----------+---------+-------------+
|  en  |           |  cancel |   Cancel    |
+------+-----------+---------+-------------+
|  de  |           |  cancel |  Abbrechen  |
+------+-----------+---------+-------------+
</code>```

(The only solution I could think of off the top of my head right now.)

C.) Some other solution.

答: I think php files is more standard. Your text is not going to change. DB's aren't really the best choice since it's read-only data.</p>

Title: Localizing a website

Body:
Which should you rather use for a medium-sized web site (I don't know the exact number of pages, words, and so on yet):

A) PHP files with static resources:

en.php

    $lang_welcome = 'Welcome';

de.php

    $lang_welcome = 'Willkommen';

B) MySQL table containing translations:

+------+-----------+---------+-------------+
| lang |   path    |  term   | translation |
+------+-----------+---------+-------------+
|  en  | index.php | welcome |   Welcome   |
+------+-----------+---------+-------------+
|  de  | index.php | welcome |  Willkommen |
+------+-----------+---------+-------------+
|  en  |           |  cancel |   Cancel    |
+------+-----------+---------+-------------+
|  de  |           |  cancel |  Abbrechen  |
+------+-----------+---------+-------------+

(The only solution I could think of off the top of my head right now.)

C.) Some other solution.


问:
Convert user date of birth html input to age in php
I'm trying to get the date from the date-time-picker name="dob" into the php but it only post 2017 in the database user_age column. However, if I assigned $dob manually to $dob = '10/09/1988' it works.

```<code><div class="form-group date-time-picker label-floating is-empty">
 <label class="control-label">Birthday</label>
 <input name="datetimepicker">
</div>
</code>```

And here is the php

```<code><?php
 $dob = $_GET['datetimepicker'];
 $dob = explode("/", $dob);
 $agv = (date("md", date("U", mktime(0, 0, 0, $dob[0], $dob[1], $dob[2]))) >
 date("md") ? ((date("Y") - $dob[2]) -1) : (date("Y") - $dob[2]));

 $age = mysqli_real_escape_string($conn, $agv);
?>
</code>```

答:
I think the problem is to get a DOB, subtract that from the date of now and present the difference in years, right?

That seems like a problem for DateTime::diff

```<code>$dob = new DateTime($_GET['dob']); // we'll just assume this is a safe date value for now
$now = new DateTime();

$age = $dob->diff($now);

$ageInYears = $age->format('%Y');
</code>```

Body:
I'm trying to get the date from the date-time-picker name="dob" into the php but it only post 2017 in the database user_age column. However, if I assigned $dob manually to $dob = '10/09/1988' it works.

 Birthday
 <input name="datetimepicker">

And here is the php

<?php
 $dob = $_GET['datetimepicker'];
 $dob = explode("/", $dob);
 $agv = (date("md", date("U", mktime(0, 0, 0, $dob[0], $dob[1], $dob[2]))) >
 date("md") ? ((date("Y") - $dob[2]) -1) : (date("Y") - $dob[2]));

 $age = mysqli_real_escape_string($conn, $agv);
?>

Body:
I think the problem is to get a DOB, subtract that from the date of now and present the difference in years, right?

That seems like a problem for DateTime::diff

$dob = new DateTime($_GET['dob']); // we'll just assume this is a safe date value for now
$now = new DateTime();

$age = $dob->diff($now);

$ageInYears = $age->format('%Y');


问:
Pandas: Replace multiple column values by unique value
I have a pandas DataFrame with many "object" columns where each of them contains many values (modalities). Then, I want to keep only the 10 most frequent modalities for each column and the others replace by 'Oth'.

For example, if I have a column 'obj_col1' which contains 4 different values:

```<code>obj_col1
'A'
'A'
'B'
'C'
'B'
'D'
</code>```

and I want to keep 2 the most frequent, here 'A' and 'B', and replace the rest by 'Oth':

```<code>obj_col2
'A'
'A'
'B'
'Oth'
'B'
'Oth'
</code>```

A piece of code for one object column (categorical variable) is:

```<code># sorted list of modalities of 'categ_var'
list_freq_modal = df['categ_var'].value_counts().index.tolist()
# replace all the modalities except the first 10 by 'Oth'
df['categ_var'].replace(list_freq_modal[10:],'Oth', inplace=True)
</code>```

But I have an error : 'NoneType' object has no attribute 'any'

Have you any idea have implement it in more optimal way ?

答:
Instead of replace we can use value_counts.head(2) and where by mapping value_counts and getting the mask with notnull() ie

```<code>x = df['obj_col1'].value_counts().head(2)
#B    2
#A    2
#Name: obj_col1, dtype: int64

df['obj_col1'].where(df['obj_col1'].map(x).notnull(),'Oth')
</code>```

Output :

```
0      A
1      A
2      B
3    Oth
4      B
5    Oth
Name: obj_col1, dtype: object
```

```<code>df['obj_col1'].map(x).notnull() # This will give the mask.
</code>```

```
0     True
1     True
2     True
3    False
4     True
5    False
Name: obj_col1, dtype: bool
```

Body:
I have a pandas DataFrame with many "object" columns where each of them contains many values (modalities). Then, I want to keep only the 10 most frequent modalities for each column and the others replace by 'Oth'.

For example, if I have a column 'obj_col1' which contains 4 different values:

obj_col1
'A'
'A'
'B'
'C'
'B'
'D'

and I want to keep 2 the most frequent, here 'A' and 'B', and replace the rest by 'Oth':

obj_col2
'A'
'A'
'B'
'Oth'
'B'
'Oth'

A piece of code for one object column (categorical variable) is:

# sorted list of modalities of 'categ_var'
list_freq_modal = df['categ_var'].value_counts().index.tolist()
# replace all the modalities except the first 10 by 'Oth'
df['categ_var'].replace(list_freq_modal[10:],'Oth', inplace=True)

But I have an error : 'NoneType' object has no attribute 'any'

Have you any idea have implement it in more optimal way ?

Body:
Instead of replace we can use value_counts.head(2) and where by mapping value_counts and getting the mask with notnull() ie

x = df['obj_col1'].value_counts().head(2)
#B    2
#A    2
#Name: obj_col1, dtype: int64

df['obj_col1'].where(df['obj_col1'].map(x).notnull(),'Oth')

Output :

0      A
1      A
2      B
3    Oth
4      B
5    Oth
Name: obj_col1, dtype: object

df['obj_col1'].map(x).notnull() # This will give the mask.

0     True
1     True
2     True
3    False
4     True
5    False
Name: obj_col1, dtype: bool


问:
Javascript can't get element's value, value equals undefined
I would like some help please.

I've recently started learning javascript, and I came across an error I can't fix, it seems simple, yet I can't find a way to fix it.
So, I have a table:

And the point of the table is to give the squares with the value "X" when clicked, a red background (changing css class), and all others green, but to do that, I need to get the value of the square, and it is always returning "undefined".

The HTML table looks like this:

```<code><table>
    <tr>
        <td class="normal" id="11" value="0" onclick="alterar('11');">0</td>
        <td class="normal" id="12" value="1" onclick="alterar('12');">1</td>
        <td class="normal" id="13" value="2" onclick="alterar('13');">2</td>
        <td class="normal" id="14" value="X" onclick="alterar('14');">X</td>
        <td class="normal" id="15" value="1" onclick="alterar('15');">1</td>
        <td class="normal" id="16" value="0" onclick="alterar('16');">0</td>
        <td class="normal" id="17" value="0" onclick="alterar('17');">0</td>
    </tr>
        <td class="normal" id="21" value="0" onclick="alterar('21');">0</td>
        <td class="normal" id="22" value="1" onclick="alterar('22');">1</td>
        <td class="normal" id="23" value="2" onclick="alterar('23');">2</td>
        <td class="normal" id="24" value="X" onclick="alterar('24');">X</td>
        <td class="normal" id="25" value="1" onclick="alterar('25');">1</td>
        <td class="normal" id="26" value="0" onclick="alterar('26');">0</td>
        <td class="normal" id="27" value="0" onclick="alterar('27');">0</td>
    </tr>
        <td class="normal" id="31" value="0" onclick="alterar('31');">0</td>
        <td class="normal" id="32" value="1" onclick="alterar('32');">1</td>
        <td class="normal" id="33" value="2" onclick="alterar('33');">2</td>
        <td class="normal" id="34" value="X" onclick="alterar('34');">X</td>
        <td class="normal" id="35" value="1" onclick="alterar('35');">1</td>
        <td class="normal" id="36" value="0" onclick="alterar('36');">0</td>
        <td class="normal" id="37" value="0" onclick="alterar('37');">0</td>
    </tr>
        <td class="normal" id="41" value="0" onclick="alterar('41');">0</td>
        <td class="normal" id="42" value="1" onclick="alterar('42');">1</td>
        <td class="normal" id="43" value="2" onclick="alterar('43');">2</td>
        <td class="normal" id="44" value="X" onclick="alterar('44');">X</td>
        <td class="normal" id="45" value="1" onclick="alterar('45');">1</td>
        <td class="normal" id="46" value="0" onclick="alterar('46');">0</td>
        <td class="normal" id="47" value="0" onclick="alterar('47');">0</td>
    </tr>
</table>
</code>```

My javascript code looks like this:

```<code>function alterar(obj){

  var id = document.getElementById(obj).id;
  var value = document.getElementById(id).value;

  if (value == 'X'){
    obj.className='red';
  } else {
    obj.className='green';
    }
}

</script>
</code>```

And if for example, I'd use the square "44", which value is "X", it tells me that

```<code>    <td class="normal" id="44" value="X" onclick="alterar('44');">X</td>
</code>```

I'd like to thank everyone in advance for their times.

答:
you can use this in on click function, which returns clicked element.

```<code><td class="normal" id="11" value="0" onclick="alterar(this);">0</td>
</code>```

then inside the function access the element you have passed.

```<code>function alterar(obj){
    var value = obj.innerText;
    if(value == 'X'){
        obj.className='red';
    } else {
        obj.className='green';
    }
}
</code>```

you don't have to query the element using id.

Body:
I would like some help please.

I've recently started learning javascript, and I came across an error I can't fix, it seems simple, yet I can't find a way to fix it.
So, I have a table:

And the point of the table is to give the squares with the value "X" when clicked, a red background (changing css class), and all others green, but to do that, I need to get the value of the square, and it is always returning "undefined".

The HTML table looks like this:

        0
        1
        2
        X
        1
        0
        0

        0
        1
        2
        X
        1
        0
        0

        0
        1
        2
        X
        1
        0
        0

        0
        1
        2
        X
        1
        0
        0

My javascript code looks like this:

function alterar(obj){

  var id = document.getElementById(obj).id;
  var value = document.getElementById(id).value;

  if (value == 'X'){
    obj.className='red';
  } else {
    obj.className='green';
    }
}

</script>

And if for example, I'd use the square "44", which value is "X", it tells me that

    X

I'd like to thank everyone in advance for their times.

Body:
you can use this in on click function, which returns clicked element.

<td class="normal" id="11" value="0" onclick="alterar(this);">0</td>

then inside the function access the element you have passed.

function alterar(obj){
    var value = obj.innerText;
    if(value == 'X'){
        obj.className='red';
    } else {
        obj.className='green';
    }
}

you don't have to query the element using id.


问:
AWS CodeDeploy deployment tracking
I would like to know if it's possible to track the deployment status of CodeDeploy by using CLI.
Currently, I'm using Bamboo to trigger the CodeDeploy deployment by CLI using: aws deploy create-deployment ... My Bamboo plan will show green the moment the deployment is triggered instead of checking if the actual deployment is succeeded. Is there a way to let Bamboo/command line verify if the actual deployment was successfully deployed?
Many thanks!</p>

答:
Your create-deployment will return a Deployment ID. Use that in aws deploy get-deployment --deployment-id XXX to see the status and info of the deployment:

http://docs.aws.amazon.com/cli/latest/reference/deploy/get-deployment.html

You can use aws deploy wait deployment-successful --deployment-id XXX to wait for completion:

http://docs.aws.amazon.com/cli/latest/reference/deploy/wait/deployment-successful.html.

Title: AWS CodeDeploy deployment tracking


问:
Add/update and display an array of meta_values
I am trying to add an array of meta_values to a single meta_key and display them in a list like so:

Assessment One, Passed

Assesment Two, Passed

My code for updating/adding the user_meta:

```<code>    $user_id = $current_user->ID;
    $key = 'assessment_result';
    $assessment_name = get_the_title();
    $new_value = array($assessment_name, 'Passed');
    $meta = get_user_meta($user_id, $key, false);
    if ( ! array($meta) ) {
        $meta = array();
    }
    $meta[] = $new_value;
    update_user_meta($user_id, $key, $meta, $unique);
</code>```

After completing two assessments, my array looks like this:

```<code>Array ( [0] => Array ( [0] => Array ( [0] => Array ( [0] => Assessment Two [1] => Passed ) ) [1] => Array ( [0] => Assessment One [1] => Passed ) ) ) 1
</code>```

There seems to be too many arrays!

Then my query looks like this:

```<code>$user_assessment_results = get_user_meta($user_id, 'assessment_result', true);
echo '<ul>';
foreach ($user_assessment_results as $user_assessment_result) {
    echo '<li>';
    $output = array();
    foreach ($user_assessment_result as $result_item) {
        $output[] =  $result_item;
    }
    if( count( $output ) ) echo join( ", ", $output );
    echo '</li>';
}
echo '</ul>';
</code>```

Which results in:

Array

Assessment One, Passed

Can you suggest where I am going wrong?

答: I found the problem $meta = get_user_meta($user_id, $key, false); should have been $meta = get_user_meta($user_id, $key, true);

Body:
I am trying to add an array of meta_values to a single meta_key and display them in a list like so:

Assessment One, Passed

Assesment Two, Passed

My code for updating/adding the user_meta:

    $user_id = $current_user->ID;
    $key = 'assessment_result';
    $assessment_name = get_the_title();
    $new_value = array($assessment_name, 'Passed');
    $meta = get_user_meta($user_id, $key, false);
    if ( ! array($meta) ) {
        $meta = array();
    }
    $meta[] = $new_value;
    update_user_meta($user_id, $key, $meta, $unique);

After completing two assessments, my array looks like this:

Array ( [0] => Array ( [0] => Array ( [0] => Array ( [0] => Assessment Two [1] => Passed ) ) [1] => Array ( [0] => Assessment One [1] => Passed ) ) ) 1

There seems to be too many arrays!

Then my query looks like this:

$user_assessment_results = get_user_meta($user_id, 'assessment_result', true);
echo '
';
foreach ($user_assessment_results as $user_assessment_result) {
    echo '
';
    $output = array();
    foreach ($user_assessment_result as $result_item) {
        $output[] =  $result_item;
    }
    if( count( $output ) ) echo join( ", ", $output );
    echo '
';
}
echo '
';

Which results in:

Array

Assessment One, Passed

Can you suggest where I am going wrong?


问:
Is there a quick way to convert all values in a column to True/False values?
For example I have the following table

```<code>+--------+-----------------------+--+
|   Id   |    BuyingAttribute    |  |
+--------+-----------------------+--+
| 1      |    Low Price          |  |
| 1      |    Good Communication |  |
| 1      |    English Speaker    |  |
| 2      |    Low Price          |  |
| ...etc | ...etc                |  |
+--------+-----------------------+--+
</code>```

Is there a way that I could transfer all the values automatically to yes/No values. I know that I can use case statement  like so

```<code>SELECT
    Id,
    CASE WHEN BuyingAttribute = 'Low Price' THEN True ELSE False END AS Buying Attribute
FROM
    myTable
</code>```

However, is there an automated  method, because it will be time consuming if I have 50 values and write 50 case statement to generate results like below

```<code>+----+-----------------------+---------------+-------------------------+----------------------+
| Id |  BuyingAttribute      | BA(Low Price) |  BA(Good Communication) |  BA(English Speaker) |
+----+-----------------------+---------------+-------------------------+----------------------+
|  1 |    Low Price          |   True        |   False                 |   False              |
|  1 |    Good Communication |   False       |   True                  |   False              |
|  1 |    English Speaker    |   False       |   False                 |   True               |
|  2 |    Low Price          |   True        |   False                 |   False              |
|    |                       |               |                         |                      |
+----+-----------------------+---------------+-------------------------+----------------------+
</code>```

答:
You can do this by allocating all possible buying attributes to all ids like this

```<code>select tid,row_number() over (partition by tid order by baba) rn,
        baba,
        t.BuyingAttribute tba
from
(
select distinct t.id tid, ba.buyingattribute baba from t
cross join (select distinct t.BuyingAttribute from t) ba
) s
left join t on t.BuyingAttribute = s.baba and t.id = s.tid
</code>```

Result

```<code>tid         rn                   baba                           tba
----------- -------------------- ------------------------------ ------------------------------
1           1                    English Speaker                English Speaker
1           2                    Good Communication             Good Communication
1           3                    Low Price                      Low Price
2           1                    English Speaker                NULL
2           2                    Good Communication             NULL
2           3                    Low Price                      Low Price
</code>```

We can then wrap this in a pivot

```<code>select tid,rn,
    case when [English Speaker] is not null then 'true' else 'false' end as 'English Speaker',
    case when [Good Communication] is not null then 'true' else 'false' end as 'Good Communication',
    case when [Low Price] is not null then 'true' else 'false' end as 'Low Price'
from
(
select tid,row_number() over (partition by tid order by baba) rn,
        baba,
        t.BuyingAttribute tba
from
(
select distinct t.id tid, ba.buyingattribute baba from t
cross join (select distinct t.BuyingAttribute from t) ba
) s
left join t on t.BuyingAttribute = s.baba and t.id = s.tid
--order by tid, baba
) t
pivot (max(baba) for baba in ([English Speaker],[Good Communication],[Low Price])) pvt
order by tid,rn
</code>```

to get

```<code>tid         rn                   English Speaker Good Communication Low Price
----------- -------------------- --------------- ------------------ ---------
1           1                    true            false              false
1           2                    false           true               false
1           3                    false           false              true
2           1                    true            false              false
2           2                    false           true               false
2           3                    false           false              true
</code>```

This would be a problem for you because you don't know how many buyingattributes you have so we need to build the above statement and execute dynamic sql.

```<code>declare @s1 nvarchar(max)
declare @s10 varchar(max)
declare @s9 varchar(max)

set @s1 = 'select tid,rn,'

set @s9 = (
          select top 1  STUFF((
          SELECT 'case when [' + t1.buyingattribute + '] is not null then ' + char(39) +  'true' + char(39) +
          ' else ' + char(39) + 'false' + char(39) + ' end as ' + char(39) + t1.buyingattribute + char(39) + ','
          from t t1 where t1.buyingattribute >= t.buyingattribute
          FOR XML PATH(''), TYPE).value('.', 'nVARCHAR(max)'), 1, 1, '')
          from
          (select distinct buyingattribute from t) t
        )
--select substring(@s9,patindex('%,%',@s9)+ 1, len(@s9) - patindex('%,%',@s9))
--select @s9
set @s9 = substring(@s9,1,len(@s9) -1)
set @s1 = concat(@s1,substring(@s9,patindex('%,%',@s9)+ 1, len(@s9) - patindex('%,%',@s9)))

set @s10 = ' from
(
select tid,row_number() over (partition by tid order by baba) rn,
        baba,
        t.BuyingAttribute tba
from
(
select distinct t.id tid, ba.buyingattribute baba from t
cross join (select distinct t.BuyingAttribute from t) ba
) s
left join t on t.BuyingAttribute = s.baba and t.id = s.tid
--order by tid, baba
) t
pivot (max(baba) for baba in ('

set @s9 = (
          select top 1  STUFF((
          SELECT '[' + t1.buyingattribute + '] ,'
          from t t1 where t1.buyingattribute >= t.buyingattribute
          FOR XML PATH(''), TYPE).value('.', 'nVARCHAR(max)'), 1, 1, '')
          from
          (select distinct buyingattribute from t) t
        )
set @s9 = substring(@s9,1,len(@s9) - 1)
set @s1 = concat(@s1,@s10,substring(@s9,patindex('%,%',@s9)+ 1, len(@s9) - patindex('%,%',@s9)),' )) pvt order by tid,rn')

exec sp_executesql @s1
</code>```

Body:
For example I have the following table

+--------+-----------------------+--+
|   Id   |    BuyingAttribute    |  |
+--------+-----------------------+--+
| 1      |    Low Price          |  |
| 1      |    Good Communication |  |
| 1      |    English Speaker    |  |
| 2      |    Low Price          |  |
| ...etc | ...etc                |  |
+--------+-----------------------+--+

Is there a way that I could transfer all the values automatically to yes/No values. I know that I can use case statement  like so

SELECT
    Id,
    CASE WHEN BuyingAttribute = 'Low Price' THEN True ELSE False END AS Buying Attribute
FROM
    myTable

However, is there an automated  method, because it will be time consuming if I have 50 values and write 50 case statement to generate results like below

+----+-----------------------+---------------+-------------------------+----------------------+
| Id |  BuyingAttribute      | BA(Low Price) |  BA(Good Communication) |  BA(English Speaker) |
+----+-----------------------+---------------+-------------------------+----------------------+
|  1 |    Low Price          |   True        |   False                 |   False              |
|  1 |    Good Communication |   False       |   True                  |   False              |
|  1 |    English Speaker    |   False       |   False                 |   True               |
|  2 |    Low Price          |   True        |   False                 |   False              |
|    |                       |               |                         |                      |
+----+-----------------------+---------------+-------------------------+----------------------+

Body:
You can do this by allocating all possible buying attributes to all ids like this

select tid,row_number() over (partition by tid order by baba) rn,
        baba,
        t.BuyingAttribute tba
from
(
select distinct t.id tid, ba.buyingattribute baba from t
cross join (select distinct t.BuyingAttribute from t) ba
) s
left join t on t.BuyingAttribute = s.baba and t.id = s.tid

Result

tid         rn                   baba                           tba
----------- -------------------- ------------------------------ ------------------------------
1           1                    English Speaker                English Speaker
1           2                    Good Communication             Good Communication
1           3                    Low Price                      Low Price
2           1                    English Speaker                NULL
2           2                    Good Communication             NULL
2           3                    Low Price                      Low Price

We can then wrap this in a pivot

select tid,rn,
    case when [English Speaker] is not null then 'true' else 'false' end as 'English Speaker',
    case when [Good Communication] is not null then 'true' else 'false' end as 'Good Communication',
    case when [Low Price] is not null then 'true' else 'false' end as 'Low Price'
from
(
select tid,row_number() over (partition by tid order by baba) rn,
        baba,
        t.BuyingAttribute tba
from
(
select distinct t.id tid, ba.buyingattribute baba from t
cross join (select distinct t.BuyingAttribute from t) ba
) s
left join t on t.BuyingAttribute = s.baba and t.id = s.tid
--order by tid, baba
) t
pivot (max(baba) for baba in ([English Speaker],[Good Communication],[Low Price])) pvt
order by tid,rn

to get

tid         rn                   English Speaker Good Communication Low Price
----------- -------------------- --------------- ------------------ ---------
1           1                    true            false              false
1           2                    false           true               false
1           3                    false           false              true
2           1                    true            false              false
2           2                    false           true               false
2           3                    false           false              true

This would be a problem for you because you don't know how many buyingattributes you have so we need to build the above statement and execute dynamic sql.

declare @s1 nvarchar(max)
declare @s10 varchar(max)
declare @s9 varchar(max)

set @s1 = 'select tid,rn,'

set @s9 = (
          select top 1  STUFF((
          SELECT 'case when [' + t1.buyingattribute + '] is not null then ' + char(39) +  'true' + char(39) +
          ' else ' + char(39) + 'false' + char(39) + ' end as ' + char(39) + t1.buyingattribute + char(39) + ','
          from t t1 where t1.buyingattribute >= t.buyingattribute
          FOR XML PATH(''), TYPE).value('.', 'nVARCHAR(max)'), 1, 1, '')
          from
          (select distinct buyingattribute from t) t
        )
--select substring(@s9,patindex('%,%',@s9)+ 1, len(@s9) - patindex('%,%',@s9))
--select @s9
set @s9 = substring(@s9,1,len(@s9) -1)
set @s1 = concat(@s1,substring(@s9,patindex('%,%',@s9)+ 1, len(@s9) - patindex('%,%',@s9)))

set @s10 = ' from
(
select tid,row_number() over (partition by tid order by baba) rn,
        baba,
        t.BuyingAttribute tba
from
(
select distinct t.id tid, ba.buyingattribute baba from t
cross join (select distinct t.BuyingAttribute from t) ba
) s
left join t on t.BuyingAttribute = s.baba and t.id = s.tid
--order by tid, baba
) t
pivot (max(baba) for baba in ('

set @s9 = (
          select top 1  STUFF((
          SELECT '[' + t1.buyingattribute + '] ,'
          from t t1 where t1.buyingattribute >= t.buyingattribute
          FOR XML PATH(''), TYPE).value('.', 'nVARCHAR(max)'), 1, 1, '')
          from
          (select distinct buyingattribute from t) t
        )
set @s9 = substring(@s9,1,len(@s9) - 1)
set @s1 = concat(@s1,@s10,substring(@s9,patindex('%,%',@s9)+ 1, len(@s9) - patindex('%,%',@s9)),' )) pvt order by tid,rn')

exec sp_executesql @s1


问:
Partially flattening a JavaScript object
I have a JavaScript object that I receive from an API that I cannot modify. I would like to use this data within a tool, but the tool only accepts values stored on the root level of the object e.g. I cannot use dot notation to access the value of a key a level down.

Based on the example below, I'd like to be able to access shape.colour, but by referencing something like shape__colour instead, from a new JSON object.

Example starting object:

```<code>[{
  "id" : 12345,
  "size" : 40,
  "shape": {
     "colour" : 'yellow',
     "dimension" : '2D'
  }
},
{
  "id" : 12346,
  "size" : 50,
  "shape": {
     "colour" : 'blue',
     "dimension" : '3D'
  }
}]
</code>```

What I need it to look like:

```<code>[{
  "id" : 12345,
  "size" : 40,
  "shape__colour": 'yellow',
  "shape__dimension" : '2D;'
  }
},
{
  "id" : 12346,
  "size" : 50,
  "shape__colour": 'blue',
  "shape__dimension" : '3D'
  }
}]
</code>```

Other examples of object flattening functions that I've come across seem to produce a single level array (removing the objects altogether), whereas I need to keep the individual objects, but for the data inside them to be on one level.

Any help would be greatly appreciated!

答:
Another map function:

```<code>const result = arr.map(
  ({shape, ...rest}) => ({ shape__colour: shape.colour, shape__dimension: shape.dimension, ...rest })
);
</code>```

Or if shape has dynamic properties:

```<code>const result = arr.map(
 ({shape, ...rest}) => Object.assign(rest, ...Object.keys(shape).map(key => {["shape__"+key] : shape[key]}))
);
</code>```

Body:
I have a JavaScript object that I receive from an API that I cannot modify. I would like to use this data within a tool, but the tool only accepts values stored on the root level of the object e.g. I cannot use dot notation to access the value of a key a level down.

Based on the example below, I'd like to be able to access shape.colour, but by referencing something like shape__colour instead, from a new JSON object.

Example starting object:

[{
  "id" : 12345,
  "size" : 40,
  "shape": {
     "colour" : 'yellow',
     "dimension" : '2D'
  }
},
{
  "id" : 12346,
  "size" : 50,
  "shape": {
     "colour" : 'blue',
     "dimension" : '3D'
  }
}]

What I need it to look like:

[{
  "id" : 12345,
  "size" : 40,
  "shape__colour": 'yellow',
  "shape__dimension" : '2D;'
  }
},
{
  "id" : 12346,
  "size" : 50,
  "shape__colour": 'blue',
  "shape__dimension" : '3D'
  }
}]

Other examples of object flattening functions that I've come across seem to produce a single level array (removing the objects altogether), whereas I need to keep the individual objects, but for the data inside them to be on one level.

Any help would be greatly appreciated!

Body:
Another map function:

const result = arr.map(
  ({shape, ...rest}) => ({ shape__colour: shape.colour, shape__dimension: shape.dimension, ...rest })
);

Or if shape has dynamic properties:

const result = arr.map(
 ({shape, ...rest}) => Object.assign(rest, ...Object.keys(shape).map(key => {["shape__"+key] : shape[key]}))
);


问:
close the included file in php
I am trying to change pro_id in MySQL query by passing the  pro_id through method.It is printing table.But it is giving

NOTICE: CONSTANT SERVER ALREADY DEFINED IN C:\WAMP64\WWW\DASHBOARD\CONFIG2.PHP ON LINE 2

NOTICE: CONSTANT USERNAME ALREADY DEFINED IN C:\WAMP64\WWW\DASHBOARD\CONFIG2.PHP ON LINE 3
NOTICE: CONSTANT PASSWORD ALREADY DEFINED IN C:\WAMP64\WWW\DASHBOARD\CONFIG2.PHP ON LINE 4
NOTICE: CONSTANT DATABASE ALREADY DEFINED IN C:\WAMP64\WWW\DASHBOARD\CONFIG2.PHP ON LINE 5

these errors.

My code is like this,

```<code><?php
// Defining function
function project($a){

            echo '<DOCTYPE html>
            <head>
                <link rel="stylesheet" type="text/css" href="http://localhost/Dashboard/css/table_css.css">

            </head>
            <section>
            <body>';

         include("C:\wamp64\www\DashBoard\Config2.php");

          $sql = "select total_tc,passed,failed,blocked, (total_tc-passed-failed-blocked) as notrun from (select * from (select version_id as version_id from testcases) as t0, (select count(tc_id) as total_tc from testcases where testcases.pro_id=$a) as t,(select count(tc_result) as passed from executions join testcases on testcases.id=executions.parent_id where tc_result='p' and testcases.pro_id=$a  )as t2,
                        (select count(tc_result) as failed from executions join testcases on testcases.id=executions.parent_id where tc_result='f' and testcases.pro_id=$a)as t3,(select count(tc_result) as blocked from executions join testcases on testcases.id=executions.parent_id where tc_result='b' and testcases.pro_id=$a)as t4) as final where version_id= 1 limit 1;";

          $query = mysqli_query($db, $sql);
          echo'<div class="tbl-header">
                <table cellpadding="0" cellspacing="0" border="0">
                    <thead>
                        <tr>
                         <th>Total Testcase</th>
                         <th>Passed</th>
                         <th>Failed</th>
                         <th>Blocked</th>
                         <th>Not run</th>
                      </tr>
                    </thead>
                </table>
          </div>
       <div class="tbl-content">
         <table cellpadding="0" cellspacing="0" border="0">';

             while ($row = mysqli_fetch_array($query))
               {
               echo '<tr>

                <td>'.$row['total_tc'].'</td>
                <td>'.$row['passed'].'</td>
                <td>'.$row['failed'].'</td>
                <td>'.$row['blocked'].'</td>
                <td>'.$row['notrun'].'</td>

              </tr>';
             }
             echo'
        </tbody>
      </table>
    </div>
  </section>
</html>';
}
// Calling function
for ($x = 1; $x <8; $x++) {
    project($x);
}
?>
</code>```

And Config2.php file contains

```<code><?php
   define('SERVER', '192.168.0.7:3306');
   define('USERNAME', 'Deepak');
   define('PASSWORD', 'test@123');
   define('DATABASE', 'dashtest');
   $db = mysqli_connect(SERVER,USERNAME,PASSWORD,DATABASE);
?>
</code>```

Can Any one help me to solve this?

答:
You are including the file with the constants in your function:

```<code>     include("C:\wamp64\www\DashBoard\Config2.php");
</code>```

So the second time you call your function, you will receive these warnings.

Either include the file outside of your function (and pass the database connection as a parameter if necessary) or use include_once instead.

Title: close the included file in php

Body:
I am trying to change pro_id in MySQL query by passing the  pro_id through method.It is printing table.But it is giving

NOTICE: CONSTANT SERVER ALREADY DEFINED IN C:\WAMP64\WWW\DASHBOARD\CONFIG2.PHP ON LINE 2

NOTICE: CONSTANT USERNAME ALREADY DEFINED IN C:\WAMP64\WWW\DASHBOARD\CONFIG2.PHP ON LINE 3
NOTICE: CONSTANT PASSWORD ALREADY DEFINED IN C:\WAMP64\WWW\DASHBOARD\CONFIG2.PHP ON LINE 4
NOTICE: CONSTANT DATABASE ALREADY DEFINED IN C:\WAMP64\WWW\DASHBOARD\CONFIG2.PHP ON LINE 5

these errors.

My code is like this,

<?php
// Defining function
function project($a){

            echo '<DOCTYPE html>

                <link rel="stylesheet" type="text/css" href="http://localhost/Dashboard/css/table_css.css">

            ';

         include("C:\wamp64\www\DashBoard\Config2.php");

          $sql = "select total_tc,passed,failed,blocked, (total_tc-passed-failed-blocked) as notrun from (select * from (select version_id as version_id from testcases) as t0, (select count(tc_id) as total_tc from testcases where testcases.pro_id=$a) as t,(select count(tc_result) as passed from executions join testcases on testcases.id=executions.parent_id where tc_result='p' and testcases.pro_id=$a  )as t2,
                        (select count(tc_result) as failed from executions join testcases on testcases.id=executions.parent_id where tc_result='f' and testcases.pro_id=$a)as t3,(select count(tc_result) as blocked from executions join testcases on testcases.id=executions.parent_id where tc_result='b' and testcases.pro_id=$a)as t4) as final where version_id= 1 limit 1;";

          $query = mysqli_query($db, $sql);
          echo'

                         Total Testcase
                         Passed
                         Failed
                         Blocked
                         Not run

';

             while ($row = mysqli_fetch_array($query))
               {
               echo '

                '.$row['total_tc'].'
                '.$row['passed'].'
                '.$row['failed'].'
                '.$row['blocked'].'
                '.$row['notrun'].'

';
             }
             echo'

';
}
// Calling function
for ($x = 1; $x <8; $x++) {
    project($x);
}
?>

And Config2.php file contains

<?php
   define('SERVER', '192.168.0.7:3306');
   define('USERNAME', 'Deepak');
   define('PASSWORD', 'test@123');
   define('DATABASE', 'dashtest');
   $db = mysqli_connect(SERVER,USERNAME,PASSWORD,DATABASE);
?>

Can Any one help me to solve this?

Body:
You are including the file with the constants in your function:

     include("C:\wamp64\www\DashBoard\Config2.php");

So the second time you call your function, you will receive these warnings.

Either include the file outside of your function (and pass the database connection as a parameter if necessary) or use include_once instead.


答:
Text translation tables in the database are universally a horrible idea.

For the file translation approach, multiple variations exist. For a very tiny application, a mnemonic id->text approach is ok (typically constants or text arrays). You should however prefer gettext, if that's available and feasible. (There are emulations as native PHP script.)

The data files usually take the form:

```<code> "Welcome at" => "Willkommen bei",
</code>```

Making a much more readable and maintainable code which doesn't rely on abbreviations or shortened array indexes/constants/variable names:

```<code> print _("Welcome at");
</code>```

Title: Localizing a website

Body:
Text translation tables in the database are universally a horrible idea.

For the file translation approach, multiple variations exist. For a very tiny application, a mnemonic id->text approach is ok (typically constants or text arrays). You should however prefer gettext, if that's available and feasible. (There are emulations as native PHP script.)

The data files usually take the form:

 "Welcome at" => "Willkommen bei",

Making a much more readable and maintainable code which doesn't rely on abbreviations or shortened array indexes/constants/variable names:

 print _("Welcome at");


问:
Edge 15 throws error when using 'for ... of' on a NodeList
When looking at the ECMAScript compatibility table, it says that Edge 15 and Edge 16 support for ... of loops.

However, when I run this code:

const list = document.querySelectorAll('[data-test]');
console.log(list);

for (const item of list) {
  console.log(item);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-test></div>
<div data-test></div>
<div data-test></div>
<div data-test></div>
<div data-test></div></code>```

It works in Chrome and Firefox, but not in Edge. Instead it says:

Object doesn't support property or method 'Symbol.iterator'.

As I understand it, NodeList actually should support it, right?

Here's a fildde to try it yourself: Test it online

Can somebody explain the problem or the mistake here?

答:
If for..of is supported but Edge 15 forgot to add the behavior to NodeList, you could polyfill it yourself with very little code:

```<code>NodeList.prototype[Symbol.iterator] = function* () {
    for(var i = 0; i < this.length ; i++) {
        yield this[i]
    }
}
</code>```

To answer the other question (is it defined as iterable in the spec?) the answer is yes:

The DOM spec defines NodeList as:

```<code>interface NodeList {
  getter Node? item(unsigned long index);
  readonly attribute unsigned long length;
  iterable<Node>;
};
</code>```

Note the third property, iterable<Node>;. Looking it up in the WebIDL spec:

In the ECMAScript language binding, an interface that is iterable will
  have “entries”, “forEach”, “keys”, “values” and @@iterator properties
  on its interface prototype object.

It seems that Edge doesn't implement any of that.

Body:
When looking at the ECMAScript compatibility table, it says that Edge 15 and Edge 16 support for ... of loops.

However, when I run this code:

const list = document.querySelectorAll('[data-test]');
console.log(list);

for (const item of list) {
  console.log(item);
}

It works in Chrome and Firefox, but not in Edge. Instead it says:

Object doesn't support property or method 'Symbol.iterator'.

As I understand it, NodeList actually should support it, right?

Here's a fildde to try it yourself: Test it online

Can somebody explain the problem or the mistake here?

Body:
If for..of is supported but Edge 15 forgot to add the behavior to NodeList, you could polyfill it yourself with very little code:

NodeList.prototype[Symbol.iterator] = function* () {
    for(var i = 0; i < this.length ; i++) {
        yield this[i]
    }
}

To answer the other question (is it defined as iterable in the spec?) the answer is yes:

The DOM spec defines NodeList as:

interface NodeList {
  getter Node? item(unsigned long index);
  readonly attribute unsigned long length;
  iterable<Node>;
};

Note the third property, iterable<Node>;. Looking it up in the WebIDL spec:

In the ECMAScript language binding, an interface that is iterable will
  have “entries”, “forEach”, “keys”, “values” and @@iterator properties
  on its interface prototype object.

It seems that Edge doesn't implement any of that.


问:
Filter stream using correlation between stream elements
Let’s say there’s a Person class that looks like this:

```<code>public class Person {
    private int id;
    private String discriminator;
    // some other fields plus getters/setters
}
</code>```

Now I have a Stream of Person elements and that stream may contain multiple Person instances that have same id, but different discriminator values, i.e. [Person{“id”: 1, “discriminator”: “A”}, Person{“id”: 1, “discriminator”: “B”}, Person{“id”: 2, “discriminator”: “A”}, ...]

What I’d like to do is to filter out all Person instances  with some id if there’s at least one Person instance with that id that has a particular discriminator value. So, continuing with the above example, filtering by discriminator value “A” would yield an empty collection (after the reduction operation, of course) and filtering by discriminator value “B” would yield a collection not containing any Person instance with id equal to 1.

I know I can reduce the stream using groupingBy collector and group elements by Person.id and then remove the mapping from the resulting Map if the mapped list contains a Person element with the specified discriminator value, but am still wondering if there’s a simpler way to achieve the same result?

答:
So below I present the solution that I've come up with. First I group the input Person collection/stream by the Person.id attribute and then I stream over the map entries and filter out those that have at least one value that matches given discriminator.</p>

```<code>import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
            new Person(1, "A"),
            new Person(1, "B"),
            new Person(1, "C"),
            new Person(2, "B"),
            new Person(2, "C"),
            new Person(3, "A"),
            new Person(3, "C"),
            new Person(4, "B")
        );

        System.out.println(persons);
        System.out.println(filterByDiscriminator(persons, "A"));
        System.out.println(filterByDiscriminator(persons, "B"));
        System.out.println(filterByDiscriminator(persons, "C"));
    }

    private static List<Person> filterByDiscriminator(List<Person> input, String discriminator) {
        return input.stream()
            .collect(Collectors.groupingBy(Person::getId))
            .entrySet().stream()
            .filter(entry -> entry.getValue().stream().noneMatch(person -> person.getDiscriminator().equals(discriminator)))
            .flatMap(entry -> entry.getValue().stream())
            .collect(Collectors.toList());
    }

}

class Person {

    private final Integer id;
    private final String discriminator;

    public Person(Integer id, String discriminator) {
        Objects.requireNonNull(id);
        Objects.requireNonNull(discriminator);
        this.id = id;
        this.discriminator = discriminator;
    }

    public Integer getId() {
        return id;
    }

    public String getDiscriminator() {
        return discriminator;
    }

    @Override
    public String toString() {
        return String.format("%s{\"id\": %d, \"discriminator\": \"%s\"}", getClass().getSimpleName(), id, discriminator);
    }
}
</code>```

Body:
Let’s say there’s a Person class that looks like this:

public class Person {
    private int id;
    private String discriminator;
    // some other fields plus getters/setters
}

Now I have a Stream of Person elements and that stream may contain multiple Person instances that have same id, but different discriminator values, i.e. [Person{“id”: 1, “discriminator”: “A”}, Person{“id”: 1, “discriminator”: “B”}, Person{“id”: 2, “discriminator”: “A”}, ...]

What I’d like to do is to filter out all Person instances  with some id if there’s at least one Person instance with that id that has a particular discriminator value. So, continuing with the above example, filtering by discriminator value “A” would yield an empty collection (after the reduction operation, of course) and filtering by discriminator value “B” would yield a collection not containing any Person instance with id equal to 1.

I know I can reduce the stream using groupingBy collector and group elements by Person.id and then remove the mapping from the resulting Map if the mapped list contains a Person element with the specified discriminator value, but am still wondering if there’s a simpler way to achieve the same result?

Body:
So below I present the solution that I've come up with. First I group the input Person collection/stream by the Person.id attribute and then I stream over the map entries and filter out those that have at least one value that matches given discriminator.

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
            new Person(1, "A"),
            new Person(1, "B"),
            new Person(1, "C"),
            new Person(2, "B"),
            new Person(2, "C"),
            new Person(3, "A"),
            new Person(3, "C"),
            new Person(4, "B")
        );

        System.out.println(persons);
        System.out.println(filterByDiscriminator(persons, "A"));
        System.out.println(filterByDiscriminator(persons, "B"));
        System.out.println(filterByDiscriminator(persons, "C"));
    }

    private static List<Person> filterByDiscriminator(List<Person> input, String discriminator) {
        return input.stream()
            .collect(Collectors.groupingBy(Person::getId))
            .entrySet().stream()
            .filter(entry -> entry.getValue().stream().noneMatch(person -> person.getDiscriminator().equals(discriminator)))
            .flatMap(entry -> entry.getValue().stream())
            .collect(Collectors.toList());
    }

}

class Person {

    private final Integer id;
    private final String discriminator;

    public Person(Integer id, String discriminator) {
        Objects.requireNonNull(id);
        Objects.requireNonNull(discriminator);
        this.id = id;
        this.discriminator = discriminator;
    }

    public Integer getId() {
        return id;
    }

    public String getDiscriminator() {
        return discriminator;
    }

    @Override
    public String toString() {
        return String.format("%s{\"id\": %d, \"discriminator\": \"%s\"}", getClass().getSimpleName(), id, discriminator);
    }
}


问:
Create a pdf for J2EE applications
Could you please anyone tell me the way to create a pdf document for J2EE Application other than iText.

We are previously used the iText, but the problem is the html file (which is generated from Jsp) display is different with the generated PDF. So I need some other way to create a pdf as same as jsp display.

Any one please suggest me the libraries other than iText?

Thanks in Advance.

答:
You are probably using iText 5 and XML Worker. Have you tried iText 7 and pdfHTML? See the HTML to PDF tutorial.

You will need:

iText 7: https://github.com/itext/itext7

the pdfHTML add-on: https://github.com/itext/i7j-pdfhtml

You claim:

the problem is the html file (which is generated from Jsp) display is different with the generated PDF.

That is certainly true when you use HTMLWorker (which you shouldn't) and it's true in many cases for XML Worker. But we rewrote iText from scratch because of the mismatch between the old iText architecture and the requirements when converting HTML to PDF.

If you have a problem with the HTML to PDF conversion, please explain the problem in a question and tag that question as an iText question. If we can improve iText 7 + pdfHTML, why wouldn't we do that?

Title: Create a pdf for J2EE applications


问:
missing image data
When I transfer data, I sometimes use bcp command.
Like this:

```<code>---Out
bcp dbname..tableName out tableName.bcp -Uuser -SSERVERNAME -n -Jiso88599

---IN
bcp dbname..tableName in tableName.bcp -Uuser -SSERVERNAME -n -Jiso88599
</code>```

I have a sybase ase db and I have transfered data with bcp commands.
There is an image column on the table. But When I transfered them image column data is missing.

Only a fraction has been transferred.

```<code>--- Prod
SELECT datalength(image_column) FROM dbo.tableName where id='5eb9f' --> 57375

--- TEST
SELECT datalength(image_column) FROM dbo.tableName where id='5eb9f' --> 32768
</code>```

Why?

答:
You have to set the size of the text/image data block with the -T parameter in bcp otherwise it defaults to 32768 bytes (or used to) which, as you have noticed, is not be big enough for your column's data. More info at:

http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc30191.1550/html/utility/X14951.htm

You can check the size of the largest row in that column via the below query then size appropriately, alternatively I tend to just set it as high as possible (i.e. just under 2GB) to ensure I get everything.

```<code>select max(datalength(column_name)) from table
</code>```

One word of warning - this will tablescan the whole table so don't run the query in a production environment on a big table.

Title: missing image data

Body:
When I transfer data, I sometimes use bcp command.
Like this:

---Out
bcp dbname..tableName out tableName.bcp -Uuser -SSERVERNAME -n -Jiso88599

---IN
bcp dbname..tableName in tableName.bcp -Uuser -SSERVERNAME -n -Jiso88599

I have a sybase ase db and I have transfered data with bcp commands.
There is an image column on the table. But When I transfered them image column data is missing.

Only a fraction has been transferred.

--- Prod
SELECT datalength(image_column) FROM dbo.tableName where id='5eb9f' --> 57375

--- TEST
SELECT datalength(image_column) FROM dbo.tableName where id='5eb9f' --> 32768

Why?

Body:
You have to set the size of the text/image data block with the -T parameter in bcp otherwise it defaults to 32768 bytes (or used to) which, as you have noticed, is not be big enough for your column's data. More info at:

http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc30191.1550/html/utility/X14951.htm

You can check the size of the largest row in that column via the below query then size appropriately, alternatively I tend to just set it as high as possible (i.e. just under 2GB) to ensure I get everything.

select max(datalength(column_name)) from table

One word of warning - this will tablescan the whole table so don't run the query in a production environment on a big table.


问:
scp a bunch of files via bash script: there must be a better way
I currently have the following bash script:

```<code>for a in `seq 16 75`;
do scp doneill@server:/mnt/device/folder/numbered_file$a.txt ./;
done;
</code>```

while this does work, it is very slow.  Each file, the request to the sever takes about 4-7 seconds, then sending the file takes another 3 or so seconds.

Is there a way to do this that involves only 1 command sent to the server (to minimize the time my VPN spends sending receiving each individual command)?  Normally, I would do something like scp doneill@server:/mnt/device/folder/numbered_file* but there are many thousands of files in the folder that I don't want to copy.  I need to get only those few (defined by the sequence).

答:
In bash:</p>

```<code>scp doneill@server:/mnt/device/folder/numbered_file{16..75}.txt ./
</code>```

Body:
I currently have the following bash script:

for a in `seq 16 75`;
do scp doneill@server:/mnt/device/folder/numbered_file$a.txt ./;
done;

while this does work, it is very slow.  Each file, the request to the sever takes about 4-7 seconds, then sending the file takes another 3 or so seconds.

Is there a way to do this that involves only 1 command sent to the server (to minimize the time my VPN spends sending receiving each individual command)?  Normally, I would do something like scp doneill@server:/mnt/device/folder/numbered_file* but there are many thousands of files in the folder that I don't want to copy.  I need to get only those few (defined by the sequence).

Body:
In bash:

scp doneill@server:/mnt/device/folder/numbered_file{16..75}.txt ./


问:
Reading large csv files using pandas with specifying dtypes giving memory error?
I am trying to read expedia data from Kaggle which contains a 4GB csv file I tried reading it using pd.read_csv('filename') and got memory error. Second approach I tried reading particular columns only using the code:

pd.read_csv('train.csv', dtype={'date_time':np.str, user_location_country': np.int32, 'user_location_region':np.int32, 'user_location_city':np.int32, 'orig_destination_distance':np.float64, 'user_id':np.int32})

this again gives me memory error but using another modification of the same method which is:

train = pd.read_csv('train.csv', dtype={'user_id':np.int32,'is_booking':bool, 'srch_destination_id':np.int32, 'hotel_cluster':np.int32},                usecols=['date_time', 'user_id', 'srch_ci', 'srch_co', 'srch_destination_id', 'is_booking', 'hotel_cluster'])'

reads the data in about 5 minutes.

My problem is I want to read more columns using any of the methods but both fails and gives Memory error. I am using 8GB RAM with 8GB swap space so reading only 7-8 columns out of 24 columns in the data will reduce the data size around 800MB so no issues on the hardware usage.
I also tried reading in chunks that I don't want to do based on the algorithms that I am going to read in the later part.

答:
Unfortunately, reading a csv file requires more memory than its size on the disk (I do not know how much more though).

You can find an alternative way to process your file here


问:
Gitkraken stuck at opening repo
Every time I open gitkrarken it gets stuck at opening repo icon. I can't open/clone/init repo.
I heard some others have the same problem but no one seems to know why this is happening and what the solution is.
Can anyone help with this?

UPDATE 1
Reinstalled it. Still having the same problem

答:
In our case there was a Latex document in the repository. Gitkraken could not open the repository.

Based on what @GeekyMonkey suggested, my student tried to start GitKraken after closing all files and shutting down his Tex editor.

It worked after that

Title: Gitkraken stuck at opening repo


问:
Sorting cyrillic words with accents
I experienced a problem with sorting array of strings written in the cyrilica (with accents). The following solution sorts the strings with and without diacritical marks separately at the beginning of the string.

```<code>function sorting(){
    let words = document.querySelectorAll(".dictionary");
    let unsorted = [];
    let collator = new Intl.Collator('ru', {sensitivity: 'base'});
    words.forEach(s => {
        unsorted.push(s.textContent);
    });
    unsorted.sort(collator.compare);
    unsorted.forEach(s => {
        document.write("<p>" + s + "</p>");
    });
}
</code>```

EDIT

This is array before sorting:

[..., 'áвтор', ..., 'авиабилéт', ..., 'янтáрный', ..., 'Áвстрия', 'áвтор', 'автостóп'];

this is after sorting:

["авиабилéт", "автостóп", ..., "янтáрный", ..., "Áвстрия", "áвтор"]

this is what I want to have

['авиабилéт', 'Áвстрия', 'áвтор', 'автостóп', ..., 'янтáрный', ...];

答: you have not provided sensitivity in options. Probably default value is 'variant'(I've tried in Chrome's console) while you need 'base'

Title: Sorting cyrillic words with accents

Body:
I experienced a problem with sorting array of strings written in the cyrilica (with accents). The following solution sorts the strings with and without diacritical marks separately at the beginning of the string.

function sorting(){
    let words = document.querySelectorAll(".dictionary");
    let unsorted = [];
    let collator = new Intl.Collator('ru', {sensitivity: 'base'});
    words.forEach(s => {
        unsorted.push(s.textContent);
    });
    unsorted.sort(collator.compare);
    unsorted.forEach(s => {
        document.write("
" + s + "
");
    });
}

EDIT

This is array before sorting:

[..., 'áвтор', ..., 'авиабилéт', ..., 'янтáрный', ..., 'Áвстрия', 'áвтор', 'автостóп'];

this is after sorting:

["авиабилéт", "автостóп", ..., "янтáрный", ..., "Áвстрия", "áвтор"]

this is what I want to have

['авиабилéт', 'Áвстрия', 'áвтор', 'автостóп', ..., 'янтáрный', ...];


问:
How to get a response number of a HTTPS request
I would like to make use of Linux command to get a response number of an HTTPS request rather than HTTP request. According to my current knowledge wget and curl can achieve the goal.

For instance, given the address https://asunnot.oikotie.fi/vuokrattavat-asunnot/espoo/13874872 I intend to use the following commands:

with curl: curl -I https://asunnot.oikotie.fi/vuokrattavat-asunnot/espoo/13874872

with wget: wget --spider -S 'https://asunnot.oikotie.fi/vuokrattavat-asunnot/espoo/13874872'

Both requests got the response as HTTP/1.1 405 Not Allowed. But when I try the address with a browser, e.g. Chrome, or Firefox etc. The page can indeed display without issue.

Anyone can help on it? How is it possible to get the correct response number rather than the first direct 405?

答:
With curl you need to set -A, --user-agent option as some HTTP servers/CGIs require the header User-Agent to be filled.

```<code>curl -I 'https://asunnot.oikotie.fi/vuokrattavat-asunnot/espoo/13874872' -A "Mozilla/5.0"
</code>```

The output:

```<code>HTTP/1.1 200 OK
Date: Tue, 14 Nov 2017 13:56:11 GMT
Content-Type: text/html
Connection: keep-alive
Server: nginx
Vary: Accept-Encoding
X-DB: 5
X-DW: 0
X-DZ: 93.72.75.166
X-VID: 93.72.75.166:14CDB9B4-DE01-3FAA-AFF5-65BC2F771745
Expires: Thu, 01 Jan 1970 00:00:01 GMT
Cache-Control: private, no-cache, no-store, must-revalidate
Edge-Control: no-store, bypass-cache
Surrogate-Control: no-store, bypass-cache
</code>```

-A, --user-agent <agent string>

                (HTTP) Specify the User-Agent string to send to the HTTP server. Some badly done CGIs fail if this field  isn't
                set  to  "Mozilla/4.0".  To  encode blanks in the string, surround the string with single quote marks. This can
                also be set with the -H, --header option of course.

Body:
With curl you need to set -A, --user-agent option as some HTTP servers/CGIs require the header User-Agent to be filled.

curl -I 'https://asunnot.oikotie.fi/vuokrattavat-asunnot/espoo/13874872' -A "Mozilla/5.0"

The output:

HTTP/1.1 200 OK
Date: Tue, 14 Nov 2017 13:56:11 GMT
Content-Type: text/html
Connection: keep-alive
Server: nginx
Vary: Accept-Encoding
X-DB: 5
X-DW: 0
X-DZ: 93.72.75.166
X-VID: 93.72.75.166:14CDB9B4-DE01-3FAA-AFF5-65BC2F771745
Expires: Thu, 01 Jan 1970 00:00:01 GMT
Cache-Control: private, no-cache, no-store, must-revalidate
Edge-Control: no-store, bypass-cache
Surrogate-Control: no-store, bypass-cache

-A, --user-agent <agent string>

                (HTTP) Specify the User-Agent string to send to the HTTP server. Some badly done CGIs fail if this field  isn't
                set  to  "Mozilla/4.0".  To  encode blanks in the string, surround the string with single quote marks. This can
                also be set with the -H, --header option of course.


问:
Apply Validation Rule to ListView's ItemsSource property
I'd like to validate a ListView by checking if the ItemsSource contains an empty collection. Here's the XAML.

```<code><ListView x:Name="lstvItemsInGroup"
            <ListView.ItemsSource>
                <Binding Path="ItemsInGroup" Mode="OneWay" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <local:CollectionNotEmptyValidationRule ErrorMessage="You must select at least one item" />
                    </Binding.ValidationRules>
                </Binding>
            </ListView.ItemsSource>

        </ListView>
</code>```

Here's the ValidationRule.

```<code>public class CollectionNotEmptyValidationRule : ValidationRule
    {
        public string ErrorMessage
        { get; set; }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        ValidationResult lResult = null;

        IEnumerable<object> lCollection = (IEnumerable<object>)value;
        if (lCollection == null || lCollection.Count() == 0)
        {
            lResult = new ValidationResult(false, ErrorMessage);
        }
        else
        {
            lResult = new ValidationResult(true, null);
        }

        return lResult;
    }
</code>```

I am forcing the validation upon loading the usercontrol with

```<code>lstvItemsInGroup.GetBindingExpression(ListView.ItemsSourceProperty).UpdateSource();
</code>```

But the ValidationRule isn't even called, I have a breakpoint in the first line and nothing.

Any clues?

Thank you.

答:
If you want to validate you should use the respective method instead of trying to update the source:</p>

```<code>BindingExpression.ValidateWithoutUpdate();
</code>```

Body:
I'd like to validate a ListView by checking if the ItemsSource contains an empty collection. Here's the XAML.

<ListView x:Name="lstvItemsInGroup"
            <ListView.ItemsSource>
                <Binding Path="ItemsInGroup" Mode="OneWay" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <local:CollectionNotEmptyValidationRule ErrorMessage="You must select at least one item" />
                    </Binding.ValidationRules>
                </Binding>
            </ListView.ItemsSource>

        </ListView>

Here's the ValidationRule.

public class CollectionNotEmptyValidationRule : ValidationRule
    {
        public string ErrorMessage
        { get; set; }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        ValidationResult lResult = null;

        IEnumerable<object> lCollection = (IEnumerable<object>)value;
        if (lCollection == null || lCollection.Count() == 0)
        {
            lResult = new ValidationResult(false, ErrorMessage);
        }
        else
        {
            lResult = new ValidationResult(true, null);
        }

        return lResult;
    }

I am forcing the validation upon loading the usercontrol with

lstvItemsInGroup.GetBindingExpression(ListView.ItemsSourceProperty).UpdateSource();

But the ValidationRule isn't even called, I have a breakpoint in the first line and nothing.

Any clues?

Thank you.

Body:
If you want to validate you should use the respective method instead of trying to update the source:

BindingExpression.ValidateWithoutUpdate();


问:
Navigation bar specific to each view controller like Apple Music
How do I have the navigation bar specific to each view controller? On the right side, the navigation bar stays with the view controller, and the left view controller has its own navigation controller. Should I just make a custom transition? Any ideas ?

答:
Add this code in your first viewController

```<code>override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.setNavigationBarHidden(false, animated: false)
}
</code>```

Then add navigationBar in your viewcontrollers from storyboad. Or you can add one in viewDidLoad programmatically

Body:
Add this code in your first viewController

override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.setNavigationBarHidden(false, animated: false)
}

Then add navigationBar in your viewcontrollers from storyboad. Or you can add one in viewDidLoad programmatically


问:
rendering texture from other class in libgdx
i am making a game in libgdx. I have a super class Monster with child classes of that monster (warrior,mage,..). I would like to render this Monster class (actually his child) in playScreen class. Each class has its own animaton and textures, damage/health values. How do i do that? In which class do i define position for rendering, animation of that monster? in child classes, super class or in playScreen?  My current code is here:

```<code>public class Monster {
public Animation monster;
public TextureAtlas atlas;
public int health;
public int damage;

public Monster(){

    atlas = new TextureAtlas(Gdx.files.internal("mons1.txt"));
    monster = new Animation(1/15f, atlas.getRegions());

}
</code>```

Child class:

```<code>public class Mage extends Monster {

public Mage(int health,int damage, Animation animation){

    super(health, damage, animation);

}
</code>```

PlayScreen class:

```<code>public class PlayScreen  implements Screen, InputProcessor {
private SpriteBatch batch;
public TextureAtlas atlas;
TextureRegion region;
private int height;
private Viewport viewport;
private Camera camera;
private int width;
private float elapsedTime = 0;
private Handler h;
private Stage stage;
private InputProcessor processor;

public PlayScreen(Handler h){
    this.h = h;
    batch = h.batch;
    camera = h.camera;
    viewport = h.viewport;
    height = h.height;
    width = h.width;
    region = new TextureRegion();
    stage = new Stage(viewport,batch);
    stateTime = 0f;

}
@Override
public void render(float delta) {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.setProjectionMatrix(camera.combined);
    batch.begin();

    batch.end();

}
</code>```

答:
Create base class that will have methods for all entities in your world.

For example let's give in name Entity. It will have only fields and methods that base for all monsters, creatures, player also, etc.

```<code>class Entity {

    protected int x;   // use getters/setters to get/change these fields
    protected int y;
    protected int width;
    protected int height;
    protected Texture texture;

    public Entity(Texture texture, int x, int y, int width, int height) {
        this.texture = texture;
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    void draw(SpriteBatch batch) {
        batch.draw(texture, x, y, width, height);
    }
}
</code>```

Now you can create base entity that will simple draw one texture always.

How to animate it? Create inheritor.

```<code>class AnimatedEntity extends Entity{

    protected float stateTimer = 0f;   // use getters/setters to get/change these fields
    protected Animation animation;

    public AnimatedEntity(Animation animation, int x, int y, int width, int height) {
        super(animation.getKeyFrames(0), x, y, width, height);  // calls parent constructor
        this.animation = animation;

    }

    @Override
    void draw(SpriteBatch batch) {
        texture = animation.getKeyFrame(stateTimer);  // texture from parent visible here
        super(batch); // calls draw method from Entity
    }
}
</code>```

Now you can extend Monster from AnimatedEntity class. To add attack method for example. Hope you got it. I mean principe.

How to draw all my entities?

Outside constructor :

```<code>ArrayList<Entity> entities;
</code>```

In constructor :

```<code>entities = new ArrayList<>();
AnimatedEntity mage = new AnimatedEntity(someAnimation, x, y, width, height);
entities.add(mage);
</code>```

In render(..) :

```<code>for (e in entities) {
    e.draw(batch);
}
</code>```

Body:
i am making a game in libgdx. I have a super class Monster with child classes of that monster (warrior,mage,..). I would like to render this Monster class (actually his child) in playScreen class. Each class has its own animaton and textures, damage/health values. How do i do that? In which class do i define position for rendering, animation of that monster? in child classes, super class or in playScreen?  My current code is here:

public class Monster {
public Animation monster;
public TextureAtlas atlas;
public int health;
public int damage;

public Monster(){

    atlas = new TextureAtlas(Gdx.files.internal("mons1.txt"));
    monster = new Animation(1/15f, atlas.getRegions());

}

Child class:

public class Mage extends Monster {

public Mage(int health,int damage, Animation animation){

    super(health, damage, animation);

}

PlayScreen class:

public class PlayScreen  implements Screen, InputProcessor {
private SpriteBatch batch;
public TextureAtlas atlas;
TextureRegion region;
private int height;
private Viewport viewport;
private Camera camera;
private int width;
private float elapsedTime = 0;
private Handler h;
private Stage stage;
private InputProcessor processor;

public PlayScreen(Handler h){
    this.h = h;
    batch = h.batch;
    camera = h.camera;
    viewport = h.viewport;
    height = h.height;
    width = h.width;
    region = new TextureRegion();
    stage = new Stage(viewport,batch);
    stateTime = 0f;

}
@Override
public void render(float delta) {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.setProjectionMatrix(camera.combined);
    batch.begin();

    batch.end();

}

Body:
Create base class that will have methods for all entities in your world.

For example let's give in name Entity. It will have only fields and methods that base for all monsters, creatures, player also, etc.

class Entity {

    protected int x;   // use getters/setters to get/change these fields
    protected int y;
    protected int width;
    protected int height;
    protected Texture texture;

    public Entity(Texture texture, int x, int y, int width, int height) {
        this.texture = texture;
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    void draw(SpriteBatch batch) {
        batch.draw(texture, x, y, width, height);
    }
}

Now you can create base entity that will simple draw one texture always.

How to animate it? Create inheritor.

class AnimatedEntity extends Entity{

    protected float stateTimer = 0f;   // use getters/setters to get/change these fields
    protected Animation animation;

    public AnimatedEntity(Animation animation, int x, int y, int width, int height) {
        super(animation.getKeyFrames(0), x, y, width, height);  // calls parent constructor
        this.animation = animation;

    }

    @Override
    void draw(SpriteBatch batch) {
        texture = animation.getKeyFrame(stateTimer);  // texture from parent visible here
        super(batch); // calls draw method from Entity
    }
}

Now you can extend Monster from AnimatedEntity class. To add attack method for example. Hope you got it. I mean principe.

How to draw all my entities?

Outside constructor :

ArrayList<Entity> entities;

In constructor :

entities = new ArrayList<>();
AnimatedEntity mage = new AnimatedEntity(someAnimation, x, y, width, height);
entities.add(mage);

In render(..) :

for (e in entities) {
    e.draw(batch);
}