问:
I want to enable textbox when checkbox is checked in jquery or javascript
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash" onclick="cash(this)">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div></code>```

答:
You can use disabled config to disable textbox on click of checkbox.

function handleChange(el) {
    var name = document.getElementById('name');
    name.disabled = !el.checked;
    name.focus()
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label><input type='checkbox' onclick='handleChange(this);'>Checkbox</label>
<br>
<label>Name : <input disabled=true type='text' id='name'></label></code>```

Body:
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}

  Cash <input type="checkbox" name="cash" id="cash" onclick="cash(this)">

  Amount *
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>

Body:
You can use disabled config to disable textbox on click of checkbox.

function handleChange(el) {
    var name = document.getElementById('name');
    name.disabled = !el.checked;
    name.focus()
}

<label><input type='checkbox' onclick='handleChange(this);'>Checkbox</label>
<br>
<label>Name : <input disabled=true type='text' id='name'></label>


来源: stackexchange

问:
WCF Optimal performance settings
Hi i am creating an API using WCF. My question can be broken down into two seperate ones

1) I have quite a few calls, for instance i have calls relating to the customer, products, orders, employees.

My question is should all this go into one public interface class e.g

```<code>public interface IRestService
public class RestService : IRestService
</code>```

Or should I have one for each call e.g

```<code>public interface ICustomer
public class Customer : ICustomer

public interface IProducts
public class Products: IProducts
</code>```

2) If you have an API which will be accessed by tens of thousands of users and thousands of users concurrently, how would you set up, what will your web config settings be for instance in terms of throttling. Also what setting would you give your InstanceContextMode, or ConcurrencyMode. Finally what type of binding would it be, bearing in mind websites and mobile phones can access the api.

答:
For the sake of good practice, I would break up the API into separate interfaces so you have the option of splitting them into separate implementations in the future. You can still have just one service class implement all of the interfaces, like this:

```<code>public class RestService : ICustomer, IProducts, IOrders
</code>```

However, it sounds as if you'd probably want to make them separate implementations anyway.

In terms of concurrency settings, ask yourself what resources need to be used on each call. If your service class's constructor can be written without any lengthy startup, then use PerCall. If you need to initialize expensive resources, then I'd recommend InstanceContextMode.Single with ConcurrencytMode.Multiple and make sure you write thread-safe code. Eg: make sure you lock() on any class properties or other shared resources before you use them.

Database connections would not count as "expensive to initialize", though, because ADO will do connection pooling for you and eliminate that overhead.

Your throttling settings will be revealed by testing, as Ladislav mentions. You'd want to stress-test your service and use the results to get an idea of how many machines you'd need to service your anticipated load. Then you'll need a dedicated load balancer to route requests as either round-robin, or something that checks the health of each server. Load balancers can be set up to GET a "systemhealth.asp" page and check the results. If you return an "OK" then that machine stays in the pool, or can be temporarily removed from the pool if it times out or returns any other status.

Your binding would need to be WebHTTPBinding for REST. BasicHTTPBinding is meant for SOAP interfaces and doesn't support [WebGet], for example.

If it doesn't have to be a REST service, then you can get a bit more performance by using NetTcpBinding.

ContentLicense: CC BY-SA 2.5

Title: WCF Optimal performance settings

Body:
Hi i am creating an API using WCF. My question can be broken down into two seperate ones

1) I have quite a few calls, for instance i have calls relating to the customer, products, orders, employees.

My question is should all this go into one public interface class e.g

public interface IRestService
public class RestService : IRestService

Or should I have one for each call e.g

public interface ICustomer
public class Customer : ICustomer

public interface IProducts
public class Products: IProducts

2) If you have an API which will be accessed by tens of thousands of users and thousands of users concurrently, how would you set up, what will your web config settings be for instance in terms of throttling. Also what setting would you give your InstanceContextMode, or ConcurrencyMode. Finally what type of binding would it be, bearing in mind websites and mobile phones can access the api.

Body:
For the sake of good practice, I would break up the API into separate interfaces so you have the option of splitting them into separate implementations in the future. You can still have just one service class implement all of the interfaces, like this:

public class RestService : ICustomer, IProducts, IOrders

However, it sounds as if you'd probably want to make them separate implementations anyway.

In terms of concurrency settings, ask yourself what resources need to be used on each call. If your service class's constructor can be written without any lengthy startup, then use PerCall. If you need to initialize expensive resources, then I'd recommend InstanceContextMode.Single with ConcurrencytMode.Multiple and make sure you write thread-safe code. Eg: make sure you lock() on any class properties or other shared resources before you use them.

Database connections would not count as "expensive to initialize", though, because ADO will do connection pooling for you and eliminate that overhead.

Your throttling settings will be revealed by testing, as Ladislav mentions. You'd want to stress-test your service and use the results to get an idea of how many machines you'd need to service your anticipated load. Then you'll need a dedicated load balancer to route requests as either round-robin, or something that checks the health of each server. Load balancers can be set up to GET a "systemhealth.asp" page and check the results. If you return an "OK" then that machine stays in the pool, or can be temporarily removed from the pool if it times out or returns any other status.

Your binding would need to be WebHTTPBinding for REST. BasicHTTPBinding is meant for SOAP interfaces and doesn't support [WebGet], for example.

If it doesn't have to be a REST service, then you can get a bit more performance by using NetTcpBinding.


问:
Deselecting an item in collection view and removing that from an array not working
I am trying to select a cell and add the content of that cell into an array and then to be able to deselect a cell and remove that same object from the array. I've been struggling for a few days and still can't seem to get it work. Select and deselect functionality works, it's adding objects to the array but upon deselection, I don't know how to remove that same object from the array. How can I deselect the cell and remove that from the array?

This is my code:

```<code>    struct Friends {
    var friendName : String!
}

struct SelectedMembers {
    var selectedFriend : String!
}

    var friends = [Friends]()
    var selectedFriends = [SelectedMembers]()

        //MARK: Select multiple cells
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as? FriendsCell
        selectedCell.append(indexPath)
        cell?.contentView.backgroundColor = .red
        print("Friends are: \(String(describing: cell?.nameSurname.text!))")

        if (cell?.isSelected)! {
            print("this is selected...")
            var selection = SelectedMembers()
            selection.selectedFriend = friends[indexPath.item].friendName
            selectedFriends.append(selection)

            print(selectedFriends)

        }

    }

    //MARK: Deselect Multiple cells
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let deselectedCell = collectionView.cellForItem(at: indexPath) as? FriendsCell
        print(indexPath.row)
        if let index = selectedFriends.index(of: selectedFriends[indexPath.row]) {
            selectedFriends.remove(at: index)
        }

        if selectedCell.contains(indexPath) {
            selectedCell.remove(at: selectedCell.index(of: indexPath)!)
            deselectedCell?.contentView.backgroundColor = .white
            print(selectedCell)
        }

        print(selectedFriends)
    }
}
</code>```

答:
this piece of code is the culprit.

if let index = selectedFriends.index(of: selectedFriends[indexPath.row]) {selectedFriends.remove(at: index)}

For example, if you have 100 rows, and if you have selected 1, 10, 50 cells, your selectedFriends array contains only 3 objects, but when someone deselected the 50 the cell, in the above code you are trying to access selectedFriends[50]..so it is not proper.

you don't need to maintain selectedCell array to keep track of selected/unselected indexes. Whenever a cell is selected you will get a callback in didSelecte and only selected cells only can be deselected.

place the below code in didDeselect()

```<code>let deselectedCell = collectionView.cellForItem(at: indexPath) as? FriendsCell
deselectedCell?.contentView.backgroundColor = .white
let friendName = friends[indexPath.item].friendName
var deselectedIndex:Int
for (index,value) in selectedFriends.enumerated() { if value.friendName == freindName { deselectedIndex = index }}
selectedFriends.remove(at:deselectedIndex}
</code>```

It is better to use Dictionary if your friend list is more, so you can avoid the for loop to find the deselected friend. Implement Equatable protocol instead of checking the only name if you go ahead with array implementation.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to select a cell and add the content of that cell into an array and then to be able to deselect a cell and remove that same object from the array. I've been struggling for a few days and still can't seem to get it work. Select and deselect functionality works, it's adding objects to the array but upon deselection, I don't know how to remove that same object from the array. How can I deselect the cell and remove that from the array?

This is my code:

    struct Friends {
    var friendName : String!
}

struct SelectedMembers {
    var selectedFriend : String!
}

    var friends = [Friends]()
    var selectedFriends = [SelectedMembers]()

        //MARK: Select multiple cells
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as? FriendsCell
        selectedCell.append(indexPath)
        cell?.contentView.backgroundColor = .red
        print("Friends are: \(String(describing: cell?.nameSurname.text!))")

        if (cell?.isSelected)! {
            print("this is selected...")
            var selection = SelectedMembers()
            selection.selectedFriend = friends[indexPath.item].friendName
            selectedFriends.append(selection)

            print(selectedFriends)

        }

    }

    //MARK: Deselect Multiple cells
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let deselectedCell = collectionView.cellForItem(at: indexPath) as? FriendsCell
        print(indexPath.row)
        if let index = selectedFriends.index(of: selectedFriends[indexPath.row]) {
            selectedFriends.remove(at: index)
        }

        if selectedCell.contains(indexPath) {
            selectedCell.remove(at: selectedCell.index(of: indexPath)!)
            deselectedCell?.contentView.backgroundColor = .white
            print(selectedCell)
        }

        print(selectedFriends)
    }
}

Body:
this piece of code is the culprit.

if let index = selectedFriends.index(of: selectedFriends[indexPath.row]) {selectedFriends.remove(at: index)}

For example, if you have 100 rows, and if you have selected 1, 10, 50 cells, your selectedFriends array contains only 3 objects, but when someone deselected the 50 the cell, in the above code you are trying to access selectedFriends[50]..so it is not proper.

you don't need to maintain selectedCell array to keep track of selected/unselected indexes. Whenever a cell is selected you will get a callback in didSelecte and only selected cells only can be deselected.

place the below code in didDeselect()

let deselectedCell = collectionView.cellForItem(at: indexPath) as? FriendsCell
deselectedCell?.contentView.backgroundColor = .white
let friendName = friends[indexPath.item].friendName
var deselectedIndex:Int
for (index,value) in selectedFriends.enumerated() { if value.friendName == freindName { deselectedIndex = index }}
selectedFriends.remove(at:deselectedIndex}

It is better to use Dictionary if your friend list is more, so you can avoid the for loop to find the deselected friend. Implement Equatable protocol instead of checking the only name if you go ahead with array implementation.


问:
ggplot color bar for less than and great than Average
What I am trying to write is, if the Team on the X axis is less than Average on the X axis or in this case 17.62, color it different and same for Greater than. So Average on the X axis is black and then the ones above and below are different colors.

```<code>dput()Road.Team Goalie.Pts.at.Home.Vs.Road.TEAM
1        ANA                        16.67692
2        ARI                        23.20000
3        BOS                        18.86667
4        BUF                        23.14667
5        CAR                        23.44615
6        CBJ                        16.62857
7        CGY                        17.33333
8        CHI                        21.77143
9        COL                        18.70769
10       DAL                        18.70000
11       DET                        20.32000
12       EDM                        16.94118
13       FLA                        23.68000
14       LAK                        12.14118
15       MIN                        17.49333
16       MTL                        21.71429
17       NJD                        11.64444
18       NSH                        17.12000
19       NYI                        15.55556
20       NYR                        18.04444
21       OTT                        13.31429
22       PHI                        21.25714
23       PIT                        20.28235
24       SJS                        14.45714
25       STL                        15.80000
26       TBL                        12.21333
27       TOR                        10.44444
28       VAN                        14.40000
29       VGK                        16.35000
30       WPG                        19.41333
31       WSH                        15.26154
32   Average                        17.62340
</code>```

```<code>rm(stats)
stats <- read.csv("HomeGoaliesPtsforVisitingTeam.csv")
stats
library(tidyverse)
p <- stats %>%
  gather(key, value, -Road.Team) %>%
  ggplot(aes(x=Road.Team, y=value)) +
  geom_col(position = "dodge")
