问:
How do you read data from firestore?
I'm trying to learn how to use firestore.

The google documentation says to try this format:

```<code>db.collection("users").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});
</code>```

So, I used that to do this (changing the db to fsDB and "users" to "newsletters"

```<code>fsDB.collection("newsletters").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});
</code>```

When I try this, I get an error that says querySnapshot is not defined. Screen shot of error message is attached.

I've seen this post and tried its suggestion as follows:

```<code>fsDB.collection("newsletters").query.get().then(function(querySnapshot) {

                            if (querySnapshot.empty) {
                                console.log('no documents found');
                            } else {
                                    querySnapshot.docs.map(function (documentSnapshot) {
                                        console.log(documentSnapshot.data().name);
                                    });
                            }

                        });
</code>```

This attempt generates a parsing error with the if statement, but I can't find a way to solve that either.

This must have a simple solution, but I can't figure out how to get a record from the database.

NEXT ATTEMPT

I tried moving the code above the return statement and putting in inside a variable as follows shown in the attached screen shot, but it still produces errors as shown. These errors are the same regardless of whether i keep or lose the brackets around querySnapshot.

ADD STATE

```<code>class Fndate extends React.Component {
    state = {
        options: [],
        anzic: [],
        country: [],
        region: [],

    }

    selectCountry (val) {
        this.setState({ country: val });
      }

      selectRegion (val) {
        this.setState({ region: val });
      }

    async componentDidMount() {
        // const fsDB = firebase.firestore(); // Don't worry about this line if it comes from your config.
        let options = [];
        await fsDB.collection("abs_for_codes").get().then(function (querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, ' => ', doc.data());
            options.push({
                value: doc.data().title.replace(/( )/g, ''),
                label: doc.data().title + ' - ABS ' + doc.id
            });
            });
        });

        let anzic = [];
        await fsDB.collection("anzic_codes").get().then(function (querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, ' => ', doc.data());
            anzic.push({
                value: doc.data().Title.replace(/( )/g, ''),
                label: doc.data().Title + ' - ANZIC ' + doc.id
            });
            });
        });

            await fsDB
            .collection("newsletter")
            .get().then((querySnapshot) => {
                querySnapshot.forEach((doc) => {
                console.log(`${doc.id} => ${doc.data().email}`);
                }
            );
            });

        this.setState({
            options,
            anzic
        });
    }
</code>```

5]5

答:
I think you should get rid of ‘.query’.
and the .empty returns false if you have data in the collection.
but i wonder, why is querySnapshot undefined in your case.

```<code>db.collection("lessons").get()
  .then(function(querySnapshot) {
    if (!querySnapshot.empty) {
        querySnapshot.docs.map(function(documentSnapshot) {
        console.log(documentSnapshot.data().name);
     })
    } else {
    console.log('no documents found');
    }
});
</code>```

console

Title: How do you read data from firestore?

Body:
I'm trying to learn how to use firestore.

The google documentation says to try this format:

db.collection("users").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});

So, I used that to do this (changing the db to fsDB and "users" to "newsletters"

fsDB.collection("newsletters").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});

When I try this, I get an error that says querySnapshot is not defined. Screen shot of error message is attached.

I've seen this post and tried its suggestion as follows:

fsDB.collection("newsletters").query.get().then(function(querySnapshot) {

                            if (querySnapshot.empty) {
                                console.log('no documents found');
                            } else {
                                    querySnapshot.docs.map(function (documentSnapshot) {
                                        console.log(documentSnapshot.data().name);
                                    });
                            }

                        });

This attempt generates a parsing error with the if statement, but I can't find a way to solve that either.

This must have a simple solution, but I can't figure out how to get a record from the database.

NEXT ATTEMPT

I tried moving the code above the return statement and putting in inside a variable as follows shown in the attached screen shot, but it still produces errors as shown. These errors are the same regardless of whether i keep or lose the brackets around querySnapshot.

ADD STATE

class Fndate extends React.Component {
    state = {
        options: [],
        anzic: [],
        country: [],
        region: [],

    }

    selectCountry (val) {
        this.setState({ country: val });
      }

      selectRegion (val) {
        this.setState({ region: val });
      }

    async componentDidMount() {
        // const fsDB = firebase.firestore(); // Don't worry about this line if it comes from your config.
        let options = [];
        await fsDB.collection("abs_for_codes").get().then(function (querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, ' => ', doc.data());
            options.push({
                value: doc.data().title.replace(/( )/g, ''),
                label: doc.data().title + ' - ABS ' + doc.id
            });
            });
        });

        let anzic = [];
        await fsDB.collection("anzic_codes").get().then(function (querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, ' => ', doc.data());
            anzic.push({
                value: doc.data().Title.replace(/( )/g, ''),
                label: doc.data().Title + ' - ANZIC ' + doc.id
            });
            });
        });

            await fsDB
            .collection("newsletter")
            .get().then((querySnapshot) => {
                querySnapshot.forEach((doc) => {
                console.log(`${doc.id} => ${doc.data().email}`);
                }
            );
            });

        this.setState({
            options,
            anzic
        });
    }

5]5

Body:
I think you should get rid of ‘.query’.
and the .empty returns false if you have data in the collection.
but i wonder, why is querySnapshot undefined in your case.

db.collection("lessons").get()
  .then(function(querySnapshot) {
    if (!querySnapshot.empty) {
        querySnapshot.docs.map(function(documentSnapshot) {
        console.log(documentSnapshot.data().name);
     })
    } else {
    console.log('no documents found');
    }
});

console


来源: stackexchange

问:
Draw portion of MTLBuffer?
I am rendering point fragments from a buffer with this call:

```<code>renderEncoder.drawPrimitives(type: .point,
                             vertexStart: 0,
                             vertexCount: 1,
                             instanceCount: emitter.currentParticles)
</code>```

emitter.currentParticles is the total number of particles in the buffer. Is it possible to somehow draw only a portion of the buffer?

I have tried this, but it draws the first half of the buffer:

```<code>renderEncoder.drawPrimitives(type: .point,
                             vertexStart: emitter.currentParticles / 2,
                             vertexCount: 1,
                             instanceCount: emitter.currentParticles / 2)
</code>```

In fact, it seems that vertexStart has no effect. I can seemingly set it to any value, and it still starts at 0.

Edit:

Pipeline configuration:

```<code>private func buildParticlePipelineStates() {
    do {
        guard let library = Renderer.device.makeDefaultLibrary(),
        let function = library.makeFunction(name: "compute") else { return }

        // particle update pipeline state
        particlesPipelineState = try Renderer.device.makeComputePipelineState(function: function)

        // render pipeline state
        let vertexFunction = library.makeFunction(name: "vertex_particle")
        let fragmentFunction = library.makeFunction(name: "fragment_particle")
        let descriptor = MTLRenderPipelineDescriptor()
        descriptor.vertexFunction = vertexFunction
        descriptor.fragmentFunction = fragmentFunction

        descriptor.colorAttachments[0].pixelFormat = renderPixelFormat
        descriptor.colorAttachments[0].isBlendingEnabled = true
        descriptor.colorAttachments[0].rgbBlendOperation = .add
        descriptor.colorAttachments[0].alphaBlendOperation = .add
        descriptor.colorAttachments[0].sourceRGBBlendFactor = .sourceAlpha
        descriptor.colorAttachments[0].sourceAlphaBlendFactor = .sourceAlpha
        descriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
        descriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha

        renderPipelineState = try
        Renderer.device.makeRenderPipelineState(descriptor: descriptor)
        renderPipelineState = try Renderer.device.makeRenderPipelineState(descriptor: descriptor)
    } catch let error {
        print(error.localizedDescription)
    }
}
</code>```

Vertex shader:

```<code>struct VertexOut {
    float4 position   [[ position ]];
    float  point_size [[ point_size ]];
    float4 color;
};

vertex VertexOut vertex_particle(constant float2 &size [[buffer(0)]],
                             device Particle *particles [[buffer(1)]],
                             constant float2 &emitterPosition [[ buffer(2) ]],
                             uint instance [[instance_id]])
{
    VertexOut out;

    float2 position = particles[instance].position + emitterPosition;
    out.position.xy = position.xy / size * 2.0 - 1.0;
    out.position.z = 0;
    out.position.w = 1;
    out.point_size = particles[instance].size * particles[instance].scale;
    out.color = particles[instance].color;
    return out;
}

fragment float4 fragment_particle(VertexOut in [[ stage_in ]],
                              texture2d<float> particleTexture [[ texture(0) ]],
                              float2 point [[ point_coord ]]) {
    constexpr sampler default_sampler;

    float4 color = particleTexture.sample(default_sampler, point);

    if ((color.a < 0.01) || (in.color.a < 0.01)) {
        discard_fragment();
    }
    color = float4(in.color.xyz, 0.2 * color.a * in.color.a);
    return color;
}
</code>```

答:
You're not using a vertex descriptor nor a [[stage_in]] parameter for your vertex shader. So, Metal is not fetching/gathering vertex data for you. You're just indexing into a buffer that's laid out with your vertex data already in the format you want. That's fine. See my answer here for more info about vertex descriptor.

Given that, though, the vertexStart parameter of the draw call only affects the value of a parameter to your vertex function with the [[vertex_id]] attribute. Your vertex function doesn't have such a parameter, let alone use it. Instead it uses an [[instance_id]] parameter to index into the vertex data buffer. You can read another of my answers here for a quick primer on draw calls and how they result in calls to your vertex shader function.

There are a couple of ways you could change things to draw only half of the points. You could change the draw call you use to:

```<code>renderEncoder.drawPrimitives(type: .point,
                             vertexStart: 0,
                             vertexCount: 1,
                             instanceCount: emitter.currentParticles / 2,
                             baseInstance: emitter.currentParticles / 2)
</code>```

This would not require any changes to the vertex shader. It just changes the range of values fed to the instance parameter. However, since it doesn't seem like this is really a case of instancing, I recommend that you change the shader and your draw call. For the shader, rename the instance parameter to vertex or vid and change its attribute from [[instance_id]] to [[vertex_id]]. Then, change the draw call to:

```<code>renderEncoder.drawPrimitives(type: .point,
                             vertexStart: emitter.currentParticles / 2,
                             vertexCount: emitter.currentParticles / 2)
</code>```

In truth, they basically behave the same way in this case, but the latter better represents what you're doing (and the draw call is simpler, which is nice).

ContentLicense: CC BY-SA 4.0

Title: Draw portion of MTLBuffer?

Body:
I am rendering point fragments from a buffer with this call:

renderEncoder.drawPrimitives(type: .point,
                             vertexStart: 0,
                             vertexCount: 1,
                             instanceCount: emitter.currentParticles)

emitter.currentParticles is the total number of particles in the buffer. Is it possible to somehow draw only a portion of the buffer?

I have tried this, but it draws the first half of the buffer:

renderEncoder.drawPrimitives(type: .point,
                             vertexStart: emitter.currentParticles / 2,
                             vertexCount: 1,
                             instanceCount: emitter.currentParticles / 2)

In fact, it seems that vertexStart has no effect. I can seemingly set it to any value, and it still starts at 0.

Edit:

Pipeline configuration:

private func buildParticlePipelineStates() {
    do {
        guard let library = Renderer.device.makeDefaultLibrary(),
        let function = library.makeFunction(name: "compute") else { return }

        // particle update pipeline state
        particlesPipelineState = try Renderer.device.makeComputePipelineState(function: function)

        // render pipeline state
        let vertexFunction = library.makeFunction(name: "vertex_particle")
        let fragmentFunction = library.makeFunction(name: "fragment_particle")
        let descriptor = MTLRenderPipelineDescriptor()
        descriptor.vertexFunction = vertexFunction
        descriptor.fragmentFunction = fragmentFunction

        descriptor.colorAttachments[0].pixelFormat = renderPixelFormat
        descriptor.colorAttachments[0].isBlendingEnabled = true
        descriptor.colorAttachments[0].rgbBlendOperation = .add
        descriptor.colorAttachments[0].alphaBlendOperation = .add
        descriptor.colorAttachments[0].sourceRGBBlendFactor = .sourceAlpha
        descriptor.colorAttachments[0].sourceAlphaBlendFactor = .sourceAlpha
        descriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
        descriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha

        renderPipelineState = try
        Renderer.device.makeRenderPipelineState(descriptor: descriptor)
        renderPipelineState = try Renderer.device.makeRenderPipelineState(descriptor: descriptor)
    } catch let error {
        print(error.localizedDescription)
    }
}

Vertex shader:

struct VertexOut {
    float4 position   [[ position ]];
    float  point_size [[ point_size ]];
    float4 color;
};

vertex VertexOut vertex_particle(constant float2 &size [[buffer(0)]],
                             device Particle *particles [[buffer(1)]],
                             constant float2 &emitterPosition [[ buffer(2) ]],
                             uint instance [[instance_id]])
{
    VertexOut out;

    float2 position = particles[instance].position + emitterPosition;
    out.position.xy = position.xy / size * 2.0 - 1.0;
    out.position.z = 0;
    out.position.w = 1;
    out.point_size = particles[instance].size * particles[instance].scale;
    out.color = particles[instance].color;
    return out;
}

fragment float4 fragment_particle(VertexOut in [[ stage_in ]],
                              texture2d<float> particleTexture [[ texture(0) ]],
                              float2 point [[ point_coord ]]) {
    constexpr sampler default_sampler;

    float4 color = particleTexture.sample(default_sampler, point);

    if ((color.a < 0.01) || (in.color.a < 0.01)) {
        discard_fragment();
    }
    color = float4(in.color.xyz, 0.2 * color.a * in.color.a);
    return color;
}

Body:
You're not using a vertex descriptor nor a [[stage_in]] parameter for your vertex shader. So, Metal is not fetching/gathering vertex data for you. You're just indexing into a buffer that's laid out with your vertex data already in the format you want. That's fine. See my answer here for more info about vertex descriptor.

Given that, though, the vertexStart parameter of the draw call only affects the value of a parameter to your vertex function with the [[vertex_id]] attribute. Your vertex function doesn't have such a parameter, let alone use it. Instead it uses an [[instance_id]] parameter to index into the vertex data buffer. You can read another of my answers here for a quick primer on draw calls and how they result in calls to your vertex shader function.

There are a couple of ways you could change things to draw only half of the points. You could change the draw call you use to:

renderEncoder.drawPrimitives(type: .point,
                             vertexStart: 0,
                             vertexCount: 1,
                             instanceCount: emitter.currentParticles / 2,
                             baseInstance: emitter.currentParticles / 2)

This would not require any changes to the vertex shader. It just changes the range of values fed to the instance parameter. However, since it doesn't seem like this is really a case of instancing, I recommend that you change the shader and your draw call. For the shader, rename the instance parameter to vertex or vid and change its attribute from [[instance_id]] to [[vertex_id]]. Then, change the draw call to:

renderEncoder.drawPrimitives(type: .point,
                             vertexStart: emitter.currentParticles / 2,
                             vertexCount: emitter.currentParticles / 2)

In truth, they basically behave the same way in this case, but the latter better represents what you're doing (and the draw call is simpler, which is nice).


问:
Using a shared read database in Microservices
It is well known that using a shared database in Microservices is not a good idea, but when we need data in another Microservice we should use messaging brokers like RabbitMQ. If the data is required just to build a new materialized view, wouldn´t be easier if some kind of shared read database was available? Or should we read 'you shall not share databases across Microservices' as do not share a writeable nor a readable database?</p>

答:
In Microservices there isn't right or wrong but best practices. The purpose of microservices is they can operate and work independently. Keeping this in mind  Read Replicas are fine as long as they are operating independently and are used only to create materialized view. If primary DB goes down , your read replicas should keep on operating. Technically they both are separate/independent databases for different purposes.

When using this approach you need to be aware of consistency. This kind of setup will be eventually consistent , so if your primary is updated it will take sometime to get reflected in read replicas and you may get stale copy while data is being replicated. If you are after strong consistency this may not be good strategy.

based on comments below

Materialized view and read replicas are two different things. You would only use Read replica to create Materialized view. But you don't do anything within the replica itself. You need to create the Materialized view into cache , separate DB or even NoSQL db. We use read replicas Only to off load the query load from write database. Materialized views are disposable. You can simply dispose them and recreate using Read Replicas. In this kind of approach you could have a periodic job that will be recreating the materialized view based on interval you choose. If you have heavy write load database it's always a good idea to create read replicas to create Materialized views. There is not other purpose of read replicas in this context. You can even use read replicas to create views on the fly , but they are simple views and you will be querying the data on the fly and may not be as fast as materialized view.

The second approach like you said is to listen to events. They are simple in a way that as soon as you would listen to the events you can update your materialized view. But again they are disposable and you can always query your actual/master database to recreate/update materialized view.


问:
How to protect some files/objects in public bucket?
I would like to create a public read aws s3 bucket with some files read restricted by a IAM role.

First of all:

I using amplify cli for deploying my «static» website.

The website is a react app

This app have public pages/react components and a admin area

I would like to restrict admin area/admin pages/admin react components with a aws IAM role

More details:

The react app is very big so I splited components using asyncComponent feature like const Dashboard = asyncComponent(() => import('./pages/Dashboard'))
So when I build the app instead to have one big file I have several small files. And all these files are on the same bucket.

Now I want to build admin pages. Always using asyncComponent we get a collection of «Admin» files and there are hosted on the same bucket. But for security reason I want to restrict access to authenticated users with a certain IAM role (for ex AdminRole).

I go through lot of doc from amplify config or AWS::S3::Bucket from cloudFormation and I saw different things that tell me it's possible but I'm very lost in this doc.

So finally I ask:

How can I protect some files/objects for reading access in s3 buckets with a IAM role?

And how can I «tag» admin components in the react app? or via amplify? maybe using regex for match files? or a specified folder? In order to apply this read restriction.

Thank you in advance for your reply.

答:
Content in Amazon S3 is private by default.

Therefore, anything you are happy for everyone in the world to view can be made publicly accessible via a Bucket Policy (whole bucket or part of a bucket) or via Access Control Lists (ACLs) on the objects themselves.

To serve content that should be restricted to specific users, take advantage of Pre-Signed URLs. These are time-limited URLs that provide temporary access to private objects in Amazon S3. They are easy to generate (no API calls required).

The way it would work is:

Users would authenticate with your application

When they wish to access restricted content, the application would determine whether they are permitted access

If they are permitted access, the application would generate a pre-signed URL. These can also be used in  and  tags to refer to pages and images.

Users will receive/view the content just like normal web components

Once the expiry time has passed, the pre-signed URLs will no longer work

See: Share an Object with Others - Amazon Simple Storage Service

(I'm not an Amplify person, so I can't speak to how Amplify would specifically generate/use pre-signed URLs.)

Body:
Content in Amazon S3 is private by default.

Therefore, anything you are happy for everyone in the world to view can be made publicly accessible via a Bucket Policy (whole bucket or part of a bucket) or via Access Control Lists (ACLs) on the objects themselves.

To serve content that should be restricted to specific users, take advantage of Pre-Signed URLs. These are time-limited URLs that provide temporary access to private objects in Amazon S3. They are easy to generate (no API calls required).

The way it would work is:

Users would authenticate with your application

When they wish to access restricted content, the application would determine whether they are permitted access

If they are permitted access, the application would generate a pre-signed URL. These can also be used in <a> and <img> tags to refer to pages and images.

Users will receive/view the content just like normal web components

Once the expiry time has passed, the pre-signed URLs will no longer work

See: Share an Object with Others - Amazon Simple Storage Service

(I'm not an Amplify person, so I can't speak to how Amplify would specifically generate/use pre-signed URLs.)


问:
Trigger a Resize on a MediaElement.js Video in Wordpress
I have a post type which is displayed in modal windows. The modals are created using the Remodal library.

Unfortunately when the modal is opened the MediaElement.js video players inside have already been initialized at incorrect dimensions - the height and width are set in inline styles with dimensions around 1600px width and 900px height. The width adjusts itself to the width of the modal but the height does not, which is creating giant black bars above and below the video.

