问:
Why IDXGIAdapter cannot cast to IDXGIFactory?
I understand that DirectX does not follow the COM standard. However, they look heck of a lot similar, hence my confusion.

For simplicity, I use the word 'COM' very loosely, and I omit all HRESULT handlings, so please bear with me.

Correct code:

Consider the following code.

```<code>ComPtr<IDXGIDevice3>            g_pDXGIDevice = nullptr;
ComPtr<ID3D11Device>            g_pD3DDevice = nullptr;
ComPtr<ID3D11DeviceContext>     g_pD3DDeviceContext = nullptr;

D3D11CreateDevice(..., &g_pD3DDevice, ..., &g_pD3DDeviceContext);
</code>```

A 'COM' object is instantiated. Since it is not a pure COM object, the component is instantiated through the D3D11 function D3D11CreateDevice() instead of the generic COM function coCreateInstance().

Upon success, the function returns 2 COM pointers: g_pD3DDevice and g_pD3DDeviceContext. This enables the client to interact and use methods with the COM server without the burden of the implementation details.

```<code>g_pD3DDevice.As(&g_pDXGIDevice);
</code>```

Next, we QueryInterface the DXGI device from the device interface through the As method of the ComPtr class.

The return is a success since the DXGI-device interface and the device interface are provided by the same COM object.

Next, we create the swap chain with:

```<code>ComPtr<IDXGIAdapter> m_adapter = nullptr;
ComPtr<IDXGIFactory> m_factory = nullptr;

g_pDXGIDevice->GetAdapter(&m_adapter);
m_adapter->GetParent(IID_PPV_ARGS(&m_factory));
m_factory->CreateSwapChain(...);
</code>```

This comes from the official MSD doc and works.

Incorrect code:

Now, before creating the swap chain, let's do the following.

```<code>m_adapter.As(&m_factory);
</code>```

This returns E_NOINTERFACE. Here's my confusion.

Why can't we QueryInterface from IDXGIAdapter to get IDXGIFactory?

Aren't they interfaces of the same DLL, that is, dxgi.dll?

Are they interfaces pertaining to the same component object?

From MSD documentation, IDXGIAdapter and IDXGIFactory are derived from the same base-class interface IDXGIObject.

Can we safely assume that they are interfaces of the same COM object, and thus, it is possible to navigate within the object interfaces through QueryInterface?

If not, how do we know from the doc if two interfaces pertain to the same object? It seems that the doc is not clear about that.

To consolidate my arguments, in debug mode, we can clearly see that both IDXGIAdapter and IDXGIFactory come from the same DLL (see screenshot below).

Screenshot of m_adapter and m_factory as items to watch in debug mode

So why does m_adapter.As(&m_factory); return an error?

Note

IDXGIFactory::CreateSwapChain has been deprecated since Direct3d 11.1 (see MS documentation).

答:
A good place to start is to read through Microsoft Docs: Programming DirectX with COM.

In many cases the DirectX COM components allow you to do just what you say: If the C++ interface class inherits from another one, you should be able to QueryInterface up or down the chain with the same object instance. IDXGIAdapter is derived from IDXGIObject, so you can QI from the adapter instance to the object interface. IDXGIFactory is also derived from IDXGIObject, so you can QI to the object interface as well. Just because they both implement the same base interface, however, does not mean you an go from an instance of adapter to an instance of the factory. I.e., they are not the same 'object'. This mirrors C++ rules for inheritance: You can freely cast an instance of a class to it's publicly inherited parent, but can't freely cast back down the hierarchy.

There are some cases in DXGI where you can "navigate back" via IUnknown::QueryInterface and IDXGIObject::GetParent. For example, the following code is a good, consistent way to "get back" to the DXGI factory from a Direct3D 11 device:

```<code>ComPtr<IDXGIFactory1> dxgiFactory;
{
    ComPtr<IDXGIDevice> dxgiDevice;
    if (SUCCEEDED(device.As(&dxgiDevice)))
    {
        ComPtr<IDXGIAdapter> adapter;
        if (SUCCEEDED(dxgiDevice->GetAdapter(&adapter)))
        {
            hr = adapter->GetParent(IID_PPV_ARGS(&dxgiFactory));
            if ( SUCCEEDED(hr) )
            {
                ...
            }
        }
    }
}
</code>```

See Anatomy of Direct3D 11 Create Device.

While this works in simple cases like the one above, general type shifting is often problematic and/or buggy. For example, with Direct3D 11 there were problems if you use the DXGICreateFactory method instead of DXGICreateFactory1, or if you mixed both in the same process.

As such, for DirectX 12 these DXGI back-track conversions (such as the code above) are explicitly not supported. You are expected to create the DXGI factory directly and then create the Direct3D 12 device from the enumerated adapter and -not- try to go the other way.

See Anatomy of Direct3D 12 Create Device.

Really the only time you are expected to use those DXGI interfaces beyond enumeration is for "surface sharing" scenarios. See Microsoft Docs: DX11 and DX12. Everything else is really there only for internal implementation purposes, and is therefore subject to change or other undocumented behaviors.

Body:
I understand that DirectX does not follow the COM standard. However, they look heck of a lot similar, hence my confusion.

For simplicity, I use the word 'COM' very loosely, and I omit all HRESULT handlings, so please bear with me.

Correct code:

Consider the following code.

ComPtr<IDXGIDevice3>            g_pDXGIDevice = nullptr;
ComPtr<ID3D11Device>            g_pD3DDevice = nullptr;
ComPtr<ID3D11DeviceContext>     g_pD3DDeviceContext = nullptr;

D3D11CreateDevice(..., &g_pD3DDevice, ..., &g_pD3DDeviceContext);

A 'COM' object is instantiated. Since it is not a pure COM object, the component is instantiated through the D3D11 function D3D11CreateDevice() instead of the generic COM function coCreateInstance().

Upon success, the function returns 2 COM pointers: g_pD3DDevice and g_pD3DDeviceContext. This enables the client to interact and use methods with the COM server without the burden of the implementation details.

g_pD3DDevice.As(&g_pDXGIDevice);

Next, we QueryInterface the DXGI device from the device interface through the As method of the ComPtr class.

The return is a success since the DXGI-device interface and the device interface are provided by the same COM object.

Next, we create the swap chain with:

ComPtr<IDXGIAdapter> m_adapter = nullptr;
ComPtr<IDXGIFactory> m_factory = nullptr;

g_pDXGIDevice->GetAdapter(&m_adapter);
m_adapter->GetParent(IID_PPV_ARGS(&m_factory));
m_factory->CreateSwapChain(...);

This comes from the official MSD doc and works.

Incorrect code:

Now, before creating the swap chain, let's do the following.

m_adapter.As(&m_factory);

This returns E_NOINTERFACE. Here's my confusion.

Why can't we QueryInterface from IDXGIAdapter to get IDXGIFactory?

Aren't they interfaces of the same DLL, that is, dxgi.dll?

Are they interfaces pertaining to the same component object?

From MSD documentation, IDXGIAdapter and IDXGIFactory are derived from the same base-class interface IDXGIObject.

Can we safely assume that they are interfaces of the same COM object, and thus, it is possible to navigate within the object interfaces through QueryInterface?

If not, how do we know from the doc if two interfaces pertain to the same object? It seems that the doc is not clear about that.

To consolidate my arguments, in debug mode, we can clearly see that both IDXGIAdapter and IDXGIFactory come from the same DLL (see screenshot below).

Screenshot of m_adapter and m_factory as items to watch in debug mode

So why does m_adapter.As(&m_factory); return an error?

Note

IDXGIFactory::CreateSwapChain has been deprecated since Direct3d 11.1 (see MS documentation).

Body:
A good place to start is to read through Microsoft Docs: Programming DirectX with COM.

In many cases the DirectX COM components allow you to do just what you say: If the C++ interface class inherits from another one, you should be able to QueryInterface up or down the chain with the same object instance. IDXGIAdapter is derived from IDXGIObject, so you can QI from the adapter instance to the object interface. IDXGIFactory is also derived from IDXGIObject, so you can QI to the object interface as well. Just because they both implement the same base interface, however, does not mean you an go from an instance of adapter to an instance of the factory. I.e., they are not the same 'object'. This mirrors C++ rules for inheritance: You can freely cast an instance of a class to it's publicly inherited parent, but can't freely cast back down the hierarchy.

There are some cases in DXGI where you can "navigate back" via IUnknown::QueryInterface and IDXGIObject::GetParent. For example, the following code is a good, consistent way to "get back" to the DXGI factory from a Direct3D 11 device:

ComPtr<IDXGIFactory1> dxgiFactory;
{
    ComPtr<IDXGIDevice> dxgiDevice;
    if (SUCCEEDED(device.As(&dxgiDevice)))
    {
        ComPtr<IDXGIAdapter> adapter;
        if (SUCCEEDED(dxgiDevice->GetAdapter(&adapter)))
        {
            hr = adapter->GetParent(IID_PPV_ARGS(&dxgiFactory));
            if ( SUCCEEDED(hr) )
            {
                ...
            }
        }
    }
}

See Anatomy of Direct3D 11 Create Device.

While this works in simple cases like the one above, general type shifting is often problematic and/or buggy. For example, with Direct3D 11 there were problems if you use the DXGICreateFactory method instead of DXGICreateFactory1, or if you mixed both in the same process.

As such, for DirectX 12 these DXGI back-track conversions (such as the code above) are explicitly not supported. You are expected to create the DXGI factory directly and then create the Direct3D 12 device from the enumerated adapter and -not- try to go the other way.

See Anatomy of Direct3D 12 Create Device.

Really the only time you are expected to use those DXGI interfaces beyond enumeration is for "surface sharing" scenarios. See Microsoft Docs: DX11 and DX12. Everything else is really there only for internal implementation purposes, and is therefore subject to change or other undocumented behaviors.


来源: stackexchange

问:
Generate a series of numbers that go up in two interweaving intervals
Let's say I want to generate a series of numbers that first jump 5 and then 10 all the way to 100 which would be

```<code>0,5,15,20,30,35,45,50,60,65,75,85,90,100
</code>```

I am aware of

```<code>seq 0 10 100
</code>```

but am looking to jump two different intervals intertwined.

ContentLicense: CC BY-SA 4.0

Body:
Let's say I want to generate a series of numbers that first jump 5 and then 10 all the way to 100 which would be

0,5,15,20,30,35,45,50,60,65,75,85,90,100

I am aware of

seq 0 10 100

but am looking to jump two different intervals intertwined.

Body:
$ cat tst.awk
BEGIN {
    for ( i=0; i<=100; i+=(++c%2 ? 5 : 10) ) {
        print i
    }
}

$ awk -f tst.awk
0
5
15
20
30
35
45
50
60
65
75
80
90
95


问:
Use decorator on class with argument to restrict properties
As the question, would like to know if there's any approach that could have the class decorator restrict the decorated class properties based on the decorator argument in typescript.

code snippet

decorator:

```<code>type Exactly<T, U extends { [key in keyof T]: any }> = { [K in keyof U]: K extends keyof T ? any : never };

function DefinePolicy<K>(infer: K) {
  return function<TCtor extends Exactly<K, TCtor>>(cls: TCtor): TCtor {
    return cls;
  };
}
</code>```

class:

```<code>export class ResouceOne {
  name: string;

  age: number;
}

@DefinePolicy(ResouceOne)
export class ResoureOnePolicy {
  name: 'foo';

  age: 20;

  incorrect: 'SHOULD GET ERROR';
}
</code>```

type check:

```<code>type TypeCheck = ResoureOnePolicy extends Exactly<ResouceOne, ResoureOnePolicy>? true: false;

// type TypeCheck = false
</code>```