p + labs(y = "FanDuel Goalie Pts",x = "Road Team",title = "Points for Home Goalies Vs Road Team")
</code>```

答:
Create a logical variable in your stats data frame and pass that to the fill argument in aes().  Something like:

```<code>stats$compare <- stats$y <= mean(stats$y)

p <- stats %>%
  gather(key, value, -Road.Team) %>%
  ggplot(aes(x=Road.Team, y=value, fill=compare)) +
  geom_col(position = "dodge")
</code>```

Body:
What I am trying to write is, if the Team on the X axis is less than Average on the X axis or in this case 17.62, color it different and same for Greater than. So Average on the X axis is black and then the ones above and below are different colors.

dput()Road.Team Goalie.Pts.at.Home.Vs.Road.TEAM
1        ANA                        16.67692
2        ARI                        23.20000
3        BOS                        18.86667
4        BUF                        23.14667
5        CAR                        23.44615
6        CBJ                        16.62857
7        CGY                        17.33333
8        CHI                        21.77143
9        COL                        18.70769
10       DAL                        18.70000
11       DET                        20.32000
12       EDM                        16.94118
13       FLA                        23.68000
14       LAK                        12.14118
15       MIN                        17.49333
16       MTL                        21.71429
17       NJD                        11.64444
18       NSH                        17.12000
19       NYI                        15.55556
20       NYR                        18.04444
21       OTT                        13.31429
22       PHI                        21.25714
23       PIT                        20.28235
24       SJS                        14.45714
25       STL                        15.80000
26       TBL                        12.21333
27       TOR                        10.44444
28       VAN                        14.40000
29       VGK                        16.35000
30       WPG                        19.41333
31       WSH                        15.26154
32   Average                        17.62340

rm(stats)
stats <- read.csv("HomeGoaliesPtsforVisitingTeam.csv")
stats
library(tidyverse)
p <- stats %>%
  gather(key, value, -Road.Team) %>%
  ggplot(aes(x=Road.Team, y=value)) +
  geom_col(position = "dodge")
p + labs(y = "FanDuel Goalie Pts",x = "Road Team",title = "Points for Home Goalies Vs Road Team")

Body:
Create a logical variable in your stats data frame and pass that to the fill argument in aes().  Something like:

stats$compare <- stats$y <= mean(stats$y)

p <- stats %>%
  gather(key, value, -Road.Team) %>%
  ggplot(aes(x=Road.Team, y=value, fill=compare)) +
  geom_col(position = "dodge")


问:
Generating maps Dynamically
I am looking to generate transport maps in a style similar to the iconic London underground [tube] map.

These maps will change from time to time and many will be required so instead of drawing them up manually in inkscape [or similar] I am hoping to have them generated dynamically from a db or dataset.

Does anyone know if there is any library apis etc. out there that would help with this task, or any suggestions in general of how [or how not] to go about this ?

I am thinking svg's would be the best way to go with this, plus there may be need for basic interactivity down the line.

I am working in php so otherwise it's GDlib, ImageMagick ?

Thanks in advance.

.k

答:
These maps will change from time to
  time and many will be required so
  instead of drawing them up manually in
  inkscape [or similar] I am hoping to
  have them generated dynamically from a
  db or dataset.

If I were in your shoes, the very first thing I'd do is try to prove that the Google Maps API won't work for your application. Then, maybe, prove that ArcGIS won't work. (Even if they don't work, they're widely used, and you get to add lines to your CV.)

Title: Generating maps Dynamically


问:
iOS - Regionmonitoring in StandBy
I´ve implemented a monitoring function for beacons (didEnterRegion).
It works great if I use my iPhone. (App is in foreground, background or only installed and closed but my iPhone has to be in use (screen on).)

If my phone is in standBy mode (top button pressed), I get no notification with didEnterRegion.
If I use my phone (screen on), the notification pop up.
Is there an opportunity to get the didEnterRegion event also in the standby mode?

```<code>self->beaconLocationManager = [[CLLocationManager alloc] init];
[self->beaconLocationManager requestAlwaysAuthorization];
self->beaconLocationManager.delegate = self;
beaconLocationManager.allowsBackgroundLocationUpdates = YES;
NSString* beaconIdentName = [NSString stringWithFormat:@"Beacon%d", cnt];
NSUUID *uuid2=[[NSUUID alloc]initWithUUIDString:uuid];
clBeconRegion2=[[CLBeaconRegion alloc]initWithProximityUUID:uuid2 identifier:beaconIdentName];
clBeconRegion2.notifyOnEntry=YES;
clBeconRegion2.notifyEntryStateOnDisplay = NO;
[self->beaconLocationManager startMonitoringForRegion:clBeconRegion2];
[self->beaconLocationManager startRangingBeaconsInRegion:clBeconRegion2];

...

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    NSLog(@"ENTER REGION");
    UILocalNotification *localNotification = [[UILocalNotification alloc]init];
    localNotification.alertBody = @"FOUNDED";
    localNotification.alertAction = [NSString stringWithFormat:@"%@ Connecting...", region.identifier];
    [[UIApplication sharedApplication]presentLocalNotificationNow:localNotification];
}
</code>```

Project settings:
Push notifications are on.
Background modes for location updates, backgroudn fetch, uses bluetooth LE accessories are on.

Tested on iOS 11.1

答:
How long have you waited for background detection? This can take up to 15 minutes.

See here for details: http://developer.radiusnetworks.com/2013/11/13/ibeacon-monitoring-in-the-background-and-foreground.html

As described in that article, you do not need to set location updates Background Mode to YES.
Also you don't need to specify notifyOnExit and notifyOnEntry as true.

Hope this may help.

Title: iOS - Regionmonitoring in StandBy

Body:
I´ve implemented a monitoring function for beacons (didEnterRegion).
It works great if I use my iPhone. (App is in foreground, background or only installed and closed but my iPhone has to be in use (screen on).)

If my phone is in standBy mode (top button pressed), I get no notification with didEnterRegion.
If I use my phone (screen on), the notification pop up.
Is there an opportunity to get the didEnterRegion event also in the standby mode?

self->beaconLocationManager = [[CLLocationManager alloc] init];
[self->beaconLocationManager requestAlwaysAuthorization];
self->beaconLocationManager.delegate = self;
beaconLocationManager.allowsBackgroundLocationUpdates = YES;
NSString* beaconIdentName = [NSString stringWithFormat:@"Beacon%d", cnt];
NSUUID *uuid2=[[NSUUID alloc]initWithUUIDString:uuid];
clBeconRegion2=[[CLBeaconRegion alloc]initWithProximityUUID:uuid2 identifier:beaconIdentName];
clBeconRegion2.notifyOnEntry=YES;
clBeconRegion2.notifyEntryStateOnDisplay = NO;
[self->beaconLocationManager startMonitoringForRegion:clBeconRegion2];
[self->beaconLocationManager startRangingBeaconsInRegion:clBeconRegion2];

...

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    NSLog(@"ENTER REGION");
    UILocalNotification *localNotification = [[UILocalNotification alloc]init];
    localNotification.alertBody = @"FOUNDED";
    localNotification.alertAction = [NSString stringWithFormat:@"%@ Connecting...", region.identifier];
    [[UIApplication sharedApplication]presentLocalNotificationNow:localNotification];
}

Project settings:
Push notifications are on.
Background modes for location updates, backgroudn fetch, uses bluetooth LE accessories are on.

Tested on iOS 11.1


答:
Smallest, simplest and easiest thing to do, using the true/false state of checkbox thereby avoiding if-else:

$('body').on('change', '#cash', function() {
  $('#cashAmount').prop("disabled", !this.checked);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div></code>```