I'm looking for a way to grab the MediaElement.js player and resize the videos when the modal is opened. Because it's initialized by Wordpress I'm not sure how to grab it. From other questions on Stack it seems that the players are inside an mejs object, and there is a built in method to resize the player and controls. However, I tried various things to try to call the resize methods on the player but nothing has worked so far. For example:

```<code>if ( mejs.players.length ) {
  mejs.players.each(function() {
    $(this).setPlayerSize();
    $(this).setControlsSize();
  }
}
</code>```

答:
My current solution is to trigger a window resize event, which causes the video to resize. (Note: jQuery trigger event doesn't work.)</p>

```<code>$(document).on('opening', '.remodal', function () {

  // Trigger window resize event to fix mejs video size issues.
  // Don't use jquery trigger event since that only triggers
  // methods hooked to events, and not the events themselves.
  if ( typeof( Event ) === 'function' ) {
    window.dispatchEvent( new Event( 'resize' ) );
  } else {
    var event = window.document.createEvent( 'UIEvents' );
    event.initUIEvent( 'resize', true, false, window, 0 );
    window.dispatchEvent( event );
  }

});
</code>```

Body:
I have a post type which is displayed in modal windows. The modals are created using the Remodal library.

Unfortunately when the modal is opened the MediaElement.js video players inside have already been initialized at incorrect dimensions - the height and width are set in inline styles with dimensions around 1600px width and 900px height. The width adjusts itself to the width of the modal but the height does not, which is creating giant black bars above and below the video.

I'm looking for a way to grab the MediaElement.js player and resize the videos when the modal is opened. Because it's initialized by Wordpress I'm not sure how to grab it. From other questions on Stack it seems that the players are inside an mejs object, and there is a built in method to resize the player and controls. However, I tried various things to try to call the resize methods on the player but nothing has worked so far. For example:

if ( mejs.players.length ) {
  mejs.players.each(function() {
    $(this).setPlayerSize();
    $(this).setControlsSize();
  }
}

Body:
My current solution is to trigger a window resize event, which causes the video to resize. (Note: jQuery trigger event doesn't work.)

$(document).on('opening', '.remodal', function () {

  // Trigger window resize event to fix mejs video size issues.
  // Don't use jquery trigger event since that only triggers
  // methods hooked to events, and not the events themselves.
  if ( typeof( Event ) === 'function' ) {
    window.dispatchEvent( new Event( 'resize' ) );
  } else {
    var event = window.document.createEvent( 'UIEvents' );
    event.initUIEvent( 'resize', true, false, window, 0 );
    window.dispatchEvent( event );
  }

});


问:
How to select the channel with maximum value at every pixel in a multichannel image?
I want to fetch the channel with maximum value at every pixel in a multichannel image. I want to do with numpy without using any loop. Is there a shortcut to fetch these values?

I can do the same by looping over every pixel value as below:

```<code>label_list = []
for i in range(height):
    for j in range(width):
        label = np.where(img[i,j,:] == np.max(img[i,j,:]))
        if label not in label_list:
            label_list.append(label)
</code>```

Each channel in my image corresponds to one object. I want to know which objects are present in the image.

答:
Argmax can solve the purpose. It returns the indices of the maximum value along an axis.

np.unique(np.argmax(img, axis=2))

Maybe it can help someone else.

Body:
I want to fetch the channel with maximum value at every pixel in a multichannel image. I want to do with numpy without using any loop. Is there a shortcut to fetch these values?

I can do the same by looping over every pixel value as below:

label_list = []
for i in range(height):
    for j in range(width):
        label = np.where(img[i,j,:] == np.max(img[i,j,:]))
        if label not in label_list:
            label_list.append(label)

Each channel in my image corresponds to one object. I want to know which objects are present in the image.


问:
Calculate days between occurrences
I have a water tank and I record dates of rainfall and usage.

```<code>**Event**       **Date**
Measurement     28 April 2019
Rainfall        29 April 2019
Measurement     2 May 2019
Rainfall        3 May 2019
Rainfall        3 May 2019
Usage       7 May 2019
Rainfall        8 May 2019
Rainfall        9 May 2019
Usage       9 May 2019
Rainfall        10 May 2019
Usage       11 May 2019
</code>```

I want to create a new column that gives the number of days since last event. So on the 10th May row of the rainfall, the result would be "1" as the previous "Rainfall" event was on the 9th May

答:
If you don't want to sort your data, add this formula ...

```<code>=IFERROR(IF(A3="Rainfall",B3 - INDIRECT("B" & MAX(IF($A$1:A2="Rainfall",ROW($A$1:A2),-1))),""),"")
</code>```

... to cell C3 and fill down.

Take note, this is an array formula so you need to apply it by pressing Ctrl + Shift + Enter.

I hope it works for you.

Title: Calculate days between occurrences

Body:
I have a water tank and I record dates of rainfall and usage.

**Event**       **Date**
Measurement     28 April 2019
Rainfall        29 April 2019
Measurement     2 May 2019
Rainfall        3 May 2019
Rainfall        3 May 2019
Usage       7 May 2019
Rainfall        8 May 2019
Rainfall        9 May 2019
Usage       9 May 2019
Rainfall        10 May 2019
Usage       11 May 2019

I want to create a new column that gives the number of days since last event. So on the 10th May row of the rainfall, the result would be "1" as the previous "Rainfall" event was on the 9th May

Body:
If you don't want to sort your data, add this formula ...

=IFERROR(IF(A3="Rainfall",B3 - INDIRECT("B" & MAX(IF($A$1:A2="Rainfall",ROW($A$1:A2),-1))),""),"")

... to cell C3 and fill down.

Take note, this is an array formula so you need to apply it by pressing Ctrl + Shift + Enter.

I hope it works for you.


问:
Sum entries per date when multiple entries of date exist
I have 1 column of dates and 1 column of 'wins' recording 1 and -1 as wins and losses. I need a quick way to tally the score across each date (so I can graph the win-rates). Eg. 5th May 7 wins, 6th may -2 wins, etc. I have multiple entries for each date and several days to work through so I can't do it manually. What would be the simplest approach/formula to solve this issue?

I'm working in Google Sheets. If someone has a simple workaround in Excel too, the solution is welcome.

答:
```<code>=QUERY(A1:B, "select A,sum(B)
              where A is not null
              group by A
              label sum(B)''")
</code>```


问:
Memset In C Using Sizeof Operator :
Here is a struct :

```<code>typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;
</code>```

For memset, which one should be used from below ?

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));
</code>```

or

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));
</code>```

What are the differences ?

答: memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys)) should work if dev_sys was malloced as (NUM_DEVICES * sizeof(device_sys))

ContentLicense: CC BY-SA 3.0

Title: Memset In C Using Sizeof Operator :

Body:
Here is a struct :

typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;

For memset, which one should be used from below ?

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));

or

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));

What are the differences ?


问:
Index 3 out of bounds for length 3 in fibonacci iterative error after reducing to three element array
I have a task where I should create fibonacci iterative using loop and array.
How can I check negative values for fibonacciNumberInOrder? My tutor told me that I don't need allocate N elements in array. I can reduce it to 3element array. And I should point this array to last three numbers of fibonacci.
Now I receive an error that: Index 3 out of bounds for length 3.
I guess it's because I've change this:

```<code>long [] fibonacci = new long [fibonacciNumberInOrder];
</code>```

to:

```<code>long [] fibonacci = new long [] {1,1,2};
</code>```

What should I do to make it work and keep my tutor's requirements?

```<code>    public class FibonacciIterative {

    public static void main(String[] args) {
        int fibonacciNumberInOrder = 5;
        fibonacci(fibonacciNumberInOrder);
    }

    public static long[] fibonacci(int fibonacciNumberInOrder) {
        long [] fibonacci = new long [] {1,1,2};
        for (int i = 2; i < fibonacciNumberInOrder; i++) {
            fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
            System.out.print(Arrays.toString(fibonacci) + ", ");
        }
        return fibonacci;
    }
}
</code>```

答:
The problem is that you're trying to store all the elements in the Array. However, since your Array is only of size three, you very quickly are trying to access an index that is out of bounds. Your tutor is correct that you only need three spots. You can shift the elements once you run out of space and overwrite the previous entries. (You only need the two previous numbers in the sequence, and then the third spot in the Array will be for the sum of the previous two)

So it'll go something like:

Iterations:

[1, 1, 2]

[1, 2, 3]

[2, 3, 5]

[3, 5, 8]

And so on. To do this, you can shift every element left one with a simple for loop:

```<code>public static long[] fibonacci(int fibonacciNumberInOrder) {
    long [] fibonacci = new long [] {1,1,2};
    for (int i = 0; i < fibonacciNumberInOrder; i++) {
        System.out.print(Arrays.toString(fibonacci) + ", ");
        for(int j = 1; j < 3; j++) {
            fibonacci[j-1] = fibonacci[j];
        }
        fibonacci[2] = fibonacci[1] + fibonacci[0];
    }
    return fibonacci;
}
</code>```

If you're trying to print the Array returned by the method, then you need to print the results of the method instead of ignoring the return value, and you need to remove the print statement in the method:

```<code>public static void main(String[] args) {
    int fibonacciNumberInOrder = 5;
    System.out.println(Arrays.toString(fibonacci(fibonacciNumberInOrder)));
}
</code>```

Body:
I have a task where I should create fibonacci iterative using loop and array.
How can I check negative values for fibonacciNumberInOrder? My tutor told me that I don't need allocate N elements in array. I can reduce it to 3element array. And I should point this array to last three numbers of fibonacci.
Now I receive an error that: Index 3 out of bounds for length 3.
I guess it's because I've change this:

long [] fibonacci = new long [fibonacciNumberInOrder];

to:

long [] fibonacci = new long [] {1,1,2};

What should I do to make it work and keep my tutor's requirements?

    public class FibonacciIterative {

    public static void main(String[] args) {
        int fibonacciNumberInOrder = 5;
        fibonacci(fibonacciNumberInOrder);
    }

    public static long[] fibonacci(int fibonacciNumberInOrder) {
        long [] fibonacci = new long [] {1,1,2};
        for (int i = 2; i < fibonacciNumberInOrder; i++) {
            fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
            System.out.print(Arrays.toString(fibonacci) + ", ");
        }
        return fibonacci;
    }
}