So I did receive false from above type check, but seems like it doesn't really work in the inner function of decorator when there's unexpected property got defined in the decorated class.

How can we have the decorator capture the type error in the first? any advice would be appreciated.

答:
The part <TCtor extends Exactly<K, TCtor>> doesn't quite make sense, generic constraints aren't "checks" they are constraints, you can specify that type must be a subtype of something else, but not that it should fit some arbitrary condition.

So making it type safe in one way (requiring that every property from infer be present in cls) is not too difficult if focus the generics around the objects, not the classes. In the current code K and TCtor are classes so function that return some objects, but you are trying to check that these object have some type. So it would be easier to type those:

// Accept class that instanciates object of type `K`
function DefinePolicy<K>(infer: new () => K) {
  return function<TCtor extends new () => K>(cls: TCtor): TCtor {
    return cls;
  };
}
```
<p>Now this code will be an error for example:</p>
```@DefinePolicy(ResouceOne)
export class ResoureOnePolicy {
  name!: 'foo';
  // Oops no age
}
```
<p>Getting rid of excess properties like <code>incorrect</code> in your snippet is trickier, you need to prevent function parameter <code>cls</code> to accept object of type <code>X</code> so that <code>cls</code> is assignable to <code>X</code>, in typescript everything is around <code>X</code> being assignable to <code>cls</code> and the other way is tricky. Here is one way. Firstly let's change inner function to also work with objects not classes:</p>
```function DefinePolicy<K>(infer: new () => K) {
  return function<TObj extends K>(cls: new () => TObj): new () => TObj {
    return cls;
  };
}
```
<p>Basically what I want to do is after <code>TObj</code> has been determined check whether <code>K</code> is assignable to it (we know that <code>TObj</code> is assignable to <code>K</code> because of constraint, we only need to check the relation the other way): if it is, then leave this function as it is, if it is not, then change type of <code>cls</code> to <code>never</code> so that you aren't able to assign anything to it and it is an error. First I'll change <code>Exactly</code> type to this:</p>
```// Returns keys that are present in U but not in T
type ExcessKeys<T, U> = keyof {
    [K in keyof U as K extends keyof T ? never : K]-?: true
};
```
<p>It should actually work withou "-?" but leaving it just to be sure in my abilities to use obscure features when unnecessary. Now the decorator becomes:</p>
```function DefinePolicy<K>(infer: new () => K) {
  return function<TObj extends K>(
    cls:
      // If there are no excess keys
      ExcessKeys<K, TObj> extends never ?
        // Leave as is
        new () => TObj :
        // Otherwise error
        never
    ): new () => TObj {
    return cls;
  };
}
```

Sandbox

This isn't very consistent and I'm sure you will find some edge cases where this check will behave in a weird way, so maybe it's worth reconsidering what you are doing and leaving only the TObj extends K part, usually this is enough. Another problem with this approach is that the error is hard to trace: it just says Type X is not assignable to type never when the decorated class has some wrong property which is very unhelpful and hard to debug.

Body:
As the question, would like to know if there's any approach that could have the class decorator restrict the decorated class properties based on the decorator argument in typescript.

code snippet

decorator:

type Exactly<T, U extends { [key in keyof T]: any }> = { [K in keyof U]: K extends keyof T ? any : never };

function DefinePolicy<K>(infer: K) {
  return function<TCtor extends Exactly<K, TCtor>>(cls: TCtor): TCtor {
    return cls;
  };
}

class:

export class ResouceOne {
  name: string;

  age: number;
}

@DefinePolicy(ResouceOne)
export class ResoureOnePolicy {
  name: 'foo';

  age: 20;

  incorrect: 'SHOULD GET ERROR';
}

type check:

type TypeCheck = ResoureOnePolicy extends Exactly<ResouceOne, ResoureOnePolicy>? true: false;

// type TypeCheck = false

So I did receive false from above type check, but seems like it doesn't really work in the inner function of decorator when there's unexpected property got defined in the decorated class.

How can we have the decorator capture the type error in the first? any advice would be appreciated.

Body:
The part <TCtor extends Exactly<K, TCtor>> doesn't quite make sense, generic constraints aren't "checks" they are constraints, you can specify that type must be a subtype of something else, but not that it should fit some arbitrary condition.

So making it type safe in one way (requiring that every property from infer be present in cls) is not too difficult if focus the generics around the objects, not the classes. In the current code K and TCtor are classes so function that return some objects, but you are trying to check that these object have some type. So it would be easier to type those:

// Accept class that instanciates object of type `K`
function DefinePolicy<K>(infer: new () => K) {
  return function<TCtor extends new () => K>(cls: TCtor): TCtor {
    return cls;
  };
}

Now this code will be an error for example:

@DefinePolicy(ResouceOne)
export class ResoureOnePolicy {
  name!: 'foo';
  // Oops no age
}

Getting rid of excess properties like incorrect in your snippet is trickier, you need to prevent function parameter cls to accept object of type X so that cls is assignable to X, in typescript everything is around X being assignable to cls and the other way is tricky. Here is one way. Firstly let's change inner function to also work with objects not classes:

function DefinePolicy<K>(infer: new () => K) {
  return function<TObj extends K>(cls: new () => TObj): new () => TObj {
    return cls;
  };
}

Basically what I want to do is after TObj has been determined check whether K is assignable to it (we know that TObj is assignable to K because of constraint, we only need to check the relation the other way): if it is, then leave this function as it is, if it is not, then change type of cls to never so that you aren't able to assign anything to it and it is an error. First I'll change Exactly type to this:

// Returns keys that are present in U but not in T
type ExcessKeys<T, U> = keyof {
    [K in keyof U as K extends keyof T ? never : K]-?: true
};

It should actually work withou "-?" but leaving it just to be sure in my abilities to use obscure features when unnecessary. Now the decorator becomes:

function DefinePolicy<K>(infer: new () => K) {
  return function<TObj extends K>(
    cls:
      // If there are no excess keys
      ExcessKeys<K, TObj> extends never ?
        // Leave as is
        new () => TObj :
        // Otherwise error
        never
    ): new () => TObj {
    return cls;
  };
}

<a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAwgNgQwM5ICIQMYHsBODi5QC8UAPACoBiArgHYbACWWtUEAHsBLQCZJQ16TFgD4AFMAQ4A5hGAAuKFToNmtAJTERUAG5ZGPKAB8lg1SwBQF0JCgBRdhggoA0hBBIKAGigBVbSQA1u5YAGZQAN5QFlCxUADaLlCMrMEgYX5QyFBJHFy8-GkZ5FAA-FC0EDoQOFCKLgC6ALSlisA41NAWAL4A3Nbg0ABKEGAIGIEUAZGJyakh4eQNiuSJDd1WoSrCrOihKRAAClhwjBggpC7iKaE1ipUA7lBimkTaLpoRMVA4ctQ4rC2QjUFAA8gAjABWbE43D4OXEGDgSEUDicrncnhcPnIEMh2jycP4lWqtXKj2er20uKhdQqVRq6nuECeLy0SjxkW+sV+wH+rCRSH6sT6PSsFg4YFwwCgSOQ-BGSCw-ycoMqXNitAQAFsIABCRRIdopaTCrKyA0Vaja8E1fobCwAAT2B2Op3OYkVypwqsq6gl7ClOBlcpQUC9KogaqOJzOIA1FR1+sUAHJQlgsCmzQgLYoAEwABntVmdEH2lTdcc9zm9vog-sl0tliDDEZ9UYrsfOAEYE1rdZa0xms98c8moIWzSlsDhfgxWlAUwBlAASoN8ABlUFAAOJ2Ep2IZDUFDEcO0vlmPukDVpWR6MNwNN0MKmv3zvXvN9pOD9OZqf0Lgc7AAuy5rpu257geR4nmeQA" rel="nofollow noreferrer">Sandbox

This isn't very consistent and I'm sure you will find some edge cases where this check will behave in a weird way, so maybe it's worth reconsidering what you are doing and leaving only the TObj extends K part, usually this is enough. Another problem with this approach is that the error is hard to trace: it just says Type X is not assignable to type never when the decorated class has some wrong property which is very unhelpful and hard to debug.


问:
Is there a way to blur compound path in p5.js?
I'd like to blur the edges of holes created by mouse clicks. This is my example. Now I've used g.js to create differences of two shapes (circles and a rectangle), and then I'd like to blur the edges of these holes on the rectangle. I've tried fliter(BLUR), but the effect was not ideal because it will blur both the holes and the maps under it. I just want to blur the rectangle with holes. Is there any way to do that?

var e2 = [];
var light = [];
var img;
var pg;
var pgPos = [];

function preload() {
  img = loadImage("https://2328a0b8-e236-4076-9848-a3275ab1c3e3.id.repl.co/map%20test.jpg");
}

function setup() {
  createCanvas(600, 600);

  background(100, 100, 100);
  pg = createGraphics(600, 600);

}

function mouseClicked() {

  push();
  let e = g.ellipse({ x: mouseX, y: mouseY }, 100, 100);
  e2.push(e);
  pop();

  light.push(createVector(mouseX, mouseY));
  pgPos.push(createVector(mouseX, mouseY));

}

function draw() {
  image(img, 0, 0);

  push();
  var e1 = g.rect({ x: width / 2, y: height / 2 }, width, height);
  let pathD = g.compound(e1, e2, 'difference');
  pathD.fill = "rgb(30, 30, 30)";
  pathD.draw(drawingContext);
  pop();

  for (i = 0; i < light.length; i++) {
    noStroke();
    fill(255, 255, 102);
    circle(light[i].x, light[i].y, 30);
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdn.rawgit.com/nodebox/g.js/master/dist/g.min.js"></script></code>```

答:
The p5.js filter() function seems to apply to the current content of the canvas (and is also very slow). However you can use the native CanvasRenderingContext2D.filter property to achieve the effect you want:

```<code>drawingContext.filter = 'blur(20px)';
// draw things you want to be blurred
drawingContext.filter = 'none';
</code>```

var e2 = [];
var light = [];
var img;
var pg;
var pgPos = [];

function preload() {
  img = loadImage("https://2328a0b8-e236-4076-9848-a3275ab1c3e3.id.repl.co/map%20test.jpg");
}

function setup() {
  createCanvas(600, 600);

  background(100, 100, 100);
  pg = createGraphics(600, 600);

}

function mouseClicked() {

  push();
  let e = g.ellipse({ x: mouseX, y: mouseY }, 100, 100);
  e2.push(e);
  pop();

  light.push(createVector(mouseX, mouseY));
  pgPos.push(createVector(mouseX, mouseY));

}

