问:
How to convert JSON Bytes in Javascript
I have inherited a somewhat large, Java- based server- side codebase that communicates with clients using JSON. For several reasons,
the Jackson- based JSON conversions must use the binary form -- in other words, the JSON that I am generating on the server
side is made up of bytes, not characters.

This was not a problem with previous clients, because they were all Java based. I could use the Jackson libraries to convert the binary back into objects. Unfortunately, I have been asked to create some browser- based clients that require the use of Javascript in order to receive and display the JSON information.

I am attempting to use JQuery's JSON conversion functions, but it turns out that neither JQuery nor the regular Javascript functions are capable of converting a set of JSON bytes back into an object. I need to convert the bytes back into characters in order to convert them back into objects.

I learned that in order to convert bytes into characters, I have to get the bytes into a byte array. This is where I am having the problems.

I have been trying to use various methods to convert the binary JSON information back into a form (a byte array) that can be converted into a meaningful object using the JSON conversion functions. I have tried using the ArrayBuffer to convert the data into a byte buffer, then the int8Array() function to create a byte array:

```<code>var buffer = new ArrayBuffer(obj.payload.length);
var bits =  new Int8Array(buffer);
</code>```

I also attempted to use uint8Array(), and tried various other conversion routines found on the Internet (and here in Stack Overflow) in order to create the array that can be converted into meaningful characters. All my attempts have either caused errors and failures at runtime, or have generated garbage that breaks the JSON converters.

Is there some way to get Javascript to read a set of bytes generated by Jackson so that they can be converted back to objects using the JSON converters? Or is Javascript only capable of converting JSON strings?

Someone please advise...

答:
Assume your binary JSON is something like this:

[123, 34, 107, 101, 121, 34, 58, 34, 118, 97, 108, 117, 101, 34, 125]

you could easily convert it to a string:

var str = String.fromCharCode.apply(String, data);

and parse that with the JSON objects parse:

JSON.parse(str);

jsfiddle

Title: How to convert JSON Bytes in Javascript

Body:
I have inherited a somewhat large, Java- based server- side codebase that communicates with clients using JSON. For several reasons,
the Jackson- based JSON conversions must use the binary form -- in other words, the JSON that I am generating on the server
side is made up of bytes, not characters.

This was not a problem with previous clients, because they were all Java based. I could use the Jackson libraries to convert the binary back into objects. Unfortunately, I have been asked to create some browser- based clients that require the use of Javascript in order to receive and display the JSON information.

I am attempting to use JQuery's JSON conversion functions, but it turns out that neither JQuery nor the regular Javascript functions are capable of converting a set of JSON bytes back into an object. I need to convert the bytes back into characters in order to convert them back into objects.

I learned that in order to convert bytes into characters, I have to get the bytes into a byte array. This is where I am having the problems.

I have been trying to use various methods to convert the binary JSON information back into a form (a byte array) that can be converted into a meaningful object using the JSON conversion functions. I have tried using the ArrayBuffer to convert the data into a byte buffer, then the int8Array() function to create a byte array:

var buffer = new ArrayBuffer(obj.payload.length);
var bits =  new Int8Array(buffer);

I also attempted to use uint8Array(), and tried various other conversion routines found on the Internet (and here in Stack Overflow) in order to create the array that can be converted into meaningful characters. All my attempts have either caused errors and failures at runtime, or have generated garbage that breaks the JSON converters.

Is there some way to get Javascript to read a set of bytes generated by Jackson so that they can be converted back to objects using the JSON converters? Or is Javascript only capable of converting JSON strings?

Someone please advise...


来源: stackexchange

问:
find common and different elements between two List in java
I want to get the below

 1. common elements between two list.

 2. Elements in ListB which is not available in ListA

 3. Elements in ListA which is not available in ListB

```<code>List<String> fruitsListA = new ArrayList<String>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Grapes");
List<String> fruitsListACopy = fruitsListA;

List<String> fruitsListB = new ArrayList<String>();
fruits.add("Strawberry");
fruits.add("Cranberry");
fruits.add("Orange");
fruits.add("Apple");
List<String> fruitsListBCopy = fruitsListB;

1. common elements between two list

    fruitsListACopy.retainAll(fruitsListB);

2. Elements in ListB which is not available in ListA

    fruitsListB.removeAll(fruitsListA);

3. Elements in ListA which is not available in ListB

    fruitsListA.removeAll(fruitsListBCopy);
</code>```

case 1 : Im able to get the common items in both the list. So If I print fruitsListACopy it gives ['Apple']

case 2 : I could see fruitsListA got modified automatically I mean instead of having all the items ['Apple','Banana','Grapes'] it has only common item
['Apple'] .

case 3: I could see fruitsListB got modified automatically I mean instead of having all the items ['Strawberry','Cranberry','Orange','Apple'] it has only
['Strawberry','Cranberry','Orange'] with the removal of coomon item which is Apple.

I could even see fruitsListA got modified automatically I mean instead of having all the items ['Apple','Banana','Grapes'] it has only common item
['Apple'] .

The changes done in the copied list gets reflects in original list when I use removeAll and retainAll methods.

Is there any other best way to meet this need?

答:
Creating a new instance instead of assigning the same object to another reference.

For example, you can replace :

```<code>    List<String> fruitsListACopy = fruitsListA;
</code>```

by

```<code>    List<String> fruitsListACopy = new ArrayList<>(fruitsListA);
</code>```

If you don't want side effects between operations on the copied lists, you have to create a new copy of the original list before each operation on it.

Then you have to call retainAll() and removeAll() on the copied lists and  provide as parameter to the methods the original lists.

Here is a sample code to illustrate :

```<code>public static void main(String[] args) {
    List<String> fruitsListA = new ArrayList<String>();
    fruitsListA.add("Apple");
    fruitsListA.add("Banana");
    fruitsListA.add("Grapes");

    List<String> fruitsListB = new ArrayList<String>();
    fruitsListB.add("Strawberry");
    fruitsListB.add("Cranberry");
    fruitsListB.add("Orange");
    fruitsListB.add("Apple");

    // copy for A
    List<String> fruitsListACopy = new ArrayList<>(fruitsListA);
    fruitsListACopy.retainAll(fruitsListB);
    // handle the result of fruitsListACopy
    System.out.println("fruitsListACopy="+fruitsListACopy);

    // copy for B
    List<String> fruitsListBCopy = new ArrayList<>(fruitsListB);
    fruitsListBCopy.removeAll(fruitsListA);
    // handle the result of fruitsListBCopy
    System.out.println("fruitsListBCopy="+fruitsListBCopy);

    // copy for A
    fruitsListACopy = new ArrayList<>(fruitsListA);
    fruitsListACopy.removeAll(fruitsListB);
    // handle the result of fruitsListACopy
    System.out.println("fruitsListACopy="+fruitsListACopy);
}
</code>```

Output :

fruitsListACopy=[Apple]

fruitsListBCopy=[Strawberry, Cranberry, Orange]

fruitsListACopy=[Banana, Grapes]

ContentLicense: CC BY-SA 3.0

Body:
I want to get the below

 1. common elements between two list.

 2. Elements in ListB which is not available in ListA

 3. Elements in ListA which is not available in ListB

List<String> fruitsListA = new ArrayList<String>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Grapes");
List<String> fruitsListACopy = fruitsListA;

List<String> fruitsListB = new ArrayList<String>();
fruits.add("Strawberry");
fruits.add("Cranberry");
fruits.add("Orange");
fruits.add("Apple");
List<String> fruitsListBCopy = fruitsListB;

1. common elements between two list

    fruitsListACopy.retainAll(fruitsListB);

2. Elements in ListB which is not available in ListA

    fruitsListB.removeAll(fruitsListA);

3. Elements in ListA which is not available in ListB

    fruitsListA.removeAll(fruitsListBCopy);

case 1 : Im able to get the common items in both the list. So If I print fruitsListACopy it gives ['Apple']

case 2 : I could see fruitsListA got modified automatically I mean instead of having all the items ['Apple','Banana','Grapes'] it has only common item
['Apple'] .

case 3: I could see fruitsListB got modified automatically I mean instead of having all the items ['Strawberry','Cranberry','Orange','Apple'] it has only
['Strawberry','Cranberry','Orange'] with the removal of coomon item which is Apple.

I could even see fruitsListA got modified automatically I mean instead of having all the items ['Apple','Banana','Grapes'] it has only common item
['Apple'] .

The changes done in the copied list gets reflects in original list when I use removeAll and retainAll methods.

Is there any other best way to meet this need?

Body:
Creating a new instance instead of assigning the same object to another reference.

For example, you can replace :

    List<String> fruitsListACopy = fruitsListA;

by

    List<String> fruitsListACopy = new ArrayList<>(fruitsListA);

If you don't want side effects between operations on the copied lists, you have to create a new copy of the original list before each operation on it.

Then you have to call retainAll() and removeAll() on the copied lists and  provide as parameter to the methods the original lists.

Here is a sample code to illustrate :

public static void main(String[] args) {
    List<String> fruitsListA = new ArrayList<String>();
    fruitsListA.add("Apple");
    fruitsListA.add("Banana");
    fruitsListA.add("Grapes");

    List<String> fruitsListB = new ArrayList<String>();
    fruitsListB.add("Strawberry");
    fruitsListB.add("Cranberry");
    fruitsListB.add("Orange");
    fruitsListB.add("Apple");

    // copy for A
    List<String> fruitsListACopy = new ArrayList<>(fruitsListA);
    fruitsListACopy.retainAll(fruitsListB);
    // handle the result of fruitsListACopy
    System.out.println("fruitsListACopy="+fruitsListACopy);

    // copy for B
    List<String> fruitsListBCopy = new ArrayList<>(fruitsListB);
    fruitsListBCopy.removeAll(fruitsListA);
    // handle the result of fruitsListBCopy
    System.out.println("fruitsListBCopy="+fruitsListBCopy);

    // copy for A
    fruitsListACopy = new ArrayList<>(fruitsListA);
    fruitsListACopy.removeAll(fruitsListB);
    // handle the result of fruitsListACopy
    System.out.println("fruitsListACopy="+fruitsListACopy);
}

Output :

fruitsListACopy=[Apple]

fruitsListBCopy=[Strawberry, Cranberry, Orange]

fruitsListACopy=[Banana, Grapes]