Body:
The problem is that you're trying to store all the elements in the Array. However, since your Array is only of size three, you very quickly are trying to access an index that is out of bounds. Your tutor is correct that you only need three spots. You can shift the elements once you run out of space and overwrite the previous entries. (You only need the two previous numbers in the sequence, and then the third spot in the Array will be for the sum of the previous two)

So it'll go something like:

Iterations:

[1, 1, 2]

[1, 2, 3]

[2, 3, 5]

[3, 5, 8]

And so on. To do this, you can shift every element left one with a simple for loop:

public static long[] fibonacci(int fibonacciNumberInOrder) {
    long [] fibonacci = new long [] {1,1,2};
    for (int i = 0; i < fibonacciNumberInOrder; i++) {
        System.out.print(Arrays.toString(fibonacci) + ", ");
        for(int j = 1; j < 3; j++) {
            fibonacci[j-1] = fibonacci[j];
        }
        fibonacci[2] = fibonacci[1] + fibonacci[0];
    }
    return fibonacci;
}

If you're trying to print the Array returned by the method, then you need to print the results of the method instead of ignoring the return value, and you need to remove the print statement in the method:

public static void main(String[] args) {
    int fibonacciNumberInOrder = 5;
    System.out.println(Arrays.toString(fibonacci(fibonacciNumberInOrder)));
}


问:
How to block access to a file to other functions within same process?
I don’t mean locking the file!

What I want to achieve is that all other threads should access the file without any problem, but in some circumstances I want to fail calls which are accessing that file through fd like dup2(2), ftruncate(2), etc. One option is to make a wrapper for all such functions like dup2(2), that will first check if to allow fd or no and then call the real dup2(2). But its a long task to do it with every sys call using fd.

Maybe if there is a solution to password protect a file so that it can only be accessed when specified password is given.

My library is being injected to anonymous process so I don’t have control over the caller and I observe that anonymous process doesn’t check fd before using it. It ends up using the fd my library is using.

Kindly don’t complain about the design issues. Please just focus on problem.

答: Through in a mutex lock and make it so that if a thread wants to access the file then it has to do so through that function?</p>


问:
Html and Php Email Input form Not working?
I just got into web designing and this is the first attempt at an Email sheet. I'm not 100 percent as to what I'm doing wrong here but when I hit submit my information is not sent and the data does not disappear. Can someone help me out and possibly show me a suggestion.

I have already tried the Mailto: action and it won't even open Microsoft outlook. Is it possible that this is because it's in my repository (it has been deployed so that I can see it live as well) and not the clients actual domain.?

HTML

```<code>      <form action="contact-form.php" method="POST">

      <label for="fname">First Name</label>
      <input type="text" id="fname" name="firstname" placeholder="Your
      name..">

      <label for="lname">Last Name</label>
      <input type="text" id="lname" name="lastname" placeholder="Your last
      name..">

      <label for="email">Email</label>
      <input type="text"  id="email" name="email"
      placeholder="contactme@email.com...">

      <label for="message">Message</label>
      <textarea id="message" name="message" placeholder="Write message
      here..." style="height:200px"></textarea>

      <input type="submit" value="Submit">

    </form>
</code>```

PHP

```<code>    if (isset($_POST['submit'])) {
    echo "error; you must complete this form"
    }
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    if(empty($fname)||empty($lname)||empty($email)||empty($message))
    {
    echo "Please fill in all applicable fields!";
    exit;
    }

    $email_from = 'contact@10keybookkeeping.com';
    $email_subject = "New Email from "$fname $lname;
    $email_body = "Message from $fname $lname. \n \n".
    "email address: $email \n".
    "Message: $message".

     $to = "contact@10keybookkeeping.com";
     $headers = "From: $email_from \r \n";

     mail($to,$email_subject,$email_body.$header)
</code>```

答:
probable you have problem with your php. Im not sure for this. this is my attempt about contact form. let you will see.</p>

```<code>    <?php
include "db_connect.php";
include 'db_config.php';

if(isset($_POST['create'])) {
    $conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
    $name = $_POST['name'];
    $email = $_POST['email'];
    $text = $_POST['subject'];

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "INSERT INTO contact (name,email, text)
    VALUES ('$name', '$email', '$text')";

    if ($conn->query($sql) === TRUE) {
        echo "successful";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
}
?>
</code>```

Body:
I just got into web designing and this is the first attempt at an Email sheet. I'm not 100 percent as to what I'm doing wrong here but when I hit submit my information is not sent and the data does not disappear. Can someone help me out and possibly show me a suggestion.

I have already tried the Mailto: action and it won't even open Microsoft outlook. Is it possible that this is because it's in my repository (it has been deployed so that I can see it live as well) and not the clients actual domain.?

HTML

      <form action="contact-form.php" method="POST">

      First Name
      <input type="text" id="fname" name="firstname" placeholder="Your
      name..">

      Last Name
      <input type="text" id="lname" name="lastname" placeholder="Your last
      name..">

      Email
      <input type="text"  id="email" name="email"
      placeholder="contactme@email.com...">

      Message
      <textarea id="message" name="message" placeholder="Write message
      here..." style="height:200px"></textarea>

      <input type="submit" value="Submit">

    </form>

PHP

    if (isset($_POST['submit'])) {
    echo "error; you must complete this form"
    }
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    if(empty($fname)||empty($lname)||empty($email)||empty($message))
    {
    echo "Please fill in all applicable fields!";
    exit;
    }

    $email_from = 'contact@10keybookkeeping.com';
    $email_subject = "New Email from "$fname $lname;
    $email_body = "Message from $fname $lname. \n \n".
    "email address: $email \n".
    "Message: $message".

     $to = "contact@10keybookkeeping.com";
     $headers = "From: $email_from \r \n";

     mail($to,$email_subject,$email_body.$header)

Body:
probable you have problem with your php. Im not sure for this. this is my attempt about contact form. let you will see.

    <?php
include "db_connect.php";
include 'db_config.php';

if(isset($_POST['create'])) {
    $conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
    $name = $_POST['name'];
    $email = $_POST['email'];
    $text = $_POST['subject'];

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "INSERT INTO contact (name,email, text)
    VALUES ('$name', '$email', '$text')";

    if ($conn->query($sql) === TRUE) {
        echo "successful";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
}
?>


问:
Can i to implement a menu in the appBar using flutter_webview_plugin?
I need to implement a menu in the application bar and also show a webview at the same time

I'm using:
-Flutter version 1.5.4-hotfix.2
-Android SDK version 28.0.3

答:
Of course you can, use an AppBar and then show de WebView.

PS: This AppBar has nothing to do with the WebView itself

UPDATE

Example:

```<code>Scaffold(
 appBar: AppBar(),
 drawer: Drawer(),
 body: WebView()
);
</code>```

Body:
Of course you can, use an AppBar and then show de WebView.

PS: This AppBar has nothing to do with the WebView itself

UPDATE

Example:

Scaffold(
 appBar: AppBar(),
 drawer: Drawer(),
 body: WebView()
);


问:
Opening a new tab with `send_keys(Keys.CONTROL + 't')` doesn't work and doesn't show any error
I am trying to open multiple tabs using this code but its syntax is not having any effect (i.e. the second tab is not opening) nor this code is showing any error. It just opens google and then stops</p>

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
driver.maximize_window()
driver.get('https://google.com')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')'
</code>```

答:
You can use the below JS

```<code>driver.execute_script("window.open('');")
</code>```

Then you can switch between windows/tabs using:

```<code>windows = driver.window_handles
driver.switch_to.window(windows[0])
driver.switch_to.window(windows[1])
</code>```

Body:
I am trying to open multiple tabs using this code but its syntax is not having any effect (i.e. the second tab is not opening) nor this code is showing any error. It just opens google and then stops

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
driver.maximize_window()
driver.get('https://google.com')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')'

Body:
You can use the below JS

driver.execute_script("window.open('');")

Then you can switch between windows/tabs using:

windows = driver.window_handles
driver.switch_to.window(windows[0])
driver.switch_to.window(windows[1])


问:
Reactstrap: Getting Modal to work
Trying to learn React and Reactstrap and trying to get Modals to work. When I click the button, it should toggle the Modal, but right now it's giving me this error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of 'App'

Can't figure out what I'm doing wrong. Can someone help let me know where I'm going wrong here? Appreciate any help you can give.

I'd like to use the most recent versions of React and Reactstrap if possible.

Here's a link on Codepen: https://codepen.io/lieberscott/pen/ddYNVP

```<code>const { Button,
       Container,
       Modal,
       ModalTitle,
       ModalHeader,
       ModalBody,
       ModalFooter } = Reactstrap;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showModal: false
    }
    this.toggleModal = this.toggleModal.bind(this);
  }

  toggleModal() {
    console.log("hello");
    this.setState({
      showModal: !this.state.showModal
    })
  }

  render() {
    return (
      <Container>
        <Headline />
        <Box />
        <Button outline color="primary" onClick={this.toggleModal}>Click</Button>
        <Modal isOpen={this.state.showModal} toggle={this.toggleModal} className="modal">
          <ModalHeader>
            <ModalTitle id="modalTitle">
              Add a Recipe
            </ModalTitle>
          </ModalHeader>
          <ModalBody>
            Modal body
          </ModalBody>
          <ModalFooter>
            Modal footer
          </ModalFooter>
        </Modal>
      </Container>
    );
  }
}

class Headline extends React.Component {
  render() {
    return (
      <div>
        Recipes
      </div>
    );
  }
}

class Box extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [
        {
        name: "Tofu tacos",
        ingredients: [
          "Shells",
          "lettuce",
          "tofu",
          "paprika"
        ]
      },
      {
        name: "Spaghetti",
        ingredients: [
          "pasta",
          "sauce",
          "salt"
        ]
      }
      ] // end of items
    } // end of this.state
  } // end of constructor
  render() {
    const allitems = this.state.items.map(item => {
      return (
        <div>
          {item.name}
        </div>
      );
    })
    return (
      <div>
        {allitems}
      </div>
    );
  }
}