function draw() {
  image(img, 0, 0);

  push();
  drawingContext.filter = 'blur(20px)';
  var e1 = g.rect({ x: width / 2, y: height / 2 }, width, height);
  let pathD = g.compound(e1, e2, 'difference');
  pathD.fill = "rgb(30, 30, 30)";
  pathD.draw(drawingContext);
  drawingContext.filter = 'none';
  pop();

  for (i = 0; i < light.length; i++) {
    noStroke();
    fill(255, 255, 102);
    circle(light[i].x, light[i].y, 30);
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdn.rawgit.com/nodebox/g.js/master/dist/g.min.js"></script></code>```

Body:
The p5.js filter() function seems to apply to the current content of the canvas (and is also very slow). However you can use the native CanvasRenderingContext2D.filter property to achieve the effect you want:

drawingContext.filter = 'blur(20px)';
// draw things you want to be blurred
drawingContext.filter = 'none';

var e2 = [];
var light = [];
var img;
var pg;
var pgPos = [];

function preload() {
  img = loadImage("https://2328a0b8-e236-4076-9848-a3275ab1c3e3.id.repl.co/map%20test.jpg");
}

function setup() {
  createCanvas(600, 600);

  background(100, 100, 100);
  pg = createGraphics(600, 600);

}

function mouseClicked() {

  push();
  let e = g.ellipse({ x: mouseX, y: mouseY }, 100, 100);
  e2.push(e);
  pop();

  light.push(createVector(mouseX, mouseY));
  pgPos.push(createVector(mouseX, mouseY));

}

function draw() {
  image(img, 0, 0);

  push();
  drawingContext.filter = 'blur(20px)';
  var e1 = g.rect({ x: width / 2, y: height / 2 }, width, height);
  let pathD = g.compound(e1, e2, 'difference');
  pathD.fill = "rgb(30, 30, 30)";
  pathD.draw(drawingContext);
  drawingContext.filter = 'none';
  pop();

  for (i = 0; i < light.length; i++) {
    noStroke();
    fill(255, 255, 102);
    circle(light[i].x, light[i].y, 30);
  }

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdn.rawgit.com/nodebox/g.js/master/dist/g.min.js"></script>


问:
BitBucket: Host key verification failed
I want to clone a remote repository to my local machine. I used the command:

```<code>git clone git@bitbucket.org:<username>/<repo_name>.git
</code>```

and I got the message:

```<code>The authenticity of host 'bitbucket.org (104.192.143.3)' can't be
established. RSA key fingerprint is
SHA256:****. Are you sure you
want to continue connecting (yes/no)?  Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository
exists.
</code>```

I just want to mention that I already took care of the ssh issues. I generated an ssh key by the command 'ssh-keygen' and I copied the contents of ~/.ssh/id_rsa.pub to Bitbucket Settings -> SSH keys (according to this link: https://confluence.atlassian.com/bitbucket/set-up-ssh-for-git-728138079.html)

I also looked at my "user and group access" and I saw this:

Can you advise me what to do?

答:
You'll get the same error:

```<code>Host key verification failed.
</code>```

in case you press enter instead of answering the question:

```<code>Are you sure you want to continue connecting (yes/no/[fingerprint])?
</code>```

with yes

Title: BitBucket: Host key verification failed

Body:
I want to clone a remote repository to my local machine. I used the command:

git clone git@bitbucket.org:<username>/<repo_name>.git

and I got the message:

The authenticity of host 'bitbucket.org (104.192.143.3)' can't be
established. RSA key fingerprint is
SHA256:****. Are you sure you
want to continue connecting (yes/no)?  Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository
exists.

I just want to mention that I already took care of the ssh issues. I generated an ssh key by the command 'ssh-keygen' and I copied the contents of ~/.ssh/id_rsa.pub to Bitbucket Settings -> SSH keys (according to this link: https://confluence.atlassian.com/bitbucket/set-up-ssh-for-git-728138079.html)

I also looked at my "user and group access" and I saw this:

Can you advise me what to do?

Body:
You'll get the same error:

Host key verification failed.

in case you press enter instead of answering the question:

Are you sure you want to continue connecting (yes/no/[fingerprint])?

with yes


问:
Spring WebFlux - Add a wrapping class before serialization
I'm developing APIs for an exam project, but I wanted their responses to be consistently  using a wrapping class on all of them (Telegram Bot API style for those who know them).

So, for example, having these two classes:

public class User {
    public int id;
    public String name;
}

public class Item {
    public int id;
    public String itemName;
    public User owner;
}
```
<p>What Spring returns to me is this output:</p>
<pre class="lang-json prettyprint-override"><code>{
    "id": 1,
    "itemName": "theItem",
    "owner": {
        "id": 2,
        "name": "theUser"
    }
}
</code>```

What I want instead is for this output to be returned:

{
    "ok": true,
    "data": {
        "id": 1,
        "itemName": "theItem",
        "owner": {
            "id": 2,
            "name": "theUser"
        }
    }
}
```
<p>Maybe using a class wrapper like this:</p>
<pre class="lang-java prettyprint-override"><code>public class ResponseWrapper<T> {
    public boolean ok;
    public T data;
}
</code>```

Is it possible to do this?

答:
I thank @JustinMathew for the help, at the end, in my case (using Spring WebFlux with Kotlin), the ResponseBodyResultHandler class was more useful to me.

// File: /MicroserviceApplication.kt

@SpringBootApplication
class MicroserviceApplication {
    @Autowired
    lateinit var serverCodecConfigurer: ServerCodecConfigurer

    @Autowired
    lateinit var requestedContentTypeResolver: RequestedContentTypeResolver

    @Bean
    fun responseWrapper(): ResponseWrapper = ResponseWrapper(
        serverCodecConfigurer.writers, requestedContentTypeResolver
    )
}
```
<pre class="lang-kotlin prettyprint-override"><code>// File: /wrapper/model/Response.kt

data class Response<T>(
    val ok: Boolean,
    val data: T?,
    val error: Error? = null
) {
    data class Error(
        val value: HttpStatus,
        val message: String?
    )
}
</code>```

// File: /wrapper/ResponseWrapper.kt

class ResponseWrapper(writers: List<HttpMessageWriter<*>>, resolver: RequestedContentTypeResolver) :
    ResponseBodyResultHandler(writers, resolver) {

    override fun supports(result: HandlerResult): Boolean =
        (result.returnType.resolve() == Mono::class.java)
                || (result.returnType.resolve() == Flux::class.java)

    @Throws(ClassCastException::class)
    override fun handleResult(exchange: ServerWebExchange, result: HandlerResult): Mono<Void> {
        val body = when (val value = result.returnValue) {
            is Mono<*> -> value
            is Flux<*> -> value.collectList()
            else -> throw ClassCastException("The \"body\" should be Mono<*> or Flux<*>!")
        }
        .map { r -> Response(true, r, null) }
        .onErrorMap { e ->
                if (e !is Response.Error)
                    Response.Error(HttpStatus.INTERNAL_SERVER_ERROR, "Internal Server Error")
                else e
            }
        .onErrorResume { e -> Mono.just(Response(false, null, e as Response.Error)) }

        return writeBody(body, returnType, exchange)
    }

    companion object {
        @JvmStatic
        private fun methodForReturnType(): Mono<Response<Any>>? = null

        private val returnType: MethodParameter = MethodParameter(
            ResponseWrapper::class.java.getDeclaredMethod("methodForReturnType"), -1
        )
    }
```

Edit: I made of this answer a library for Spring WebFlux 2.7.3 here.

P.S. I also took a cue from this other question, which faces the same problem but with Java.

Body:
I'm developing APIs for an exam project, but I wanted their responses to be consistently  using a wrapping class on all of them (Telegram Bot API style for those who know them).

So, for example, having these two classes:

public class User {
    public int id;
    public String name;
}

public class Item {
    public int id;
    public String itemName;
    public User owner;
}

What Spring returns to me is this output:

{
    "id": 1,
    "itemName": "theItem",
    "owner": {
        "id": 2,
        "name": "theUser"
    }
}

What I want instead is for this output to be returned:

{
    "ok": true,
    "data": {
        "id": 1,
        "itemName": "theItem",
        "owner": {
            "id": 2,
            "name": "theUser"
        }
    }
}

Maybe using a class wrapper like this:

public class ResponseWrapper<T> {
    public boolean ok;
    public T data;
}

Is it possible to do this?

Body:
I thank @JustinMathew for the help, at the end, in my case (using Spring WebFlux with Kotlin), the ResponseBodyResultHandler class was more useful to me.

// File: /MicroserviceApplication.kt

@SpringBootApplication
class MicroserviceApplication {
    @Autowired
    lateinit var serverCodecConfigurer: ServerCodecConfigurer

    @Autowired
    lateinit var requestedContentTypeResolver: RequestedContentTypeResolver

    @Bean
    fun responseWrapper(): ResponseWrapper = ResponseWrapper(
        serverCodecConfigurer.writers, requestedContentTypeResolver
    )
}

// File: /wrapper/model/Response.kt

data class Response<T>(
    val ok: Boolean,
    val data: T?,
    val error: Error? = null
) {
    data class Error(
        val value: HttpStatus,
        val message: String?
    )
}

// File: /wrapper/ResponseWrapper.kt

class ResponseWrapper(writers: List<HttpMessageWriter<*>>, resolver: RequestedContentTypeResolver) :
    ResponseBodyResultHandler(writers, resolver) {

    override fun supports(result: HandlerResult): Boolean =
        (result.returnType.resolve() == Mono::class.java)
                || (result.returnType.resolve() == Flux::class.java)

    @Throws(ClassCastException::class)
    override fun handleResult(exchange: ServerWebExchange, result: HandlerResult): Mono<Void> {
        val body = when (val value = result.returnValue) {
            is Mono<*> -> value
            is Flux<*> -> value.collectList()
            else -> throw ClassCastException("The \"body\" should be Mono<*> or Flux<*>!")
        }
        .map { r -> Response(true, r, null) }
        .onErrorMap { e ->
                if (e !is Response.Error)
                    Response.Error(HttpStatus.INTERNAL_SERVER_ERROR, "Internal Server Error")
                else e
            }
        .onErrorResume { e -> Mono.just(Response(false, null, e as Response.Error)) }

        return writeBody(body, returnType, exchange)
    }

    companion object {
        @JvmStatic
        private fun methodForReturnType(): Mono<Response<Any>>? = null

        private val returnType: MethodParameter = MethodParameter(
            ResponseWrapper::class.java.getDeclaredMethod("methodForReturnType"), -1
        )
    }

Edit: I made of this answer a library for Spring WebFlux 2.7.3 here.

P.S. I also took a cue from this other question, which faces the same problem but with Java.


问:
Cannot get OAuth access token using the Twitter API
I'm creating a web app that will use Twitter API's and OAuth so that my app can post to my users twitter accounts.

Here is where I'm at so far - I get to the twitter authorization page.

Authorize the app to be able to post to my twitter account, which sends me to my callback file.

Get the oath_token and oauth_verifier info.

That's where I'm stuck. I CAN NOT seem to get the access token. Here is my callback code:

```<code>include 'db.php';
include 'EpiCurl.php';
include 'EpiOAuth.php';
include 'EpiTwitter.php';
include 'secret.php';

$Twitter = new EpiTwitter($consumerKey, $consumerSecret);

// user comes from twitter
$Twitter->setToken($_GET['oauth_token']);
$token = $Twitter->getAccessToken();
setcookie('oauth_token', $token->oauth_token);
setcookie('oauth_token_secret', $token->oauth_token_secret);
$Twitter->setToken($token->oauth_token, $token->oauth_token_secret);
</code>```

I've been researching and testing for about 5 hours and still nothing. I have tried to echo $token and it just comes out empty.

Am I missing something big here? seems like an easy task..? Thank you so much for any help :))))

答:
Try this:

```<code>  $Twitter = new EpiTwitter($consumerKey, $consumerSecret);

  // user comes from twitter
  $Twitter->setToken($_GET['oauth_token']);

  $oauth_verifier = $_GET['oauth_verifier'];
  $token = $Twitter->getAccessToken(array('oauth_verifier' => $oauth_verifier));

  $Twitter->setToken($token->oauth_token, $token->oauth_token_secret);

  $creds = $Twitter->get('/account/verify_credentials.json');
</code>```

Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a web app that will use Twitter API's and OAuth so that my app can post to my users twitter accounts.

Here is where I'm at so far - I get to the twitter authorization page.

Authorize the app to be able to post to my twitter account, which sends me to my callback file.

Get the oath_token and oauth_verifier info.

That's where I'm stuck. I CAN NOT seem to get the access token. Here is my callback code:

include 'db.php';
include 'EpiCurl.php';
include 'EpiOAuth.php';
include 'EpiTwitter.php';
include 'secret.php';

$Twitter = new EpiTwitter($consumerKey, $consumerSecret);

// user comes from twitter
$Twitter->setToken($_GET['oauth_token']);
$token = $Twitter->getAccessToken();
setcookie('oauth_token', $token->oauth_token);
setcookie('oauth_token_secret', $token->oauth_token_secret);
$Twitter->setToken($token->oauth_token, $token->oauth_token_secret);

I've been researching and testing for about 5 hours and still nothing. I have tried to echo $token and it just comes out empty.

Am I missing something big here? seems like an easy task..? Thank you so much for any help :))))

Body:
Try this:

  $Twitter = new EpiTwitter($consumerKey, $consumerSecret);

  // user comes from twitter
  $Twitter->setToken($_GET['oauth_token']);

  $oauth_verifier = $_GET['oauth_verifier'];
  $token = $Twitter->getAccessToken(array('oauth_verifier' => $oauth_verifier));

  $Twitter->setToken($token->oauth_token, $token->oauth_token_secret);

  $creds = $Twitter->get('/account/verify_credentials.json');

Hope it helps.


问:
Combining ResourceT with bracket in a streaming pipeline
Here a simplification of my code:

import Database.PostgreSQL.Simple (Connection)
import qualified Streaming.Prelude as S
import Streaming.ByteString.Char8 as C
import Streaming.Zip (gunzip)
import Streaming

main :: IO ()
main = do
  res <- runResourceT $ calculateA myLinesStream
  return ()

type MyLinesStream m r = S.Stream (S.Of String) m r

connect :: IO Connection
connect = undefined

close :: Connection -> IO ()
close = undefined

calculateA :: MonadIO m => MyLinesStream m r -> m ()
calculateA stream = liftIO (bracket connect close (go stream))
  where
    go :: MonadIO m => MyLinesStream m r -> Connection -> m ()
    go stream conn = stream & S.length_ >>= liftIO . print

myLinesStream :: (MonadIO m, MonadResource m) => MyLinesStream m ()
myLinesStream = do
  S.each ["1.zip", "2.zip"]
    & S.mapM (\fileName -> C.readFile fileName & gunzip)
    & S.mconcat
    & C.lines
    & mapsM (S.toList . C.unpack)
    & void
```
<p>There is a type error on the following line on the <code>go stream</code>:</p>
<pre class="lang-hs prettyprint-override"><code>calculateA stream = liftIO (bracket connect close (go stream))
</code>```

The error says:

```<code>Couldn't match type ‘m’ with ‘IO’
  ‘m’ is a rigid type variable bound by
    the type signature for:
      calculateA :: forall (m :: * -> *) r.
                    MonadIO m =>
                    MyLinesStream m r -> m ()
Expected type: Connection -> IO ()
    Actual type: Connection -> m ()
</code>```

Questions

What to do to make this code typecheck and still make it secure for releasing resources in the calculateA function?

I'm reading multiple files using C.readFile and then wrapping it inside runResourceT. Will this properly release all the file handles?

Is the composition good? (Note that I need the calculateA function separately from the myLinesStream)

答:
The problem is that you are trying to use bracket with a monad that is too general. bracket has signature:

```<code>bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
</code>```

It takes IO actions as parameters. However, the go function that you pass to bracket needs to work in a generic base monad m chosen by the caller of calculateA (you later make that monad be ResourceT IO in main).

The bracket from base and ResourceT don't mix very well. Instead, you need to turn to special functions from the resourcet package like allocate and release, and use them to define a helper like:

```<code>bracketStream :: (Functor f, MonadResource m)
              => IO a
              -> (a -> IO ())
              -> (a -> Stream f m b)
              -> Stream f m b
bracketStream alloc free inside = do
        (key, seed) <- lift (allocate alloc free)
        r <- inside seed
        release key
        pure r
</code>```

How does it work? If you have a stream of Xs, it prepends an allocation action at the beginning of the stream (registering the corresponding cleanup action to be called in case of abnormal termination, like exceptions) and it also adds an explicit call to the cleanup action when the stream is exhausted:

(allocate+register cleanup) X X X ... X (cleanup)

You wrote:

I'm reading multiple files using C.readFile and then wrapping it
inside runResourceT. Will this properly release all the file handles?

Yes. With ResourceT, resources are freed either when an explicit cleanup action is performed, or when when we "exit" the ResourceT with runResourceT (perhaps abnormally, with an exception).

So, if we read a stream of Xs followed by a stream of Ys, we would have:

```<code>(allocate+register cleanup) X X X ... X (cleanup) (allocate+register cleanup) Y Y Y ... Y (cleanup)
</code>```

That is, the resource that produces Xs would be released before allocating the resource that produces Ys.

Body:
Here a simplification of my code:

import Database.PostgreSQL.Simple (Connection)
import qualified Streaming.Prelude as S
import Streaming.ByteString.Char8 as C
import Streaming.Zip (gunzip)
import Streaming

main :: IO ()
main = do
  res <- runResourceT $ calculateA myLinesStream
  return ()

type MyLinesStream m r = S.Stream (S.Of String) m r

connect :: IO Connection
connect = undefined

close :: Connection -> IO ()
close = undefined

calculateA :: MonadIO m => MyLinesStream m r -> m ()
calculateA stream = liftIO (bracket connect close (go stream))
  where
    go :: MonadIO m => MyLinesStream m r -> Connection -> m ()
    go stream conn = stream & S.length_ >>= liftIO . print

myLinesStream :: (MonadIO m, MonadResource m) => MyLinesStream m ()
myLinesStream = do
  S.each ["1.zip", "2.zip"]
    & S.mapM (\fileName -> C.readFile fileName & gunzip)
    & S.mconcat
    & C.lines
    & mapsM (S.toList . C.unpack)
    & void

There is a type error on the following line on the go stream:

calculateA stream = liftIO (bracket connect close (go stream))

The error says:

Couldn't match type ‘m’ with ‘IO’
  ‘m’ is a rigid type variable bound by
    the type signature for:
      calculateA :: forall (m :: * -> *) r.
                    MonadIO m =>
                    MyLinesStream m r -> m ()
Expected type: Connection -> IO ()
    Actual type: Connection -> m ()

Questions

What to do to make this code typecheck and still make it secure for releasing resources in the calculateA function?

I'm reading multiple files using C.readFile and then wrapping it inside runResourceT. Will this properly release all the file handles?

Is the composition good? (Note that I need the calculateA function separately from the myLinesStream)

Body:
The problem is that you are trying to use bracket with a monad that is too general. bracket has signature:

bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c

It takes IO actions as parameters. However, the go function that you pass to bracket needs to work in a generic base monad m chosen by the caller of calculateA (you later make that monad be ResourceT IO in main).

The bracket from base and ResourceT don't mix very well. Instead, you need to turn to special functions from the resourcet package like allocate and release, and use them to define a helper like:

bracketStream :: (Functor f, MonadResource m)
              => IO a
              -> (a -> IO ())
              -> (a -> Stream f m b)
              -> Stream f m b
bracketStream alloc free inside = do
        (key, seed) <- lift (allocate alloc free)
        r <- inside seed
        release key
        pure r

How does it work? If you have a stream of Xs, it prepends an allocation action at the beginning of the stream (registering the corresponding cleanup action to be called in case of abnormal termination, like exceptions) and it also adds an explicit call to the cleanup action when the stream is exhausted:

(allocate+register cleanup) X X X ... X (cleanup)

You wrote:

I'm reading multiple files using C.readFile and then wrapping it
inside runResourceT. Will this properly release all the file handles?

Yes. With ResourceT, resources are freed either when an explicit cleanup action is performed, or when when we "exit" the ResourceT with runResourceT (perhaps abnormally, with an exception).

So, if we read a stream of Xs followed by a stream of Ys, we would have:

(allocate+register cleanup) X X X ... X (cleanup) (allocate+register cleanup) Y Y Y ... Y (cleanup)

That is, the resource that produces Xs would be released before allocating the resource that produces Ys.


问:
Execute a query string as part of a hard-coded statement
I have a very long stored procedure that runs a select statement. The statement I would like to add at the end would work in a query string. Is it possible to execute a query string as part of a hard-coded statement in SQL Server?</p>
```<code>SELECT *
FROM INV_DATA
WHERE 1 = 1
  AND MY_ID =

SET @SQL = @SQL + ' SELECT id FROM people WHERE id =
    CASE WHEN NOT EXISTS (SELECT ... WHERE storeID = (CASE WHEN ...@ACT_METHOD = ...)) AND ...'
</code>```

答:
It's not possible the way you are trying to do it.

Another way to achieve the same result would be:

I am assuming , the last statement you want to add to existing procedure must have some dynamic criteria but it will always return a list of IDs.

So write a dynamic SQL to select all Ids and put the result in a temp table.

Declare @sql varchar(2000) @sql = ''Select Id from ....'. -- put your query which you want to add to procedure here.

```<code>Create table #temp ( Id int)

Insert into #temp Exec(@sql)
</code>```

Now use this #temp table as a join to existing select query in proc.

```<code>Select *
From INV_DATA a
Join #temp b On a MY_ID = b.id
Where 1=1
</code>```

Body:
I have a very long stored procedure that runs a select statement. The statement I would like to add at the end would work in a query string. Is it possible to execute a query string as part of a hard-coded statement in SQL Server?

SELECT *
FROM INV_DATA
WHERE 1 = 1
  AND MY_ID =

SET @SQL = @SQL + ' SELECT id FROM people WHERE id =
    CASE WHEN NOT EXISTS (SELECT ... WHERE storeID = (CASE WHEN ...@ACT_METHOD = ...)) AND ...'

Body:
It's not possible the way you are trying to do it.

Another way to achieve the same result would be:

I am assuming , the last statement you want to add to existing procedure must have some dynamic criteria but it will always return a list of IDs.

So write a dynamic SQL to select all Ids and put the result in a temp table.

Declare @sql varchar(2000) @sql = ''Select Id from ....'. -- put your query which you want to add to procedure here.

Create table #temp ( Id int)

Insert into #temp Exec(@sql)

Now use this #temp table as a join to existing select query in proc.

Select *
From INV_DATA a
Join #temp b On a MY_ID = b.id
Where 1=1


问:
How to ssh from one server to multiple server and switch to root and then change root password
From server A, i want to ssh multiple server using a non root user as direct root login is disabled to all server.

then i need to su - to switch to root

perform some normal operations, like changing directory, listing file etc.

and at the end change the root password using passwd command

I have expect installed on all servers and i am able to ssh from server A to any of the other servers but stuck in switching to root user and performing other operations as listed above.

```<code>#!/bin/bash
ssh user@ip<<'ENDSSH'
./su2root
#random operations
pwd
whoami
#random operations
./changepass
ENDSSH
</code>```

su2root

```<code>#!/usr/bin/expect -f
spawn su -
set password "rootpass"
expect "assword:"
send "$password\r"
</code>```

changepass

```<code>#!/usr/bin/expect -f
set newpassword "newrootpass"
spawn passwd
expect "*assword*"
send "$newpassword\r"
expect "*assword*"
send "$newpassword\r"
expect eof
exit 0
</code>```

expecting to accomplish it using shell scripting only. Thanks in advance.

答:
My initial comment on your question noted that you should be looking into running expect locally and spawning ssh sessions to the remote servers.

While not exactly answering your question, here is a simple expect script that logs into a remote system (one of my systems at home named valhalla), uses sudo -i to become root and executes the id command to show the user UID/GIDs. Note that I use ssh keys for logins which is why there is no expect for the initial login password.

The remote systems do not need expect in this example.

```<code>#!/usr/bin/expect
# vi: set ts=2 sw=2 noai ic showmode showmatch:

spawn ssh valhalla
expect "valhalla:"
send "sudo -i\r"
expect "assword for *"
send "XXXXXX\r"
expect "# "
send "id\r"
expect "(root)"
exit 0
</code>```

Body:
From server A, i want to ssh multiple server using a non root user as direct root login is disabled to all server.

then i need to su - to switch to root

perform some normal operations, like changing directory, listing file etc.

and at the end change the root password using passwd command

I have expect installed on all servers and i am able to ssh from server A to any of the other servers but stuck in switching to root user and performing other operations as listed above.

#!/bin/bash
ssh user@ip<<'ENDSSH'
./su2root
#random operations
pwd
whoami
#random operations
./changepass
ENDSSH

su2root

#!/usr/bin/expect -f
spawn su -
set password "rootpass"
expect "assword:"
send "$password\r"

changepass

#!/usr/bin/expect -f
set newpassword "newrootpass"
spawn passwd
expect "*assword*"
send "$newpassword\r"
expect "*assword*"
send "$newpassword\r"
expect eof
exit 0

expecting to accomplish it using shell scripting only. Thanks in advance.

Body:
My initial comment on your question noted that you should be looking into running expect locally and spawning ssh sessions to the remote servers.

While not exactly answering your question, here is a simple expect script that logs into a remote system (one of my systems at home named valhalla), uses sudo -i to become root and executes the id command to show the user UID/GIDs. Note that I use ssh keys for logins which is why there is no expect for the initial login password.

The remote systems do not need expect in this example.

#!/usr/bin/expect
# vi: set ts=2 sw=2 noai ic showmode showmatch:

spawn ssh valhalla
expect "valhalla:"
send "sudo -i\r"
expect "assword for *"
send "XXXXXX\r"
expect "# "
send "id\r"
expect "(root)"
exit 0


问:
How can I keep image and lens rotation synchronized with BlowupJS?
I used the blowup.js plugin as a base, and I am trying to rotate the image, and the lens to follow the rotation. But it is not working.

When I put the rotate(180deg) for example, the lens and the image are mismatched, if I remove the rotate(180deg) they are aligned.

Anybody know how to help me?

sample in JSFiddle

var $element = $('#target');
$element.css({
  'transform': 'rotate(180deg)'
}); // rotate imagem in html

// Constants
var $IMAGE_URL = $element.attr("src");
var NATIVE_IMG = new Image();
NATIVE_IMG.src = $element.attr("src");

var lens = document.createElement("div");
lens.id = "BlowupLens";
$("body").append(lens);
$blowupLens = $("#BlowupLens");

$blowupLens.css({
  "position": "absolute",
  "display": "none",
  "pointer-events": "none",
  "zIndex": 999999,
  "width": 200,
  "height": 200,
  "border": "6px solid #FFF",
  "background": "#FFF",
  "border-radius": "50%",
  "box-shadow": "0 8px 17px 0 rgba(0, 0, 0, 0.2)",
  "background-repeat": "no-repeat",
});

// Show magnification lens
$element.mouseenter(function() {
  $blowupLens.css("display", "block");
});

// Mouse motion on image
$element.mousemove(function(e) {

  // Lens position coordinates
  var lensX = e.pageX - (200 / 2);
  var lensY = e.pageY - (200 / 2);

  var width = $element.width();
  var height = $element.height();

  // Relative coordinates of image
  var relX = e.pageX - $('#target').offset().left;
  var relY = e.pageY - $('#target').offset().top;

  // Zoomed image coordinates
  var zoomX = -Math.floor(relX / width * (NATIVE_IMG.width) - 200 / 2);
  var zoomY = -Math.floor(relY / height * (NATIVE_IMG.height) - 200 / 2);

  var backPos = zoomX + "px " + zoomY + "px";
  var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";

  // Apply styles to lens
  $blowupLens.css({
    left: lensX,
    top: lensY,
    "background-image": "url(" + encodeURI($IMAGE_URL) + ")",
    "background-size": backgroundSize,
    "background-position": backPos,
    "transform": "rotate(180deg)" //rotate the image original
  });
})

// Hide magnification lens
$element.mouseleave(function() {
  $blowupLens.css("display", "none");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#target {
  margin-left: 160px;
  width: 700;
  height: 500px;
}</code>```

```

答:
You might rotate the lens in the opposite direction (-180deg) and inverse background position too:

Side note: you don't want to apply background-image on every mousemove, move it to the lens init.

var $element = $('#target');
$element.css({
  'transform': 'rotate(180deg)'
}); // rotate imagem in html

// Constants
var $IMAGE_URL = $element.attr("src");
var NATIVE_IMG = new Image();
NATIVE_IMG.src = $element.attr("src");

var lens = document.createElement("div");
lens.id = "BlowupLens";
$("body").append(lens);
$blowupLens = $("#BlowupLens");

$blowupLens.css({
  "position": "absolute",
  "display": "none",
  "pointer-events": "none",
  "zIndex": 999999,
  "width": 200,
  "height": 200,
  "border": "6px solid #FFF",
  "background": "#FFF",
  "border-radius": "50%",
  "box-shadow": "0 8px 17px 0 rgba(0, 0, 0, 0.2)",
  "background-repeat": "no-repeat",
});

// Show magnification lens
$element.mouseenter(function() {
  $blowupLens.css("display", "block");
});

// Mouse motion on image
$element.mousemove(function(e) {

  // Lens position coordinates
  var lensX = e.pageX - (200 / 2);
  var lensY = e.pageY - (200 / 2);

  var width = $element.width();
  var height = $element.height();

  // Relative coordinates of image
  var relX = e.pageX - $('#target').offset().left;
  var relY = e.pageY - $('#target').offset().top;

  // Zoomed image coordinates
  var zoomX = -Math.floor(relX / width * (NATIVE_IMG.width) - 200 / 2);
  var zoomY = -Math.floor(relY / height * (NATIVE_IMG.height) - 200 / 2);

  var backPos = "calc(100% - " + zoomX + "px) calc(100% - " + zoomY + "px)";
  var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";

  // Apply styles to lens
  $blowupLens.css({
    left: lensX,
    top: lensY,
    "background-image": "url(" + encodeURI($IMAGE_URL) + ")",
    "background-size": backgroundSize,
    "background-position": backPos,
    "transform": "rotate(-180deg)" //rotate the image original
  });
})

// Hide magnification lens
$element.mouseleave(function() {
  $blowupLens.css("display", "none");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#target {
  margin-left: 160px;
  width: 400;
  height: 250px;
}</code>```

```
</div>
</div>
</p>
<p><strong>Update:</strong>
For more general case of image rotation, I'd use an additional absolutely positioned image within the lens instead of <code>background-image</code>. It's way easier to control:</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-js lang-js prettyprint-override"><code>var $pic = $('#target');

// Constants
const lensD = 70, // lens diameter
  src = $pic.attr("src"),
  tоp = $pic.offset().top,
  lеft = $pic.offset().left;

let angle, scaleX, scaleY;

const $lens = $('<div id="lens"/>')
  .css({
    width: lensD,
    height: lensD
  })
  .appendTo('body');

const $lensImage = $(`<img src="${src}">`)
  .on('load', function() {
    scaleX = this.width / ($pic.width() || 1);
    scaleY = this.height / ($pic.height() || 1);
  })
  .appendTo($lens);

// Mouse motion on image
$pic.mousemove(function(e) {

  // Lens position
  $lens.css({
    transform: (`
      translateX(${e.pageX - lensD/2}px)
      translateY(${e.pageY - lensD/2}px)
    `)
  });

  // Zoomed image position
  $lensImage.css({
    transform: (`
      translateX(${(lеft - e.pageX) * scaleX + lensD/2}px)
      translateY(${(tоp - e.pageY) * scaleY + lensD/2}px)
      rotateZ(${angle}deg)
    `)
  });
});

// Show magnification lens
$pic.mouseenter(function() {
  $lens.css("display", "block");
});

// Hide magnification lens
$pic.mouseleave(function() {
  $lens.css("display", "none");
});

// Rotation (aux)
$('#angle')
  .on('input', function() {
    $('#a').val((angle = $(this).val()) + 'deg');
    $pic.css({
      transform: `rotateZ(${angle}deg)`
    });
    $lensImage.css({
      transform: `rotateZ(${angle}deg)`
    });
  })
  .trigger('input')
  .val();</code>```

#a {
  border: 0
}

#target,
#lens img {
  width: 200px;
  height: 100px;
  margin: 40px;
}

#lens {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  display: none;
  margin: 0;
  padding: 0;
  border: solid 3px #0003;
  border-radius: 50%;
  overflow: hidden;
  pointer-events: none;
}

#lens img {
  position: absolute;
  width: auto;
  height: auto;
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<fieldset>
  Rotate: <input id="a" readonly><br>
  -180 <input type="range" min="-180" max="180" step="1" value="-9" id="angle"> 180
</fieldset>

<img id="target" src="https://picsum.photos/id/111/400/200"></code>```

Body:
I used the blowup.js plugin as a base, and I am trying to rotate the image, and the lens to follow the rotation. But it is not working.

When I put the rotate(180deg) for example, the lens and the image are mismatched, if I remove the rotate(180deg) they are aligned.

Anybody know how to help me?

sample in JSFiddle

var $element = $('#target');
$element.css({
  'transform': 'rotate(180deg)'
}); // rotate imagem in html

// Constants
var $IMAGE_URL = $element.attr("src");
var NATIVE_IMG = new Image();
NATIVE_IMG.src = $element.attr("src");

var lens = document.createElement("div");
lens.id = "BlowupLens";
$("body").append(lens);
$blowupLens = $("#BlowupLens");

$blowupLens.css({
  "position": "absolute",
  "display": "none",
  "pointer-events": "none",
  "zIndex": 999999,
  "width": 200,
  "height": 200,
  "border": "6px solid #FFF",
  "background": "#FFF",
  "border-radius": "50%",
  "box-shadow": "0 8px 17px 0 rgba(0, 0, 0, 0.2)",
  "background-repeat": "no-repeat",
});

// Show magnification lens
$element.mouseenter(function() {
  $blowupLens.css("display", "block");
});

// Mouse motion on image
$element.mousemove(function(e) {

  // Lens position coordinates
  var lensX = e.pageX - (200 / 2);
  var lensY = e.pageY - (200 / 2);

  var width = $element.width();
  var height = $element.height();

  // Relative coordinates of image
  var relX = e.pageX - $('#target').offset().left;
  var relY = e.pageY - $('#target').offset().top;

  // Zoomed image coordinates
  var zoomX = -Math.floor(relX / width * (NATIVE_IMG.width) - 200 / 2);
  var zoomY = -Math.floor(relY / height * (NATIVE_IMG.height) - 200 / 2);

  var backPos = zoomX + "px " + zoomY + "px";
  var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";

  // Apply styles to lens
  $blowupLens.css({
    left: lensX,
    top: lensY,
    "background-image": "url(" + encodeURI($IMAGE_URL) + ")",
    "background-size": backgroundSize,
    "background-position": backPos,
    "transform": "rotate(180deg)" //rotate the image original
  });
})

// Hide magnification lens
$element.mouseleave(function() {
  $blowupLens.css("display", "none");
});

#target {
  margin-left: 160px;
  width: 700;
  height: 500px;
}

Body:
You might rotate the lens in the opposite direction (-180deg) and inverse background position too:

Side note: you don't want to apply background-image on every mousemove, move it to the lens init.

var $element = $('#target');
$element.css({
  'transform': 'rotate(180deg)'
}); // rotate imagem in html

// Constants
var $IMAGE_URL = $element.attr("src");
var NATIVE_IMG = new Image();
NATIVE_IMG.src = $element.attr("src");

var lens = document.createElement("div");
lens.id = "BlowupLens";
$("body").append(lens);
$blowupLens = $("#BlowupLens");

$blowupLens.css({
  "position": "absolute",
  "display": "none",
  "pointer-events": "none",
  "zIndex": 999999,
  "width": 200,
  "height": 200,
  "border": "6px solid #FFF",
  "background": "#FFF",
  "border-radius": "50%",
  "box-shadow": "0 8px 17px 0 rgba(0, 0, 0, 0.2)",
  "background-repeat": "no-repeat",
});

// Show magnification lens
$element.mouseenter(function() {
  $blowupLens.css("display", "block");
});

// Mouse motion on image
$element.mousemove(function(e) {

  // Lens position coordinates
  var lensX = e.pageX - (200 / 2);
  var lensY = e.pageY - (200 / 2);

  var width = $element.width();
  var height = $element.height();

  // Relative coordinates of image
  var relX = e.pageX - $('#target').offset().left;
  var relY = e.pageY - $('#target').offset().top;

  // Zoomed image coordinates
  var zoomX = -Math.floor(relX / width * (NATIVE_IMG.width) - 200 / 2);
  var zoomY = -Math.floor(relY / height * (NATIVE_IMG.height) - 200 / 2);

  var backPos = "calc(100% - " + zoomX + "px) calc(100% - " + zoomY + "px)";
  var backgroundSize = NATIVE_IMG.width + "px " + NATIVE_IMG.height + "px";

  // Apply styles to lens
  $blowupLens.css({
    left: lensX,
    top: lensY,
    "background-image": "url(" + encodeURI($IMAGE_URL) + ")",
    "background-size": backgroundSize,
    "background-position": backPos,
    "transform": "rotate(-180deg)" //rotate the image original
  });
})

// Hide magnification lens
$element.mouseleave(function() {
  $blowupLens.css("display", "none");
});

#target {
  margin-left: 160px;
  width: 400;
  height: 250px;
}

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
  <img id="target" src="https://iili.io/0hL7ou.png">
</body>

Update:
For more general case of image rotation, I'd use an additional absolutely positioned image within the lens instead of background-image. It's way easier to control:

var $pic = $('#target');

// Constants
const lensD = 70, // lens diameter
  src = $pic.attr("src"),
  tоp = $pic.offset().top,
  lеft = $pic.offset().left;

let angle, scaleX, scaleY;

const $lens = $('<div id="lens"/>')
  .css({
    width: lensD,
    height: lensD
  })
  .appendTo('body');

const $lensImage = $(`<img src="${src}">`)
  .on('load', function() {
    scaleX = this.width / ($pic.width() || 1);
    scaleY = this.height / ($pic.height() || 1);
  })
  .appendTo($lens);

// Mouse motion on image
$pic.mousemove(function(e) {

  // Lens position
  $lens.css({
    transform: (`
      translateX(${e.pageX - lensD/2}px)
      translateY(${e.pageY - lensD/2}px)
    `)
  });

  // Zoomed image position
  $lensImage.css({
    transform: (`
      translateX(${(lеft - e.pageX) * scaleX + lensD/2}px)
      translateY(${(tоp - e.pageY) * scaleY + lensD/2}px)
      rotateZ(${angle}deg)
    `)
  });
});

// Show magnification lens
$pic.mouseenter(function() {
  $lens.css("display", "block");
});

// Hide magnification lens
$pic.mouseleave(function() {
  $lens.css("display", "none");
});

// Rotation (aux)
$('#angle')
  .on('input', function() {
    $('#a').val((angle = $(this).val()) + 'deg');
    $pic.css({
      transform: `rotateZ(${angle}deg)`
    });
    $lensImage.css({
      transform: `rotateZ(${angle}deg)`
    });
  })
  .trigger('input')
  .val();

#a {
  border: 0
}

#target,
#lens img {
  width: 200px;
  height: 100px;
  margin: 40px;
}

#lens {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  display: none;
  margin: 0;
  padding: 0;
  border: solid 3px #0003;
  border-radius: 50%;
  overflow: hidden;
  pointer-events: none;
}

#lens img {
  position: absolute;
  width: auto;
  height: auto;
  margin: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<fieldset>
  Rotate: <input id="a" readonly><br>
  -180 <input type="range" min="-180" max="180" step="1" value="-9" id="angle"> 180
</fieldset>

<img id="target" src="https://picsum.photos/id/111/400/200">


问:
Use 'import module' or 'from module import'?
I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python and I'm trying to start off with best practices in mind.

Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what's the best way to avoid any gotchas down the road?

答:
My own answer to this depends mostly on first, how many different modules I'll be using.  If i'm only going to use one or two, I'll often use from ... import since it makes for fewer keystrokes in the rest of the file, but if I'm going to make use of many different modules, I prefer just import because that means that each module reference is self-documenting.  I can see where each symbol comes from without having to hunt around.

Usuaully I prefer the self documenting style of plain import and only change to from.. import when the number of times I have to type the module name grows above 10 to 20, even if there's only one module being imported.

OwnerDisplayName: kRON

ContentLicense: CC BY-SA 2.5


问:
Attaching ENI on eth0 on EC2 instance startup
I need to attach a static private IP to an instance in an ASG. Since I can't specify it in the Launch Template, I'm using a user-data script to attach an existing ENI on instance startup. It works fine with --device-index 1 but then I get a total of two IPs.

Why is it not possible to have --device-index 0 to attach only the IP address I need?

答:
According to the AWS Certified Solutions Architect Study Guide,

"Every instance must have a primary network interface"

"You can't remove the primary ENI from an instance, and you can't change its subnet."

My best guess is that by the time you run your user-data script, you already have a primary network interface attached.


问:
ConversionError: Failed to convert value(s) to axis units: '2015-01-01'
I am trying to convert values to axis units. I checked codes with similar problems but none addressed this specific challenge. As can be seen in the image below, expected plot (A) was supposed to show month (Jan, Feb etc.) on the x-axis, but it was showing dates (2015-01 etc) in plot (B).

Below is the source code, kindly assist. Thanks.

```<code>plt.rcParams["font.size"] = 18

plt.figure(figsize=(20,5))
plt.plot(df.air_temperature,label="Air temperature at Frankfurt Int. Airport in 2015")
plt.xlim(("2015-01-01","2015-12-31"))
plt.xticks(["2015-{:02d}-15".format(x) for x in range(1,13,1)],["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"])
plt.legend()
plt.ylabel("Temperature (°C)")
plt.show()

</code>```

答:
A wise way to draw the plot with datetime is to use datetime format in place of str; so, first of all, you should do this conversion:

```<code>df = pd.read_csv(r'data/frankfurt_weather.csv')
df['time'] = pd.to_datetime(df['time'], format = '%Y-%m-%d %H:%M')
</code>```

Then you can set up the plot as you please, preferably following Object Oriented Interface:

```<code>plt.rcParams['font.size'] = 18
fig, ax = plt.subplots(figsize = (20,5))

ax.plot(df['time'], df['air_temperature'], label = 'Air temperature at Frankfurt Int. Airport in 2015')

ax.legend()
ax.set_ylabel('Temperature (°C)')

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

Then you can customize:

x ticks' labels format and position with matplotlib.dates:

```<code>ax.xaxis.set_major_locator(md.MonthLocator(interval = 1))
ax.xaxis.set_major_formatter(md.DateFormatter('%b'))
</code>```

x axis limits:

```<code>ax.set_xlim([pd.to_datetime('2015-01-01', format = '%Y-%m-%d'),
             pd.to_datetime('2015-12-31', format = '%Y-%m-%d')])
</code>```

capital first letter of x ticks' labels for months' names

```<code>fig.canvas.draw()
ax.set_xticklabels([month.get_text().title() for month in ax.get_xticklabels()])
</code>```

Complete Code

```<code>import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as md

df = pd.read_csv(r'data/frankfurt_weather.csv')
df['time'] = pd.to_datetime(df['time'], format = '%Y-%m-%d %H:%M')

plt.rcParams['font.size'] = 18
fig, ax = plt.subplots(figsize = (20,5))

ax.plot(df['time'], df['air_temperature'], label = 'Air temperature at Frankfurt Int. Airport in 2015')

ax.legend()
ax.set_ylabel('Temperature (°C)')

ax.xaxis.set_major_locator(md.MonthLocator(interval = 1))
ax.xaxis.set_major_formatter(md.DateFormatter('%b'))

ax.set_xlim([pd.to_datetime('2015-01-01', format = '%Y-%m-%d'),
             pd.to_datetime('2015-12-31', format = '%Y-%m-%d')])

fig.canvas.draw()
ax.set_xticklabels([month.get_text().title() for month in ax.get_xticklabels()])

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

Body:
I am trying to convert values to axis units. I checked codes with similar problems but none addressed this specific challenge. As can be seen in the image below, expected plot (A) was supposed to show month (Jan, Feb etc.) on the x-axis, but it was showing dates (2015-01 etc) in plot (B).

Below is the source code, kindly assist. Thanks.

plt.rcParams["font.size"] = 18

plt.figure(figsize=(20,5))
plt.plot(df.air_temperature,label="Air temperature at Frankfurt Int. Airport in 2015")
plt.xlim(("2015-01-01","2015-12-31"))
plt.xticks(["2015-{:02d}-15".format(x) for x in range(1,13,1)],["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"])
plt.legend()
plt.ylabel("Temperature (°C)")
plt.show()

Body:
A wise way to draw the plot with datetime is to use datetime format in place of str; so, first of all, you should do this conversion:

df = pd.read_csv(r'data/frankfurt_weather.csv')
df['time'] = pd.to_datetime(df['time'], format = '%Y-%m-%d %H:%M')

Then you can set up the plot as you please, preferably following Object Oriented Interface:

plt.rcParams['font.size'] = 18
fig, ax = plt.subplots(figsize = (20,5))

ax.plot(df['time'], df['air_temperature'], label = 'Air temperature at Frankfurt Int. Airport in 2015')

ax.legend()
ax.set_ylabel('Temperature (°C)')

plt.show()

Then you can customize:

x ticks' labels format and position with matplotlib.dates:

ax.xaxis.set_major_locator(md.MonthLocator(interval = 1))
ax.xaxis.set_major_formatter(md.DateFormatter('%b'))

x axis limits:

ax.set_xlim([pd.to_datetime('2015-01-01', format = '%Y-%m-%d'),
             pd.to_datetime('2015-12-31', format = '%Y-%m-%d')])

capital first letter of x ticks' labels for months' names

fig.canvas.draw()
ax.set_xticklabels([month.get_text().title() for month in ax.get_xticklabels()])

Complete Code

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as md

df = pd.read_csv(r'data/frankfurt_weather.csv')
df['time'] = pd.to_datetime(df['time'], format = '%Y-%m-%d %H:%M')

plt.rcParams['font.size'] = 18
fig, ax = plt.subplots(figsize = (20,5))

ax.plot(df['time'], df['air_temperature'], label = 'Air temperature at Frankfurt Int. Airport in 2015')

ax.legend()
ax.set_ylabel('Temperature (°C)')

ax.xaxis.set_major_locator(md.MonthLocator(interval = 1))
ax.xaxis.set_major_formatter(md.DateFormatter('%b'))

ax.set_xlim([pd.to_datetime('2015-01-01', format = '%Y-%m-%d'),
             pd.to_datetime('2015-12-31', format = '%Y-%m-%d')])

fig.canvas.draw()
ax.set_xticklabels([month.get_text().title() for month in ax.get_xticklabels()])

plt.show()


问:
Gazebo how can i change model weigth during runtime?
I want to decrease model weigth in runtime. I am currently working on a plugin but it doesn't seem to work. I am using iris model with pixhawk 4 sitl. My purpose is to simulate a liquid spraying drone like firefighter. To do that I have to decrease the weigth of the drone in time. Thank you. Here is the code that I have:</p>
```<code>#include <functional>
#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/common/common.hh>

namespace gazebo
{
class joint_c : public ModelPlugin
{
public:
    void Load(physics::ModelPtr _parent, sdf::ElementPtr /*_sdf*/)
    {

        this->model = _parent;
        this->world= this->model->GetWorld();
        this->iris=this->world->ModelByName("iris");
        this->base_link = this->iris->GetLink("base_link");

        base_link->GetInertial()->SetMass(800000);    // Changing the mass

        this->updateConnection = event::Events::ConnectWorldUpdateBegin(boost::bind(&joint_c::OnUpdate, this, _1));
    }

public:
    void OnUpdate(const common::UpdateInfo &_info)
    {

    }

private:

    physics::ModelPtr model;
    physics::ModelPtr iris;
    physics::WorldPtr world;
    event::ConnectionPtr updateConnection;
    physics::LinkPtr  base_link;

};

// Register this plugin with the simulator
GZ_REGISTER_MODEL_PLUGIN(joint_c)
}
</code>```

答:
I finally figured it out.

I used base_link->GetInertial()->SetMass(new_mass); configuration in OnUpdate() function as kiner_shah told in the comments. But that only changed visual value. In order to apply the change I put base_link -> UpdateMass();

Then I add the plugin path and the plugin to the model sdf file like described in here Gazebo model plugin

Here is my code:

```<code>    #include <functional>
    #include <gazebo/gazebo.hh>
    #include <gazebo/physics/physics.hh>
    #include <gazebo/common/common.hh>
    #include <unistd.h>

    float x = 25;
    int count = 0;

    namespace gazebo
    {
      class joint_c : public ModelPlugin
      {
      public: void Load(physics::ModelPtr _parent, sdf::ElementPtr /*_sdf*/)
        {

        this->model = _parent;
        this->world= this->model->GetWorld();
        this->iris=this->world->ModelByName("iris");
        this->base_link = this->iris->GetLink("base_link");

    this->updateConnection = event::Events::ConnectWorldUpdateBegin(boost::bind(&joint_c::OnUpdate, this, _1));
    }

    public: void OnUpdate(const common::UpdateInfo &_info)
        {
          count = count + 1;
          if(count > 10000){
            x = 22;
          }
          if(count > 13000){
            x = 19;
          }
          if(count > 16000){
            x = 17;
          }
          if(count > 18000){
            x = 15;
          }
          base_link -> GetInertial() -> SetMass(x);
          base_link -> UpdateMass();
        }

      private:

          physics::ModelPtr model;
          physics::ModelPtr iris;
          physics::WorldPtr world;
          event::ConnectionPtr updateConnection;
          physics::LinkPtr  base_link;

      };

      // Register this plugin with the simulator
      GZ_REGISTER_MODEL_PLUGIN(joint_c)
    }
</code>```

Body:
I want to decrease model weigth in runtime. I am currently working on a plugin but it doesn't seem to work. I am using iris model with pixhawk 4 sitl. My purpose is to simulate a liquid spraying drone like firefighter. To do that I have to decrease the weigth of the drone in time. Thank you. Here is the code that I have:

#include <functional>
#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/common/common.hh>

namespace gazebo
{
class joint_c : public ModelPlugin
{
public:
    void Load(physics::ModelPtr _parent, sdf::ElementPtr /*_sdf*/)
    {

        this->model = _parent;
        this->world= this->model->GetWorld();
        this->iris=this->world->ModelByName("iris");
        this->base_link = this->iris->GetLink("base_link");

        base_link->GetInertial()->SetMass(800000);    // Changing the mass

        this->updateConnection = event::Events::ConnectWorldUpdateBegin(boost::bind(&joint_c::OnUpdate, this, _1));
    }

public:
    void OnUpdate(const common::UpdateInfo &_info)
    {

    }

private:

    physics::ModelPtr model;
    physics::ModelPtr iris;
    physics::WorldPtr world;
    event::ConnectionPtr updateConnection;
    physics::LinkPtr  base_link;

};

// Register this plugin with the simulator
GZ_REGISTER_MODEL_PLUGIN(joint_c)
}

Body:
I finally figured it out.

I used base_link->GetInertial()->SetMass(new_mass); configuration in OnUpdate() function as kiner_shah told in the comments. But that only changed visual value. In order to apply the change I put base_link -> UpdateMass();

Then I add the plugin path and the plugin to the model sdf file like described in here Gazebo model plugin

Here is my code:

    #include <functional>
    #include <gazebo/gazebo.hh>
    #include <gazebo/physics/physics.hh>
    #include <gazebo/common/common.hh>
    #include <unistd.h>

    float x = 25;
    int count = 0;

    namespace gazebo
    {
      class joint_c : public ModelPlugin
      {
      public: void Load(physics::ModelPtr _parent, sdf::ElementPtr /*_sdf*/)
        {

        this->model = _parent;
        this->world= this->model->GetWorld();
        this->iris=this->world->ModelByName("iris");
        this->base_link = this->iris->GetLink("base_link");

    this->updateConnection = event::Events::ConnectWorldUpdateBegin(boost::bind(&joint_c::OnUpdate, this, _1));
    }

    public: void OnUpdate(const common::UpdateInfo &_info)
        {
          count = count + 1;
          if(count > 10000){
            x = 22;
          }
          if(count > 13000){
            x = 19;
          }
          if(count > 16000){
            x = 17;
          }
          if(count > 18000){
            x = 15;
          }
          base_link -> GetInertial() -> SetMass(x);
          base_link -> UpdateMass();
        }

      private:

          physics::ModelPtr model;
          physics::ModelPtr iris;
          physics::WorldPtr world;
          event::ConnectionPtr updateConnection;
          physics::LinkPtr  base_link;

      };

      // Register this plugin with the simulator
      GZ_REGISTER_MODEL_PLUGIN(joint_c)
    }


问:
Why is there an empty line after every record when writing a CSV file?
I have some lists and want to write them in a CSV file.
Every list has 9200 items.

And every list must be a column in a CSV file.

I write this code:

```<code>file_path = os.path.join(os.path.realpath(folder_name), 'file_wanted.csv')
file_list = [list_1, list_2, list_3, list_4, list_5, list_6, list_7, list_8]
exported = zip_longest(*file_list)

with open(file_path, "w+", errors="ignore") as file:
    write = csv.writer(file)
    write.writerow(["list_1", "list_2", "list_3", "list_4", "list_5", "list_6", "list_7", "list_8"])
    write.writerows(exported)
</code>```

But I have the file like that

Is there a better way to write the code so that the extra line doesn't bloom for me after every record

答:
If there is an empty line every second line, you need to add newline='' like so:

```<code>with open(file_path,"w+",errors="ignore", newline='') as file:
</code>```

Body:
I have some lists and want to write them in a CSV file.
Every list has 9200 items.

And every list must be a column in a CSV file.

I write this code:

file_path = os.path.join(os.path.realpath(folder_name), 'file_wanted.csv')
file_list = [list_1, list_2, list_3, list_4, list_5, list_6, list_7, list_8]
exported = zip_longest(*file_list)

with open(file_path, "w+", errors="ignore") as file:
    write = csv.writer(file)
    write.writerow(["list_1", "list_2", "list_3", "list_4", "list_5", "list_6", "list_7", "list_8"])
    write.writerows(exported)

But I have the file like that

Is there a better way to write the code so that the extra line doesn't bloom for me after every record

Body:
If there is an empty line every second line, you need to add newline='' like so:

with open(file_path,"w+",errors="ignore", newline='') as file:


问:
reverse gravity : how to reset the values to their default values?
I try to create reverse gravity, and I have an issue after I click several times on the button "physics" : it is supposed to restart with the default values, but after 10 times, the balls go too fast and I don't understand why. The function works fine the first time, but then it starts to accelerate each time you click on "physics".

https://codepen.io/Arthur222/pen/QWOgMXq

```<code>let isOn = 0;
let canvas = document.getElementById("canvas");
if (canvas.getContext('2d') == null ) alert("erreur javascript");
let ctx = canvas.getContext('2d');
let velocity=1, force=1, mass = 1, radius=30;
let lastTs;

//FCN

window.addEventListener('load', ()=>{
    resize();
    window.addEventListener('resize', resize);
    createBalls();
    drawBalls();
});

// PHYSICS

let balls = [];
function createBalls(){
  for ( let i=0; i<6; i++){
    let x = radius+(i*radius*2);
    if (i>0) x = radius+(i*(radius+10)*2);
    let vel = Math.random();
    let ball = {x:x, y:250, xBase:x, yBase:250, velocity:vel, velocityBase:vel, radius:30, active:true}
    balls.push(ball);
  }
}

function startPhy1(){

  if (isOn == 1){
    console.log("canvas.width, canvas.height : "+canvas.width, canvas.height);
    ctx.clearRect(0,0,canvas.width, canvas.height);
    balls.forEach(element => {
      element.y = element.yBase;
      element.active = true;
      element.velocity = element.velocityBase;
    });
  }

  isOn = 1;
  lastTs = getTimestamp();
  runPhy();
  draw();
}

function runPhy(){
  let t = (getTimestamp() - lastTs)/1000;

  balls.forEach(element => {
    if ( element.active ){ //still below
      element.y -= element.velocity * t;
      element.velocity += ( force / mass ) * t;
      if ( element.y <= element.radius+10 ){//already on top
        element.active = false;
        element.y = element.radius;//stay on top
      }
    }
  });
  requestAnimationFrame(runPhy);

}

function getTimestamp() {
  return new Date().getTime();
}
// DRAW

function draw(){
  drawBalls();
  requestAnimationFrame(draw);
}

function drawBalls(){
  ctx.clearRect(0,0,canvas.width, canvas.height);
  for (let i=0; i< balls.length; i++){

    ctx.beginPath();
    ctx.arc(balls[i].x, balls[i].y, balls[i].radius, 0, 2 * Math.PI, false);
    ctx.strokeStyle = "green";
    ctx.lineWidth = 2;
    ctx.stroke();
  }

}

function resize(){
  ctx.canvas.width = window.innerWidth*0.7;
  ctx.canvas.height = window.innerHeight*0.9;
}
</code>```

答:
I think the problem with your code is that you are requesting the animation frame every time that the button is clicked.

I tried fixing your code without success, that's why I coded this one. Try it:

const canvas = document.getElementById('root')
const btn = document.getElementById('btn')
const ctx = canvas.getContext('2d')
const circleImage = new Image()

circleImage.src = 'https://i.stack.imgur.com/CdziF.png'

var piece = {
  image: circleImage,
  x: 100,
  y: 250,
  width: 50
}

var speed = 0
var max = 10

function gameLoop(){
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  ctx.drawImage(piece.image, piece.x, piece.y)

  speed < max ? speed += 0.1 : null

  if(piece.y > 0){
    piece.y -= speed
    piece.y < 0 ? piece.y = 0 : null // Position correction
  }
  window.requestAnimationFrame(gameLoop)   // Needed to keep looping
}

function start(){
  if(btn.value === 'start'){
    btn.value = 'restart'
    circleImage.onload = window.requestAnimationFrame(gameLoop)  // Start gameLoop()
  }
  if(btn.value === 'restart'){
    speed = 0
    piece.y = 250
  }
}

btn.addEventListener('click', start) // When btn is clicked execute start()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="btn" type="button" value="start" />
<p>
<canvas id="root" height="300" width="300" style="border:1px solid grey"></code>```

And see here what happens when the request animation frame is requested everytime the a button is clicked:

const canvas = document.getElementById('root')
const btn = document.getElementById('btn')
const ctx = canvas.getContext('2d')
const circleImage = new Image()

circleImage.src = 'https://i.stack.imgur.com/CdziF.png'

var piece = {
  image: circleImage,
  x: 100,
  y: 250,
  width: 50
}

var speed = 0
var max = 10

function gameLoop(){
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  ctx.drawImage(piece.image, piece.x, piece.y)

  speed < max ? speed += 0.1 : null

  if(piece.y > 0){
    piece.y -= speed
    piece.y < 0 ? piece.y = 0 : null // Position correction
  }
  window.requestAnimationFrame(gameLoop)   // Needed to keep looping
}

function start(){
  if(btn.value === 'start'){
    speed = 0
    piece.y = 250
    circleImage.onload = window.requestAnimationFrame(gameLoop)  // Start gameLoop()
  }
}

btn.addEventListener('click', start) // When btn is clicked execute start()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="btn" type="button" value="start" />
<p>
<canvas id="root" height="300" width="300" style="border:1px solid grey"></code>```

Body:
I try to create reverse gravity, and I have an issue after I click several times on the button "physics" : it is supposed to restart with the default values, but after 10 times, the balls go too fast and I don't understand why. The function works fine the first time, but then it starts to accelerate each time you click on "physics".

https://codepen.io/Arthur222/pen/QWOgMXq

let isOn = 0;
let canvas = document.getElementById("canvas");
if (canvas.getContext('2d') == null ) alert("erreur javascript");
let ctx = canvas.getContext('2d');
let velocity=1, force=1, mass = 1, radius=30;
let lastTs;

//FCN

window.addEventListener('load', ()=>{
    resize();
    window.addEventListener('resize', resize);
    createBalls();
    drawBalls();
});

// PHYSICS

let balls = [];
function createBalls(){
  for ( let i=0; i<6; i++){
    let x = radius+(i*radius*2);
    if (i>0) x = radius+(i*(radius+10)*2);
    let vel = Math.random();
    let ball = {x:x, y:250, xBase:x, yBase:250, velocity:vel, velocityBase:vel, radius:30, active:true}
    balls.push(ball);
  }
}

function startPhy1(){

  if (isOn == 1){
    console.log("canvas.width, canvas.height : "+canvas.width, canvas.height);
    ctx.clearRect(0,0,canvas.width, canvas.height);
    balls.forEach(element => {
      element.y = element.yBase;
      element.active = true;
      element.velocity = element.velocityBase;
    });
  }

  isOn = 1;
  lastTs = getTimestamp();
  runPhy();
  draw();
}

function runPhy(){
  let t = (getTimestamp() - lastTs)/1000;

  balls.forEach(element => {
    if ( element.active ){ //still below
      element.y -= element.velocity * t;
      element.velocity += ( force / mass ) * t;
      if ( element.y <= element.radius+10 ){//already on top
        element.active = false;
        element.y = element.radius;//stay on top
      }
    }
  });
  requestAnimationFrame(runPhy);

}

function getTimestamp() {
  return new Date().getTime();
}
// DRAW

function draw(){
  drawBalls();
  requestAnimationFrame(draw);
}

function drawBalls(){
  ctx.clearRect(0,0,canvas.width, canvas.height);
  for (let i=0; i< balls.length; i++){

    ctx.beginPath();
    ctx.arc(balls[i].x, balls[i].y, balls[i].radius, 0, 2 * Math.PI, false);
    ctx.strokeStyle = "green";
    ctx.lineWidth = 2;
    ctx.stroke();
  }

}

function resize(){
  ctx.canvas.width = window.innerWidth*0.7;
  ctx.canvas.height = window.innerHeight*0.9;
}

Body:
I think the problem with your code is that you are requesting the animation frame every time that the button is clicked.

I tried fixing your code without success, that's why I coded this one. Try it:

const canvas = document.getElementById('root')
const btn = document.getElementById('btn')
const ctx = canvas.getContext('2d')
const circleImage = new Image()

circleImage.src = 'https://i.stack.imgur.com/CdziF.png'

var piece = {
  image: circleImage,
  x: 100,
  y: 250,
  width: 50
}

var speed = 0
var max = 10

function gameLoop(){
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  ctx.drawImage(piece.image, piece.x, piece.y)

  speed < max ? speed += 0.1 : null

  if(piece.y > 0){
    piece.y -= speed
    piece.y < 0 ? piece.y = 0 : null // Position correction
  }
  window.requestAnimationFrame(gameLoop)   // Needed to keep looping
}

function start(){
  if(btn.value === 'start'){
    btn.value = 'restart'
    circleImage.onload = window.requestAnimationFrame(gameLoop)  // Start gameLoop()
  }
  if(btn.value === 'restart'){
    speed = 0
    piece.y = 250
  }
}

btn.addEventListener('click', start) // When btn is clicked execute start()

<input id="btn" type="button" value="start" />
<p>
<canvas id="root" height="300" width="300" style="border:1px solid grey">

And see here what happens when the request animation frame is requested everytime the a button is clicked:

const canvas = document.getElementById('root')
const btn = document.getElementById('btn')
const ctx = canvas.getContext('2d')
const circleImage = new Image()

circleImage.src = 'https://i.stack.imgur.com/CdziF.png'

var piece = {
  image: circleImage,
  x: 100,
  y: 250,
  width: 50
}

var speed = 0
var max = 10

function gameLoop(){
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  ctx.drawImage(piece.image, piece.x, piece.y)

  speed < max ? speed += 0.1 : null

  if(piece.y > 0){
    piece.y -= speed
    piece.y < 0 ? piece.y = 0 : null // Position correction
  }
  window.requestAnimationFrame(gameLoop)   // Needed to keep looping
}

function start(){
  if(btn.value === 'start'){
    speed = 0
    piece.y = 250
    circleImage.onload = window.requestAnimationFrame(gameLoop)  // Start gameLoop()
  }
}

btn.addEventListener('click', start) // When btn is clicked execute start()

<input id="btn" type="button" value="start" />
<p>
<canvas id="root" height="300" width="300" style="border:1px solid grey">


问:
How do I manipulate an argument with mockito
I am using junit to run a few unit tests. One of these calls a method in an object that I mock using mockito like;

```<code>@Mock
private MyClass myClass;
</code>```

I then set up mockito to do something like

```<code>Mockito.when(myClass.foo(Mockito.any()).thenReturn(bar);
</code>```

Now myClass.foo actually takes another one of my classes (say class Person) as an argument and what I would like to do is something like this

```<code>Mockito.when(myClass.foo(Person parson)).thenDo(person.setName("Name")).thenReturn(bar);
</code>```

That is of course pseudo code but I hope it illustrates what I am trying to do. Is this possible?

答:
In this case if your goal is to set field of Person object you can do that before or after the line:

```<code>Mockito.when(myClass.foo(Mockito.any()).thenReturn(bar);
</code>```

doAnswer() would help do operations based on input, but operations would be performed on copy of arguments not the original arguments.

Body:
I am using junit to run a few unit tests. One of these calls a method in an object that I mock using mockito like;

@Mock
private MyClass myClass;

I then set up mockito to do something like

Mockito.when(myClass.foo(Mockito.any()).thenReturn(bar);

Now myClass.foo actually takes another one of my classes (say class Person) as an argument and what I would like to do is something like this

Mockito.when(myClass.foo(Person parson)).thenDo(person.setName("Name")).thenReturn(bar);

That is of course pseudo code but I hope it illustrates what I am trying to do. Is this possible?

Body:
In this case if your goal is to set field of Person object you can do that before or after the line:

Mockito.when(myClass.foo(Mockito.any()).thenReturn(bar);

doAnswer() would help do operations based on input, but operations would be performed on copy of arguments not the original arguments.


问:
Android BroadcastReceiver not working after install
Greetings!  I'm working on an application that has a BroadcastReceiver listening on "android.intent.action.PHONE_STATE", which is run when the phone state is changed (I used it to run code when an incoming call is detected).  This works fine on most of my test phones, but a few don't seem to trigger the receiver at all.  However, once these problem phones are restarted everything works as expected.

Is there a reason these phones need to be restarted before the BroadcaseReceiver can pick anything up?  Is there a way I can detect if it isn't running and manually "start" the BroadcaseReceiver?  I'm stumped, so I'd appreciate any help you can offer.

Thank You.

答:
To expand on the issue: starting from Android 3.1, installed applications are put in "STOPPED" state. To invoke BroadcastReceiver(s) from stopped application an additional broadcast intent flag is required.

More details: http://developer.android.com/sdk/android-3.1.html#launchcontrols

I created FLAG_INCLUDE_STOPPED_PACKAGES constant (=32) in my application (for pre-Android 3.1) and just add it to my broadcast intent intent.addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);


问:
Pytorch Implementation of Feedforward ANN with Varying Inputs: RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
I'm trying to work with a custom Feedforward implementation that takes varying rows of the input and performs some sort of operation on it.

For example, imagine if the function, f, just sums the rows and columns of an input Tensor:

```<code>f = lambda x: torch.sum(x)  # sum across all dimensions, producing a scalar
</code>```

Now, for the input Tensor I have an (n, m) matrix and I want to map the function f over all the rows except the row under consideration. For example, here is the vanilla implementation that works:

```<code>d = []  # append the values to d
my_tensor = torch.rand(3, 5, requires_grad=True)  # = (n, m)
indices = list(range(n))  # list of indices

for i in range(n):  # loop through the indices
    curr_range = indices[:i] + indices[i+1:]  # fetch all indices except for the current one
    d.append(f(my_tensor[curr_range])  # calculate sum over all elements excluding row i
</code>```

Produces a (n, 1) matrix, which is what I want. The problem is Pytorch cannot auto-differentiate over this and I'm getting errors having to do with lack of grad because I have non-primitive Torch operations:

```<code>RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
</code>```

答: Turns out casting the output to using x = torch.tensor(d, requires_grad=True) did the trick in the feedforward.

Body:
I'm trying to work with a custom Feedforward implementation that takes varying rows of the input and performs some sort of operation on it.

For example, imagine if the function, f, just sums the rows and columns of an input Tensor:

f = lambda x: torch.sum(x)  # sum across all dimensions, producing a scalar

Now, for the input Tensor I have an (n, m) matrix and I want to map the function f over all the rows except the row under consideration. For example, here is the vanilla implementation that works:

d = []  # append the values to d
my_tensor = torch.rand(3, 5, requires_grad=True)  # = (n, m)
indices = list(range(n))  # list of indices

for i in range(n):  # loop through the indices
    curr_range = indices[:i] + indices[i+1:]  # fetch all indices except for the current one
    d.append(f(my_tensor[curr_range])  # calculate sum over all elements excluding row i

Produces a (n, 1) matrix, which is what I want. The problem is Pytorch cannot auto-differentiate over this and I'm getting errors having to do with lack of grad because I have non-primitive Torch operations:

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn