问:
Best practice for React's setState
With React's relatively new state hook, I was wondering what best practices dictate as far as use cases. For example, which of the two below is preferred:

```<code>const [water, setWater] = useState('');
</code>```

and then call:

```<code>if (args._d) {
  setWater(args._d);
}
</code>```

or:

```<code>const [state, setState] = React.useState({ water: '' });
</code>```

and then call:

```<code>if (args._d) {
  setState({ water: 'something' })
}
</code>```

答:
Most of the examples I've seen (including the React documentation) use your first approach, especially when dealing with only one piece of state. That said, neither approach is inherently better/worse than the other (the React docs have some guidance on this).

One thing to note is that the setters returned from useState will replace, not merge, the existing state. This becomes important when dealing with multiple state values:

```<code>const [state, setState] = useState({ water: '', food:  []});

// Incorrect! This will overwrite state, removing `food`:
setState({ water: 'H2O' });

// Correct, but more verbose than class-based setState:
setState(prevState => ({
  ...prevState,
  water: 'H2O'
}));
</code>```

If you do set multiple values in a single state, the React docs say this:

we recommend to split state into multiple state variables based on which values tend to change together.

The docs also favor using useReducer when state logic becomes more complex. Here's the relevant section in the docs: https://reactjs.org/docs/hooks-faq.html#should-i-use-one-or-many-state-variables

Title: Best practice for React's setState

Body:
With React's relatively new state hook, I was wondering what best practices dictate as far as use cases. For example, which of the two below is preferred:

const [water, setWater] = useState('');

and then call:

if (args._d) {
  setWater(args._d);
}

or:

const [state, setState] = React.useState({ water: '' });

and then call:

if (args._d) {
  setState({ water: 'something' })
}

Body:
Most of the examples I've seen (including the React documentation) use your first approach, especially when dealing with only one piece of state. That said, neither approach is inherently better/worse than the other (the React docs have some guidance on this).

One thing to note is that the setters returned from useState will replace, not merge, the existing state. This becomes important when dealing with multiple state values:

const [state, setState] = useState({ water: '', food:  []});

// Incorrect! This will overwrite state, removing `food`:
setState({ water: 'H2O' });

// Correct, but more verbose than class-based setState:
setState(prevState => ({
  ...prevState,
  water: 'H2O'
}));

If you do set multiple values in a single state, the React docs say this:

we recommend to split state into multiple state variables based on which values tend to change together.

The docs also favor using useReducer when state logic becomes more complex. Here's the relevant section in the docs: https://reactjs.org/docs/hooks-faq.html#should-i-use-one-or-many-state-variables


来源: stackexchange

问:
How do I convert battery voltage into battery percentage on a 4.15V Li-Ion Battery in an Arduino IDE? (I am making some kind of LED Battery Indicator)
I know that battery discharge on a 4.15V Li-Ion is not linear, so I would like to have some equation that I can apply in my code to show the correct battery percentage.

I can't find any good resources on doing this in an Arduino IDE. (Help with link if you guys have)

答:
Actually, you can't do much about nonlinear behavior; you can measure your max and min voltages and calculate the battery percentage based on that. Below I created a function that returns the percentage of battery level. Remember to edit battery_max and battery_min based on your battery voltage levels.

Also, I recommend you create a resistor divider circuit to reduce the voltage level because if your input power supply drops down, the Arduino will feed directly from Analog input which is undesirable.

```<code>int battery_pin = A3;

float battery_read()
{
    //read battery voltage per %
    long sum = 0;                   // sum of samples taken
    float voltage = 0.0;            // calculated voltage
    float output = 0.0;             //output value
    const float battery_max = 4.20; //maximum voltage of battery
    const float battery_min = 3.0;  //minimum voltage of battery before shutdown

    for (int i = 0; i < 500; i++)
    {
        sum += analogRead(battery_pin);
        delayMicroseconds(1000);
    }
    // calculate the voltage
    voltage = sum / (float)500;
    // voltage = (voltage * 5.0) / 1023.0; //for default reference voltage
    voltage = (voltage * 1.1) / 1023.0; //for internal 1.1v reference
    //round value by two precision
    voltage = roundf(voltage * 100) / 100;
    Serial.print("voltage: ");
    Serial.println(voltage, 2);
    output = ((voltage - battery_min) / (battery_max - battery_min)) * 100;
    if (output < 100)
        return output;
    else
        return 100.0f;
}

void setup()
{
    analogReference(INTERNAL); //set reference voltage to internal
    Serial.begin(9600);
}

void loop()
{
    Serial.print("Battery Level: ");
    Serial.println(battery_read(), 2);
    delay(1000);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Actually, you can't do much about nonlinear behavior; you can measure your max and min voltages and calculate the battery percentage based on that. Below I created a function that returns the percentage of battery level. Remember to edit battery_max and battery_min based on your battery voltage levels.

Also, I recommend you create a resistor divider circuit to reduce the voltage level because if your input power supply drops down, the Arduino will feed directly from Analog input which is undesirable.

int battery_pin = A3;

float battery_read()
{
    //read battery voltage per %
    long sum = 0;                   // sum of samples taken
    float voltage = 0.0;            // calculated voltage
    float output = 0.0;             //output value
    const float battery_max = 4.20; //maximum voltage of battery
    const float battery_min = 3.0;  //minimum voltage of battery before shutdown

    for (int i = 0; i < 500; i++)
    {
        sum += analogRead(battery_pin);
        delayMicroseconds(1000);
    }
    // calculate the voltage
    voltage = sum / (float)500;
    // voltage = (voltage * 5.0) / 1023.0; //for default reference voltage
    voltage = (voltage * 1.1) / 1023.0; //for internal 1.1v reference
    //round value by two precision
    voltage = roundf(voltage * 100) / 100;
    Serial.print("voltage: ");
    Serial.println(voltage, 2);
    output = ((voltage - battery_min) / (battery_max - battery_min)) * 100;
    if (output < 100)
        return output;
    else
        return 100.0f;
}

void setup()
{
    analogReference(INTERNAL); //set reference voltage to internal
    Serial.begin(9600);
}

void loop()
{
    Serial.print("Battery Level: ");
    Serial.println(battery_read(), 2);
    delay(1000);
}


问:
Trouble loading NIB file into a UIView
Please forgive me as this question has been asked 100 times on here (and I promise that I've read every thread!), but I simply can't figure out how to correctly load a NIB file into a UIView.  I tried two approaches (seen below), though neither seemed to work for me.  I have a UINavController/UIViewController setup and I'm trying to load a subclassed UIView into a small area on one of these UIViewControllers.

This answer seemed reasonable, but i can't seem to get it to work:  iPhone - Load a UIView from a nib file?

```<code>// ViewController.m
localAssetUpdater = [[LocalAssetUpdater alloc] initWithFrame:[self.view frame]];

// LocalAssetUpdater.m
- (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
        [[NSBundle mainBundle] loadNibNamed:@"LocalAssetUpdater" owner:self options:nil];

        [self reset];
        [self beginLoad];
    }
    return self;
}

 //OR:

// ViewController.m
localAssetUpdater = [LocalAssetUpdater myView];

// LocalAssetUpdater.m
+ (LocalAssetUpdater *) myView
{
    NSArray* array = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil];
    return [array objectAtIndex:0]; // assume that MyView is the only object in the xib
}
</code>```

答:
```<code>@implementation MyView

+ (MyView*) myView
{
  NSArray* array = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil];
  for (id object in array) {
    if ([object isKindOfClass:[YourClassName class]])
        self = (YourClassName*)object;
}
}

@end
</code>```

ContentLicense: CC BY-SA 3.0

Title: Trouble loading NIB file into a UIView

Body:
Please forgive me as this question has been asked 100 times on here (and I promise that I've read every thread!), but I simply can't figure out how to correctly load a NIB file into a UIView.  I tried two approaches (seen below), though neither seemed to work for me.  I have a UINavController/UIViewController setup and I'm trying to load a subclassed UIView into a small area on one of these UIViewControllers.

This answer seemed reasonable, but i can't seem to get it to work:  iPhone - Load a UIView from a nib file?

// ViewController.m
localAssetUpdater = [[LocalAssetUpdater alloc] initWithFrame:[self.view frame]];

// LocalAssetUpdater.m
- (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
        [[NSBundle mainBundle] loadNibNamed:@"LocalAssetUpdater" owner:self options:nil];

        [self reset];
        [self beginLoad];
    }
    return self;
}

 //OR:

// ViewController.m
localAssetUpdater = [LocalAssetUpdater myView];

// LocalAssetUpdater.m
+ (LocalAssetUpdater *) myView
{
    NSArray* array = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil];
    return [array objectAtIndex:0]; // assume that MyView is the only object in the xib
}


问:
Arranging the number 1 in a 2d matrix
Given the number of rows and columns of a 2d matrix

Initially all elements of matrix are 0

Given the number of 1's that should be present in each row

Given the number of 1's that should be present in each column

Determine if it is possible to form such matrix.

Example:

```<code>Input: r=3 c=2 (no. of rows and columns)
2 1 0 (number of 1's that should be present in each row respectively)
1 2 (number of 1's that should be present in each column respectively)
</code>```

Output: Possible

Explanation:

```<code>1 1
0 1
0 0
</code>```

I tried solving this problem for like 12 hours by checking if summation of Ri = summation of Ci

But I wondered if wouldn't be possible for cases like

```<code>3 3
1 3 0
0 2 2
</code>```

r and c can be upto 10^5

Any ideas how should I move further?

Edit: Constraints added and output should only be "possible" or "impossible". The possible matrix need not be displayed.

Can anyone help me now?

答:
(Note: to avoid confusion between when I'm talking about the actual numbers in the problem vs. when I'm talking about the zeros in the ones in the matrix, I'm going to instead fill the matrix with spaces and X's. This obviously doesn't change the problem.)

Some observations:

If you're filling in a row, and there's (for example) one column needing 10 more X's and another column needing 5 more X's, then you're sometimes better off putting the X in the "10" column and saving the "5" column for later (because you might later run into 5 rows that each need 2 X's), but you're never better off putting the X in the "5" column and saving the "10" column for later (because even if you later run into 10 rows that all need an X, they won't mind if they don't all go in the same column). So we can use a somewhat "greedy" algorithm: always put an X in the column still needing the most X's. (Of course, we'll need to make sure that we don't greedily put an X in the same column multiple times for the same row!)

Since you don't need to actually output a possible matrix, the rows are all interchangeable and the columns are all interchangeable; all that matter is how many rows still need 1 X, how many still need 2 X's, etc., and likewise for columns.

With that in mind, here's one fairly simple approach:

(Optimization.) Add up the counts for all the rows, add up the counts for all the columns, and return "impossible" if the sums don't match.

Create an array of length r+1 and populate it with how many columns need 1 X, how many need 2 X's, etc. (You can ignore any columns needing 0 X's.)

(Optimization.) To help access the array efficiently, build a stack/linked-list/etc. of the indices of nonzero array elements, in decreasing order (e.g., starting at index r if it's nonzero, then index r−1 if it's nonzero, etc.), so that you can easily find the elements representing columns to put X's in.

(Optimization.) To help determine when there'll be a row can't be satisfied, also make note of the total number of columns needing any X's, and make note of the largest number of X's needed by any row. If the former is less than the latter, return "impossible".

(Optimization.) Sort the rows by the number of X's they need.

Iterate over the rows, starting with the one needing the fewest X's and ending with the one needing the most X's, and for each one:

Update the array accordingly. For example, if a row needs 12 X's, and the array looks like [..., 3, 8, 5], then you'll update the array to look like [..., 3+7 = 10, 8+5−7 = 6, 5−5 = 0]. If it's not possible to update the array because you run out of columns to put X's in, return "impossible". (Note: this part should never actually return "impossible", because we're keeping count of the number of columns left and the max number of columns we'll need, so we should have already returned "impossible" if this was going to happen. I mention this check only for clarity.)

Update the stack/linked-list of indices of nonzero array elements.

Update the total number of columns needing any X's. If it's now less than the greatest number of X's needed by any row, return "impossible".

(Optimization.) If the first nonzero array element has an index greater than the number of rows left, return "impossible".

If we complete our iteration without having returned "impossible", return "possible".

(Note: the reason I say to start with the row needing the fewest X's, and work your way to the row with the most X's, is that a row needing more X's may involve examining updating more elements of the array and of the stack, so the rows needing fewer X's are cheaper. This isn't just a matter of postponing the work: the rows needing fewer X's can help "consolidate" the array, so that there will be fewer distinct column-counts, making the later rows cheaper than they would otherwise be. In a very-bad-case scenario, such as the case of a square matrix where every single row needs a distinct positive number of X's and every single column needs a distinct positive number of X's, the fewest-to-most order means you can handle each row in O(1) time, for linear time overall, whereas the most-to-fewest order would mean that each row would take time proportional to the number of X's it needs, for quadratic time overall.)

Overall, this takes no worse than O(r+c+n) time (where n is the number of X's); I think that the optimizations I've listed are enough to ensure that it's closer to O(r+c) time, but it's hard to be 100% sure. I recommend trying it to see if it's fast enough for your purposes.

Title: Arranging the number 1 in a 2d matrix

Body:
Given the number of rows and columns of a 2d matrix

Initially all elements of matrix are 0

Given the number of 1's that should be present in each row

Given the number of 1's that should be present in each column

Determine if it is possible to form such matrix.

Example:

Input: r=3 c=2 (no. of rows and columns)
2 1 0 (number of 1's that should be present in each row respectively)
1 2 (number of 1's that should be present in each column respectively)

Output: Possible

Explanation:

1 1
0 1
0 0

I tried solving this problem for like 12 hours by checking if summation of Ri = summation of Ci

But I wondered if wouldn't be possible for cases like

3 3
1 3 0
0 2 2

r and c can be upto 10^5

Any ideas how should I move further?

Edit: Constraints added and output should only be "possible" or "impossible". The possible matrix need not be displayed.

Can anyone help me now?


问:
flink unit testing - cannot set the context to process all function
assuming that I have this

```<code>class FooProcess extends ProcessAllWindowFunction[String,String, TimeWindow]{
override def process(context: Context, elements: Iterable[String], out: Collector[String]): Unit = ???
}
</code>```

I want to write some unit tests to the process method but I am having issues mocking the context

```<code>val context =  mock[Context[FooProcess]]
</code>```

This import fails (cannot resolve symbol Context)

```<code>import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction.Context
</code>```

Any idea / best practices for unit testing in flink ?

答:
The issue here is that the Context is inner class of the ProcessAllWindowFunction class. In scala inner classes are bound to the outer objects. So, if You want to mock the context and use it to test the process() function then you can do something as below:

```<code>val foo = new FooProcess
val mock = mock[foo.Context]
foo.process(...)
</code>```

Body:
assuming that I have this

class FooProcess extends ProcessAllWindowFunction[String,String, TimeWindow]{
override def process(context: Context, elements: Iterable[String], out: Collector[String]): Unit = ???
}

I want to write some unit tests to the process method but I am having issues mocking the context

val context =  mock[Context[FooProcess]]

This import fails (cannot resolve symbol Context)

import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction.Context

Any idea / best practices for unit testing in flink ?

Body:
The issue here is that the Context is inner class of the ProcessAllWindowFunction class. In scala inner classes are bound to the outer objects. So, if You want to mock the context and use it to test the process() function then you can do something as below:

val foo = new FooProcess
val mock = mock[foo.Context]
foo.process(...)


问:
equivalent to R's `do.call` in python
Is there an equivalent to R's do.call in python?

```<code>do.call(what = 'sum', args = list(1:10)) #[1] 55
do.call(what = 'mean', args = list(1:10)) #[1] 5.5

?do.call
# Description
# do.call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.
</code>```

答:
Goes similar to previous answer, but why so complicated?

```<code>def do_call(what, args=[], kwargs = {}):
    return what(*args, **kwargs)
</code>```

(Which is more elegant than my previously posted definition:)

```<code>def do_call(which, args=None, kwargs = None):
    if args is None and kwargs is not None:
        return which(**kwargs)
    elif args is not None and kwargs is None:
        return which(*args)
    else:
        return which(*args, **kwargs)
</code>```

Python's sum is different than R's sum (1 argument a list expected vs.
arbitraily many arguments expected in R). So we define our own sum (mysum)
which behaves similarly to R's sum. In a similar way we define mymean.

```<code>def mysum(*args):
    return sum(args)

def mymean(*args):
    return sum(args)/len(args)
</code>```

Now we can recreate your example in Python - as a reasonable 1:1 translation of the R function call.

```<code>do_call(what = mymean, args=[1, 2, 3])
## 2.0
do_call(what = mysum, args=[1, 2, 3])
## 6
</code>```

For functions with argument names, we use a dict for kwargs, where the parameter
names are keys of the dictionary (as strings) and their values the values.

```<code>def myfunc(a, b, c):
    return a + b + c

do_call(what = myfunc, kwargs={"a": 1, "b": 2, "c": 3})
## 6

# we can even mix named and unnamed parts
do_call(what = myfunc, args = [1, 2], kwargs={"c": 3})
## 6
</code>```

Title: equivalent to R's `do.call` in python

Body:
Is there an equivalent to R's do.call in python?

do.call(what = 'sum', args = list(1:10)) #[1] 55
do.call(what = 'mean', args = list(1:10)) #[1] 5.5

?do.call
# Description
# do.call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.

Body:
Goes similar to previous answer, but why so complicated?

def do_call(what, args=[], kwargs = {}):
    return what(*args, **kwargs)

(Which is more elegant than my previously posted definition:)

def do_call(which, args=None, kwargs = None):
    if args is None and kwargs is not None:
        return which(**kwargs)
    elif args is not None and kwargs is None:
        return which(*args)
    else:
        return which(*args, **kwargs)

Python's sum is different than R's sum (1 argument a list expected vs.
arbitraily many arguments expected in R). So we define our own sum (mysum)
which behaves similarly to R's sum. In a similar way we define mymean.

def mysum(*args):
    return sum(args)

def mymean(*args):
    return sum(args)/len(args)

Now we can recreate your example in Python - as a reasonable 1:1 translation of the R function call.

do_call(what = mymean, args=[1, 2, 3])
## 2.0
do_call(what = mysum, args=[1, 2, 3])
## 6

For functions with argument names, we use a dict for kwargs, where the parameter
names are keys of the dictionary (as strings) and their values the values.

def myfunc(a, b, c):
    return a + b + c

do_call(what = myfunc, kwargs={"a": 1, "b": 2, "c": 3})
## 6

# we can even mix named and unnamed parts
do_call(what = myfunc, args = [1, 2], kwargs={"c": 3})
## 6


问:
Vue. How to watch localstorage for changes?
Another script (no vue.js) write some data in localstorage, for example array "links". But my vue app see it only after page reload (because localstorage is  not react in vue). How can I watch localstorage for changes and show without reload page?</p>

答:
Local storage isn't really designed for dynamic data that's constantly updating, but lets assume you can't control that.

VueJS only watches data in its components, so you can't use VueJS.

One solution, that isn't pretty is using setInterval (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) that would run every x seconds and get the value from localStorage.

It's not pretty or efficient, bu something like

```<code>let name = 'Bergur'
setInterval(function() {
name = localStorage.getItem('name')
}, 5000)
</code>```

Body:
Local storage isn't really designed for dynamic data that's constantly updating, but lets assume you can't control that.

VueJS only watches data in its components, so you can't use VueJS.

One solution, that isn't pretty is using setInterval (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) that would run every x seconds and get the value from localStorage.

It's not pretty or efficient, bu something like

let name = 'Bergur'
setInterval(function() {
name = localStorage.getItem('name')
}, 5000)


问:
How get correct values from DB in Laravel 5.8
I'm begginer in Laravel. I have this code:

```<code>class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use psCMS\Presenters\UserPresenter;

    public static $roles = [];

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function comments()
    {
        return $this->hasMany('App\Comments');
    }

    public function hasRole(array $roles)
    {

        foreach($roles as $role)
        {

            if(isset(self::$roles[$role]))
            {
                if(self::$roles[$role])  return true;

            }
            else
            {
                self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                if(self::$roles[$role]) return true;
            }

        }
        return false;
    }

}

class Role extends Model
{
    protected $quarded = [];
    public $timestamps = false;

    public function users()
    {
        return $this->belongsToMany('App\User');
    }

}
</code>```

and schema:

```<code>Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });

Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });

Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });
</code>```

And my user:

```<code>DB::table('users')->insert([
            'name' => 'Marian',
            'surname' => 'La',
            'email' => 'marian@icloud.com',
            'email_verified_at' => \Carbon\Carbon::now(),
            'password' => Hash::make('passw'),
        ]);