问:
Does the datamapper convert the SGBD result as an object?
I am working with MySql and results/rows are returned within an array.

I do understand that in the end, the model layer "goal" is to return an object once the SGBD query is processed.

So, should the process of converting rows (or a single row) into an object be integrated in the DataMapper (which is part of the Model layer) or should it be the responsibility of a third service that would be injected in the DataMapper?

Thank you

答:
So, should the process of converting rows (or a single row) into an
  object be integrated in the DataMapper.

Well yes it's the responsibility of the data mapper. It should return an entity, not a result set.

or should it be the responsibility of a third service that would be injected in the DataMapper?

This is also a possibility, google to "UnitOfWork" I think that's what you are looking for.
https://www.sitepoint.com/implementing-a-unit-of-work/

You can also take a look at the doctrine source
https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/EntityManager.php


问:
Extract body text from Email PHP
I am currently using an imap stream to get emails from an inbox.

Everything is working fine except I am unsure how to get the body text and title of the email.  If I do imap_body($connection,$message) the base 64 equivalent of the email attachment is included in the text.

I am currently using this function to get the attachments.

http://www.electrictoolbox.com/function-extract-email-attachments-php-imap/

答:
My solution (works with all types and charset) :</p>

```<code>function format_html($str) {
    // Convertit tous les caractères éligibles en entités HTML en convertissant les codes ASCII 10 en $lf
    $str = htmlentities($str, ENT_COMPAT, "UTF-8");
    $str = str_replace(chr(10), "<br>", $str);
    return $str;
}

// Start

$obj_structure = imap_fetchstructure($imapLink, $obj_mail->msgno);

// Recherche de la section contenant le corps du message et extraction du contenu
$obj_section = $obj_structure;
$section = "1";
for ($i = 0 ; $i < 10 ; $i++) {
    if ($obj_section->type == 0) {
        break;
    } else {
        $obj_section = $obj_section->parts[0];
        $section.= ($i > 0 ? ".1" : "");
    }
}
$text = imap_fetchbody($imapLink, $obj_mail->msgno, $section);
// Décodage éventuel
if ($obj_section->encoding == 3) {
    $text = imap_base64($text);
} else if ($obj_section->encoding == 4) {
    $text = imap_qprint($text);
}
// Encodage éventuel
foreach ($obj_section->parameters as $obj_param) {
    if (($obj_param->attribute == "charset") && (mb_strtoupper($obj_param->value) != "UTF-8")) {
        $text = utf8_encode($text);
        break;
    }
}

// End
print format_html($text);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Extract body text from Email PHP

Body:
My solution (works with all types and charset) :

function format_html($str) {
    // Convertit tous les caractères éligibles en entités HTML en convertissant les codes ASCII 10 en $lf
    $str = htmlentities($str, ENT_COMPAT, "UTF-8");
    $str = str_replace(chr(10), "<br>", $str);
    return $str;
}

// Start

$obj_structure = imap_fetchstructure($imapLink, $obj_mail->msgno);

// Recherche de la section contenant le corps du message et extraction du contenu
$obj_section = $obj_structure;
$section = "1";
for ($i = 0 ; $i < 10 ; $i++) {
    if ($obj_section->type == 0) {
        break;
    } else {
        $obj_section = $obj_section->parts[0];
        $section.= ($i > 0 ? ".1" : "");
    }
}
$text = imap_fetchbody($imapLink, $obj_mail->msgno, $section);
// Décodage éventuel
if ($obj_section->encoding == 3) {
    $text = imap_base64($text);
} else if ($obj_section->encoding == 4) {
    $text = imap_qprint($text);
}
// Encodage éventuel
foreach ($obj_section->parameters as $obj_param) {
    if (($obj_param->attribute == "charset") && (mb_strtoupper($obj_param->value) != "UTF-8")) {
        $text = utf8_encode($text);
        break;
    }
}

// End
print format_html($text);


问:
Heroku router log parameter description
Heroku router log has 10 parameters and descriptions are in https://devcenter.heroku.com/articles/http-routing#heroku-router-log-format.
one of the parameter is service.It described like amount of time in milliseconds spent proxying data between the backend web process and the client.
Is service time is response time of the request or what it is? Could anyone explain?

答:
No. Service is the amount of time spent within the Heroku Router.

That router sits between your app and an AWS ELB, and know how to route a request to the right dyno depending on the provided hostname.

Title: Heroku router log parameter description


问:
Convert "informal" month-day index to a datetime index
I have a series whose index is in month-day format. It is not officially a datetime index. In addition, the series contains one datum for each day of the year:

```<code>       Data_Value
01-01         156
01-02         139
01-03         133
01-04         106
01-05         128
01-06         189
</code>```

My goal is to make a line plot with the "Data_Value" in the y-axis and the twelve months in the x-axis. But I want to plot the 365 data, not aggregate them into 12 months. Something like this:

Anyway, my first movement has been to plot the 365 data ignoring the fact of putting the months names in the x-axis:

```<code>s = np.array(s)
plt.figure()
plt.plot(s, '-o')
</code>```

But in the last command I got the error "ValueError: could not convert string to float: '12-31'".

Does anybody how to convert "informal" month-day index to a datetime index omitting the year? Or any other solution to reach my final goal of plotting the series? Thx.

答:
This is what I have done, as jezrael suggested:

Add one random year to index to convert it to datetime index:

```<code>s.index = '2014-' + s.index.astype(str)
s.index = pd.to_datetime(s.index)
days_s = s.index
days_s = np.array(days_s)
</code>```

Then set and draw the plot:

```<code>plt.figure()
plt.plot(days_s, s, '-o')
</code>```

And change x-axis from %y-%m-%d to %m format using mdates.DateFormatter:

```<code>import matplotlib.dates as mdates
monthsFmt = mdates.DateFormatter('%m')
plt.gca().xaxis.set_major_formatter(monthsFmt)
</code>```

Finally, render plot:

```<code>plt.show()
</code>```

I do not know if this solution is a bit sloppy but it works.

Body:
I have a series whose index is in month-day format. It is not officially a datetime index. In addition, the series contains one datum for each day of the year:

       Data_Value
01-01         156
01-02         139
01-03         133
01-04         106
01-05         128
01-06         189

My goal is to make a line plot with the "Data_Value" in the y-axis and the twelve months in the x-axis. But I want to plot the 365 data, not aggregate them into 12 months. Something like this:

Anyway, my first movement has been to plot the 365 data ignoring the fact of putting the months names in the x-axis:

s = np.array(s)
plt.figure()
plt.plot(s, '-o')

But in the last command I got the error "ValueError: could not convert string to float: '12-31'".

Does anybody how to convert "informal" month-day index to a datetime index omitting the year? Or any other solution to reach my final goal of plotting the series? Thx.

Body:
This is what I have done, as jezrael suggested:

Add one random year to index to convert it to datetime index:

s.index = '2014-' + s.index.astype(str)
s.index = pd.to_datetime(s.index)
days_s = s.index
days_s = np.array(days_s)

Then set and draw the plot:

plt.figure()
plt.plot(days_s, s, '-o')

And change x-axis from %y-%m-%d to %m format using mdates.DateFormatter:

import matplotlib.dates as mdates
monthsFmt = mdates.DateFormatter('%m')
plt.gca().xaxis.set_major_formatter(monthsFmt)

Finally, render plot:

plt.show()

I do not know if this solution is a bit sloppy but it works.


问:
Select tag not including options after the first time
Relatively new to php, I want to fetch a column named make for which i am using a loop and mysqli_fetch_row to fetch each row from the column and then i am inserting the data into a select tag. The problem I am facing is that it inserts the data into the options tag the first time, and after that it just echos it out of the list.
Here is the code for it,

```<code>$SQLstring = "select make from inventory";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("<p>Unable to query the $TableName table.</p>"."<p>Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
//$row= mysqli_fetch_all($queryResult);
$i=0;
echo"<label for='make'>Please select a make:</label>
<select>
    <option name='make' value='All'>All</option>";
    while($row= mysqli_fetch_row($queryResult)){
    echo"<option value='$row[$i]'>$row[$i]</option>
</select>";
    }
</code>```

What to d0 here?

答:
As already stated in the comments, the probable problem is the placement of your </select>.

Try this:

```<code>echo "<label for='make'>Please select a make:</label><select>";
echo "<option name='make' value='All'>All</option>";
while($row= mysqli_fetch_row($queryResult))
    echo "<option value='$row[$i]'>$row[$i]</option>";
echo "</select>";
</code>```

Like this, it will only output 'select' once after the options.

As an additional hint, I suggest looking into debugging tools like 'Firebug', which will help you a long way finding problems like these by letting you examine the HTML behind the page you're seeing.

Body:
Relatively new to php, I want to fetch a column named make for which i am using a loop and mysqli_fetch_row to fetch each row from the column and then i am inserting the data into a select tag. The problem I am facing is that it inserts the data into the options tag the first time, and after that it just echos it out of the list.
Here is the code for it,

$SQLstring = "select make from inventory";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("
Unable to query the $TableName table.
"."
Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "
";
//$row= mysqli_fetch_all($queryResult);
$i=0;
echo"Please select a make:
<select>
    <option name='make' value='All'>All</option>";
    while($row= mysqli_fetch_row($queryResult)){
    echo"<option value='$row[$i]'>$row[$i]</option>
</select>";
    }

What to d0 here?

Body:
As already stated in the comments, the probable problem is the placement of your </select>.

Try this:

echo "<label for='make'>Please select a make:</label><select>";
echo "<option name='make' value='All'>All</option>";
while($row= mysqli_fetch_row($queryResult))
    echo "<option value='$row[$i]'>$row[$i]</option>";
echo "</select>";

Like this, it will only output 'select' once after the options.

As an additional hint, I suggest looking into debugging tools like 'Firebug', which will help you a long way finding problems like these by letting you examine the HTML behind the page you're seeing.


问:
yylval undefined with flex and bison
I have searched almost every material online. But I am still confused why lexer cannot identify yylval.

Here is the case:
I have defined a bunch of ADT in node.h and realize them in node.c, my purpose is to generate a AST after these structures are properly stored. But I am stucked with bison file.

First, I change %union to union YYSTYPE {...}; and typedef union YYSTYPE YYSTYPE;, I don't why I need to do this, some other files posted online seems to work well with %uinion.

Then, I am stucked with yylval things. I have done bison -d things, and checked it already in parser.c(I have specified the bison output), so I think extern YYSTYPE yylval; should work. But it doesn't. So I wonder if there is another way to solve yylval undeclared problem.

I only use the two types of YYSTYPE struct, int and char *, can I separate the union YYSYTPE and struct for the AST? This means, the nonterminals will have no associated types. Do you guys have any other ideas??

答:
Do you have %pure-parser (or similar) set in your .y file? This disables the normal lex declarations, as they are not re-entrant.

https://www.gnu.org/software/bison/manual/html_node/Pure-Decl.html

Title: yylval undefined with flex and bison


问:
Custom google maps infowindow using ionic 2
I am new to ionic 2, I am trying to create a custom info window, so when a user clicks on a marker they can see some basic information like a picture and the name of the location, but they can also click on a link in the infoWindow that opens a modal with details on that location. Here is how i want to add it to my marker. </p>

```<code>addMarker(lat: number, lng: number, place: any): void {
    let latLng = new google.maps.LatLng(lat, lng);

    let marker = new google.maps.Marker({
        map: this.map,
        animation: google.maps.Animation.DROP,
        position: latLng,
        title: place.name
    });

    let infoWindow = new google.maps.InfoWindow({
       content: `<>custom template here with some basic details</>`
    });

    marker.addListener('click', ()=> {
       infoWindow.open(this.map, marker);

    });

    this.markers.push(marker);
}
</code>```

答:
If you don't want to use any external library then you can see below example. You need to add addEventListener when infowindow is ready.Because when infowindow is ready you can find the component by document.getElementById('id').

```<code>let infoWindow = new google.maps.InfoWindow({
    content :  `<p id = "myid">Click</p>`
});
google.maps.event.addListenerOnce(infoWindow, 'domready', () => {
    document.getElementById('myid').addEventListener('click', () => {
            alert('Clicked');
        });
});
</code>```

Body:
I am new to ionic 2, I am trying to create a custom info window, so when a user clicks on a marker they can see some basic information like a picture and the name of the location, but they can also click on a link in the infoWindow that opens a modal with details on that location. Here is how i want to add it to my marker.

addMarker(lat: number, lng: number, place: any): void {
    let latLng = new google.maps.LatLng(lat, lng);

    let marker = new google.maps.Marker({
        map: this.map,
        animation: google.maps.Animation.DROP,
        position: latLng,
        title: place.name
    });

    let infoWindow = new google.maps.InfoWindow({
       content: `<>custom template here with some basic details</>`
    });

    marker.addListener('click', ()=> {
       infoWindow.open(this.map, marker);

    });

    this.markers.push(marker);
}

Body:
If you don't want to use any external library then you can see below example. You need to add addEventListener when infowindow is ready.Because when infowindow is ready you can find the component by document.getElementById('id').

let infoWindow = new google.maps.InfoWindow({
    content :  `<p id = "myid">Click</p>`
});
google.maps.event.addListenerOnce(infoWindow, 'domready', () => {
    document.getElementById('myid').addEventListener('click', () => {
            alert('Clicked');
        });
});


问:
$uibModal backdrop false not working
Need a semi transparent background outside the modal area.W hat I get is Opaque white area.Tried setting backdrop:false dint work.

```<code>    var confirmInstance = $uibModal.open({
    animation: true,
    ariaLabelledBy: 'modal-title',
    ariaDescribedBy: 'modal-body',
    templateUrl: 'abc.html',
    size: 'sm',
    backdrop: false,
    controller:function($uibModalInstance){
                this.cancel = function() {
                    $uibModalInstance.dismiss('cancel');
                };
                this.ok=function(){
                }
    },
    controllerAs:'$ctrl',
    resolve: {
                items: function () {
                console.log("In resolve");
            }
    }
    });
</code>```

Below is my Html code for modal:

```<code>    <div><h1>Welcome here.. doing some more displaying stuff</h1></div>
        <script type="text/ng-template" id="abc.html">
            <div class="modal-header">
            Remove {{$ctrl.type}}
                 <button type="button" class="close" data-dismiss="modal" ng-click="$ctrl.cancel()">×</button>
            </div>
            <div class="modal-body" id="modal-body">
               <p>Confirm request for removal of {{$ctrl.type}} {{$ctrl.name}}?</p>
            </div>
            <div class="modal-footer">
                <button class="btn-revoke" type="button" ng-click="$ctrl.ok()">Ok</button>
                <button class="btn-cancel" type="button" ng-click="$ctrl.cancel()">Cancel</button>
            </div>
        </script>
</code>```

答: Remove backdrop: false. Because the default behaviour is to show semi-transparent background.</p>

Title: $uibModal backdrop false not working

Body:
Need a semi transparent background outside the modal area.W hat I get is Opaque white area.Tried setting backdrop:false dint work.

    var confirmInstance = $uibModal.open({
    animation: true,
    ariaLabelledBy: 'modal-title',
    ariaDescribedBy: 'modal-body',
    templateUrl: 'abc.html',
    size: 'sm',
    backdrop: false,
    controller:function($uibModalInstance){
                this.cancel = function() {
                    $uibModalInstance.dismiss('cancel');
                };
                this.ok=function(){
                }
    },
    controllerAs:'$ctrl',
    resolve: {
                items: function () {
                console.log("In resolve");
            }
    }
    });

Below is my Html code for modal:

Welcome here.. doing some more displaying stuff


问:
how to do multiple sums in single query
let's say that I have this tables :

table num1 :

```<code>+----+-----+
| no | val |
+----+-----+
| 1  | 10  |
| 2  | 15  |
| 3  | 20  |
+----+-----+
</code>```

table num2:

```<code>+----+-----+
| no | tot |
+----+-----+
| 1  | 15  |
| 2  | 20  |
| 3  | 25  |
+----+-----+
</code>```

so, i want to select sum value of table nu1.val and table num2.tot in single query

```<code> Select sum(a.val),sum(b.tot) from num1 a, num2 b
</code>```

the query is not working
please help

答:
Join those 2 tables on No column then sum it.</p>

```<code>select sum(n1.val),sum(n2.tot) from num1 n1 join num2 n2 on n1.no=n2.no
</code>```

Title: how to do multiple sums in single query

Body:
let's say that I have this tables :

table num1 :

+----+-----+
| no | val |
+----+-----+
| 1  | 10  |
| 2  | 15  |
| 3  | 20  |
+----+-----+

table num2:

+----+-----+
| no | tot |
+----+-----+
| 1  | 15  |
| 2  | 20  |
| 3  | 25  |
+----+-----+

so, i want to select sum value of table nu1.val and table num2.tot in single query

 Select sum(a.val),sum(b.tot) from num1 a, num2 b

the query is not working
please help

Body:
Join those 2 tables on No column then sum it.

select sum(n1.val),sum(n2.tot) from num1 n1 join num2 n2 on n1.no=n2.no


问:
Unity2.0 - Is it possible to specify assemblies and namespaces for type lookup programatically?
I am using Unity2 with XML configuration. It has the neat feature to specify namespaces and assemblies in the XML config for which automatic type lookup is performed, so that you do not need to always specify full name or create an alias.

Is it possible to specify assemblies and namespaces for the automatic type lookup programatically, without them being explicitly listed in the XML configuration? My goal is to simplify the XML configuration for my application's administrators. Types from two or three namespaces will almost always be used in the container registrations, so I would like these namespaces to be included in the lookup automatically.

答:
There's nothing built in explicitly to support this.

An option would require a few more steps in your code. instead of just calling container.LoadConfiguration(), you'd instead explicitly grab the configuration section:

```<code>var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
</code>```

Then, you'd go into the Namespaces or Assemblies properties on the section, and add new NamespaceElement or AssemblyElement objects pointing at the "standard" namespaces and assemblies. Then you apply the updated configuration section to the container. Something like this:

```<code>section.Namespaces.Add(new NamespaceElement() { Name = "my.standard.namespace" });
container.LoadConfiguration(section);
</code>```

I haven't actually tried this, :-), but it should work.

ContentLicense: CC BY-SA 2.5

Body:
There's nothing built in explicitly to support this.

An option would require a few more steps in your code. instead of just calling container.LoadConfiguration(), you'd instead explicitly grab the configuration section:

var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

Then, you'd go into the Namespaces or Assemblies properties on the section, and add new NamespaceElement or AssemblyElement objects pointing at the "standard" namespaces and assemblies. Then you apply the updated configuration section to the container. Something like this:

section.Namespaces.Add(new NamespaceElement() { Name = "my.standard.namespace" });
container.LoadConfiguration(section);

I haven't actually tried this, :-), but it should work.


问:
Detect Sub-Object in a image
Currently, I am reading the literature for object detection with deepl learning algorithms, and i founded many methods like "Fast-CNN, Faster-RCNN, YOLO9000", but I have a question, does he exist a method that can detect object and sub-object for example "we detect a person and his hand, his feet and so on ..."

Please if anyone know something about that please advice me

"I use Tensorflow for my implementation"

Thanks

答:
Such methods do exist! Note that detecting the class of an object from an image using neural networks is "easier" than detecting exactly what body part is where. This would require you to have a model for each body part, and an algorithm that determines where this body part is located (not an easy task!).

One example of a paper from 2014 that proposes a model is this one: http://www.cv-foundation.org/openaccess/content_cvpr_2014/papers/Chen_Detect_What_You_2014_CVPR_paper.pdf . Note that there are many approaches to this problem, so you should do a bit of literature study to find the one that best suits your problem!

Good luck!

Title: Detect Sub-Object in a image


问:
zsh run command if process is running
I want to get some info from cmus-remote if cmus is running

```<code>#!/bin/zsh

pgrep cmus>& /dev/null
if [ $? -eq 0 ]; then
  title=$(cmus-remote -Q | grep tag | grep title | sed 's/tag title //')
  artist=$(cmus-remote -Q | grep tag | grep " artist " | sed 's/tag artist //')
  album=$(cmus-remote -Q | grep tag | grep " album " | sed 's/tag album //')
  track=$(cmus-remote -Q | grep tag | grep tracknumber | sed 's/tag tracknumber //')
  echo $track $title - $artist - $album
else
  echo ""
fi
</code>```

the output for a running cmus is correct, when cmus isn't running I get

```<code>cmus-remote: cmus is not running
cmus-remote: cmus is not running
cmus-remote: cmus is not running
cmus-remote: cmus is not running
-
</code>```

I have a workaround by appending >& /dev/null on each corresponding line but that's not what I want, I would like the code not to be executed at all. And I don't the output from the else case.

答:
```<code>pgrep cmus>& /dev/null
if [ $? -eq 0 ]; then
  title=$(cmus-remote -Q | grep tag | grep title | sed 's/tag title //') > /dev/null 2>&1
  artist=$(cmus-remote -Q | grep tag | grep " artist " | sed 's/tag artist //') > /dev/null 2>&1
  album=$(cmus-remote -Q | grep tag | grep " album " | sed 's/tag album //') > /dev/null 2>&1
  track=$(cmus-remote -Q | grep tag | grep tracknumber | sed 's/tag tracknumber //') >/ dev/null 2>&1
  echo $track $title - $artist - $album
else
  echo ""
fi
</code>```

Adding > /dev/null 2>&1

2 refers to the second file descriptor of the process, i.e. stderr.

> means redirection.

&1 means the target of the redirection should be the same location as the first file descriptor, i.e. stdout.

So this command first redirects stdout to /dev/null and then redirects stderr there as well. This effectively silences all output (regular or error).

In your case cmus-remote: cmus is not running is an stderr so the redirection that you should use should be able to redirect both STDOUT and STDERR

Title: zsh run command if process is running

Body:
I want to get some info from cmus-remote if cmus is running

#!/bin/zsh

pgrep cmus>& /dev/null
if [ $? -eq 0 ]; then
  title=$(cmus-remote -Q | grep tag | grep title | sed 's/tag title //')
  artist=$(cmus-remote -Q | grep tag | grep " artist " | sed 's/tag artist //')
  album=$(cmus-remote -Q | grep tag | grep " album " | sed 's/tag album //')
  track=$(cmus-remote -Q | grep tag | grep tracknumber | sed 's/tag tracknumber //')
  echo $track $title - $artist - $album
else
  echo ""
fi

the output for a running cmus is correct, when cmus isn't running I get

cmus-remote: cmus is not running
cmus-remote: cmus is not running
cmus-remote: cmus is not running
cmus-remote: cmus is not running
-

I have a workaround by appending >& /dev/null on each corresponding line but that's not what I want, I would like the code not to be executed at all. And I don't the output from the else case.

Body:
pgrep cmus>& /dev/null
if [ $? -eq 0 ]; then
  title=$(cmus-remote -Q | grep tag | grep title | sed 's/tag title //') > /dev/null 2>&1
  artist=$(cmus-remote -Q | grep tag | grep " artist " | sed 's/tag artist //') > /dev/null 2>&1
  album=$(cmus-remote -Q | grep tag | grep " album " | sed 's/tag album //') > /dev/null 2>&1
  track=$(cmus-remote -Q | grep tag | grep tracknumber | sed 's/tag tracknumber //') >/ dev/null 2>&1
  echo $track $title - $artist - $album
else
  echo ""
fi

Adding > /dev/null 2>&1

2 refers to the second file descriptor of the process, i.e. stderr.

> means redirection.

&1 means the target of the redirection should be the same location as the first file descriptor, i.e. stdout.

So this command first redirects stdout to /dev/null and then redirects stderr there as well. This effectively silences all output (regular or error).

In your case cmus-remote: cmus is not running is an stderr so the redirection that you should use should be able to redirect both STDOUT and STDERR


问:
TokenMismatchException when posting a form using laravel5.4
TokenMismatchException in VerifyCsrfToken.php line 68,when i try to post a form.

```<code><form method="post" action="url('add')" >
{{ csrf_field() }}
<input type="text" name="title" />
<input type="submit" value="Add" />
</form>
</code>```

Its was working fine before i added this package.

答:
If you don't use Laravel Form, for example:

```<code>{!! Form::open([]) !!}
{!! Form::close() !!}
</code>```

you can use:

```<code><input type="hidden" name="_token" value="{{ csrf_token() }}">
</code>```

Sometimes you need to clear your cache as well.

Body:
TokenMismatchException in VerifyCsrfToken.php line 68,when i try to post a form.

<form method="post" action="url('add')" >
{{ csrf_field() }}
<input type="text" name="title" />
<input type="submit" value="Add" />
</form>

Its was working fine before i added this package.

Body:
If you don't use Laravel Form, for example:

{!! Form::open([]) !!}
{!! Form::close() !!}

you can use:

<input type="hidden" name="_token" value="{{ csrf_token() }}">

Sometimes you need to clear your cache as well.


问:
C# Json to custom class
I have json:

```<code>[
     {
        "Name" : "SHA of timestamp",
        "ProjectURL" : "URL to Proj",
        "AccountIdentifier" : "Account Identifier",
        "Repositories":
        {
            "GitLink1":
            {
                "Login" : "login1",
                "Password"  : "pas1"
            },
            "GitLink2":
            {
                "Login" : "login2",
                "Password"  : "pas2"
            },

            ...

            "GitLink999":
            {
                "Login" : "login999",
                "Password" : "pass999"
            }
        }
    },

    ...

    {
        Same entry
    }
]
</code>```

I need to fill it in IEnumerable of my created classes

```<code>public class Git
{
    public string Login { get; set; }
    public string Password { get; set; }
}

public class Repositories
{
    public Git git { get; set; }
}

public class ConfigEntry
{
    public string Name { get; set; }
    public string ProjectURL { get; set; }
    public string AccountIdentifier { get; set; }
    public Repositories Repositories { get; set; }
}
</code>```

Using

```<code>IEnumerable<ConfigurationEntry> config = JsonConvert.DeserializeObject<IEnumerable<ConfigurationEntry>>(CONFIGJSON);
</code>```

Where CONFIGJSON contains frst json file.

Gives me this data of ConfigEntry class :

Name : "filled with some data"

ProjectURL : same

AccountIdentifier : same

Repositories : NULL

How i can fill Repositories field with all data i have in config JSON?

Is there any ideas.

答:
Your class definitions aren't quite right.

Your "repositories" class only contains a single Git, but needs to be a Dictionary.

I think if you use this you will be close:

```<code>public class Git
{
    public string Login { get; set; }
    public string Password { get; set; }
}
public class ConfigEntry
{
    public string Name { get; set; }
    public string ProjectURL { get; set; }
    public string AccountIdentifier { get; set; }
    public Dictionary<string,Git> Repositories { get; set; }
}
</code>```

you may also need a non-generic IEnumerable, so it knows which objects to actually create:

```<code>JsonConvert.DeserializeObject<List<ConfigurationEntry>>(CONFIGJSON);
</code>```

Title: C# Json to custom class

Body:
I have json:

[
     {
        "Name" : "SHA of timestamp",
        "ProjectURL" : "URL to Proj",
        "AccountIdentifier" : "Account Identifier",
        "Repositories":
        {
            "GitLink1":
            {
                "Login" : "login1",
                "Password"  : "pas1"
            },
            "GitLink2":
            {
                "Login" : "login2",
                "Password"  : "pas2"
            },

            ...

            "GitLink999":
            {
                "Login" : "login999",
                "Password" : "pass999"
            }
        }
    },

    ...

    {
        Same entry
    }
]

I need to fill it in IEnumerable of my created classes

public class Git
{
    public string Login { get; set; }
    public string Password { get; set; }
}

public class Repositories
{
    public Git git { get; set; }
}

public class ConfigEntry
{
    public string Name { get; set; }
    public string ProjectURL { get; set; }
    public string AccountIdentifier { get; set; }
    public Repositories Repositories { get; set; }
}

Using

IEnumerable<ConfigurationEntry> config = JsonConvert.DeserializeObject<IEnumerable<ConfigurationEntry>>(CONFIGJSON);

Where CONFIGJSON contains frst json file.

Gives me this data of ConfigEntry class :

Name : "filled with some data"

ProjectURL : same

AccountIdentifier : same

Repositories : NULL

How i can fill Repositories field with all data i have in config JSON?

Is there any ideas.

Body:
Your class definitions aren't quite right.

Your "repositories" class only contains a single Git, but needs to be a Dictionary.

I think if you use this you will be close:

public class Git
{
    public string Login { get; set; }
    public string Password { get; set; }
}
public class ConfigEntry
{
    public string Name { get; set; }
    public string ProjectURL { get; set; }
    public string AccountIdentifier { get; set; }
    public Dictionary<string,Git> Repositories { get; set; }
}

you may also need a non-generic IEnumerable, so it knows which objects to actually create:

JsonConvert.DeserializeObject<List<ConfigurationEntry>>(CONFIGJSON);


问:
Calling JSON from another activity JAVA
I am trying to call the following method which is supposed to parse a JSON file from another activity. How come Android Studio is showing me a error?

This is the first activity called FirstActivity.java

```<code> public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);

        ReadJSON classToReadJSON = new ReadJSON();
        classToReadJSON.loadJSONFromAsset();
    }}
</code>```

This is my second class ReadJSON.java:

```<code>public class ReadJSON extends AppCompatActivity{
    public String loadJSONFromAsset() {
            String json = null;
            try {
                InputStream is = getAssets().open("jsonfile.json");
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();
                json = new String(buffer, "UTF-8");
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
            return json;
        }
}
</code>```

The code to parse the JSON file derives from Faizan's answer.
Reading a json file in Android

Edit: Sorry for not having posted the error log, I am still pretty new to programming.

So this is the error log:

```<code>D/AndroidRuntime: Shutting down VM

                  --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.zeus.jsonstackoverflow, PID: 2805
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.zeus.jsonstackoverflow/com.example.zeus.jsonstackoverflow.FirstActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                      at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
                      at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
                      at android.view.ContextThemeWrapper.getAssets(ContextThemeWrapper.java:116)
                      at com.example.zeus.jsonstackoverflow.ReadJSON.loadJSONFromAsset(ReadJSON.java:16)
                      at com.example.zeus.jsonstackoverflow.FirstActivity.onCreate(FirstActivity.java:14)
                      at android.app.Activity.performCreate(Activity.java:6662)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

I would highly appreciate any help on this matter.

答:
You have to pass Context to the method if you are not using Activity try this :

```<code> public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);

        ReadJSON classToReadJSON = new ReadJSON();
        classToReadJSON.loadJSONFromAsset(this);
    }
}
</code>```

ReadJSON.class

```<code>public class ReadJSON {
public String loadJSONFromAsset(Context c) {
        String json = null;
        try {
            InputStream is = c.getAssets().open("jsonfile.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }
}
</code>```

Title: Calling JSON from another activity JAVA

Body:
I am trying to call the following method which is supposed to parse a JSON file from another activity. How come Android Studio is showing me a error?

This is the first activity called FirstActivity.java

 public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);

        ReadJSON classToReadJSON = new ReadJSON();
        classToReadJSON.loadJSONFromAsset();
    }}

This is my second class ReadJSON.java:

public class ReadJSON extends AppCompatActivity{
    public String loadJSONFromAsset() {
            String json = null;
            try {
                InputStream is = getAssets().open("jsonfile.json");
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();
                json = new String(buffer, "UTF-8");
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
            return json;
        }
}

The code to parse the JSON file derives from Faizan's answer.
Reading a json file in Android

Edit: Sorry for not having posted the error log, I am still pretty new to programming.

So this is the error log:

D/AndroidRuntime: Shutting down VM

                  --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.zeus.jsonstackoverflow, PID: 2805
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.zeus.jsonstackoverflow/com.example.zeus.jsonstackoverflow.FirstActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                      at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
                      at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
                      at android.view.ContextThemeWrapper.getAssets(ContextThemeWrapper.java:116)
                      at com.example.zeus.jsonstackoverflow.ReadJSON.loadJSONFromAsset(ReadJSON.java:16)
                      at com.example.zeus.jsonstackoverflow.FirstActivity.onCreate(FirstActivity.java:14)
                      at android.app.Activity.performCreate(Activity.java:6662)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

I would highly appreciate any help on this matter.

Body:
You have to pass Context to the method if you are not using Activity try this :

 public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);

        ReadJSON classToReadJSON = new ReadJSON();
        classToReadJSON.loadJSONFromAsset(this);
    }
}

ReadJSON.class

public class ReadJSON {
public String loadJSONFromAsset(Context c) {
        String json = null;
        try {
            InputStream is = c.getAssets().open("jsonfile.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }
}


问:
Query showing records that do NOT match in between tables
I have two tables. One is a table of the reports that have been submitted to us. Another is a temp table with the records of reports that should eventually be submitted to us. I would like to show only the records in the temp table that do not match the ones in the reports table (so the reports that still must be submitted are displayed).

Example data is:

```<code>Reports table:

CREATE TABLE [dbo].[Reports]
(
    [ReportID] [int] IDENTITY(1,1) NOT NULL,
    [ReportDate] [date] NULL,
    [AssessmentID] [int] NOT NULL,
    [ReportType] [varchar](50) NULL
);

AssessmentID    ReportType  ReportID
1   1st Quarterly   27
2   1st Quarterly   30
2   2nd Quarterly   31
2   3rd Quarterly   32

QuarterlyReportsDue table:

CREATE TABLE #QuarterlyReportsDue
(
AssessmentID INT,
InstallationDate DATE,
QuarterlyReportType VARCHAR(50)
);

AssessmentID    InstallationDate    QuarterlyReportType
1   2009-08-14  1st Quarterly
1   2009-08-14  2nd Quarterly
1   2009-08-14  3rd Quarterly
1   2009-08-14  4th Quarterly
2   2008-05-16  4th Quarterly
2   2008-05-16  3rd Quarterly
2   2008-05-16  2nd Quarterly
2   2008-05-16  1st Quarterly
</code>```

I have tried LEFT OUTER JOINS but am running into issues. Please see my below SQL:

```<code>SELECT #QuarterlyReportsDue.InstallationDate, #QuarterlyReportsDue.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue
LEFT OUTER JOIN Reports ON #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
WHERE Reports.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
AND Reports.ReportType <> #QuarterlyReportsDue.QuarterlyReportType
ORDER BY #QuarterlyReportsDue.AssessmentID
</code>```

And my results:

```<code>AssessmentID    QuarterlyReportType ReportType  ReportID
1   2nd Quarterly   1st Quarterly   27
1   3rd Quarterly   1st Quarterly   27
1   4th Quarterly   1st Quarterly   27
2   4th Quarterly   1st Quarterly   30
2   4th Quarterly   2nd Quarterly   31
2   4th Quarterly   3rd Quarterly   32
2   1st Quarterly   2nd Quarterly   31
2   1st Quarterly   3rd Quarterly   32
2   3rd Quarterly   1st Quarterly   30
2   3rd Quarterly   2nd Quarterly   31
2   2nd Quarterly   1st Quarterly   30
2   2nd Quarterly   3rd Quarterly   32
</code>```

For assessment 1 it works great, assessment 2 has many duplicates. How can I get around this to only show the ideal results?

```<code>AssessmentID    QuarterlyReportType ReportType
1   2nd Quarterly   1st Quarterly
1   3rd Quarterly   1st Quarterly
1   4th Quarterly   1st Quarterly
2       4th Quarterly
</code>```

答:
When you LEFT JOIN to a table and then reference one of that table's columns in the WHERE clause, you implicitly turn the join into an INNER JOIN. Instead, move those conditions out of the WHERE and make them part of the JOIN conditions.</p>

```<code>SELECT q.InstallationDate, q.QuarterlyReportType, Reports.ReportType
    FROM #QuarterlyReportsDue q
        LEFT OUTER JOIN Reports r
            ON q.AssessmentID = r.AssessmentID
                AND q.QuarterlyReportType = r.ReportType
                AND r.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
    WHERE r.AssessmentID IS NULL /* matching record not found in Reports table */
    ORDER BY #QuarterlyReportsDue.AssessmentID
</code>```

Body:
I have two tables. One is a table of the reports that have been submitted to us. Another is a temp table with the records of reports that should eventually be submitted to us. I would like to show only the records in the temp table that do not match the ones in the reports table (so the reports that still must be submitted are displayed).

Example data is:

Reports table:

CREATE TABLE [dbo].[Reports]
(
    [ReportID] [int] IDENTITY(1,1) NOT NULL,
    [ReportDate] [date] NULL,
    [AssessmentID] [int] NOT NULL,
    [ReportType] [varchar](50) NULL
);

AssessmentID    ReportType  ReportID
1   1st Quarterly   27
2   1st Quarterly   30
2   2nd Quarterly   31
2   3rd Quarterly   32

QuarterlyReportsDue table:

CREATE TABLE #QuarterlyReportsDue
(
AssessmentID INT,
InstallationDate DATE,
QuarterlyReportType VARCHAR(50)
);

AssessmentID    InstallationDate    QuarterlyReportType
1   2009-08-14  1st Quarterly
1   2009-08-14  2nd Quarterly
1   2009-08-14  3rd Quarterly
1   2009-08-14  4th Quarterly
2   2008-05-16  4th Quarterly
2   2008-05-16  3rd Quarterly
2   2008-05-16  2nd Quarterly
2   2008-05-16  1st Quarterly

I have tried LEFT OUTER JOINS but am running into issues. Please see my below SQL:

SELECT #QuarterlyReportsDue.InstallationDate, #QuarterlyReportsDue.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue
LEFT OUTER JOIN Reports ON #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
WHERE Reports.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
AND Reports.ReportType <> #QuarterlyReportsDue.QuarterlyReportType
ORDER BY #QuarterlyReportsDue.AssessmentID

And my results:

AssessmentID    QuarterlyReportType ReportType  ReportID
1   2nd Quarterly   1st Quarterly   27
1   3rd Quarterly   1st Quarterly   27
1   4th Quarterly   1st Quarterly   27
2   4th Quarterly   1st Quarterly   30
2   4th Quarterly   2nd Quarterly   31
2   4th Quarterly   3rd Quarterly   32
2   1st Quarterly   2nd Quarterly   31
2   1st Quarterly   3rd Quarterly   32
2   3rd Quarterly   1st Quarterly   30
2   3rd Quarterly   2nd Quarterly   31
2   2nd Quarterly   1st Quarterly   30
2   2nd Quarterly   3rd Quarterly   32

For assessment 1 it works great, assessment 2 has many duplicates. How can I get around this to only show the ideal results?

AssessmentID    QuarterlyReportType ReportType
1   2nd Quarterly   1st Quarterly
1   3rd Quarterly   1st Quarterly
1   4th Quarterly   1st Quarterly
2       4th Quarterly

Body:
When you LEFT JOIN to a table and then reference one of that table's columns in the WHERE clause, you implicitly turn the join into an INNER JOIN. Instead, move those conditions out of the WHERE and make them part of the JOIN conditions.

SELECT q.InstallationDate, q.QuarterlyReportType, Reports.ReportType
    FROM #QuarterlyReportsDue q
        LEFT OUTER JOIN Reports r
            ON q.AssessmentID = r.AssessmentID
                AND q.QuarterlyReportType = r.ReportType
                AND r.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
    WHERE r.AssessmentID IS NULL /* matching record not found in Reports table */
    ORDER BY #QuarterlyReportsDue.AssessmentID


答:
Quite a few problems/misconceptions in your code.

First, your ReadJSON doesn't need to extend AppCompatActivity as it's not an Activity. This is one way of doing it:

```<code>public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);

        String myJsonString = loadJSONFromAsset();
    }

    public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = getAssets().open("jsonfile.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

}
</code>```

Second, with the returned json you have to do something. I put it in the myJsonString variable and probably you will have to transform it into a JSONObject and parse it.

The crash appears because you are trying to .getAssets(...) from a null context. By putting the loadJSONFromAsset in your activity you will have a context.

Title: Calling JSON from another activity JAVA

Body:
Quite a few problems/misconceptions in your code.

First, your ReadJSON doesn't need to extend AppCompatActivity as it's not an Activity. This is one way of doing it:

public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);

        String myJsonString = loadJSONFromAsset();
    }

    public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = getAssets().open("jsonfile.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

}

Second, with the returned json you have to do something. I put it in the myJsonString variable and probably you will have to transform it into a JSONObject and parse it.

The crash appears because you are trying to .getAssets(...) from a null context. By putting the loadJSONFromAsset in your activity you will have a context.


问:
Linq query to get person visited zones of current day
I am working on web api with Entity framework as object-relational mapping (ORM) framework for ADO.NET. I need to write a linq query which should return most recent 5 zones traveled by a person.

My table with respective columns is depicted in the attached image. I am using azure sql database as my back-end storage, from the above data i need to get top 5 zone_id list as [4,2,3,2,1] by using linq query. client may request to get zones list with in specific range of stime.

答:
Not 100% sure what you are asking but to get the list of zone-Id would be something like:

```<code>var zoneIds = data.Select(z => z.zone_id).Distinct();
</code>```

This will get you the individual zone ids. (The distinct removes duplicate zone id entries).

If you want to filter by date it would be something like:

```<code>var zoneIds = data.Where(z => z.stime > [lowerDateTimeBound] && z.stime < [upperDateTimeBound]).Select(z => z.zone_id).Distinct();
</code>```

For most recent 5 I would use:

```<code>var zoneIds = data.OrderByDescending(z => z.stime).Select(z => z.zone_id).Distinct().Take(5);
</code>```

If you want to get all zones without removing duplicates remove the .Distinct() call. And to get more result change the Take(x) number. Result should be as follows:

```<code>[1, 2, 3, 4] // With distinct
[1, 1, 2, 2, 3] // Without distinct
</code>```

UPDATE: based on your comments.

Use this to get the list of zone Ids:

```<code>var zoneIds = data.OrderByDescending(z => z.stime).Select(z => z.zone_id).ToList();
var zoneIdsArray = zoneIds.ToArray();
for(int c = 1; c < zoneIdsArray.Count(); c ++)
{
    if (zoneIdsArray[c].zone_id == zoneIdsArray[c-1].zone_id)
    {
        zoneIds.Remove(zoneIdsArray[c]);
    }
}

var last5Zones = zoneIds.Select(z => z.zone_id).ToList().Take(5);
</code>```

The resulting last5Zones list should have the correct list of last 5 zones (according to what I think you are looking for from your comments)

Body:
Not 100% sure what you are asking but to get the list of zone-Id would be something like:

var zoneIds = data.Select(z => z.zone_id).Distinct();

This will get you the individual zone ids. (The distinct removes duplicate zone id entries).

If you want to filter by date it would be something like:

var zoneIds = data.Where(z => z.stime > [lowerDateTimeBound] && z.stime < [upperDateTimeBound]).Select(z => z.zone_id).Distinct();

For most recent 5 I would use:

var zoneIds = data.OrderByDescending(z => z.stime).Select(z => z.zone_id).Distinct().Take(5);

If you want to get all zones without removing duplicates remove the .Distinct() call. And to get more result change the Take(x) number. Result should be as follows:

[1, 2, 3, 4] // With distinct
[1, 1, 2, 2, 3] // Without distinct

UPDATE: based on your comments.

Use this to get the list of zone Ids:

var zoneIds = data.OrderByDescending(z => z.stime).Select(z => z.zone_id).ToList();
var zoneIdsArray = zoneIds.ToArray();
for(int c = 1; c < zoneIdsArray.Count(); c ++)
{
    if (zoneIdsArray[c].zone_id == zoneIdsArray[c-1].zone_id)
    {
        zoneIds.Remove(zoneIdsArray[c]);
    }
}

var last5Zones = zoneIds.Select(z => z.zone_id).ToList().Take(5);

The resulting last5Zones list should have the correct list of last 5 zones (according to what I think you are looking for from your comments)


问:
Flink Cassandra Time out Error
I am working on Kafka Flink Cassandra Sink. Flink code is working fine for almost 4 hours. After that, I got an exception.

Caused by: com.datastax.driver.core.exceptions.WriteTimeoutException: Cassandra timeout during write query at consistency LOCAL_ONE (1 replica were required but only 0 acknowledged the write)

Can anyone help?

答: This is not related to Flink but to Cassandra: your are probably writing too fast in Cassandra. Check your amount of RAM allocated to Cassandra, the number of CPU, ....</p>

Title: Flink Cassandra Time out Error


问:
Traverse through each row for a column text
I have a below grid

The html code is at pastebin.com/GBP3AZNQ

I want to verify whether "test123" is present. I want to traverse through each row of column master obligationname and look for the text test123.

Can anyone guide me how to do this?

答:
You can take the parent class and achieve this as follows:

```<code>element.all(by.xpath("//div[@class='ui-grid-cell-contents ng-scope ng-binding']")).getText().then(function (msg)
{
console.log("Grid contains" + msg);
expect(msg).toContain("test123");
}
</code>```

If suppose the Master_obligation name is test_876
Then

```<code>var master_obligation_name= "test_876" ;
</code>```

Suppose you are filling obligation_name as:

```<code>element(by.xpath("path to master_obligation text field")).sendKeys(master_obligation_name);
</code>```

After creation of the row, validating the newly added row:

```<code> var row_check = element(by.xpath("//div[contains(text(),'test_876')]"));
 if(row_check.isPresent())
 {
  row_check.getText().then(function (msg) {
        console.log("Grid contains" + msg);
  });
 }
</code>```

Happy Learning. :-)

Body:
You can take the parent class and achieve this as follows:

element.all(by.xpath("//div[@class='ui-grid-cell-contents ng-scope ng-binding']")).getText().then(function (msg)
{
console.log("Grid contains" + msg);
expect(msg).toContain("test123");
}

If suppose the Master_obligation name is test_876
Then

var master_obligation_name= "test_876" ;

Suppose you are filling obligation_name as:

element(by.xpath("path to master_obligation text field")).sendKeys(master_obligation_name);

After creation of the row, validating the newly added row:

 var row_check = element(by.xpath("//div[contains(text(),'test_876')]"));
 if(row_check.isPresent())
 {
  row_check.getText().then(function (msg) {
        console.log("Grid contains" + msg);
  });
 }

Happy Learning. :-)


问:
Curl post request fails - bugs in a script or blocked?
I'm trying to post a request to http://iate.europa.eu/ using the following script:

```<code>     <?php

$output_array = array();

$post = "method=search&saveStats=true&screenSize=1920x1080&query=bond&valid=Szukaj+&sourceLanguage=en&targetLanguages=pl&domain=&domain=12&typeOfSearch=s&request=";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://iate.europa.eu/SearchByQueryEdit.do');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

echo $server_output = curl_exec ($ch);

?>
</code>```

The data I used:

When I run the script, I get "Access Denied. Your request has been denied for security reason."

Does the script trigger some security mechansims or does it simply make bad requests?

Thx in advance,

Lukasz

答:
I have added an agent. Try this:</p>

```<code>$post = "method=search&saveStats=true&screenSize=1920x1080&query=bond&valid=Szukaj+&sourceLanguage=en&targetLanguages=pl&domain=&domain=12&typeOfSearch=s&request=";

$ch = curl_init();

/* Additional Code Start */
$agent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0";
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
/* Additional Code End*/

curl_setopt($ch, CURLOPT_URL, 'http://iate.europa.eu/SearchByQueryEdit.do');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

echo $server_output = curl_exec ($ch);
</code>```

Body:
I'm trying to post a request to http://iate.europa.eu/ using the following script:

     <?php

$output_array = array();

$post = "method=search&saveStats=true&screenSize=1920x1080&query=bond&valid=Szukaj+&sourceLanguage=en&targetLanguages=pl&domain=&domain=12&typeOfSearch=s&request=";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://iate.europa.eu/SearchByQueryEdit.do');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

echo $server_output = curl_exec ($ch);

?>

The data I used:

When I run the script, I get "Access Denied. Your request has been denied for security reason."

Does the script trigger some security mechansims or does it simply make bad requests?

Thx in advance,

Lukasz

Body:
I have added an agent. Try this:

$post = "method=search&saveStats=true&screenSize=1920x1080&query=bond&valid=Szukaj+&sourceLanguage=en&targetLanguages=pl&domain=&domain=12&typeOfSearch=s&request=";

$ch = curl_init();

/* Additional Code Start */
$agent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0";
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
/* Additional Code End*/

curl_setopt($ch, CURLOPT_URL, 'http://iate.europa.eu/SearchByQueryEdit.do');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

echo $server_output = curl_exec ($ch);


问:
Autoformat row based on values in each cell using Excel VBA?
I have Table1

Column A has a Date e.g. 30/5/2017

Column B has Status e.g "Success"

Column C has Value e.g 500

Requirement: Apply custom Conditional formatting in VBA when a cell is changed

Let's say the change happened in Columns A, B or C in row 5

Regardless whether the change happened in Columns A, B, or C, the same logic should be executed.

If column A value is less than Now(), then row 5 should be red background and white text. No further checks should run.

Else If column B is "Success", then row 5 should be green background and white text. No further checks should run.

Else If column C has value less than 500, then row 5 should be blue background and white text. No further checks should run.

The VBA code below is to check for change on a cell - it autoformats cell in column b with a hyperlink.

What I need now is to autoformat the whole row based on the criteria above.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

          If ((Not Intersect(Target, Range("B:B")) Is Nothing) Or (Not Intersect(Target, Range("F:F")) Is Nothing) Or (Not Intersect(Target, Range("G:G")) Is Nothing) Or (Not Intersect(Target, Range("I:I")) Is Nothing)) Then

          End If

End Sub
</code>```

答:
I am assuming your table (having three columns) are present in Sheet1.
So, add following code in Sheet1 (not in separate module)

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
  Dim irow As Variant

  ' First identify the row changed
  irow = Target.Row

  ' Invoke row formatter routine
  Call DefineFormat(irow)

End Sub
</code>```

Then add following piece of code in a module (you may add under Sheet1 as well but it will limit the uses of this module)

```<code>Sub DefineFormat(irow) ' Receive the row number for processing

    Dim vVal As Variant
    Dim Rng As Range
    Dim lFont, lFill As Long

    ' Define the basis for validation
    Dim Current, Success, limit As Variant ' Can be defined as constant as well
        Current = Date ' Set today's date
        Success = "Success" ' Set success status check
        limit = 500 ' Set limit for value check

    ' Set range for the entire row - Columns A(index 1) to Column C (index 3)
    Set Rng = Range(Application.ActiveSheet.Cells(irow, 1).Address, Application.ActiveSheet.Cells(irow, 3).Address)
    lFont = vbWhite

    ' Assuming columns A, B and C needs to be formatted
    If Application.ActiveSheet.Cells(irow, 1) < Current Then
        lFill = vbRed  ' Check for col A
        Else:
            If Application.ActiveSheet.Cells(irow, 2) = Success Then
            lFill = vbGreen   ' Check for col B
            Else
                If Application.ActiveSheet.Cells(irow, 3) < limit Then
                 lFill = vbBlue   ' Check for col C
                 Else     ' Default formatting
                    lFill = xlNone
                    lFont = vbBlack
                End If
            End If
    End If

        Rng.Interior.Color = lFill
        Rng.Font.Color = lFont
End Sub
</code>```

