问:
Adding a range value and putting the sum to a different sheet
I have a table (Sheet1) with scores in Column C.  When I click the button, I want a sum to display in another sheet (Summary) in cell B2.  After clicking the button, I want the table to be deleted but the sum will stay in Cell B2. Then, I will continue my entry for another month and do the cycle.

Screenshot:

My code so far:

```<code>Private Sub CommandButton1_Click()

Set myRange = Range(ActiveCell, ActiveCell.End(xlUp))

Dim myCount As Integer

myCount = Application.Count(myRange)

Sheets("Summary").Range("B2").Value = "=SUM(C2:C6" & myCount & ")"  '

End Sub
</code>```

答:
This code will do a sum on the summary sheet of column c in Sheet1. Make sure there is a header on the Summary sheet for column B.  </p>

```<code>Private Sub CommandButton1_Click()

Dim sum As Worksheet, ws As Worksheet
Set sum = Sheets("Summary"): Set ws = Sheets("Sheet1")

sum.Range("B" & sum.Range("B1000000").End(xlUp).Offset(1, 0).Row) = WorksheetFunction.sum(ws.Range("C2:C" & ws.Range("C100000").End(xlUp).Row))
ws.Range("A2:C" & ws.Range("A1").SpecialCells(xlCellTypeLastCell).row).ClearContents

End Sub
</code>```

Body:
I have a table (Sheet1) with scores in Column C.  When I click the button, I want a sum to display in another sheet (Summary) in cell B2.  After clicking the button, I want the table to be deleted but the sum will stay in Cell B2. Then, I will continue my entry for another month and do the cycle.

Screenshot:

My code so far:

Private Sub CommandButton1_Click()

Set myRange = Range(ActiveCell, ActiveCell.End(xlUp))

Dim myCount As Integer

myCount = Application.Count(myRange)

Sheets("Summary").Range("B2").Value = "=SUM(C2:C6" & myCount & ")"  '

End Sub

Body:
This code will do a sum on the summary sheet of column c in Sheet1. Make sure there is a header on the Summary sheet for column B.

Private Sub CommandButton1_Click()

Dim sum As Worksheet, ws As Worksheet
Set sum = Sheets("Summary"): Set ws = Sheets("Sheet1")

sum.Range("B" & sum.Range("B1000000").End(xlUp).Offset(1, 0).Row) = WorksheetFunction.sum(ws.Range("C2:C" & ws.Range("C100000").End(xlUp).Row))
ws.Range("A2:C" & ws.Range("A1").SpecialCells(xlCellTypeLastCell).row).ClearContents

End Sub


来源: stackexchange

问:
How to assign a string variable value to a 2d array
I am trying to populate a 2d array with String values.

int m; n; are used in my loops to assign to rows and columns.

In an inner loop I am pulling out strings from a separate string array and assigning each value to a string variable. Then I am trying to assign that string variable to the 2d array of strings.

String variable = value of string in string array at a specific index;

```<code>String[m][n] example =  variable;
</code>```

It seems to working fine except it doesn't seem to be loading the string in the string variable into the 2d array.

Can anyone help me to understand why this is happening and how I might successfully assign the data to the 2d array?

```<code>for(m = 0; m < people.size(); m++){
        for(n = 0; n < people.get(m).getNames().length; n++){

            for(int i = 0; i < people.size(); i ++){
                for(j = 0; j < people.get(i).getNames().length; j++){
                    String name = people.get(i).getNames()[j];

                }
        NamesGrid [m][n] =  name;

        }
</code>```

答:
It's hard to tell just what you want to accomplish.  The fact that you've posted non-matching curly braces doesn't help.

But basically, a double to populate all the array elements would look like:

```<code>for(m = 0; m < people.size(); m++){
    for(n = 0; n < people.get(m).getNames().length; n++){
        namesGrid[m][n] = ?????????;
    }
}
</code>```

where you have to fill in the expression.  (And maybe add some code above the assignment to help with the computation.)

So what info do we have at the point where the array element is being assigned?  We know what m and n are--the row and column of the namesGrid array.  It also looks like they are also the "row" and "column" of objects in some people object.  (It looks like people has several lists of names, and people.get(i) gives you one list of names?  I'm not sure.)

But since we already know the row and column numbers for people, i.e. m and n, we can use those to access the data in people.  We don't need extra for loops to do that.  Or, to look at it another way: you need to iterate through all the elements of namesGrid, and you need to iterate through all the people, but you are iterating over them at the same time since the two structures are roughly the same shape, so to speak.  When you use m and n to iterate through namesGrid, they are also iterating through people.  So you don't need extra loops to iterate through people.

So get rid of those two extra i and j loops, and just use m and n to get the name:

```<code>String name = people.get(m).getNames()[n];
</code>```

If this isn't what you really wanted, please edit your question and provide more details.  Also, variable names by convention begin with a lower-case letter in Java, so I've changed namesGrid in my answer.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to populate a 2d array with String values.

int m; n; are used in my loops to assign to rows and columns.

In an inner loop I am pulling out strings from a separate string array and assigning each value to a string variable. Then I am trying to assign that string variable to the 2d array of strings.

String variable = value of string in string array at a specific index;

String[m][n] example =  variable;

It seems to working fine except it doesn't seem to be loading the string in the string variable into the 2d array.

Can anyone help me to understand why this is happening and how I might successfully assign the data to the 2d array?

for(m = 0; m < people.size(); m++){
        for(n = 0; n < people.get(m).getNames().length; n++){

            for(int i = 0; i < people.size(); i ++){
                for(j = 0; j < people.get(i).getNames().length; j++){
                    String name = people.get(i).getNames()[j];

                }
        NamesGrid [m][n] =  name;

        }

Body:
It's hard to tell just what you want to accomplish.  The fact that you've posted non-matching curly braces doesn't help.

But basically, a double to populate all the array elements would look like:

for(m = 0; m < people.size(); m++){
    for(n = 0; n < people.get(m).getNames().length; n++){
        namesGrid[m][n] = ?????????;
    }
}

where you have to fill in the expression.  (And maybe add some code above the assignment to help with the computation.)

So what info do we have at the point where the array element is being assigned?  We know what m and n are--the row and column of the namesGrid array.  It also looks like they are also the "row" and "column" of objects in some people object.  (It looks like people has several lists of names, and people.get(i) gives you one list of names?  I'm not sure.)

But since we already know the row and column numbers for people, i.e. m and n, we can use those to access the data in people.  We don't need extra for loops to do that.  Or, to look at it another way: you need to iterate through all the elements of namesGrid, and you need to iterate through all the people, but you are iterating over them at the same time since the two structures are roughly the same shape, so to speak.  When you use m and n to iterate through namesGrid, they are also iterating through people.  So you don't need extra loops to iterate through people.

So get rid of those two extra i and j loops, and just use m and n to get the name:

String name = people.get(m).getNames()[n];

If this isn't what you really wanted, please edit your question and provide more details.  Also, variable names by convention begin with a lower-case letter in Java, so I've changed namesGrid in my answer.


问:
What is the type of the super object returned by super()?
From here:

```<code>super( [ type [ , object-or-type ]] )
</code>```

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

If the second argument is omitted, the super object returned is
  unbound.

If the second argument is an object, isinstance(obj, type) must be
  true.

If the second argument is a type, issubclass(type2, type) must be
  true (this is useful for classmethods).

If I am correct, a type is a class, and a class is a type. A class
is an object, so a type is also an object.  Why does the quote
distinguish the two cases when the second argument being an object
when it is a type?

When the second argument is a type, why is issubclass(type2, type)
required to be true?

What is the type of the super object    returned by super in each of the three cases respectively? Or how do you determine the type of the super object returned by super?

When the second argument is an object, because "The search order is same as that used by getattr() except that the type itself is skipped", I guessed that the type of the superobject returned by super function should be a subclass of any ancestry class of the first argument type, but I found that it is actually not by testing with issubclass. So did I misunderstand something?

答:
just for the point 3 about the type super in the 3 cases (2 first are similar):</p>

```<code>class A(object):
    def sup(self):
        return (super(A, self))

class A1(object):
    def sup(self):
        return (super())

class B(object):
    def sup(self):
        return (super(B))

class C(A):
    def sup(self):
        return (super(A,C))

a = A()
a_sup = a.sup()
print(type(a_sup))  #<class 'super'>
print(a_sup.__doc__)  #The most base type
print(a_sup.__self__)  #<__main__.A object at 0x7f9d0d2d8668>
print(a_sup.__self_class__) #<class '__main__.A'>
print(a_sup.__thisclass__)  #<class '__main__.A'>

print()
a1 = A1()
a_sup = a1.sup()
print(type(a_sup))  #<class 'super'>
print(a_sup.__doc__)  #The most base type
print(a_sup.__self__)  #<__main__.A1 object at 0x7f9d0d2d86d8>
print(a_sup.__self_class__) #<class '__main__.A1'>
print(a_sup.__thisclass__) #<class '__main__.A1'>

print()
b = B()
b_sup = b.sup()
print(type(b_sup))  #<class 'super'>
print(b_sup.__doc__)
'''
super() -> same as super(__class__, <first argument>)
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:
class C(B):
    def meth(self, arg):
        super().meth(arg)
This works for class methods too:
class C(B):
    @classmethod
    def cmeth(cls, arg):
        super().cmeth(arg)
'''

print(b_sup.__self__)  #None
print(b_sup.__self_class__)  #None
print(b_sup.__thisclass__)  #<class '__main__.B'>

print()
c=C()
c_sup = c.sup()
print(type(c_sup))  #<class 'super'>
print(c_sup.__doc__) #The most base type
print(c_sup.__self__) #<class '__main__.C'>
print(c_sup.__self_class__) #<class '__main__.C'>
print(c_sup.__thisclass__) #<class '__main__.A'>
</code>```

Body:
From here:

super( [ type [ , object-or-type ]] )

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

If the second argument is omitted, the super object returned is
  unbound.

If the second argument is an object, isinstance(obj, type) must be
  true.

If the second argument is a type, issubclass(type2, type) must be
  true (this is useful for classmethods).

If I am correct, a type is a class, and a class is a type. A class
is an object, so a type is also an object.  Why does the quote
distinguish the two cases when the second argument being an object
when it is a type?

When the second argument is a type, why is issubclass(type2, type)
required to be true?

What is the type of the super object    returned by super in each of the three cases respectively? Or how do you determine the type of the super object returned by super?

When the second argument is an object, because "The search order is same as that used by getattr() except that the type itself is skipped", I guessed that the type of the superobject returned by super function should be a subclass of any ancestry class of the first argument type, but I found that it is actually not by testing with issubclass. So did I misunderstand something?

Body:
just for the point 3 about the type super in the 3 cases (2 first are similar):

class A(object):
    def sup(self):
        return (super(A, self))

class A1(object):
    def sup(self):
        return (super())

class B(object):
    def sup(self):
        return (super(B))

class C(A):
    def sup(self):
        return (super(A,C))

a = A()
a_sup = a.sup()
print(type(a_sup))  #<class 'super'>
print(a_sup.__doc__)  #The most base type
print(a_sup.__self__)  #<__main__.A object at 0x7f9d0d2d8668>
print(a_sup.__self_class__) #<class '__main__.A'>
print(a_sup.__thisclass__)  #<class '__main__.A'>

print()
a1 = A1()
a_sup = a1.sup()
print(type(a_sup))  #<class 'super'>
print(a_sup.__doc__)  #The most base type
print(a_sup.__self__)  #<__main__.A1 object at 0x7f9d0d2d86d8>
print(a_sup.__self_class__) #<class '__main__.A1'>
print(a_sup.__thisclass__) #<class '__main__.A1'>

print()
b = B()
b_sup = b.sup()
print(type(b_sup))  #<class 'super'>
print(b_sup.__doc__)
'''
super() -> same as super(__class__, <first argument>)
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:
class C(B):
    def meth(self, arg):
        super().meth(arg)
This works for class methods too:
class C(B):
    @classmethod
    def cmeth(cls, arg):
        super().cmeth(arg)
'''

print(b_sup.__self__)  #None
print(b_sup.__self_class__)  #None
print(b_sup.__thisclass__)  #<class '__main__.B'>

print()
c=C()
c_sup = c.sup()
print(type(c_sup))  #<class 'super'>
print(c_sup.__doc__) #The most base type
print(c_sup.__self__) #<class '__main__.C'>
print(c_sup.__self_class__) #<class '__main__.C'>
print(c_sup.__thisclass__) #<class '__main__.A'>


问:
setting breakpoint angular cli .spec.ts code for debugging
I'm using angular2 cli and am following the test debugging instructions here official documentation. I'm able to search for the spec.ts source files which are in the app folder and set break points. However, I'm not able to do the same for the test files for components in other folder. The tests do run but I'm not able to find the source file in the chrome browser. Shall I edit some config file? I've tried to add the source files manually to the source in chrome but that doesn't help in setting the breakpoint. Any help is very much appreciated. </p>

答:
Do this and see what happens:

In a test that you cannot find, add a debugger; statement

Run ng test

When Karma is loaded in a new browser window, click the "Debug" button

Open the developer tools as soon as a new tab is opened in Chrome (reload the tab if you do this late)

See the "Source" devtools tab open to the file and break on the debugger statement. This should be the answer to your question.


问:
Adding comma separated items on separate lines to a dict in Python
I am using python 2.7, and using python dicts.

I have my output like this:

```<code>goods: apples, oranges
trunk_names: trunk01, trunk02, trunk03,trunk04,
             trunk05,trunk06, trunk07,trunk08,
             trunk09,trunk10, trunk11,trunk12
</code>```

My code:

```<code>    d = {}
    for line in output.split("\n"):
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value
</code>```

Expected key and its value:

```<code> trunk_names: trunk01, trunk02, trunk03,trunk04,trunk05,trunk06, trunk07,trunk08,trunk09,trunk10, trunk11,trunk12
</code>```

Actual key and values being output:

```<code> trunk_names: trunk01, trunk02, trunk03,trunk04,
</code>```

答:
How stable is your structure, if it is very stable and the data quality is high then your can simplify by testing if the line.endswith(','):

```<code>In []:
d = {}
f = iter(output.split('\n'))
for line in f:
    key, line = map(str.strip, line.split(':', 1))
    while line.endswith(','):
        line += next(f)
    d[key] = [i.strip() for i in line.split(',')]

pprint.pprint(d)

Out[]:
{'goods': ['apples', 'oranges'],
 'trunk_names': ['trunk01',
                 'trunk02',
                 'trunk03',
                 'trunk04',
                 'trunk05',
                 'trunk06',
                 'trunk07',
                 'trunk08',
                 'trunk09',
                 'trunk10',
                 'trunk11',
                 'trunk12']}
</code>```

Body:
I am using python 2.7, and using python dicts.

I have my output like this:

goods: apples, oranges
trunk_names: trunk01, trunk02, trunk03,trunk04,
             trunk05,trunk06, trunk07,trunk08,
             trunk09,trunk10, trunk11,trunk12

My code:

    d = {}
    for line in output.split("\n"):
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value

Expected key and its value:

 trunk_names: trunk01, trunk02, trunk03,trunk04,trunk05,trunk06, trunk07,trunk08,trunk09,trunk10, trunk11,trunk12

Actual key and values being output:

 trunk_names: trunk01, trunk02, trunk03,trunk04,

Body:
How stable is your structure, if it is very stable and the data quality is high then your can simplify by testing if the line.endswith(','):

In []:
d = {}
f = iter(output.split('\n'))
for line in f:
    key, line = map(str.strip, line.split(':', 1))
    while line.endswith(','):
        line += next(f)
    d[key] = [i.strip() for i in line.split(',')]

pprint.pprint(d)

Out[]:
{'goods': ['apples', 'oranges'],
 'trunk_names': ['trunk01',
                 'trunk02',
                 'trunk03',
                 'trunk04',
                 'trunk05',
                 'trunk06',
                 'trunk07',
                 'trunk08',
                 'trunk09',
                 'trunk10',
                 'trunk11',
                 'trunk12']}


问:
How to use belongsToMany in Sequelize?
I'm creating a web app using sequelize to connect to a postgres database. I've managed to teach myself how to use hasMany and belongsTo in order to call, create and destroy data. I'm having trouble with belongsToMany.

In my server I'm trying to create a Trip that belongsToMany Users as riders and added an association for User belongToMany Trip as riders as well. I want to be able to create a trip on a POST request but can't figure out how to call the Ids.

///// MODELS
trip.js

```<code>module.exports = function(sequelize, DataTypes) {
  var Trip = sequelize.define("Trip", {
    driverStart: DataTypes.STRING,
    driverEnd: DataTypes.STRING,
    riderStarts: DataTypes.ARRAY(DataTypes.STRING),
    riderEnds: DataTypes.ARRAY(DataTypes.STRING),
    tripDate: DataTypes.DATE,
    tripHour: DataTypes.INTEGER,
    availableSeats: DataTypes.INTEGER,
    price: DataTypes.INTEGER,
    tripIsActive: DataTypes.BOOLEAN
  });
  Trip.associate = function(models) {
    Trip.hasMany(models.User, {
      through: "riders_on_trip",
      as: "riders",
      onDelete: "CASCADE",
      foreignKey: "riderIds"
    });
    Trip.belongsTo(models.User, {
      as: "driver",
      onDelete: "CASCADE",
      foreignKey: "driverId"
    });
  };
  return Trip;
};
</code>```

user.js

```<code>module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    email: DataTypes.STRING,
    password: DataTypes.STRING,
    profileImgUrl: DataTypes.STRING,
    fName: DataTypes.STRING,
    lName: DataTypes.STRING,
    yearOfBirth: DataTypes.INTEGER,
    gender: DataTypes.STRING,
    ratings: {
      type: DataTypes.ARRAY(DataTypes.INTEGER),
      defaultValue: [5]
    },
    onTrip: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },
    createdAt: {
      type: DataTypes.DATE,
      defaultValue: sequelize.literal('NOW()')
    },
    updatedAt: {
      type: DataTypes.DATE,
      defaultValue: sequelize.literal('NOW()')
    }
  });
  User.associate = function(models) {
    User.hasMany(models.RideRequest, {
      onDelete: "CASCADE",
      foreignKey: "riderId"
    });
    User.hasMany(models.DriveRequest, {
      onDelete: "CASCADE",
      foreignKey: "driverId"
    });
    User.hasMany(models.Notification, {
      as: 'sender',
      onDelete: "CASCADE",
      foreignKey: "senderId"
    });
    User.hasMany(models.Notification, {
      as: 'receiver',
      onDelete: "CASCADE",
      foreignKey: "receiverId"
    });
    User.belongsToMany(models.Trip, {
      as: "riders",
      through: "riders_on_trip",
      onDelete: "CASCADE",
      foreignKey: "riderIds"
    });
    User.hasMany(models.Trip, {
      as: "driver",
      onDelete: "CASCADE",
      foreignKey: "driverId"
    });
  };
  return User;
};
</code>```

///// Controllers

trip.js

```<code>  create: function create(req,res) {
    // var decodedIds = req.params.riderIds.split("-");
    var decoded = jwt.decode(req.query.token);
    // console.log(decodedIds + '------------------ DECODED IDS ----------------');
    model.User.set
    return model.Trip.create({
      driverStart: req.body.driverStart,
      driverEnd: req.body.driverEnd,
      riderStarts: req.body.riderStarts,
      riderEnds: req.body.riderEnds,
      tripDate: req.body.tripDate,
      tripHour: req.body.tripHour,
      availableSeats: req.body.availableSeats,
      price: req.body.price,
      tripIsActive: req.body.tripIsActive,
      driverId: req.params.driverId,
      riders: [{riderIds: 2}, {riderIds: 2}, {riderIds: 3}]
    }).then(function (trip) {
      console.log(trip.riderIds + '------------ RIDER IDS ---------------');
      return res.status(201).json({
        message: 'Trip created successfully',
        obj: trip
      });
    }).catch(function (err) {
      return res.status(400).json({
        title: 'Error occured while creating trip',
        error: err
      });
    });
  },
</code>```

Is there any master of programming who could give me a brief explanation on how I could create a trip with this kind of association in sequelize?

答:
You dont need the hasMany, belongsTo stuff on Trip and User if you are setting up a many to many table. it looks like you set up the many to many table correctly, but if you need to query the trips that belong to a specific user you will need to add another association

```<code>Trip.belongsToMany(models.User, {
  as: "driver",
  through: "riders_on_trip",
});
</code>```

you get the gist.

you can get the rider ids like this:

```<code>trip.getRiders().then(function (rider){
    return riders.map((rider) => {
        return rider.id;
    });
)};
</code>```

Title: How to use belongsToMany in Sequelize?

Body:
I'm creating a web app using sequelize to connect to a postgres database. I've managed to teach myself how to use hasMany and belongsTo in order to call, create and destroy data. I'm having trouble with belongsToMany.

In my server I'm trying to create a Trip that belongsToMany Users as riders and added an association for User belongToMany Trip as riders as well. I want to be able to create a trip on a POST request but can't figure out how to call the Ids.

///// MODELS
trip.js

module.exports = function(sequelize, DataTypes) {
  var Trip = sequelize.define("Trip", {
    driverStart: DataTypes.STRING,
    driverEnd: DataTypes.STRING,
    riderStarts: DataTypes.ARRAY(DataTypes.STRING),
    riderEnds: DataTypes.ARRAY(DataTypes.STRING),
    tripDate: DataTypes.DATE,
    tripHour: DataTypes.INTEGER,
    availableSeats: DataTypes.INTEGER,
    price: DataTypes.INTEGER,
    tripIsActive: DataTypes.BOOLEAN
  });
  Trip.associate = function(models) {
    Trip.hasMany(models.User, {
      through: "riders_on_trip",
      as: "riders",
      onDelete: "CASCADE",
      foreignKey: "riderIds"
    });
    Trip.belongsTo(models.User, {
      as: "driver",
      onDelete: "CASCADE",
      foreignKey: "driverId"
    });
  };
  return Trip;
};

user.js

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    email: DataTypes.STRING,
    password: DataTypes.STRING,
    profileImgUrl: DataTypes.STRING,
    fName: DataTypes.STRING,
    lName: DataTypes.STRING,
    yearOfBirth: DataTypes.INTEGER,
    gender: DataTypes.STRING,
    ratings: {
      type: DataTypes.ARRAY(DataTypes.INTEGER),
      defaultValue: [5]
    },
    onTrip: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },
    createdAt: {
      type: DataTypes.DATE,
      defaultValue: sequelize.literal('NOW()')
    },
    updatedAt: {
      type: DataTypes.DATE,
      defaultValue: sequelize.literal('NOW()')
    }
  });
  User.associate = function(models) {
    User.hasMany(models.RideRequest, {
      onDelete: "CASCADE",
      foreignKey: "riderId"
    });
    User.hasMany(models.DriveRequest, {
      onDelete: "CASCADE",
      foreignKey: "driverId"
    });
    User.hasMany(models.Notification, {
      as: 'sender',
      onDelete: "CASCADE",
      foreignKey: "senderId"
    });
    User.hasMany(models.Notification, {
      as: 'receiver',
      onDelete: "CASCADE",
      foreignKey: "receiverId"
    });
    User.belongsToMany(models.Trip, {
      as: "riders",
      through: "riders_on_trip",
      onDelete: "CASCADE",
      foreignKey: "riderIds"
    });
    User.hasMany(models.Trip, {
      as: "driver",
      onDelete: "CASCADE",
      foreignKey: "driverId"
    });
  };
  return User;
};

///// Controllers

trip.js

  create: function create(req,res) {
    // var decodedIds = req.params.riderIds.split("-");
    var decoded = jwt.decode(req.query.token);
    // console.log(decodedIds + '------------------ DECODED IDS ----------------');
    model.User.set
    return model.Trip.create({
      driverStart: req.body.driverStart,
      driverEnd: req.body.driverEnd,
      riderStarts: req.body.riderStarts,
      riderEnds: req.body.riderEnds,
      tripDate: req.body.tripDate,
      tripHour: req.body.tripHour,
      availableSeats: req.body.availableSeats,
      price: req.body.price,
      tripIsActive: req.body.tripIsActive,
      driverId: req.params.driverId,
      riders: [{riderIds: 2}, {riderIds: 2}, {riderIds: 3}]
    }).then(function (trip) {
      console.log(trip.riderIds + '------------ RIDER IDS ---------------');
      return res.status(201).json({
        message: 'Trip created successfully',
        obj: trip
      });
    }).catch(function (err) {
      return res.status(400).json({
        title: 'Error occured while creating trip',
        error: err
      });
    });
  },

Is there any master of programming who could give me a brief explanation on how I could create a trip with this kind of association in sequelize?

Body:
You dont need the hasMany, belongsTo stuff on Trip and User if you are setting up a many to many table. it looks like you set up the many to many table correctly, but if you need to query the trips that belong to a specific user you will need to add another association

Trip.belongsToMany(models.User, {
  as: "driver",
  through: "riders_on_trip",
});

you get the gist.

you can get the rider ids like this:

trip.getRiders().then(function (rider){
    return riders.map((rider) => {
        return rider.id;
    });
)};


问:
How Linux system calls interact with filesystem
Lately I faced this excercise:

Given this sequence of system calls in a Linux C language program:

```<code>fd = open("f123", O_RDWRT | O_CREAT, 0777);
lseek(fd, 0x1000000L, 0);
write(fd, &fd, sizeof(int));
</code>```

draw the file system data structures and disk blocks that are modified by these operations, considering a 4 KByte block size, and index block pointers of 4 bytes.

For the first system call (open) I realized how it works and schematized it in this way:

Now, skipping the draw part (I realize it would make difficult to answer), I'd like to understand how lseek and write works in term of inodes and index blocks (whatever they are).

I tried figuring that lseek computes the correct inode (as block size is known), but still no clue on how it actually works.

答:
In Linux, these system calls interact with Virtual File System(VFS). VFS builds an abstraction over real filesystems, it defines some useful data structures to organize filesystem.

inodes represents real file on the disk. Through inodes structure can access not only the inode block, but also data blocks on disk.

directory entry represents part of a path. A d_entry doesn't always refer to a real file on the disk. If it refers to a directory on disk, there will be a pointer to the inode struct of the directory file.

file represents files open by processes. There's also a pointer to its d_entry in the struct.

Here are snippets from file struct:

```<code>struct file {
    // ... other attributes
    struct path     f_path;
    #define f_dentry    f_path.dentry
    #define f_vfsmnt    f_path.mnt
    const struct file_operations    *f_op;
};
struct file_operations {
    // ... other operations
    struct module *owner;
    loff_t (*llseek) (struct file *, loff_t, int);
    ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
    ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
}
</code>```

These objects all has an operation list field. VFS defines these operations and underlaying filesystems implement these operations or use general implementations provided by VFS.

Syscall open() creates the file object, other syscalls like lseek() simply get file object (through Fd) and call the corresponding function in the operation list, like write() will call f->f_op->write(f, ...), then filesystem may follow the file -> d_entry -> inode path to access file on disk.

Body:
Lately I faced this excercise:

Given this sequence of system calls in a Linux C language program:

fd = open("f123", O_RDWRT | O_CREAT, 0777);
lseek(fd, 0x1000000L, 0);
write(fd, &fd, sizeof(int));

draw the file system data structures and disk blocks that are modified by these operations, considering a 4 KByte block size, and index block pointers of 4 bytes.

For the first system call (open) I realized how it works and schematized it in this way:

Now, skipping the draw part (I realize it would make difficult to answer), I'd like to understand how lseek and write works in term of inodes and index blocks (whatever they are).

I tried figuring that lseek computes the correct inode (as block size is known), but still no clue on how it actually works.

Body:
In Linux, these system calls interact with Virtual File System(VFS). VFS builds an abstraction over real filesystems, it defines some useful data structures to organize filesystem.

inodes represents real file on the disk. Through inodes structure can access not only the inode block, but also data blocks on disk.

directory entry represents part of a path. A d_entry doesn't always refer to a real file on the disk. If it refers to a directory on disk, there will be a pointer to the inode struct of the directory file.

file represents files open by processes. There's also a pointer to its d_entry in the struct.

Here are snippets from file struct:

struct file {
    // ... other attributes
    struct path     f_path;
    #define f_dentry    f_path.dentry
    #define f_vfsmnt    f_path.mnt
    const struct file_operations    *f_op;
};
struct file_operations {
    // ... other operations
    struct module *owner;
    loff_t (*llseek) (struct file *, loff_t, int);
    ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
    ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
}

These objects all has an operation list field. VFS defines these operations and underlaying filesystems implement these operations or use general implementations provided by VFS.

Syscall open() creates the file object, other syscalls like lseek() simply get file object (through Fd) and call the corresponding function in the operation list, like write() will call f->f_op->write(f, ...), then filesystem may follow the file -> d_entry -> inode path to access file on disk.


问:
Acessing Controller and Action name at _initVars() Zend Framework
I hope I had made me clear in my question!

I would like to access the getControllerName() and getActionName() inside _initVars(). This is what I'm trying to do:

```<code>    protected function _initVars()
    {

        $this->bootstrap('layout');
        $layout = $this->getResource('layout');
        $view = $layout->getView();
        $view->theme = 'MY_THEME';

        $this->bootstrap('frontController');
        $front = $this->getResource('frontController');

        echo '```';
        print_r($front->getRequest());
        echo '```';
        exit;

        return $view;

    }
</code>```

I'm getting no response, the fields controllername and actionname are returning empty, this is what I get in the return:

```<code>Zend_Controller_Front Object
(
    [_baseUrl:protected] =>
    [_controllerDir:protected] =>
    [_dispatcher:protected] => Zend_Controller_Dispatcher_Standard Object
        (
            [_curDirectory:protected] =>
            [_curModule:protected] => default
            [_controllerDirectory:protected] => Array
                (
                    [default] => /var/www/proj_rodrigo/application/controllers
                )

            [_defaultAction:protected] => index
            [_defaultController:protected] => index
            [_defaultModule:protected] => default
            [_frontController:protected] =>
            [_invokeParams:protected] => Array
                (
                )
</code>```

It's just a part of the code, the necessary things are there, in the old schema of Zend I could be capable to do it calling Zend_Front_Controller, but now I don't know more how to use it.

Appreciate any help!
Best regards and sorry for my BAD English.

To fix this issue, I add the postDispatche at my plugin:

public function postDispatch(Zend_Controller_Request_Abstract $request)
{

```<code>$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
$layout = $bootstrap->getResource('layout');
$view = $layout->getView();

$view->controller = $this->getRequest()->getControllerName();
$view->action = $this->getRequest()->getActionName();
</code>```

}

Thanks again!

答:
It looks like this code is in the Bootstrap class. Since Bootstrap code runs before the routing - in, fact this stage is where routing is often defined - the controller and action are not yet determined.

If you want to get that info, you need to create a front-controller plugin implementing an early-running method - that runs after routing has set the controller and action - like routeShutdown() or dispatchLoopStartup()or preDispatch().

Check out: ZF Dispatch Overview (PDF)

ContentLicense: CC BY-SA 2.5

Body:
I hope I had made me clear in my question!

I would like to access the getControllerName() and getActionName() inside _initVars(). This is what I'm trying to do:

    protected function _initVars()
    {

        $this->bootstrap('layout');
        $layout = $this->getResource('layout');
        $view = $layout->getView();
        $view->theme = 'MY_THEME';

        $this->bootstrap('frontController');
        $front = $this->getResource('frontController');

        echo '
';
        print_r($front->getRequest());
        echo '
';
        exit;

        return $view;

    }

I'm getting no response, the fields controllername and actionname are returning empty, this is what I get in the return:

Zend_Controller_Front Object
(
    [_baseUrl:protected] =>
    [_controllerDir:protected] =>
    [_dispatcher:protected] => Zend_Controller_Dispatcher_Standard Object
        (
            [_curDirectory:protected] =>
            [_curModule:protected] => default
            [_controllerDirectory:protected] => Array
                (
                    [default] => /var/www/proj_rodrigo/application/controllers
                )

            [_defaultAction:protected] => index
            [_defaultController:protected] => index
            [_defaultModule:protected] => default
            [_frontController:protected] =>
            [_invokeParams:protected] => Array
                (
                )

It's just a part of the code, the necessary things are there, in the old schema of Zend I could be capable to do it calling Zend_Front_Controller, but now I don't know more how to use it.

Appreciate any help!
Best regards and sorry for my BAD English.

To fix this issue, I add the postDispatche at my plugin:

public function postDispatch(Zend_Controller_Request_Abstract $request)
{

$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
$layout = $bootstrap->getResource('layout');
$view = $layout->getView();

$view->controller = $this->getRequest()->getControllerName();
$view->action = $this->getRequest()->getActionName();

}

Thanks again!


问:
how to prepare a query to json postgresql field in php
I am having a problem creating a query in PHP to retrieve a json value from a postgresql database.

The problem is within the json WHERE clause of the following simple query

```<code>select * from json_data where jsonfield ? 'roottag';
</code>```

if i use the PDO prepare:

```<code>$query->prepare($sqlSelect);
</code>```

PDO will translate the ? (postgres json operator to see if the json field starts with a specific tag) to $1.

How do i write a sql statement similar to the one above to be used within php PDO?

答:
To safe other people some time: A PATCH IS ON THE WAY! (at the time of writing)

see: https://github.com/php/php-src/pull/1967

Body:
I am having a problem creating a query in PHP to retrieve a json value from a postgresql database.

The problem is within the json WHERE clause of the following simple query

select * from json_data where jsonfield ? 'roottag';

if i use the PDO prepare:

$query->prepare($sqlSelect);

PDO will translate the ? (postgres json operator to see if the json field starts with a specific tag) to $1.

How do i write a sql statement similar to the one above to be used within php PDO?


问:
Not exported function cannot be used or it is Ok?
In R package there may be some not exported functions which can only access by package name:::function name. These functions were not exported by the author of the package. Is that mean we cannot access them in anyway because the copyright? What about if I really need to based my work on these functions? Any help please?

答: The functions that are not exported are usually internal helper functions for the package. These are not normally meant for general usage. It should be fine to use them, but there may be little or no documentation about them. </p>


问:
The Decorator Pattern & Extension Methods in c#
Before going to describe my problem first,I would like to define definitions of Decorator and Extension method
Decorator

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality

Extension method

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type

I have following code snippet in c#

```<code>public interface IMyInterface
{
    void Print();
}

public static class Extension
{
    public static void PrintInt(this IMyInterface myInterface, int i)
    {
        Console.WriteLine
            ("Extension.PrintInt(this IMyInterface myInterface, int i)");
    }

    public static void PrintString(this IMyInterface myInterface, string s)
    {
        Console.WriteLine
            ("Extension.PrintString(this IMyInterface myInterface, string s)");
    }
}

public class Imp : IMyInterface
{
    #region IMyInterface Members

    public void Print()
    {
        Console.WriteLine("Imp");
    }

    #endregion
}

class Program
{
    static void Main(string[] args)
    {
        Imp obj = new Imp();
        obj.Print();
        obj.PrintInt(10);
    }
}
</code>```

In the above code I am extending  interface without modifying the existing code,and these two methods are available to derived class. So my question is this: Is the extension method a replacement of the decorator pattern?

答:
This explanation by Erich Gamma (GoF) seems to be the best... http://www.mif.vu.lt/~plukas/resources/Extension%20Objects/ExtensionObjectsPattern%20Gamma96.pdf

Essentially stating that

a) Combining all the operations and state that the different clients (present and future) need into a single interface results in a bloated interface

b) Desired operations (known and unknown) can be categorized into components. From which one (or more) Component Interfaces) (extended interfaces) can be defined. These may or may not be implemented by objects (current and future).

c) Clients that wish to use this extended interface can query whether a component supports it

d) Finally, this extended interface has a common base class (ComponentExtension) with minimal interface to manage the extension itself (checking if an extension exists, informing the extension that it is about to be deleted)

To be used when:

1 When your existing classes may need additional and unforeseen interfaces (i.e. new, currently unknown patterns of behavior).

2 When a class representing a key abstraction plays different (unforeseen & open-ended) roles for different clients.

3 You wish to extend without sub-classing

It is similar to the following patterns

Visitor which needs  stable class hierarchy & introduces dependency cycle

Decorator where the use is more transparent, the interface is narrow and existing operations should be augmented

Adapter which supports EXISTING interfaces

Body:
Before going to describe my problem first,I would like to define definitions of Decorator and Extension method
Decorator

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality

Extension method

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type

I have following code snippet in c#

public interface IMyInterface
{
    void Print();
}

public static class Extension
{
    public static void PrintInt(this IMyInterface myInterface, int i)
    {
        Console.WriteLine
            ("Extension.PrintInt(this IMyInterface myInterface, int i)");
    }

    public static void PrintString(this IMyInterface myInterface, string s)
    {
        Console.WriteLine
            ("Extension.PrintString(this IMyInterface myInterface, string s)");
    }
}

public class Imp : IMyInterface
{
    #region IMyInterface Members

    public void Print()
    {
        Console.WriteLine("Imp");
    }

    #endregion
}

class Program
{
    static void Main(string[] args)
    {
        Imp obj = new Imp();
        obj.Print();
        obj.PrintInt(10);
    }
}

In the above code I am extending  interface without modifying the existing code,and these two methods are available to derived class. So my question is this: Is the extension method a replacement of the decorator pattern?


问:
turning string into a number
I am trying to calculate the price total of the below html code and add the result to the dom throuh the JS code further below:

```<code><div class="row">
<div class="col-xs-2 text-center">
<span class="p-name">IronBubble-head</span>
<span id="price-number">$25</span>
<label id="qty" for="qty">QTY</label><input type="number" value="1">
<span id="total">0</span>
<button class="btn btn-delete" type="button">Delete</button>
</div>
</div>
</code>```

and this javascript code:

```<code>function getTotalPrice(e) {
var Price = document.getElementById('price-number').value;
var Quantity = document.getElementById('qty').value;
var Total = document.getElementById('total');
total.innerHTML = Price * Quantity;
}
</code>```

Although the result I get is always NaN.
where is the mistake?

Thanks!

答:
You need strip out any non-numeric characters from price value

```<code>var priceValue = parseFloat(Price.textContent.replace(/[^\d.]/, ''), 10)
</code>```

Full Code

```<code>var Price = document.getElementById('price-number')
var Quantity = document.getElementById('qty')
var Total = document.getElementById('total')

function getTotalPrice() {
  var priceValue = parseFloat(Price.textContent.replace(/[^\d.]/, ''), 10)
  var quantityValue = parseFloat(Quantity.value, 10) || 0
  var totalValue = priceValue * quantityValue

  return totalValue
}

Quantity.addEventListener('input', function() {
    total.innerHTML = getTotalPrice()
})
</code>```

JSFiddle Demo: https://jsfiddle.net/mkpyvqfh/6/

Title: turning string into a number

Body:
I am trying to calculate the price total of the below html code and add the result to the dom throuh the JS code further below:

IronBubble-head
$25
QTY<input type="number" value="1">
0
<button class="btn btn-delete" type="button">Delete</button>

and this javascript code:

function getTotalPrice(e) {
var Price = document.getElementById('price-number').value;
var Quantity = document.getElementById('qty').value;
var Total = document.getElementById('total');
total.innerHTML = Price * Quantity;
}

Although the result I get is always NaN.
where is the mistake?

Thanks!

Body:
You need strip out any non-numeric characters from price value

var priceValue = parseFloat(Price.textContent.replace(/[^\d.]/, ''), 10)

Full Code

var Price = document.getElementById('price-number')
var Quantity = document.getElementById('qty')
var Total = document.getElementById('total')

function getTotalPrice() {
  var priceValue = parseFloat(Price.textContent.replace(/[^\d.]/, ''), 10)
  var quantityValue = parseFloat(Quantity.value, 10) || 0
  var totalValue = priceValue * quantityValue

  return totalValue
}

Quantity.addEventListener('input', function() {
    total.innerHTML = getTotalPrice()
})

JSFiddle Demo: https://jsfiddle.net/mkpyvqfh/6/


问:
Java Rest Api with web browser
So I created a simple java rest api that lets a user enter a movie or search for a movie from mysql database (using postman). My question is I want to create a simple web application that lets the user enter the criteria for a movie, send that data to the api to process it. I am not sure what do I have to use for the web application. Can I use HTML, javascript, jquery for it, or do I have to use jsp and servlets because of Java. </p>

答:
To simplify your code I suggest using JQuery for the API calls. If you want something more elaborated, learn Anguar 4. It's not hard and it works very nice.

HTML, JSF, JSP it doesn't matter. If you want to use JSP "because of Java", you probably don't need to build REST services.

Title: Java Rest Api with web browser


问:
Unity Compute Shader Synchronization
I need your help today ! I begin to work with compute shader in a really simple use case :
I have a depth camera and I want to calculate the bounding box of an object near to the camera.

But I have too much pixel to process and I want to use GPGPU, compute shader and parallelization to compute this.

I currently have a problem, when I run my program, I have the same min and max coordinates. So I think that all my group and threads write in the same time to my StructuredBuffers.

Do you have an idea to how to do that?

Here is the code of my compute shader :

```<code>#pragma kernel ComputeBoundingBox

//We define the size of a group in the x, y and z directions, y and z direction will just be one (because 1D array is used for depthData)
#define thread_group_size_x 1024
#define thread_group_size_y 1
#define thread_group_size_z 1
//Size of the depthData picture
#define width 512;
#define height 424;

//DataBuffer = depthData of the camera
//minBuffer, maxBuffer, array of size 3 with min/max x, y and z
//mask = image area to process
RWStructuredBuffer<float> dataBuffer;
globallycoherent RWStructuredBuffer<float>minBuffer;
globallycoherent RWStructuredBuffer<float> maxBuffer;
RWStructuredBuffer<float> mask;

float xValue = 0, yValue = 0, zValue = 0;

[numthreads(thread_group_size_x, thread_group_size_y, thread_group_size_z)]
void ComputeBoundingBox(uint3 id : SV_DispatchThreadID)
{
    //xValue and yValue = [X,Y] index in 2D
    //zValue = depthValue of [X,Y] index
    xValue = (id.x + 1) % width;
    yValue = (id.x + 1) / width;
    zValue = dataBuffer[id.x];

    if (mask[id.x] > 0.49)
    {
        if (zValue > 500 && zValue < 1500)
        {
            if (xValue < minBuffer[0])
                minBuffer[0] = xValue;
            else if (xValue > maxBuffer[0])
                maxBuffer[0] = xValue;
            if (yValue < minBuffer[1])
                minBuffer[1] = yValue;
            else if (yValue > maxBuffer[1])
                maxBuffer[1] = yValue;
            if (zValue < minBuffer[2])
                minBuffer[2] = zValue;
            else if (zValue > maxBuffer[2])
                maxBuffer[2] = zValue;
        }
    }
}
</code>```

Here is the part of code who call the compute shader :

```<code>void RunShader()
    {
        dataBuffer.SetData(depthDataFloat);
        minDataBuffer.SetData(reinitialiseMinBuffer);
        maxDataBuffer.SetData(reinitialiseMaxBuffer);
        maskBuffer.SetData(mask);

        computeShader.SetBuffer(_kernel, "dataBuffer", dataBuffer);
        computeShader.SetBuffer(_kernel, "minBuffer", minDataBuffer);
        computeShader.SetBuffer(_kernel, "maxBuffer", maxDataBuffer);
        computeShader.SetBuffer(_kernel, "mask", maskBuffer);

        computeShader.Dispatch(_kernel, 212, 1, 1);
    }
</code>```

答:
In your case you do not handle data races, so multiple threads can write in the same place.

In order to make sure that your writes are atomic, you need to use interlocked functions.
Those only work with uint, but in your case (assuming depth data is always > 0),
binary comparison of float will match comparison of their values.

Here is the modified shader :

```<code>#pragma kernel ComputeBoundingBox

#define thread_group_size_x 1024
#define thread_group_size_y 1
#define thread_group_size_z 1
//Size of the depthData picture
#define width 512;
#define height 424;

//DataBuffer = depthData of the camera
//minBuffer, maxBuffer, array of size 3 with min/max x, y and z
//mask = image area to process
StructuredBuffer<float> dataBuffer;
RWStructuredBuffer<float>minBuffer;
RWStructuredBuffer<float> maxBuffer;
StructuredBuffer<float> mask;

[numthreads(thread_group_size_x, thread_group_size_y, thread_group_size_z)]
void ComputeBoundingBox(uint3 id : SV_DispatchThreadID)
{
    //xValue and yValue = [X,Y] index in 2D
    //zValue = depthValue of [X,Y] index
    uint xValue = (id.x + 1) % width;
    uint yValue = (id.x + 1) / width;
    uint zValue = asuint(dataBuffer[id.x]);

    if (mask[id.x] > 0.49)
    {
        if (zValue > 500 && zValue < 1500)
        {
             uint oldValue;
             InterlockedMin(minBuffer[0],xValue,oldValue);
             InterlockedMax(maxBuffer[0],xValue,oldValue);

             InterlockedMin(minBuffer[1],yValue,oldValue);
             InterlockedMax(maxBuffer[1],yValue,oldValue);

             InterlockedMin(minBuffer[2],zValue,oldValue);
             InterlockedMax(maxBuffer[2],zValue,oldValue);
        }
    }
}
</code>```

I did assign dataBuffer and mask as StructuredBuffers too (since you only read to those, it is generally faster with them bound as such).

Also you need to ensure that your min/max buffers are cleared with a suitable value first (that is, before to call that shader).

This can be done with a simple compute shader (dispatch a single thread):

```<code>RWStructuredBuffer<float> minBuffer;
RWStructuredBuffer<float> maxBuffer;

[numthreads(1, 1, 1)]
void ClearBuffers(uint3 id : SV_DispatchThreadID)
{
     uint maxUint = 0xffffffff;
     uint minUint = 0;
     minBuffer[0]= asfloat(maxUint);
     minBuffer[1]= asfloat(maxUint);
     minBuffer[2]= asfloat(maxUint);

     maxBuffer[0]= asfloat(minUint);
     maxBuffer[1]= asfloat(minUint);
     maxBuffer[2]= asfloat(minUint);
}
</code>```

Please note that uint/float aliasing in that case will work, so you don't need to perform any conversion.

Title: Unity Compute Shader Synchronization

Body:
I need your help today ! I begin to work with compute shader in a really simple use case :
I have a depth camera and I want to calculate the bounding box of an object near to the camera.

But I have too much pixel to process and I want to use GPGPU, compute shader and parallelization to compute this.

I currently have a problem, when I run my program, I have the same min and max coordinates. So I think that all my group and threads write in the same time to my StructuredBuffers.

Do you have an idea to how to do that?

Here is the code of my compute shader :

#pragma kernel ComputeBoundingBox

//We define the size of a group in the x, y and z directions, y and z direction will just be one (because 1D array is used for depthData)
#define thread_group_size_x 1024
#define thread_group_size_y 1
#define thread_group_size_z 1
//Size of the depthData picture
#define width 512;
#define height 424;

//DataBuffer = depthData of the camera
//minBuffer, maxBuffer, array of size 3 with min/max x, y and z
//mask = image area to process
RWStructuredBuffer<float> dataBuffer;
globallycoherent RWStructuredBuffer<float>minBuffer;
globallycoherent RWStructuredBuffer<float> maxBuffer;
RWStructuredBuffer<float> mask;

float xValue = 0, yValue = 0, zValue = 0;

[numthreads(thread_group_size_x, thread_group_size_y, thread_group_size_z)]
void ComputeBoundingBox(uint3 id : SV_DispatchThreadID)
{
    //xValue and yValue = [X,Y] index in 2D
    //zValue = depthValue of [X,Y] index
    xValue = (id.x + 1) % width;
    yValue = (id.x + 1) / width;
    zValue = dataBuffer[id.x];

    if (mask[id.x] > 0.49)
    {
        if (zValue > 500 && zValue < 1500)
        {
            if (xValue < minBuffer[0])
                minBuffer[0] = xValue;
            else if (xValue > maxBuffer[0])
                maxBuffer[0] = xValue;
            if (yValue < minBuffer[1])
                minBuffer[1] = yValue;
            else if (yValue > maxBuffer[1])
                maxBuffer[1] = yValue;
            if (zValue < minBuffer[2])
                minBuffer[2] = zValue;
            else if (zValue > maxBuffer[2])
                maxBuffer[2] = zValue;
        }
    }
}

Here is the part of code who call the compute shader :

void RunShader()
    {
        dataBuffer.SetData(depthDataFloat);
        minDataBuffer.SetData(reinitialiseMinBuffer);
        maxDataBuffer.SetData(reinitialiseMaxBuffer);
        maskBuffer.SetData(mask);

        computeShader.SetBuffer(_kernel, "dataBuffer", dataBuffer);
        computeShader.SetBuffer(_kernel, "minBuffer", minDataBuffer);
        computeShader.SetBuffer(_kernel, "maxBuffer", maxDataBuffer);
        computeShader.SetBuffer(_kernel, "mask", maskBuffer);

        computeShader.Dispatch(_kernel, 212, 1, 1);
    }

Body:
In your case you do not handle data races, so multiple threads can write in the same place.

In order to make sure that your writes are atomic, you need to use interlocked functions.
Those only work with uint, but in your case (assuming depth data is always > 0),
binary comparison of float will match comparison of their values.

Here is the modified shader :

#pragma kernel ComputeBoundingBox

#define thread_group_size_x 1024
#define thread_group_size_y 1
#define thread_group_size_z 1
//Size of the depthData picture
#define width 512;
#define height 424;

//DataBuffer = depthData of the camera
//minBuffer, maxBuffer, array of size 3 with min/max x, y and z
//mask = image area to process
StructuredBuffer<float> dataBuffer;
RWStructuredBuffer<float>minBuffer;
RWStructuredBuffer<float> maxBuffer;
StructuredBuffer<float> mask;

[numthreads(thread_group_size_x, thread_group_size_y, thread_group_size_z)]
void ComputeBoundingBox(uint3 id : SV_DispatchThreadID)
{
    //xValue and yValue = [X,Y] index in 2D
    //zValue = depthValue of [X,Y] index
    uint xValue = (id.x + 1) % width;
    uint yValue = (id.x + 1) / width;
    uint zValue = asuint(dataBuffer[id.x]);

    if (mask[id.x] > 0.49)
    {
        if (zValue > 500 && zValue < 1500)
        {
             uint oldValue;
             InterlockedMin(minBuffer[0],xValue,oldValue);
             InterlockedMax(maxBuffer[0],xValue,oldValue);

             InterlockedMin(minBuffer[1],yValue,oldValue);
             InterlockedMax(maxBuffer[1],yValue,oldValue);

             InterlockedMin(minBuffer[2],zValue,oldValue);
             InterlockedMax(maxBuffer[2],zValue,oldValue);
        }
    }
}

I did assign dataBuffer and mask as StructuredBuffers too (since you only read to those, it is generally faster with them bound as such).

Also you need to ensure that your min/max buffers are cleared with a suitable value first (that is, before to call that shader).

This can be done with a simple compute shader (dispatch a single thread):

RWStructuredBuffer<float> minBuffer;
RWStructuredBuffer<float> maxBuffer;

[numthreads(1, 1, 1)]
void ClearBuffers(uint3 id : SV_DispatchThreadID)
{
     uint maxUint = 0xffffffff;
     uint minUint = 0;
     minBuffer[0]= asfloat(maxUint);
     minBuffer[1]= asfloat(maxUint);
     minBuffer[2]= asfloat(maxUint);

     maxBuffer[0]= asfloat(minUint);
     maxBuffer[1]= asfloat(minUint);
     maxBuffer[2]= asfloat(minUint);
}

Please note that uint/float aliasing in that case will work, so you don't need to perform any conversion.


问:
Responsive navigation
I'm trying to make my navigation responsive, I have no idea how, it want it so it doesn't jump of to the next line, I know that the padding is causing this and I could help this by using percentages as width but that looks hella ugly.

This is how the page looks on normal resolution:
http://imgur.com/a/YO7xh

This is how it looks when I zoom in.. (this is what I don't want to happen):
http://imgur.com/a/a3Siu

What can I do to prevent this from happening?

Code for navigation:

.header-side .game {
  float: right;
}

.header-side .selected {
  color: #f7c22c;
}

.header-side .other {
  float: left;
}

.bottom-header {
  height: 115px;
  border-bottom: 1px solid #343538;
  display: flex;
  color: #787878;
  text-transform: uppercase;
  font-size: 14px;
}

header {
  width: 100%;
}

.top-header {
  height: 45px;
  border-bottom: 1px solid #343538;
  width: 100%;
}

.header-side {
  width: 45%;
  height: 100%;
}

.header-middle {
  width: 10%;
  margin: auto;
  display: flex;
  align-items: center;
}

.header-divider {
  height: 60px;
  text-align: center;
  transform: rotate(45deg);
  width: 60px;
  margin: auto;
  border: 1px solid #f7c22c;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="top-header">
    This is the top header!
  </div>
  <div class="bottom-header">
    <div class="header-side">
      <div class="nav-item game">skin upgrade</div>
      <div class="nav-item game">skin royale</div>
      <div class="nav-item game selected">skin crash</div>
    </div>
    <div class="header-middle">
      <div class="header-divider">
      </div>
    </div>
    <div class="header-side">
      <div class="nav-item other">deposit</div>
      <div class="nav-item other">withdraw</div>
      <div class="nav-item other">provably fair</div>
    </div>
  </div>
</header></code>```

答:
Try use media query in css like that:

```<code>@media screen and (max-width: 768px) {
  element {padding: 0;}
}
</code>```

So, when the the resolution get into 768px, it will remove the padding of the element.

Title: Responsive navigation

Body:
I'm trying to make my navigation responsive, I have no idea how, it want it so it doesn't jump of to the next line, I know that the padding is causing this and I could help this by using percentages as width but that looks hella ugly.

This is how the page looks on normal resolution:
http://imgur.com/a/YO7xh

This is how it looks when I zoom in.. (this is what I don't want to happen):
http://imgur.com/a/a3Siu

What can I do to prevent this from happening?

Code for navigation:

.header-side .game {
  float: right;
}

.header-side .selected {
  color: #f7c22c;
}

.header-side .other {
  float: left;
}

.bottom-header {
  height: 115px;
  border-bottom: 1px solid #343538;
  display: flex;
  color: #787878;
  text-transform: uppercase;
  font-size: 14px;
}

header {
  width: 100%;
}

.top-header {
  height: 45px;
  border-bottom: 1px solid #343538;
  width: 100%;
}

.header-side {
  width: 45%;
  height: 100%;
}

.header-middle {
  width: 10%;
  margin: auto;
  display: flex;
  align-items: center;
}

.header-divider {
  height: 60px;
  text-align: center;
  transform: rotate(45deg);
  width: 60px;
  margin: auto;
  border: 1px solid #f7c22c;
}

    This is the top header!

skin upgrade

skin royale

skin crash

deposit

withdraw

provably fair

Body:
Try use media query in css like that:

@media screen and (max-width: 768px) {
  element {padding: 0;}
}

So, when the the resolution get into 768px, it will remove the padding of the element.


问:
MYSQL calculation is returning a wrong value
I have two columns in my database. Column r and column l.
I have two rows in it. Row 302 and row 303.

For row 302 I have the following data

```<code>---------------------------
|   k_id   |   l   |   r  |
|--------------------------
| 302      | 400   | 0    |
| 303      | 0     | 400  |
---------------------------
</code>```

I am trying to run an SQL statement to select the total in row l and l.

In this case the calculation must be: 400 - 400 = 0. But when I run the query I get 400 instead of 0.

Does someone know why I dont get the right response?

Here is my sql statement:

```<code>SELECT COALESCE(SUM(l), 0) - COALESCE(SUM(r), 0) as total
FROM trans
WHERE user_id = '1' AND k_id IN ('302', '303')
GROUP BY k_id WITH ROLLUP LIMIT 0,1
</code>```

答: The problem is the group by k_id part of the statement. This instructs mysql to do the sum by k_id values, therefore 302 and 303 will be summed up separately. Remove the group by clause and the rollup and you will get 0.

Body:
I have two columns in my database. Column r and column l.
I have two rows in it. Row 302 and row 303.

For row 302 I have the following data

---------------------------
|   k_id   |   l   |   r  |
|--------------------------
| 302      | 400   | 0    |
| 303      | 0     | 400  |
---------------------------

I am trying to run an SQL statement to select the total in row l and l.

In this case the calculation must be: 400 - 400 = 0. But when I run the query I get 400 instead of 0.

Does someone know why I dont get the right response?

Here is my sql statement:

SELECT COALESCE(SUM(l), 0) - COALESCE(SUM(r), 0) as total
FROM trans
WHERE user_id = '1' AND k_id IN ('302', '303')
GROUP BY k_id WITH ROLLUP LIMIT 0,1


问:
Spring Data JPA: query ManyToMany, How Can I get the data from mapped Class?
I am developing Spring Boot app with Spring Data JPA and H2 database. I am using spring-data-jpa.
When I use ManyToMany mapper class to get the data of another class. But I found it is NULL.

The code is on github

Book.class

```<code>@Entity
public class Book implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "BOOK_AUTHOR", joinColumns = {
        @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")}, inverseJoinColumns = {
        @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")})
private Set<Author> authors;

public Book() {
    super();
}

public Book(String name) {
    super();
    this.name = name;
    this.authors = new HashSet<>();
}

public Book(String name, Set<Author> authors) {
    super();
    this.name = name;
    this.authors = authors;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

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

public Set<Author> getAuthors() {
    return authors;
}

public void setAuthors(Set<Author> authors) {
    this.authors = authors;
}

@Override
public String toString() {
    return String.format("Book [id=%s, name=%s, authors=%s]", id, name, authors);
}

}
</code>```

Author.class

```<code>@Entity
public class Author implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(mappedBy = "authors")
private Set<Book> books;

//why CAN NOT GET the data when using these code else ?
//    @ManyToMany(cascade = CascadeType.ALL)
//    @JoinTable(name = "BOOK_AUTHOR", joinColumns = {
//            @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")},
//inverseJoinColumns = {
//            @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")})
//    private Set<Book> books;

public Author() {
    super();
}

public Author(String name) {
    super();
    this.name = name;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

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

public Set<Book> getBooks() {
    return books;
}

public void setBooks(Set<Book> books) {
    this.books = books;
}

@Override
public String toString() {
    return String.format("Author [id=%s, name=%s, books=%s]", id, name, books);
}

}
</code>```

Test code snapper in test.class

```<code>    List<Book> books = bookRepository.findAll();
    for (Book it : books) {
        Set<Author> authors = it.getAuthors();
        //CAN get authors data.
        System.out.println(authors.size());
    }

    assertThat(bookRepository.findAll()).hasSize(2);

    List<Author> authors = authorRepository.findAll();
    for (Author it : authors) {
        //CAN NOT get books data ? Why and HOW ?
        //HOW can I get the books data ? Or other ways ?
        // thanks
        Set<Book> books1 = it.getBooks();
        assertThat(books1 == null);
    }

    assertThat(authorRepository.findAll()).hasSize(3);
</code>```

Is there some error in my code ?
Or other ways ?

Thanks vary much.

答:
When I use this code iterator the Set, crash on console:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session, encore un fois

So, I search this tips on Stackoverflow.com.

This answer help me

Just add

FISRT - Initial books

```<code>@ManyToMany(mappedBy = "authors")
private Set<Book> books = new HashSet<Book>();
</code>```

Using @JB Nizet advise, thanks!

SECOND - Add FetchType.EAGER in end links

```<code>@ManyToMany(mappedBy = "posts", fetch = FetchType.EAGER)
@JsonBackReference
</code>```

Thanks for all.

Body:
I am developing Spring Boot app with Spring Data JPA and H2 database. I am using spring-data-jpa.
When I use ManyToMany mapper class to get the data of another class. But I found it is NULL.

The code is on github

Book.class

@Entity
public class Book implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "BOOK_AUTHOR", joinColumns = {
        @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")}, inverseJoinColumns = {
        @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")})
private Set<Author> authors;

public Book() {
    super();
}

public Book(String name) {
    super();
    this.name = name;
    this.authors = new HashSet<>();
}

public Book(String name, Set<Author> authors) {
    super();
    this.name = name;
    this.authors = authors;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

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

public Set<Author> getAuthors() {
    return authors;
}

public void setAuthors(Set<Author> authors) {
    this.authors = authors;
}

@Override
public String toString() {
    return String.format("Book [id=%s, name=%s, authors=%s]", id, name, authors);
}

}

Author.class

@Entity
public class Author implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(mappedBy = "authors")
private Set<Book> books;

//why CAN NOT GET the data when using these code else ?
//    @ManyToMany(cascade = CascadeType.ALL)
//    @JoinTable(name = "BOOK_AUTHOR", joinColumns = {
//            @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")},
//inverseJoinColumns = {
//            @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")})
//    private Set<Book> books;

public Author() {
    super();
}

public Author(String name) {
    super();
    this.name = name;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

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

public Set<Book> getBooks() {
    return books;
}

public void setBooks(Set<Book> books) {
    this.books = books;
}

@Override
public String toString() {
    return String.format("Author [id=%s, name=%s, books=%s]", id, name, books);
}

}

Test code snapper in test.class

    List<Book> books = bookRepository.findAll();
    for (Book it : books) {
        Set<Author> authors = it.getAuthors();
        //CAN get authors data.
        System.out.println(authors.size());
    }

    assertThat(bookRepository.findAll()).hasSize(2);

    List<Author> authors = authorRepository.findAll();
    for (Author it : authors) {
        //CAN NOT get books data ? Why and HOW ?
        //HOW can I get the books data ? Or other ways ?
        // thanks
        Set<Book> books1 = it.getBooks();
        assertThat(books1 == null);
    }

    assertThat(authorRepository.findAll()).hasSize(3);

Is there some error in my code ?
Or other ways ?

Thanks vary much.

Body:
When I use this code iterator the Set, crash on console:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session, encore un fois

So, I search this tips on Stackoverflow.com.

This answer help me

Just add

FISRT - Initial books

@ManyToMany(mappedBy = "authors")
private Set<Book> books = new HashSet<Book>();

Using @JB Nizet advise, thanks!

SECOND - Add FetchType.EAGER in end links

@ManyToMany(mappedBy = "posts", fetch = FetchType.EAGER)
@JsonBackReference

Thanks for all.


问:
Angular 4, Make ng lint error fatal
Angular CLI has a built in linter, running ng lint will lint my code base and report any errors. It can even fix some automatically.

Is there a way I can make linter errors fatal whilst runnning the site with ng serve? i.e I want to display an error message on the front page of the site if any code isn't properly linted?

答:
This is not possible with today's tools.

What you can do is get a tslint extension in your favourite editor. This will show the errors in the editor. For VS Code, just searching for tslint will show the extension directly.

You can also make it part of an NPM script. For example, in your package.json:

```
"scripts": {
  "build": "ng lint && ng build"
}
```

This is still not interactive, but you can a version of it that developers are required to run before pushing code, and your CI build tool runs as well.

For interactive experience, a code editor extension is as close as this gets. In VS Code the tslint errors show in the file itself, and in the errors panel as well, which works nicely for the developers I work with.

Title: Angular 4, Make ng lint error fatal

Body:
This is not possible with today's tools.

What you can do is get a tslint extension in your favourite editor. This will show the errors in the editor. For VS Code, just searching for tslint will show the extension directly.

You can also make it part of an NPM script. For example, in your package.json:

"scripts": {
  "build": "ng lint && ng build"
}

This is still not interactive, but you can a version of it that developers are required to run before pushing code, and your CI build tool runs as well.

For interactive experience, a code editor extension is as close as this gets. In VS Code the tslint errors show in the file itself, and in the errors panel as well, which works nicely for the developers I work with.


问:
Implement an algorithm in Scala to determin if a string has all unique characters
I am solving trivial problems to learn Scala. Here is what I have come up with

```<code>def isUnique(str: String): Boolean = {
    if (str.length > 128) return false
    val uniqueChars = new Array[Boolean](128)

    !(str.map(c => addChar(c, uniqueChars)).find(identity).isDefined)
}

def addChar(ch: Char, uniqueChars: Array[Boolean]): Boolean = {
    if (uniqueChars(ch)) return true else {
    uniqueChars(ch) = true;
    return false
}
</code>```

Is that it?

Please note that I don't care about the logic or optimization at this point. I only need to learn the Scala way of doing it.

[Edit]
Let's assume we don't want to use the string distinct method. I only need to verify the functional style of Scala.

答:
OK, so if you don't to want utilize the distinct library method then recursion is usually the functional way to go.

```<code>def isUnique(str: String, chrs: Set[Char] = Set()): Boolean =
  str.length == 0 ||
    !chrs(str.head) &&
      isUnique(str.tail, chrs + str.head)

isUnique("abcdexf")  // true
isUnique("abcdxxf")  // false
isUnique("fbcdexf")  // false
isUnique("abdbexf")  // false
</code>```

Body:
I am solving trivial problems to learn Scala. Here is what I have come up with

def isUnique(str: String): Boolean = {
    if (str.length > 128) return false
    val uniqueChars = new Array[Boolean](128)

    !(str.map(c => addChar(c, uniqueChars)).find(identity).isDefined)
}

def addChar(ch: Char, uniqueChars: Array[Boolean]): Boolean = {
    if (uniqueChars(ch)) return true else {
    uniqueChars(ch) = true;
    return false
}

Is that it?

Please note that I don't care about the logic or optimization at this point. I only need to learn the Scala way of doing it.

[Edit]
Let's assume we don't want to use the string distinct method. I only need to verify the functional style of Scala.

Body:
OK, so if you don't to want utilize the distinct library method then recursion is usually the functional way to go.

def isUnique(str: String, chrs: Set[Char] = Set()): Boolean =
  str.length == 0 ||
    !chrs(str.head) &&
      isUnique(str.tail, chrs + str.head)

isUnique("abcdexf")  // true
isUnique("abcdxxf")  // false
isUnique("fbcdexf")  // false
isUnique("abdbexf")  // false


答:
Well, you could use https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
Or you could go with percentage. After all a desktop webpage wouldnt look any better in a 420p screen.
I would suggest to go with something more "low resolution", such as a mobile design, so using media queries is probably the best you can do.

EDIT: https://www.w3schools.com/css/css_rwd_mediaqueries.asp
This is what you want.

Title: Responsive navigation


问:
docker compose variable substitution
It seems that I am not understanding something about variable substitution in the following page (my variable NUM is not registering): https://github.com/compose-spec/compose-spec/blob/master/spec.md#Interpolation

See screenshot below. Running this on mac OSX.

答:
In addition to $$ solution provided by @ayman-nedjmeddine above you also need to do following, to make shell variables available in compose you have two options

Option 1

log in as root , set your variable and execute docker-compose

root>export NUM=5

root>docker-compose up

Option 2

use sudo -E from user shell, -E will propagate user shell env to sudo,

provide sudo access to docker/docker-compose

add :SETENV: to the command in sudoer file to use -E option in sudo

eg:

```<code>sudo visudo -f /etc/sudoers.d/docker-compose
    ALL   ALL=(ALL:ALL) NOPASSWD:SETENV: /usr/local/bin/docker-compose
sudo visudo -f /etc/sudoers.d/docker
    ALL   ALL=(ALL:ALL) NOPASSWD:SETENV: /usr/bin/docker
</code>```

finally use

```<code>user1>export NUM=5
user1>sudo -E docker-compose up
</code>```

ContentLicense: CC BY-SA 4.0

Title: docker compose variable substitution

Body:
In addition to $$ solution provided by @ayman-nedjmeddine above you also need to do following, to make shell variables available in compose you have two options

Option 1

log in as root , set your variable and execute docker-compose

root>export NUM=5

root>docker-compose up

Option 2

use sudo -E from user shell, -E will propagate user shell env to sudo,

provide sudo access to docker/docker-compose

add :SETENV: to the command in sudoer file to use -E option in sudo

eg:

sudo visudo -f /etc/sudoers.d/docker-compose
    ALL   ALL=(ALL:ALL) NOPASSWD:SETENV: /usr/local/bin/docker-compose
sudo visudo -f /etc/sudoers.d/docker
    ALL   ALL=(ALL:ALL) NOPASSWD:SETENV: /usr/bin/docker

finally use

user1>export NUM=5
user1>sudo -E docker-compose up


问:
Convert string to array in Java?
I have a string which has the values like this (format is the same):

```<code>name:xxx
occupation:yyy
phone:zzz
</code>```

I want to convert this into an array and get the occupation value using indexes.

Any suggestions?

答:
If you are only interested in the occupation value, you could do:</p>

```<code>String s = "name:xxx occupation:yyy phone:zzz";
Pattern pattern = Pattern.compile(".*occupation:(\\S+).*");
Matcher matcher = pattern.matcher(s);
if (matcher.matches()){
    String occupation = matcher.group(1);
}
</code>```

Title: Convert string to array in Java?

Body:
I have a string which has the values like this (format is the same):

name:xxx
occupation:yyy
phone:zzz

I want to convert this into an array and get the occupation value using indexes.

Any suggestions?

Body:
If you are only interested in the occupation value, you could do:

String s = "name:xxx occupation:yyy phone:zzz";
Pattern pattern = Pattern.compile(".*occupation:(\\S+).*");
Matcher matcher = pattern.matcher(s);
if (matcher.matches()){
    String occupation = matcher.group(1);
}


问:
Using Microsoft Graph client sdk how would you use search Odata query
Using Microsoft Graph client sdk how would one go about using search Odata query to lookup if subject or body contains a certain search term.

The $search Odata query parameter is available in the Graph Client api, but i could not find how to use the parameter using the client sdk for c#.

答:
You can add any query parameters by passing in a list of QueryOptions to the Request method.

```<code>List<QueryOption> options = new List<QueryOption>
{
     new QueryOption("$search", "lunch")
};
var messages = await client.Me.Messages.Request(options).GetAsync();
</code>```

Documentation: https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/docs/overview.md#custom-query-options

Body:
You can add any query parameters by passing in a list of QueryOptions to the Request method.

List<QueryOption> options = new List<QueryOption>
{
     new QueryOption("$search", "lunch")
};
var messages = await client.Me.Messages.Request(options).GetAsync();

Documentation: https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/docs/overview.md#custom-query-options


问:
Qt5: filtering out the horizontal component from wheel events
I am trying to filter out any horizontal wheel/touchpad scrolling in a widget (ProjectTreeView) that is based on a QTreeView. The idea is to let the vertical movement pass through, supporting horizontal scrolling only via the scrollbar.

I've tried to implement this via a ProjectTreeView::wheelEvent() event handler (below), but that function somehow has the opposite effect. Am I overlooking something (too) obvious or doing something wrong altogether?

```<code>void ProjectTreeView::wheelEvent(QWheelEvent *e)
{
    if ((e->pixelDelta().x() != 0 || e->angleDelta().x() !=0)
#ifdef Q_OS_MACOS
        // allow horizontal scrolling controlled by a physical mouse wheel
        && e->source() != Qt::MouseEventNotSynthesized
#endif
    ){
        QPoint pixelDelta(e->pixelDelta()), angleDelta(e->angleDelta());
        // disable horizontal wheel scrolling
        pixelDelta.setX(0);
        angleDelta.setX(0);
        // discard the original event
        e->accept();
        QWheelEvent filtered(e->posF(), e->globalPosF(), pixelDelta, angleDelta,
            e->delta(), e->orientation(), e->buttons(),
            e->modifiers(), e->phase(), e->source(), e->inverted());
        QCoreApplication::sendEvent(this, &filtered);
    } else {
        QTreeView::wheelEvent(e);
    }
}
</code>```

When I try to filter via ProjectTreeView::event(QEvent*) I observe that
1) I hardly receive any wheel events at all, at least not when I'm trying to scroll (some come in when I release the touchpad)
2) the events that do come in don't have the required delta information (both components are 0).

This reminds me of remarks I've seen about the Qt4 implementation about how the events are actually treated by a different widget.

thanks!

答:
You can do it easily by installing and event filter function.

```<code>bool eventFilter( QObject * o, QEvent * e ) {
   if (e->type() == QEvent::Wheel
       && qobject_cast<ProjectTreeView*>( o ) ) {
        // Then do what you want, per example: ignore it.
        e->ignore();
        return true;
   }
   return QWidget::eventFilter( o, e );
}
</code>```

If you want the user to use the scroll by clicking in the scrollbar then you can modify the focus polizy of the widget. It should fix your problem:

```<code>setFocusPolicy(Qt::ClickFocus);
</code>```

Body:
I am trying to filter out any horizontal wheel/touchpad scrolling in a widget (ProjectTreeView) that is based on a QTreeView. The idea is to let the vertical movement pass through, supporting horizontal scrolling only via the scrollbar.

I've tried to implement this via a ProjectTreeView::wheelEvent() event handler (below), but that function somehow has the opposite effect. Am I overlooking something (too) obvious or doing something wrong altogether?

void ProjectTreeView::wheelEvent(QWheelEvent *e)
{
    if ((e->pixelDelta().x() != 0 || e->angleDelta().x() !=0)
#ifdef Q_OS_MACOS
        // allow horizontal scrolling controlled by a physical mouse wheel
        && e->source() != Qt::MouseEventNotSynthesized
#endif
    ){
        QPoint pixelDelta(e->pixelDelta()), angleDelta(e->angleDelta());
        // disable horizontal wheel scrolling
        pixelDelta.setX(0);
        angleDelta.setX(0);
        // discard the original event
        e->accept();
        QWheelEvent filtered(e->posF(), e->globalPosF(), pixelDelta, angleDelta,
            e->delta(), e->orientation(), e->buttons(),
            e->modifiers(), e->phase(), e->source(), e->inverted());
        QCoreApplication::sendEvent(this, &filtered);
    } else {
        QTreeView::wheelEvent(e);
    }
}

When I try to filter via ProjectTreeView::event(QEvent*) I observe that
1) I hardly receive any wheel events at all, at least not when I'm trying to scroll (some come in when I release the touchpad)
2) the events that do come in don't have the required delta information (both components are 0).

This reminds me of remarks I've seen about the Qt4 implementation about how the events are actually treated by a different widget.

thanks!

Body:
You can do it easily by installing and event filter function.

bool eventFilter( QObject * o, QEvent * e ) {
   if (e->type() == QEvent::Wheel
       && qobject_cast<ProjectTreeView*>( o ) ) {
        // Then do what you want, per example: ignore it.
        e->ignore();
        return true;
   }
   return QWidget::eventFilter( o, e );
}

If you want the user to use the scroll by clicking in the scrollbar then you can modify the focus polizy of the widget. It should fix your problem:

setFocusPolicy(Qt::ClickFocus);


问:
What is RevertToSelf()? - C#.net
I don't understand what RevertToSelf() does in a .net application. Checking MSDN definition it reads the definition as

```<code>The RevertToSelf function terminates the impersonation of a client application.
</code>```

So does the current user context changes to a sysadmin context by stopping client's context? By calling RevertToSelf() will my code run on sys admin mode?

Update

Okay so what happens if I call RevertToSelf() in an ASP.NET application? Let us consider I dont start any impersonation. So if I call RevertToSelf() will it revert to the application pool identity?

答: It changes to context of user that ran the application before impersonation. It is not necessary sysadmin. Read more here: http://msdn.microsoft.com/en-us/library/aa376391(v=vs.85).aspx</p>

Title: What is RevertToSelf()? - C#.net

Body:
I don't understand what RevertToSelf() does in a .net application. Checking MSDN definition it reads the definition as

The RevertToSelf function terminates the impersonation of a client application.

So does the current user context changes to a sysadmin context by stopping client's context? By calling RevertToSelf() will my code run on sys admin mode?

Update

Okay so what happens if I call RevertToSelf() in an ASP.NET application? Let us consider I dont start any impersonation. So if I call RevertToSelf() will it revert to the application pool identity?


问:
Match Phone Number from Sheet Cell Value to Google Contacts and get Full name and Address
It's my first question, I am feeling nervous.

Here, I am trying to get Customer Full name and address from google contacts. But it's not working. Looking for experts help

```<code>function importContact() {
   var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "Stock" ) {
    var r = s.getActiveCell();
    var phone = r.getValue()
  if( r.getColumn() == 10 ) {
      var nextCell1 = r.offset(0, 1);
      var nextCell2 = r.offset(0, 2);
      var contacts = ContactsApp.getContactsByPhone(phone,'Other');
   for(var i = 0, iLen = contacts.length; i < iLen; i++) {
    var fullname = contacts[i].getFullName();
    var address = contacts[i].getAddresses(ContactsApp.Field.HOME_ADDRESS);
    if(fullname) {
       nextCell1.setValue(fullname);
       nextCell2.setValue(address);
    } else {
       nextCell1.setValue('New Customer');
    }
  }
}
}
}
</code>```

Thank you very much

答:
Solution #1 did not seem to fully work, so debugged and amended until:

it did confirm the "new customer" event, and

worked for addresses.

Tried to comment Cooper's one, but do not have enough reputation. Hope this is ok, and am ready to erase my reply if needed.

A few notes on the code:

it assumes that any contact has a name field, but it might not be always true;

it checks if the address fields exists though, because it is way more likely to be empty than name field;

in case address does not exist code enters N.A. in the address cell;

var address = addresses[0].getAddress()  was the main missing link in the first solution, apparently;

users other than the original questioner should replace "Stock" in if( s.getName() == "Stock" ) with appropriate Sheet Name.

As should be obvious, by now: I am a learner, not an expert. Any suggestion to improve is more than welcome.

function importContact()
{
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  if( s.getName() == "Stock" )
  {
    var r = s.getActiveCell();
    var phone = r.getValue();
    if( r.getColumn() == 1 )
    {
      var nextCell1 = r.offset(0, 1);
      var nextCell2 = r.offset(0, 2);
      var contacts = ContactsApp.getContactsByPhone(phone);
      if(contacts.length == 0)
      {
        nextCell1.setValue('New Customer');
      }
      else
      {
        for(var i = 0; i < contacts.length; i++)
        {
          var fullname = contacts[i].getFullName();
          nextCell1.setValue(fullname);
          var addresses = contacts[i].getAddresses(ContactsApp.Field.HOME_ADDRESS);
          if (addresses.length == 0)
          {
            nextCell2.setValue("Not Available");
          }
          else
          {
            var address = addresses[0].getAddress() //this was the missing link in the first solution, apparently
            nextCell2.setValue(address);
          }
        }
      }
     }
    }
}```

Body:
It's my first question, I am feeling nervous.

Here, I am trying to get Customer Full name and address from google contacts. But it's not working. Looking for experts help

function importContact() {
   var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "Stock" ) {
    var r = s.getActiveCell();
    var phone = r.getValue()
  if( r.getColumn() == 10 ) {
      var nextCell1 = r.offset(0, 1);
      var nextCell2 = r.offset(0, 2);
      var contacts = ContactsApp.getContactsByPhone(phone,'Other');
   for(var i = 0, iLen = contacts.length; i < iLen; i++) {
    var fullname = contacts[i].getFullName();
    var address = contacts[i].getAddresses(ContactsApp.Field.HOME_ADDRESS);
    if(fullname) {
       nextCell1.setValue(fullname);
       nextCell2.setValue(address);
    } else {
       nextCell1.setValue('New Customer');
    }
  }
}
}
}

Thank you very much


问:
Custom domain name with create-react-app + github pages
I followed the instructions here in order to deploy my site on github pages. This works fine; I can go here to view the deployed project.

However, I'm having problems setting up a custom domain name. I followed the instructions outlined in this post, and added a CNAME file pointing at www.onlineomnichord.com to my public/ folder. When I go to my site, I get a 404 Not Found when trying to GET my project's bundled js file. You can see that behavior if you go to www.onlineomnichord.com in the Network tab of Inspect. Not really sure how to resolve this, any suggestions?

Note: the repo I'm working with can be found here.

答: Decided to just use the heroku buildpack. Plays much nicer with BrowserRouter too.


问:
Operator '>=' cannot be applied to operands of type 'string' and 'string'
I'm using Entity Framework in C# and my code is

```<code>var result = ef.services.Where(entry => entry.tarikhservice >= textBoxX1.Text
                                     && entry.tarikhservice <= textBoxX2.Text).ToList();
</code>```

which gives me this error:

Operator '>=' cannot be applied to operands of type 'string' and 'string'

How to compare two string and fix the error?

答:
I'm not sure I agree with the rationale given in the current answers for not implementing the comparison operators in String. In fact, I submit that implementing them using String.Compare would be just as consistent as the current equality operator implementation using String.Equals.

I have a different theory. If you examine the Best Practices for Using Strings in .NET you will note the following recommendation:

The String class lets you test for equality by calling either the
  static or instance Equals method overloads, or by using the static
  equality operator. The overloads and operator use ordinal comparison
  by default. However, we still recommend that you call an overload that
  explicitly specifies the StringComparison type even if you want to
  perform an ordinal comparison

Note that they couldn't enforce this recommendation even if they wanted to - even if they didn't override the == operator in String, you could still do  str1 == str2. Heck, you could compare an integer to a string using the equality operator if you really wanted to (obj i = 1). This is because == translates into reference equality when not overridden specifically for the operand types.

The BCL designers realized this and decided they would be better off implementing a comparison operator that works as expected most of the time, rather than delegate the comparison to reference equality, which would be a really bad idea considering string interning and Unicode equivalence.

Now, back to comparison operators. The same pitfalls with string equality apply, but the BCL designers have an easier time here. By simply not implementing these operators, the compiler does their job for them and, as we can see in this question, prevents devs from even trying to do things like str1 >= str2.

Body:
I'm using Entity Framework in C# and my code is

var result = ef.services.Where(entry => entry.tarikhservice >= textBoxX1.Text
                                     && entry.tarikhservice <= textBoxX2.Text).ToList();

which gives me this error:

Operator '>=' cannot be applied to operands of type 'string' and 'string'

How to compare two string and fix the error?


答:
Some years ago I've written a tiny IDisposable-implementing class called Impersonator to do the impersonation/revertion (nearly) automatically.

Maybe if you take a look, it will tell you how and when to use it?

Title: What is RevertToSelf()? - C#.net


问:
How to add custom properties to Paperjs objects?
I found some discussions about doing this using the inject method, like this one https://groups.google.com/forum/#!topic/paperjs/16ToDJquig8

But I cannot find this method in the official doc.  So what is the officially recommended way to add custom properties to Paperjs objects?

答:
If you just want to add properties to an Item, you can use Item.data.

From paper.js documentation:

Item.data: A plain javascript object which can be used to store arbitrary data on the item.

Example:

```<code>var path = new Path();
path.data.remember = 'milk';
</code>```

Body:
If you just want to add properties to an Item, you can use Item.data.

From paper.js documentation:

Item.data: A plain javascript object which can be used to store arbitrary data on the item.

Example:

var path = new Path();
path.data.remember = 'milk';


问:
How to deliver new features (Website)
I have recently been thinking about one of my websites. It's getting big and gaining a community and I have realized; how would I implement new features. Would I code instantly on the website or would I have to pull a backup and code on it then put it back up on the server. Because both methods seem to be inefficient.

Would there be a way that I can do such a thing, like a version system (similar to apps)?

答:
Create a duplicate, test your code until you're satisfied. Check the edge cases. Try to break it. Then, when you're sure it's solid, roll it out to your users during very light usage because you might need to turn off  the whole site during the upgrade.

Testing, testing, testing is they key.

Title: How to deliver new features (Website)


问:
CSS Overlapping divs of equal size
I want a div on the top of another div. Before putting the position:absolute, the p's on the top div look great, but when I put the position:absolute, it shows the three p's in a straight line with no spaces between them.

How do I make this div with position:absolute to have the p's in different lines, like it is supposed to be?

Here's an example of what I'm trying to do:

```<code><div class="box">
<p>Some text</p>

<div class="box-top">
<p>• Line 1</p>
<p>• Line 2</p>
<p>• Line 3</p>
</div>

</div>
</code>```

Like I said before, I want a div ("box-top") on the top of another div ("box").

答:
All you need to do is set position: relative on the parent and position: absolute on the child. If you want the child to occupy the size of the parent, I would use top: 0; left: 0; right: 0; bottom: 0; for positioning.

.box {
  position: relative;
  background: black;
  color: white;
  height: 50vh;
}
.box-top {
  background: white;
  color: black;
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <p>Some text</p>
  <div class="box-top">
    <p>• Line 1</p>
    <p>• Line 2</p>
    <p>• Line 3</p>
  </div>
</div></code>```

Title: CSS Overlapping divs of equal size

Body:
I want a div on the top of another div. Before putting the position:absolute, the p's on the top div look great, but when I put the position:absolute, it shows the three p's in a straight line with no spaces between them.

How do I make this div with position:absolute to have the p's in different lines, like it is supposed to be?

Here's an example of what I'm trying to do:

Some text

• Line 1

• Line 2

• Line 3

Like I said before, I want a div ("box-top") on the top of another div ("box").

Body:
All you need to do is set position: relative on the parent and position: absolute on the child. If you want the child to occupy the size of the parent, I would use top: 0; left: 0; right: 0; bottom: 0; for positioning.

.box {
  position: relative;
  background: black;
  color: white;
  height: 50vh;
}
.box-top {
  background: white;
  color: black;
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
}

<div class="box">
  <p>Some text</p>
  <div class="box-top">
    <p>• Line 1</p>
    <p>• Line 2</p>
    <p>• Line 3</p>
  </div>
</div>