DB::table('role_user')->insert([
                'user_id' => 1,
                'role_id' => 1,
            ]);
</code>```

This code work fine. I have problem with my role.
How can i print user role in blade?

I make this code:

```<code>public function getAdmin(int $id)
    {
        return User::find($id);
    }

$admin = $this->getAdmin(1);
</code>```

And now my $admin - has admin object.

When i print in blade file: $admin->name, $admin->surname - it's work.

When i print: {{ $admin->roles }}

i have result:

```<code>[{"id":1,"name":"admin","pivot":{"user_id":1,"role_id":1}}]
</code>```

How can I show correct value (admin):

I need result: admin not this:
    [{"id":1,"name":"admin","pivot":{"user_id":1,"role_id":1}}]

答:
That is Many to Many relationship and each user may have many roles ! So use foreach to print all of rules in your blade :

```<code>@foreach ($admin->roles as $role)
  {{ $role -> name }},
@endforeach
</code>```

https://laravel.com/docs/5.8/eloquent-relationships#many-to-many

Hope this helps !

Body:
I'm begginer in Laravel. I have this code:

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;
    use psCMS\Presenters\UserPresenter;

    public static $roles = [];

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function comments()
    {
        return $this->hasMany('App\Comments');
    }

    public function hasRole(array $roles)
    {

        foreach($roles as $role)
        {

            if(isset(self::$roles[$role]))
            {
                if(self::$roles[$role])  return true;

            }
            else
            {
                self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                if(self::$roles[$role]) return true;
            }

        }
        return false;
    }

}

class Role extends Model
{
    protected $quarded = [];
    public $timestamps = false;

    public function users()
    {
        return $this->belongsToMany('App\User');
    }

}

and schema:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->boolean('enable')->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->bigInteger('counter')->default(0);
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
        });

Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });

Schema::create('role_user', function (Blueprint $table) {
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('role_id')->unsigned();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->engine = "InnoDB";
        });

And my user:

DB::table('users')->insert([
            'name' => 'Marian',
            'surname' => 'La',
            'email' => 'marian@icloud.com',
            'email_verified_at' => \Carbon\Carbon::now(),
            'password' => Hash::make('passw'),
        ]);

DB::table('role_user')->insert([
                'user_id' => 1,
                'role_id' => 1,
            ]);

This code work fine. I have problem with my role.
How can i print user role in blade?

I make this code:

public function getAdmin(int $id)
    {
        return User::find($id);
    }

$admin = $this->getAdmin(1);

And now my $admin - has admin object.

When i print in blade file: $admin->name, $admin->surname - it's work.

When i print: {{ $admin->roles }}

i have result:

[{"id":1,"name":"admin","pivot":{"user_id":1,"role_id":1}}]

How can I show correct value (admin):

I need result: admin not this:
    [{"id":1,"name":"admin","pivot":{"user_id":1,"role_id":1}}]

Body:
That is Many to Many relationship and each user may have many roles ! So use foreach to print all of rules in your blade :

@foreach ($admin->roles as $role)
  {{ $role -> name }},
@endforeach

https://laravel.com/docs/5.8/eloquent-relationships#many-to-many

Hope this helps !


问:
NHibernate, SQL Server - enum to int mapping
I have a class that has an enum type indicating whether the message type is Email or Sms. The enum type is defined:

```<code>public enum ReminderType
{
    Email = 1,
    Sms = 2
}
</code>```

The class that utilizes this type looks like:

```<code>public class Reminder : EntityBase
{
    public virtual string Origin { get; set; }
    public virtual string Recipient { get; set; }
    public virtual ReminderType Type { get; set; }
    public virtual Business Business { get; set; }
    public virtual DateTime Created { get; set; }

    public Reminder()
    {
        Created = DateTime.UtcNow;
    }
}
</code>```

When I try to persist an entity of type Reminder to the database however, I get the following error:

```<code>System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value 'Email' to data type int.
</code>```

The backing field is of type int, so I'm not sure why NHibernate is trying to map the string representation by default. I'm using Fluent NHibernate, and the relevant mapping code is:

```<code>mappings.Override<Reminder>(map =>
{
     map.Map(x => x.Type).Column("Type")
});
</code>```

I'm pretty sure the default behavior of NHibernate is to map enums as ints, so why is it not doing so in this case? I'm using SQL Server 2005, if that matters.

答:
You should never map Enum as int in NHibernate. It becomes a reason of having a ghost updates.

The best way to it is just not setting a type property in XML mappings. To achieve that in Fluent NHibernate you can use .CustomType(string.Empty).

Some additional info you can find here.

Body:
I have a class that has an enum type indicating whether the message type is Email or Sms. The enum type is defined:

public enum ReminderType
{
    Email = 1,
    Sms = 2
}

The class that utilizes this type looks like:

public class Reminder : EntityBase
{
    public virtual string Origin { get; set; }
    public virtual string Recipient { get; set; }
    public virtual ReminderType Type { get; set; }
    public virtual Business Business { get; set; }
    public virtual DateTime Created { get; set; }

    public Reminder()
    {
        Created = DateTime.UtcNow;
    }
}

When I try to persist an entity of type Reminder to the database however, I get the following error:

System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value 'Email' to data type int.

The backing field is of type int, so I'm not sure why NHibernate is trying to map the string representation by default. I'm using Fluent NHibernate, and the relevant mapping code is:

mappings.Override<Reminder>(map =>
{
     map.Map(x => x.Type).Column("Type")
});

I'm pretty sure the default behavior of NHibernate is to map enums as ints, so why is it not doing so in this case? I'm using SQL Server 2005, if that matters.


问:
Calling DialogFragment in Fragment Kotlin
I'm trying to call my dialogfragment into my loginfragment and show an alert dialog box, the show method says that:

None of the following functions can be called with the arguments
  supplied. show(FragmentManager!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment
  show(FragmentTransaction!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment

```<code>val newFragment = CustomDialogFragment.newInstance("pass content here")

val fm = fragmentManager
newFragment.show(fm, "look")
</code>```

Here is my CustomDialogFragment code:

```<code>import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenstand.android.TreeTracker.R
import org.greenstand.android.TreeTracker.application.Permissions
import org.greenstand.android.TreeTracker.utilities.*
import org.greenstand.android.TreeTracker.viewmodels.LoginViewModel
import org.koin.android.viewmodel.ext.android.viewModel
import timber.log.Timber
class CustomDialogFragment : DialogFragment()
{
    private var content: String? = null

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        content = arguments!!.getString("content")

        val style = DialogFragment.STYLE_NO_FRAME
        val theme = R.style.DialogTheme
        setStyle(style, theme)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle): View
    {
        val view = inflater!!.inflate(R.layout.layout_dialog, container, false)

        val btnAccept = view.findViewById<View>(R.id.buttonAccept) as Button

        val textViewContent = view.findViewById<View>(R.id.textViewContent) as TextView
        textViewContent.text = content;

        btnAccept.setOnClickListener{
            dismiss();
        }

        return view;
    }

    companion object
    {
        fun newInstance(content: String) : CustomDialogFragment
        {
            val f = CustomDialogFragment()

            val args = Bundle()
            args.putString("content", content)
            f.arguments = args

            return f
        }
    }

}
</code>```

Can someone indicate what exactly I need to pass into the show method? Any help is appreciated, thanks :)

答:
Make sure that your activity is a child of https://developer.android.com/reference/androidx/fragment/app/FragmentActivity.html, for example you can use https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity as a parent activity.

Then to get the fragmentManager use the getSupportFragment() method, or just val fm = supportFragmentManager

Body:
I'm trying to call my dialogfragment into my loginfragment and show an alert dialog box, the show method says that:

None of the following functions can be called with the arguments
  supplied. show(FragmentManager!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment
  show(FragmentTransaction!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment

val newFragment = CustomDialogFragment.newInstance("pass content here")

val fm = fragmentManager
newFragment.show(fm, "look")

Here is my CustomDialogFragment code:

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenstand.android.TreeTracker.R
import org.greenstand.android.TreeTracker.application.Permissions
import org.greenstand.android.TreeTracker.utilities.*
import org.greenstand.android.TreeTracker.viewmodels.LoginViewModel
import org.koin.android.viewmodel.ext.android.viewModel
import timber.log.Timber
class CustomDialogFragment : DialogFragment()
{
    private var content: String? = null

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        content = arguments!!.getString("content")

        val style = DialogFragment.STYLE_NO_FRAME
        val theme = R.style.DialogTheme
        setStyle(style, theme)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle): View
    {
        val view = inflater!!.inflate(R.layout.layout_dialog, container, false)

        val btnAccept = view.findViewById<View>(R.id.buttonAccept) as Button

        val textViewContent = view.findViewById<View>(R.id.textViewContent) as TextView
        textViewContent.text = content;

        btnAccept.setOnClickListener{
            dismiss();
        }

        return view;
    }

    companion object
    {
        fun newInstance(content: String) : CustomDialogFragment
        {
            val f = CustomDialogFragment()

            val args = Bundle()
            args.putString("content", content)
            f.arguments = args

            return f
        }
    }

}

Can someone indicate what exactly I need to pass into the show method? Any help is appreciated, thanks :)


问:
How to connect InputMethodService with a Service?
I want to connect my custom Softkeyboard, which is expanding the InputMethodService, with another Service. I need to call a method in my Softkeyboard from a generic Service.

The problem is that i can not extend the Binder class because the method onBind() is defined final in the AbstractInputMethodService...

now, how can I call a method in my SoftKeyboard class from other service ?

答:
I've solved this by using a broadcast receiver class.

```<code>    class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("GET_KEY_KEY")) {
            String msg = intent.getStringExtra("msg");
                InputConnection ic = getCurrentInputConnection();
                if (ic != null) {
                    ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
                }
        }

    }
}
</code>```

then I sent a broadcast to my service.

```<code>                Intent intent = new Intent();
            intent.setAction("GET_KEY_KEY");
            sendBroadcast(intent);