Title: I want to enable textbox when checkbox is checked in jquery or javascript

Body:
Smallest, simplest and easiest thing to do, using the true/false state of checkbox thereby avoiding if-else:

$('body').on('change', '#cash', function() {
  $('#cashAmount').prop("disabled", !this.checked);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div>


问:
Join two observable arrays together
```<code>checkAllThreads() {
    const userId = this.auth.getUser().uid;
    const buyerThreads = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges();
    const sellerThreads = this.afs.collection('threads', ref => ref.where('sellerId', '==', userId)).valueChanges();
    this.subscription = forkJoin(buyerThreads, sellerThreads)
      .map(([bT, sT]) => [...bT, ...sT])
      .subscribe(res=> {
        console.log(res) //never console logs
        //logic to iterate through array, look for unread threads goes here
      });
  }
</code>```

I'm using AngularFire2 to query my Firestore database for all documents in the 'threads' collection with the fields sellerId or buyerId equal to their userId. From what I understand, AngularFire2 does not allow you to query all documents where either one is true; if you chain their .where() method, it will return all documents where both are true (which in my case would be 0). So, I'm trying to get two Observable arrays and combine them in one single array in order to tell the user in real time whether or not they have unread messages.

I tried the code above (adapted from an answer here), which didn't run anything in the subscribe method. From what I can tell, I think it's because my observables aren't completed, as I need to have the data update in real time. Is there any way to take two still-streaming observable arrays and combine them into one, or will I have to figure out another way?

答:
Use combineLatest instead of forkJoin.

So it should be...

```<code>checkAllThreads() {
    const userId = this.auth.getUser().uid;
    const buyerThreads = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges();
    const sellerThreads = this.afs.collection('threads', ref => ref.where('sellerId', '==', userId)).valueChanges();
    this.subscription = Observable.combineLatest(buyerThreads, sellerThreads)
      .map(([bT, sT]) => [...bT, ...sT])
      .subscribe(res=> {
        console.log(res);
      });
  }
</code>```

You may need to import these two lines.

```<code>import 'rxjs/add/observable/combineLatest';
import { Observable } from 'rxjs/Observable';
</code>```

Title: Join two observable arrays together

Body:
checkAllThreads() {
    const userId = this.auth.getUser().uid;
    const buyerThreads = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges();
    const sellerThreads = this.afs.collection('threads', ref => ref.where('sellerId', '==', userId)).valueChanges();
    this.subscription = forkJoin(buyerThreads, sellerThreads)
      .map(([bT, sT]) => [...bT, ...sT])
      .subscribe(res=> {
        console.log(res) //never console logs
        //logic to iterate through array, look for unread threads goes here
      });
  }

I'm using AngularFire2 to query my Firestore database for all documents in the 'threads' collection with the fields sellerId or buyerId equal to their userId. From what I understand, AngularFire2 does not allow you to query all documents where either one is true; if you chain their .where() method, it will return all documents where both are true (which in my case would be 0). So, I'm trying to get two Observable arrays and combine them in one single array in order to tell the user in real time whether or not they have unread messages.

I tried the code above (adapted from an answer here), which didn't run anything in the subscribe method. From what I can tell, I think it's because my observables aren't completed, as I need to have the data update in real time. Is there any way to take two still-streaming observable arrays and combine them into one, or will I have to figure out another way?

Body:
Use combineLatest instead of forkJoin.

So it should be...

checkAllThreads() {
    const userId = this.auth.getUser().uid;
    const buyerThreads = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges();
    const sellerThreads = this.afs.collection('threads', ref => ref.where('sellerId', '==', userId)).valueChanges();
    this.subscription = Observable.combineLatest(buyerThreads, sellerThreads)
      .map(([bT, sT]) => [...bT, ...sT])
      .subscribe(res=> {
        console.log(res);
      });
  }

You may need to import these two lines.

import 'rxjs/add/observable/combineLatest';
import { Observable } from 'rxjs/Observable';


问:
Windows Services Error in C#
I using c#. At this time I using Windows 7.My question is ; When I running my code,
that's gives me errors etc 193:0xc1 error , Services started but after stopped , 1053 services  errors.
Here is my code.

```<code>    public RupdaterService()
    {
        InitializeComponent();
        this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
    }
      protected override void OnStart (string[] args)
    {
        timer1.Enabled=true;
        this.DBEntry("Service Started");
    }
      protected override void OnStop()
    {
        this.timer1.Enabled = false;
        this.DBEntry("Service Stopped");
    }

    private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
    {

        this.DBEntry("Service Running");
        }

 Here is my App.Config.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<configSections>

    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5***9" >
        <section name="HedefliRUpdater.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5***9" requirePermission="false" />
    </sectionGroup>
</configSections>

<system.serviceModel>

</system.serviceModel>

<applicationSettings>
    <HedefliRUpdater.Properties.Settings>
        <setting name="HedefliRUpdater_srvHedefli_wsrvHermesHedefliMesaj"
            serializeAs="String">
            <value>http://***.com/hedefli/srvHedefli.asmx</value>
        </setting>
    </HedefliRUpdater.Properties.Settings>
</applicationSettings>
</code>```

Thanks in advance,

答: I don't know what your problem is, but this question Easier way to debug a Windows service provides excellent tips to allow you to debug the startup of your service.</p>

Title: Windows Services Error in C#

Body:
I using c#. At this time I using Windows 7.My question is ; When I running my code,
that's gives me errors etc 193:0xc1 error , Services started but after stopped , 1053 services  errors.
Here is my code.

    public RupdaterService()
    {
        InitializeComponent();
        this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
    }
      protected override void OnStart (string[] args)
    {
        timer1.Enabled=true;
        this.DBEntry("Service Started");
    }
      protected override void OnStop()
    {
        this.timer1.Enabled = false;
        this.DBEntry("Service Stopped");
    }

    private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
    {

        this.DBEntry("Service Running");
        }

 Here is my App.Config.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<configSections>

    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5***9" >

    </sectionGroup>
</configSections>

<system.serviceModel>

</system.serviceModel>

<applicationSettings>
    <HedefliRUpdater.Properties.Settings>
        <setting name="HedefliRUpdater_srvHedefli_wsrvHermesHedefliMesaj"
            serializeAs="String">
            <value>http://***.com/hedefli/srvHedefli.asmx</value>
        </setting>
    </HedefliRUpdater.Properties.Settings>
</applicationSettings>

Thanks in advance,


问:
Can't Navigate Between Activities
I have two activities, trying to navigate from the first one to the second one by pressing a button. First one is like this:

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_first);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_new_message);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(FirstActivity.this, SecondActivity.class);
            startActivity(myIntent);
        }
    });
}
</code>```

And the second one is like this:

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_second);
   // other stuff
}
</code>```

When the Floating Action Button is pressed then, absolutely nothing happens. What is wrong with my code?

Update: This is the manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="...">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".firstActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="secondActivity"></activity>

    </application>

</manifest>
</code>```

And this is the code for Floating Action Button:

```<code>FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    //Button button = (Button) findViewById(R.id.button);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast toast = Toast.makeText(getApplicationContext(), "Pressed!", Toast.LENGTH_LONG);
            toast.show();
                        }
    });
</code>```

In XML:

```<code> <android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:id="@+id/fab"
    android:tint="@android:color/white"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    app:fabSize="mini"
    android:layout_alignParentRight="true" />
</code>```

The whole layout:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:id="@+id/fab"
        android:tint="@android:color/white"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        app:fabSize="mini"
        android:layout_alignParentRight="true" />

    <ListView
        android:id="@+id/list_of_messages"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:clickable="true"
        android:divider="@android:color/transparent"
        android:dividerHeight="16dp"
        android:focusable="auto"
        android:focusableInTouchMode="true" />
</RelativeLayout>
</code>```

答:
Try changing to this inside your Manifest.xml file:

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".FirstActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SecondActivity"></activity>

</application>
</code>```

EDIT-

To bring FAB to front use:

           fab.bringToFront(); before setting onClickListener to it.

Thanks for pointing out Mike M

Title: Can't Navigate Between Activities

Body:
I have two activities, trying to navigate from the first one to the second one by pressing a button. First one is like this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_first);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_new_message);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(FirstActivity.this, SecondActivity.class);
            startActivity(myIntent);
        }
    });
}

And the second one is like this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_second);
   // other stuff
}

When the Floating Action Button is pressed then, absolutely nothing happens. What is wrong with my code?

Update: This is the manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="...">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".firstActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="secondActivity"></activity>

    </application>

</manifest>

And this is the code for Floating Action Button:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    //Button button = (Button) findViewById(R.id.button);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast toast = Toast.makeText(getApplicationContext(), "Pressed!", Toast.LENGTH_LONG);
            toast.show();
                        }
    });

In XML:

 <android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:id="@+id/fab"
    android:tint="@android:color/white"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    app:fabSize="mini"
    android:layout_alignParentRight="true" />

The whole layout:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:id="@+id/fab"
        android:tint="@android:color/white"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        app:fabSize="mini"
        android:layout_alignParentRight="true" />

    <ListView
        android:id="@+id/list_of_messages"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:clickable="true"
        android:divider="@android:color/transparent"
        android:dividerHeight="16dp"
        android:focusable="auto"
        android:focusableInTouchMode="true" />
</RelativeLayout>

Body:
Try changing to this inside your Manifest.xml file:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".FirstActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SecondActivity"></activity>

</application>

EDIT-

To bring FAB to front use:

           fab.bringToFront(); before setting onClickListener to it.

Thanks for pointing out Mike M


问:
How to open .jl file
I want to open a .jl file and convert it to a readable file preferably in .xls format.
I do not have any any idea about Julia language.
Is there a file opener for jl files?

答:
A .jl file is a julia script.
It is source code.
Not data.

You can open it up in any text editor, e.g. notepad on windows.
However, it won't normally contain anything useful to you unless you want to edit that code.
(It might contain some array literals that you want, I guess)

Perhaps you mean to ask "How can I open a .jld file"?
Which is a julia HDF5 file.
In which case please ask another question.

ContentLicense: CC BY-SA 4.0

Title: How to open .jl file


问:
Ionic 2 video capturing
Can someone help me out where i can find or tell me how to implement video capturing for ionic 2 typescript.

I know about the picture taking which is simple but theirs no clear documentation on how to capture videos

答:
Install the Cordova and Ionic Native plugins:

```<code>    ionic cordova plugin add cordova-plugin-media-capture
    npm install --save @ionic-native/media-capture
</code>```

videoplayer.html

```<code>   <ion-content padding>
   <button ion-button (click)="startrecording()">Start Video
   Recording</button>
   <button ion-button (click)="selectvideo()">Select Video From
   Gallery</button>
   <video #myvideo height="300" width="300" controls></video>
   </ion-content>
</code>```

videoplayer.ts

```<code>    import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from '@ionic-native/media-capture';
    import { Camera } from "@ionic-native/camera";
    .......
    @ViewChild('myvideo') myVideo: any;
    ......
    constructor(public camera:Camera, private mediaCapture: MediaCapture)
    {}
    startrecording() {
    this.mediaCapture.captureVideo((videodata) => {
    alert(JSON.stringify(videodata));
    })
    }

    selectvideo() {
    let video = this.myVideo.nativeElement;
    var options = {
    sourceType: 2,
    mediaType: 1
    };

    this.camera.getPicture(options).then((data) => {
    video.src = data;
    video.play();
   })
   }
  }
</code>```

Source : http://tphangout.com/ionic-2-video-capture-and-playback/
         https://ionicframework.com/docs/native/media-capture/

Title: Ionic 2 video capturing

Body:
Install the Cordova and Ionic Native plugins:

    ionic cordova plugin add cordova-plugin-media-capture
    npm install --save @ionic-native/media-capture

videoplayer.html

   <ion-content padding>
   <button ion-button (click)="startrecording()">Start Video
   Recording</button>
   <button ion-button (click)="selectvideo()">Select Video From
   Gallery</button>
   <video #myvideo height="300" width="300" controls></video>
   </ion-content>

videoplayer.ts

    import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from '@ionic-native/media-capture';
    import { Camera } from "@ionic-native/camera";
    .......
    @ViewChild('myvideo') myVideo: any;
    ......
    constructor(public camera:Camera, private mediaCapture: MediaCapture)
    {}
    startrecording() {
    this.mediaCapture.captureVideo((videodata) => {
    alert(JSON.stringify(videodata));
    })
    }

    selectvideo() {
    let video = this.myVideo.nativeElement;
    var options = {
    sourceType: 2,
    mediaType: 1
    };

    this.camera.getPicture(options).then((data) => {
    video.src = data;
    video.play();
   })
   }
  }

Source : http://tphangout.com/ionic-2-video-capture-and-playback/
         https://ionicframework.com/docs/native/media-capture/


问:
Routes how to hide them on the url bar rails 3
My route file has the following in it for the root. what i want is when i click on say about it doesn't show me http://127.0.0.1:3000/home/about what i would like is either http://127.0.0.1:3000/about
or just the URL http://127.0.0.1:3000/ like root dose. I'm running rails 3 if you can post a snip it of a route file that will do this or give me a url to see it at that would be great.

```<code># You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => "home#index"

# See how all your routes lay out with "rake routes"
</code>```

答:
Check out http://edgeguides.rubyonrails.org/routing.html for more details.

You should put the root route at the end of the file.

You need to delete the public/index.html file for the root route to take effect.

Make sure you have a home controller

Make sure you have a view called index in the views/home/ folder

Then http://127.0.0.1:3000/ will display your index action

If you want your root to go to the about action, also change the route file to root :to => "home#about". Of course make sure you have an about view.

Body:
My route file has the following in it for the root. what i want is when i click on say about it doesn't show me http://127.0.0.1:3000/home/about what i would like is either http://127.0.0.1:3000/about
or just the URL http://127.0.0.1:3000/ like root dose. I'm running rails 3 if you can post a snip it of a route file that will do this or give me a url to see it at that would be great.

# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => "home#index"

# See how all your routes lay out with "rake routes"


问:
how to tell between return values from setInterval in nodejs
The return value from setInterval in nodejs is not a number but an object. Then how can I identify which timer object is returned? The following console.log only prints [object Object].</p>

```<code>  res.writeHead(200, {
        'Connection': 'keep-alive',
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache'
      });
  const id=setInterval(function(){

      res.write('data:helloworld! \n\n');

    }, 1000);
  console.log("to begin:interval id is "+id)

  req.on("close",function(){
    console.log("to end:interval id is "+id)
    clearInterval(id)
  })
</code>```

答:
If what you're trying to do here is to identify different timers in your logging so you can correlate log messages to a particular timer, then you can put an identifiable property on each timer object and then log that id value.</p>

```<code>  // variable declared at a module level scope so it persists:
  let timerCntr = 1;

  // code inside your request handler

  res.writeHead(200, {
      'Connection': 'keep-alive',
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache'
  });

  const timer = setInterval(function() {
      res.write('data:helloworld! \n\n');
  }, 1000);
  // assign ID to the timer object
  timer.myid = timerCntr++;
  console.log("to begin:interval id is " + timer.myid)

  req.on("close", function() {
      console.log("to end:interval id is " + timer.myid)
      clearInterval(timer);
  })
</code>```

Body:
The return value from setInterval in nodejs is not a number but an object. Then how can I identify which timer object is returned? The following console.log only prints [object Object].

  res.writeHead(200, {
        'Connection': 'keep-alive',
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache'
      });
  const id=setInterval(function(){

      res.write('data:helloworld! \n\n');

    }, 1000);
  console.log("to begin:interval id is "+id)

  req.on("close",function(){
    console.log("to end:interval id is "+id)
    clearInterval(id)
  })

Body:
If what you're trying to do here is to identify different timers in your logging so you can correlate log messages to a particular timer, then you can put an identifiable property on each timer object and then log that id value.

  // variable declared at a module level scope so it persists:
  let timerCntr = 1;

  // code inside your request handler

  res.writeHead(200, {
      'Connection': 'keep-alive',
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache'
  });

  const timer = setInterval(function() {
      res.write('data:helloworld! \n\n');
  }, 1000);
  // assign ID to the timer object
  timer.myid = timerCntr++;
  console.log("to begin:interval id is " + timer.myid)

  req.on("close", function() {
      console.log("to end:interval id is " + timer.myid)
      clearInterval(timer);
  })


问:
How to detect if navigation drawer is open?
The title explains it all. All what I want to do is to know if the navigation drawer is open or not. I searched a lot on the net and found the method isDrawerOpen(int drawerGravity)but couldn't find a satisfactory answer which explains how to use it in a method. I would appreciate if anyone explains it to me.

答:
By the following way you can find the Drawer is open or close..</p>

```<code> public class YourActivity extends AppCompatActivity implements  DrawerLayout.DrawerListener {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dash_board);

        DrawerLayout drawer=(DrawerLayout)findViewById(R.id.container);
        drawer.setDrawerListener(this);
    }//onCreate()

    @Override
    public void onDrawerOpened(View arg0) {
      //write your code
    }

    @Override
    public void onDrawerClosed(View arg0) {
        //write your code
    }

    @Override
    public void onDrawerSlide(View arg0, float arg1) {
        //write your code
    }

    @Override
    public void onDrawerStateChanged(int arg0) {
        //write your code
    }
}//class
</code>```

Body:
By the following way you can find the Drawer is open or close..

 public class YourActivity extends AppCompatActivity implements  DrawerLayout.DrawerListener {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dash_board);

        DrawerLayout drawer=(DrawerLayout)findViewById(R.id.container);
        drawer.setDrawerListener(this);
    }//onCreate()

    @Override
    public void onDrawerOpened(View arg0) {
      //write your code
    }

    @Override
    public void onDrawerClosed(View arg0) {
        //write your code
    }

    @Override
    public void onDrawerSlide(View arg0, float arg1) {
        //write your code
    }

    @Override
    public void onDrawerStateChanged(int arg0) {
        //write your code
    }
}//class


问:
How to use webpack to watch and update on changes?
I am learning metaljs and trying to setup development environment. I am following the getting-started JSX part. I am having problem setting up localhost server on my development environment that updates when I make changes. This app uses webpack.

Let me elaborate my situation:

On src/Modal.js, I have:

```<code><div class="my-modal">
    <h2>Hello World!</h2>
    <p>Test 123</p>