This will format the row as the data is modified (just like conditional formatting)

Also, if you need to format the entire table in one go, then you may call DefineFormat routine in a loop for each row of the table as illustrated by Fadi in his reply.

Body:
I have Table1

Column A has a Date e.g. 30/5/2017

Column B has Status e.g "Success"

Column C has Value e.g 500

Requirement: Apply custom Conditional formatting in VBA when a cell is changed

Let's say the change happened in Columns A, B or C in row 5

Regardless whether the change happened in Columns A, B, or C, the same logic should be executed.

If column A value is less than Now(), then row 5 should be red background and white text. No further checks should run.

Else If column B is "Success", then row 5 should be green background and white text. No further checks should run.

Else If column C has value less than 500, then row 5 should be blue background and white text. No further checks should run.

The VBA code below is to check for change on a cell - it autoformats cell in column b with a hyperlink.

What I need now is to autoformat the whole row based on the criteria above.

Private Sub Worksheet_Change(ByVal Target As Range)

          If ((Not Intersect(Target, Range("B:B")) Is Nothing) Or (Not Intersect(Target, Range("F:F")) Is Nothing) Or (Not Intersect(Target, Range("G:G")) Is Nothing) Or (Not Intersect(Target, Range("I:I")) Is Nothing)) Then

          End If

End Sub

Body:
I am assuming your table (having three columns) are present in Sheet1.
So, add following code in Sheet1 (not in separate module)

Private Sub Worksheet_Change(ByVal Target As Range)
  Dim irow As Variant

  ' First identify the row changed
  irow = Target.Row

  ' Invoke row formatter routine
  Call DefineFormat(irow)

End Sub

Then add following piece of code in a module (you may add under Sheet1 as well but it will limit the uses of this module)

Sub DefineFormat(irow) ' Receive the row number for processing

    Dim vVal As Variant
    Dim Rng As Range
    Dim lFont, lFill As Long

    ' Define the basis for validation
    Dim Current, Success, limit As Variant ' Can be defined as constant as well
        Current = Date ' Set today's date
        Success = "Success" ' Set success status check
        limit = 500 ' Set limit for value check

    ' Set range for the entire row - Columns A(index 1) to Column C (index 3)
    Set Rng = Range(Application.ActiveSheet.Cells(irow, 1).Address, Application.ActiveSheet.Cells(irow, 3).Address)
    lFont = vbWhite

    ' Assuming columns A, B and C needs to be formatted
    If Application.ActiveSheet.Cells(irow, 1) < Current Then
        lFill = vbRed  ' Check for col A
        Else:
            If Application.ActiveSheet.Cells(irow, 2) = Success Then
            lFill = vbGreen   ' Check for col B
            Else
                If Application.ActiveSheet.Cells(irow, 3) < limit Then
                 lFill = vbBlue   ' Check for col C
                 Else     ' Default formatting
                    lFill = xlNone
                    lFont = vbBlack
                End If
            End If
    End If

        Rng.Interior.Color = lFill
        Rng.Font.Color = lFont
End Sub

This will format the row as the data is modified (just like conditional formatting)

Also, if you need to format the entire table in one go, then you may call DefineFormat routine in a loop for each row of the table as illustrated by Fadi in his reply.


问:
knockout.js access element from observablearray for a href context

    #scroll-wrapper {
        margin: 5px;
        max-height: 250px;
        overflow: auto;
        vertical-align: top;
    }

```<code>#thumbnails {
    vertical-align: top;
    padding-bottom: 10px;
    max-height: 500px;
    min-width: 100px;
    overflow-y: hidden;
    overflow-x: scroll;
    white-space: nowrap;
}

.thumbnail-container {
    display: inline-block;
    position: relative;
    line-height: 5px;
    margin: 3px;
    margin-bottom: 15px !important;
}
#abc {
    overflow-y: scroll;
    overflow-x: hidden;
    height: 200px;
}
</code>```

```<code>   <form method="post">
    <div data-bind="foreach: lists" id="thumbnails">
        <div class="thumbnail-container">
            <span data-bind="text:listname"></span><br /><br /><br /><br /><br />
            <div id="abc">
                <ul class="list-group" data-bind="foreach: cardlists">
                    <li class="list-group-item">
                        <span data-bind="text: cardname"></span>

                    </li>
                </ul>
                <a href="#" data-bind="click:  $parent.showhideaddcard">Add Card</a><br />
                <div data-bind="visible: showRenderTimes">
                    <input type="text" data-bind="value: $parent.cardtext" /><br /><br /><br />
                    <input type="button" value="Add" data-bind="click: $parent.addcard" />
                    <input type="button" value="Cancel" data-bind="click: $parent.cancelcard" />
                </div>
            </div>
        </div>
    </div>
    <p>
        <span id="addVar" data-bind="click: addList">Add List</span>
    </p>

    <p class="alignRight">
        <input type="submit" value="Check">
    </p>
</form>
</code>```

This is my code

```<code> var ListModal = function(lists) {
    var self = this;
    self.cardtext = ko.observable();
    self.lists = ko.observableArray(ko.utils.arrayMap(lists, function (list) {
        return { listname: list.listname,  cardlists: ko.observableArray(list.cardlists), showRenderTimes: ko.observable(false) };
    }));

    self.addList = function() {
        self.lists.push({
            listname: "asdasdasd asdasd",
            cardlists: ko.observableArray([
                {
                    cardname: "card 1"
                },
                {
                    cardname: "card 2"
                },
                {
                    cardname: "card 3"
                }
            ]),
            showRenderTimes: false

        });
    };

    self.showhideaddcard = function (list) {
        self.showRenderTimes(true);   // problem is here
    };

    self.save = function ()
    {

    };
};
</code>```

how to access showRenderTimes in lists observable array in showhideaddcard button context?.

答:
First you need to modify the addList function and make showRenderTimes as observable object, because on the initialization of self.list you set that as observable object.

```<code>showRenderTimes: ko.observable(false)
</code>```

Then this is how you pass the data to showhideaddcard function

```<code><a href="#" data-bind="click: $parent.showhideaddcard($data())">Add Card</a><br />
</code>```

You can modify the value of showRenderTimes like this

```<code>self.showhideaddcard = function (list) {
    list.showRenderTimes(true);
};
</code>```

Body:
    #scroll-wrapper {
        margin: 5px;
        max-height: 250px;
        overflow: auto;
        vertical-align: top;
    }

#thumbnails {
    vertical-align: top;
    padding-bottom: 10px;
    max-height: 500px;
    min-width: 100px;
    overflow-y: hidden;
    overflow-x: scroll;
    white-space: nowrap;
}

.thumbnail-container {
    display: inline-block;
    position: relative;
    line-height: 5px;
    margin: 3px;
    margin-bottom: 15px !important;
}
#abc {
    overflow-y: scroll;
    overflow-x: hidden;
    height: 200px;
}

   <form method="post">

                Add Card

                    <input type="text" data-bind="value: $parent.cardtext" />

                    <input type="button" value="Add" data-bind="click: $parent.addcard" />
                    <input type="button" value="Cancel" data-bind="click: $parent.cancelcard" />

        Add List

        <input type="submit" value="Check">

</form>

This is my code

 var ListModal = function(lists) {
    var self = this;
    self.cardtext = ko.observable();
    self.lists = ko.observableArray(ko.utils.arrayMap(lists, function (list) {
        return { listname: list.listname,  cardlists: ko.observableArray(list.cardlists), showRenderTimes: ko.observable(false) };
    }));

    self.addList = function() {
        self.lists.push({
            listname: "asdasdasd asdasd",
            cardlists: ko.observableArray([
                {
                    cardname: "card 1"
                },
                {
                    cardname: "card 2"
                },
                {
                    cardname: "card 3"
                }
            ]),
            showRenderTimes: false

        });
    };

    self.showhideaddcard = function (list) {
        self.showRenderTimes(true);   // problem is here
    };

    self.save = function ()
    {

    };
};

how to access showRenderTimes in lists observable array in showhideaddcard button context?.

Body:
First you need to modify the addList function and make showRenderTimes as observable object, because on the initialization of self.list you set that as observable object.

showRenderTimes: ko.observable(false)

Then this is how you pass the data to showhideaddcard function

<a href="#" data-bind="click: $parent.showhideaddcard($data())">Add Card</a><br />

You can modify the value of showRenderTimes like this

self.showhideaddcard = function (list) {
    list.showRenderTimes(true);
};


问:
Error while trying to upload file using kairos
Iam using kairos api for face recognition .Iam trying to enroll an image.The documentation here says it also accepts base64 encode photos.So I have encoded the image using base 64 and I get the following error

```<code>{"Errors":[{"ErrCode":5000,"Message":"an invalid image was sent must be jpg or p
ng format"}]}
</code>```

I have used the following python code for sending the requests

```<code>import cv2
import requests
import base64
import json

image=cv2.imread('Face-images/Subject 9.jpg')
encoded_string =base64.b64encode(image)
payload2= {"image":encoded_string ,"subject_id":"Abhishek","gallery_name":"MyGallery"}
headers={'Content-Type':'application/json','app_id':'app_id','app_key':'app_key'}
r = requests.post('https://api.kairos.com/enroll',headers=headers,data=json.dumps(payload2),verify=False)
print  r.text
</code>```

Any help would be appreciated

答:
Don't encode your photos. Probably they accept it, but its harder to pass. Check this solution:</p>

```<code>import requests

files = {"image": (filename,open(location+'/'+filename,"rb"))}
payload= {"subject_id":"Abhishek",
          "gallery_name":"MyGallery"}
headers={'Content-Type':'application/json',
         'app_id':'app_id',
         'app_key':'app_key'}
response = requests.post('https://api.kairos.com/enroll',headers=headers,data=payload,files=files,verify=False)
print response.text
</code>```

Body:
Iam using kairos api for face recognition .Iam trying to enroll an image.The documentation here says it also accepts base64 encode photos.So I have encoded the image using base 64 and I get the following error

{"Errors":[{"ErrCode":5000,"Message":"an invalid image was sent must be jpg or p
ng format"}]}

I have used the following python code for sending the requests

import cv2
import requests
import base64
import json

image=cv2.imread('Face-images/Subject 9.jpg')
encoded_string =base64.b64encode(image)
payload2= {"image":encoded_string ,"subject_id":"Abhishek","gallery_name":"MyGallery"}
headers={'Content-Type':'application/json','app_id':'app_id','app_key':'app_key'}
r = requests.post('https://api.kairos.com/enroll',headers=headers,data=json.dumps(payload2),verify=False)
print  r.text

Any help would be appreciated

Body:
Don't encode your photos. Probably they accept it, but its harder to pass. Check this solution:

import requests

files = {"image": (filename,open(location+'/'+filename,"rb"))}
payload= {"subject_id":"Abhishek",
          "gallery_name":"MyGallery"}
headers={'Content-Type':'application/json',
         'app_id':'app_id',
         'app_key':'app_key'}
response = requests.post('https://api.kairos.com/enroll',headers=headers,data=payload,files=files,verify=False)
print response.text


问:
Swing: programatically modifying the UI without triggering callbacks
If it is taken for granted that you need to modify programatically an element of the UI, like, say, a JComboBox's selected item without triggering any modification/notification event, then how to do it relatively cleanly?

Surely I can detach all the listeners then reattach them once I've modified what I want to modify but, typically, how is one supposed to do that? (once again, by considering that it is granted that that some element shall be modified and that it is considered granted that those modification should not trigger any callbacks).

P.S: I did do it by writing methods that do actually detach all the listeners, perform the modification, then re-attach all the listeners and it does work, but it seems a bit crappy to me.

答:
I think the methods you implement are the closest you can get to a clean way of doing what you're looking for.  And while I understand the requirement is taken for granted, it might be worth noting that by avoiding all the set listeners (specifically, ALL of them, not just the ones you were setting up yourself), you might end up driving the state of your application to something that is internally inconsistent.

I suppose what I'm saying is you should proceed with care :)


问:
How to update getServicelocator to zend 3
I'm new to zend3, and I came across a problem, getservicelocator no longer exists in version 3, I'm working with a controller, I wanted to know how to implement this migration,  Anyone know how to make this change</p>

```<code>namespace Base\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\ArrayAdapter;

abstract class AbstractController extends AbstractActionController
{

    /**
     *  Entity manager
     * @var
     */
    protected $em;
    /** Entity
     * @var
     */
    protected $entity;
    /**
     * Controller
     * @var
     */
    protected $controller;
    /**
     * @var
     */
    protected $route;
    /**
     * @var
     */
    protected $service;
    /**
     * @var
     */
    protected $form;

    private $configTable;
    /**
     * AbstractController constructor.
     */
    abstract function __construct();
...
/**
     *
     * @return \Zend\Http\Response
     */
    public function excluirAction()
    {
        $service = $this->getServiceLocator()->get($this->service);
        $id = $this->params()->fromRoute('id',0);
        // Abstract service
        if ($service->remove(array('id' => $id))) {
            $this->flashMessenger()->addSuccessMessage('Success');
        } else {
            $this->flashMessenger()->addErrorMessage('Error');
        }

        return $this->redirect()->toRoute($this->route, array('controller' => $this->controller));

    }
</code>```

答:
The architecture is not really good in your case, why would you have an action in an abstract controller...

The right way would be for the controller not to be abstract and pass the service through the constructor.

The wrong way would be to inject the service locator using a delegator.

The idea of removing the service locator is to be clearer on the dependencies of the class, so the code is way more readable (like "oh, I see this class needs ... and ... to do NAME_OF_THE_ACTION").
Also, it highly improve the code testability (you know what dependencies to mock/fake).

Body:
I'm new to zend3, and I came across a problem, getservicelocator no longer exists in version 3, I'm working with a controller, I wanted to know how to implement this migration,  Anyone know how to make this change

namespace Base\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\ArrayAdapter;

abstract class AbstractController extends AbstractActionController
{

    /**
     *  Entity manager
     * @var
     */
    protected $em;
    /** Entity
     * @var
     */
    protected $entity;
    /**
     * Controller
     * @var
     */
    protected $controller;
    /**
     * @var
     */
    protected $route;
    /**
     * @var
     */
    protected $service;
    /**
     * @var
     */
    protected $form;

    private $configTable;
    /**
     * AbstractController constructor.
     */
    abstract function __construct();
...
/**
     *
     * @return \Zend\Http\Response
     */
    public function excluirAction()
    {
        $service = $this->getServiceLocator()->get($this->service);
        $id = $this->params()->fromRoute('id',0);
        // Abstract service
        if ($service->remove(array('id' => $id))) {
            $this->flashMessenger()->addSuccessMessage('Success');
        } else {
            $this->flashMessenger()->addErrorMessage('Error');
        }

        return $this->redirect()->toRoute($this->route, array('controller' => $this->controller));

    }


问:
Does Silverlight 4 comply with the WCAG 2.0 specifications
I need to build a web application which complies with the WCAG 2.0 specification.

One main feature of this application is that some code must be executed on the client. I don't have any way to avoid it (it's the old problem of the electronic sign).

That's why I thought of Silverlight (and because of RIA services, of course). But I haven't found any information about whether an application developed this way would meet the WCAG 2.0 requirements.

Any links or opinions?

Thanks in advance.

答: See Accessibility Supported Uses for Microsoft Silverlight 2.0.</p>


问:
search by retaining the only group for the searched items and hiding others in ng-repeat
I created ng-repeat based on the department group, want to use search filter but when searching for an item then should display only the group for that searched item by hiding other items and other groups as well.
Right now showing the searched item properly under its group and hiding other items but not other group names.

$scope.users=[
{
"Name":"AA",
"Age":20,
"Department":"Sales",
"Sal":4000
},
{
"Name":"BB",
"Age":25,
"Department":"Accounts",
"Sal":6320
},
{
"Name":"CC",
"Age":34,
"Department":"Sales",
"Sal":8500
},
{
"Name":"DD",
"Age":32,
"Department":"Accounts",
"Sal":3500
},
{
"Name":"EE",
"Age":25,
"Department":"Sales",
"Sal":4900
},
{
"Name":"FF",
"Age":30,
"Department":"Production",
"Sal":4520
}
];

$scope.workers=[
{
"Name":"alpha",
"Age":90,
"Department":"XYX",
"Sal":9999
},
{
"Name":"BETA",
"Age":80,
"Department":"ABC",
"Sal":88888
}];
 $scope.workers=angular.fromJson(jsonData2);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" ng-model="searchOn" ">
<br>

<div ng-repeat="(key, value) in users | groupBy: 'Department' ">
  <div>
    <p>{{ key }}</p>
  </div>

  <div ng-repeat="usr in value | filter: searchOn ">
    <div>
      <p>Name: {{usr.Name}} Age: {{usr.Age}}</p>
    </div>
</div>
</div>

<div ng-repeat="(key, value) in workers | groupBy: 'Department' ">
  <div>
    <p>{{ key }}</p>
  </div>

  <div ng-repeat="wrk in value | filter: searchOn ">
    <div>
      <p>Name: {{wrk.Name}} Age: {{wrk.Age}}</p>
    </div>
</div>
</div>

the below is the $scope.users

Name Age Department Sal
AA 20 Sales  4000
BB 25 Accounts 6320
CC 34 Sales  8500
DD 32 Accounts 3500
EE 25 Sales  4900
FF 30 Production 4520

and the end result I want something like below

Department

 Sales:  AA 20 Sales  4000
         CC 34 Sales  8500
         EE 25 Sales  4900

 Accounts: BB 25 Accounts 6320
        DD 32 Accounts 3500

 Production: FF 30 Production 4520</code>```

答:
You have to use a temporary variable to store your filtered users.
like :

```<code>ng-repeat="usr in filteredArray = (value | filter: searchOn)"
</code>```

and bind the length of filter data to ng-if. like :

```<code> <p ng-if="filteredArray.length > 0" ng-bind="key"></p>
</code>```

See this working fiddle

Updated Fiddel Link for updated question.

Body:
I created ng-repeat based on the department group, want to use search filter but when searching for an item then should display only the group for that searched item by hiding other items and other groups as well.
Right now showing the searched item properly under its group and hiding other items but not other group names.

$scope.users=[
{
"Name":"AA",
"Age":20,
"Department":"Sales",
"Sal":4000
},
{
"Name":"BB",
"Age":25,
"Department":"Accounts",
"Sal":6320
},
{
"Name":"CC",
"Age":34,
"Department":"Sales",
"Sal":8500
},
{
"Name":"DD",
"Age":32,
"Department":"Accounts",
"Sal":3500
},
{
"Name":"EE",
"Age":25,
"Department":"Sales",
"Sal":4900
},
{
"Name":"FF",
"Age":30,
"Department":"Production",
"Sal":4520
}
];

$scope.workers=[
{
"Name":"alpha",
"Age":90,
"Department":"XYX",
"Sal":9999
},
{
"Name":"BETA",
"Age":80,
"Department":"ABC",
"Sal":88888
}];
 $scope.workers=angular.fromJson(jsonData2);
});

<input type="text" ng-model="searchOn" ">

{{ key }}

Name: {{usr.Name}} Age: {{usr.Age}}

{{ key }}

Name: {{wrk.Name}} Age: {{wrk.Age}}

the below is the $scope.users

Name Age Department Sal
AA 20 Sales  4000
BB 25 Accounts 6320
CC 34 Sales  8500
DD 32 Accounts 3500
EE 25 Sales  4900
FF 30 Production 4520

and the end result I want something like below

Department

 Sales:  AA 20 Sales  4000
         CC 34 Sales  8500
         EE 25 Sales  4900

 Accounts: BB 25 Accounts 6320
        DD 32 Accounts 3500

 Production: FF 30 Production 4520

Body:
You have to use a temporary variable to store your filtered users.
like :

ng-repeat="usr in filteredArray = (value | filter: searchOn)"

and bind the length of filter data to ng-if. like :

 <p ng-if="filteredArray.length > 0" ng-bind="key"></p>

See this working fiddle

Updated Fiddel Link for updated question.