</code>```

Body:
I've solved this by using a broadcast receiver class.

    class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("GET_KEY_KEY")) {
            String msg = intent.getStringExtra("msg");
                InputConnection ic = getCurrentInputConnection();
                if (ic != null) {
                    ic.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
                }
        }

    }
}

then I sent a broadcast to my service.

                Intent intent = new Intent();
            intent.setAction("GET_KEY_KEY");
            sendBroadcast(intent);


答:
If you want to see changes in local storage that are made outside your influence, you can poll it.

data() {
    return {
      lastChange: null,
      timer: null
    }
  },
  created() {
    let curVal = localStorage.getItem('foo');
    this.lastChange = new Date()
    this.timer = setInterval(() => {
      const newVal = localStorage.getItem('foo');
      if (newVal !== curVal) {
        curVal = newVal;
        // fireEvent, update state, etc
        // or update data in your component
        this.lastChange = new Date()
      }
    }, 1000);
  },
  beforeDestroy() {
    cleaInterval(this.timer)
  }```

Title: Vue. How to watch localstorage for changes?

Body: Another script (no vue.js) write some data in localstorage, for example array "links". But my vue app see it only after page reload (because localstorage is  not react in vue). How can I watch localstorage for changes and show without reload page?


问:
How to create many-to-many relationship in Express?
I'm writing a small API using Express and TypeScript. I have a POST request and a GET request. With POST request I get in a list of organizations, who might have daughter organizations, and the daughters might also have daughters, etc.

Im thinking of creating 2 db tables in postgreSQL. Organization and Parent_child.

```<code>Organization{
   id: number,
   name: string
}

Parent_child{
    parent_id: number,
    child_id: number
}
</code>```

I'd like to create many-to-many relation from Organization to Organization through Parent_child. I have spend hours to understand how to use DB and most tutorials are vague at best.

Any suggestions on how to do it or what module to use for this? I have read about sequelize and typeORM but tutorials and manuals for them don't help me much.

答: Go through the well detailed steps to have sequelize hook up to your Postgres instance, then define your models like they do in the docs... make sure you pay strict attention to setting up the associations in your models.. the belongsToMany was a bit tricky when I first tried it but if you have an trouble then post back here and I’ll show you where you may have gone wrong </p>

Body:
I'm writing a small API using Express and TypeScript. I have a POST request and a GET request. With POST request I get in a list of organizations, who might have daughter organizations, and the daughters might also have daughters, etc.

Im thinking of creating 2 db tables in postgreSQL. Organization and Parent_child.

Organization{
   id: number,
   name: string
}

Parent_child{
    parent_id: number,
    child_id: number
}

I'd like to create many-to-many relation from Organization to Organization through Parent_child. I have spend hours to understand how to use DB and most tutorials are vague at best.

Any suggestions on how to do it or what module to use for this? I have read about sequelize and typeORM but tutorials and manuals for them don't help me much.


问:
Using JQuery to call a WebMethod
I am having trouble getting inside my Search WebMethod from my JQuery call.
Maybe someone could help to point me in the right direction.

I also packed up everything into a zip file incase someone wants to check it out for a closer look.

http://www.filedropper.com/jsonexample

Thanks
Ryan

```<code>    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>JSON Example</title>
    <script type="text/javascript" language="JavaScript" src="jquery-1.3.1.min.js"></script>

<script type="text/javascript" language="javascript">

function Search() {
    var search = $("#searchbox").val();
    var options = {
        type: "POST",
        url: "Default.aspx/Search",
        data: "{text:" + search + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            alert('Success!');
        }
    };
    $.ajax(options);
}
</script>

</head>
<body>
    <form id="form1" runat="server">
        <input type="text" id="searchbox" size="40" />
        <a href="#" onclick="Search()" id="goSearch">Search</a>
        <br />
        <div id="Load" />
    </form>
</body>
</html>
</code>```

And here is the code behind for the default.aspx

```<code> Imports System.Data
    Imports System.Web.Services
    Imports System.Web.Script.Serialization

    Partial Class _Default
        Inherits System.Web.UI.Page

        <WebMethod()> _
        Public Shared Function Search(ByVal text As String) As IEnumerable
            Return "test"
        End Function

    End Class
</code>```

答:
You need to do the following (C#):

The WebMethod must be public static

It must be decorated with the [WebMethod] attribute

You need a ScriptManager on your .aspx page

Set the ScriptManager's EnablePageMethods="true"

And here is some sample javascript:

```<code>$().ready(function() {
    $(yourDropDownList).change(LoadValues);
});

function LoadValues() {
    PageMethods.YourMethod(arg1, CallSuccess, CallFailed);
}

function CallFailed(result) {
    alert('AJAX Error:' + result.get_message());
}

function CallSuccess(result) {
    //do whatever you need with the result
}
</code>```

OwnerDisplayName: Ryan

LastEditorDisplayName: CQ

ContentLicense: CC BY-SA 2.5

Title: Using JQuery to call a WebMethod

Body:
I am having trouble getting inside my Search WebMethod from my JQuery call.
Maybe someone could help to point me in the right direction.

I also packed up everything into a zip file incase someone wants to check it out for a closer look.

http://www.filedropper.com/jsonexample

Thanks
Ryan

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>JSON Example</title>

    <form id="form1" runat="server">
        <input type="text" id="searchbox" size="40" />
        Search

    </form>

And here is the code behind for the default.aspx

 Imports System.Data
    Imports System.Web.Services
    Imports System.Web.Script.Serialization

    Partial Class _Default
        Inherits System.Web.UI.Page

        <WebMethod()> _
        Public Shared Function Search(ByVal text As String) As IEnumerable
            Return "test"
        End Function

    End Class

Body:
You need to do the following (C#):

The WebMethod must be public static

It must be decorated with the [WebMethod] attribute

You need a ScriptManager on your .aspx page

Set the ScriptManager's EnablePageMethods="true"

And here is some sample javascript:

$().ready(function() {
    $(yourDropDownList).change(LoadValues);
});

function LoadValues() {
    PageMethods.YourMethod(arg1, CallSuccess, CallFailed);
}

function CallFailed(result) {
    alert('AJAX Error:' + result.get_message());
}

function CallSuccess(result) {
    //do whatever you need with the result
}

OwnerDisplayName: flesh


问:
to draw graph with mysql data
I need to draw a line graph with mysql data which has two columns. some one help me with a sample code.</p>

答: Have you tried looking at JFreeChart?</p>

Title: to draw graph with mysql data

Body: Have you tried looking at JFreeChart?


问:
Mongo - Merge Duplicate Entries In A Collection And Remove Old Entries
I'm trying to migrate an old database that reads from millions of CSV files to Mongodb. The old database has millions of entries and essentially what I want is for the new database to have these three fields - Contact Name, Email & Contact Numbers. I will be reading this information in from hundreds of different CSV files with various formats. I have written a python script that will extract the information from these files and put them in a new csv file in the following layout:

Email:Name:Contact_No

The issue that I am having is that some of these emails are present in multiple CSV files and may have multiple different contact numbers. When I import these CSV files using the mongoimport command there may be multiple entries for the same email.

I am trying to create one entry in the master collection that will be formatted as follows:

{
  Email:samplemail@xxx.com
  Name: John Doe
  Phone: [
           12345678,
           23456789,
           12354677,
         ]

}```
</div>
</div>
</p>

<p>I am quiet new to Mongo so I was hoping someone with a bit more insight and experience would be able to suggest an alternative solution to my current implementation. </p>

<p>*********************  CURRENT IMPLEMENTATION *************************</p>

<p>At the moment I import the CSV files to the Database by following these 4 steps.</p>

<ol>
<li>Import the database using the mongo import command</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>mongoimport -d Master_Contacts -c Master_Collection --type csv --file '/root/Documents/log.csv' --columnsHaveTypes --fields "Email.string(),Name.string(),Number.string()" --numInsertionWorkers 8</code>```

This appears to work fine. I can import approximately 1.6 million entries in about 2 mins with only 8GB of ram allocated.

Remove Duplicates

My current implementation of removing duplicates is as follows. I use the aggregate function to find multiple entries for the same email-> find all entries with that email and associated numbers and then output these to a new collection called duplicates using the following command:

db.Master_Collection.aggregate([{$group: {_id: {email:"$email"},count: { "$sum":1 },number:{$addToSet:"$number"}}},{ $match: {count: { "$gt": 1 }}}, {$out:"duplicates"}],{allowDiskUse:true})```
</div>
</div>
</p>

<p>I am then removing these results from the original collection using the following command:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>db.Master_Collection.aggregate([{$group: {_id: {email:"$email"},count: { "$sum":1 },number:{$addToSet:"$number"}}},{ $match: {count: { "$gt": 1 }}}],{allowDiskUse:true}).forEach(function(doc){print(db.Master_Collection.remove({"email":doc._id.email}))});</code>```

Insert All Entries in Duplicate Collection Back Into Original Collection

I then again loop over the duplicates collection and insert all the entries into the master collection. However this seems to be highly inefficient and time consuming.

Would anyone please be able to provide suggestions or alternative solution.

Thanks in advance guys

答:
I suggest that you aggregate the duplicates prior to insert into the destination table. You could do this in your Python script by, in memory preferably, collecting the duplicate contact info and storing it in the appropriate entry in a dictionary.

Then bulk insert your dictionary.

These fewer steps and fewer I/O operations should give you want you want with better performance.

Body:
I'm trying to migrate an old database that reads from millions of CSV files to Mongodb. The old database has millions of entries and essentially what I want is for the new database to have these three fields - Contact Name, Email & Contact Numbers. I will be reading this information in from hundreds of different CSV files with various formats. I have written a python script that will extract the information from these files and put them in a new csv file in the following layout:

Email:Name:Contact_No

The issue that I am having is that some of these emails are present in multiple CSV files and may have multiple different contact numbers. When I import these CSV files using the mongoimport command there may be multiple entries for the same email.

I am trying to create one entry in the master collection that will be formatted as follows:

{
  Email:samplemail@xxx.com
  Name: John Doe
  Phone: [
           12345678,
           23456789,
           12354677,
         ]

}

I am quiet new to Mongo so I was hoping someone with a bit more insight and experience would be able to suggest an alternative solution to my current implementation.

*********************  CURRENT IMPLEMENTATION *************************

At the moment I import the CSV files to the Database by following these 4 steps.

Import the database using the mongo import command

mongoimport -d Master_Contacts -c Master_Collection --type csv --file '/root/Documents/log.csv' --columnsHaveTypes --fields "Email.string(),Name.string(),Number.string()" --numInsertionWorkers 8

This appears to work fine. I can import approximately 1.6 million entries in about 2 mins with only 8GB of ram allocated.

Remove Duplicates

My current implementation of removing duplicates is as follows. I use the aggregate function to find multiple entries for the same email-> find all entries with that email and associated numbers and then output these to a new collection called duplicates using the following command:

db.Master_Collection.aggregate([{$group: {_id: {email:"$email"},count: { "$sum":1 },number:{$addToSet:"$number"}}},{ $match: {count: { "$gt": 1 }}}, {$out:"duplicates"}],{allowDiskUse:true})

I am then removing these results from the original collection using the following command:

db.Master_Collection.aggregate([{$group: {_id: {email:"$email"},count: { "$sum":1 },number:{$addToSet:"$number"}}},{ $match: {count: { "$gt": 1 }}}],{allowDiskUse:true}).forEach(function(doc){print(db.Master_Collection.remove({"email":doc._id.email}))});

Insert All Entries in Duplicate Collection Back Into Original Collection

I then again loop over the duplicates collection and insert all the entries into the master collection. However this seems to be highly inefficient and time consuming.

Would anyone please be able to provide suggestions or alternative solution.

Thanks in advance guys


问:
How to handle lighting in orthographic projection in modern opengl?
I had been doing lighting calculation in fragment shader in eye space coordinate for perspective projections ( both vertex shaders and fragment shaders are attached) and it had been working out fine.

But when the same shaders are used with orthographic projection or(FOV) Field of view is reduced in perspective projection (10-degree FOV) then it does not work well. Shading becomes weird.

So far my understanding is that calculation of eye coordinate derivative becomes pointless in the fragemt shader because of the way orthographic projections works and the derivative of eye coordinate position is always zero except on edges ( correct me if I am wrong here as I have limited experience of working with computer graphics and OpenGL).
I am nor able to figure out How to do it correctly. It would be great if someone could point me to correct source of information.

Vertex Shader

```<code>#version 330 core
layout (location = 0) in vec3 vertex_position;

uniform mat4 transform_matrix;
uniform mat4 view_matrix;
uniform mat4 model_matrix;
out vec3 ec_pos;
void main()
{
 gl_Position = (view_matrix*transform_matrix*model_matrix*vec4(vertex_position, 1.0));
    ec_pos = gl_Position.xyz;
}
</code>```

Fragment Shader

```<code>#version 330 core
out vec4 FragColor;
uniform vec3 objectColor;
in vec3 ec_pos;
void main()
{
    vec3 lightColor = vec3(0.99,0.96,0.89);
    vec3 lightPos = vec3(0,0,0,1);
    vec3 ec_normal = normalize(cross(dFdx(ec_pos), dFdy(ec_pos)));
    float diff = max(dot(ec_normal, lightPos), 0.0);
    vec3 diffuse =  diff * lightColor;
    vec3 result =  diffuse  * objectColor;
    FragColor = vec4(result, 1.0);
}
</code>```

答:
I have solved my own problem by doing the calculation in the camera coordinate space ( i.e, just before applying projection transformation). Here is the correct code:

Vertex Shader:

```<code>void main()
{
    vec4 mcPos = model_matrix*vec4(vertex_position, 1.0);
    vec4 wcPos = transform_matrix*vec4(mcPos);
    gl_Position = view_matrix*wcPos;
    mc_pos = mcPos.xyz;
    wc_pos = wcPos.xyz;
}
</code>```

Fragment Shader:

```<code>#version 330 core
out vec4 FragColor;
uniform vec3 objectColor;
in vec3 mc_pos;
in vec3 wc_pos;
void main()
{
    vec3 lightColor = vec3(0.99,0.96,0.89);
    vec3 lightPos = vec3(0,0,1);
    vec3 wc_normal = normalize(cross(dFdx(wc_pos), dFdy(wc_pos)));
    float diff = max(dot(wc_normal, lightPos), 0.0);
    vec3 diffuse = (diff) * lightColor;
    vec3 result = ( diffuse ) * objectColor;
    FragColor = vec4(result, 1.0);
}
</code>```

Correct shading

Body:
I had been doing lighting calculation in fragment shader in eye space coordinate for perspective projections ( both vertex shaders and fragment shaders are attached) and it had been working out fine.

But when the same shaders are used with orthographic projection or(FOV) Field of view is reduced in perspective projection (10-degree FOV) then it does not work well. Shading becomes weird.

So far my understanding is that calculation of eye coordinate derivative becomes pointless in the fragemt shader because of the way orthographic projections works and the derivative of eye coordinate position is always zero except on edges ( correct me if I am wrong here as I have limited experience of working with computer graphics and OpenGL).
I am nor able to figure out How to do it correctly. It would be great if someone could point me to correct source of information.

Vertex Shader

#version 330 core
layout (location = 0) in vec3 vertex_position;

uniform mat4 transform_matrix;
uniform mat4 view_matrix;
uniform mat4 model_matrix;
out vec3 ec_pos;
void main()
{
 gl_Position = (view_matrix*transform_matrix*model_matrix*vec4(vertex_position, 1.0));
    ec_pos = gl_Position.xyz;
}

Fragment Shader

#version 330 core
out vec4 FragColor;
uniform vec3 objectColor;
in vec3 ec_pos;
void main()
{
    vec3 lightColor = vec3(0.99,0.96,0.89);
    vec3 lightPos = vec3(0,0,0,1);
    vec3 ec_normal = normalize(cross(dFdx(ec_pos), dFdy(ec_pos)));
    float diff = max(dot(ec_normal, lightPos), 0.0);
    vec3 diffuse =  diff * lightColor;
    vec3 result =  diffuse  * objectColor;
    FragColor = vec4(result, 1.0);
}

Body:
I have solved my own problem by doing the calculation in the camera coordinate space ( i.e, just before applying projection transformation). Here is the correct code:

Vertex Shader:

void main()
{
    vec4 mcPos = model_matrix*vec4(vertex_position, 1.0);
    vec4 wcPos = transform_matrix*vec4(mcPos);
    gl_Position = view_matrix*wcPos;
    mc_pos = mcPos.xyz;
    wc_pos = wcPos.xyz;
}

Fragment Shader:

#version 330 core
out vec4 FragColor;
uniform vec3 objectColor;
in vec3 mc_pos;
in vec3 wc_pos;
void main()
{
    vec3 lightColor = vec3(0.99,0.96,0.89);
    vec3 lightPos = vec3(0,0,1);
    vec3 wc_normal = normalize(cross(dFdx(wc_pos), dFdy(wc_pos)));
    float diff = max(dot(wc_normal, lightPos), 0.0);
    vec3 diffuse = (diff) * lightColor;
    vec3 result = ( diffuse ) * objectColor;
    FragColor = vec4(result, 1.0);
}

Correct shading


问:
How can i place a newly generated pagination link data into a new div element
please i need some help on how i can append a pagination link data to the current page.

Lets say i have the following pagination links: [1][2][3] and i am currently on the page http://127.0.0.1/link?page1

I want it to be that when i click [2] the data from [2] is appended to the current page and when i click [3] the data from [3] is also append to the current page without any of the data on the current page changing.

I would also like it not to load any specific loaded page twice.

Here is what i have tried:

```<code>$(document).on('click', '.pagination a', function(e) {
    e.preventDefault();

    var page = $(this).attr('href');
    getOffersPage(page);

    function getOffersPage(page) {
        if (page === page) {
            var resultSection = $('#new-result');
            $('.appended-data').load(page + ' #new-result', function() {
                $('#paginated-links').addClass('text-right x1-margin-top');
            });
        }
    }
});
</code>```

答:
So here's an example how to generate elements from data using Vue JS. As you can see, the snippet simply generates a paragraph for each number in an array containing the numbers 1 to 20. We have two buttons to lazily load more respectively less content.

A major benefit of using Vue (or React, or Angular) is that the reactivity meachanism makes sure that changes to the model (in this case changes to page upon pressing more or less) are detected and trigger re-rendering.

const items = []
for (i = 1; i <= 20; i++) {
  items[i - 1] = i
}

new Vue({
  el: '#lazy-load-example',
  data: {
    items,
    page: 1,
    pageSize: 5,
  },
  methods: {
    itemsForPage() {
      const N = this.page * this.pageSize
      return this.items.slice(0, Math.min(N, this.items.length))
    },
    onMore() {
      const N = this.Page * this.pageSize
      if (this.hasMore()) {
        this.page++
      }
    },
    onLess() {
      if (this.page > 1) {
        this.page--
      }
    },
    hasMore() {
      return this.page < this.items.length / this.pageSize;
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<style>
    .as-console-wrapper { display: none !important; }
</style>

<div class="card d-flex flex-column" id="lazy-load-example">
  <div class="card-body d-flex flex-column justify-content-between">
    <h2 class="card-title">Lazy Load Example</h2>
    <div class="col-12"><p v-for="item in itemsForPage()" class="col-3">item: {{ item }} </p></div>
  </div>
  <div class="card-footer d-flex">
    <div class="mr-2"><button class="btn btn-primary" :disabled="page === 1"  v-on:click="onLess">Less</button></div>
    <div><button class="btn btn-primary" :disabled="!hasMore()"  v-on:click="onMore">More</button></div>
  </div>
</div></code>```

Body:
please i need some help on how i can append a pagination link data to the current page.

Lets say i have the following pagination links: [1][2][3] and i am currently on the page http://127.0.0.1/link?page1

I want it to be that when i click [2] the data from [2] is appended to the current page and when i click [3] the data from [3] is also append to the current page without any of the data on the current page changing.

I would also like it not to load any specific loaded page twice.

Here is what i have tried:

$(document).on('click', '.pagination a', function(e) {
    e.preventDefault();

    var page = $(this).attr('href');
    getOffersPage(page);

    function getOffersPage(page) {
        if (page === page) {
            var resultSection = $('#new-result');
            $('.appended-data').load(page + ' #new-result', function() {
                $('#paginated-links').addClass('text-right x1-margin-top');
            });
        }
    }
});

Body:
So here's an example how to generate elements from data using Vue JS. As you can see, the snippet simply generates a paragraph for each number in an array containing the numbers 1 to 20. We have two buttons to lazily load more respectively less content.

A major benefit of using Vue (or React, or Angular) is that the reactivity meachanism makes sure that changes to the model (in this case changes to page upon pressing more or less) are detected and trigger re-rendering.

const items = []
for (i = 1; i <= 20; i++) {
  items[i - 1] = i
}

new Vue({
  el: '#lazy-load-example',
  data: {
    items,
    page: 1,
    pageSize: 5,
  },
  methods: {
    itemsForPage() {
      const N = this.page * this.pageSize
      return this.items.slice(0, Math.min(N, this.items.length))
    },
    onMore() {
      const N = this.Page * this.pageSize
      if (this.hasMore()) {
        this.page++
      }
    },
    onLess() {
      if (this.page > 1) {
        this.page--
      }
    },
    hasMore() {
      return this.page < this.items.length / this.pageSize;
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<style>
    .as-console-wrapper { display: none !important; }
</style>

<div class="card d-flex flex-column" id="lazy-load-example">
  <div class="card-body d-flex flex-column justify-content-between">
    <h2 class="card-title">Lazy Load Example</h2>
    <div class="col-12"><p v-for="item in itemsForPage()" class="col-3">item: {{ item }} </p></div>
  </div>
  <div class="card-footer d-flex">
    <div class="mr-2"><button class="btn btn-primary" :disabled="page === 1"  v-on:click="onLess">Less</button></div>
    <div><button class="btn btn-primary" :disabled="!hasMore()"  v-on:click="onMore">More</button></div>
  </div>
</div>


答:
InnoDB's B+Tree secondary indexes don't get formed that way.  Think of it this way:

For each row, construct a string composed of Program,Parameter,PK.

Sort those strings.

Lay them out in a BTree.

Note:  There was no hint of splitting up by Program.  What if 99.9% of the Programs were in Program #5?  That would be a rather unbalanced BTree.  Handy for your one rare query, but slower for the majority of other queries.

With the nicely balanced B+Tree, your query must:

Drill down the BTree to find the first 'row' for Program = 'MyProgram'

Walk forward through the leaf nodes of the B+Tree, using the "+" to step from one leaf block to the next.

While walking, keep track of each new Parameter.

Quit when Program = 'MyProgram' fails.

Notes:

DISTINCT was easily implemented in my step 3 by understanding how the items are ordered.

"Using index" says that the index was "covering" -- since you only needed Program and Parameter (and those were the columns in the INDEX).  The PK is also implicitly available for "covering".

The 15 that you provided disagrees with the cardinaliity of "4676".  But that just points out that the statistics are sometimes quite far off.  (Statistics has no impact on optimization of this query.)

I considered having one table with unique triples (Date, Program, Parameter)

Yes, having such a table would make your query run much faster.  But is it worth the maintenance of such?

Another thing that table would let you do is to normalize out those 3 columns into a single MEDIUMINT UNSIGNED (only 3 bytes) instead of perhaps 30 bytes now being used on the average row.  Again, would the complexity of the JOINs, etc, outweigh the benifit?  It would shrink the disk footprint by perhaps 50%.

Title: Why isn't SELECT DISTINCT on an indexed column instantaneous?

Body:
I have a table like this that stores configurations of various programs that are run.  It looks something like this:

+--------------+---------------+------+-----+---------+-------+
| Field        | Type          | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| Date         | date          | YES  | MUL | NULL    |       |
| Program      | varchar(20)   | YES  | MUL | NULL    |       |
| ConfigFile   | int(11)       | YES  |     | NULL    |       |
| Parameter    | varchar(20)   | YES  |     | NULL    |       |
| Value        | varchar(20)   | YES  |     | NULL    |       |
+--------------+---------------+------+-----+---------+-------+

The ConfigFile field contains the number of the config file -- for some of the programs there is more than one config file that can be chosen.

It has a couple of indices, like so:

+-------+------------+----------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name  | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| lists |          1 | Date     |            1 | Date         | A         |     1108060 |     NULL | NULL   | YES  | BTREE      |         |               |
| lists |          1 | Date     |            2 | Program      | A         |     1108060 |     NULL | NULL   | YES  | BTREE      |         |               |
| lists |          1 | Date     |            3 | Parameter    | A         |     1108060 |     NULL | NULL   | YES  | BTREE      |         |               |
| lists |          1 | Program  |            1 | Program      | A         |        4676 |     NULL | NULL   | YES  | BTREE      |         |               |
| lists |          1 | Program  |            2 | Parameter    | A         |      183706 |     NULL | NULL   | YES  | BTREE      |         |               |
+-------+------------+----------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

Now let's say I want to know what the parameters for a given program are.  It seems like I should be able to do something like this:

SELECT DISTINCT Parameter FROM params WHERE Program = 'MyProgram';

This has the following explain plan:

+----+-------------+--------+------------+------+----------------+---------+---------+-------+-----------+----------+--------------------------+
| id | select_type | table  | partitions | type | possible_keys  | key     | key_len | ref   | rows      | filtered | Extra                    |
+----+-------------+--------+------------+------+----------------+---------+---------+-------+-----------+----------+--------------------------+
|  1 | SIMPLE      | params | NULL       | ref  | Date,Program   | Program | 23      | const | 137203382 |   100.00 | Using where; Using index |
+----+-------------+--------+------------+------+----------------+---------+---------+-------+-----------+----------+--------------------------+

There are something like 15 different choices for Program, and maybe between 10 and 100 values of Parameter for each program.

With my understanding of how a database index works, I'd expect this to complete instantaneously.  In particular, I'd expect the underlying data structure to be a binary search tree with 15 nodes, which I search to find the one corresponding to my program; after finding my program, it takes me to second binary search tree with perhaps 100 nodes or fewer, which I'd then simply traverse.

When I actually run the query, though, it winds up taking several minutes.

To me this suggests that there are perhaps multiple copies of the same value in the binary search tree, one per node of the table.  Is this what's happening, and, if so, what can I do to mitigate this situation?

I considered having one table with unique triples (Date, Program, Parameter) and having a relation, but I'm not sure how to perform a bulk insert of the data in this situation.  And if I'm wrong about why it's so slow then of course this wouldn't even help.


问:
Genymotion 3.0 trial version showing Black Screen on Windows 10
My Genymotion is showing black screen i have try all the methode of configuration by configuring correctly my virtual box adapter so i don't know what's wrong again.

答:
You need to check 4 different things:

proxy connections to be off( Gennymotion/setting/Network)

SDK be set( Gennymotion/ABD/SDK)

Graphic card driver be successfully installed

Virtual box installed and working correctly

Try again please. hope you will fix it easily.


问:
How to import modules given a list of their names?
I am trying to import modules from a list. This would be to allow easier editing of imported modules, cleaner error message, and better error handling. Here is basically what I am trying to do:

```<code>imports = ['sys', 'itertools', 'datetime', 'os']
for x in imports:
    try:
        import x
        print "Successfully imported ", x, '.'
    except ImportError:
        print "Error importing ", x, '.'
</code>```

The issue here is that it tries importing x, not the value x should hold. I realize that to import from the list I could do something like below, but I do not see a way to handle the errors with it:

```<code>imports = ['sys', 'itertools', 'datetime', 'os']
modules = map(__import__, imports)
</code>```

Is there a way to integrate the error handling with this method or should I try a different approach?

答:
you can import programatically achieving the same effect as import module as module_shortname by using globals():

```<code>packages_to_import = [{'name': 'numpy', 'as': 'np'},
                      {'name': 'pandas', 'as': 'pd'}]

for package in packages_to_import:
    package_name = package['name']
    import_as = package.get('as', package_name)

    globals()[import_as] = __import__(package_name)

print(np.version.full_version)
print(pd.__version__)
</code>```

Body:
I am trying to import modules from a list. This would be to allow easier editing of imported modules, cleaner error message, and better error handling. Here is basically what I am trying to do:

imports = ['sys', 'itertools', 'datetime', 'os']
for x in imports:
    try:
        import x
        print "Successfully imported ", x, '.'
    except ImportError:
        print "Error importing ", x, '.'

The issue here is that it tries importing x, not the value x should hold. I realize that to import from the list I could do something like below, but I do not see a way to handle the errors with it:

imports = ['sys', 'itertools', 'datetime', 'os']
modules = map(__import__, imports)

Is there a way to integrate the error handling with this method or should I try a different approach?

Body:
you can import programatically achieving the same effect as import module as module_shortname by using globals():

packages_to_import = [{'name': 'numpy', 'as': 'np'},
                      {'name': 'pandas', 'as': 'pd'}]

for package in packages_to_import:
    package_name = package['name']
    import_as = package.get('as', package_name)

    globals()[import_as] = __import__(package_name)

print(np.version.full_version)
print(pd.__version__)


问:
Errors in HTML - red ending paragraph tags
This is my first webpage, and the end paragraph tags are red.

Can someone tell me what I have done wrong, please?

This is my code. It was working fine, but when I have tried to add some CSS to it, it started displaying my text in a weird way, so I assume it must have some errors in my code.

Engagement Pro

Frequently Asked Questions

Below you will find answers to the questions we get asked the most about Engagement Pro.

        Managers

Why can't log in?

A lead came through with no contact details, how do I remove it?

I have added a comment to an unlogged lead, why is it not excluded?

A guest enquired twice, but when I created the enquiry it didn't link to the other one.

Where do I find leads that are being added in my diary by reception?

        Sales associates

Why can't log in?

Why doesn't the 'Export to Pinnacle' button work?

Why do I have guests I know nothing about in my diary?

Is there an easier way to see my diary for today, other han changing the date range?

When adding an appointment, it doesn't show in my appointments diary

Why are the postcodes highlighted yellow or green sometimes?

        </ul

          Product geniuses

Why can't log in?

Why does my video have so little views?

Why can I not save a video?

For any other questions/suggestions please contact Steven Harris or Andreea Mitel.

```

答:
You must note that
 is not allowed within a
 element.

Body: You must note that <ul> is not allowed within a <p> element.


问:
How to convert fixed margins in percent?
Here is a wrapper div with 450 px. If I set the height to 100vh, then the bottom margin of the title should adapt to the viewport.

.title,
.subtitle {
  border: 1px solid #000;
}

.wrapper {
  display: flex;
  flex-direction: column;
  width: 16%;
  height: 450px;
  margin-right: 42%;
  margin-left: 42%;
  border: 1px solid #000;
}

.title {
  margin-bottom: 1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="title">Title</div>
  <div class="subtitle">Subtitle</div>
</div></code>```

https://codepen.io/anon/pen/ZNoZVm

Summary: The margins of the elements in wrapper should remain in proportion to the viewport.

答:
I don't 100% understand (I know, I shouldn't be answering if I don't understand) but could it be that you're trying to say that you'd like the height of the wrapper to be the height of the viewport (screen height).

If that's the case then you're doing everything right, except...

On default the body has a margin of 8px. You simply have to remove that and you will get the result you're looking for.

body {
  margin: 0;
}

/* =================== */

.title,
.subtitle {
  border: 1px solid #000;
}

.wrapper {
  display: flex;
  flex-direction: column;
  width: 16%;
  height: 100vh;
  margin-right: 42%;
  margin-left: 42%;
  border: 1px solid #000;
}

.title {
  margin-bottom: 1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="title">Title</div>
  <div class="subtitle">Subtitle</div>
</div></code>```

(If you're wandering why you're still able to scroll, it's because "border" adds to the height (and width) so if your border-bottom is 3px and your height like 10px, you have an overall height of 13px)

Body:
Here is a wrapper div with 450 px. If I set the height to 100vh, then the bottom margin of the title should adapt to the viewport.

.title,
.subtitle {
  border: 1px solid #000;
}

.wrapper {
  display: flex;
  flex-direction: column;
  width: 16%;
  height: 450px;
  margin-right: 42%;
  margin-left: 42%;
  border: 1px solid #000;
}

.title {
  margin-bottom: 1rem;
}

Title

Subtitle

https://codepen.io/anon/pen/ZNoZVm

Summary: The margins of the elements in wrapper should remain in proportion to the viewport.

Body:
I don't 100% understand (I know, I shouldn't be answering if I don't understand) but could it be that you're trying to say that you'd like the height of the wrapper to be the height of the viewport (screen height).

If that's the case then you're doing everything right, except...

On default the body has a margin of 8px. You simply have to remove that and you will get the result you're looking for.

body {
  margin: 0;
}

/* =================== */

.title,
.subtitle {
  border: 1px solid #000;
}

.wrapper {
  display: flex;
  flex-direction: column;
  width: 16%;
  height: 100vh;
  margin-right: 42%;
  margin-left: 42%;
  border: 1px solid #000;
}

.title {
  margin-bottom: 1rem;
}

<div class="wrapper">
  <div class="title">Title</div>
  <div class="subtitle">Subtitle</div>
</div>

(If you're wandering why you're still able to scroll, it's because "border" adds to the height (and width) so if your border-bottom is 3px and your height like 10px, you have an overall height of 13px)


问:
What does Prometheus summary.observe method do?
I'm trying to play with summary metrics and not quiet understand where do I put summary.observe call? Here is prom-client example (you can find on npm):

    const client = require('prom-client');
    const summary = new client.Summary({
      name: 'metric_name',
      help: 'metric_help'
    });
    summary.observe(10);
```
<p>but there is no enough info how to use it.</p>
<ol>
<li><p>what does observe(10) mean?</p>
</li>
<li><p>where do I put that summary.observe(10) call? Just right after summary metric declaration or at the end of function/endpoint call like:</p>
<pre class="lang-js prettyprint-override"><code>const client = require('prom-client');

const summary = new client.Summary({
  name: 'metric_name',
  help: 'metric_help'
});
summary.observe(10); // do I put it here?

async myFunc(){
    await this.serviceCall();
    summary.observe(10); // or here?
}
</code>```

Does anybody have a good example/explanation of summary observe?

答:
First, let's clarify what an summary is: a summary metric captures individual observations from an event and summarizes them into a number of related metric:

a sum of values (aka observations)

observation count

quantiles

Taking an example: if you are measuring the response time of a service:

first, you create a summary metrics providing

a name and labels (as usual to identify the metric) - ex: foobar_request_duration_seconds

usually some way to indicate the windows of measurements (number of observation or maximum age of events)

a list of quantiles to compute - ex: 0.1, 0.5 (median), 0.75, 0.9

for each request, you will compute the response time of a request - this is an observation

you then feed the computed request response time to the summary object

when Prometheus scrapes you end-point, metrics are computed from the response time measures observed

foobar_request_duration_seconds_sum: total number of seconds consumed by requests

foobar_request_duration_seconds_count: number of requests (note you can compute average with sum)

foobar_request_duration_seconds_seconds{quantile="0.1"}: response time 10% (... same for all configured quantiles)

I hope this should help you understand the prom-client documentation:

The first example shows how to indicate the quantiles to compute

```<code>new client.Summary({
  name: 'metric_name',
  help: 'metric_help',
  percentiles: [0.01, 0.1, 0.9, 0.99]
});
</code>```

The second how to limit the window of measurements; here, measure are computed over the last 10 minutes (using 5 buckets - this impacts smoothing of values):

```<code>new client.Summary({
  name: 'metric_name',
  help: 'metric_help',
  maxAgeSeconds: 600,
  ageBuckets: 5
});
</code>```

Coming back to your question, the observe() method should be called on what you are observing.

If you want to measure some data returned by serviceCall(), you feed it to the summary

```<code>number_bytes_exchanged = await this.serviceCall();
summary.observe(number_bytes_exchanged);
</code>```

If you want to measure the time taken by service call

```<code>const observe_response_time = summary.startTimer();
await this.serviceCall();
observe_response_time();
</code>```

Body:
I'm trying to play with summary metrics and not quiet understand where do I put summary.observe call? Here is prom-client example (you can find on npm):

    const client = require('prom-client');
    const summary = new client.Summary({
      name: 'metric_name',
      help: 'metric_help'
    });
    summary.observe(10);

but there is no enough info how to use it.

what does observe(10) mean?

where do I put that summary.observe(10) call? Just right after summary metric declaration or at the end of function/endpoint call like:

const client = require('prom-client');

const summary = new client.Summary({
  name: 'metric_name',
  help: 'metric_help'
});
summary.observe(10); // do I put it here?

async myFunc(){
    await this.serviceCall();
    summary.observe(10); // or here?
}

Does anybody have a good example/explanation of summary observe?

Body:
First, let's clarify what an summary is: a summary metric captures individual observations from an event and summarizes them into a number of related metric:

a sum of values (aka observations)

observation count

quantiles

Taking an example: if you are measuring the response time of a service:

first, you create a summary metrics providing

a name and labels (as usual to identify the metric) - ex: foobar_request_duration_seconds

usually some way to indicate the windows of measurements (number of observation or maximum age of events)

a list of quantiles to compute - ex: 0.1, 0.5 (median), 0.75, 0.9

for each request, you will compute the response time of a request - this is an observation

you then feed the computed request response time to the summary object

when Prometheus scrapes you end-point, metrics are computed from the response time measures observed

foobar_request_duration_seconds_sum: total number of seconds consumed by requests

foobar_request_duration_seconds_count: number of requests (note you can compute average with sum)

foobar_request_duration_seconds_seconds{quantile="0.1"}: response time 10% (... same for all configured quantiles)

I hope this should help you understand the prom-client documentation:

The first example shows how to indicate the quantiles to compute

new client.Summary({
  name: 'metric_name',
  help: 'metric_help',
  percentiles: [0.01, 0.1, 0.9, 0.99]
});

The second how to limit the window of measurements; here, measure are computed over the last 10 minutes (using 5 buckets - this impacts smoothing of values):

new client.Summary({
  name: 'metric_name',
  help: 'metric_help',
  maxAgeSeconds: 600,
  ageBuckets: 5
});

Coming back to your question, the observe() method should be called on what you are observing.

If you want to measure some data returned by serviceCall(), you feed it to the summary

number_bytes_exchanged = await this.serviceCall();
summary.observe(number_bytes_exchanged);

If you want to measure the time taken by service call

const observe_response_time = summary.startTimer();
await this.serviceCall();
observe_response_time();


问:
react toggling checkall button in Redux Reactjs
Currently I am learning Redux and the problem I have now is that the selectall checkbox, should be working when someone hit this button. Result is that all the checkbox should be toggling (check or uncheck). But now I am stuck with my logic. When someone call the selectAll function, it should iterate through all the input checkboxes and from that point it should check or uncheck all the checkboxes.

import React from 'react';
import { selectAll } from '../actions';
import { connect } from 'react-redux';

const CheckAll = () => {
    return (

            TodoList <input type="checkbox" onChange={e => {
                e.preventDefault();
                selectAll()
                }}/>

    )
}

const mapDispatchToProps = dispatch => {
    return {
        selectAll: () => dispatch({type: 'SELECT_ALL'})
    }
}

export default connect(mapDispatchToProps)(CheckAll);

import React from 'react';
import { connect } from 'react-redux';
import { removeTodo } from '../actions';

const TodoList = ({ todos, removeTodo }) => {
    return (

             {todos.map((todo) => {
                return (

                        // checkbox should be toggling here when somene clicks on the selectAll checkbox.
                        <input type="checkbox" checkbox="false"/>
                        {todo.text}
                         removeTodo(todo.id, 1)}>x

                )
            } )}

    )
}

const mapDispatchProps = dispatch => {
    return {
        removeTodo: id => dispatch(removeTodo(id))
    }
}

const mapStateToProps = state => {
    return {
        todos: state.reducer || []
    }
}

export default connect(mapStateToProps, mapDispatchProps)(TodoList);

// the reducer below

const reducer = (state = [], action) => {
    switch(action.type) {
        case 'ADD_TODO':
            return [
                ...state,
                {
                    id: action.id,
                    text: action.payload,
                    completed: action.completed
                }
            ];
        case 'REMOVE_TODO':
            return state.filter(({id}) => id !== action.id);
        case 'SELECT_ALL':
            console.log('');
            const allMarked = state.every(action => action.completed);

            return state.map(todo => ({
                ...todo,
                completed: !allMarked
            }));
        default:
            return state;
    }
}

export default reducer;```

I want a functional checkbox, that when everyone clicks on that checkbox, it should be toggling checked or unchecked. But keep in mind that if the user clicks on the individual checkbox, it should not affect the check/uncheckall button.

答:
The main issue is that your checkboxes are not controlled inputs. You're looking at the the completed property to see if the boxes have been checked, but their values are not linked to that property and are not updating the state when they change.  You'll need to feed that value to the inputs as its checked property and add an onChange handler to keep it current:

```<code>             {todos.map((todo, index) => {
                return (
                    <li key={todo.id}>
                        // checkbox should be toggling here when somene clicks on the selectAll checkbox.
                        <input type="checkbox" checked={todo.completed} onChange={() => checkTodo(index)}/>
                        {todo.text}
                        <span onClick={e => removeTodo(todo.id, 1)}>x</span>
                    </li>
                )
            } )}
</code>```

And for a handler you'll need to add a new action and reducer case:

```<code>case 'CHECK_TODO':
            const copy = Array.from(state);
            copy[action.index].completed = !copy[action.index].completed;
            return copy;
            break;
</code>```

You'll of course need to add the index to the action, or use the ID if you'd like, and map its dispatch.  Also as Junius pointed out, be sure you are referring to your props correctly, but I don't think you need this for a functional component, and maybe I've just never seen it before but I don't think a JSX component will render without brackets:

```<code>const CheckAll = (props) => {
  return (
    <div>
      <TodoList/> <input type="checkbox" onChange={e => {
            e.preventDefault();
            props.selectAll()
      }}/>
   </div>
  )
}
</code>```

Body:
Currently I am learning Redux and the problem I have now is that the selectall checkbox, should be working when someone hit this button. Result is that all the checkbox should be toggling (check or uncheck). But now I am stuck with my logic. When someone call the selectAll function, it should iterate through all the input checkboxes and from that point it should check or uncheck all the checkboxes.

import React from 'react';
import { selectAll } from '../actions';
import { connect } from 'react-redux';

const CheckAll = () => {
    return (

            TodoList <input type="checkbox" onChange={e => {
                e.preventDefault();
                selectAll()
                }}/>

    )
}

const mapDispatchToProps = dispatch => {
    return {
        selectAll: () => dispatch({type: 'SELECT_ALL'})
    }
}

export default connect(mapDispatchToProps)(CheckAll);

import React from 'react';
import { connect } from 'react-redux';
import { removeTodo } from '../actions';

const TodoList = ({ todos, removeTodo }) => {
    return (

             {todos.map((todo) => {
                return (

                        // checkbox should be toggling here when somene clicks on the selectAll checkbox.
                        <input type="checkbox" checkbox="false"/>
                        {todo.text}
                         removeTodo(todo.id, 1)}>x

                )
            } )}

    )
}

const mapDispatchProps = dispatch => {
    return {
        removeTodo: id => dispatch(removeTodo(id))
    }
}

const mapStateToProps = state => {
    return {
        todos: state.reducer || []
    }
}

export default connect(mapStateToProps, mapDispatchProps)(TodoList);

// the reducer below

const reducer = (state = [], action) => {
    switch(action.type) {
        case 'ADD_TODO':
            return [
                ...state,
                {
                    id: action.id,
                    text: action.payload,
                    completed: action.completed
                }
            ];
        case 'REMOVE_TODO':
            return state.filter(({id}) => id !== action.id);
        case 'SELECT_ALL':
            console.log('');
            const allMarked = state.every(action => action.completed);

            return state.map(todo => ({
                ...todo,
                completed: !allMarked
            }));
        default:
            return state;
    }
}

export default reducer;

I want a functional checkbox, that when everyone clicks on that checkbox, it should be toggling checked or unchecked. But keep in mind that if the user clicks on the individual checkbox, it should not affect the check/uncheckall button.

Body:
The main issue is that your checkboxes are not controlled inputs. You're looking at the the completed property to see if the boxes have been checked, but their values are not linked to that property and are not updating the state when they change.  You'll need to feed that value to the inputs as its checked property and add an onChange handler to keep it current:

             {todos.map((todo, index) => {
                return (
                    <li key={todo.id}>
                        // checkbox should be toggling here when somene clicks on the selectAll checkbox.
                        <input type="checkbox" checked={todo.completed} onChange={() => checkTodo(index)}/>
                        {todo.text}
                        <span onClick={e => removeTodo(todo.id, 1)}>x</span>
                    </li>
                )
            } )}

And for a handler you'll need to add a new action and reducer case:

case 'CHECK_TODO':
            const copy = Array.from(state);
            copy[action.index].completed = !copy[action.index].completed;
            return copy;
            break;

You'll of course need to add the index to the action, or use the ID if you'd like, and map its dispatch.  Also as Junius pointed out, be sure you are referring to your props correctly, but I don't think you need this for a functional component, and maybe I've just never seen it before but I don't think a JSX component will render without brackets:

const CheckAll = (props) => {
  return (
    <div>
      <TodoList/> <input type="checkbox" onChange={e => {
            e.preventDefault();
            props.selectAll()
      }}/>
   </div>
  )
}


问:
Print out a selected number of a string problem
The exercise says "Make a function with two parameters a string (s) and an integer(n). The function then will return the first n characters. That's what I did, but I'm getting a compiler error "[Warning] passing arg 1 of `symbolse' makes pointer from integer without a cast". I've tried to do some changes, to override this error but then I don't get  the result I want or the program crashes.

```<code> #include<stdio.h>
 #include<stdlib.h>

 void symbolse(char s[50],int n){
    int i;
    for(i=0;i<n;i++)
    printf("%c ",s[i]);

 }

main(){
   int m;
   char a[50];
   printf("Give integer: ");
   scanf("%d",&m);
   printf("Give string: ");
   a[50]=getchar();
   symbolse(a[50],m);

   system("pause");

 }
</code>```

Ex. The user gives m=3 and a[50]=House . The program should print Hou .

答:
Try this...</p>

```<code>void symbolse(char s[50],int n){

int i;

for(i=0;i<n;i++)

printf("%c ",s[i]);

}

main(){

  int m;

  char a[50];

  printf("Give integer: ");

  scanf("%d",&m);

  printf("Give string: ");

  fgets(a,sizeof(a),strin); /* get chars from stdin */

  symbolse(a,m); /* Call the function giving array's base address */

  system("pause");

}
</code>```

Body:
The exercise says "Make a function with two parameters a string (s) and an integer(n). The function then will return the first n characters. That's what I did, but I'm getting a compiler error "[Warning] passing arg 1 of `symbolse' makes pointer from integer without a cast". I've tried to do some changes, to override this error but then I don't get  the result I want or the program crashes.

 #include<stdio.h>
 #include<stdlib.h>

 void symbolse(char s[50],int n){
    int i;
    for(i=0;i<n;i++)
    printf("%c ",s[i]);

 }

main(){
   int m;
   char a[50];
   printf("Give integer: ");
   scanf("%d",&m);
   printf("Give string: ");
   a[50]=getchar();
   symbolse(a[50],m);

   system("pause");

 }

Ex. The user gives m=3 and a[50]=House . The program should print Hou .

Body:
Try this...

void symbolse(char s[50],int n){

int i;

for(i=0;i<n;i++)

printf("%c ",s[i]);

}

main(){

  int m;

  char a[50];

  printf("Give integer: ");

  scanf("%d",&m);

  printf("Give string: ");

  fgets(a,sizeof(a),strin); /* get chars from stdin */

  symbolse(a,m); /* Call the function giving array's base address */

  system("pause");

}


问:
How do I use the ffmpeg CLI to stretch the beginning of an audio stream, using silence, to match the start of the video?
I'm encoding mpd for DashJS using ffmpeg. I'm trying to encode a video that has audio starting 26 seconds after video. When I play it use DashJS, the video refuses to show until the audio starts. What's the best way to stretch the audio to to the beginning of the video using the ffmpeg cli using silence?

I've tried several filters but with no success.

Here's my command:

"ffmpeg" "-i" "static/uploads/tmp.10370ba20dc842f7af87037c8e25e895.mkv" "-c:v" "libx264" "-x264opts" "keyint=25:min-keyint=25:no-scenecut" "-pix_fmt" "yuv420p" "-profile:v" "baseline" "-level" "3" "-coder" "1" "-g" "250" "-c:a" "libfdk_aac" "-b:a" "192k" "-ar" "44100" "-ac" "2" "-map" "0:0" "-map" "0:1" "-map" "0:2" "-map" "0:3" "-metadata" "title=Video" "-f" "dash" "-use_template" "1" "-use_timeline" "1" "-seg_duration" "5" "-init_seg_name" "$RepresentationID$-init.m4s" "-media_seg_name" "$RepresentationID$-$Time$.m4s" "-max_muxing_queue_size" "9999" "-shortest" "-avoid_negative_ts" "make_non_negative" "static/uploads/abea93fe8fe645f291beb6223398e025/index.out"

I tried amixing evalsrc=0 with source 0:1, the stream that starts at 26 seconds but it still starts at 26 seconds.

答:
I found out how to do this. Read the section on first_pts on the aresample page: https://ffmpeg.org/ffmpeg-resampler.html

In my case I added -filter_complex "[0:1] aresample=first_pts=0 [s1]"