const app = document.getElementById("app");

ReactDOM.render(<App />, app);
</code>```

答:
Reactstrap Modal don't show, because is need fade set on False. plz look my code who worked.

```<code>class Demoextends extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        modal: false,
        fade: false
    };
    this.toggle = this.toggle.bind(this);
};
toggle() {
    console.log("hello");
    this.setState({
        modal: !this.state.modal
    });
    console.log( 'after setState: ', this.state );
}
render() {
    return (
        <div>
            <Button color="danger" onClick={this.toggle}>Launch</Button>
            <Modal isOpen={this.state.modal} fade={this.state.fade }  toggle={this.toggle}>
                <ModalHeader toggle={this.toggle}>Modal title</ModalHeader>
                <ModalBody>
                </ModalBody>
                <ModalFooter>
                    <Button onClick={this.toggle}>Do Something</Button>{' '}
                    <Button onClick={this.toggle}>Cancel</Button>
                </ModalFooter>
            </Modal>
        </div>
    );
}
</code>```

}

export default Demoextends;

Of course You must add and part of reactstrap in your code

Title: Reactstrap: Getting Modal to work

Body:
Trying to learn React and Reactstrap and trying to get Modals to work. When I click the button, it should toggle the Modal, but right now it's giving me this error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of 'App'

Can't figure out what I'm doing wrong. Can someone help let me know where I'm going wrong here? Appreciate any help you can give.

I'd like to use the most recent versions of React and Reactstrap if possible.

Here's a link on Codepen: https://codepen.io/lieberscott/pen/ddYNVP

const { Button,
       Container,
       Modal,
       ModalTitle,
       ModalHeader,
       ModalBody,
       ModalFooter } = Reactstrap;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showModal: false
    }
    this.toggleModal = this.toggleModal.bind(this);
  }

  toggleModal() {
    console.log("hello");
    this.setState({
      showModal: !this.state.showModal
    })
  }

  render() {
    return (
      <Container>
        <Headline />
        <Box />
        <Button outline color="primary" onClick={this.toggleModal}>Click</Button>
        <Modal isOpen={this.state.showModal} toggle={this.toggleModal} className="modal">
          <ModalHeader>
            <ModalTitle id="modalTitle">
              Add a Recipe
            </ModalTitle>
          </ModalHeader>
          <ModalBody>
            Modal body
          </ModalBody>
          <ModalFooter>
            Modal footer
          </ModalFooter>
        </Modal>
      </Container>
    );
  }
}

class Headline extends React.Component {
  render() {
    return (

        Recipes

    );
  }
}

class Box extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [
        {
        name: "Tofu tacos",
        ingredients: [
          "Shells",
          "lettuce",
          "tofu",
          "paprika"
        ]
      },
      {
        name: "Spaghetti",
        ingredients: [
          "pasta",
          "sauce",
          "salt"
        ]
      }
      ] // end of items
    } // end of this.state
  } // end of constructor
  render() {
    const allitems = this.state.items.map(item => {
      return (

          {item.name}

      );
    })
    return (

        {allitems}

    );
  }
}

const app = document.getElementById("app");

ReactDOM.render(<App />, app);

Body:
Reactstrap Modal don't show, because is need fade set on False. plz look my code who worked.

class Demoextends extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        modal: false,
        fade: false
    };
    this.toggle = this.toggle.bind(this);
};
toggle() {
    console.log("hello");
    this.setState({
        modal: !this.state.modal
    });
    console.log( 'after setState: ', this.state );
}
render() {
    return (
        <div>
            <Button color="danger" onClick={this.toggle}>Launch</Button>
            <Modal isOpen={this.state.modal} fade={this.state.fade }  toggle={this.toggle}>
                <ModalHeader toggle={this.toggle}>Modal title</ModalHeader>
                <ModalBody>
                </ModalBody>
                <ModalFooter>
                    <Button onClick={this.toggle}>Do Something</Button>{' '}
                    <Button onClick={this.toggle}>Cancel</Button>
                </ModalFooter>
            </Modal>
        </div>
    );
}

}

export default Demoextends;

Of course You must add and part of reactstrap in your code


问:
In Apache Airflow, how can I get the results of a "SELECT" statement on a Google Cloud SQL Database?
I need to retrieve data from a Google Cloud SQL database in one of my Dags.

I tried using the CloudSqlQueryOperator (https://airflow.readthedocs.io/en/latest/howto/connection/gcp_sql.html) but my SELECT queries are not working. Is there a way to retrieve data from a select query on Google Cloud SQL from Airflow?

答:
The query operator does "not return any data from the database, so it is useless to pass it DQL queries".

You may or may not want to use the export operator instead, depending on


问:
How can I compare different files by creation date and file size?
I want to check the backup files from last 2 days and compare if the
size of current file (today) is greater than another (yesterday) with
different backup file names.

I have 10 Server with MYSQL and everyday create each server an backup from database and send to backup server.

By some server there is more than one database, therefore server
create different backup files in same day and send to backup server. i
need to be sure if a backup was made today and if the file (today) is
larger than old file (yesterday)?

55M 25. Mai 03:45 /home/backup/server1/SW1_20190525.sql.gz

48M 25. Mai 03:45 /home/backup/server1/SW2_20190525.sql.gz

39M 25. Mai 03:45 /home/backup/server1/SW3_20190525.sql.gz

35M 25. Mai 03:45 /home/backup/server1/SW4_20190525.sql.gz

42M 25. Mai 03:45 /home/backup/server1/SW5_20190525.sql.gz

57M 26. Mai 03:45 /home/backup/server1/SW1_20190526.sql.gz

51M 26. Mai 03:45 /home/backup/server1/SW2_20190526.sql.gz

20K 26. Mai 03:45 /home/backup/server1/SW3_20190526.sql.gz

45M 26. Mai 03:45 /home/backup/server1/SW4_20190526.sql.gz

48M 26. Mai 03:45 /home/backup/server1/SW5_20190526.sql.gz

i expect to check:

SW1_20190526.sql.gz > SW1_20190525.sql.gz

SW2_20190526.sql.gz > SW2_20190525.sql.gz

SW3_20190526.sql.gz >  SW3_20190525.sql.gz

SW4_20190526.sql.gz > SW4_20190525.sql.gz

SW5_20190526.sql.gz > SW5_20190525.sql.gz

when OK say 0 OK

when not say 1 Error (for example => SW3_20190526.sql.gz)

答:
Just change the ~/testing/* to path/to/your/files*
remember to put the *

NOTE:
This version of the script assumes that you run it on the desired day. For example (date-command and the latest file entry match)

```<code># Set directory to loop through
dir=~/testing/*

# Todays date used to grep for today's file
today=$(date +%Y%m%d)

# Yesterday's date used to grep for yesterday's file
yesterday=$(date -d "yesterday" '+%Y%m%d')

# Start point to loop through each SW? files
num=1

# Start looping through directory
for file in $dir; do

    # Get today's file by date
    file_td=$(ls SW[$num]* | grep $today)

    # Get yesterday's file by date
    file_yd=$(ls SW[$num]* | grep $yesterday)

    # Get size of today's file
    size_td=$(stat -c %s $file_td)

    # Get size of yesterday's file
    size_yd=$(stat -c %s $file_yd)

    # Test if file size is equal or greater than
    if (($size_td >= $size_yd)); then
        echo "$file_td is equal or bigger that $file_yd"
    else
        echo "$file_yd is bigger $file_td"
    fi

    # Limit SW? to 5 so its doesn't attempt the script on none existing file
    # You change the 5 to how ever many SW's there are in the directory
    ((num++)) && [[ $num > 5 ]] && exit

done
</code>```

NOTE:
This version of the script doesn't assume anything and just grabs the last two entries the directory accepted. This simulates "today" and "yesterday" with out needing you to run the script on the last day.

```<code># File Directory to loop through
dir=~/testing/*

# Starting point for file names SW1 - SW?
num=1

# Begin looping through directory
for file in $dir; do

    # Set the latest file in directory SW? to today
    file_td=$(ls SW[$num]* | sort -u -r | sed '1q;d')

    # Set the second latest file in directory SW? to yesterday
    file_yd=$(ls SW[$num]* | sort -u -r | sed '2q;d')

    # Get size of today's file
    size_td=$(stat -c %s $file_td)

    # Get size of yesterday's file
    size_yd=$(stat -c %s $file_yd)

     # Test if file size is equal or greater than
    if (($size_td >= $size_yd)); then
        echo "$file_td is equal or bigger that $file_yd"
    else
        echo "$file_yd is bigger $file_td"
    fi

    # Limit SW? to 5 so its doesn't attempt the script on none existing files
    # You change the 5 to how ever many SW's there are in the directory
    ((num++)) && [[ $num > 5 ]] && exit

done
</code>```

Body:
Just change the ~/testing/* to path/to/your/files*
remember to put the *

NOTE:
This version of the script assumes that you run it on the desired day. For example (date-command and the latest file entry match)

# Set directory to loop through
dir=~/testing/*

# Todays date used to grep for today's file
today=$(date +%Y%m%d)

# Yesterday's date used to grep for yesterday's file
yesterday=$(date -d "yesterday" '+%Y%m%d')

# Start point to loop through each SW? files
num=1

# Start looping through directory
for file in $dir; do

    # Get today's file by date
    file_td=$(ls SW[$num]* | grep $today)

    # Get yesterday's file by date
    file_yd=$(ls SW[$num]* | grep $yesterday)

    # Get size of today's file
    size_td=$(stat -c %s $file_td)

    # Get size of yesterday's file
    size_yd=$(stat -c %s $file_yd)

    # Test if file size is equal or greater than
    if (($size_td >= $size_yd)); then
        echo "$file_td is equal or bigger that $file_yd"
    else
        echo "$file_yd is bigger $file_td"
    fi

    # Limit SW? to 5 so its doesn't attempt the script on none existing file
    # You change the 5 to how ever many SW's there are in the directory
    ((num++)) && [[ $num > 5 ]] && exit

done

NOTE:
This version of the script doesn't assume anything and just grabs the last two entries the directory accepted. This simulates "today" and "yesterday" with out needing you to run the script on the last day.

# File Directory to loop through
dir=~/testing/*

# Starting point for file names SW1 - SW?
num=1

# Begin looping through directory
for file in $dir; do

    # Set the latest file in directory SW? to today
    file_td=$(ls SW[$num]* | sort -u -r | sed '1q;d')

    # Set the second latest file in directory SW? to yesterday
    file_yd=$(ls SW[$num]* | sort -u -r | sed '2q;d')

    # Get size of today's file
    size_td=$(stat -c %s $file_td)

    # Get size of yesterday's file
    size_yd=$(stat -c %s $file_yd)

     # Test if file size is equal or greater than
    if (($size_td >= $size_yd)); then
        echo "$file_td is equal or bigger that $file_yd"
    else
        echo "$file_yd is bigger $file_td"
    fi

    # Limit SW? to 5 so its doesn't attempt the script on none existing files
    # You change the 5 to how ever many SW's there are in the directory
    ((num++)) && [[ $num > 5 ]] && exit

done


问:
monitor a program's memory usage in Linux
Are there any tools available in Linux which graphically or textually display memory usage for a program?  For example, if I write a C++ program and would like to verify that objects are being allocated and deallocated properly in memory, are there applications available that would visually show the objects being instantiated and deleted?  When I used to program in Visual Studio, I remember stepping through a program and using a debug pane to monitor memory usage and am looking for something similar to that in Linux.  </p>

答: conky ( screenshots) is a great simple computer resource viewer that posts over the desktop wallpaper.  I keep an eye on memory use and specific program use.</p>

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Nathan Fellman

OwnerDisplayName: ramiii


问:
Create Folder that can not accessible by any other application
i want to create a one folder that can not accessible by any other application.

Is it possible to do this ? If yes then give me the solution how to achieve this functionality.

答:
Use internal storage like so:</p>

```<code>String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
</code>```

Body:
Use internal storage like so:

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();


问:
How do I write text lines to file with variables to a file?
I am trying to automate writing a large Silvaco ATLAS (a TCAD software) script with varying values of variables in it through python. So I am trying to write ATLAS code lines to a file but I want to use key/variable values from a dictionary that I have generated in my python code. Any better way to do this?

Let's say the dict in my python looks like,

```<code>    variable_dict = {'length':22, 'height': 200, 'width':10}
</code>```

(A similar dict but with a lot more keys)
so I was going to write the ATLAS code as follows:

```<code>    atlas_code = ''' x=%length
                     y=%height
                     z=%width
             '''
</code>```

(a similar ATLAS code but with a lot more lines of code and lot more variables from the variable_dict)

and the write it to a file, like

```<code>    f.write(atlas_code)
</code>```

I expect the written ATLAS file to look like

```<code>    #atlas_code.in
    x=22
    y=200
    z=10
</code>```

答:
You can use Template like below:</p>

```<code>import string
content = string.Template('x=$length\ny=$height\nz=$width')
f.write(content.substitute(length=variable_dict['length'], height=variable_dict['height'], width=variable_dict['width']))
</code>```

Body:
I am trying to automate writing a large Silvaco ATLAS (a TCAD software) script with varying values of variables in it through python. So I am trying to write ATLAS code lines to a file but I want to use key/variable values from a dictionary that I have generated in my python code. Any better way to do this?

Let's say the dict in my python looks like,

    variable_dict = {'length':22, 'height': 200, 'width':10}

(A similar dict but with a lot more keys)
so I was going to write the ATLAS code as follows:

    atlas_code = ''' x=%length
                     y=%height
                     z=%width
             '''

(a similar ATLAS code but with a lot more lines of code and lot more variables from the variable_dict)

and the write it to a file, like

    f.write(atlas_code)

I expect the written ATLAS file to look like

    #atlas_code.in
    x=22
    y=200
    z=10

Body:
You can use Template like below:

import string
content = string.Template('x=$length\ny=$height\nz=$width')
f.write(content.substitute(length=variable_dict['length'], height=variable_dict['height'], width=variable_dict['width']))


问:
Import data.sql MySQL Docker Container
If I have a data.sql, how I can import database to my mysql docker container? How I can import database data. In a dockerised world this adds a layer of complexity. some methods please.

Here my docker-compose.yml:

```<code>nginx:
  build: ./nginx/
  container_name: nginx-container
  ports:
    - 80:80
  links:
    - php
  volumes_from:
    - app-data

php:
  build: ./php/
  container_name: php-container
  expose:
    - 9000
  links:
    - mysql
  volumes_from:
    - app-data

app-data:
  image: php:7.0-fpm
  container_name: app-data-container
  volumes:
    - ./www/html/:/var/www/html/
  command: "true"

mysql:
  image: mysql:latest
  container_name: mysql-container
  ports:
    - 3306:3306
  volumes_from:
    - mysql-data
  environment:
    MYSQL_ROOT_PASSWORD: secret
    MYSQL_DATABASE: name_db
    MYSQL_USER: user
    MYSQL_PASSWORD: password

mysql-data:
  image: mysql:latest
  container_name: mysql-data-container
  volumes:
    - /var/lib/mysql
  command: "true"
</code>```

答:
You can run a container setting a shared directory (-v volume), and then run bash in that container. After this, you can interactively use mysql-client to execute the .sql file, from inside the container. obs: /my-host-dir/shared-dir is the .sql location in the host system.

```<code>docker run --detach --name=test-mysql -p host-port:container-port  --env="MYSQL_ROOT_PASSWORD=my-root-pswd" -v /my-host-dir/shared-dir:/container-dir mysql:latest

docker exec -it test-mysql bash
</code>```

Inside the container...

```<code>mysql -p < /container-dir/file.sql
</code>```

Custom parameters:

test-mysql (container name)

host-port and container-port

my-root-pswd (mysql root password)

/my-host-dir/shared-dir and /container-dir (the host directory that will be mounted in the container, and the container location of the shared directory)

Title: Import data.sql MySQL Docker Container

Body:
If I have a data.sql, how I can import database to my mysql docker container? How I can import database data. In a dockerised world this adds a layer of complexity. some methods please.

Here my docker-compose.yml:

nginx:
  build: ./nginx/
  container_name: nginx-container
  ports:
    - 80:80
  links:
    - php
  volumes_from:
    - app-data

php:
  build: ./php/
  container_name: php-container
  expose:
    - 9000
  links:
    - mysql
  volumes_from:
    - app-data

app-data:
  image: php:7.0-fpm
  container_name: app-data-container
  volumes:
    - ./www/html/:/var/www/html/
  command: "true"

mysql:
  image: mysql:latest
  container_name: mysql-container
  ports:
    - 3306:3306
  volumes_from:
    - mysql-data
  environment:
    MYSQL_ROOT_PASSWORD: secret
    MYSQL_DATABASE: name_db
    MYSQL_USER: user
    MYSQL_PASSWORD: password

mysql-data:
  image: mysql:latest
  container_name: mysql-data-container
  volumes:
    - /var/lib/mysql
  command: "true"

Body:
You can run a container setting a shared directory (-v volume), and then run bash in that container. After this, you can interactively use mysql-client to execute the .sql file, from inside the container. obs: /my-host-dir/shared-dir is the .sql location in the host system.

docker run --detach --name=test-mysql -p host-port:container-port  --env="MYSQL_ROOT_PASSWORD=my-root-pswd" -v /my-host-dir/shared-dir:/container-dir mysql:latest

docker exec -it test-mysql bash

Inside the container...

mysql -p < /container-dir/file.sql

Custom parameters:

test-mysql (container name)

host-port and container-port

my-root-pswd (mysql root password)

/my-host-dir/shared-dir and /container-dir (the host directory that will be mounted in the container, and the container location of the shared directory)


问:
Dealing with special characters PHP Webdriver
I'm trying to send a special character (é) using sendkeys, example:

```<code>$webdriver->findElement(element)->sendKeys('Sévigny');
</code>```

and its returning an error

#4 /file.php(136): Facebook\WebDriver\Remote\RemoteWebElement->sendKeys('S\xE9vigny')

#5 in /vendor/facebook/webdriver/lib/Exception/WebDriverException.php on line 114

I tried decoding the character first, but it didn't help. I also saw solutions that mention WebUtility.HtmlDecode, but I'm not sure how this is done PHP webdriver and there's no mention of it in documentation

Thank you

答:
How about this:</p>

```<code>$webdriver->findElement(element)->sendKeys(utf8_encode('Sévigny'));
</code>```

Body:
I'm trying to send a special character (é) using sendkeys, example:

$webdriver->findElement(element)->sendKeys('Sévigny');

and its returning an error

#4 /file.php(136): Facebook\WebDriver\Remote\RemoteWebElement->sendKeys('S\xE9vigny')

#5 in /vendor/facebook/webdriver/lib/Exception/WebDriverException.php on line 114

I tried decoding the character first, but it didn't help. I also saw solutions that mention WebUtility.HtmlDecode, but I'm not sure how this is done PHP webdriver and there's no mention of it in documentation

Thank you

Body:
How about this:

$webdriver->findElement(element)->sendKeys(utf8_encode('Sévigny'));


问:
How to filter on the duplicate rows of a dataframe?
I want to add condition to extract the duplicate rows in a dataframe

DF

```<code>KEY    STAT    NUM      ID
ab      L       3       1678
cd      D       4       23221
ab      D       8       1678
cd      L       0       38754
</code>```

For duplicate key I need to check for ID if that is same then keep both the rows.
If ID is different then I need to check NUM and keep the one with greater NUM value and ignore other

Expected OUTPUT

```<code>KEY    STAT    NUM      ID
ab      L       3       1678
cd      D       4       23221
ab      D       8       1678
</code>```

I have edited the scope a bit because I needed to do a merge on the KEY column.So I am planning to pull out both the duplicate values in the merged table.
This is the code that I wrote keeping @piRSquared answer as reference but not getting desired dataframe.

```<code>def func(d):
    if d.KEY.nunique()>=1:
        if d.ID.nunique()>=1:
            return d
        else:
            return d.nlargest(1,columns=['NUM'])
    else:
        return d
</code>```

```<code>pd.concat([func(d) for _, d in DF.groupby('KEY')])

</code>```

答:
I found a good answer in counting the frequency of a value in a column of a dataframe here:

count the frequency that a value occurs in a dataframe column

Basically to extract duplicates in a dataframe try:

```<code># create a count column
df['Count'] = df.groupby('your_col')['your_col'].transform('count')
# Filter out Count = 1
df = df[(df.Count > 1)]
</code>```

Body:
I want to add condition to extract the duplicate rows in a dataframe

DF

KEY    STAT    NUM      ID
ab      L       3       1678
cd      D       4       23221
ab      D       8       1678
cd      L       0       38754

For duplicate key I need to check for ID if that is same then keep both the rows.
If ID is different then I need to check NUM and keep the one with greater NUM value and ignore other

Expected OUTPUT

KEY    STAT    NUM      ID
ab      L       3       1678
cd      D       4       23221
ab      D       8       1678

I have edited the scope a bit because I needed to do a merge on the KEY column.So I am planning to pull out both the duplicate values in the merged table.
This is the code that I wrote keeping @piRSquared answer as reference but not getting desired dataframe.

def func(d):
    if d.KEY.nunique()>=1:
        if d.ID.nunique()>=1:
            return d
        else:
            return d.nlargest(1,columns=['NUM'])
    else:
        return d

pd.concat([func(d) for _, d in DF.groupby('KEY')])

Body:
I found a good answer in counting the frequency of a value in a column of a dataframe here:

count the frequency that a value occurs in a dataframe column

Basically to extract duplicates in a dataframe try:

# create a count column
df['Count'] = df.groupby('your_col')['your_col'].transform('count')
# Filter out Count = 1
df = df[(df.Count > 1)]


问:
What are the differences between Cloud Dataflow and Dataprep
Both Dataprep and Dataflow can be used for ETL tasks. In fact Dataprep seems to use Dataflow jobs. Is it that the only difference that Dataprep provides tools to write dataflow jobs with a user interface ?</p>

答: Dataprep is a tool for performing ETL on file sources through a UI. Convenient, but relatively limited. Dataflow is a managed service for deploying ETL pipelines written using the apache beam programming model, useful for both batch and streaming data, and can potentially be used with whatever data sources you want (e.g. Kafka, pubsub, datastore, JDBC...). Dataprep is more limited to GCS and BigQuery.</p>


问:
Restrict authorization or reduce result in case specific parameter arent satisfy requirements
Describing University via software I faced an auth issue.

Previously I had only a Headmaster role, which can do and access anything.
But as for now, I need to integrate a Teacher role.

The Teacher role should have an option to access certain features, which could be easily restricted by Authorize attribute. But in some cases, I want to reduce the number of data allowed to access for this role, e.g. not all students of the universe, but the ones who study Teacher's Subject.

All of this is already described in EF, (e.g. teacher-subject, subject-students relationships). But now I struggle to refuse (return 403) request for subject or students which are not allowed to access by Teacher.

I thought about a Specification pattern usage for my Services, so the resulting data will be reduced with a Specification's filter, as it helps reduce the data amount, sometimes to no-data, but didn't help to fully refuse a request.

Could you kindly provide me a link or an architectural idea to satisfy expectations for both use-cases specified above?

```<code>// entity models
class Subject {
    ...
    public Teacher Teacher { get; set; }
    public List<Students> { get; set; }
    ...
}

class Teacher {
    ...
    public List<Subject> Subjects { get; set; }
    ...
}
class Student {
    ...
    public List<Subject> StudiedSubjects {get; set; }
    ...
}

// first use-case I want to solve
public ActionResult<List<Student>> GetStudent()
{
    // previously I just did
    return Ok(_studentsService.GetStudents());

    // but as for now in case of Teacher role accessed the method I want to
    // reduce the number of returned students
}

// second use-case I want to solve
public ActionResult<Subject> GetSubjectDetails(int subjectId)
{
    // previously I just did
    return Ok(_subjectService.GetSubject(subjectId);

    // but as for now in case of Teacher role I need to check whether its
    // allowed to get the subject and return Access denied in case its not
}

</code>```

答:
For your first case, because the Action have no parameters at all, it'll make more sense to return Students that are accessible for a Teacher, or no Students at all if no one take all the subjects of certain Teacher, so 403 are not needed in this case. You could pass the User from controller or inject HttpContextAssessor to StudentService and use it for filtering.

as for your second case, its a perfect situation to return 403 if the SubjectId is not related to the Teacher in context. If you dont mind getting data from database for each request, you can use Requirement combined AuthorizationHandler in a Policy-Based Authorization by retrieving any data you need for authorization from database thus determine if the teacher has access to certain Subject(s). Steps to achieve it:

First setup the policy for the Teachers-Subjects relation and the handlers in Startup.ConfigureServices :

```<code>services.AddAuthorization(options =>
{
    options.AddPolicy("TeacherSubject", policy => policy.Requirements.Add( new TeacherSubjectRequirement() ));
});
services.AddScoped<IAuthorizationHandler, TeacherSubjectHandler>();
</code>```

next create the AuthorizationHandler for that policy:

```<code>public class TeacherSubjectHandler : AuthorizationHandler<TeacherSubjectRequirement>
{
    readonly IHttpContextAccessor _contextAccessor;
    readonly UserManager<AppUser> _usermanager;
    readonly UserToTeacherService _userToTeacherService;

    public ThePolicyAuthorizationHandler(IHttpContextAccessor c, UserManager<AppUser> u, _userToTeacherService s)
    {
        _contextAccessor = c;
        _userManager = u;
        _userToTeacherService = s;
    }

    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authHandlerContext, TeacherSubjectRequirement requirement)
    {
        var user = _userManager.GetUserAsync(_contextAccessor.HttpContext.User);
        var teacher = _userToTeacherService(user); //I assume this service will also retrieve teacher's subjects
        var subjectIds = teacher.Subjects.Select(s => s.SubjectId).ToList();

        if (context.Resource is AuthorizationFilterContext filterContext)
        {
            var subjectIdStr = filterContext.RouteData.Values["id"].ToString();
            if ( int.TryParse(subjectIdStr, out var subjectId) && subjectIds.Contains(subjectId) )
            {
                context.Succeed(requirement);
            }

        }

    }
}
</code>```

as for the Requirement class, its just an empty class:

```<code>public class TeacherSubjectRequirement: IAuthorizationRequirement
{

}
</code>```

Since we're doing the authorization mechanism in AuthorizationHandler, we can leave this class empty. But it will still needed for the policy-based authorization to works.

And then for the policy to take effect, add attribute to the controller

```<code>[Authorize(Policy = "TeacherSubject")]
public ActionResult<Subject> GetSubjectDetails(int subjectId)
{
    //existing code
}
</code>```

But to be honest, I haven't tried putting policy-based attribute in an Action. If this doesn't work, putting the attribute in controller will surely works.

Hope this helps.

Body:
Describing University via software I faced an auth issue.

Previously I had only a Headmaster role, which can do and access anything.
But as for now, I need to integrate a Teacher role.

The Teacher role should have an option to access certain features, which could be easily restricted by Authorize attribute. But in some cases, I want to reduce the number of data allowed to access for this role, e.g. not all students of the universe, but the ones who study Teacher's Subject.

All of this is already described in EF, (e.g. teacher-subject, subject-students relationships). But now I struggle to refuse (return 403) request for subject or students which are not allowed to access by Teacher.

I thought about a Specification pattern usage for my Services, so the resulting data will be reduced with a Specification's filter, as it helps reduce the data amount, sometimes to no-data, but didn't help to fully refuse a request.

Could you kindly provide me a link or an architectural idea to satisfy expectations for both use-cases specified above?

// entity models
class Subject {
    ...
    public Teacher Teacher { get; set; }
    public List<Students> { get; set; }
    ...
}

class Teacher {
    ...
    public List<Subject> Subjects { get; set; }
    ...
}
class Student {
    ...
    public List<Subject> StudiedSubjects {get; set; }
    ...
}

// first use-case I want to solve
public ActionResult<List<Student>> GetStudent()
{
    // previously I just did
    return Ok(_studentsService.GetStudents());

    // but as for now in case of Teacher role accessed the method I want to
    // reduce the number of returned students
}

// second use-case I want to solve
public ActionResult<Subject> GetSubjectDetails(int subjectId)
{
    // previously I just did
    return Ok(_subjectService.GetSubject(subjectId);

    // but as for now in case of Teacher role I need to check whether its
    // allowed to get the subject and return Access denied in case its not
}

Body:
For your first case, because the Action have no parameters at all, it'll make more sense to return Students that are accessible for a Teacher, or no Students at all if no one take all the subjects of certain Teacher, so 403 are not needed in this case. You could pass the User from controller or inject HttpContextAssessor to StudentService and use it for filtering.

as for your second case, its a perfect situation to return 403 if the SubjectId is not related to the Teacher in context. If you dont mind getting data from database for each request, you can use Requirement combined AuthorizationHandler in a Policy-Based Authorization by retrieving any data you need for authorization from database thus determine if the teacher has access to certain Subject(s). Steps to achieve it:

First setup the policy for the Teachers-Subjects relation and the handlers in Startup.ConfigureServices :

services.AddAuthorization(options =>
{
    options.AddPolicy("TeacherSubject", policy => policy.Requirements.Add( new TeacherSubjectRequirement() ));
});
services.AddScoped<IAuthorizationHandler, TeacherSubjectHandler>();

next create the AuthorizationHandler for that policy:

public class TeacherSubjectHandler : AuthorizationHandler<TeacherSubjectRequirement>
{
    readonly IHttpContextAccessor _contextAccessor;
    readonly UserManager<AppUser> _usermanager;
    readonly UserToTeacherService _userToTeacherService;

    public ThePolicyAuthorizationHandler(IHttpContextAccessor c, UserManager<AppUser> u, _userToTeacherService s)
    {
        _contextAccessor = c;
        _userManager = u;
        _userToTeacherService = s;
    }

    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authHandlerContext, TeacherSubjectRequirement requirement)
    {
        var user = _userManager.GetUserAsync(_contextAccessor.HttpContext.User);
        var teacher = _userToTeacherService(user); //I assume this service will also retrieve teacher's subjects
        var subjectIds = teacher.Subjects.Select(s => s.SubjectId).ToList();

        if (context.Resource is AuthorizationFilterContext filterContext)
        {
            var subjectIdStr = filterContext.RouteData.Values["id"].ToString();
            if ( int.TryParse(subjectIdStr, out var subjectId) && subjectIds.Contains(subjectId) )
            {
                context.Succeed(requirement);
            }

        }

    }
}

as for the Requirement class, its just an empty class:

public class TeacherSubjectRequirement: IAuthorizationRequirement
{

}

Since we're doing the authorization mechanism in AuthorizationHandler, we can leave this class empty. But it will still needed for the policy-based authorization to works.

And then for the policy to take effect, add attribute to the controller

[Authorize(Policy = "TeacherSubject")]
public ActionResult<Subject> GetSubjectDetails(int subjectId)
{
    //existing code
}

But to be honest, I haven't tried putting policy-based attribute in an Action. If this doesn't work, putting the attribute in controller will surely works.

Hope this helps.


问:
ui-bootstrap send click value to another controller
I have a main controller, and in it I call a modal. In this modal, I have a model called name and I would like to retrieve this field to store in my localStorage. I searched on several sites but it did not work. My controller is this:

```<code>app.controller('gameCtrl', ['$scope', '$uibModal', function($scope, $uibModal) {

    $scope.openModal ()

    $scope.congratulations = function() {
        if ($scope.matchedCard.length == 2) {
            alert('ACABOU')
            clearInterval($scope.interval);
            $scope.finalTime = $scope.timer.innerHTML;
            $scope.player = [{
                // Here i want save $scope._player (modal)  in local storage
                name: $scope._player = player;
                moves: $scope.moves,
                time: $scope.minute + " minutos " + $scope.second + " segundos"
            }]

            if (localStorage.getItem('players')) {
                var totalPlayers = JSON.parse(localStorage.getItem('players'));
                totalPlayers.push({
                    name: $scope.name,
                    moves: $scope.moves,
                    time: $scope.minute + " minutos " + $scope.second + " segundos"
                })
                localStorage.setItem('players', JSON.stringify(totalPlayers));
            } else {
                localStorage.setItem('players', JSON.stringify($scope.player));
            }
            var totalPlayers = JSON.parse(localStorage.getItem('players'));
        };
    }
</code>```

```<code>    $scope.openModal = function() {
        $uibModal.open({
            templateUrl: '../../../pages/component/modal.html',
            controller: function($scope, $uibModalInstance) {
                $scope.savePlayer = function(player) {
                    $scope._player = player;
                    $uibModalInstance.close();
                };
                $scope.cancel = function() {
                    $uibModalInstance.dismiss('cancel');
                }
            }
        })
    };
</code>```

I would like to send the input value, so I could retrieve it in the tro controller

答:
With promise based modals such as $uibModal, send the data back as an argument to the .close method:

```<code>$scope.openModal = function() {
    return $uibModal.open({
        templateUrl: '../../../pages/component/modal.html',
        controller: function($scope, $uibModalInstance) {
            $scope.savePlayer = function(player) {
                $scope._player = player;
                ̶$̶u̶i̶b̶M̶o̶d̶a̶l̶I̶n̶s̶t̶a̶n̶c̶e̶.̶c̶l̶o̶s̶e̶(̶)̶;̶
                $uibModalInstance.close(player);
            };
            $scope.cancel = function() {
                $uibModalInstance.dismiss('cancel');
            }
        }
    })
};
</code>```

With $uibModal, the promise is attached as the result property of the instance object:

```<code>var modalInstance = $scope.openModal();

modalInstance.result
  .then(function (player) {
     console.log("Modal closed with:", player);
}).catch(function (reason) {
     console.log("Modal cancelled:", reason);
});
</code>```

For more information, see

UI-Bootstrap Directive API Reference - $uibModal

Body:
I have a main controller, and in it I call a modal. In this modal, I have a model called name and I would like to retrieve this field to store in my localStorage. I searched on several sites but it did not work. My controller is this:

app.controller('gameCtrl', ['$scope', '$uibModal', function($scope, $uibModal) {

    $scope.openModal ()

    $scope.congratulations = function() {
        if ($scope.matchedCard.length == 2) {
            alert('ACABOU')
            clearInterval($scope.interval);
            $scope.finalTime = $scope.timer.innerHTML;
            $scope.player = [{
                // Here i want save $scope._player (modal)  in local storage
                name: $scope._player = player;
                moves: $scope.moves,
                time: $scope.minute + " minutos " + $scope.second + " segundos"
            }]

            if (localStorage.getItem('players')) {
                var totalPlayers = JSON.parse(localStorage.getItem('players'));
                totalPlayers.push({
                    name: $scope.name,
                    moves: $scope.moves,
                    time: $scope.minute + " minutos " + $scope.second + " segundos"
                })
                localStorage.setItem('players', JSON.stringify(totalPlayers));
            } else {
                localStorage.setItem('players', JSON.stringify($scope.player));
            }
            var totalPlayers = JSON.parse(localStorage.getItem('players'));
        };
    }

    $scope.openModal = function() {
        $uibModal.open({
            templateUrl: '../../../pages/component/modal.html',
            controller: function($scope, $uibModalInstance) {
                $scope.savePlayer = function(player) {
                    $scope._player = player;
                    $uibModalInstance.close();
                };
                $scope.cancel = function() {
                    $uibModalInstance.dismiss('cancel');
                }
            }
        })
    };

I would like to send the input value, so I could retrieve it in the tro controller

Body:
With promise based modals such as $uibModal, send the data back as an argument to the .close method:

$scope.openModal = function() {
    return $uibModal.open({
        templateUrl: '../../../pages/component/modal.html',
        controller: function($scope, $uibModalInstance) {
            $scope.savePlayer = function(player) {
                $scope._player = player;
                ̶$̶u̶i̶b̶M̶o̶d̶a̶l̶I̶n̶s̶t̶a̶n̶c̶e̶.̶c̶l̶o̶s̶e̶(̶)̶;̶
                $uibModalInstance.close(player);
            };
            $scope.cancel = function() {
                $uibModalInstance.dismiss('cancel');
            }
        }
    })
};

With $uibModal, the promise is attached as the result property of the instance object:

var modalInstance = $scope.openModal();

modalInstance.result
  .then(function (player) {
     console.log("Modal closed with:", player);
}).catch(function (reason) {
     console.log("Modal cancelled:", reason);
});

For more information, see

UI-Bootstrap Directive API Reference - $uibModal


问:
Do I have to write a privacy policy if i'm using unity analytics or unity advertisement or facebook sdk
I have set up unity analytics and unity advertisement and Facebook SDK on my android game, I have published it several times and it got suspended two times, I don't want to risk anymore so I wanted to know if I should write a private policy telling the users why I use unity and stuff?
Thank you in advance :)</p>

答:
You need a privacy policy, but you don't necessarily have to write one yourself. On the Unity forums, if you're using Unity Analytics and Unity Ads, they recommend using the following link for your privacy policy when publishing to the Google Play Store:

https://unity3d.com/legal/privacy-policy

I use it for my game, and I've never had a problem.


问:
Get Value from range from another sheet to list
I am trying to get values from the column A of the sheet "Listing", to use it in a combo box in the "Menu" sheet.

Here the code of the menu sheet:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect([4:7], Target) Is Nothing  And Target.Count = 1 Then
     ActiveSheet.DropDowns.Delete
        Set CB = Me.Shapes.AddFormControl(xlDropDown, Left:=Target.Left,
        Top:=Target.Top, Width:=60, Height:=15)
        With CB
            .name = "CB"
            .OnAction = "CB_Change"
            .List = Worksheets("Listing").Range("A1").Value
        End With

    End If
End Sub
</code>```

The Worksheets("Listing").Range("A1").Value fails and I get an

error 438: object doesn't support this property or method

答:
This works:</p>

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim lst

    If Not Intersect([4:7], Target) Is Nothing And Target.Count = 1 Then

        With Worksheets("Listing")
            lst = "'" & .Name & "'!" & _
               .Range(.Range("a1"), _
                      .Cells(.Rows.Count, 1).End(xlUp)).Address()
        End With

        Me.DropDowns.Delete
        With Me.Shapes.AddFormControl(xlDropDown, Left:=Target.Left, _
                                      top:=Target.top, Width:=60, Height:=15)
             .Name = "CB"
            .OnAction = "CB_Change"
            .ControlFormat.ListFillRange = lst
        End With

    End If
End Sub
</code>```

Body:
I am trying to get values from the column A of the sheet "Listing", to use it in a combo box in the "Menu" sheet.

Here the code of the menu sheet:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect([4:7], Target) Is Nothing  And Target.Count = 1 Then
     ActiveSheet.DropDowns.Delete
        Set CB = Me.Shapes.AddFormControl(xlDropDown, Left:=Target.Left,
        Top:=Target.Top, Width:=60, Height:=15)
        With CB
            .name = "CB"
            .OnAction = "CB_Change"
            .List = Worksheets("Listing").Range("A1").Value
        End With

    End If
End Sub

The Worksheets("Listing").Range("A1").Value fails and I get an

error 438: object doesn't support this property or method

Body:
This works:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim lst

    If Not Intersect([4:7], Target) Is Nothing And Target.Count = 1 Then

        With Worksheets("Listing")
            lst = "'" & .Name & "'!" & _
               .Range(.Range("a1"), _
                      .Cells(.Rows.Count, 1).End(xlUp)).Address()
        End With

        Me.DropDowns.Delete
        With Me.Shapes.AddFormControl(xlDropDown, Left:=Target.Left, _
                                      top:=Target.top, Width:=60, Height:=15)
             .Name = "CB"
            .OnAction = "CB_Change"
            .ControlFormat.ListFillRange = lst
        End With

    End If
End Sub