问:
How do I test and run a local version of my Discord bot while it is hosted?
I recently hosted my first Discord bot on Heroku. I am trying to update it and make some changes, but I am only getting the hosted-bot's responses on Discord. I am using Node.js to run it locally for testing. Not sure how to run a local version that doesn't interfere with the hosted version. I am working on adding embeds and it is important to see the messages from the bot on Discord in testing. Might be a dumb question, but I am fairly confused on how to do this.</p>

答:
When you are using discord.js, what you are actually programming is essentially just a set of functions that make using the discord API easier. For example, you could always use the discord API to send messages (or reactions and other interactions) to users without using discord.js, but that would be more difficult which is why we have libraries like discord.js.

Running tests using a local bot while your main bot is hosted would most likely be possible, but this could also have some unforeseen consequences depending on the actual function of the bot itself. Additionally, if you are using slash commands, you would have to register the new commands and this could mess with the hosted bot since Discord tries to alert users whenever slash commands are changed.

In summary, it very well may be possible to use a local bot even though you are hosting another version of that same bot already, but a much better option would be to either edit the source code of the bot which is being hosted, make another bot for testing purposes, or simply stop hosting the bot for a short period of time while doing tests.


来源: stackexchange

问:
Changing value of a variable based on condition in R
I am trying to change a value for a variable depending on other variables. So if value of one variable equals that of second variable then value of third variable should be multiplied by -1.

My code looks like this:

```<code>df <- df %>%
       mutate (C = case_when((A1) == (A2) & (R1) == (R2) ~ C,
                                (A1) == (R1) & (A2) == (R2) ~ (-1L)*C))
</code>```

where A1, A2, R1, R2 are character variables and C is a numerical variable.

I get

```<code>error: case_when(...)`.
must be a double vector, not a logical vector.
</code>```

If I change (-1L) to (-1) then it gives me NA for C

TIA!!

答:
Maybe the following will solve the problem.

Instead of checking the condition where there are no changes, leave only the changes condition and all others in the TRUE clause.

```<code>df <- df %>%
  mutate(
    C = case_when(
      (A1 == R1) & (A2 == R2) ~ -1L*C,
      TRUE ~ C
  ))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to change a value for a variable depending on other variables. So if value of one variable equals that of second variable then value of third variable should be multiplied by -1.

My code looks like this:

df <- df %>%
       mutate (C = case_when((A1) == (A2) & (R1) == (R2) ~ C,
                                (A1) == (R1) & (A2) == (R2) ~ (-1L)*C))

where A1, A2, R1, R2 are character variables and C is a numerical variable.

I get

error: case_when(...)`.
must be a double vector, not a logical vector.

If I change (-1L) to (-1) then it gives me NA for C

TIA!!

Body:
Maybe the following will solve the problem.

Instead of checking the condition where there are no changes, leave only the changes condition and all others in the TRUE clause.

df <- df %>%
  mutate(
    C = case_when(
      (A1 == R1) & (A2 == R2) ~ -1L*C,
      TRUE ~ C
  ))


问:
I want to hide  tag whose data-original-title="Close" after page loads but it is visible in jquery
I have a page which opens in Modal window and I want to hide  tag whose data-original-title="Close" after page loads with the following code but it doesn't work: I am using SAAS system where there is an option to open a page in MODAL window.

```<code>function startUp() {
  $("i[data-original-title='Close']").hide();
}

<body onload="startUp(); return true;">
</body>
</code>```

I tried document.addEventListener('DOMContentLoaded'... as well

答:
Your can access the data-* attribute using JQuery by using the data() method.

Have a look at the JQuery docs on this. They have plenty of examples.

EDIT

I want to hide tag whose data-original-title="Close" after page loads

You can use the document readystatechange event to hide the element that contain "Close" in the data attribute.

window.addEventListener('load', (event) => {
  $('#container div').each(function() {
    if ($(this).data('original-title') == 'Close') {
      $(this).hide();
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="container">
  <div data-original-title="Close" id="div1">Close</div>
  <div data-original-title="Close" id="div2">Close</div>
  <div data-original-title="Keep Open" id="div3">Keep Open</div>
</div></code>```

Title: I want to hide <i> tag whose data-original-title="Close" after page loads but it is visible in jquery

Body:
I have a page which opens in Modal window and I want to hide  tag whose data-original-title="Close" after page loads with the following code but it doesn't work: I am using SAAS system where there is an option to open a page in MODAL window.

function startUp() {
  $("i[data-original-title='Close']").hide();
}

I tried document.addEventListener('DOMContentLoaded'... as well

Body:
Your can access the data-* attribute using JQuery by using the data() method.

Have a look at the JQuery docs on this. They have plenty of examples.

EDIT

I want to hide tag whose data-original-title="Close" after page loads

You can use the document readystatechange event to hide the element that contain "Close" in the data attribute.

window.addEventListener('load', (event) => {
  $('#container div').each(function() {
    if ($(this).data('original-title') == 'Close') {
      $(this).hide();
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="container">
  <div data-original-title="Close" id="div1">Close</div>
  <div data-original-title="Close" id="div2">Close</div>
  <div data-original-title="Keep Open" id="div3">Keep Open</div>
</div>


问:
Strange problem with Sunspot.
I have model:

```<code>class Topic < ActiveRecord::Base
  attr_accessible :title, :description

  has_many :comments, :dependent => :destroy
end
</code>```

And:

```<code>class Comment < ActiveRecord::Base
  attr_accessible :body, :topic_id
  belongs_to :topic
end
</code>```

In my topic_spec.rb:

```<code>  it "should have the right associated comment" do
      @topic.comments.should include(@comment)
    end

    it "should destroy associated comments" do
      @topic.destroy
      Comment.find_by_id(@comment.id).should be_nil
    end
</code>```

And I receive following errors:

```<code>1)   Failure/Error: @topic.comments.should == @comment
     NameError:
       undefined method `inspect' for class `ActiveRecord::Associations::CollectionProxy'
</code>```

```<code>2) Failure/Error: Comment.find_by_id(@comment.id).should be_nil
   expected: nil
        got: #<Comment id: 1, body: "first", created_at: "2011-08-18 09:55:06", updated_at: "2011-08-18 09:55:06">
</code>```

What I doing wrong? This errors appeared after I started using sunspot.

In my topic.rb:

```<code>  searchable :auto_index => true, :auto_remove => true do
    text :title, :boost => 5
    text :description

    text :comments do
      comments.map(&:body)
    end
  end
</code>```

If I commented this lines:

```<code>#    text :comments do
#      comments.map(&:body)
#    end
</code>```

All tests successfully pass!

答:
The problem is you are comparing an array (@topic.comments) and an object (@comment) with ==. You should check if the object is contained in the array:

```<code>@topic.comments.should include(@comment)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Strange problem with Sunspot.

Body:
I have model:

class Topic < ActiveRecord::Base
  attr_accessible :title, :description

  has_many :comments, :dependent => :destroy
end

And:

class Comment < ActiveRecord::Base
  attr_accessible :body, :topic_id
  belongs_to :topic
end

In my topic_spec.rb:

  it "should have the right associated comment" do
      @topic.comments.should include(@comment)
    end

    it "should destroy associated comments" do
      @topic.destroy
      Comment.find_by_id(@comment.id).should be_nil
    end

And I receive following errors:

1)   Failure/Error: @topic.comments.should == @comment
     NameError:
       undefined method `inspect' for class `ActiveRecord::Associations::CollectionProxy'

2) Failure/Error: Comment.find_by_id(@comment.id).should be_nil
   expected: nil
        got: #<Comment id: 1, body: "first", created_at: "2011-08-18 09:55:06", updated_at: "2011-08-18 09:55:06">

What I doing wrong? This errors appeared after I started using sunspot.

In my topic.rb:

  searchable :auto_index => true, :auto_remove => true do
    text :title, :boost => 5
    text :description

    text :comments do
      comments.map(&:body)
    end
  end

If I commented this lines:

#    text :comments do
#      comments.map(&:body)
#    end

All tests successfully pass!

Body:
The problem is you are comparing an array (@topic.comments) and an object (@comment) with ==. You should check if the object is contained in the array:

@topic.comments.should include(@comment)


问:
Fibronacci sequence spitting wrong number
I have created a function that sumbs up all odd fibronacci numbers up to a given number, and for the most part it works all for except one number.  For example sumFibs(10) should return 10 becuz all Fib #s <= 10 are 1,1,3 and 5.

If I do sumFibs(75024); I get 135721 instead of the expected value is 60696. For every other number it works perfectly and am scratching my head to solve it

function sumFibs(num) {

  let thunderAss = [];
  let currDmp = 0;
  let nxtRmp = 1;
  var pushNxt = 0;
  // push into array
  for (let x = 0; x < num; x++) {
    if (x <= 1) {
      console.log("lets go");
      thunderAss.push(1); // 2l almond milk
    } else {
      thunderAss.push(thunderAss[x - 1] + thunderAss[x - 2]);
      console.log(x, " x is factor");
    }
  }
  console.log(thunderAss);

  let cuntNuts = 0;
  for (let x = 0; x < num; x++) {
    if (cuntNuts < num) {
      if (thunderAss[x] % 2 == 0) {} else {
        cuntNuts += thunderAss[x];
      }
    } else {
      break;
    }
  }
  console.log("CN: ", cuntNuts);
  return cuntNuts;
}
sumFibs(75024); // 60696 but 135721
sumFibs(4);```

答:
The condition if (cuntNuts < num) is wrong. cuntNuts is the sum of fibonacci numbers, not the fibonacci number itself. So you're stopping when the sum reaches n, not summing all the odd numbers up to n.

You should be comparing thunderAss[x] with num. And it should be <= if that number should be included in the total.

You can also put this condition into the for loop header rather than adding it as a separate check in the body.

function sumFibs(num) {

  let thunderAss = [];
  let currDmp = 0;
  let nxtRmp = 1;
  var pushNxt = 0;
  // push into array
  for (let x = 0; x < num; x++) {
    if (x <= 1) {
      console.log("lets go");
      thunderAss.push(1); // 2l almond milk
    } else {
      thunderAss.push(thunderAss[x - 1] + thunderAss[x - 2]);
      console.log(x, " x is factor");
    }
  }
  console.log(thunderAss);

  let cuntNuts = 0;
  for (let x = 0; thunderAss[x] <= num; x++) {
    if (thunderAss[x] % 2 == 0) {} else {
      cuntNuts += thunderAss[x];
    }
  }
  console.log("CN: ", cuntNuts);
  return cuntNuts;
}
sumFibs(75024); // 60696 but 135721
sumFibs(4);```


问:
Flutter Bottom Navigation Bar with conditions
I want to have a bottom navigation bar, and in the list of widgets i want to have the different screens. But to show the working screen or not i have var isWorking = prefs.getString('isWorking'), and i want that if isWorking == null to return WorkingScreen else StopWorkingScreen. From doing my research i think i have to use Future Builder, but if someone can demostrate on how to fix this issue than ill highly appreciate it. And btw im trying to have the same bottom navigation bar for WorkingScreen() and StopWorkingScreen(), so if the user is isWorking != null it will show the StopWorkingScreen(), and the bottom navigation bar at the bottom too, same with the WorkingScreen(), so the screens that are gonna be with the bottom navigation bars are WorkingScreen(), StopWorkingScreen(), ReportScreen(), ProfileScreen(), EditProfileScreen. But when the user presses the home bottom navy button it will check if the user is working or not and will show the screen. But the EditProfileScreen() is not gonna have its own bottom naby bar since is a part of the ProfileScreen so its just gonan have the same bottom navy bar as the Profile Screen. So (WorkingScreen(), StopWorkingScreen()) same bottom navy bar, (ReportsScreen()) navy second navy var, and the third is (ProfileScreen() and  EditProfileScreen()) having the same bottom navy bar</p>
```<code>class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {

  Future<Widget> isUserWorking () async{
    final prefs = await SharedPreferences.getInstance();
    var isWorking = prefs.getString('isWorking');
    if(isWorking == null){
      return const WorkingScreen();
    } else{
      return const StopWorkingScreen();
    }
  },
  int _selectedIndex = 0;
  static const TextStyle optionStyle =
  TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static List<Widget> _widgetOptions = <Widget>[
    isUserWorking(), // this is what im trying to do but getting error
    ReportsScreen(),
    ProfileScreen(),
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}
</code>```

答:
You can plug your future into a FutureBuilder like this

```<code>import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class IsUserWorking extends StatelessWidget {
  const IsUserWorking({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<SharedPreferences>(
      future: SharedPreferences.getInstance(),
      builder: (context, snapshot) {
        final isWorking = snapshot.data?.getString('isWorking');
        if(isWorking == null){
          return const WorkingScreen();
        } else{
        return const StopWorkingScreen();
        }
      },
    );
  }
}
</code>```

A simple google search also gave me this, How to change the bottom navigation bar items based on a condition in Flutter

Body:
I want to have a bottom navigation bar, and in the list of widgets i want to have the different screens. But to show the working screen or not i have var isWorking = prefs.getString('isWorking'), and i want that if isWorking == null to return WorkingScreen else StopWorkingScreen. From doing my research i think i have to use Future Builder, but if someone can demostrate on how to fix this issue than ill highly appreciate it. And btw im trying to have the same bottom navigation bar for WorkingScreen() and StopWorkingScreen(), so if the user is isWorking != null it will show the StopWorkingScreen(), and the bottom navigation bar at the bottom too, same with the WorkingScreen(), so the screens that are gonna be with the bottom navigation bars are WorkingScreen(), StopWorkingScreen(), ReportScreen(), ProfileScreen(), EditProfileScreen. But when the user presses the home bottom navy button it will check if the user is working or not and will show the screen. But the EditProfileScreen() is not gonna have its own bottom naby bar since is a part of the ProfileScreen so its just gonan have the same bottom navy bar as the Profile Screen. So (WorkingScreen(), StopWorkingScreen()) same bottom navy bar, (ReportsScreen()) navy second navy var, and the third is (ProfileScreen() and  EditProfileScreen()) having the same bottom navy bar

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {

  Future<Widget> isUserWorking () async{
    final prefs = await SharedPreferences.getInstance();
    var isWorking = prefs.getString('isWorking');
    if(isWorking == null){
      return const WorkingScreen();
    } else{
      return const StopWorkingScreen();
    }
  },
  int _selectedIndex = 0;
  static const TextStyle optionStyle =
  TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static List<Widget> _widgetOptions = <Widget>[
    isUserWorking(), // this is what im trying to do but getting error
    ReportsScreen(),
    ProfileScreen(),
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

Body:
You can plug your future into a FutureBuilder like this

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class IsUserWorking extends StatelessWidget {
  const IsUserWorking({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<SharedPreferences>(
      future: SharedPreferences.getInstance(),
      builder: (context, snapshot) {
        final isWorking = snapshot.data?.getString('isWorking');
        if(isWorking == null){
          return const WorkingScreen();
        } else{
        return const StopWorkingScreen();
        }
      },
    );
  }
}

A simple google search also gave me this, How to change the bottom navigation bar items based on a condition in Flutter


问:
Converting Metal Shader texture type from 2D to 2D Multisample
I am following a tutorial by 2etime on YouTube about Apple's Metal graphics API. Everything works as intended, but when I try to change the view's sample count, I get a lot of errors. The errors, though, are easily fixed. So far, I've changed the sample count in every file, but I am stuck at the shaders. To change the view's sample count, you have to change the texture sample count (at least in my case), and to change the texture sample count, you have to change the texture type to multisample. This is easily done. However, after this change, I get errors from the shaders. It looks like the fragment shader uses texture2d, and I need to change it to texture2d_ms, but when I do so, I get error saying that 'sample' function is not valid. I will post the code and the error. I've tried searching on the internet, but I can't seem to find anything.

FinalShaders.metal

```<code>#include <metal_stdlib>
#include "Shared.metal"
using namespace metal;

struct FinalRasterizerData {
    float4 position [[ position ]];
    float2 textureCoordinate;
};

vertex FinalRasterizerData final_vertex_shader(const VertexIn vIn [[ stage_in ]]) {
    FinalRasterizerData rd;

    rd.position = float4(vIn.position, 1.0);
    rd.textureCoordinate = vIn.textureCoordinate;

    return rd;
}

fragment half4 final_fragment_shader(const FinalRasterizerData rd [[ stage_in ]],
                                     texture2d_ms<float> baseTexture) {
    sampler s;

    float2 textureCoordinate = rd.textureCoordinate;
    textureCoordinate.y = 1 - textureCoordinate.y;

    float4 color = baseTexture.sample(s, textureCoordinate);

    return half4(color);
}
</code>```

Shared.metal

```<code>#ifndef SHARED_METAL
#define SHARED_METAL

#include <metal_stdlib>
using namespace metal;

struct VertexIn {
    float3 position [[ attribute(0) ]];
    float4 color [[ attribute(1) ]];
    float2 textureCoordinate [[ attribute(2) ]];
    float3 normal [[ attribute(3) ]];
    float3 tangent [[ attribute(4) ]];
    float3 bitangent [[ attribute(5) ]];
};

struct RasterizerData{
    float4 position [[ position ]];
    float4 color;
    float2 textureCoordinate;
    float totalGameTime;

    float3 worldPosition;
    float3 toCameraVector;

    float3 surfaceNormal;
    float3 surfaceTangent;
    float3 surfaceBitangent;
};

struct ModelConstants{
    float4x4 modelMatrix;
};

struct SceneConstants{
    float totalGameTime;
    float4x4 viewMatrix;
    float4x4 skyViewMatrix;
    float4x4 projectionMatrix;
    float3 cameraPosition;
};

struct Material {
    float4 color;
    bool isLit;
    bool useBaseTexture;
    bool useNormalMapTexture;

    float3 ambient;
    float3 diffuse;
    float3 specular;
    float shininess;
};

struct LightData {
    float3 position;
    float3 color;
    float brightness;

    float ambientIntensity;
    float diffuseIntensity;
    float specularIntensity;
};

#endif
</code>```

And the error:

No member named 'sample' in 'metal::texture2d_ms<float, metal::access::read, void>'

I know it clearly says that 'sample' is not existent, but I can't find any solution. When I removed it, and replaced the return with different value, I only see a lot of green/yellow lines, and no 3d objects. Thanks for any help!

(the shader the error is happening in is the fragment one in final shaders.metal)

答:
Sampling in a way that sample function means doesn't make sense for multisampled textures. What you are looking for instead is reading the exact sample value at a given texcoord.

If you look in the Metal Shader Language specification, in section 6.12.8 it describes which functions exist for 2D multisampled textures.

Those include:

```<code>Tv read(uint2 coord, uint sample) const
Tv read(ushort2 coord, ushort sample) const

uint get_width() const
uint get_height() const
uint get_num_samples() const
</code>```

In read function, coord means pixel coordinates, so they would go from 0 to get_width() on X axis and from 0 to get_height() on Y axis. sample is the index of the sample, so it would be from 0 to get_num_samples()

Body:
I am following a tutorial by 2etime on YouTube about Apple's Metal graphics API. Everything works as intended, but when I try to change the view's sample count, I get a lot of errors. The errors, though, are easily fixed. So far, I've changed the sample count in every file, but I am stuck at the shaders. To change the view's sample count, you have to change the texture sample count (at least in my case), and to change the texture sample count, you have to change the texture type to multisample. This is easily done. However, after this change, I get errors from the shaders. It looks like the fragment shader uses texture2d, and I need to change it to texture2d_ms, but when I do so, I get error saying that 'sample' function is not valid. I will post the code and the error. I've tried searching on the internet, but I can't seem to find anything.

FinalShaders.metal

#include <metal_stdlib>
#include "Shared.metal"
using namespace metal;

struct FinalRasterizerData {
    float4 position [[ position ]];
    float2 textureCoordinate;
};

vertex FinalRasterizerData final_vertex_shader(const VertexIn vIn [[ stage_in ]]) {
    FinalRasterizerData rd;

    rd.position = float4(vIn.position, 1.0);
    rd.textureCoordinate = vIn.textureCoordinate;

    return rd;
}

fragment half4 final_fragment_shader(const FinalRasterizerData rd [[ stage_in ]],
                                     texture2d_ms<float> baseTexture) {
    sampler s;

    float2 textureCoordinate = rd.textureCoordinate;
    textureCoordinate.y = 1 - textureCoordinate.y;

    float4 color = baseTexture.sample(s, textureCoordinate);

    return half4(color);
}

Shared.metal

#ifndef SHARED_METAL
#define SHARED_METAL

#include <metal_stdlib>
using namespace metal;

struct VertexIn {
    float3 position [[ attribute(0) ]];
    float4 color [[ attribute(1) ]];
    float2 textureCoordinate [[ attribute(2) ]];
    float3 normal [[ attribute(3) ]];
    float3 tangent [[ attribute(4) ]];
    float3 bitangent [[ attribute(5) ]];
};

struct RasterizerData{
    float4 position [[ position ]];
    float4 color;
    float2 textureCoordinate;
    float totalGameTime;

    float3 worldPosition;
    float3 toCameraVector;

    float3 surfaceNormal;
    float3 surfaceTangent;
    float3 surfaceBitangent;
};

struct ModelConstants{
    float4x4 modelMatrix;
};

struct SceneConstants{
    float totalGameTime;
    float4x4 viewMatrix;
    float4x4 skyViewMatrix;
    float4x4 projectionMatrix;
    float3 cameraPosition;
};

struct Material {
    float4 color;
    bool isLit;
    bool useBaseTexture;
    bool useNormalMapTexture;

    float3 ambient;
    float3 diffuse;
    float3 specular;
    float shininess;
};

struct LightData {
    float3 position;
    float3 color;
    float brightness;

    float ambientIntensity;
    float diffuseIntensity;
    float specularIntensity;
};

#endif

And the error:

No member named 'sample' in 'metal::texture2d_ms<float, metal::access::read, void>'

I know it clearly says that 'sample' is not existent, but I can't find any solution. When I removed it, and replaced the return with different value, I only see a lot of green/yellow lines, and no 3d objects. Thanks for any help!

(the shader the error is happening in is the fragment one in final shaders.metal)

Body:
Sampling in a way that sample function means doesn't make sense for multisampled textures. What you are looking for instead is reading the exact sample value at a given texcoord.

If you look in the Metal Shader Language specification, in section 6.12.8 it describes which functions exist for 2D multisampled textures.

Those include:

Tv read(uint2 coord, uint sample) const
Tv read(ushort2 coord, ushort sample) const

uint get_width() const
uint get_height() const
uint get_num_samples() const

In read function, coord means pixel coordinates, so they would go from 0 to get_width() on X axis and from 0 to get_height() on Y axis. sample is the index of the sample, so it would be from 0 to get_num_samples()


问:
How to unit test an Update method with no return using xUnit
I have the follow method in the Repository class:

```<code>public async Task<int> Update(Entity entity)
{
    string sql = "UPDATE table SET name = @name";
    return await ExecuteAsync(sql, entity);
}
</code>```

So, how can I do the unit test in this method, to ensure the record has been changed in the database ? I need to use mock or don't apply in this case ?

答: Right now your code looks like untestable. To make it testable in this method you pasted, ExecuteAsync needs to be a mockable method of some interface injected in your service under test. Then after execution of Update method, you can verify that ExecuteAsync was called with the statement  "UPDATE table SET name = @name"

Body:
I have the follow method in the Repository class:

public async Task<int> Update(Entity entity)
{
    string sql = "UPDATE table SET name = @name";
    return await ExecuteAsync(sql, entity);
}

So, how can I do the unit test in this method, to ensure the record has been changed in the database ? I need to use mock or don't apply in this case ?


问:
MongoDB duplicate key in single document
relative noob.
I have a MongoDB collection, where it appears one of the keys has been duplicated within a document. The document count is 13603, but aggregating by the key and counting results in 13604. I have run this 3 times, 30 minutes apart, so I know it's not a timing issue. I am trying to find the document with the duplicate key, but don't understand aggregations enough to find it.

I found a similar thread here but I see no solution for finding the "corrupt" document within a collection.

This is NOT a duplicate key across documents or a duplicate document issue; it is a duplicate key within the same document issue. Any help is appreciated.

screen-shot comparing document count to key-aggregation count

答:
It is most probably incorrect:

```<code> db.collection.count()
</code>```

Check this ticket here

Try to count with this:

```<code>  db.collection.countDocuments({})
</code>```

The db.collection.count() is just reading the collection count metadata , it is fast but inacurate especially in sharded cluster since sometimes there is orphaned documents not updated in collection metadata , you need to clean orphans and then try again.

From the documentation:

Avoid using the db.collection.count() method without a query predicate since without the query predicate, the method returns results based on the collection's metadata, which may result in an approximate count. In particular,

On a sharded cluster, the resulting count will not correctly filter out orphaned documents.
After an unclean shutdown, the count may be incorrect.
For counts based on collection metadata, see also collStats pipeline stage with the count option.

Body:
It is most probably incorrect:

 db.collection.count()

Check this ticket here

Try to count with this:

  db.collection.countDocuments({})

The db.collection.count() is just reading the collection count metadata , it is fast but inacurate especially in sharded cluster since sometimes there is orphaned documents not updated in collection metadata , you need to clean orphans and then try again.

From the documentation:

Avoid using the db.collection.count() method without a query predicate since without the query predicate, the method returns results based on the collection's metadata, which may result in an approximate count. In particular,

On a sharded cluster, the resulting count will not correctly filter out orphaned documents.
After an unclean shutdown, the count may be incorrect.
For counts based on collection metadata, see also collStats pipeline stage with the count option.


问:
Laravel Enum casting error Call to undefined method App\\Enums\\UserType::from()
When I try to cast a attribute from my model to one of my enums, it throws an erro:

Call to undefined method App\Enums\UserType::from()

I can not find anything about the required find() method.

I followed the instructions here.

My Enum UserType:

```<code>namespace App\Enums;

enum UserType
{
    case CUSTOMER;
    case PARTNER;
    case ADMIN;
}
</code>```

And my User-model:

```<code>namespace App\Models;

use App\Enums\UserType;
use FaarenTech\LaravelCustomUuids\Interfaces\HasCustomUuidInterface;
use FaarenTech\LaravelCustomUuids\Models\UuidModel;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableInterface;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableInterface;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Auth\Authenticatable;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Auth\Passwords\CanResetPassword;

class User extends UuidModel implements
    AuthorizableInterface,
    AuthenticatableInterface,
    CanResetPasswordInterface,
    HasCustomUuidInterface
{
    use
        HasApiTokens,
        HasFactory,
        Notifiable,
        Authenticatable,
        Authorizable,
        CanResetPassword,
        MustVerifyEmail,
        SoftDeletes;

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'type' => UserType::class
    ];
}
</code>```

答:
You need to map each enum to a scalar value (int, float, string, bool), this way Laravel can convert from the (database stored) value -> enum.

e.g.

```<code>enum UserType: string
{
    case CUSTOMER = 'CUSTOMER';
    case PARTNER = 'PARTNER';
    case ADMIN = 'ADMIN';
}
</code>```

See Backed Enums in PHP:

Backed enums implement an internal BackedEnum interface, which exposes
two additional methods:

from(int|string): self will take a scalar and return the corresponding
Enum Case. If one is not found, it will throw a ValueError. This is
mainly useful in cases where the input scalar is trusted and a missing
enum value should be considered an application-stopping error.

Body:
When I try to cast a attribute from my model to one of my enums, it throws an erro:

Call to undefined method App\Enums\UserType::from()

I can not find anything about the required find() method.

I followed the instructions here.

My Enum UserType:

namespace App\Enums;

enum UserType
{
    case CUSTOMER;
    case PARTNER;
    case ADMIN;
}

And my User-model:

namespace App\Models;

use App\Enums\UserType;
use FaarenTech\LaravelCustomUuids\Interfaces\HasCustomUuidInterface;
use FaarenTech\LaravelCustomUuids\Models\UuidModel;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableInterface;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableInterface;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Auth\Authenticatable;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Auth\Passwords\CanResetPassword;

class User extends UuidModel implements
    AuthorizableInterface,
    AuthenticatableInterface,
    CanResetPasswordInterface,
    HasCustomUuidInterface
{
    use
        HasApiTokens,
        HasFactory,
        Notifiable,
        Authenticatable,
        Authorizable,
        CanResetPassword,
        MustVerifyEmail,
        SoftDeletes;

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'type' => UserType::class
    ];
}

Body:
You need to map each enum to a scalar value (int, float, string, bool), this way Laravel can convert from the (database stored) value -> enum.

e.g.

enum UserType: string
{
    case CUSTOMER = 'CUSTOMER';
    case PARTNER = 'PARTNER';
    case ADMIN = 'ADMIN';
}

See Backed Enums in PHP:

Backed enums implement an internal BackedEnum interface, which exposes
two additional methods:

from(int|string): self will take a scalar and return the corresponding
Enum Case. If one is not found, it will throw a ValueError. This is
mainly useful in cases where the input scalar is trusted and a missing
enum value should be considered an application-stopping error.


问:
Error: Invalid value for region: project: required field is not set
On GCP, I'm trying to create a Cloud Run service and a Serverless Network Endpoint Group with this Terraform code below:

provider "google" {
  credentials = file("myCredentials.json")
  project     = "myproject-813137"
  region      = "asia-northeast1"
}

resource "google_cloud_run_service" "default" {
  name     = "hello-world"
  location = "asia-northeast1"

  template {
    spec {
      containers {
        image = "gcr.io/myproject-813137/hello-world:latest"
      }
    }
  }

  traffic {
    percent         = 100
    latest_revision = true
  }
}

data "google_iam_policy" "noauth" {
  binding {
    role = "roles/run.invoker"
    members = [
      "allUsers",
    ]
  }
}

resource "google_cloud_run_service_iam_policy" "noauth" {
  location    = google_cloud_run_service.default.location
  project     = google_cloud_run_service.default.project
  service     = google_cloud_run_service.default.name

  policy_data = data.google_iam_policy.noauth.policy_data
}

resource "google_compute_region_network_endpoint_group" "cloudrun_neg" {
  provider              = google-beta
  name                  = "neg"
  network_endpoint_type = "SERVERLESS"
  region                = "asia-northeast1"
  cloud_run {
    service = google_cloud_run_service.default.name
  }
}
```

But I got this error:

Error: Invalid value for region: project: required field is not set

Are there any mistakes in my Terraform code?

答:
Remove "provider = google-beta" from "google_compute_region_network_endpoint_group":

```<code>resource "google_compute_region_network_endpoint_group" "cloudrun_neg" {
  # provider              = google-beta // Here to remove
  name                  = "neg"
  network_endpoint_type = "SERVERLESS"
  region                = "asia-northeast1"
  cloud_run {
    service = google_cloud_run_service.default.name
  }
}
</code>```

Even though you have already defined provider "google" below, you redefined "provider = google-beta" in "google_compute_region_network_endpoint_group":

provider "google" {
  credentials = file("myCredentials.json")
  project     = "myproject-813137"
  region      = "asia-northeast1"
}
```

That's why you got this error:

Error: Invalid value for region: project: required field is not set

Body:
On GCP, I'm trying to create a Cloud Run service and a Serverless Network Endpoint Group with this Terraform code below:

provider "google" {
  credentials = file("myCredentials.json")
  project     = "myproject-813137"
  region      = "asia-northeast1"
}

resource "google_cloud_run_service" "default" {
  name     = "hello-world"
  location = "asia-northeast1"

  template {
    spec {
      containers {
        image = "gcr.io/myproject-813137/hello-world:latest"
      }
    }
  }

  traffic {
    percent         = 100
    latest_revision = true
  }
}

data "google_iam_policy" "noauth" {
  binding {
    role = "roles/run.invoker"
    members = [
      "allUsers",
    ]
  }
}

resource "google_cloud_run_service_iam_policy" "noauth" {
  location    = google_cloud_run_service.default.location
  project     = google_cloud_run_service.default.project
  service     = google_cloud_run_service.default.name

  policy_data = data.google_iam_policy.noauth.policy_data
}

resource "google_compute_region_network_endpoint_group" "cloudrun_neg" {
  provider              = google-beta
  name                  = "neg"
  network_endpoint_type = "SERVERLESS"
  region                = "asia-northeast1"
  cloud_run {
    service = google_cloud_run_service.default.name
  }
}

But I got this error:

Error: Invalid value for region: project: required field is not set

Are there any mistakes in my Terraform code?

Body:
Remove "provider = google-beta" from "google_compute_region_network_endpoint_group":

resource "google_compute_region_network_endpoint_group" "cloudrun_neg" {
  # provider              = google-beta // Here to remove
  name                  = "neg"
  network_endpoint_type = "SERVERLESS"
  region                = "asia-northeast1"
  cloud_run {
    service = google_cloud_run_service.default.name
  }
}

Even though you have already defined provider "google" below, you redefined "provider = google-beta" in "google_compute_region_network_endpoint_group":

provider "google" {
  credentials = file("myCredentials.json")
  project     = "myproject-813137"
  region      = "asia-northeast1"
}

That's why you got this error:

Error: Invalid value for region: project: required field is not set


问:
Ruby on Rails - Errno::EACCES in Posts#show
I'm doing this ruby on rails tutorial - http://guides.rubyonrails.org/getting_started.html
After doing 6.4 part, I started getting this error if I try to do anything. For I get this error when trying to see a post:

Errno::EACCES in Posts#show

```<code>Showing /home/user/rails/blog/app/views/layouts/application.html.erb where line #5 raised:

 <html>
  <head>
    <title>Blog</title>
    <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
    <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
    <%= csrf_meta_tags %>
  </head>

Permission denied - /home/user/rails/blog/tmp/cache/assets/development/sass/bd7e1cc0cf5d133ac313bf5ffa5e5d87b843522a/comments.css.scssc
  (in /home/user/rails/blog/app/assets/stylesheets/comments.css.scss)

Rails.root: /home/user/rails/blog

app/views/layouts/application.html.erb:5:in `_app_views_layouts_application_html_erb__1904510075995834678_70186546148480'
Request

Parameters:

{"id"=>"1"}
</code>```

It shows that this line raised an error:

```<code><%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
</code>```

And the file that shows I was denied to access (comments.css.scss), is empty, with just three comment lines. What could be wrong here? I followed tutorial guidelines, don't know what I could have done differently.

答:
If your OS is Windows you can run this in the Windows command prompt.</p>
```<code>icacls C:\User\username\rails\blog /grant Everyone:F
</code>```

Body:
I'm doing this ruby on rails tutorial - http://guides.rubyonrails.org/getting_started.html
After doing 6.4 part, I started getting this error if I try to do anything. For I get this error when trying to see a post:

Errno::EACCES in Posts#show

Showing /home/user/rails/blog/app/views/layouts/application.html.erb where line #5 raised:

    <title>Blog</title>
    <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
    <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
    <%= csrf_meta_tags %>

Permission denied - /home/user/rails/blog/tmp/cache/assets/development/sass/bd7e1cc0cf5d133ac313bf5ffa5e5d87b843522a/comments.css.scssc
  (in /home/user/rails/blog/app/assets/stylesheets/comments.css.scss)

Rails.root: /home/user/rails/blog

app/views/layouts/application.html.erb:5:in `_app_views_layouts_application_html_erb__1904510075995834678_70186546148480'
Request

Parameters:

{"id"=>"1"}

It shows that this line raised an error:

<%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>

And the file that shows I was denied to access (comments.css.scss), is empty, with just three comment lines. What could be wrong here? I followed tutorial guidelines, don't know what I could have done differently.

Body:
If your OS is Windows you can run this in the Windows command prompt.

icacls C:\User\username\rails\blog /grant Everyone:F


问:
MS chart in crystal reports
Is is possible to include the chart image of ms chart asp.net control in crystral reports rendered in a resolution suitable for print?

My website shows an mschart and i want that same chart in my crystal report so the client can print it. I don't want to use the crystal reports chart.

答:
When you save an MS chart as an image it always comes out at 96dpi, which isn't really great if you want to print it - should be more like 300dpi.

A simple workaround is to temporarily increase the chart size before calling SaveImage().

```<code>var originalWidth = myChart.Width;
var originalHeight = myChart.Height;
myChart.Width *= 3;
myChart.Height *= 3;

myChart.SaveImage("path\to\imageFile", ChartImageFormat.Bmp);

myChart.Width = originalWidth;
myChart.Height = originalHeight;
</code>```

This results in an image 3 times the size of the original.  When shrunk to 1/3 of its size, it will have 96 x 3 = 288dpi, which looks a lot nicer when printed.

Title: MS chart in crystal reports

Body:
When you save an MS chart as an image it always comes out at 96dpi, which isn't really great if you want to print it - should be more like 300dpi.

A simple workaround is to temporarily increase the chart size before calling SaveImage().

var originalWidth = myChart.Width;
var originalHeight = myChart.Height;
myChart.Width *= 3;
myChart.Height *= 3;

myChart.SaveImage("path\to\imageFile", ChartImageFormat.Bmp);

myChart.Width = originalWidth;
myChart.Height = originalHeight;

This results in an image 3 times the size of the original.  When shrunk to 1/3 of its size, it will have 96 x 3 = 288dpi, which looks a lot nicer when printed.


问:
Find the Statistical Mode on multiple columns in Oracle
I have a Customer Location Table Like Below.

```<code>CREATE TABLE CusLoc (
  person_id   INTEGER NOT NULL PRIMARY KEY,
  Base_Location_M1 VARCHAR2(100),
  Base_Location_M2 VARCHAR2(100),
  Base_Location_M3 VARCHAR2(100),
  Base_Location_M4 VARCHAR2(100),
  Base_Location_M5 VARCHAR2(100),
  Base_Location_M6 VARCHAR2(100)
);

INSERT INTO CusLoc
VALUES (123, 'London', 'Paris', 'London', 'Paris','London', 'Spain');

INSERT INTO CusLoc
VALUES (134, 'Oslo', 'Dubai', 'Oslo', 'Dubai','Oslo', 'Dubai');
</code>```

I want to create 2 more columns. Column 'Most_Used_Base_Location_T3' and 'Most_Used_Base_Location_T6' which will calculate the statistical mode of the occurrences of the location and populate the columns at a person_id level.

For the first record, i.e person_id 123, the expected result is 'London' for Most_Used_Base_Location_T3 and 'London' as well for Most_Used_Base_Location_T6.

For the secondrecord, i.e person_id 134, the expected result is 'Oslo' for Most_Used_Base_Location_T3 and if there is a tie like in last six months, Both 'Dubai' and 'Oslo' has appeared equal number of time then
Most_Used_Base_Location_T6 should take the latest month value i.e 'Oslo'

NB: *M1 is the latest Month & M6 is the oldest
*T3 is the statistical mode of M1,M2 and M3
*T6 is the statistical mode of M1,M2,M3,M4,M5 and M6

答:
One of the easiest ways is to use unpivot + FIRST or LAST aggregate functions:

select
   v.person_id,
   max(b3)keep(dense_rank first order by cnt desc, a) Most_Used_Base_Location_T3,
   max(b)keep(dense_rank first order by cnt desc, a) Most_Used_Base_Location_T6
from (
   select
      c.*
     ,case when a in ('M1','M2','M3') then b end b3
     ,count(*)over(partition by b) cnt
   from CusLoc
   unpivot(
     b for a in (
        Base_Location_M1 as 'M1',
        Base_Location_M2 as 'M2',
        Base_Location_M3 as 'M3',
        Base_Location_M4 as 'M4',
        Base_Location_M5 as 'M5',
        Base_Location_M6 as 'M6'
     )
   ) c
) v
group by person_id
/
```
<p>DBFiddle: https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=fa2d34936824e18dff16a79bc2a19586</p>
<p><strong>Updated as per new info:</strong></p>
<p>DBFiddle</p>
```select
   v.id,
   max(b3)keep(dense_rank first order by cnt3 desc, a) Most_Used_Base_Location_T3,
   max(b)keep(dense_rank first order by cnt desc, a) Most_Used_Base_Location_T8
from (
   select
      id,a,b
     ,b3
     ,count(b3)over(partition by id,b3) cnt3
     ,count(b )over(partition by id,b) cnt
   from (
       select
           id,a
          ,nullif(b,'NA') as b
          ,case when a in ('M1','M2','M3') then nullif(b,'NA') end b3
       from test_mug1
       unpivot(
         b for a in (
            T1_MUG_Data as 'M1',
            T2_MUG_Data as 'M2',
            T3_MUG_Data as 'M3',
            T4_MUG_Data as 'M4',
            T5_MUG_Data as 'M5',
            T6_MUG_Data as 'M6',
            T7_MUG_Data as 'M7',
            T8_MUG_Data as 'M8'
         )
       )
   ) c
) v
group by id
order by id
```

Body:
I have a Customer Location Table Like Below.

CREATE TABLE CusLoc (
  person_id   INTEGER NOT NULL PRIMARY KEY,
  Base_Location_M1 VARCHAR2(100),
  Base_Location_M2 VARCHAR2(100),
  Base_Location_M3 VARCHAR2(100),
  Base_Location_M4 VARCHAR2(100),
  Base_Location_M5 VARCHAR2(100),
  Base_Location_M6 VARCHAR2(100)
);

INSERT INTO CusLoc
VALUES (123, 'London', 'Paris', 'London', 'Paris','London', 'Spain');

INSERT INTO CusLoc
VALUES (134, 'Oslo', 'Dubai', 'Oslo', 'Dubai','Oslo', 'Dubai');

I want to create 2 more columns. Column 'Most_Used_Base_Location_T3' and 'Most_Used_Base_Location_T6' which will calculate the statistical mode of the occurrences of the location and populate the columns at a person_id level.

For the first record, i.e person_id 123, the expected result is 'London' for Most_Used_Base_Location_T3 and 'London' as well for Most_Used_Base_Location_T6.

For the secondrecord, i.e person_id 134, the expected result is 'Oslo' for Most_Used_Base_Location_T3 and if there is a tie like in last six months, Both 'Dubai' and 'Oslo' has appeared equal number of time then
Most_Used_Base_Location_T6 should take the latest month value i.e 'Oslo'

NB: *M1 is the latest Month & M6 is the oldest
*T3 is the statistical mode of M1,M2 and M3
*T6 is the statistical mode of M1,M2,M3,M4,M5 and M6

Body:
One of the easiest ways is to use unpivot + FIRST or LAST aggregate functions:

select
   v.person_id,
   max(b3)keep(dense_rank first order by cnt desc, a) Most_Used_Base_Location_T3,
   max(b)keep(dense_rank first order by cnt desc, a) Most_Used_Base_Location_T6
from (
   select
      c.*
     ,case when a in ('M1','M2','M3') then b end b3
     ,count(*)over(partition by b) cnt
   from CusLoc
   unpivot(
     b for a in (
        Base_Location_M1 as 'M1',
        Base_Location_M2 as 'M2',
        Base_Location_M3 as 'M3',
        Base_Location_M4 as 'M4',
        Base_Location_M5 as 'M5',
        Base_Location_M6 as 'M6'
     )
   ) c
) v
group by person_id
/

DBFiddle: https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=fa2d34936824e18dff16a79bc2a19586

Updated as per new info:

DBFiddle

select
   v.id,
   max(b3)keep(dense_rank first order by cnt3 desc, a) Most_Used_Base_Location_T3,
   max(b)keep(dense_rank first order by cnt desc, a) Most_Used_Base_Location_T8
from (
   select
      id,a,b
     ,b3
     ,count(b3)over(partition by id,b3) cnt3
     ,count(b )over(partition by id,b) cnt
   from (
       select
           id,a
          ,nullif(b,'NA') as b
          ,case when a in ('M1','M2','M3') then nullif(b,'NA') end b3
       from test_mug1
       unpivot(
         b for a in (
            T1_MUG_Data as 'M1',
            T2_MUG_Data as 'M2',
            T3_MUG_Data as 'M3',
            T4_MUG_Data as 'M4',
            T5_MUG_Data as 'M5',
            T6_MUG_Data as 'M6',
            T7_MUG_Data as 'M7',
            T8_MUG_Data as 'M8'
         )
       )
   ) c
) v
group by id
order by id


问:
scripts/basic/fixdep: No such file or directory
When installing some driver by ./install.sh (ex: https://www.mellanox.com/products/adapter-software/firmware-tools ), I see this log:

```<code>scripts/basic/fixdep: No such file or directory
</code>```

but I do have this file.

```<code>ll /lib/modules/4.15.20/build/scripts/basic/fixdep
-rwxr-xr-x 1 root root 22240 May  5 03:02 /lib/modules/4.15.20/build/scripts/basic/fixdep
</code>```

before the driver installation (./install.sh), I had done:

```<code>gunzip < /proc/config.gz > .config
make oldconfig
make prepare
make scripts
</code>```

ref:
https://serverfault.com/questions/568395/what-is-creating-the-generated-autoconf-h

答:
I had the same problem. I fixed it like this:

go your linux header files :

probably for ubuntu/debian:

```<code>cd /usr/src/linux-headers-5.4.0-97-generic
</code>```

custom linux distro / yocto:

```<code>cd /usr/src/kernel
</code>```

then execute "make scripts"

you will see like this screen:

```<code>  HOSTCC  scripts/basic/fixdep
  HOSTCC  scripts/basic/bin2c
  HOSTCC  scripts/dtc/dtc.o
  HOSTCC  scripts/dtc/flattree.o
  HOSTCC  scripts/dtc/fstree.o
  HOSTCC  scripts/dtc/data.o
  HOSTCC  scripts/dtc/livetree.o
  HOSTCC  scripts/dtc/treesource.o
  HOSTCC  scripts/dtc/srcpos.o
.
.
</code>```

now check the fixdep file out under ../scripts/basic/ file path.

Body:
When installing some driver by ./install.sh (ex: https://www.mellanox.com/products/adapter-software/firmware-tools ), I see this log:

scripts/basic/fixdep: No such file or directory

but I do have this file.

ll /lib/modules/4.15.20/build/scripts/basic/fixdep
-rwxr-xr-x 1 root root 22240 May  5 03:02 /lib/modules/4.15.20/build/scripts/basic/fixdep

before the driver installation (./install.sh), I had done:

gunzip < /proc/config.gz > .config
make oldconfig
make prepare
make scripts

ref:
https://serverfault.com/questions/568395/what-is-creating-the-generated-autoconf-h

Body:
I had the same problem. I fixed it like this:

go your linux header files :

probably for ubuntu/debian:

cd /usr/src/linux-headers-5.4.0-97-generic

custom linux distro / yocto:

cd /usr/src/kernel

then execute "make scripts"

you will see like this screen:

  HOSTCC  scripts/basic/fixdep
  HOSTCC  scripts/basic/bin2c
  HOSTCC  scripts/dtc/dtc.o
  HOSTCC  scripts/dtc/flattree.o
  HOSTCC  scripts/dtc/fstree.o
  HOSTCC  scripts/dtc/data.o
  HOSTCC  scripts/dtc/livetree.o
  HOSTCC  scripts/dtc/treesource.o
  HOSTCC  scripts/dtc/srcpos.o
.
.

now check the fixdep file out under ../scripts/basic/ file path.


问:
How to create a N = 1000 , 2 dimensional 2 classes dataset given mean = [-8,8]T, covariance = [ [0.3 1.5] [1.5 9.0] ]
Generate a 1000 two-dimensional dataset, X that is of two classes and plot. The 1
500 data vectors are modeled by the Gaussian distribution with mean, m1 = [ 8, 8]
T
and the rest 500 data vectors are modeled by the Gaussian distribution with mean
m2 = [ 8, 8] . The covariance matrix for both distributions are
T
S = [0.3 1.5 1.5 9.0 ]
Use the same prescription to generate another data 200 and create a test dataset X .</p>

答:
Using numpy.random.multivariate_normal you can do that.
Using the info you provided, you can do something like:</p>
```<code>mean = [8,8]
cov = [[0.3, 1.5], [1.5, 9.0]]
x, y = np.random.multivariate_normal(mean, cov, 200).T
</code>```

Body:
Using numpy.random.multivariate_normal you can do that.
Using the info you provided, you can do something like:

mean = [8,8]
cov = [[0.3, 1.5], [1.5, 9.0]]
x, y = np.random.multivariate_normal(mean, cov, 200).T


问:
Entity Framework, calling a procedure through FromSqlRaw()
I am replacing a very long sql statement in C# with a stored procedure. The sql was called by the FromSqlRaw function. What piece of EF functionality can be implemented to achieve the same result. The following returns an exception error near b6f42 or similar each time I run the program. The procedure results called from SSMS are satisfactory.</p>
```<code>var wrk = DbCtx.WRK.FromSqlRaw($"Execute GetCustomersAsync
        {Id} {LastName}").ToObservableCollection();
</code>```

答:
You could use SqlQuery for that:

```<code>           var param1 = new SqlParameter()
            {
                ParameterName = "@Date",
                SqlDbType = SqlDbType.DateTime,
                Value = validityEnd
            };
            var parameters = new SqlParameter[] { param1 };

            return context
                .Set<TEntity>()
                .SqlQuery<ReturnType>(
                    "[schema].[spName] @Date",
                    parameters);
</code>```

Body:
I am replacing a very long sql statement in C# with a stored procedure. The sql was called by the FromSqlRaw function. What piece of EF functionality can be implemented to achieve the same result. The following returns an exception error near b6f42 or similar each time I run the program. The procedure results called from SSMS are satisfactory.

var wrk = DbCtx.WRK.FromSqlRaw($"Execute GetCustomersAsync
        {Id} {LastName}").ToObservableCollection();

Body:
You could use SqlQuery for that:

           var param1 = new SqlParameter()
            {
                ParameterName = "@Date",
                SqlDbType = SqlDbType.DateTime,
                Value = validityEnd
            };
            var parameters = new SqlParameter[] { param1 };

            return context
                .Set<TEntity>()
                .SqlQuery<ReturnType>(
                    "[schema].[spName] @Date",
                    parameters);


问:
how to get specific nested values inside of XML using Linq to XML C# in .Net 5.0
I'm working with a massive XML file that is exported from Confluence to represent the current state of a given Confluence space. For those familiar with Confluence this is used for backing up and restoring or migrating Confluence spaces in or across environments.

I'm trying to automate some basic analysis on the XML so I can output some useful information for determining if our export data is "OK" based on a set of rules we have defined.

Given the size of some of these exports and the structure of the XML it can be a pain and very time consuming to analyze this manually.

Essentially I've whittled down the XML to a IEnumerable of "object" XElements.

```<code>var filename = "export.xml";
var currentDirectory = Directory.GetCurrentDirectory();
var confluenceExportFilePath = Path.Combine(currentDirectory, filename);
XDocument confluenceExport = XDocument.Load(confluenceExportFilePath);
var objects = confluenceExport.Descendants("object");
</code>```

Then I've taken that further and only selected objects that contain a class attribute equal to "Page" as I only care about the "objects" that are Page "objects". Up to this point I've returned some basic "header" information about each Page.

```<code>var pages =
from page in objects
where (string)page.Attribute("class") == "Page"
select new Page
{
    Id = (string)page.Element("id"),
    Title = (string)page.Elements("property").FirstOrDefault(property =>
        property.Attribute("name").Value == "title"),
    Version = (int)page.Elements("property").FirstOrDefault(property =>
        property.Attribute("name").Value == "version"),
};
</code>```

An example page "object" may look like this:

```<code><object class="Page" package="com.atlassian.confluence.pages">
    <id name="id">001</id>
    <property name="title"><![CDATA[Test Page]]></property>
    <property name="lowerTitle"><![CDATA[test page]]></property>
    <property name="version">022</property>
    <property name="creationDate">2020-06-15 20:13:00.195</property>
    <property name="lastModificationDate">2020-06-18 12:01:04.482</property>
    <property name="versionComment"><![CDATA[]]></property>
    <collection name="bodyContents" class="java.util.Collection">
        <element class="BodyContent" package="com.atlassian.confluence.core">
            <id name="id">011</id>
        </element>
    </collection>
    <collection name="historicalVersions" class="java.util.Collection">
        <element class="Page" package="com.atlassian.confluence.pages">
            <id name="id">021</id>
        </element>
        <element class="Page" package="com.atlassian.confluence.pages">
            <id name="id">022</id>
        </element>
    </collection>
    <property name="contentStatus"><![CDATA[current]]></property>
    <collection name="attachments" class="java.util.Collection">
        <element class="Attachment" package="com.atlassian.confluence.pages">
            <id name="id">031</id>
        </element>
        <element class="Attachment" package="com.atlassian.confluence.pages">
            <id name="id">032</id>
        </element>
    </collection>
</object>
</code>```

However, I wanted to dig a little deeper into the XML and get some more specific data and I'm struggling to do that. For example, I would like to select the "id" value that is nested inside the BodyContent collection.

```<code>    <collection name="bodyContents" class="java.util.Collection">
        <element class="BodyContent" package="com.atlassian.confluence.core">
            <id name="id">011</id>
        </element>
    </collection>
</code>```

Ultimately what I would like is to be able to output:

```<code>Page ID: 001
Page Title: Test Page
Page Version: 022
Page Body Content ID: 011
</code>```

How can I go about getting this?

答:
The code below looks for the first element with the class BodyContent and takes the value of its id child element. For the xml in your example, these search criteria will suffice.

```<code>var pages =
    from page in objects
    where (string)page.Attribute("class") == "Page"
    select new Page
    {
        BodyContentId =
            (string)page
                .Descendants("element")
                .Where(o => (string)o.Attribute("class") == "BodyContent")
                .FirstOrDefault()?.Element("id")

        // Other properties
    };
</code>```

Giving you also a pointer to a post about how to handle large xml files.

In short, use an XmlReader to loop over the page <object class="Page> elements and only load an XElement/XDocument per single page onto which you apply the Linq statements above.

Body:
I'm working with a massive XML file that is exported from Confluence to represent the current state of a given Confluence space. For those familiar with Confluence this is used for backing up and restoring or migrating Confluence spaces in or across environments.

I'm trying to automate some basic analysis on the XML so I can output some useful information for determining if our export data is "OK" based on a set of rules we have defined.

Given the size of some of these exports and the structure of the XML it can be a pain and very time consuming to analyze this manually.

Essentially I've whittled down the XML to a IEnumerable of "object" XElements.

var filename = "export.xml";
var currentDirectory = Directory.GetCurrentDirectory();
var confluenceExportFilePath = Path.Combine(currentDirectory, filename);
XDocument confluenceExport = XDocument.Load(confluenceExportFilePath);
var objects = confluenceExport.Descendants("object");

Then I've taken that further and only selected objects that contain a class attribute equal to "Page" as I only care about the "objects" that are Page "objects". Up to this point I've returned some basic "header" information about each Page.

var pages =
from page in objects
where (string)page.Attribute("class") == "Page"
select new Page
{
    Id = (string)page.Element("id"),
    Title = (string)page.Elements("property").FirstOrDefault(property =>
        property.Attribute("name").Value == "title"),
    Version = (int)page.Elements("property").FirstOrDefault(property =>
        property.Attribute("name").Value == "version"),
};

An example page "object" may look like this:

<object class="Page" package="com.atlassian.confluence.pages">
    <id name="id">001</id>
    <property name="title"><![CDATA[Test Page]]></property>
    <property name="lowerTitle"><![CDATA[test page]]></property>
    <property name="version">022</property>
    <property name="creationDate">2020-06-15 20:13:00.195</property>
    <property name="lastModificationDate">2020-06-18 12:01:04.482</property>
    <property name="versionComment"><![CDATA[]]></property>
    <collection name="bodyContents" class="java.util.Collection">
        <element class="BodyContent" package="com.atlassian.confluence.core">
            <id name="id">011</id>
        </element>
    </collection>
    <collection name="historicalVersions" class="java.util.Collection">
        <element class="Page" package="com.atlassian.confluence.pages">
            <id name="id">021</id>
        </element>
        <element class="Page" package="com.atlassian.confluence.pages">
            <id name="id">022</id>
        </element>
    </collection>
    <property name="contentStatus"><![CDATA[current]]></property>
    <collection name="attachments" class="java.util.Collection">
        <element class="Attachment" package="com.atlassian.confluence.pages">
            <id name="id">031</id>
        </element>
        <element class="Attachment" package="com.atlassian.confluence.pages">
            <id name="id">032</id>
        </element>
    </collection>
</object>

However, I wanted to dig a little deeper into the XML and get some more specific data and I'm struggling to do that. For example, I would like to select the "id" value that is nested inside the BodyContent collection.

    <collection name="bodyContents" class="java.util.Collection">
        <element class="BodyContent" package="com.atlassian.confluence.core">
            <id name="id">011</id>
        </element>
    </collection>

Ultimately what I would like is to be able to output:

Page ID: 001
Page Title: Test Page
Page Version: 022
Page Body Content ID: 011

How can I go about getting this?

Body:
The code below looks for the first element with the class BodyContent and takes the value of its id child element. For the xml in your example, these search criteria will suffice.

var pages =
    from page in objects
    where (string)page.Attribute("class") == "Page"
    select new Page
    {
        BodyContentId =
            (string)page
                .Descendants("element")
                .Where(o => (string)o.Attribute("class") == "BodyContent")
                .FirstOrDefault()?.Element("id")

        // Other properties
    };

Giving you also a pointer to a post about how to handle large xml files.

In short, use an XmlReader to loop over the page <object class="Page> elements and only load an XElement/XDocument per single page onto which you apply the Linq statements above.


问:
Ruby Rails User's Email Being overwritten
Playing around with authentication from scratch and for some reason my users email address is not being saved to the DB. When I fire up the console and pull a random user, their email is always nil, but have validations set for the presence of email and am get a successful user created message. This was working before and not sure what broke it. I know this is something super simple but it has got me for the last few hours and am hoping a second pair of eyes can tell me what I'm doing wrong. GitHub link below
[https://github.com/smarandache1990/auth][1]</p>
```<code>        <h1>Sign Up</h1>

        <%= form_for @user do |f| %>
          <% if @user.errors.any? %>
            <div class="error_messages">
              <h2>Form is invalid</h2>
              <ul>
                <% for message in @user.errors.full_messages %>
                  <li><%= message %></li>
                <% end %>
              </ul>
            </div>
          <% end %>
          <p>
            <%= f.label :email %><br />
            <%= f.text_field :email %>
            <% @user.errors.full_messages_for(:email).each do |message| %>
              <div><%= message %></div>
            <% end %>
          </p>
          <p>
            <%= f.label :password %><br />
            <%= f.password_field :password %>
            <% @user.errors.full_messages_for(:password).each do |message| %>
              <div><%= message %></div>
            <% end %>
          </p>
          <p>
            <%= f.label :password_confirmation %><br />
            <%= f.password_field :password_confirmation %>
            <% @user.errors.full_messages_for(:password_confirmation).each do |message| %>
              <div><%= message %></div>
            <% end %>
          </p>
          <p class="button"><%= f.submit %></p>
        <% end %>
</code>```
```<code>        <h1>Sign In</h1>

        <%= form_tag sessions_path do %>

            <p>
                <%= label_tag :email %><br />
                <%= text_field_tag :email, params[:email] %>
            </p>
            <p>
                <%= label_tag :password %><br />
                <%= password_field_tag :password %>
            </p>
            <p class="button"><%= submit_tag "Log in" %></p>

        <% end %>
</code>```
```<code>            class User < ApplicationRecord
                attr_accessor :email, :password, :password_confirmation

                before_save :encrypt_password

                validates :password, confirmation: true, on: :create
                validates :password_confirmation, presence: true

                #validates_presence_of :password, :on => :create
                #validates_confirmation_of :password
                validates_presence_of :email
                validates_uniqueness_of :email

                def self.authenticate(email, password)
                user = find_by_email(email)
                if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
                    user
                else
                    nil
                end
                end

                def encrypt_password
                if password.present?
                    self.password_salt = BCrypt::Engine.generate_salt
                    self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
                end
                end
            end

</code>```
```<code>    class UsersController < ApplicationController
      def new
        @user = User.new
      end

      def create
        @user = User.new(user_params)
        if @user.save
          redirect_to log_in_path, :notice => "Signed up!"
        else
          render :new, status: :unprocessable_entity
        end
      end

      private
      def user_params
        params.require(:user).permit(:email, :password, :password_confirmation)
      end
    end
</code>```
```<code>        class SessionsController < ApplicationController
          def new
          end

          def create
            @user = User.authenticate(params[:email], params[:password])
            if @user
              session[:user_id] = @user.id
              redirect_to root_url, :notice => "Logged in!"
            else
              flash.now[:notice] = "Wrong username or password"
              render :new, status: :unprocessable_entity
            end
          end

          def destroy
            session[:user_id] = nil
            redirect_to root_url, :notice => "Logged out!"
          end

        end

</code>```

答:
Remove the email from the attr_acessor (here).

attr_accessor creates the getters and setters for all attributes listed there. So, basically, you're overriding these methods for the email attribute.

About the validation, use this:

```<code>validates :email, presence: true, uniqueness: true
</code>```

Body:
Playing around with authentication from scratch and for some reason my users email address is not being saved to the DB. When I fire up the console and pull a random user, their email is always nil, but have validations set for the presence of email and am get a successful user created message. This was working before and not sure what broke it. I know this is something super simple but it has got me for the last few hours and am hoping a second pair of eyes can tell me what I'm doing wrong. GitHub link below
[https://github.com/smarandache1990/auth][1]

Sign Up

        <%= form_for @user do |f| %>
          <% if @user.errors.any? %>

Form is invalid

                <% for message in @user.errors.full_messages %>

<%= message %>

                <% end %>

          <% end %>

            <%= f.label :email %>

            <%= f.text_field :email %>
            <% @user.errors.full_messages_for(:email).each do |message| %>

<%= message %>

            <% end %>

            <%= f.label :password %>

            <%= f.password_field :password %>
            <% @user.errors.full_messages_for(:password).each do |message| %>

<%= message %>

            <% end %>

            <%= f.label :password_confirmation %>

            <%= f.password_field :password_confirmation %>
            <% @user.errors.full_messages_for(:password_confirmation).each do |message| %>

<%= message %>

            <% end %>

<%= f.submit %>

        <% end %>

Sign In

        <%= form_tag sessions_path do %>

                <%= label_tag :email %>

                <%= text_field_tag :email, params[:email] %>

                <%= label_tag :password %>

                <%= password_field_tag :password %>

<%= submit_tag "Log in" %>

        <% end %>

            class User < ApplicationRecord
                attr_accessor :email, :password, :password_confirmation

                before_save :encrypt_password

                validates :password, confirmation: true, on: :create
                validates :password_confirmation, presence: true

                #validates_presence_of :password, :on => :create
                #validates_confirmation_of :password
                validates_presence_of :email
                validates_uniqueness_of :email

                def self.authenticate(email, password)
                user = find_by_email(email)
                if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
                    user
                else
                    nil
                end
                end

                def encrypt_password
                if password.present?
                    self.password_salt = BCrypt::Engine.generate_salt
                    self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
                end
                end
            end

    class UsersController < ApplicationController
      def new
        @user = User.new
      end

      def create
        @user = User.new(user_params)
        if @user.save
          redirect_to log_in_path, :notice => "Signed up!"
        else
          render :new, status: :unprocessable_entity
        end
      end

      private
      def user_params
        params.require(:user).permit(:email, :password, :password_confirmation)
      end
    end

        class SessionsController < ApplicationController
          def new
          end

          def create
            @user = User.authenticate(params[:email], params[:password])
            if @user
              session[:user_id] = @user.id
              redirect_to root_url, :notice => "Logged in!"
            else
              flash.now[:notice] = "Wrong username or password"
              render :new, status: :unprocessable_entity
            end
          end

          def destroy
            session[:user_id] = nil
            redirect_to root_url, :notice => "Logged out!"
          end

        end

Body:
Remove the email from the attr_acessor (here).

attr_accessor creates the getters and setters for all attributes listed there. So, basically, you're overriding these methods for the email attribute.

About the validation, use this:

validates :email, presence: true, uniqueness: true


问:
Docker socket not accessible due to file permissions
I am trying to simulate a development environment in a Docker container. As part of this effort, I want the Docker container to have the same users and groups as the host. This can be achieved by mounting the host's user and group configuration file when running docker run (see the full docker run command at the bottom).

When you start this container, you login into the container as the same user and group as on the host (specifying the flag --user $(id -u):$(id -g)). Suppose that user is ubuntu and that group is also ubuntu.

Now, I also want to be able to run Docker commands from within the container. I attempt doing this by mounting the docker socket file so the Docker client in the Docker container can communicate with the Docker daemon on the host.

On the host, the login user has been added to the group docker and the docker socket file permissions are set such that any user in the group docker can issue docker commands:

```<code>ubuntu@laptop:$ ls -l /var/run/docker.sock
srw-rw---- 1 root docker 0 Feb  8 09:45 /var/run/docker.sock

ubuntu@laptop:$ docker images # (no sudo required)
REPOSITORY                                                           TAG                                        IMAGE ID       CREATED          SIZE
dind                                                                 latest                                     65b727c75899   42 minutes ago   611MB
postgres                                                             9.6-bullseye                               2266d156fa6a   5 weeks ago      239MB
ubuntu                                                               20.04                                      ba6acccedd29   3 months ago     72.8MB
</code>```

However, when I run a docker command like docker images from inside the container, I get a file permission error:

```<code>ubuntu@b5bb183641e8:$ docker images
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.24/images/json: dial unix /var/run/docker.sock: connect: permission denied
</code>```

If I run the above command as root (or with sudo) in the Docker container, the above command runs correctly.

This is happening because the user ubuntu is able to read/write to the docker socket on the host, but not on the container. I don't understand why that would be the case provided that I have mounted all the relevant file permissions configuration files from the host onto the container. I expect the same behavior on the container as on the host.

For reference,
Image (tagged as `dind:latest) of the container is defined by the following Dockefile

```<code>FROM ubuntu:20.04

RUN apt update && apt -y install sudo docker.io

CMD /bin/bash
</code>```

Running the docker container with all the relevant files mounted:

```<code>$ docker run \
> --user $(id -u):$(id -g) \
> -v /etc/group:/etc/group:ro \
> -v /etc/gshadow:/etc/gshadow:ro \
> -v /etc/passwd:/etc/passwd:ro \
> -v /etc/shadow:/etc/shadow:ro \
> -v /etc/sudoers.d:/etc/sudoers.d:ro \
> -v /var/run/docker.sock:/var/run/docker.sock \
> dind:latest
</code>```

答:
When you specify a group with this option:

```<code>--user $(id -u):$(id -g)
</code>```

that is the only group assigned to the user, it ignores everything else specified in /etc/group. Normally you can specify just the user and the group ids will be configured from /etc/passwd and /etc/group. That would look like:

```<code>--user $(id -u)
</code>```

Unfortunately, I believe this is done based on the files in the image, before the volume is mounted. So you need to manually add additional groups with --group-add, and for the docker socket you need the docker group (you may need to replace that with the gid):

```<code>--group-add docker
</code>```

Body:
I am trying to simulate a development environment in a Docker container. As part of this effort, I want the Docker container to have the same users and groups as the host. This can be achieved by mounting the host's user and group configuration file when running docker run (see the full docker run command at the bottom).

When you start this container, you login into the container as the same user and group as on the host (specifying the flag --user $(id -u):$(id -g)). Suppose that user is ubuntu and that group is also ubuntu.

Now, I also want to be able to run Docker commands from within the container. I attempt doing this by mounting the docker socket file so the Docker client in the Docker container can communicate with the Docker daemon on the host.

On the host, the login user has been added to the group docker and the docker socket file permissions are set such that any user in the group docker can issue docker commands:

ubuntu@laptop:$ ls -l /var/run/docker.sock
srw-rw---- 1 root docker 0 Feb  8 09:45 /var/run/docker.sock

ubuntu@laptop:$ docker images # (no sudo required)
REPOSITORY                                                           TAG                                        IMAGE ID       CREATED          SIZE
dind                                                                 latest                                     65b727c75899   42 minutes ago   611MB
postgres                                                             9.6-bullseye                               2266d156fa6a   5 weeks ago      239MB
ubuntu                                                               20.04                                      ba6acccedd29   3 months ago     72.8MB

However, when I run a docker command like docker images from inside the container, I get a file permission error:

ubuntu@b5bb183641e8:$ docker images
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.24/images/json: dial unix /var/run/docker.sock: connect: permission denied

If I run the above command as root (or with sudo) in the Docker container, the above command runs correctly.

This is happening because the user ubuntu is able to read/write to the docker socket on the host, but not on the container. I don't understand why that would be the case provided that I have mounted all the relevant file permissions configuration files from the host onto the container. I expect the same behavior on the container as on the host.

For reference,
Image (tagged as `dind:latest) of the container is defined by the following Dockefile

FROM ubuntu:20.04

RUN apt update && apt -y install sudo docker.io

CMD /bin/bash

Running the docker container with all the relevant files mounted:

$ docker run \
> --user $(id -u):$(id -g) \
> -v /etc/group:/etc/group:ro \
> -v /etc/gshadow:/etc/gshadow:ro \
> -v /etc/passwd:/etc/passwd:ro \
> -v /etc/shadow:/etc/shadow:ro \
> -v /etc/sudoers.d:/etc/sudoers.d:ro \
> -v /var/run/docker.sock:/var/run/docker.sock \
> dind:latest

Body:
When you specify a group with this option:

--user $(id -u):$(id -g)

that is the only group assigned to the user, it ignores everything else specified in /etc/group. Normally you can specify just the user and the group ids will be configured from /etc/passwd and /etc/group. That would look like:

--user $(id -u)

Unfortunately, I believe this is done based on the files in the image, before the volume is mounted. So you need to manually add additional groups with --group-add, and for the docker socket you need the docker group (you may need to replace that with the gid):

--group-add docker


问:
Error: XML transformation error in Azure Pipelines
I've spent the day trying to get to the bottom of an XML transformation error in Azure DevOps and I can't seem to get a handle on the problem. Locally the config transform works fine and the config transforms for the other environments that I'm deploying to are working in Azure DevOps.

The error that appears in the logs when the IIS Web App Deployment task is terminated is:

```<code>2021-02-26T15:29:49.9263250Z ##[error]Error: XML transformation error while transforming C:\...\Web.config using C:\...\Web.Live.config.
</code>```

Obviously I've cut out the long file paths that Azure DevOps applies.

Further up in the IIS Web App Deployment task logs the following error appears but is not highlighted as being significant. Aster this error is logged it does appear to apply transforms, before giving the aforementioned error which terminates the process:

```<code>2021-02-26T15:29:49.9178971Z System.NullReferenceException: Object reference not set to an instance of an object.
2021-02-26T15:29:49.9180071Z    at Microsoft.Web.XmlTransform.XmlTransformationLogger.ConvertUriToFileName(XmlDocument xmlDocument)
2021-02-26T15:29:49.9180525Z    at Microsoft.Web.XmlTransform.XmlTransformationLogger.LogWarning(XmlNode referenceNode, String message, Object[] messageArgs)
2021-02-26T15:29:49.9180911Z    at Microsoft.Web.XmlTransform.Transform.ApplyOnAllTargetNodes()
</code>```

I've been through the XML file and can't find any malformed XML, I've also run it through an XML validator. I've previewed the transform locally in Visual Studio 2019 Professional (possible using Slow Cheetah) and it's fine there too.

Can anyone give a pointer as to what might cause this transformation error in the pipelines?

答:
I know this one is a bit old, but the problem could be that the VSBuild task is transforming the web.config file, and then the release pipeline is as well.

So for example, if you have a transform that removes the debug attribute, unless the VSBuild task has a TransformWebConfigEnabled=False parameter, it will transform the web.config and remove the debug attribute.  When the release pipeline runs it will again try to remove the attribute, but it's already been removed, so the error is thrown.

Here's how I instruct the VSBuild task not to transform:

```<code>- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)" /p:AutoParameterizationWebConfigConnectionStrings=False /p:TransformWebConfigEnabled=False'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'
</code>```

Body:
I've spent the day trying to get to the bottom of an XML transformation error in Azure DevOps and I can't seem to get a handle on the problem. Locally the config transform works fine and the config transforms for the other environments that I'm deploying to are working in Azure DevOps.

The error that appears in the logs when the IIS Web App Deployment task is terminated is:

2021-02-26T15:29:49.9263250Z ##[error]Error: XML transformation error while transforming C:\...\Web.config using C:\...\Web.Live.config.

Obviously I've cut out the long file paths that Azure DevOps applies.

Further up in the IIS Web App Deployment task logs the following error appears but is not highlighted as being significant. Aster this error is logged it does appear to apply transforms, before giving the aforementioned error which terminates the process:

2021-02-26T15:29:49.9178971Z System.NullReferenceException: Object reference not set to an instance of an object.
2021-02-26T15:29:49.9180071Z    at Microsoft.Web.XmlTransform.XmlTransformationLogger.ConvertUriToFileName(XmlDocument xmlDocument)
2021-02-26T15:29:49.9180525Z    at Microsoft.Web.XmlTransform.XmlTransformationLogger.LogWarning(XmlNode referenceNode, String message, Object[] messageArgs)
2021-02-26T15:29:49.9180911Z    at Microsoft.Web.XmlTransform.Transform.ApplyOnAllTargetNodes()

I've been through the XML file and can't find any malformed XML, I've also run it through an XML validator. I've previewed the transform locally in Visual Studio 2019 Professional (possible using Slow Cheetah) and it's fine there too.

Can anyone give a pointer as to what might cause this transformation error in the pipelines?

Body:
I know this one is a bit old, but the problem could be that the VSBuild task is transforming the web.config file, and then the release pipeline is as well.

So for example, if you have a transform that removes the debug attribute, unless the VSBuild task has a TransformWebConfigEnabled=False parameter, it will transform the web.config and remove the debug attribute.  When the release pipeline runs it will again try to remove the attribute, but it's already been removed, so the error is thrown.

Here's how I instruct the VSBuild task not to transform:

- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)" /p:AutoParameterizationWebConfigConnectionStrings=False /p:TransformWebConfigEnabled=False'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'


问:
Selenium: Trying to login but the same page is reloaded after click
I am trying to login a page.

I entered the e-mail & password inputs by element.sendKeys() without any error.

After that I need to click the 'loginButton' button. But the button is defined as non keyboard-focusable.

When I run the automation, the button is clicked. But the automation is not continue with the next page (main page); just reloads the same page with empty inputs.

I tried several ways to click the button and also tried to enter by using 'ENTER' key;

```<code>// **1.**
 loginButton.click();

// **2.**
 robot.keyPress(KeyEvent.VK_ENTER);

// **3.**
 Actions act = new Actions(dDriver);
 act.moveToElement(driver.findElement(By.id("loginButton"))).click().build().perform();

// **4.**
 JavascriptExecutor executor;
</code>```

All of them seems that I can click the button but after that as I mentioned, the page is reloaded, not continue with the next page.

What else can I try?

答:
To click() on the element Giriş Yap you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

cssSelector:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.green_flat#loginButton"))).click();
</code>```

xpath:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='green_flat' and @id='loginButton'][text()='Giriş Yap']"))).click();
</code>```

Body:
I am trying to login a page.

I entered the e-mail & password inputs by element.sendKeys() without any error.

After that I need to click the 'loginButton' button. But the button is defined as non keyboard-focusable.

When I run the automation, the button is clicked. But the automation is not continue with the next page (main page); just reloads the same page with empty inputs.

I tried several ways to click the button and also tried to enter by using 'ENTER' key;

// **1.**
 loginButton.click();

// **2.**
 robot.keyPress(KeyEvent.VK_ENTER);

// **3.**
 Actions act = new Actions(dDriver);
 act.moveToElement(driver.findElement(By.id("loginButton"))).click().build().perform();

// **4.**
 JavascriptExecutor executor;

All of them seems that I can click the button but after that as I mentioned, the page is reloaded, not continue with the next page.

What else can I try?

Body:
To click() on the element Giriş Yap you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

cssSelector:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.green_flat#loginButton"))).click();

xpath:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='green_flat' and @id='loginButton'][text()='Giriş Yap']"))).click();


问:
Picture source with srcset
I want to use  tag and 3 image formats. avif \ webp \ png. At the same time, but not to forget about retina displays.

At the moment I came up with something like this format:

```<code><picture>
    <source srcset="components/header/img/logo.avif, components/header/img/logo@2x.avif 2x" type="image/avif">
    <source srcset="components/header/img/logo.webp, components/header/img/logo@2x.webp 2x" type="image/webp">
    <img class="someClass" src="components/header/img/logo.png" srcset="components/header/img/logo@2x.png 2x" alt="Logo">
</picture>
</code>```

But how much of this is correct ? Maybe it should be implemented in some other way ?

答:
While the standard HTML  element doesn't support compatibility fallbacks for images, the <picture> element does. <picture> is used as a wrapper for a number of <source> elements, each specifying a version of the image in a different format or under different media conditions, as well as an  element which defines where to display the image and the fallback to the default or "most compatible" version.

```<code><picture>
   <source srcset="diagram.svg" type="image/svg+xml">
   <source srcset="diagram.png" type="image/png">
   <img src="diagram.gif" width="620" height="540"
   alt="Diagram showing the data channels">
</picture>
</code>```

More info developer.mozilla.org

I hope I was helpful

Title: Picture source with srcset

Body:
I want to use  tag and 3 image formats. avif \ webp \ png. At the same time, but not to forget about retina displays.

At the moment I came up with something like this format:

<picture>
    <source srcset="components/header/img/logo.avif, components/header/img/logo@2x.avif 2x" type="image/avif">
    <source srcset="components/header/img/logo.webp, components/header/img/logo@2x.webp 2x" type="image/webp">

</picture>

But how much of this is correct ? Maybe it should be implemented in some other way ?

Body:
While the standard HTML <img> element doesn't support compatibility fallbacks for images, the <picture> element does. <picture> is used as a wrapper for a number of <source> elements, each specifying a version of the image in a different format or under different media conditions, as well as an <img> element which defines where to display the image and the fallback to the default or "most compatible" version.

<picture>
   <source srcset="diagram.svg" type="image/svg+xml">
   <source srcset="diagram.png" type="image/png">
   <img src="diagram.gif" width="620" height="540"
   alt="Diagram showing the data channels">
</picture>

More info developer.mozilla.org

I hope I was helpful