问:
r update.packages() not updating packages that are imported by other packages
I recently updated to R 3.5.1 from 3.4.3.  I updated my packages as follows:

(a) copied packages from my old library into my new library (taking care not to overwrite the base packages)

(b) ran update.packages(ask = FALSE, dependencies = TRUE)

I found that a number of packages didn't install where they were listed as imports of other packages as they had 'been created with an r version with different internals, and needs to be reinstalled'.

Somewhat frustratingly, this message seemed to be iterating through some hidden list of associated or linked packages but only telling me there was a problem for one package at a time; i.e. I would install the package that had the wrong version, then try reinstalling the package it had blocked from installing, only to get the error repeated for a different package.  I had to go through this multiple times until there were no more incorrect-version associated packages and finally the package I needed to use could be installed / updated.

Also - I note that some packages were installed from source (these were frequently but not exclusively the ones that caused the 'different internals' error for associated packages above).  I do have Rtools installed so not a problem for me but just an observation as update.packages was doing this every time it encountered a source version that was more up to date than a windows binary (I have a windows 10 PC).

I conclude from all this that update.packages skipped a lot of packages and did not in fact update them for some reason?  I'm still finding packages that did not update.

For example:

```<code>> DescTools::Gmean(x)
Error: package ‘expm’ was installed by an R version with different internals; it needs to be reinstalled for use with this R version
</code>```

Looking at the CRAN entry for DescTools here indicates that the package expm is not a dependency but is imported.

However ?import.packages says of the dependencies argument:

dependencies:

logical indicating whether to also install uninstalled
  packages which these packages depend on/link to/import/suggest (and so
  on recursively). Not used if repos = NULL. Can also be a character
  vector, a subset of c("Depends", "Imports", "LinkingTo", "Suggests",
  "Enhances").

Only supported if lib is of length one (or missing), so it is
  unambiguous where to install the dependent packages. If this is not
  the case it is ignored, with a warning.

The default, NA, means c("Depends", "Imports", "LinkingTo"). TRUE
  means to use c("Depends", "Imports", "LinkingTo", "Suggests") for pkgs
  and c("Depends", "Imports", "LinkingTo") for added dependencies: this
  installs all the packages needed to run pkgs, their examples, tests
  and vignettes (if the package author specified them correctly).

In all of these, "LinkingTo" is omitted for binary packages.

This implies that update.packages(...dependencies = TRUE) should have also updated and / or installed all packages imported by other packages as well.

What am I missing?

答:
I had the same issue after update to R 3.6.0. In my case a slight modification of Carlos Santillan's solution solved the problem:

```<code>for (i in 2:length(.libPaths())) {
  lib <- .libPaths()[i]
  install.packages(
    lib  = .libPaths()[1] ,
    pkgs = as.data.frame(installed.packages(lib), stringsAsFactors=FALSE)$Package,
    type = 'source'
  )
}
</code>```

In my setup .libPaths() retuns the following:

```<code>> .libPaths()
[1] "/home/wassermann/R/x86_64-pc-linux-gnu-library/3.6" "/usr/local/lib/R/site-library"
[3] "/usr/lib/R/site-library"                            "/usr/lib/R/library"
</code>```

The first directory in .libPaths() is writeable at the user level, the other three are read-only. The code iterates over all packages in read-only folders and installs their newer versions in the user writeable directory. It's not optimal in the sense that it may iterate over some packages more than once, but you need to run it only once and after that all packages install without the iritating "different internals" error.

Body:
I recently updated to R 3.5.1 from 3.4.3.  I updated my packages as follows:

(a) copied packages from my old library into my new library (taking care not to overwrite the base packages)

(b) ran update.packages(ask = FALSE, dependencies = TRUE)

I found that a number of packages didn't install where they were listed as imports of other packages as they had 'been created with an r version with different internals, and needs to be reinstalled'.

Somewhat frustratingly, this message seemed to be iterating through some hidden list of associated or linked packages but only telling me there was a problem for one package at a time; i.e. I would install the package that had the wrong version, then try reinstalling the package it had blocked from installing, only to get the error repeated for a different package.  I had to go through this multiple times until there were no more incorrect-version associated packages and finally the package I needed to use could be installed / updated.

Also - I note that some packages were installed from source (these were frequently but not exclusively the ones that caused the 'different internals' error for associated packages above).  I do have Rtools installed so not a problem for me but just an observation as update.packages was doing this every time it encountered a source version that was more up to date than a windows binary (I have a windows 10 PC).

I conclude from all this that update.packages skipped a lot of packages and did not in fact update them for some reason?  I'm still finding packages that did not update.

For example:

> DescTools::Gmean(x)
Error: package ‘expm’ was installed by an R version with different internals; it needs to be reinstalled for use with this R version

Looking at the CRAN entry for DescTools here indicates that the package expm is not a dependency but is imported.

However ?import.packages says of the dependencies argument:

dependencies:

logical indicating whether to also install uninstalled
  packages which these packages depend on/link to/import/suggest (and so
  on recursively). Not used if repos = NULL. Can also be a character
  vector, a subset of c("Depends", "Imports", "LinkingTo", "Suggests",
  "Enhances").

Only supported if lib is of length one (or missing), so it is
  unambiguous where to install the dependent packages. If this is not
  the case it is ignored, with a warning.

The default, NA, means c("Depends", "Imports", "LinkingTo"). TRUE
  means to use c("Depends", "Imports", "LinkingTo", "Suggests") for pkgs
  and c("Depends", "Imports", "LinkingTo") for added dependencies: this
  installs all the packages needed to run pkgs, their examples, tests
  and vignettes (if the package author specified them correctly).

In all of these, "LinkingTo" is omitted for binary packages.

This implies that update.packages(...dependencies = TRUE) should have also updated and / or installed all packages imported by other packages as well.

What am I missing?

Body:
I had the same issue after update to R 3.6.0. In my case a slight modification of Carlos Santillan's solution solved the problem:

for (i in 2:length(.libPaths())) {
  lib <- .libPaths()[i]
  install.packages(
    lib  = .libPaths()[1] ,
    pkgs = as.data.frame(installed.packages(lib), stringsAsFactors=FALSE)$Package,
    type = 'source'
  )
}

In my setup .libPaths() retuns the following:

> .libPaths()
[1] "/home/wassermann/R/x86_64-pc-linux-gnu-library/3.6" "/usr/local/lib/R/site-library"
[3] "/usr/lib/R/site-library"                            "/usr/lib/R/library"

The first directory in .libPaths() is writeable at the user level, the other three are read-only. The code iterates over all packages in read-only folders and installs their newer versions in the user writeable directory. It's not optimal in the sense that it may iterate over some packages more than once, but you need to run it only once and after that all packages install without the iritating "different internals" error.


来源: stackexchange

问:
Is toString() only useful for debugging?
Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

答:
First, the toString method should return a human-readable textual representation of the object.

This issue is brought up in Effective Java as Item 10: Always override toString.

It references the Java API Specification for the Object.toString method:

The result should be a concise but
  informative representation that is
  easy for a person to read.

Aside from debugging, overriding the toString method of a class can be useful when ading objects into a JList or a JTable, which by default will use the toString method to display the object as a textual form in the list or table.

For example, in my case, I've overridden the toString method of objects that are added to a JList so that the user will be able to see information about the item in a list through the GUI.

So, there are indeed cases where the toString method is useful for cases other than debugging. The key is to have the toString method return information that is actually useful for a person to see, not the default Object.toString implementation where the object's memory location is used for its textual representation.

OwnerDisplayName: Camilo Díaz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Camilo Díaz

OwnerDisplayName: coobird


问:
What open-source QR Code Generator would you recommend?
I'm looking for a library to generate QR codes in .NET I've stumbled across a few paid ones, but very few free ones that look any good. Anyone have experience with a good free open-source library?

Thanks

答: http://code.google.com/p/zxing/ and How To Use ZXing C# Port might answer your question.</p>

ContentLicense: CC BY-SA 3.0


问:
Creating Association between two entries in SQL table
I have a piece of work to do setting up a database for a small enterprise.

Currently I have 5 tables set up:

Customers

Accounts

Associations

Security(Collateral)

References (Reference Codes relating to a Job type)

One of the tasks I have is to create an association table that will link to the Customers table and show the association between 2 customers.

Columns for Association table:

AssociationID

Customer1

AssociationType

Customer2

The output should be "Customer1 is AssocationType of Customer2" eg "Dave is Accountant for Jim"

How do I set it up so that Customer1 & Customer2 are from the Customer's table? I think it might be with Foreign Keys but I am unsure.

答:
You can set up foreign keys:

```<code>alter table associations add constraint fk_associations_customer1
    foreign key (customer1_id) references customers (customer_id);

alter table associations add constraint fk_associations_customer2
    foreign key (customer2_id) references customers (customer_id);
</code>```

Foreign keys should be made to the primary key, so you need to define customers so:

```<code>create table customers (
    customer_id int primary key, -- perhaps identity, serial or autoincrement depending on your database
    . . .
);
</code>```

You'll note the naming conventions:

Tables are in the plural (the contain multiple examples of something).

The primary key is the singular followed by _id.

The foreign key is either the same name as, or very similar to, the primary key of the referenced table.

ContentLicense: CC BY-SA 4.0

Body:
You can set up foreign keys:

alter table associations add constraint fk_associations_customer1
    foreign key (customer1_id) references customers (customer_id);

alter table associations add constraint fk_associations_customer2
    foreign key (customer2_id) references customers (customer_id);

Foreign keys should be made to the primary key, so you need to define customers so:

create table customers (
    customer_id int primary key, -- perhaps identity, serial or autoincrement depending on your database
    . . .
);

You'll note the naming conventions:

Tables are in the plural (the contain multiple examples of something).

The primary key is the singular followed by _id.

The foreign key is either the same name as, or very similar to, the primary key of the referenced table.


问:
Is it possible in C++11 to combine functions into a new function?
This is more a kind of theoretical question. Is it possible in C++11 to combine functions into a new function? For example :

```<code>auto f = [](int i){return i * 2;};
auto g = [](int i){return i + 10;};
</code>```

So this works:

```<code>auto c = f(g(20)); // = 60
</code>```

But I want an object that stores the combination, like

```<code>auto c = f(g);
std::cout << c(20) << std::endl; //prints 60
</code>```

Edit:
Additionally what i want to create is a function a, which you can give a function b and an int n, and which returns the n'th combination of the given function b. For example (not compilable)

```<code>template<typename T>
auto combine(T b, int i) -> decltype(T)
{
   if (i == 0)
      return b;

   return combine(b, i - 1);
}

auto c = combine(f, 2); //c = f(f(f(int)))
</code>```

答:
You can write something along the lines of:

```<code>#include <functional>
#include <iostream>

template<class F>
F compose(F f, F g)
{
  return [=](int x) { return f(g(x)); };
}

int main()
{
  std::function<int (int)> f = [](int i) { return i * 2; };
  std::function<int (int)> g = [](int i) { return i + 10; };

  auto c = compose(f, g);
  std::cout << c(20) << '\n';  // prints 60
}
</code>```

The code can be simply extended to cover the second half of the question:

```<code>template<class F>
F compose(F f, unsigned n)
{
  auto g = f;

  for (unsigned i = 0; i < n; ++i)
    g = compose(g, f);

  return g;
}

int main()
{
  std::function<int (int)> h = [](int i) { return i * i; };

  auto d = compose(h, 1);
  auto e = compose(h, 2);
  std::cout << d(3) << "\n"    // prints 81
            << e(3) << "\n";   // prints 6561
}
</code>```

NOTE. Here using std::function. It isn't a lambda but wraps a lambda with a performance cost.

Body:
This is more a kind of theoretical question. Is it possible in C++11 to combine functions into a new function? For example :

auto f = [](int i){return i * 2;};
auto g = [](int i){return i + 10;};

So this works:

auto c = f(g(20)); // = 60

But I want an object that stores the combination, like

auto c = f(g);
std::cout << c(20) << std::endl; //prints 60

Edit:
Additionally what i want to create is a function a, which you can give a function b and an int n, and which returns the n'th combination of the given function b. For example (not compilable)

template<typename T>
auto combine(T b, int i) -> decltype(T)
{
   if (i == 0)
      return b;

   return combine(b, i - 1);
}

auto c = combine(f, 2); //c = f(f(f(int)))

Body:
You can write something along the lines of:

#include <functional>
#include <iostream>

template<class F>
F compose(F f, F g)
{
  return [=](int x) { return f(g(x)); };
}

int main()
{
  std::function<int (int)> f = [](int i) { return i * 2; };
  std::function<int (int)> g = [](int i) { return i + 10; };

  auto c = compose(f, g);
  std::cout << c(20) << '\n';  // prints 60
}

The code can be simply extended to cover the second half of the question:

template<class F>
F compose(F f, unsigned n)
{
  auto g = f;

  for (unsigned i = 0; i < n; ++i)
    g = compose(g, f);

  return g;
}

int main()
{
  std::function<int (int)> h = [](int i) { return i * i; };

  auto d = compose(h, 1);
  auto e = compose(h, 2);
  std::cout << d(3) << "\n"    // prints 81
            << e(3) << "\n";   // prints 6561
}

NOTE. Here using std::function. It isn't a lambda but wraps a lambda with a performance cost.


问:
Can anyone explain the difference between closure and anonymous functions?
I am relatively new to Javascript. I understand the concept of anonymous functions - but closures seem less clear. The similarity between the two (in my mind atleast), is confusing.

Could someone explain the difference? (preferrably, with some code snippet, to illustrate the points clearer).

答:
An anonymous function is one which does not have any name to it, rest is same as the normal functions in Javascript.
Here is an ex.
Case 1:
This is just some normal/regular javascript function

```<code>var sayHello = function iWillSayHello(name){
     var fullName = "Hello, " + name;
     console.log(fullName);
}
sayHello("ABC");    // prints--->  Hello, ABC
</code>```

Case 2:
This is Annonymous function,
It is the same function with the same behavior as above,

```<code>var sayHello = function(name){
     var fullName = "Hello, " + name;
     console.log(fullName);
}
sayHello("ABC");    // prints--->  Hello, ABC
</code>```

Case 3:
If(I think) by "anonymous function" you mean IIFE(Immediately Invoked Function Execution),
that is this,

```<code>(function(name){
     var fullName = "Hello, " + name;
     console.log(fullName);
})();     // prints--->  Hello, ABC
</code>```

The difference here is, In "Case 1" and "Case 2" you have to call the function explicitly, BUT in "Case 3" it is invoked automatically (i.e. with "()" at the end you are calling it as it is declared).
It will be called as compiler reaches that line.

Clouser, on the other hand, is a function inside a function.
What makes a Clouser a special in js, is it still can access the values of the variable from the "local scope" of the outer function even if the outer function has returned.

Clouser = function + outer context

here is a simple example,

```<code>function outerSayHello(firstName){
    var fullName = firstName;
    function innerSayHello(lastName){
         console.log("Hello, ", fullName + " " + lastName);
    }

    return innerSayHello;
}

console.log("1-------------------------");
var sayHello = outerSayHello("A");
sayHello("B");
//Hello,  A B

console.log("2-------------------------");
var sayHello1 = outerSayHello("A1");
sayHello1("B1");
//Hello,  A1 B1

console.log("3-------------------------");
sayHello("b");
//Hello,  A b

console.log("4-------------------------");
sayHello1("b1");
//Hello,  A1 b1

console.log("5-------------------------");
outerSayHello("ABC")("XYZ");
//Hello,  ABC XYZ

to better understand these let's console the sayHello variable

console.log("6-------------------------",sayHello);
/*
  innerSayHello(lastName){
         console.log("Hello, ", fullName + " " + lastName);
    }
*/
</code>```

What it means is sayHello variable has pointer/reference to the innerSayHello function.
And because innerSayHello is relying on fullName variable, it will still be maintained on the heap, and fullName and innerSayHello still be on the stack even after outerSayHello returns.
So in the heap, it will create multiple references for fullname and innerSayHello.

Body:
An anonymous function is one which does not have any name to it, rest is same as the normal functions in Javascript.
Here is an ex.
Case 1:
This is just some normal/regular javascript function

var sayHello = function iWillSayHello(name){
     var fullName = "Hello, " + name;
     console.log(fullName);
}
sayHello("ABC");    // prints--->  Hello, ABC

Case 2:
This is Annonymous function,
It is the same function with the same behavior as above,

var sayHello = function(name){
     var fullName = "Hello, " + name;
     console.log(fullName);
}
sayHello("ABC");    // prints--->  Hello, ABC

Case 3:
If(I think) by "anonymous function" you mean IIFE(Immediately Invoked Function Execution),
that is this,

(function(name){
     var fullName = "Hello, " + name;
     console.log(fullName);
})();     // prints--->  Hello, ABC

The difference here is, In "Case 1" and "Case 2" you have to call the function explicitly, BUT in "Case 3" it is invoked automatically (i.e. with "()" at the end you are calling it as it is declared).
It will be called as compiler reaches that line.

Clouser, on the other hand, is a function inside a function.
What makes a Clouser a special in js, is it still can access the values of the variable from the "local scope" of the outer function even if the outer function has returned.

Clouser = function + outer context

here is a simple example,

function outerSayHello(firstName){
    var fullName = firstName;
    function innerSayHello(lastName){
         console.log("Hello, ", fullName + " " + lastName);
    }

    return innerSayHello;
}

console.log("1-------------------------");
var sayHello = outerSayHello("A");
sayHello("B");
//Hello,  A B

console.log("2-------------------------");
var sayHello1 = outerSayHello("A1");
sayHello1("B1");
//Hello,  A1 B1

console.log("3-------------------------");
sayHello("b");
//Hello,  A b

console.log("4-------------------------");
sayHello1("b1");
//Hello,  A1 b1

console.log("5-------------------------");
outerSayHello("ABC")("XYZ");
//Hello,  ABC XYZ

to better understand these let's console the sayHello variable

console.log("6-------------------------",sayHello);
/*
  innerSayHello(lastName){
         console.log("Hello, ", fullName + " " + lastName);
    }
*/

What it means is sayHello variable has pointer/reference to the innerSayHello function.
And because innerSayHello is relying on fullName variable, it will still be maintained on the heap, and fullName and innerSayHello still be on the stack even after outerSayHello returns.
So in the heap, it will create multiple references for fullname and innerSayHello.


问:
Information about Bootstrap 4 class ".dual-collapse2"
Hello I have never seen a documentation about ".dual-collapse2" and I've seen that people use this class in different examples like this one:
Re-positioning items on navbar collapse in Bootstrap

Can someone explain since there is no info for such a class in the official documentation. Thanks

答:
Hello so with the help of other forums I conclude that this is a custom class added from the code writer, used instead ID - the user adds this class wherever he wants a div to be collapsed and then uses </p>

```<code>data-target=".dual-collapse2"
</code>```

Body:
Hello so with the help of other forums I conclude that this is a custom class added from the code writer, used instead ID - the user adds this class wherever he wants a div to be collapsed and then uses

data-target=".dual-collapse2"


问:
How to check if a pair of coordinates is within a range in Numpy?
I have an array of coordinates:

>> b
array([[11,  1],
       [45, 10],
       [-4,  5],
       [ 8,  9]])
```

<p>And I want to check whether each x value is between 4 and 15 and each y value is between 1 and 7. If a pair of coordinates qualifies, then a <code>True</code> should be added to the list, else <code>False</code>. And this should give me</p>

<pre class="lang-py prettyprint-override"><code>array([True, False, False, False])
</code>```

I am aware I can do this using list comprehension, but is there a faster/neater way to do it?

Body:
I have an array of coordinates:

>> b
array([[11,  1],
       [45, 10],
       [-4,  5],
       [ 8,  9]])

And I want to check whether each x value is between 4 and 15 and each y value is between 1 and 7. If a pair of coordinates qualifies, then a True should be added to the list, else False. And this should give me

array([True, False, False, False])

I am aware I can do this using list comprehension, but is there a faster/neater way to do it?

Body:
((b >= [4, 1]) & (b <= [15, 7])).all(axis=1)

Out: array([ True, False, False, False])


问:
How to display a simple abcjs sheet in an Angular application?
Using the abcjs library in an Angular 7 application, I have the following template:

```<code><div id="{{device.name}}"></div>
</code>```

with the controller:

```<code>@Component({
  selector: 'midi-sheet',
  templateUrl: './sheet.component.html',
  styleUrls: ['./sheet.component.css']
})
export class SheetComponent implements AfterViewInit, OnDestroy  {

  // devices$: Observable<Array<Device>>;
  @Input() device: Device;

  constructor(
    // private storeService: StoreService,
    private sheetService: SheetService
  ) { }

  ngAfterViewInit() {
    this.createSheet();
  }

  ngOnDestroy() {
  }

  private createSheet() {
    const sheet = this.sheetService.createSheet(this.device.name);
  }

}
</code>```

and its service:

```<code>export class SheetService {

  public createSheet(name: string) {
    const elementName: string = '#' + name;
    // tslint:disable-next-line: max-line-length
    const tune = 'X:1\nT: Cooley\'s\nM: 4/4\nL: 1/8\nR: reel\nK: Emin\nD2|:"Em"EB{c}BA B2 EB|~B2 AB dBAG|"D"FDAD BDAD|FDAD dAFD|\n"Em"EBBA B2 EB|B2 AB defg|"D"afe^c dBAF|1"Em"DEFD E2 D2:|2"Em"DEFD E2 gf||\n|:"Em"eB B2 efge|eB B2 gedB|"D"A2 FA DAFA|A2 FA defg|\n"Em"eB B2 eBgB|eB B2 defg|"D"afe^c dBAF|1"Em"DEFD E2 gf:|2"Em"DEFD E4|]\n';
    const sheet = abcjs.renderAbc(elementName, tune, {});
    console.log('Created a sheet for ' + name);
    return sheet;
  }

}
</code>```

The console log shows the sheet is being created:

```<code>Created a sheet for VMPKOutput
</code>```

and the Chrome browser console element tab shows:

```<code><midi-sheet _ngcontent-hvr-c2="" _nghost-hvr-c4="" ng-reflect-device="[object Object]"><div _ngcontent-hvr-c4="" id="MidiThroughPort-0"></div></midi-sheet>
</code>```

But there is no visible sheet in the page.

答:
I've never used this library before, but I took a quick look at the source code and I think you can just pass the native element directly. Which would make it easier to create multiple components on the same page without having to generate unique IDs.

The render function is here:

https://github.com/paulrosen/abcjs/blob/master/src/api/abc_tunebook_svg.js#L160

Tunebook assumes it's a DOM element unless the value is a string:

https://github.com/paulrosen/abcjs/blob/master/src/api/abc_tunebook.js#L137

Use the component's element instead.

```<code>@Component({
  selector: 'midi-sheet',
  // drop the template as it's not needed
  styleUrls: ['./sheet.component.css']
})
export class SheetComponent implements OnInit {
  @Input() device: Device;

  constructor(private sheetService: SheetService,
              private el: ElementRef<HTMLElement>) { }

  ngOnInit() {
    // should work inside ngOnInit and pass the DOM element of this component
    this.sheetService.createSheet(this.el);
  }
}
</code>```

In your service just update to use an element.

```<code>export class SheetService {
  public createSheet(el: ElementRef<HTMLElement>) {
    const tune = 'X:1\nT: Cooley\'s\nM: 4/4\nL: 1/8\nR: reel\nK: Emin\nD2|:"Em"EB{c}BA B2 EB|~B2 AB dBAG|"D"FDAD BDAD|FDAD dAFD|\n"Em"EBBA B2 EB|B2 AB defg|"D"afe^c dBAF|1"Em"DEFD E2 D2:|2"Em"DEFD E2 gf||\n|:"Em"eB B2 efge|eB B2 gedB|"D"A2 FA DAFA|A2 FA defg|\n"Em"eB B2 eBgB|eB B2 defg|"D"afe^c dBAF|1"Em"DEFD E2 gf:|2"Em"DEFD E4|]\n';
    return abcjs.renderAbc(el.nativeElement, tune, {});
  }
}
</code>```

Body:
Using the abcjs library in an Angular 7 application, I have the following template:

with the controller:

@Component({
  selector: 'midi-sheet',
  templateUrl: './sheet.component.html',
  styleUrls: ['./sheet.component.css']
})
export class SheetComponent implements AfterViewInit, OnDestroy  {

  // devices$: Observable<Array<Device>>;
  @Input() device: Device;

  constructor(
    // private storeService: StoreService,
    private sheetService: SheetService
  ) { }

  ngAfterViewInit() {
    this.createSheet();
  }

  ngOnDestroy() {
  }

  private createSheet() {
    const sheet = this.sheetService.createSheet(this.device.name);
  }

}

and its service:

export class SheetService {

  public createSheet(name: string) {
    const elementName: string = '#' + name;
    // tslint:disable-next-line: max-line-length
    const tune = 'X:1\nT: Cooley\'s\nM: 4/4\nL: 1/8\nR: reel\nK: Emin\nD2|:"Em"EB{c}BA B2 EB|~B2 AB dBAG|"D"FDAD BDAD|FDAD dAFD|\n"Em"EBBA B2 EB|B2 AB defg|"D"afe^c dBAF|1"Em"DEFD E2 D2:|2"Em"DEFD E2 gf||\n|:"Em"eB B2 efge|eB B2 gedB|"D"A2 FA DAFA|A2 FA defg|\n"Em"eB B2 eBgB|eB B2 defg|"D"afe^c dBAF|1"Em"DEFD E2 gf:|2"Em"DEFD E4|]\n';
    const sheet = abcjs.renderAbc(elementName, tune, {});
    console.log('Created a sheet for ' + name);
    return sheet;
  }

}

The console log shows the sheet is being created:

Created a sheet for VMPKOutput

and the Chrome browser console element tab shows:

<midi-sheet _ngcontent-hvr-c2="" _nghost-hvr-c4="" ng-reflect-device="[object Object]">

</midi-sheet>

But there is no visible sheet in the page.

Body:
I've never used this library before, but I took a quick look at the source code and I think you can just pass the native element directly. Which would make it easier to create multiple components on the same page without having to generate unique IDs.

The render function is here:

https://github.com/paulrosen/abcjs/blob/master/src/api/abc_tunebook_svg.js#L160

Tunebook assumes it's a DOM element unless the value is a string:

https://github.com/paulrosen/abcjs/blob/master/src/api/abc_tunebook.js#L137

Use the component's element instead.

@Component({
  selector: 'midi-sheet',
  // drop the template as it's not needed
  styleUrls: ['./sheet.component.css']
})
export class SheetComponent implements OnInit {
  @Input() device: Device;

  constructor(private sheetService: SheetService,
              private el: ElementRef<HTMLElement>) { }

  ngOnInit() {
    // should work inside ngOnInit and pass the DOM element of this component
    this.sheetService.createSheet(this.el);
  }
}

In your service just update to use an element.

export class SheetService {
  public createSheet(el: ElementRef<HTMLElement>) {
    const tune = 'X:1\nT: Cooley\'s\nM: 4/4\nL: 1/8\nR: reel\nK: Emin\nD2|:"Em"EB{c}BA B2 EB|~B2 AB dBAG|"D"FDAD BDAD|FDAD dAFD|\n"Em"EBBA B2 EB|B2 AB defg|"D"afe^c dBAF|1"Em"DEFD E2 D2:|2"Em"DEFD E2 gf||\n|:"Em"eB B2 efge|eB B2 gedB|"D"A2 FA DAFA|A2 FA defg|\n"Em"eB B2 eBgB|eB B2 defg|"D"afe^c dBAF|1"Em"DEFD E2 gf:|2"Em"DEFD E4|]\n';
    return abcjs.renderAbc(el.nativeElement, tune, {});
  }
}


问:
Why wordpress stopped to create oembed cache entries right after i wrote custom 'oembed_dataparse' filter
I made the filter to replace standard data parse output and it works fine in frontend. But there is no _oembed_xxxxxxxxxxxxx entries in postmeta table though   _oembed_time_xxxxxxxxxxxxxxx is.

my filter:

add_filter( 'oembed_dataparse', function ( $return, $data, $url ) {
    if ( 'YouTube' === $data->provider_name )
        $return = <<<EOD
thumbnail_url}");"><button class="ytp-large-play-button ytp-button" aria-label="Смотреть"><svg height="100%" version="1.1" viewBox="0 0 68 48" width="100%"><path class="ytp-large-play-button-bg" d="M66.52,7.74c-0.78-2.93-2.49-5.41-5.42-6.19C55.79,.13,34,0,34,0S12.21,.13,6.9,1.55 C3.97,2.33,2.27,4.81,1.48,7.74C0.06,13.05,0,24,0,24s0.06,10.95,1.48,16.26c0.78,2.93,2.49,5.41,5.42,6.19 C12.21,47.87,34,48,34,48s21.79-0.13,27.1-1.55c2.93-0.78,4.64-3.26,5.42-6.19C67.94,34.95,68,24,68,24S67.94,13.05,66.52,7.74z" fill="#212121" fill-opacity="0.8"></path><path d="M 45,24 27,14 27,34" fill="#fff"></path></svg></button>
EOD;

    return $return;
}, 10, 3 );
```

What is wrong?

答: Well, all because of non utf-8 characters in  content replacement.</p>

Body:
I made the filter to replace standard data parse output and it works fine in frontend. But there is no _oembed_xxxxxxxxxxxxx entries in postmeta table though   _oembed_time_xxxxxxxxxxxxxxx is.

my filter:

add_filter( 'oembed_dataparse', function ( $return, $data, $url ) {
    if ( 'YouTube' === $data->provider_name )
        $return = <<<EOD
thumbnail_url}");"><button class="ytp-large-play-button ytp-button" aria-label="Смотреть"><svg height="100%" version="1.1" viewBox="0 0 68 48" width="100%"><path class="ytp-large-play-button-bg" d="M66.52,7.74c-0.78-2.93-2.49-5.41-5.42-6.19C55.79,.13,34,0,34,0S12.21,.13,6.9,1.55 C3.97,2.33,2.27,4.81,1.48,7.74C0.06,13.05,0,24,0,24s0.06,10.95,1.48,16.26c0.78,2.93,2.49,5.41,5.42,6.19 C12.21,47.87,34,48,34,48s21.79-0.13,27.1-1.55c2.93-0.78,4.64-3.26,5.42-6.19C67.94,34.95,68,24,68,24S67.94,13.05,66.52,7.74z" fill="#212121" fill-opacity="0.8"></path><path d="M 45,24 27,14 27,34" fill="#fff"></path></svg></button>
EOD;

    return $return;
}, 10, 3 );

What is wrong?


问:
How to delete Xcode source control that remains after removing .git on the command line?
Here you can see there is no .git file because i removed it

```<code>rm -rf .git
</code>```

And here you can see that Xcode still has a reference to the git repository.

I'd like to recover the history.

Downloading a new version from github doesn't work because it's missing a project.pbxproj file online.

=0

答: the solution is to delete the .DS_Store folder in the directory of the .git file.</p>

Body:
Here you can see there is no .git file because i removed it

rm -rf .git

And here you can see that Xcode still has a reference to the git repository.

I'd like to recover the history.

Downloading a new version from github doesn't work because it's missing a project.pbxproj file online.

=0


问:
Celery worker hangs without any error
I have a production setup for running celery workers for making a POST / GET request to remote service and storing result, It is handling load around 20k tasks per 15 min.

The problem is that the workers go numb for no reason, no errors, no warnings.

I have tried adding multiprocessing also, the same result.

In log I see the increase in the time of executing task, like succeeded in s

For more details look at https://github.com/celery/celery/issues/2621

答:
Follow this tutorial

Celery Django Link

Add the following to the settings

NB Install redis for both transport and result

```<code>   # TRANSPORT
   CELERY_BROKER_TRANSPORT = 'redis'
   CELERY_BROKER_HOST = 'localhost'
   CELERY_BROKER_PORT = '6379'
   CELERY_BROKER_VHOST = '0'

   # RESULT
   CELERY_RESULT_BACKEND = 'redis'
   CELERY_REDIS_HOST = 'localhost'
   CELERY_REDIS_PORT = '6379'
   CELERY_REDIS_DB = '1'
</code>```

Title: Celery worker hangs without any error

Body:
Follow this tutorial

Celery Django Link

Add the following to the settings

NB Install redis for both transport and result

   # TRANSPORT
   CELERY_BROKER_TRANSPORT = 'redis'
   CELERY_BROKER_HOST = 'localhost'
   CELERY_BROKER_PORT = '6379'
   CELERY_BROKER_VHOST = '0'

   # RESULT
   CELERY_RESULT_BACKEND = 'redis'
   CELERY_REDIS_HOST = 'localhost'
   CELERY_REDIS_PORT = '6379'
   CELERY_REDIS_DB = '1'


问:
Batch-file to update files from SVN and then run a program
Currently am executing a program from command prompt, basically a Python command, but I want that to be automated so that the program runs the latest version of the files before the program starts.

So current program is run by saying:

```<code>python c:\program\mysoftwareUI.py
</code>```

mysoftwareUI.py is present in folder that constantly is provided with updates

Now I want to write a batch file with the above command but before that also SVN command that updates the folder before the actual program is run.

How can I do this?

答:
Create a .bat file script and place it into a directory that is in the PATH variable or the current working directory.

=== doit.bat

```<code>@ECHO OFF
PUSHD "c:\program"
svn up
python c:\program\mysoftwareUI.py
POPD
EXIT /B
</code>```

Body:
Currently am executing a program from command prompt, basically a Python command, but I want that to be automated so that the program runs the latest version of the files before the program starts.

So current program is run by saying:

python c:\program\mysoftwareUI.py

mysoftwareUI.py is present in folder that constantly is provided with updates

Now I want to write a batch file with the above command but before that also SVN command that updates the folder before the actual program is run.

How can I do this?

Body:
Create a .bat file script and place it into a directory that is in the PATH variable or the current working directory.

=== doit.bat

@ECHO OFF
PUSHD "c:\program"
svn up
python c:\program\mysoftwareUI.py
POPD
EXIT /B


问:
Take care my Linux Memory Usage Summary in console
I recently saw my AWS EC2 instance's states at SSH helper program (Not a putty program).

I saw below.

```<code>[centos@ip-172-31-xx-xx ~]$ free -h
             total       used       free     shared    buffers     cached
Mem:          1.8G       1.0G       869M       144K       137M       267M
-/+ buffers/cache:       600M       1.2G
Swap:           0B         0B         0B
</code>```

I understand buffers and cached usage are reserved usage, so it is empty usage. But, I didn't understand this.

-/+ buffers/cache:       600M       1.2G

What does it mean?

答:
According to the post Meaning of the buffers/cache line in the output of free.

It seems to be the used memory minus the free memory in cache and buffers and the free memory plus the free memory in cache and buffers.

You can calculate the value if you form the sum of buffers and cached (400M) and substract the value from used (1000M - 400M = 600M) and add it on free (869M + 400~ 1,2G).

Body:
I recently saw my AWS EC2 instance's states at SSH helper program (Not a putty program).

I saw below.

[centos@ip-172-31-xx-xx ~]$ free -h
             total       used       free     shared    buffers     cached
Mem:          1.8G       1.0G       869M       144K       137M       267M
-/+ buffers/cache:       600M       1.2G
Swap:           0B         0B         0B

I understand buffers and cached usage are reserved usage, so it is empty usage. But, I didn't understand this.

-/+ buffers/cache:       600M       1.2G

What does it mean?


问:
Computing the lowest monthly payment using bisection search in python
I'm trying to compute the minimum monthly payment to pay off a loan using the following:

```<code>balance = 999999
annualInterestRate = .18
monthlyInterestRate = annualInterestRate/12

balanceCOPY = balance

#Bisection search parameters

lo = balance/12
hi = (balance*(1+monthlyInterestRate**12))/12
epsilon = .01

guess = (lo + hi)/2

while True:
   for month in range(1,13):
      balance = balance - guess
      balance = balance + (monthlyInterestRate*balance)

   if balance > 0 and balance > epsilon:
      lo = guess
      balance = balanceCOPY
   elif balance < 0 and balance < -epsilon:
      hi = guess
      balance = balanceCOPY
   else:
      print('Lowest payment: ',str(round(guess,2)))
      break

   guess = (lo + hi)/2
</code>```

However, I seem to be stuck in some sort of infinite loop where my guess variable is not being updated. How can I break out of the infinite loop and have my guess variable updated?

The problem was in my math. I meant to say

```<code>hi = (balance*(1+monthlyInterestRate)**12)/12
</code>```

Thank you for all the help everyone!

答:
```<code>    balance = balance
annualInterestRate = annualInterestRate
monthlyInterestRate = annualInterestRate/12

balanceCOPY = balance

#Bisection search parameters

lo = balance/12
hi = (balance*(1+monthlyInterestRate)**12)/12
epsilon = .01

guess = (lo + hi)/2

while True:
   for month in range(1,13):
      balance = balance - guess
      balance = balance + (monthlyInterestRate*balance)

   if balance > 0 and balance > epsilon:
      lo = guess
      balance = balanceCOPY
   elif balance < 0 and balance < -epsilon:
      hi = guess
      balance = balanceCOPY
   else:
      print('Lowest payment: ',str(round(guess,2)))
      break

   guess = (lo + hi)/2
</code>```

Body:
I'm trying to compute the minimum monthly payment to pay off a loan using the following:

balance = 999999
annualInterestRate = .18
monthlyInterestRate = annualInterestRate/12

balanceCOPY = balance

#Bisection search parameters

lo = balance/12
hi = (balance*(1+monthlyInterestRate**12))/12
epsilon = .01

guess = (lo + hi)/2

while True:
   for month in range(1,13):
      balance = balance - guess
      balance = balance + (monthlyInterestRate*balance)

   if balance > 0 and balance > epsilon:
      lo = guess
      balance = balanceCOPY
   elif balance < 0 and balance < -epsilon:
      hi = guess
      balance = balanceCOPY
   else:
      print('Lowest payment: ',str(round(guess,2)))
      break

   guess = (lo + hi)/2

However, I seem to be stuck in some sort of infinite loop where my guess variable is not being updated. How can I break out of the infinite loop and have my guess variable updated?

The problem was in my math. I meant to say

hi = (balance*(1+monthlyInterestRate)**12)/12

Thank you for all the help everyone!


问:
How to get sum of char values produced in a loop?
Sorry if the title is misleading or is confusing, but here is my dilemma.
I am inputting a string, and want to assign a value to each capitalized letter in the alphabet (A=1, .. Z=26) and then add the values of each letter in that string.

Example: ABCD = 10  (since 1 + 2 + 3 + 4)

But I don't know how to add all the values in the string

NOTE: This is only for capitalized letters and strings

```<code>public class Test {

    public static void main(String[] args) {

        Scanner scannerTest = new Scanner(System.in);
        System.out.println("Enter a name here: ");

        String str = scannerTest.nextLine();

        char[] ch = str.toCharArray();
        int temp_integer = 64;

        for (char c : ch) {
            int temp = (int) c;

               if (temp <= 90 & temp >= 65){
            int sum = (temp - temp_integer);
            System.out.println(sum);
        }
      }
    }
}
</code>```

So, as you can see I print out the sum for each time its looped,
meaning: if I input "AB", the output will be 1 and 2.

However, I want to go a step further, and add these two values together, but I'm stumped, any suggestions or help? (NOTE: this is not a assignment or anything, just practising problem sets)

答:
Achieve the same in a concise way by employing Java 8's lambda functions</p>

```<code>String str = "ABCD";
int sum = str.chars()
                .filter(c -> c >= 'A' && c <= 'Z')
                .map(c -> 1 + c - 'A')
                .reduce(0, Integer::sum);