</div>
</code>```

The way I view what it looks like, is that I am currently running index.html on google chrome (without running any server) - I also have my webpack --watch on to compile any changes on files:

file:///Users/iggy/path/to/index.html

When I change content from 123 to 456. Webpack --watch automatically detects it. I refresh Chrome, and voila! It is changed:

All is great but I wish to run it on server instead. My ideal env would be like when I run create-react-app -> npm run start (react-scripts start). In short, the ideal environment would be to run it on a localhost server, and whenever I make any edit on my files, webpack would recompile and when I refresh, it would update. However, I can't think of a good way to implement it.

I have tried using http-server -p 4000 while running webpack --watch, but when I update my file, it would not update when I refresh the localhost:4000.

Is there a way to setup my development environment to run my metaljs app on localhost server, watch for updates, and allow me to refresh to see the update?

Repo can be found here

答:
Using Hot-module-replacement with webpack-dev-server should auto refresh.

Have a read of this https://webpack.js.org/guides/hot-module-replacement/

cheers

Body:
I am learning metaljs and trying to setup development environment. I am following the getting-started JSX part. I am having problem setting up localhost server on my development environment that updates when I make changes. This app uses webpack.

Let me elaborate my situation:

On src/Modal.js, I have:

Hello World!

Test 123

The way I view what it looks like, is that I am currently running index.html on google chrome (without running any server) - I also have my webpack --watch on to compile any changes on files:

file:///Users/iggy/path/to/index.html

When I change content from 123 to 456. Webpack --watch automatically detects it. I refresh Chrome, and voila! It is changed:

All is great but I wish to run it on server instead. My ideal env would be like when I run create-react-app -> npm run start (react-scripts start). In short, the ideal environment would be to run it on a localhost server, and whenever I make any edit on my files, webpack would recompile and when I refresh, it would update. However, I can't think of a good way to implement it.

I have tried using http-server -p 4000 while running webpack --watch, but when I update my file, it would not update when I refresh the localhost:4000.

Is there a way to setup my development environment to run my metaljs app on localhost server, watch for updates, and allow me to refresh to see the update?

Repo can be found here


答:
As I see, Julia is a script language therefor the file can be opened in a text editor like Notepad++, Vim, etc. Do not use word processor (like LibreOffice Writer) if you want to modify it, but it's OK if you want to read only.

To get started:
https://docs.julialang.org/en/stable/

Title: How to open .jl file

Body:
I want to open a .jl file and convert it to a readable file preferably in .xls format.
I do not have any any idea about Julia language.
Is there a file opener for jl files?


问:
Swift: Adding text to image does not work
I'm trying to edit an image by adding text to it, but the code I got from this post does not work: How to write text on image in Objective-C (iOS)?

My image-editing code looks like this:

```<code>func addTextToImage(image:UIImage, text:NSString, pointof: CGPoint) -> UIImage{

    let font:UIFont = UIFont.boldSystemFontOfSize(12)

    let dict:NSDictionary = [NSFontAttributeName : font]

    UIGraphicsBeginImageContext(image.size)
    image.drawInRect(CGRectMake(0, 0, image.size.width, image.size.height))
    let rect: CGRect = CGRectMake(pointof.x, pointof.y, image.size.width, image.size.height)
    let color: UIColor = UIColor.whiteColor()
    text.drawInRect(CGRectIntegral(rect), withAttributes:dict)

    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}
</code>```

And then I use the textViewDidChange method to add the text to the image, but it does not work:

```<code>func textViewDidChange(textView: UITextView){
    backgroundImage.image = addTextToImage(imageToView, text: textViewer.text, pointof: CGPointMake(0, 0))
}
</code>```

Any suggestions on what I'm doing wrong would be appreciated.

答:
```<code>func addTextToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage
{
    let textColor = UIColor.blue

    let textFont = UIFont(name: "ChalkboardSE-Regular", size: 26)!

    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(image.size, false, scale)

    let textFontAttributes = [
        NSFontAttributeName: textFont,
        NSForegroundColorAttributeName: textColor,
        ] as [String : Any]

    image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))

    let rect = CGRect(origin: point, size: image.size)
    text.draw(in: rect, withAttributes: textFontAttributes)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}
</code>```

Body:
I'm trying to edit an image by adding text to it, but the code I got from this post does not work: How to write text on image in Objective-C (iOS)?

My image-editing code looks like this:

func addTextToImage(image:UIImage, text:NSString, pointof: CGPoint) -> UIImage{

    let font:UIFont = UIFont.boldSystemFontOfSize(12)

    let dict:NSDictionary = [NSFontAttributeName : font]

    UIGraphicsBeginImageContext(image.size)
    image.drawInRect(CGRectMake(0, 0, image.size.width, image.size.height))
    let rect: CGRect = CGRectMake(pointof.x, pointof.y, image.size.width, image.size.height)
    let color: UIColor = UIColor.whiteColor()
    text.drawInRect(CGRectIntegral(rect), withAttributes:dict)

    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

And then I use the textViewDidChange method to add the text to the image, but it does not work:

func textViewDidChange(textView: UITextView){
    backgroundImage.image = addTextToImage(imageToView, text: textViewer.text, pointof: CGPointMake(0, 0))
}

Any suggestions on what I'm doing wrong would be appreciated.


问:
extension method as a way to rename property
Some class has ugly field called URL, but Id rather call it file.

```<code>
public static void setFile(this AxWMPLib.AxWindowsMediaPlayer mp, string filename) {
    mp.URL = filename;
}
</code>```

and

```<code>
public static string file(this AxWMPLib.AxWindowsMediaPlayer mp) {
     return mp.URL;
}
</code>```

Is there any way to not use setFile, but make file act like property?

答: I think what you're after is extension properties, which don't exist. The extension methods require () to follow the method name when called.</p>

OwnerDisplayName: mark

Body:
Some class has ugly field called URL, but Id rather call it file.

public static void setFile(this AxWMPLib.AxWindowsMediaPlayer mp, string filename) {
    mp.URL = filename;
}

and

public static string file(this AxWMPLib.AxWindowsMediaPlayer mp) {
     return mp.URL;
}

Is there any way to not use setFile, but make file act like property?

OwnerDisplayName: John Sheehan


问:
Ng test throws an error Cannot find module 'angular-cli/plugins/karma'
Using angular-cli trying to write a test for a service after executing ng test. I get this error:

```<code>02 03 2017 14:51:09.486:ERROR [config]: Error in config file!
 { Error: Cannot find module 'angular-cli/plugins/karma'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at module.exports (/Desktop/e2-frontend/karma.conf.js:12:7)
    at Object.parseConfig (/Desktop/e2-frontend/node_modules/karma/lib/config.js:342:5)
    at new Server (/Desktop/e2-frontend/node_modules/karma/lib/server.js:56:20)
    at Promise (/Desktop/e2-frontend/node_modules/@angular/cli/tasks/test.js:34:33)
    at Class.run (/Desktop/e2-frontend/node_modules/@angular/cli/tasks/test.js:15:16)
    at Class.run (/Desktop/e2-frontend/node_modules/@angular/cli/commands/test.js:106:25)
    at Class.<anonymous> (/Desktop/e2-frontend/node_modules/@angular/cli/ember-cli/lib/models/command.js:134:17)
    at process._tickCallback (internal/process/next_tick.js:103:7) code: 'MODULE_NOT_FOUND' }
</code>```

karma.config.js

```<code>    // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-remap-istanbul'),
      require('angular-cli/plugins/karma')
    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['angular-cli']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    remapIstanbulReporter: {
      reports: {
        html: 'coverage',
        lcovonly: './coverage/coverage.lcov'
      }
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'karma-remap-istanbul']
              : ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
</code>```

It seems like it cannot find karma for some reason. there has to be a different location for it.
How can I fix this error?

答:
First, make sure you install the latest angular CLI (npm install --save-dev @angular/cli:latest) and remove 'angular-cli' in package.json

Second, go to karma.conf.js edit the following:

from
frameworks: ['jasmine', 'angular-cli']

to
frameworks: ['jasmine', @angular/cli']

from

```<code>require('angular-cli/plugins/karma')
</code>```

to

```<code>require('@angular/cli/plugins/karma')
</code>```

from

```<code>preprocessors: {
      './src/test.ts': ['angular-cli']
    },
</code>```

to

```<code>preprocessors: {
      './src/test.ts': ['@angular/cli']
    },
</code>```

Then, edit your angular-cli.json

from

```<code>"environments": {
        "source": "environments/environment.ts",
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
</code>```

to

```<code>"environmentSource": "environments/environments.ts",
      "environments": {
        "dev": "environments/environments.ts",
        "prod": "environments/environments.prod.ts"
      }
</code>```

Body:
Using angular-cli trying to write a test for a service after executing ng test. I get this error:

02 03 2017 14:51:09.486:ERROR [config]: Error in config file!
 { Error: Cannot find module 'angular-cli/plugins/karma'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at module.exports (/Desktop/e2-frontend/karma.conf.js:12:7)
    at Object.parseConfig (/Desktop/e2-frontend/node_modules/karma/lib/config.js:342:5)
    at new Server (/Desktop/e2-frontend/node_modules/karma/lib/server.js:56:20)
    at Promise (/Desktop/e2-frontend/node_modules/@angular/cli/tasks/test.js:34:33)
    at Class.run (/Desktop/e2-frontend/node_modules/@angular/cli/tasks/test.js:15:16)
    at Class.run (/Desktop/e2-frontend/node_modules/@angular/cli/commands/test.js:106:25)
    at Class.<anonymous> (/Desktop/e2-frontend/node_modules/@angular/cli/ember-cli/lib/models/command.js:134:17)
    at process._tickCallback (internal/process/next_tick.js:103:7) code: 'MODULE_NOT_FOUND' }

karma.config.js

    // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-remap-istanbul'),
      require('angular-cli/plugins/karma')
    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['angular-cli']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    remapIstanbulReporter: {
      reports: {
        html: 'coverage',
        lcovonly: './coverage/coverage.lcov'
      }
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'karma-remap-istanbul']
              : ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

It seems like it cannot find karma for some reason. there has to be a different location for it.
How can I fix this error?

Body:
First, make sure you install the latest angular CLI (npm install --save-dev @angular/cli:latest) and remove 'angular-cli' in package.json

Second, go to karma.conf.js edit the following:

from
frameworks: ['jasmine', 'angular-cli']

to
frameworks: ['jasmine', @angular/cli']

from

require('angular-cli/plugins/karma')

to

require('@angular/cli/plugins/karma')

from

preprocessors: {
      './src/test.ts': ['angular-cli']
    },

to

preprocessors: {
      './src/test.ts': ['@angular/cli']
    },

Then, edit your angular-cli.json

from

"environments": {
        "source": "environments/environment.ts",
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }

to

"environmentSource": "environments/environments.ts",
      "environments": {
        "dev": "environments/environments.ts",
        "prod": "environments/environments.prod.ts"
      }


问:
How to add a phone number to a contact programmatically in Android?
I have an app that can add and delete contacts just fine. And if there is an existing value in an existing contact, it can be modified just fine. But I can't seem to be able to insert new values into existing contacts. For example, if there is an existing value for a home phone number, but not for the work phone number, I tried using the fillowing to add the value (cintact idValue and workNumber are passed in):

```<code>    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValue(ContactsContract.Data.CONTACT_ID, idValue)
            .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, workNumber)
            .build());
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
</code>```

But I get a NullPointerException:

```<code>java.lang.NullPointerException
    at com.android.providers.contacts.ContactsProvider2.insertData(ContactsProvider2.java:2604)
    at com.android.providers.contacts.ContactsProvider2.insertInTransaction(ContactsProvider2.java:2452)
    at com.android.providers.contacts.SQLiteContentProvider.insert(SQLiteContentProvider.java:106)
    at com.android.providers.contacts.ContactsProvider2.insert(ContactsProvider2.java:2256)
    at android.content.ContentProviderOperation.apply(ContentProviderOperation.java:214)
    at com.android.providers.contacts.SQLiteContentProvider.applyBatch(SQLiteContentProvider.java:216)
    at com.android.providers.contacts.ContactsProvider2.applyBatch(ContactsProvider2.java:2290)
    at android.content.ContentProvider$Transport.applyBatch(ContentProvider.java:217)
    at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:194)
    at android.os.Binder.execTransact(Binder.java:336)
    at dalvik.system.NativeStart.run(Native Method)
</code>```

Can someone please tell me what I'm doing wrong?

答: You were getting error because Android doesn't give you access to add a contact directly to you Contact table. Rather you need to modify or add a raw Contact and Android will automatically create a Contact for you.</p>

Body:
I have an app that can add and delete contacts just fine. And if there is an existing value in an existing contact, it can be modified just fine. But I can't seem to be able to insert new values into existing contacts. For example, if there is an existing value for a home phone number, but not for the work phone number, I tried using the fillowing to add the value (cintact idValue and workNumber are passed in):

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValue(ContactsContract.Data.CONTACT_ID, idValue)
            .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, workNumber)
            .build());
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

But I get a NullPointerException:

java.lang.NullPointerException
    at com.android.providers.contacts.ContactsProvider2.insertData(ContactsProvider2.java:2604)
    at com.android.providers.contacts.ContactsProvider2.insertInTransaction(ContactsProvider2.java:2452)
    at com.android.providers.contacts.SQLiteContentProvider.insert(SQLiteContentProvider.java:106)
    at com.android.providers.contacts.ContactsProvider2.insert(ContactsProvider2.java:2256)
    at android.content.ContentProviderOperation.apply(ContentProviderOperation.java:214)
    at com.android.providers.contacts.SQLiteContentProvider.applyBatch(SQLiteContentProvider.java:216)
    at com.android.providers.contacts.ContactsProvider2.applyBatch(ContactsProvider2.java:2290)
    at android.content.ContentProvider$Transport.applyBatch(ContentProvider.java:217)
    at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:194)
    at android.os.Binder.execTransact(Binder.java:336)
    at dalvik.system.NativeStart.run(Native Method)

Can someone please tell me what I'm doing wrong?


问:
javascript programming with jinja values
I have a block of HTML code

```<code><td>{{stock.C4}}</td>
<td>{{stock.C5}}</td>
<td>{{stock.C6}}</td>
<td>{{stock.C7}}</td>
<td>{{stock.C8}}</td>
</code>```

{{stock.C4}} has an output of None in the html cell.
I want (maybe javascript?) code that basically says

```<code> if {{stock.C4}} == 'None'
       element.style.backgroundColor = "red"
</code>```

code that makes the cell a color based on the html/jinja value

答:
If the content of the cell il really empty, you can add the rule

```<code>td:empty {
    background-color: red;
}
</code>```

to your css (adapt the selector and the styles to your needs).

the :empty pseudoclass is supported since ie9 (no need to say that other browser support it from day zero).
Also mobile support seems quite good.

Body:
I have a block of HTML code

{{stock.C4}}
{{stock.C5}}
{{stock.C6}}
{{stock.C7}}
{{stock.C8}}

{{stock.C4}} has an output of None in the html cell.
I want (maybe javascript?) code that basically says

 if {{stock.C4}} == 'None'
       element.style.backgroundColor = "red"

code that makes the cell a color based on the html/jinja value

Body:
If the content of the cell il really empty, you can add the rule

td:empty {
    background-color: red;
}

to your css (adapt the selector and the styles to your needs).

the :empty pseudoclass is supported since ie9 (no need to say that other browser support it from day zero).
Also mobile support seems quite good.


问:
Magento child theme style-m.less, etc not found
I'm learning Magento 2 and creating a child theme based off Blank. In my web/css folder I only have a source/_extend.less and source/lib/variables/_colors.less

It should be pulling everything else from the parent theme from my understanding. But it's saying /MyTheme/en_US/css/styles-m.css and /MyTheme/en_US/css/styles-l.css are not found. How can that be? What am I doing wrong?

I had a _theme.less too in addition to the _extend.less but deleted it after I realized I misunderstood its use.

I've cleared the cache and deleted files out of pub/static/frontend and var/view_preprocessed

答:
Try and do a static deploy to fix the problem. Do this on your shell/terminal on the root of your magento site.

```<code>php ./bin/magento setup:static-content:deploy --theme <Use the theme name you created example myTheme/default>
</code>```

Note this process will possibly take long.

After this process you then reload your site.

Body:
Try and do a static deploy to fix the problem. Do this on your shell/terminal on the root of your magento site.

php ./bin/magento setup:static-content:deploy --theme <Use the theme name you created example myTheme/default>

Note this process will possibly take long.

After this process you then reload your site.


问:
Mechanisms to enumerate resources of Azure
I have a requirement where I need to periodically enumerate the resources of azure namely - VMs, Images, Instance types, Regions, Resource groups, storage, networks and so on.

The current approach I am thinking is to periodically make the Java SDK calls to list these resources and enumerate them into my local store. This can be done on a scheduled basis (say every 10 mins).

However, I was wondering if Azure provides any other mechanism to do this. For example, Is there a way to subscribe changes for say VMs and we get notified whenever there's a change in VM state (power off to power on, etc)?

答: No, there is no such mechanism. There might be some events available in Event Grid, but generally speaking - no.</p>


问:
mysql query for my project (It has only 1 table named judge_review) which needs to sort out top 3 winners

I have tried writing the below query but i just need 3 winners(1st,2nd and 3rd place) and my query has just brought every project in descending order but i need only top 3.

```<code><SELECT judge_review.sub_ID, SUM(judge_review.avgPoints) AS TOTAL FROM judge_review GROUP BY judge_review.sub_ID ORDER BY TOTAL DESC>
</code>```

答:
You need to apply LIMIT 3

```<code>SELECT judge_review.sub_ID,
       SUM(judge_review.avgPoints) AS TOTAL
       FROM judge_review
       GROUP BY judge_review.sub_ID
       ORDER BY TOTAL DESC
       LIMIT 3
</code>```

Reference:- Limit Data Selections From a MySQL Database

Body:
I have tried writing the below query but i just need 3 winners(1st,2nd and 3rd place) and my query has just brought every project in descending order but i need only top 3.

<SELECT judge_review.sub_ID, SUM(judge_review.avgPoints) AS TOTAL FROM judge_review GROUP BY judge_review.sub_ID ORDER BY TOTAL DESC>

Body:
You need to apply LIMIT 3

SELECT judge_review.sub_ID,
       SUM(judge_review.avgPoints) AS TOTAL
       FROM judge_review
       GROUP BY judge_review.sub_ID
       ORDER BY TOTAL DESC
       LIMIT 3

Reference:- Limit Data Selections From a MySQL Database


问:
I have some problems about lists Python 2.7
Could you tell me what's wrong here?

For some reason there's nothing added into the list.

```<code>textarea = raw_input()
n=0
txa = []
string =""

while(n < len(textarea)):
    if(textarea[n] != ' ' or textarea[n] != ','):

        string += textarea[n]
        n=n+1
        print (string)

    else:
        print "For some reason I'm never here."

        if(string == ' ' or string == ','):
            string = ""
        else:
            txa.append(string)
            string = ""
            n=n+1
print(txa)
</code>```

Sorry for my english.

答:
```<code>>>> txt = "Hello, goodbye Fred"
>>> txt.replace(',', ' ').split()
['Hello', 'goodbye', 'Fred']
</code>```

Body:
Could you tell me what's wrong here?

For some reason there's nothing added into the list.

textarea = raw_input()
n=0
txa = []
string =""

while(n < len(textarea)):
    if(textarea[n] != ' ' or textarea[n] != ','):

        string += textarea[n]
        n=n+1
        print (string)

    else:
        print "For some reason I'm never here."

        if(string == ' ' or string == ','):
            string = ""
        else:
            txa.append(string)
            string = ""
            n=n+1
print(txa)

Sorry for my english.


问:
Linux Bash how to grab output and put it back in the script using for loop
Variable's value in bash can be easily called with echo $var command like this

```<code>user@linux:~$ a=1; b=2; c=a+b
user@linux:~$ echo $a $b $c
1 2 a+b
user@linux:~$
</code>```

What I'm trying to accomplish is to replace x with the actual value in a,b,c

```<code>user@linux:~$ a=1; b=2; c=a+b
user@linux:~$ for i in a b c; do echo "$i = x"; done
a = x
b = x
c = x
user@linux:~$
</code>```

By using similar for loop, I hope I can get an output like this

```<code>a = 1
b = 2
c = a+b
</code>```

答:
Use indirection:

```<code>$ for i in a b c; do echo "$i = ${!i}"; done
a = 1
b = 2
c = a+b
</code>```

Documentation

Indirection is explained in man bash:

If the first character of parameter is an exclamation point (!), and
  parameter is not a nameref, it introduces a level of variable
  indirection.  Bash uses the value of the variable formed from the rest
  of parameter as the name of the variable; this variable is then
  expanded and that value   is used in the rest of the substitution,
  rather than the value of parameter itself.  This is known as indirect
  expansion.   If  parameter  is  a   nameref, this expands to the name
  of the variable referenced by parameter instead of performing the
  complete indirect expansion.  The exceptions
   to this are the expansions of ${!prefix*} and ${!name[@]} described
  below.  The exclamation point must immediately  follow  the  left
  brace  in  order to introduce indirection.

Body:
Variable's value in bash can be easily called with echo $var command like this

user@linux:~$ a=1; b=2; c=a+b
user@linux:~$ echo $a $b $c
1 2 a+b
user@linux:~$

What I'm trying to accomplish is to replace x with the actual value in a,b,c

user@linux:~$ a=1; b=2; c=a+b
user@linux:~$ for i in a b c; do echo "$i = x"; done
a = x
b = x
c = x
user@linux:~$

By using similar for loop, I hope I can get an output like this

a = 1
b = 2
c = a+b

Body:
Use indirection:

$ for i in a b c; do echo "$i = ${!i}"; done
a = 1
b = 2
c = a+b

Documentation

Indirection is explained in man bash:

If the first character of parameter is an exclamation point (!), and
  parameter is not a nameref, it introduces a level of variable
  indirection.  Bash uses the value of the variable formed from the rest
  of parameter as the name of the variable; this variable is then
  expanded and that value   is used in the rest of the substitution,
  rather than the value of parameter itself.  This is known as indirect
  expansion.   If  parameter  is  a   nameref, this expands to the name
  of the variable referenced by parameter instead of performing the
  complete indirect expansion.  The exceptions
   to this are the expansions of ${!prefix*} and ${!name[@]} described
  below.  The exclamation point must immediately  follow  the  left
  brace  in  order to introduce indirection.


问:
Spark Structured Streaming - compare two streams
I am using Kafka and Spark 2.1 Structured Streaming. I have two topics with data in json format eg:

```<code>topic 1:

{"id":"1","name":"tom"}
{"id":"2","name":"mark"}

topic 2:

{"name":"tom","age":"25"}
{"name":"mark","age:"35"}
</code>```

I need to compare those two streams in Spark base on tag:name and when value is equal execute some additional definition/function.

How to use Spark Structured Streaming to do this ?

Thanks

答:
I faced a similar requirement some time ago: I had 2 streams which had to be "joined" together based on some criteria. What I used was a function called mapGroupsWithState.

What this functions does (in few words, more details on the reference below) is to take stream in the form of (K,V) and accumulate together its elements on a common state, based on the key of each pair. Then you have ways to tell Spark when the state is complete (according to your application), or even have a timeout for incomplete states.

Example based on your question:

Read Kafka topics into a Spark Stream:

```<code>val rawDataStream: DataFrame = spark.readStream
.format("kafka")
.option("kafka.bootstrap.servers", bootstrapServers)
.option("subscribe", "topic1,topic2") // Both topics on same stream!
.option("startingOffsets", "latest")
.option("failOnDataLoss", "true")
.load()
.selectExpr("CAST(value AS STRING) as jsonData") // Kafka sends bytes
</code>```

Do some operations on your data (I prefer SQL, but you can use the DataFrame API) to transform each element into a key-value pair:

```<code>spark.sqlContext.udf.register("getKey", getKey) // You define this function; I'm assuming you will be using the name as key in your example.

val keyPairsStream = rawDataStream
.sql("getKey(jsonData) as ID, jsonData from rawData")
.groupBy($"ID")
</code>```

Use the mapGroupsWithState function (I will show you the basic idea; you will have to define the myGrpFunct according to your needs):

```<code>keyPairsStream
.mapGroupsWithState(GroupStateTimeout.ProcessingTimeTimeout())(myGrpFunct)
</code>```

Thats it! If you implement myGrpFunct correctly, you will have one stream of merged data, which you can further transform, like the following:

["tom",{"id":"1","name":"tom"},{"name":"tom","age":"25"}]

["mark",{"id":"2","name":"mark"},{"name":"mark","age:"35"}]

Hope this helps!

An excellent explanation with some code snippets: http://asyncified.io/2017/07/30/exploring-stateful-streaming-with-spark-structured-streaming/

Body:
I am using Kafka and Spark 2.1 Structured Streaming. I have two topics with data in json format eg:

topic 1:

{"id":"1","name":"tom"}
{"id":"2","name":"mark"}

topic 2:

{"name":"tom","age":"25"}
{"name":"mark","age:"35"}

I need to compare those two streams in Spark base on tag:name and when value is equal execute some additional definition/function.

How to use Spark Structured Streaming to do this ?

Thanks

Body:
I faced a similar requirement some time ago: I had 2 streams which had to be "joined" together based on some criteria. What I used was a function called mapGroupsWithState.

What this functions does (in few words, more details on the reference below) is to take stream in the form of (K,V) and accumulate together its elements on a common state, based on the key of each pair. Then you have ways to tell Spark when the state is complete (according to your application), or even have a timeout for incomplete states.

Example based on your question:

Read Kafka topics into a Spark Stream:

val rawDataStream: DataFrame = spark.readStream
.format("kafka")
.option("kafka.bootstrap.servers", bootstrapServers)
.option("subscribe", "topic1,topic2") // Both topics on same stream!
.option("startingOffsets", "latest")
.option("failOnDataLoss", "true")
.load()
.selectExpr("CAST(value AS STRING) as jsonData") // Kafka sends bytes

Do some operations on your data (I prefer SQL, but you can use the DataFrame API) to transform each element into a key-value pair:

spark.sqlContext.udf.register("getKey", getKey) // You define this function; I'm assuming you will be using the name as key in your example.

val keyPairsStream = rawDataStream
.sql("getKey(jsonData) as ID, jsonData from rawData")
.groupBy($"ID")

Use the mapGroupsWithState function (I will show you the basic idea; you will have to define the myGrpFunct according to your needs):

keyPairsStream
.mapGroupsWithState(GroupStateTimeout.ProcessingTimeTimeout())(myGrpFunct)

Thats it! If you implement myGrpFunct correctly, you will have one stream of merged data, which you can further transform, like the following:

["tom",{"id":"1","name":"tom"},{"name":"tom","age":"25"}]

["mark",{"id":"2","name":"mark"},{"name":"mark","age:"35"}]

Hope this helps!

An excellent explanation with some code snippets: http://asyncified.io/2017/07/30/exploring-stateful-streaming-with-spark-structured-streaming/


答:
well, if you have a controller home with an action about and want to call about directly, you can do something in your routes like match "/about" => "home#about" :as => :about

if you want to call the route, for example by using a link_to you can say it like this:

```<code><%= link_to "Home", about_url %>
</code>```

you can do rake:routes to see all the generated routes, you'll see one mapped to about with controller => home and action => about

Then, when you call http://localhost/about it will actually call the home controller's about action

you can read more material about routing here

Title: Routes how to hide them on the url bar rails 3

Body:
My route file has the following in it for the root. what i want is when i click on say about it doesn't show me http://127.0.0.1:3000/home/about what i would like is either http://127.0.0.1:3000/about
or just the URL http://127.0.0.1:3000/ like root dose. I'm running rails 3 if you can post a snip it of a route file that will do this or give me a url to see it at that would be great.

# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root :to => "home#index"

# See how all your routes lay out with "rake routes"

Body:
well, if you have a controller home with an action about and want to call about directly, you can do something in your routes like match "/about" => "home#about" :as => :about

if you want to call the route, for example by using a link_to you can say it like this:

<%= link_to "Home", about_url %>

you can do rake:routes to see all the generated routes, you'll see one mapped to about with controller => home and action => about

Then, when you call http://localhost/about it will actually call the home controller's about action

you can read more material about routing here


答: To limit number of returned rows in the result set you have to specify number of that rows by adding to the end of the query LIMIT 3.

Title: mysql query for my project (It has only 1 table named judge_review) which needs to sort out top 3 winners


问:
Automatic Language detection from Images for OCR character Extraction
I am building a software using python in which the image is uploaded.The software will extract the text using tesseract ocr.

But I want my software to detect the languages in the images automatically and extract the detected text.

Please suggest me some ways to do that,I am ready to do Machine Learning also but i can't determine a perfect pipeline for the process.

Thanks In-advance.

答: Tesseract has script detection within "OSD", but not language Detection , you cannot detect language automatically you have to specify language.</p>


问:
How can I make custom SQL with order by in codeigniter
My code is here Sql Query :

```<code>$sql ="select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc";
$product=$this->db->query($sql)->result_array();
</code>```

view all products by using customs SQL but still not showing order by desc.

答:
Try this:</p>

```<code>$sql = "SELECT * FROM `products` WHERE `status`=1 AND `country`=5 AND `product_price` > 50 AND `product_price` <= 100 ORDER BY `product_id` DESC";
        $product = $this->db->query($sql)->result_array();
</code>```

Body:
My code is here Sql Query :

$sql ="select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc";
$product=$this->db->query($sql)->result_array();

view all products by using customs SQL but still not showing order by desc.

Body:
Try this:

$sql = "SELECT * FROM `products` WHERE `status`=1 AND `country`=5 AND `product_price` > 50 AND `product_price` <= 100 ORDER BY `product_id` DESC";
        $product = $this->db->query($sql)->result_array();


问:
UITableView with UILabel SizeToFit get mess when Scrolling
Hi everyone I have problem with my tableview, i make Cell with uilabel with SizeToFit and then calculate the UILabel Height for set the cell Height everything work well except when i scrolling my tableView the text get weird like one char per line:

My TableViewVell Method is:

```<code>-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

UILabel *label = (UILabel *)[cell viewWithTag:1];
label.text = [someArray objectAtIndex:indexPath.row];
// Set the UILabel to fit my text;
messageLabel.lineBreakMode = UILineBreakModeWordWrap;
messageLabel.numberOfLines = 0;
[messageLabel sizeToFit];

return cell;
}
</code>```

The Cell Height stay in the correct Size the problem only with the UILabel ...
this the result when i load the view:

First screenshot

And this is after i start scroll the TableView:

Second screenshot

Any Help???

答:
You can set preferred Width property of label. That worked for me

preferred Width

Body:
Hi everyone I have problem with my tableview, i make Cell with uilabel with SizeToFit and then calculate the UILabel Height for set the cell Height everything work well except when i scrolling my tableView the text get weird like one char per line:

My TableViewVell Method is:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

UILabel *label = (UILabel *)[cell viewWithTag:1];
label.text = [someArray objectAtIndex:indexPath.row];
// Set the UILabel to fit my text;
messageLabel.lineBreakMode = UILineBreakModeWordWrap;
messageLabel.numberOfLines = 0;
[messageLabel sizeToFit];

return cell;
}

The Cell Height stay in the correct Size the problem only with the UILabel ...
this the result when i load the view:

First screenshot

And this is after i start scroll the TableView:

Second screenshot

Any Help???


问:
Capitalize first letter of each word in java
So far after searching the web I can only get the first word to be capitalized.
"Wonder Woman" and "The Avengers" only get the first letter capitalized in the 1st word and not the 2nd.
I'm basically looking for that "java trick" to do the trick and not use a different class like WordUtilize or what ever it is.

Here's my code:

```<code>public class Movie extends Shows{

    private static String title;
    private static HashSet<String> _Movie;
    private static float time;

    public static void main(String[] args) {
        getTitle();
    }

    public static void getTitle() {
        theMovies();
        Scanner _title = new Scanner(System.in);
        System.out.println("Which movie would you like to see?");
        title = _title.nextLine();

        title = title.substring(0,1).toUpperCase() + title.substring(1).toLowerCase();

        _title.close();
        System.out.println("You entered " + title + " movie");

        if(_Movie.contains(title)) {
            System.out.println(title);
        } else {
            System.out.println("Sorry, we only have Batman, Superman, Wonder Woman, and The Avengers");
        }
    }

    public static void theMovies() {
        _Movie = new HashSet<>();
        _Movie.add("Batman");
        _Movie.add("Superman");
        _Movie.add("Wonder Woman");
        _Movie.add("The Avengers");
    }
}
</code>```

Here's the result I get:

Which movie would you like to see?
Wonder Woman
You entered Wonder woman movie
Sorry, we only have Batman, Superman, Wonder Woman, and The Avengers

Thanks for reading!
Edit Sorry for the pictures. Didn't know it was a big deal on here. :/

答:
Assuming the space as delimiter, You can make use of StringBuffer to convert the first letter of the words to uppercase.

```<code>public String toFirstCharUpperAll(String string){
     StringBuffer sb=new StringBuffer(string);
        for(int i=0;i<sb.length();i++)
            if(i==0 || sb.charAt(i-1)==' ')//first letter to uppercase by default
                sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
     return sb.toString();
}
</code>```

Body:
So far after searching the web I can only get the first word to be capitalized.
"Wonder Woman" and "The Avengers" only get the first letter capitalized in the 1st word and not the 2nd.
I'm basically looking for that "java trick" to do the trick and not use a different class like WordUtilize or what ever it is.

Here's my code:

public class Movie extends Shows{

    private static String title;
    private static HashSet<String> _Movie;
    private static float time;

    public static void main(String[] args) {
        getTitle();
    }

    public static void getTitle() {
        theMovies();
        Scanner _title = new Scanner(System.in);
        System.out.println("Which movie would you like to see?");
        title = _title.nextLine();

        title = title.substring(0,1).toUpperCase() + title.substring(1).toLowerCase();

        _title.close();
        System.out.println("You entered " + title + " movie");

        if(_Movie.contains(title)) {
            System.out.println(title);
        } else {
            System.out.println("Sorry, we only have Batman, Superman, Wonder Woman, and The Avengers");
        }
    }

    public static void theMovies() {
        _Movie = new HashSet<>();
        _Movie.add("Batman");
        _Movie.add("Superman");
        _Movie.add("Wonder Woman");
        _Movie.add("The Avengers");
    }
}

Here's the result I get:

Which movie would you like to see?
Wonder Woman
You entered Wonder woman movie
Sorry, we only have Batman, Superman, Wonder Woman, and The Avengers

Thanks for reading!
Edit Sorry for the pictures. Didn't know it was a big deal on here. :/

Body:
Assuming the space as delimiter, You can make use of StringBuffer to convert the first letter of the words to uppercase.

public String toFirstCharUpperAll(String string){
     StringBuffer sb=new StringBuffer(string);
        for(int i=0;i<sb.length();i++)
            if(i==0 || sb.charAt(i-1)==' ')//first letter to uppercase by default
                sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
     return sb.toString();
}


问:
DwmExtendFrameIntoClientArea without TransparencyKey?
When using DwmExtendFrameIntoClientArea function I need to choose Form.TransparencyKey, a color that a glass will be drawn on instead.

The problem is that i writing image-edit tool, and when TransparencyKey color appear inside the edited image, the user see glass instead.

How do i extend the glass into client area without losing some color?

答:
There's no reason you should be using the Form.TransparencyKey property with DWM functions. That property relates to layered windows, which has nothing to do with the Aero glass effect. I assume the fact that it might work is more a consequence of implementation detail (like all 3 RGB values of the color you've set as the TransparencyKey are the same), rather than by design.

GDI treats black as the transparency color, so you should just paint the particular regions of your form that you want to appear as glass with a black brush. Because you're limiting the black fill to only those areas, there's no reason this should interfere with the rest of your UI.

Of course, any black text (such as that drawn on controls) that appears in the area you're rendering as glass is going to look ugly. The solution is either to switch to GDI+-based rendering or to move your controls outside of the area to be rendered as glass. If you need finer control over the area of your form that should appear glassy than provided by DwmExtendFrameIntoClientArea (which literally just extends the frame by a set amount), look into using DwmEnableBlurBehindWindow instead. See my more complete answer here on how to use that function.