</code>```

Body:
Sorry if the title is misleading or is confusing, but here is my dilemma.
I am inputting a string, and want to assign a value to each capitalized letter in the alphabet (A=1, .. Z=26) and then add the values of each letter in that string.

Example: ABCD = 10  (since 1 + 2 + 3 + 4)

But I don't know how to add all the values in the string

NOTE: This is only for capitalized letters and strings

public class Test {

    public static void main(String[] args) {

        Scanner scannerTest = new Scanner(System.in);
        System.out.println("Enter a name here: ");

        String str = scannerTest.nextLine();

        char[] ch = str.toCharArray();
        int temp_integer = 64;

        for (char c : ch) {
            int temp = (int) c;

               if (temp <= 90 & temp >= 65){
            int sum = (temp - temp_integer);
            System.out.println(sum);
        }
      }
    }
}

So, as you can see I print out the sum for each time its looped,
meaning: if I input "AB", the output will be 1 and 2.

However, I want to go a step further, and add these two values together, but I'm stumped, any suggestions or help? (NOTE: this is not a assignment or anything, just practising problem sets)

Body:
Achieve the same in a concise way by employing Java 8's lambda functions

String str = "ABCD";
int sum = str.chars()
                .filter(c -> c >= 'A' && c <= 'Z')
                .map(c -> 1 + c - 'A')
                .reduce(0, Integer::sum);


问:
Calculate relative frequencies of factor levels in dataset
Let this be my data:

```<code>my.data<-data.frame(name=c("a","b","b","c","c","c"))
</code>```

What I need is a variable that indicates for each name, their respective relative frequency in the dataset. Essentially, this would look like that:

```<code>  name    target
1    a 0.1666667
2    b 0.3333333
3    b 0.3333333
4    c 0.5000000
5    c 0.5000000
6    c 0.5000000
</code>```

What I tried is that I computed dummy variables for each name, and then based on these dummies I calculated new variables that indicate the relative frequency of each name in the dataset. See below:

```<code>temp_dummies<-data.frame(spatstat::dummify(my.data$name))
my.data<-cbind.data.frame(my.data, temp_dummies)
rm(temp_dummies)

my.data %>%
  dplyr::mutate(a_per=mean(a),
                b_per=mean(b),
                c_per=mean(c)) -> my.data
</code>```

Now I need to extract the relative frequencies for each name and aggregate it back to get my target variable. I guess I should do something like this below but I don't know what to mutate.

```<code>my.data %>%
  dplyr::group_by(name) %>%
  dplyr::mutate(...) -> my.data
</code>```

Questions:

How would I get my target variable using dplyr? Am I on the right track?

Is there an easier way to achive the same result?

Might it be possible to write a function that does all of this stuff automatically? It seems like a pretty standard problem that we should be able to fix by simply applying a function(x) to name.

答:
With base-R, you could use the following one-liner:

```<code>my.data$target <- (table(my.data$name)/nrow(my.data))[ my.data$name ]
</code>```

Explanation and in several lines of code:

we use the table function to get the number of occurrences of name and divide it by the number of rows in the df with nrow. After that you look up the "name" of the current row in the "table". This value is saved in the appropriate row of the new column.

```<code>t <- table(my.data$name)/nrow(my.data)
my.data$target <- t[ my.data$name ]
my.data

  name    target
1    a 0.1666667
2    b 0.3333333
3    b 0.3333333
4    c 0.5000000
5    c 0.5000000
6    c 0.5000000
</code>```

Body:
Let this be my data:

my.data<-data.frame(name=c("a","b","b","c","c","c"))

What I need is a variable that indicates for each name, their respective relative frequency in the dataset. Essentially, this would look like that:

  name    target
1    a 0.1666667
2    b 0.3333333
3    b 0.3333333
4    c 0.5000000
5    c 0.5000000
6    c 0.5000000

What I tried is that I computed dummy variables for each name, and then based on these dummies I calculated new variables that indicate the relative frequency of each name in the dataset. See below:

temp_dummies<-data.frame(spatstat::dummify(my.data$name))
my.data<-cbind.data.frame(my.data, temp_dummies)
rm(temp_dummies)

my.data %>%
  dplyr::mutate(a_per=mean(a),
                b_per=mean(b),
                c_per=mean(c)) -> my.data

Now I need to extract the relative frequencies for each name and aggregate it back to get my target variable. I guess I should do something like this below but I don't know what to mutate.

my.data %>%
  dplyr::group_by(name) %>%
  dplyr::mutate(...) -> my.data

Questions:

How would I get my target variable using dplyr? Am I on the right track?

Is there an easier way to achive the same result?

Might it be possible to write a function that does all of this stuff automatically? It seems like a pretty standard problem that we should be able to fix by simply applying a function(x) to name.

Body:
With base-R, you could use the following one-liner:

my.data$target <- (table(my.data$name)/nrow(my.data))[ my.data$name ]

Explanation and in several lines of code:

we use the table function to get the number of occurrences of name and divide it by the number of rows in the df with nrow. After that you look up the "name" of the current row in the "table". This value is saved in the appropriate row of the new column.

t <- table(my.data$name)/nrow(my.data)
my.data$target <- t[ my.data$name ]
my.data

  name    target
1    a 0.1666667
2    b 0.3333333
3    b 0.3333333
4    c 0.5000000
5    c 0.5000000
6    c 0.5000000


问:
Inconsistent chrono::high_resolution_clock delay
I'm trying to implement a MIDI-like clocked sample player.

There is a timer, which increments pulse counter, and every 480 pulses is a quarter, so pulse period is 1041667 ns for 120 beats per minute.
Timer is not sleep-based and running in separate thread, but it seems like delay time is inconsistent: period between samples played in a test file is fluctuating +- 20 ms (in some occasions period is OK and steady, I can't find out dependency of this effect).

Audio backend influence is excluded: i've tried OpenAL as well as SDL_mixer.

```<code>void Timer_class::sleep_ns(uint64_t ns){
    auto start = std::chrono::high_resolution_clock::now();
    bool sleep = true;

    while(sleep)
    {
        auto now = std::chrono::high_resolution_clock::now();
        auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
        if (elapsed.count() >= ns) {
                TestTime = elapsed.count();
                sleep = false;
                //break;
        }
    }
}

void Timer_class::Runner(void){
// this running as thread
    while(1){
        sleep_ns(BPMns);
        if (Run) Transport.IncPlaybackMarker(); // marker increment
        if (Transport.GetPlaybackMarker() == Transport.GetPlaybackEnd()){ // check if timer have reached end, which is 480 pulses
            Transport.SetPlaybackMarker(Transport.GetPlaybackStart());
            Player.PlayFile(1); // period of this event fluctuates severely
        }
    }
};

void Player_class::PlayFile(int FileNumber){
    #ifdef AUDIO_SDL_MIXER
        if(Mix_PlayChannel(-1, WaveData[FileNumber], 0)==-1) {
        printf("Mix_PlayChannel: %s\n",Mix_GetError());
    }
    #endif // AUDIO_SDL_MIXER
}
</code>```

Am i doing something wrong  in terms of an approach? Is there any better way to implement timer of this kind?
Deviation higher than 4-5 ms is too much in case of audio.

答:
I see a large error and a small error.  The large error is that your code assumes that the main processing in Runner consistently takes zero time:

```<code>    if (Run) Transport.IncPlaybackMarker(); // marker increment
    if (Transport.GetPlaybackMarker() == Transport.GetPlaybackEnd()){ // check if timer have reached end, which is 480 pulses
        Transport.SetPlaybackMarker(Transport.GetPlaybackStart());
        Player.PlayFile(1); // period of this event fluctuates severely
    }
</code>```

That is, you're "sleeping" for the time you want your loop iteration to take, and then you're doing processing on top of that.

The small error is presuming that you can represent your ideal loop iteration time with an integral number of nanoseconds.  This error is so small that it doesn't really matter.  However I amuse myself by showing people how they can get rid of this error too. :-)

First lets correct the small error by exactly representing the idealized loop iteration time:

```<code>using quarterPeriod = std::ratio<1, 2>;
using iterationPeriod = std::ratio_divide<quarterPeriod, std::ratio<480>>;
using iteration_time = std::chrono::duration<std::int64_t, iterationPeriod>;
</code>```

I know nothing of music, but I'm guessing the above code is right because if you convert iteration_time{1} to nanoseconds, you get approximately 1041667ns.  iteration_time{1} is intended to be the precise amount of time you want each iteration of your loop in Timer_class::Runner to take.

To correct the large error, you need to sleep until a time_point, as opposed to sleeping for a duration.  Here's a generic utility to help you do that:

```<code>template <class Clock, class Duration>
void
delay_until(std::chrono::time_point<Clock, Duration> tp)
{
    while (Clock::now() < tp)
        ;
}
</code>```

Now if you code Timer_class::Runner to use delay_until instead of sleep_ns, I think you'll get better results:

```<code>void
Timer_class::Runner()
{
    auto next_start = std::chrono::steady_clock::now() + iteration_time{1};

    while (true)
    {
        if (Run) Transport.IncPlaybackMarker(); // marker increment
        if (Transport.GetPlaybackMarker() == Transport.GetPlaybackEnd()){ // check if timer have reached end, which is 480 pulses
            Transport.SetPlaybackMarker(Transport.GetPlaybackStart());
            Player.PlayFile(1);
        }
        delay_until(next_start);
        next_start += iteration_time{1};
    }
}
</code>```

Body:
I'm trying to implement a MIDI-like clocked sample player.

There is a timer, which increments pulse counter, and every 480 pulses is a quarter, so pulse period is 1041667 ns for 120 beats per minute.
Timer is not sleep-based and running in separate thread, but it seems like delay time is inconsistent: period between samples played in a test file is fluctuating +- 20 ms (in some occasions period is OK and steady, I can't find out dependency of this effect).

Audio backend influence is excluded: i've tried OpenAL as well as SDL_mixer.

void Timer_class::sleep_ns(uint64_t ns){
    auto start = std::chrono::high_resolution_clock::now();
    bool sleep = true;

    while(sleep)
    {
        auto now = std::chrono::high_resolution_clock::now();
        auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start);
        if (elapsed.count() >= ns) {
                TestTime = elapsed.count();
                sleep = false;
                //break;
        }
    }
}

void Timer_class::Runner(void){
// this running as thread
    while(1){
        sleep_ns(BPMns);
        if (Run) Transport.IncPlaybackMarker(); // marker increment
        if (Transport.GetPlaybackMarker() == Transport.GetPlaybackEnd()){ // check if timer have reached end, which is 480 pulses
            Transport.SetPlaybackMarker(Transport.GetPlaybackStart());
            Player.PlayFile(1); // period of this event fluctuates severely
        }
    }
};

void Player_class::PlayFile(int FileNumber){
    #ifdef AUDIO_SDL_MIXER
        if(Mix_PlayChannel(-1, WaveData[FileNumber], 0)==-1) {
        printf("Mix_PlayChannel: %s\n",Mix_GetError());
    }
    #endif // AUDIO_SDL_MIXER
}

Am i doing something wrong  in terms of an approach? Is there any better way to implement timer of this kind?
Deviation higher than 4-5 ms is too much in case of audio.

Body:
I see a large error and a small error.  The large error is that your code assumes that the main processing in Runner consistently takes zero time:

    if (Run) Transport.IncPlaybackMarker(); // marker increment
    if (Transport.GetPlaybackMarker() == Transport.GetPlaybackEnd()){ // check if timer have reached end, which is 480 pulses
        Transport.SetPlaybackMarker(Transport.GetPlaybackStart());
        Player.PlayFile(1); // period of this event fluctuates severely
    }

That is, you're "sleeping" for the time you want your loop iteration to take, and then you're doing processing on top of that.

The small error is presuming that you can represent your ideal loop iteration time with an integral number of nanoseconds.  This error is so small that it doesn't really matter.  However I amuse myself by showing people how they can get rid of this error too. :-)

First lets correct the small error by exactly representing the idealized loop iteration time:

using quarterPeriod = std::ratio<1, 2>;
using iterationPeriod = std::ratio_divide<quarterPeriod, std::ratio<480>>;
using iteration_time = std::chrono::duration<std::int64_t, iterationPeriod>;

I know nothing of music, but I'm guessing the above code is right because if you convert iteration_time{1} to nanoseconds, you get approximately 1041667ns.  iteration_time{1} is intended to be the precise amount of time you want each iteration of your loop in Timer_class::Runner to take.

To correct the large error, you need to sleep until a time_point, as opposed to sleeping for a duration.  Here's a generic utility to help you do that:

template <class Clock, class Duration>
void
delay_until(std::chrono::time_point<Clock, Duration> tp)
{
    while (Clock::now() < tp)
        ;
}

Now if you code Timer_class::Runner to use delay_until instead of sleep_ns, I think you'll get better results:

void
Timer_class::Runner()
{
    auto next_start = std::chrono::steady_clock::now() + iteration_time{1};

    while (true)
    {
        if (Run) Transport.IncPlaybackMarker(); // marker increment
        if (Transport.GetPlaybackMarker() == Transport.GetPlaybackEnd()){ // check if timer have reached end, which is 480 pulses
            Transport.SetPlaybackMarker(Transport.GetPlaybackStart());
            Player.PlayFile(1);
        }
        delay_until(next_start);
        next_start += iteration_time{1};
    }
}


问:
using Kivy Garden Graph in KV language
How do I use the kivy module garden.graph inside the kv file? I only found documentation that explained how to use it in the main python script.

I imported the kivy.garden.graph in the python file, and I can add the Graph inside the kv file, but I didn't find any documentation how to set the size, plots etc.

```<code>Graph:
    id: graph_test
    plot: MeshLinePlot
</code>```

this gives an error since MeshLinePlot is not defined, though I imported it on the python side.

any help would be highly appreciated, maybe we could then add this info to the graph's github readme as well.

答:
The answer from Mattis Asp was very helpful but didn't quite work for me.  I am new to this, so maybe these things are too obvious to need stating.  But in case it helps someone else at my level, I had to:

Indent the properties under the Graph: declaration in the kv file (to get around an "invalid data after declaration" exception from the kv parser.

Add these includes:

language: lang-py

```<code>from kivy.properties import ObjectProperty
from kivy.app import App
from kivy.uix.widget import Widget
</code>```

to the top of the python file.

Name the kv file to match the app class definition, so: graphLayout.kv (I had called it graph.kv so it was just ignored -- newbie mistake!)

I was getting "invalid property name" for graph_test : graph_test.  So I commented that out and used the id instead, changing the line

```<code>self.graph_test.add_plot(plot)
</code>```

to:

```<code>self.ids["graph_test"].add_plot(plot)
</code>```

I bet at least some of these changes have to do with version differences in kivy so, for clarity, I am using kivy 1.9.1 and python 2.7.13.

Title: using Kivy Garden Graph in KV language

Body:
How do I use the kivy module garden.graph inside the kv file? I only found documentation that explained how to use it in the main python script.

I imported the kivy.garden.graph in the python file, and I can add the Graph inside the kv file, but I didn't find any documentation how to set the size, plots etc.

Graph:
    id: graph_test
    plot: MeshLinePlot

this gives an error since MeshLinePlot is not defined, though I imported it on the python side.

any help would be highly appreciated, maybe we could then add this info to the graph's github readme as well.

Body:
The answer from Mattis Asp was very helpful but didn't quite work for me.  I am new to this, so maybe these things are too obvious to need stating.  But in case it helps someone else at my level, I had to:

Indent the properties under the Graph: declaration in the kv file (to get around an "invalid data after declaration" exception from the kv parser.

Add these includes:

language: lang-py

from kivy.properties import ObjectProperty
from kivy.app import App
from kivy.uix.widget import Widget

to the top of the python file.

Name the kv file to match the app class definition, so: graphLayout.kv (I had called it graph.kv so it was just ignored -- newbie mistake!)

I was getting "invalid property name" for graph_test : graph_test.  So I commented that out and used the id instead, changing the line

self.graph_test.add_plot(plot)

to:

self.ids["graph_test"].add_plot(plot)

I bet at least some of these changes have to do with version differences in kivy so, for clarity, I am using kivy 1.9.1 and python 2.7.13.


问:
using distinct command
using distinct command in SQL is good practice or not? is there any drawback of distinct command?</p>

答:
If you need to use it regularly to get the correct output then you have a design or JOIN issue

It's perfectly valid for use otherwise.

It is a kind of aggregate though: the equivalent to a GROUP BY on all output columns. So it is an extra step is query processing

Title: using distinct command


问:
How to provide custom comparator for `std::multiset` without overloading `operator()`, `std::less`, `std::greater`?
I want a custom comparator for the following code. However, I am not allowed to overload  operator(), std::less, std::greater.

I tried to achieve this using lambda but gcc won't allow me to use auto as a non-static member. Any other way to make this work?

```<code>#include <iostream>
#include <map>
#include <set>

class Test
{
public:
    // bool operator () (const int lhs, const int rhs) { // not allowed
    //     return lhs > rhs;
    // };
    using list = std::multiset<int  /*, Test*/>;
    std::map<const char*, list> scripts;
};

int main()
{
    Test t;
    t.scripts["Linux"].insert(5);
    t.scripts["Linux"].insert(8);
    t.scripts["Linux"].insert(0);

    for (auto a : t.scripts["Linux"]) {
        std::cout << a << std::endl;
    }

    std::cout << "end";
}
</code>```

Edit: With lambdas

```<code>class Test
{
  public:
    auto compare = [] (const int a, const int b) { return a < b;}
    using list = std::multiset<int, compare>;    //here
    std::map<const char*, list> scripts;
};
</code>```

Error:

```<code>'auto' not allowed in non-static class member
 auto compare = [] (const int a, const int b) { return a < b;}
</code>```

答:
There is a problem with your approach even if you could define a lambda the way you want to. Take a look at the multiset declaration:

```<code>template<
    class Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class multiset;
</code>```

Notice how each template parameter is a type (using the class keyword). Now look at how you tried to define your list:

```<code>using list = std::multiset<int, compare>;
                            ^      ^
                          type   value
</code>```

The first parameter is good, but the second is a mismatch. The Compare parameter needs to be a type, not an object. One general way to resolve this sort of situation is to replace compare with decltype(compare), but that seems to be not what you want (plus it is problematic for lambda types). You seem to want a default constructed list to use compare instead of merely a default constructed object of the same type.

So what you need is a class whose default constructed object implements operator() in a way that gives the order you want. Since we're dealing with int, the standard library has some ready-made types for this purpose, namely std::less and std::greater.

```<code>using list = std::multiset<int, std::greater<int>>;
</code>```

However, I cannot overload operator(), std::less, std::greater.

Hmm... this suggests that the example code may have been over-simplified, as an overload is not called for. OK, let's suppose the list is of some type that's harder to deal with, say:

```<code>class I { /* Internals not important for this example. */ };
using list = std::multiset<I, ???>;
</code>```

If you are allowed to modify I, then the simplest approach might be to define operator> (or operator<) for objects of type I. Since std::greater (or std::less) uses this operator, you get the desired order from the standard template without overloading it.

If you are not allowed to modify I, then I think you're left with writing your own function object, as this is one situation where a lambda is inadequate. Fortunately, classes implementing function objects are easy to write; lambdas have superseded them in other situations mostly because the lambda syntax tends to be more convenient.

```<code>struct CompareI {
    bool operator() (const I & lhs, const I & rhs) const { return /* fill this in */; }
};
using list = std::multiset<I, CompareI>;
</code>```

While this defines an operator(), it is not an overload. So it should satisfy the requirements given to you.

Body:
I want a custom comparator for the following code. However, I am not allowed to overload  operator(), std::less, std::greater.

I tried to achieve this using lambda but gcc won't allow me to use auto as a non-static member. Any other way to make this work?

#include <iostream>
#include <map>
#include <set>

class Test
{
public:
    // bool operator () (const int lhs, const int rhs) { // not allowed
    //     return lhs > rhs;
    // };
    using list = std::multiset<int  /*, Test*/>;
    std::map<const char*, list> scripts;
};

int main()
{
    Test t;
    t.scripts["Linux"].insert(5);
    t.scripts["Linux"].insert(8);
    t.scripts["Linux"].insert(0);

    for (auto a : t.scripts["Linux"]) {
        std::cout << a << std::endl;
    }

    std::cout << "end";
}

Edit: With lambdas

class Test
{
  public:
    auto compare = [] (const int a, const int b) { return a < b;}
    using list = std::multiset<int, compare>;    //here
    std::map<const char*, list> scripts;
};

Error:

'auto' not allowed in non-static class member
 auto compare = [] (const int a, const int b) { return a < b;}

Body:
There is a problem with your approach even if you could define a lambda the way you want to. Take a look at the multiset declaration:

template<
    class Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class multiset;

Notice how each template parameter is a type (using the class keyword). Now look at how you tried to define your list:

using list = std::multiset<int, compare>;
                            ^      ^
                          type   value

The first parameter is good, but the second is a mismatch. The Compare parameter needs to be a type, not an object. One general way to resolve this sort of situation is to replace compare with decltype(compare), but that seems to be not what you want (plus it is problematic for lambda types). You seem to want a default constructed list to use compare instead of merely a default constructed object of the same type.

So what you need is a class whose default constructed object implements operator() in a way that gives the order you want. Since we're dealing with int, the standard library has some ready-made types for this purpose, namely std::less and std::greater.

using list = std::multiset<int, std::greater<int>>;

However, I cannot overload operator(), std::less, std::greater.

Hmm... this suggests that the example code may have been over-simplified, as an overload is not called for. OK, let's suppose the list is of some type that's harder to deal with, say:

class I { /* Internals not important for this example. */ };
using list = std::multiset<I, ???>;

If you are allowed to modify I, then the simplest approach might be to define operator> (or operator<) for objects of type I. Since std::greater (or std::less) uses this operator, you get the desired order from the standard template without overloading it.

If you are not allowed to modify I, then I think you're left with writing your own function object, as this is one situation where a lambda is inadequate. Fortunately, classes implementing function objects are easy to write; lambdas have superseded them in other situations mostly because the lambda syntax tends to be more convenient.

struct CompareI {
    bool operator() (const I & lhs, const I & rhs) const { return /* fill this in */; }
};
using list = std::multiset<I, CompareI>;

While this defines an operator(), it is not an overload. So it should satisfy the requirements given to you.