问:
Iterate through video's in Videojs
Thanks for looking at my question. For a assignment I need to iterate through 5 video's in a JQuery accordion. We need to create our own buttons, which have their own functions. At the moment I have 5 div's with different videos, however, when I want to play for instance the second video, the first video will start playing. This will also be the case for the 3th, 4th and 5th video.

Question:
How can I change my code, so each play button will be working for each different video? My guess is the JQuery Each function, but I have no clue.

```<code>        <div id="video-wrap">
            <div id="accordion">
                <div class="acc-wrap"><img class="arrow" src="img/arrow.svg" alt="arrow">
                    <h3>Introduction</h3>
                </div>
                <div>
                    <div class="video-player" id="player-1">
                        <video id="my-video-1" class="video-js" preload="auto" width="1088px" height="612"
                            data-setup="{}">
                            <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4" />
                            <p class="vjs-no-js">
                                To view this video please enable JavaScript, and consider upgrading to a
                                web browser that
                                <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5
                                    video</a>
                            </p>
                        </video>
                        <div class="player-buttons">
                            <a class="play-toggle" class="video-play">
                                <img class="pause" src="img/play-btn.svg" alt="pause button">
                                <img class="play" src="img/play-btn2.svg" alt="play button">
                            </a>
                            <a class="forward-btn">
                                <img src="img/forward btn.svg" alt="forward button">
                            </a>
                            <a class="rewind-btn">
                                <img src="img/rewind btn.svg" alt="forward button">
                            </a>
                        </div>
                    </div>
                </div>
                <div class="acc-wrap"><img class="arrow" src="img/arrow.svg" alt="arrow">
                    <h3>Daniel Shiffman: Coding Challenge 1</h3>
                </div>
                <div>
                    <div class="video-player" id="player-2">
                        <video id="my-video-2" class="video-js" preload="auto" width="1088px" height="612"
                            data-setup="{}">
                            <source src="video/citral.mp4" type="video/mp4" />
                            <p class="vjs-no-js">
                                To view this video please enable JavaScript, and consider upgrading to a
                                web browser that
                                <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5
                                    video</a>
                            </p>
                        </video>
                        <div class="player-buttons">
                            <a class="play-toggle" class="video-play">
                                <img class="pause" src="img/play-btn.svg" alt="pause button">
                                <img class="play" src="img/play-btn2.svg" alt="play button">
                            </a>
                            <a class="forward-btn">
                                <img src="img/forward btn.svg" alt="forward button">
                            </a>
                            <a class="rewind-btn">
                                <img src="img/rewind btn.svg" alt="forward button">
                            </a>
                        </div>
                    </div>
                </div>
                <div class="acc-wrap"><img src="img/arrow.svg" alt="arrow">
                    <h3>Daniel Shiffman: Coding Challenge 2</h3>
                </div>
                <div>
                    <div class="video-player" id="player-3">
                        <video controls id="my-video-3" class="video-js" preload="auto" width="1088px" height="612"
                            data-setup="{}">
                            <source src="https://player.vimeo.com/video/420225730" type="video/mp4" />
                            <p class="vjs-no-js">
                                To view this video please enable JavaScript, and consider upgrading to a
                                web browser that
                                <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5
                                    video</a>
                            </p>
                        </video>
                        <div class="player-buttons">
                            <a class="play-toggle" class="video-play">
                                <img class="pause" src="img/play-btn.svg" alt="pause button">
                                <img class="play" src="img/play-btn2.svg" alt="play button">
                            </a>
                            <a class="forward-btn">
                                <img src="img/forward btn.svg" alt="forward button">
                            </a>
                            <a class="rewind-btn">
                                <img src="img/rewind btn.svg" alt="forward button">
                            </a>
                        </div>
                    </div>
                </div>
                <div class="acc-wrap"><img src="img/arrow.svg" alt="arrow">
                    <h3>Daniel Shiffman: Coding Challenge 3</h3>
                </div>
                <div>
                    <div class="video-player" id="player-4">
                        <video controls id="my-video-4" class="video-js" preload="auto" width="1088px" height="612"
                            data-setup="{}">
                            <source src="https://player.vimeo.com/video/420225730" type="video/mp4" />
                            <p class="vjs-no-js">
                                To view this video please enable JavaScript, and consider upgrading to a
                                web browser that
                                <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5
                                    video</a>
                            </p>
                        </video>
                        <div class="player-buttons">
                            <a class="play-toggle" class="video-play">
                                <img class="pause" src="img/play-btn.svg" alt="pause button">
                                <img class="play" src="img/play-btn2.svg" alt="play button">
                            </a>
                            <a class="forward-btn">
                                <img src="img/forward btn.svg" alt="forward button">
                            </a>
                            <a class="rewind-btn">
                                <img src="img/rewind btn.svg" alt="forward button">
                            </a>
                        </div>
                    </div>
                </div>
                <div class="acc-wrap"><img src="img/arrow.svg" alt="arrow">
                    <h3>Daniel Shiffman: Coding Challenge 4</h3>
                </div>
                <div>
                    <div class="video-player" id="player-5">
                        <video controls id="my-video-5" class="video-js" preload="auto" width="1088px" height="612"
                            data-setup="{}">
                            <source src="https://player.vimeo.com/video/420225730" type="video/mp4" />
                            <p class="vjs-no-js">
                                To view this video please enable JavaScript, and consider upgrading to a
                                web browser that
                                <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5
                                    video</a>
                            </p>
                        </video>
                        <div class="player-buttons">
                            <a class="play-toggle" class="video-play">
                                <img class="pause" src="img/play-btn.svg" alt="pause button">
                                <img class="play" src="img/play-btn2.svg" alt="play button">
                            </a>
                            <a class="forward-btn">
                                <img src="img/forward btn.svg" alt="forward button">
                            </a>
                            <a class="rewind-btn">
                                <img src="img/rewind btn.svg" alt="forward button">
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
</code>```
```<code>// Play/pause toggle //
$('.play-toggle').click(function () {
    if ($('.acc-wrap').hasClass("ui-state-active")) {
        if (player.paused()) {
            player.play();
            $('.play').css({
                "visibility": "visible",
            });
            $('.pause').css({
                "visibility": "hidden",
            });
        } else {
            player.pause();
            $('.play').css({
                "visibility": "hidden",
            });
            $('.pause').css({
                "visibility": "visible",
            });
        };
    };
});
</code>```

答:
I would recommend looking into learning more about Scope and Classes / Object Prototypes.

The problem with you jQuery code right away is that there are multiple .play-toggle classes and you currently have no way of identifying the correct video in which this play button belongs to.

You can begin to scope if by passing the event param into your click handler to identify which item is actually being clicked on

```<code>$('.play-toggle').click(function (event) {
    console.log(event)
})
</code>```

From here you can identify parent container find the video and hook into the play pause functions. However I would recommend another approach.

Step 1: Create a VideoPlayer Class to house all VideoPlayer functionality

```<code>class VideoPlayer {
    constructor(el) {
        this._el = el
        this._video = el.querySelector('video')
        this._playToggle = el.querySelector('.play-toggle')

        this.setupEventListeners()
    }

    setupEventListeners() {
        this._playToggle.addEventListener('click',() => {
            console.log(`play button clicked on element id ${this._el.id}`)
        })
    }
}
</code>```

If you are not sure about classes please read up on them, here we are scoping the video player elements and saving them as variables and then initialising an event listener that listens for you click event. You would store all your video player functionality inside this class

Step 2: Iterate through the page and identify all potential video players

```<code>let videoPlayers = document.querySelectorAll('.video-player')
</code>```

Here we know all video players are wrapped in the parent class video-player if you console.log(videoPlayers) you should see an array of elements

Step 3. Create an instance of the VideoPlayer class for each element

```<code>videos.forEach(v => new VideoPlayer(v))
</code>```

This will create a new instance of the VidePlayer class for each item you have inside videoPlayers, now if you click a play button you should see a log in your console of play button clicked on element id (whatever id)

Once again inside your video player class I would house all the logic for your buttons, here you can hook into whatever HTML5 video events you want to customize your video player.

Please note that you will have to handle removing your event listeners on your own, this is not a complete answer but should give you enough information on how to solve your problem

Title: Iterate through video's in Videojs

Body:
Thanks for looking at my question. For a assignment I need to iterate through 5 video's in a JQuery accordion. We need to create our own buttons, which have their own functions. At the moment I have 5 div's with different videos, however, when I want to play for instance the second video, the first video will start playing. This will also be the case for the 3th, 4th and 5th video.

Question:
How can I change my code, so each play button will be working for each different video? My guess is the JQuery Each function, but I have no clue.

Introduction

                        <video id="my-video-1" class="video-js" preload="auto" width="1088px" height="612"
                            data-setup="{}">
                            <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4" />

                                To view this video please enable JavaScript, and consider upgrading to a
                                web browser that
                                supports HTML5
                                    video

                        </video>

Daniel Shiffman: Coding Challenge 1

                        <video id="my-video-2" class="video-js" preload="auto" width="1088px" height="612"
                            data-setup="{}">
                            <source src="video/citral.mp4" type="video/mp4" />

                                To view this video please enable JavaScript, and consider upgrading to a
                                web browser that
                                supports HTML5
                                    video

                        </video>

Daniel Shiffman: Coding Challenge 2

                        <video controls id="my-video-3" class="video-js" preload="auto" width="1088px" height="612"
                            data-setup="{}">
                            <source src="https://player.vimeo.com/video/420225730" type="video/mp4" />

                                To view this video please enable JavaScript, and consider upgrading to a
                                web browser that
                                supports HTML5
                                    video

                        </video>

Daniel Shiffman: Coding Challenge 3

                        <video controls id="my-video-4" class="video-js" preload="auto" width="1088px" height="612"
                            data-setup="{}">
                            <source src="https://player.vimeo.com/video/420225730" type="video/mp4" />

                                To view this video please enable JavaScript, and consider upgrading to a
                                web browser that
                                supports HTML5
                                    video

                        </video>

Daniel Shiffman: Coding Challenge 4

                        <video controls id="my-video-5" class="video-js" preload="auto" width="1088px" height="612"
                            data-setup="{}">
                            <source src="https://player.vimeo.com/video/420225730" type="video/mp4" />

                                To view this video please enable JavaScript, and consider upgrading to a
                                web browser that
                                supports HTML5
                                    video

                        </video>

// Play/pause toggle //
$('.play-toggle').click(function () {
    if ($('.acc-wrap').hasClass("ui-state-active")) {
        if (player.paused()) {
            player.play();
            $('.play').css({
                "visibility": "visible",
            });
            $('.pause').css({
                "visibility": "hidden",
            });
        } else {
            player.pause();
            $('.play').css({
                "visibility": "hidden",
            });
            $('.pause').css({
                "visibility": "visible",
            });
        };
    };
});

Body:
I would recommend looking into learning more about Scope and Classes / Object Prototypes.

The problem with you jQuery code right away is that there are multiple .play-toggle classes and you currently have no way of identifying the correct video in which this play button belongs to.

You can begin to scope if by passing the event param into your click handler to identify which item is actually being clicked on

$('.play-toggle').click(function (event) {
    console.log(event)
})

From here you can identify parent container find the video and hook into the play pause functions. However I would recommend another approach.

Step 1: Create a VideoPlayer Class to house all VideoPlayer functionality

class VideoPlayer {
    constructor(el) {
        this._el = el
        this._video = el.querySelector('video')
        this._playToggle = el.querySelector('.play-toggle')

        this.setupEventListeners()
    }

    setupEventListeners() {
        this._playToggle.addEventListener('click',() => {
            console.log(`play button clicked on element id ${this._el.id}`)
        })
    }
}

If you are not sure about classes please read up on them, here we are scoping the video player elements and saving them as variables and then initialising an event listener that listens for you click event. You would store all your video player functionality inside this class

Step 2: Iterate through the page and identify all potential video players

let videoPlayers = document.querySelectorAll('.video-player')

Here we know all video players are wrapped in the parent class video-player if you console.log(videoPlayers) you should see an array of elements

Step 3. Create an instance of the VideoPlayer class for each element

videos.forEach(v => new VideoPlayer(v))

This will create a new instance of the VidePlayer class for each item you have inside videoPlayers, now if you click a play button you should see a log in your console of play button clicked on element id (whatever id)

Once again inside your video player class I would house all the logic for your buttons, here you can hook into whatever HTML5 video events you want to customize your video player.

Please note that you will have to handle removing your event listeners on your own, this is not a complete answer but should give you enough information on how to solve your problem


来源: stackexchange

问:
Keras: Unable to use custom loss function in my model
I'm building a language model using Keras and I would like to use perplexity as my loss function, However when I tried to compile my model with my loss function, I get a value error saying that the loss function is unknown.

My loss function looks as follows:

```<code>def perplexity_loss(y_true, y_pred):
    """
    The perplexity metric. Why isn't this part of Keras yet?!
    https://stackoverflow.com/questions/41881308/how-to-calculate-perplexity-of-rnn-in-tensorflow
    https://github.com/keras-team/keras/issues/8267
    """
    cross_entropy = keras.losses.SparseCategoricalCrossentropy(y_true, y_pred)
    perplexity = tf.keras.backend.exp(cross_entropy)
    return perplexity
</code>```

And this is how I initiate my model:

```<code># define model
model = Sequential()
model.add(Embedding(vocab_size, 500, input_length=max_length-1))
model.add(LSTM(750))
model.add(Dense(vocab_size, activation='softmax'))
# compile network
model.compile(loss='perplexity_loss', optimizer='adam', metrics=['accuracy'])
# fit network
model.fit(X, y, epochs=150, verbose=2)
</code>```

I get the following error:

```<code>ValueError: Unknown loss function:perplexity
</code>```

答:
The error is caused because instead of the function, you are passing a string ('perplexity_loss'). The following should do the trick:

```<code>model.compile(loss=perplexity_loss, optimizer='adam', metrics=['accuracy'])
</code>```

Note that when you'd want to load the model again, you would have to use:

```<code>from keras.models import load_model

model = load_model('my_model.h5', custom_objects={'perplexity_loss': perplexity_loss})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm building a language model using Keras and I would like to use perplexity as my loss function, However when I tried to compile my model with my loss function, I get a value error saying that the loss function is unknown.

My loss function looks as follows:

def perplexity_loss(y_true, y_pred):
    """
    The perplexity metric. Why isn't this part of Keras yet?!
    https://stackoverflow.com/questions/41881308/how-to-calculate-perplexity-of-rnn-in-tensorflow
    https://github.com/keras-team/keras/issues/8267
    """
    cross_entropy = keras.losses.SparseCategoricalCrossentropy(y_true, y_pred)
    perplexity = tf.keras.backend.exp(cross_entropy)
    return perplexity

And this is how I initiate my model:

# define model
model = Sequential()
model.add(Embedding(vocab_size, 500, input_length=max_length-1))
model.add(LSTM(750))
model.add(Dense(vocab_size, activation='softmax'))
# compile network
model.compile(loss='perplexity_loss', optimizer='adam', metrics=['accuracy'])
# fit network
model.fit(X, y, epochs=150, verbose=2)

I get the following error:

ValueError: Unknown loss function:perplexity

Body:
The error is caused because instead of the function, you are passing a string ('perplexity_loss'). The following should do the trick:

model.compile(loss=perplexity_loss, optimizer='adam', metrics=['accuracy'])

Note that when you'd want to load the model again, you would have to use:

from keras.models import load_model

model = load_model('my_model.h5', custom_objects={'perplexity_loss': perplexity_loss})


问:
Not able to run Elasticsearch in docker on amazon Ec2 instance
I am trying to run elasticsearch 7.7 in docker container using t2.medium instance and went through this SO question and official ES docs on installing ES using docker but even after giving discovery.type: single-node its not bypassing the bootstrap checks mentioned in several posts.

My elasticsearch.yml file

```<code>cluster.name: scanner
node.name: node-1
network.host: 0.0.0.0
discovery.type: single-node
cluster.initial_master_nodes: node-1 // tried explicitly giving this but no luck
xpack.security.enabled: true
</code>```

My Dockerfile

```<code>FROM docker.elastic.co/elasticsearch/elasticsearch:7.7.0
COPY elasticsearch.yml /usr/share/elasticsearch/elasticsearch.yml
USER root
RUN chmod go-w /usr/share/elasticsearch/elasticsearch.yml
RUN chown root:elasticsearch /usr/share/elasticsearch/elasticsearch.yml
USER elasticsearch
</code>```

And this is how I am building and running the image.

```<code>docker build -t es:latest .
docker run --ulimit nofile=65535:65535 -p 9200:9200 es:latest
</code>```

And relevant error logs

75", "message": "bound or publishing to a non-loopback address,
  enforcing bootstrap checks" } ERROR: 1 bootstrap checks failed 1:
  the default discovery settings are unsuitable for production use; at
  least one of [discovery.seed_hosts, discovery.seed_providers,
  cluster.initial_master_nodes] must be configured ERROR: Elasticsearch
  did not exit normally - check the logs at
  /usr/share/elasticsearch/logs/docker-cluster.log

答:
Elasticsearch in a single node

```<code>version: '3.7'
services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.7.0
    container_name: elasticsearch
    environment:
      - node.name=vibhuvi-node
      - discovery.type=single-node
      - cluster.name=vibhuvi-es-data-cluster
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms1024m -Xmx1024m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - vibhuviesdata:/usr/share/elasticsearch/data
    ports:
      - 9200:9200
    networks:
      - elastic
networks:
  elastic:
    driver: bridge
volumes:
  vibhuviesdata:
    driver: local
</code>```

Run

docker-compose up -d

Body:
I am trying to run elasticsearch 7.7 in docker container using t2.medium instance and went through this SO question and official ES docs on installing ES using docker but even after giving discovery.type: single-node its not bypassing the bootstrap checks mentioned in several posts.

My elasticsearch.yml file

cluster.name: scanner
node.name: node-1
network.host: 0.0.0.0
discovery.type: single-node
cluster.initial_master_nodes: node-1 // tried explicitly giving this but no luck
xpack.security.enabled: true

My Dockerfile

FROM docker.elastic.co/elasticsearch/elasticsearch:7.7.0
COPY elasticsearch.yml /usr/share/elasticsearch/elasticsearch.yml
USER root
RUN chmod go-w /usr/share/elasticsearch/elasticsearch.yml
RUN chown root:elasticsearch /usr/share/elasticsearch/elasticsearch.yml
USER elasticsearch

And this is how I am building and running the image.

docker build -t es:latest .
docker run --ulimit nofile=65535:65535 -p 9200:9200 es:latest

And relevant error logs

75", "message": "bound or publishing to a non-loopback address,
  enforcing bootstrap checks" } ERROR: 1 bootstrap checks failed 1:
  the default discovery settings are unsuitable for production use; at
  least one of [discovery.seed_hosts, discovery.seed_providers,
  cluster.initial_master_nodes] must be configured ERROR: Elasticsearch
  did not exit normally - check the logs at
  /usr/share/elasticsearch/logs/docker-cluster.log

Body:
Elasticsearch in a single node

version: '3.7'
services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.7.0
    container_name: elasticsearch
    environment:
      - node.name=vibhuvi-node
      - discovery.type=single-node
      - cluster.name=vibhuvi-es-data-cluster
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms1024m -Xmx1024m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - vibhuviesdata:/usr/share/elasticsearch/data
    ports:
      - 9200:9200
    networks:
      - elastic
networks:
  elastic:
    driver: bridge
volumes:
  vibhuviesdata:
    driver: local

Run

docker-compose up -d


问:
Is there any way to freeze the build in Cruise Control .NET?
I am using Cruise Control .NET to automate the build. I have configured lots of project for the automated build in CCNET. Is there any way to freeze particular build and after sometime, i wanna release that to old state, like i wanna remove the freeze and the user would be able to build it again.

Can i do some configuration for the same?

答:
You have to edit the config file. The easiest way is to set the <triggers/> to empty. That way you can still manually force a build but the automation will stop.

```<code><cruisecontrol>
   <project name="MyProject">
      <webURL>http://mybuildserver/ccnet/</webURL>
      <triggers>
      <!-- No more automated builds -->
      <!-- <intervalTrigger seconds="60" /> -->
      </triggers>
      <modificationDelaySeconds>10</modificationDelaySeconds>
</code>```

Update

This is mainly when i give a build to
  QA for testing, and others should not
  force buil by mistake and change the
  build. For this reason i am looking
  something which can freeze the build.

You shouldn't rely on having to pause the build system. The whole point of CruiseControl is to implement a continuous build system. You are breaking that model by trying to stop the builds. You should setup a pipeline for your builds:

Tag Build with Date and Release information. Release Candidate 0.1 Build 23423_20110602

Deploy a build to another machine for testing.

This way you know exactly which build the QA team is testing. And more importantly, you can go back in time in your version control system to see the code or branch.

There isn't any point having CruiseControl if the policy is to pause the build for each QA cycle. I suggest rethinking the process and coming up with a solution that doesn't involve having to stop the builds.

ContentLicense: CC BY-SA 3.0

Body:
You have to edit the config file. The easiest way is to set the <triggers/> to empty. That way you can still manually force a build but the automation will stop.

<cruisecontrol>
   <project name="MyProject">
      <webURL>http://mybuildserver/ccnet/</webURL>
      <triggers>
      <!-- No more automated builds -->
      <!-- <intervalTrigger seconds="60" /> -->
      </triggers>
      <modificationDelaySeconds>10</modificationDelaySeconds>

Update

This is mainly when i give a build to
  QA for testing, and others should not
  force buil by mistake and change the
  build. For this reason i am looking
  something which can freeze the build.

You shouldn't rely on having to pause the build system. The whole point of CruiseControl is to implement a continuous build system. You are breaking that model by trying to stop the builds. You should setup a pipeline for your builds:

Tag Build with Date and Release information. Release Candidate 0.1 Build 23423_20110602

Deploy a build to another machine for testing.

This way you know exactly which build the QA team is testing. And more importantly, you can go back in time in your version control system to see the code or branch.

There isn't any point having CruiseControl if the policy is to pause the build for each QA cycle. I suggest rethinking the process and coming up with a solution that doesn't involve having to stop the builds.


问:
saving state into localstorage in react
I call this function on every button click.

the problem is when the button first clicked it doesn't save the first element until next clicks
so the first element never get saved

 const add=()=>{
    if(website){
      setInfo([...info,{website:website,password:generate()}])
      localStorage.setItem("data",JSON.stringify(info));
    }
  }
```

<p>state info:</p>

<pre class="lang-js prettyprint-override"><code>const[info,setInfo]=useState([])
</code>```

答:
setInfo change will be available on the next render. You should calculate the value in a separate variable and then set it.</p>

```<code>const add=()=>{
  if(website){
    let value = [...info,{website:website,password:generate()}];
    setInfo(value)
    localStorage.setItem("data",JSON.stringify(value));
  }
}
</code>```

Title: saving state into localstorage in react

Body:
I call this function on every button click.

the problem is when the button first clicked it doesn't save the first element until next clicks
so the first element never get saved

 const add=()=>{
    if(website){
      setInfo([...info,{website:website,password:generate()}])
      localStorage.setItem("data",JSON.stringify(info));
    }
  }

state info:

const[info,setInfo]=useState([])

Body:
setInfo change will be available on the next render. You should calculate the value in a separate variable and then set it.

const add=()=>{
  if(website){
    let value = [...info,{website:website,password:generate()}];
    setInfo(value)
    localStorage.setItem("data",JSON.stringify(value));
  }
}


问:
How to create invoices from an external module in odoo
I created a custom module and in that module, the user should be able to create invoices from sales generated in the module.

The function I am using seems to work fine and I can even get the id of the created invoice, but the invoice does not show in the Accounting module of Odoo13.

This is the code am using to create the invoice with:

```<code>invoice_vals = {
        'partner_id': 1,
        'state': 'draft',
        'invoice_date': self.date,
        'invoice_payment_term_id': 1,
        'invoice_line_ids': [0, 0, {
            'name': 'name',
            'account_id': 2,
            'analytic_account_id': 1,
            'quanitity': 100,
            'price_unit': 100,
        }]
    }
    invoice = self.env['account.move'].sudo().create(invoice_vals)
</code>```

I have hard coded the values for now just to test that it should work.

答:
It will create a draft journal entry visible under Invoicing/Accounting/Miscellaneous/Journal Entries.

Customer and vendor bills are filtered using type field, out_invoice for Customer invoice, and in_invoice for vendor bill.

Fix quanitity field name, it should be quantity.

Body:
I created a custom module and in that module, the user should be able to create invoices from sales generated in the module.

The function I am using seems to work fine and I can even get the id of the created invoice, but the invoice does not show in the Accounting module of Odoo13.

This is the code am using to create the invoice with:

invoice_vals = {
        'partner_id': 1,
        'state': 'draft',
        'invoice_date': self.date,
        'invoice_payment_term_id': 1,
        'invoice_line_ids': [0, 0, {
            'name': 'name',
            'account_id': 2,
            'analytic_account_id': 1,
            'quanitity': 100,
            'price_unit': 100,
        }]
    }
    invoice = self.env['account.move'].sudo().create(invoice_vals)

I have hard coded the values for now just to test that it should work.


问:
float not working in mysql database
i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.</p>

```<code>include 'connect.php';

$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");

while ($row=mysql_fetch_assoc($sql)) {

$start=$row['start'];

}

echo $start; //nothing happens
</code>```

答:
WHERE stuff = '$stuff' is a String comparison.

Compare number like so

```<code>WHERE stuff = $stuff
</code>```

Title: float not working in mysql database

Body:
i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.

include 'connect.php';

$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");

while ($row=mysql_fetch_assoc($sql)) {

$start=$row['start'];

}

echo $start; //nothing happens

Body:
WHERE stuff = '$stuff' is a String comparison.

Compare number like so

WHERE stuff = $stuff


问:
adminer in a kubernetes pod
I am trying to create a pod with both phpmyadmin and adminer in it. I have the Dockerfile created but I am not sure of the entrypoint needed.

Has anyone accomplished this before? I have everything figured out but the entrypoint...

```<code>FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]

FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]
</code>```

------UPDATE 1 ----------
after read some comments I spilt my Dockerfiles and will create a yml file for the kube pod

```<code>FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]
</code>```

container 2

```<code>FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]
</code>```

I am still not sure what the entrypoint script should be

答:
You'd almost always run this in two separate Deployments.  Since the only thing you're doing in this custom Dockerfile is setting environment variables, you don't even need a custom image; you can use the env: part of the pod spec to define environment variables at deploy time.

image: adminer:4 # without PHPMyAdmin
env:
  - name: POSTGRES_DB
    value: [...]       # fixed value in pod spec
    # valueFrom: ...   # or get it from a ConfigMap or Secret
```

Run two Deployments, with one container in each, and a matching Service for each.  (Don't run bare pods, and don't be tempted to put both containers in a single deployment.)  If the databases are inside Kubernetes too, use their Services' names and ports; I'd usually expect these to be the "normal" 3306/5432 ports.

Title: adminer in a kubernetes pod

Body:
I am trying to create a pod with both phpmyadmin and adminer in it. I have the Dockerfile created but I am not sure of the entrypoint needed.

Has anyone accomplished this before? I have everything figured out but the entrypoint...

FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]

FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]

------UPDATE 1 ----------
after read some comments I spilt my Dockerfiles and will create a yml file for the kube pod

FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]

container 2

FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]

I am still not sure what the entrypoint script should be

Body:
You'd almost always run this in two separate Deployments.  Since the only thing you're doing in this custom Dockerfile is setting environment variables, you don't even need a custom image; you can use the env: part of the pod spec to define environment variables at deploy time.

image: adminer:4 # without PHPMyAdmin
env:
  - name: POSTGRES_DB
    value: [...]       # fixed value in pod spec
    # valueFrom: ...   # or get it from a ConfigMap or Secret

Run two Deployments, with one container in each, and a matching Service for each.  (Don't run bare pods, and don't be tempted to put both containers in a single deployment.)  If the databases are inside Kubernetes too, use their Services' names and ports; I'd usually expect these to be the "normal" 3306/5432 ports.


问:
Use "cmd /c" but hide the console window
I have a shortcut running this command when clicked: cmd /c "full path to my batch file". When I use it, it does what it is supposed to do, but in the process the ugly console window pops up. Is there any way to make this command start a hidden or at least minimized window?

答:
This will create a separate process (without a window), and not block parent window so it can continue your main work:</p>

```<code>start /b cmd /c "full path to my batch file"
</code>```

Body:
This will create a separate process (without a window), and not block parent window so it can continue your main work:

start /b cmd /c "full path to my batch file"


问:
Test IF file exist, ELSE xcopy these two files
Morning all.

So I've been up hours trying to cobble together -a variety of replies to other posts- into my own code in order to see if I could get something usable. No-go. I'm sufficiently lost in the sauce that I've now got to ask for some help from you.

Background:
OS: Windows 10
I use the program text2folders.exe to create 20-30 new folders on a secondary drive every night.
Primarily, I have a base file "aGallery-dl.bat" that I populate each folder with using an xcopy batch file. Secondarily, from time to time I update the source file "aGallery-dl.bat" using the same xcopy and this overwrites the older target file, populating all folders with the newest "aGallery-dl.bat" (whether they need it or not). All is well.

```<code>@echo off
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"
</code>```

I've recently decided I want to add two new files to each folder and have expanded my xcopy to include these. All is well.

```<code>@echo off
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder2.jpg" "%%a\"
</code>```

Folder.jpg
a big red X

Folder2.jpg
a big yellow ! mark

When I choose to run a "aGallery-dl.bat" in a given folder (again, one of 100's), it first deletes Folder.jpg then renames Folder2.jpg to Folder.jpg. This has the effect of the red X being replaced by the yellow ! when viewing the folder in File Explorer parent folder. Secondly, it calls "gallery-dl.exe." I use going from red to yellow to let me know I've run "aGallery-dl.bat" at least once. All is well.

```<code>rem @echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\aGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"
del .\Folder.jpg
</code>```

If "aGallery-dl.bat" completes successfully, it finally deletes the Folder.jpg (currently yellow !), and now the representative contents of the folder (usually DeviantArt .jpg's) are visible.

Problem:
When I have to re-run my original xcopy command to update "aGallery-dl.bat" in ALL FOLDERS, the Folder.jpg and Folder2.jpg will be re-copied to all folders, defeating the purpose of deleting them once via "aGallery-dl.bat." I don't want to have to go back and re-run "aGallery-dl.bat" intermittently across 100's of folders (again, only those that have had aGallery-dl.bat run at least once). I need some type of test, that if "aGallery-dl.bat" is already present in the target folder, DO NOT xcopy Folder.jpg and Folder2.jpg aka vague example, below.

```<code>*********************************Some sort of test statement here!!!***********************

:aGallery-dlPresent
GOTO eof

:aGallery-dlNotPresent
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder2.jpg" "%%a\"
GOTO eof

:eof
</code>```

I had found a hopeful candidate test statement in the below (copied in its original form from what/where I read in other post), but am looking for ideas/replacements as I HAVE NO IDEA how to modify/inject/implement the below to work in the above.

```<code>If exist \\%DIR%\%Folder%\123456789.wav xcopy \\%DIR%\%Folder%\123456789.wav D:\%New Folder%\ /y
</code>```

Having XCopy copy a file and not overwrite the previous one if it exists (without prompting)

Note: The below is a vague approximation of what it should all look like (barring having a correct -test statement-).

```<code>rem @echo off
*********************************Some sort of test statement here!!!***********************

:aGallery-dlPresent
GOTO eof

:aGallery-dlNotPresent
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder2.jpg" "%%a\"
GOTO eof

:eof

for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"
</code>```

答:
The command for copying a file is COPY. It is an internal command of Windows command processor cmd.exe. XCOPY is an eXtended file and directory copying executable in directory %SystemRoot%\System32 which is deprecated since Windows Vista as there is even more powerful ROBOCOPY which is with full qualified file name %SystemRoot%\System32\robocopy.exe.

There is no need to use XCOPY or ROBOCOPY for this simple file copying task. COPY is enough on source files aGallery-dl.bat, Folder.jpgand Folder2.jpg don't have hidden attribute set and the same files in the target directories don't have read-only attribute set.

.\ references the current directory which can be any directory. Windows Explorer sets the directory of the batch file as current directory on double clicking on a batch file. But this is nearly the only method to run a batch file on which the directory of the executed batch file is set automatically as current directory (except the batch file is stored on a network resource accessed using UNC path).

There is %~dp0 to reference the path of the batch file. This path always ends with a backslash which means that no additional backslash is needed on concatenating the batch file path with a file or folder name. The usage of %~dp0 makes it possible to reference files in same directory as the executed batch file independent on which directory is the current directory on execution of the batch file.

The batch file needed for your task is:

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
for /D %%I in ("U:\11Web\gallery-dl\deviantart\*") do (
    if not exist "%%I\aGallery-dl.bat" (
        copy "%~dp0Folder.jpg" "%%I\"
        copy "%~dp0Folder2.jpg" "%%I\"
    )
    copy /Y "%~dp0aGallery-dl.bat" "%%I\"
)
endlocal
</code>```

A file/folder name must be enclosed in " if containing a space or one of these characters &()[]{}^=;!'+,`~. For that reason all file/folder names are enclosed in this batch file in double quotes although inside the batch files no file/folder name contains a space or one of the characters in the list. It is important to understand on batch file writing how a command line looks like after Windows command processor processed the command line. See following topics:

How does the Windows Command Interpreter (CMD.EXE) parse scripts?

How to debug a batch file?

Windows interprets *.* like just * which means any file or folder name. For that reason it is enough to just write * and omit .*.

Please note that for /D ignores directories with hidden attribute set.

The batch file checks first for each subfolder if it does not contain the batch file aGallery-dl.bat. In this case it copies the two files Folder.jpg and Folder2.jpg from directory of executed batch file to current subdirectory of U:\11Web\gallery-dl\deviantart.

Then the batch file aGallery-dl.bat is copied from directory of executed batch file to to current subdirectory of U:\11Web\gallery-dl\deviantart independent on its existence in the destination directory.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /? ... explains %~dp0 ... drive and path of argument 0 ... full batch file path.

cmd /? ... outputs the help of Windows command processor executing a batch file.

copy /?

echo /?

endlocal /?

for /?

if /?

setlocal /?

See also the chapters Issue 6 and Issue 7 in this answer why using setlocal EnableExtensions DisableDelayedExpansion and endlocal although not necessary by default and why using I instead of a as loop variable although a would work here, too.

Body:
Morning all.

So I've been up hours trying to cobble together -a variety of replies to other posts- into my own code in order to see if I could get something usable. No-go. I'm sufficiently lost in the sauce that I've now got to ask for some help from you.

Background:
OS: Windows 10
I use the program text2folders.exe to create 20-30 new folders on a secondary drive every night.
Primarily, I have a base file "aGallery-dl.bat" that I populate each folder with using an xcopy batch file. Secondarily, from time to time I update the source file "aGallery-dl.bat" using the same xcopy and this overwrites the older target file, populating all folders with the newest "aGallery-dl.bat" (whether they need it or not). All is well.

@echo off
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"

I've recently decided I want to add two new files to each folder and have expanded my xcopy to include these. All is well.

@echo off
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder2.jpg" "%%a\"

Folder.jpg
a big red X

Folder2.jpg
a big yellow ! mark

When I choose to run a "aGallery-dl.bat" in a given folder (again, one of 100's), it first deletes Folder.jpg then renames Folder2.jpg to Folder.jpg. This has the effect of the red X being replaced by the yellow ! when viewing the folder in File Explorer parent folder. Secondly, it calls "gallery-dl.exe." I use going from red to yellow to let me know I've run "aGallery-dl.bat" at least once. All is well.

rem @echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\aGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"
del .\Folder.jpg

If "aGallery-dl.bat" completes successfully, it finally deletes the Folder.jpg (currently yellow !), and now the representative contents of the folder (usually DeviantArt .jpg's) are visible.

Problem:
When I have to re-run my original xcopy command to update "aGallery-dl.bat" in ALL FOLDERS, the Folder.jpg and Folder2.jpg will be re-copied to all folders, defeating the purpose of deleting them once via "aGallery-dl.bat." I don't want to have to go back and re-run "aGallery-dl.bat" intermittently across 100's of folders (again, only those that have had aGallery-dl.bat run at least once). I need some type of test, that if "aGallery-dl.bat" is already present in the target folder, DO NOT xcopy Folder.jpg and Folder2.jpg aka vague example, below.

*********************************Some sort of test statement here!!!***********************

:aGallery-dlPresent
GOTO eof

:aGallery-dlNotPresent
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder2.jpg" "%%a\"
GOTO eof

:eof

I had found a hopeful candidate test statement in the below (copied in its original form from what/where I read in other post), but am looking for ideas/replacements as I HAVE NO IDEA how to modify/inject/implement the below to work in the above.

If exist \\%DIR%\%Folder%\123456789.wav xcopy \\%DIR%\%Folder%\123456789.wav D:\%New Folder%\ /y

Having XCopy copy a file and not overwrite the previous one if it exists (without prompting)

Note: The below is a vague approximation of what it should all look like (barring having a correct -test statement-).

rem @echo off
*********************************Some sort of test statement here!!!***********************

:aGallery-dlPresent
GOTO eof

:aGallery-dlNotPresent
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder2.jpg" "%%a\"
GOTO eof

:eof

for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"

Body:
The command for copying a file is COPY. It is an internal command of Windows command processor cmd.exe. XCOPY is an eXtended file and directory copying executable in directory %SystemRoot%\System32 which is deprecated since Windows Vista as there is even more powerful ROBOCOPY which is with full qualified file name %SystemRoot%\System32\robocopy.exe.

There is no need to use XCOPY or ROBOCOPY for this simple file copying task. COPY is enough on source files aGallery-dl.bat, Folder.jpgand Folder2.jpg don't have hidden attribute set and the same files in the target directories don't have read-only attribute set.

.\ references the current directory which can be any directory. Windows Explorer sets the directory of the batch file as current directory on double clicking on a batch file. But this is nearly the only method to run a batch file on which the directory of the executed batch file is set automatically as current directory (except the batch file is stored on a network resource accessed using UNC path).

There is %~dp0 to reference the path of the batch file. This path always ends with a backslash which means that no additional backslash is needed on concatenating the batch file path with a file or folder name. The usage of %~dp0 makes it possible to reference files in same directory as the executed batch file independent on which directory is the current directory on execution of the batch file.

The batch file needed for your task is:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
for /D %%I in ("U:\11Web\gallery-dl\deviantart\*") do (
    if not exist "%%I\aGallery-dl.bat" (
        copy "%~dp0Folder.jpg" "%%I\"
        copy "%~dp0Folder2.jpg" "%%I\"
    )
    copy /Y "%~dp0aGallery-dl.bat" "%%I\"
)
endlocal

A file/folder name must be enclosed in " if containing a space or one of these characters &()[]{}^=;!'+,`~. For that reason all file/folder names are enclosed in this batch file in double quotes although inside the batch files no file/folder name contains a space or one of the characters in the list. It is important to understand on batch file writing how a command line looks like after Windows command processor processed the command line. See following topics:

How does the Windows Command Interpreter (CMD.EXE) parse scripts?

How to debug a batch file?

Windows interprets *.* like just * which means any file or folder name. For that reason it is enough to just write * and omit .*.

Please note that for /D ignores directories with hidden attribute set.

The batch file checks first for each subfolder if it does not contain the batch file aGallery-dl.bat. In this case it copies the two files Folder.jpg and Folder2.jpg from directory of executed batch file to current subdirectory of U:\11Web\gallery-dl\deviantart.

Then the batch file aGallery-dl.bat is copied from directory of executed batch file to to current subdirectory of U:\11Web\gallery-dl\deviantart independent on its existence in the destination directory.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /? ... explains %~dp0 ... drive and path of argument 0 ... full batch file path.

cmd /? ... outputs the help of Windows command processor executing a batch file.

copy /?

echo /?

endlocal /?

for /?

if /?

setlocal /?

See also the chapters Issue 6 and Issue 7 in this answer why using setlocal EnableExtensions DisableDelayedExpansion and endlocal although not necessary by default and why using I instead of a as loop variable although a would work here, too.


问:
Java Swing Help
I'm trying to create a grid of JButtons, with index values to the left and right of the button grid.

Here is my code, but I'm getting a NullPointerException.  What is the problem?

```<code>public class Test {
public static void main(String args[]) {
    JFrame myapp = new JFrame("test");
    myapp.setLayout(new FlowLayout());

    myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myapp.setSize(400,400);
    myapp.setVisible(true);

    myapp.getContentPane().add(Board());
}

private static JPanel Board() {
    JButton[][] buttons = new JButton [10][10];

    JPanel board = new JPanel(new GridLayout(11,11));

    String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
    String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
    JTextField k;

    for (int i = 0; i < 11; i++) {
        for (int j = 0; j < 11; j++) {
            if ((j != 0) && (i != 0)) {
                //myboard[i-1][j-1].addActionListener(new ButtonHandler());
                board.add(buttons[i-1][j-1]);
            }
            if (i == 0) {
                if (j != 0) {
                    // used to display row of numbers
                    k = new JTextField(columnlabels[j]);
                    k.setEditable(false);
                    k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                } else {
                    // used to display column of numbers
                    k = new JTextField();
                    k.setEditable(false);
                }
                board.add(k);
            } else if (j == 0) {
                k = new JTextField(rowlabels[i]);
                k.setEditable(false);
                k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                board.add(k);
            }
        }
    }

    return board;
}
}
</code>```

I'm probably doing something obvious, but Swing is kind of new to me, so any help would be greatly appreciated.

答:
```<code>JButton[][] buttons = new JButton [10][10];
</code>```

only creates an array of nulls, you have to initialize the buttons. and adding null to panel causes a NPE.

Title: Java Swing Help

Body:
I'm trying to create a grid of JButtons, with index values to the left and right of the button grid.

Here is my code, but I'm getting a NullPointerException.  What is the problem?

public class Test {
public static void main(String args[]) {
    JFrame myapp = new JFrame("test");
    myapp.setLayout(new FlowLayout());

    myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myapp.setSize(400,400);
    myapp.setVisible(true);

    myapp.getContentPane().add(Board());
}

private static JPanel Board() {
    JButton[][] buttons = new JButton [10][10];

    JPanel board = new JPanel(new GridLayout(11,11));

    String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
    String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
    JTextField k;

    for (int i = 0; i < 11; i++) {
        for (int j = 0; j < 11; j++) {
            if ((j != 0) && (i != 0)) {
                //myboard[i-1][j-1].addActionListener(new ButtonHandler());
                board.add(buttons[i-1][j-1]);
            }
            if (i == 0) {
                if (j != 0) {
                    // used to display row of numbers
                    k = new JTextField(columnlabels[j]);
                    k.setEditable(false);
                    k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                } else {
                    // used to display column of numbers
                    k = new JTextField();
                    k.setEditable(false);
                }
                board.add(k);
            } else if (j == 0) {
                k = new JTextField(rowlabels[i]);
                k.setEditable(false);
                k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                board.add(k);
            }
        }
    }

    return board;
}
}

I'm probably doing something obvious, but Swing is kind of new to me, so any help would be greatly appreciated.

Body:
JButton[][] buttons = new JButton [10][10];

only creates an array of nulls, you have to initialize the buttons. and adding null to panel causes a NPE.


问:
Can't inherit from IdentityUser and IdentityRole in ASP.NET Core 2.0
I'm trying to finish updating to .NET Core 2.0 but a couple of errors pop up:

The problem:

I have two classes, ApplicationRole and ApplicationUser which inherit some properties from IdentityRole and IdentityUser.

With the update to Core 2.0 I'm getting the following errors, claiming that IdentityRole and IdentityUser could not be found.

However, the package Microsoft.AspNetCore.Identity.EntityFrameworkCore 2.0 is installed in the new version of .NET Core

About IdentityRole:

Message 1:

The type or namespace name 'IdentityRole' could not be found (is it missing a using directive or an assembly reference?)

Message 2:

The 'Application.Models.ApplicationRole' type can not be used as a parameter of type 'TRole' in the generic type or method 'IdentityDbContext '. There is no implicit reference conversion from 'Application.Models.ApplicationRole' to 'Microsoft.AspNetCore.Identity.IdentityRole '.

Definition of ApplicationRole:

```<code>public class ApplicationRole:IdentityRole
{
    public string Description { get; set; }
    public DateTime CreatedDated { get; set; }
    public string IPAddress { get; set; }
}
</code>```

About IdentityUser:

Message 1:

The type or namespace name 'IdentityUser' could not be found (is it missing a using directive or an assembly reference?)

Message 2:

The 'Application.Models.ApplicationUser' type can not be used as a parameter of type 'TUser' in the generic type or method 'IdentityDbContext '. There is no implicit reference conversion from 'Application.Models.ApplicationUser' to 'Microsoft.AspNetCore.Identity.IdentityUser '.

Definition of ApplicationUser

```<code>public class ApplicationUser:IdentityUser
{
    public string Name { get; set; }
}
</code>```

The guide followed to define this classes and their use are here:

http://www.c-sharpcorner.com/article/asp-net-core-mvc-authentication-and-role-based-authorization-with-asp-net-core/

With the change to Core 2.0 I wonder how IdentityRole and IdentityUser changed so I can no longer inherit from them.

答:
You need to install Microsoft.AspNetCore.Identity.EntityFramework package

```<code>Install-Package Microsoft.AspNetCore.Identity.EntityFramework
</code>```

or

```<code>dotnet add package Microsoft.AspNetCore.Identity.EntityFramework
</code>```

Body:
I'm trying to finish updating to .NET Core 2.0 but a couple of errors pop up:

The problem:

I have two classes, ApplicationRole and ApplicationUser which inherit some properties from IdentityRole and IdentityUser.

With the update to Core 2.0 I'm getting the following errors, claiming that IdentityRole and IdentityUser could not be found.

However, the package Microsoft.AspNetCore.Identity.EntityFrameworkCore 2.0 is installed in the new version of .NET Core

About IdentityRole:

Message 1:

The type or namespace name 'IdentityRole' could not be found (is it missing a using directive or an assembly reference?)

Message 2:

The 'Application.Models.ApplicationRole' type can not be used as a parameter of type 'TRole' in the generic type or method 'IdentityDbContext '. There is no implicit reference conversion from 'Application.Models.ApplicationRole' to 'Microsoft.AspNetCore.Identity.IdentityRole '.

Definition of ApplicationRole:

public class ApplicationRole:IdentityRole
{
    public string Description { get; set; }
    public DateTime CreatedDated { get; set; }
    public string IPAddress { get; set; }
}

About IdentityUser:

Message 1:

The type or namespace name 'IdentityUser' could not be found (is it missing a using directive or an assembly reference?)

Message 2:

The 'Application.Models.ApplicationUser' type can not be used as a parameter of type 'TUser' in the generic type or method 'IdentityDbContext '. There is no implicit reference conversion from 'Application.Models.ApplicationUser' to 'Microsoft.AspNetCore.Identity.IdentityUser '.

Definition of ApplicationUser

public class ApplicationUser:IdentityUser
{
    public string Name { get; set; }
}

The guide followed to define this classes and their use are here:

http://www.c-sharpcorner.com/article/asp-net-core-mvc-authentication-and-role-based-authorization-with-asp-net-core/

With the change to Core 2.0 I wonder how IdentityRole and IdentityUser changed so I can no longer inherit from them.

Body:
You need to install Microsoft.AspNetCore.Identity.EntityFramework package

Install-Package Microsoft.AspNetCore.Identity.EntityFramework

or

dotnet add package Microsoft.AspNetCore.Identity.EntityFramework


问:
Indexing with pointers - How pointer works with slices?
In the below main() code:

```<code>package main

import (
    "fmt"

    "github.com/myhub/cs61a/poetry"
)

func main() {

    p := poetry.NewPoem([][]string{
        {
            "And from my pillow, looking forth by light",
            "Of moon or favoring stars, I could behold",
            "The antechapel where the statue stood",
            "Of Newton, with his prism and silent face,",
            "The marble index of a mind forever",
            "Voyaging through strange seas of thought, alone.",
        },
        {
            "inducted into Greek and Christian",
            "modes of thinking, must take a longer way around.",
            "Like children born into love, they exult in the here",
            "who have felt separation and grave misgivings, they",
            "and of humanity, and of God. Great literature, like",
            "struggles to reconcile suffering with faith in the ",
        },
    })

    fmt.Printf("%T\n", p[0])

}
</code>```

p[0] works fine by pointing to first stanza using below function constructor:

```<code>package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return poem
}
</code>```

If, NewPoem() returns value of type *Poem, as shown below:

```<code>package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) *Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return &poem
}
</code>```

then, p[0] in main() gives below error:

```<code>     Invalid operation: p[0] (type *poetry.Poem does not support indexing)
</code>```

Why pointer to slice of slice of strings does not support p[0] syntax?

答:
Why pointer to slice of slice of strings does not support p[0] syntax?

Because it's a pointer it has no indexable elements inside like array or slice.
If you wish index access to Stanza's you may dereference the pointer (thus gaining a slice) and then access 0'th element in the slice:

fmt.Printf("%T\n", (*p)[0])
```

<p>Output:</p>

```main.Stanza
```

<p>Or a whole code of an example: https://play.golang.org/p/7abmjp6AxA4</p>

<p>BUT.
Do you really need a pointer to a slice? Slices in Golang are very lightweight structures - the consists of 3 64 bit values: a pointer to an array with data, current length of the array and a maximal length of the array - so called capacity of slice.</p>

<p>We can compare passing a slice with passing a pointer to it:</p>

<ol>
<li><p>24 bytes and you get an address where data resides</p></li>
<li><p>8 bytes but then you must dereference it - go to another location in RAM to get a slice (24 bytes) and then get an address of a data. Such indirection can be more expensive operation. </p></li>
</ol>

<p>Passing a slice is enough for 99% of cases. Even when you read data from file using OS methods you pass a slice as a buffer.</p>

```f, _ := os.Open("/tmp/dat")

// Create a buffer of size 5
b1 := make([]byte, 5)

// Read some bytes from the beginning of the file.
// Allow up to 5 to be read - this value is taken from slice length
// Read returns how many bytes actually were read.
n, _ := f.Read(b1)
```

More info: https://gobyexample.com/reading-files

Body:
In the below main() code:

package main

import (
    "fmt"

    "github.com/myhub/cs61a/poetry"
)

func main() {

    p := poetry.NewPoem([][]string{
        {
            "And from my pillow, looking forth by light",
            "Of moon or favoring stars, I could behold",
            "The antechapel where the statue stood",
            "Of Newton, with his prism and silent face,",
            "The marble index of a mind forever",
            "Voyaging through strange seas of thought, alone.",
        },
        {
            "inducted into Greek and Christian",
            "modes of thinking, must take a longer way around.",
            "Like children born into love, they exult in the here",
            "who have felt separation and grave misgivings, they",
            "and of humanity, and of God. Great literature, like",
            "struggles to reconcile suffering with faith in the ",
        },
    })

    fmt.Printf("%T\n", p[0])

}

p[0] works fine by pointing to first stanza using below function constructor:

package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return poem
}

If, NewPoem() returns value of type *Poem, as shown below:

package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) *Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return &poem
}

then, p[0] in main() gives below error:

     Invalid operation: p[0] (type *poetry.Poem does not support indexing)

Why pointer to slice of slice of strings does not support p[0] syntax?

Body:
Why pointer to slice of slice of strings does not support p[0] syntax?

Because it's a pointer it has no indexable elements inside like array or slice.
If you wish index access to Stanza's you may dereference the pointer (thus gaining a slice) and then access 0'th element in the slice:

fmt.Printf("%T\n", (*p)[0])

Output:

main.Stanza

Or a whole code of an example: https://play.golang.org/p/7abmjp6AxA4

BUT.
Do you really need a pointer to a slice? Slices in Golang are very lightweight structures - the consists of 3 64 bit values: a pointer to an array with data, current length of the array and a maximal length of the array - so called capacity of slice.

We can compare passing a slice with passing a pointer to it:

24 bytes and you get an address where data resides

8 bytes but then you must dereference it - go to another location in RAM to get a slice (24 bytes) and then get an address of a data. Such indirection can be more expensive operation.

Passing a slice is enough for 99% of cases. Even when you read data from file using OS methods you pass a slice as a buffer.

f, _ := os.Open("/tmp/dat")

// Create a buffer of size 5
b1 := make([]byte, 5)

// Read some bytes from the beginning of the file.
// Allow up to 5 to be read - this value is taken from slice length
// Read returns how many bytes actually were read.
n, _ := f.Read(b1)

More info: https://gobyexample.com/reading-files


问:
Getting Container IP in a Go application
I have a simple Go application running inside a docker container. I wish to get the container IP of that container inside the Go application itself. How can I do that? I am a newbie so please help me out, if this question sounds silly</p>

答:
You can get the hostname using os.hostname() function.
Below golang code can give you some idea

```<code>package main

import (
    "fmt"
    "os"
)

func main() {
    containerHostname, err := os.Hostname()
}
</code>```

containerHostname variable will have the hostname of the container.

Body:
You can get the hostname using os.hostname() function.
Below golang code can give you some idea

package main

import (
    "fmt"
    "os"
)

func main() {
    containerHostname, err := os.Hostname()
}

containerHostname variable will have the hostname of the container.


答:
setInfo function will update the state asynchronously so when you call localStorage.setItem function and pass info in it, info array hasn't been updated yet.

You can create an array and pass it to setInfo and setItem function. This way, you don't have to depend on setInfo function to update the state before you save it in localStorage

```<code>const add = () => {
   if(website){
      const arr = [...info,{website:website,password:generate()}]
      setInfo(arr);
      localStorage.setItem("data",JSON.stringify(arr));
   }
}
</code>```

Title: saving state into localstorage in react

Body:
I call this function on every button click.

the problem is when the button first clicked it doesn't save the first element until next clicks
so the first element never get saved

 const add=()=>{
    if(website){
      setInfo([...info,{website:website,password:generate()}])
      localStorage.setItem("data",JSON.stringify(info));
    }
  }

state info:

const[info,setInfo]=useState([])

Body:
setInfo function will update the state asynchronously so when you call localStorage.setItem function and pass info in it, info array hasn't been updated yet.

You can create an array and pass it to setInfo and setItem function. This way, you don't have to depend on setInfo function to update the state before you save it in localStorage

const add = () => {
   if(website){
      const arr = [...info,{website:website,password:generate()}]
      setInfo(arr);
      localStorage.setItem("data",JSON.stringify(arr));
   }
}


问:
CAS SSO Docker Image fails caused by Tomcat Server
When I'm trying to run my docker image. It seems there's something missing, but I can't figure it out yet.

Exception is triggered by:

```<code>Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat server
</code>```

You can see images posted below

Any ideas?

Image 1

Image 2

Image 3

答:
Based on the documentation provided on the README:

Create a keystore file thekeystore under /etc/cas. Use the password changeit for both the keystore and the key/certificate entries. This can either be done using the JDK's keytool utility or via the following command:
  ./gradlew[.bat] createKeystore
  Ensure the keystore is loaded up with keys and certificates of the server.

Body:
When I'm trying to run my docker image. It seems there's something missing, but I can't figure it out yet.

Exception is triggered by:

Caused by: org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat server

You can see images posted below

Any ideas?

Image 1

Image 2

Image 3


问:
Is it possible to verify NIST P-256 curve in NEAR smart contract on Rust?
I'm considering doing multisig with one of signatures using iOS Secure Enclave. However it only supports NIST P-256 curve.

I know it's not supported on protocol level, but is it possible to implement it in Rust smart contract? If so – where do I start?

答:
Currently even if you can verify inside the smart contract NIST P-256 curve (here are libraries for verification, for example - https://github.com/RustCrypto/elliptic-curves/tree/master/p256), you would still need to sign the transaction with some ED25519 or SECP-256K1 key first to actually get blockchain to accept it before the contract code will be execute.

My understanding is that right now you can just store sequence of bytes in secure enclave and read it out and sign any function in user land. Here how it can be done securely - https://github.com/AlphaWallet/alpha-wallet-ios/pull/1272

If this is an important consideration to support iOS secure enclave singing, you can create a spec change proposal to add SECP-256P1 (which is NIST P-256) as an alternative key type to NEAR. It would have obvious downsides, but this is a clear upside as well and it's optional so each individual user can decide which curve they prefer to use.


问:
Event.preventDefault does not seem to work (async context)
I realise there are a few questions about preventDefault not working. But my question is about the rather straightforward case where you have an async function and an error is thrown:

```<code>throw 'error of some kind';
</code>```

... and then you want to have a "mopping up" function to catch any and all such errors. This then works as expected:

```<code>window.addEventListener('unhandledrejection', function (event) {
    console.log( 'unhandled Promise rejection, event: ', event );

    // event.preventDefault();
});
</code>```

But if I uncomment the event.preventDefault(), I expect to see the throw message not then get printed as an error to console. But it always does get so printed.

I checked to make sure that event is indeed cancelable in this case. It claims to be so.

PS from my experiments it seems to be that

```<code>window.onunhandledrejection = event => {
    ...
};
</code>```

is just another way of implementing this same listener for this same "unhandledrejection" event. Using event.preventDefault() there doesn't seem to work either.

Edit

After a few experiments I seem to find that the only way I can find to prevent this is to swallow the error (using try...catch) at some point, preferably at the highest async call in the stack (or rather in the sequence of calls of async functions), if that can be determined.

window.addEventListener('unhandledrejection', event => {
  console.log(event.cancelable, event.reason, "unhandled rejection")
  event.preventDefault()
  event.stopPropagation()
  event.stopImmediatePropagation()
  return false
})

async function x() {
  console.log('async')
  throw "async error"
}

x()

new Promise(res => {
  console.log('prom')
  throw "prom error"
})```

答:
Verified on Firefox 76. Straight Promises don't work either. Looks like a bug. Probably should file an issue with Mozilla's Firefox tracker.

Note: this is not a solution. It's doubtful there is any solution except filing a bug and having it fixed.

window.onerror = msg => console.log(msg) || false

window.addEventListener('unhandledrejection', event => {
  console.log(event.cancelable, event.reason, "unhandled rejection")
  event.preventDefault()
  event.stopPropagation()
  event.stopImmediatePropagation()
  return false
})

async function x() {
  console.log('async')
  throw "async error"
}

x()

new Promise(res => {
  console.log('prom')
  throw "prom error"
})```

Body:
I realise there are a few questions about preventDefault not working. But my question is about the rather straightforward case where you have an async function and an error is thrown:

throw 'error of some kind';

... and then you want to have a "mopping up" function to catch any and all such errors. This then works as expected:

window.addEventListener('unhandledrejection', function (event) {
    console.log( 'unhandled Promise rejection, event: ', event );

    // event.preventDefault();
});

But if I uncomment the event.preventDefault(), I expect to see the throw message not then get printed as an error to console. But it always does get so printed.

I checked to make sure that event is indeed cancelable in this case. It claims to be so.

PS from my experiments it seems to be that

window.onunhandledrejection = event => {
    ...
};

is just another way of implementing this same listener for this same "unhandledrejection" event. Using event.preventDefault() there doesn't seem to work either.

Edit

After a few experiments I seem to find that the only way I can find to prevent this is to swallow the error (using try...catch) at some point, preferably at the highest async call in the stack (or rather in the sequence of calls of async functions), if that can be determined.

window.addEventListener('unhandledrejection', event => {
  console.log(event.cancelable, event.reason, "unhandled rejection")
  event.preventDefault()
  event.stopPropagation()
  event.stopImmediatePropagation()
  return false
})

async function x() {
  console.log('async')
  throw "async error"
}

x()

new Promise(res => {
  console.log('prom')
  throw "prom error"
})


问:
autoconf: best practice for including `libftdi` in `configure.ac`
Hello everybody out there using GNU autoconf,

What is the best practice to look for libftdi and including it with autoconf for compiling a C program using it?

The following snippet from a configure.ac file works, but I'm not sure, whether it is best practice:

```<code>PKG_CHECK_MODULES([LIBFTDI], [libftdi])
#AC_CHECK_LIB([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_SEARCH_LIBS([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_CHECK_HEADERS([ftdi.h],[],[echo "error: missing libftdi header files" && exit 1])
LIBS="-lftdi $LIBS $LDFLAGS" # works, but is this the best way?
</code>```

I'm building the program with autoconf (GNU Autoconf) 2.69 and compiling it with gcc version 7.5.0 on Ubuntu 18.04.

答:
You can check it like this:

```<code>AC_CHECK_LIB([ftdi],[ftdi_init],[],[echo "error: missing libftdi library" && exit 1],[])
    LDFLAGS="-lftdi $LDFLAGS"
</code>```

The second argument for AC_CHECK_LIB is a function exported by the library, and in this case the init call works well.

Body:
Hello everybody out there using GNU autoconf,

What is the best practice to look for libftdi and including it with autoconf for compiling a C program using it?

The following snippet from a configure.ac file works, but I'm not sure, whether it is best practice:

PKG_CHECK_MODULES([LIBFTDI], [libftdi])
#AC_CHECK_LIB([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_SEARCH_LIBS([ftdi],[ftdi],[ftdi])  # Why doesn't this work?
#AC_CHECK_HEADERS([ftdi.h],[],[echo "error: missing libftdi header files" && exit 1])
LIBS="-lftdi $LIBS $LDFLAGS" # works, but is this the best way?

I'm building the program with autoconf (GNU Autoconf) 2.69 and compiling it with gcc version 7.5.0 on Ubuntu 18.04.

Body:
You can check it like this:

AC_CHECK_LIB([ftdi],[ftdi_init],[],[echo "error: missing libftdi library" && exit 1],[])
    LDFLAGS="-lftdi $LDFLAGS"

The second argument for AC_CHECK_LIB is a function exported by the library, and in this case the init call works well.


问:
How to upload file to Remote Server by windows phone
In web App, there is an Input Tag to upload file. In windows phone, It seems it is different. I need hlep on writing HttpWebRequest code to upload file to remote server ( if possible to skydrive). Can you show me how to solve this problem.

1) Upload file from Windows phone.
2) How would I handle the uploaded file on server-side If I use Asp.net.

Thanks.

答:
Something like this.  I suggest you ask about how to handle it on the server side in its own question with a different set of tags.</p>

```<code>var uri = "http://example.com/some_applette"
var request = HttpWebRequest.create(uri);
request.Method = "POST";
request.ContentType = "image/jpeg";  // Change to whatever you're uploading.
request.BeginGetRequestStream((result1) =>
{
    using (Stream stream = request.EndGetRequestStream(result1))
    {
        // Bytes contains the data to upload.
        stream.Write(bytes, 0, bytes.Length);
    }

    request.BeginGetResponse((result2) =>
    {
        var response = request.EndGetResponse(result2);

        // Optionally handle the response.
        var responseStream = response.GetResponseStream();
        ...
    }
}, null);
</code>```

Body:
Something like this.  I suggest you ask about how to handle it on the server side in its own question with a different set of tags.

var uri = "http://example.com/some_applette"
var request = HttpWebRequest.create(uri);
request.Method = "POST";
request.ContentType = "image/jpeg";  // Change to whatever you're uploading.
request.BeginGetRequestStream((result1) =>
{
    using (Stream stream = request.EndGetRequestStream(result1))
    {
        // Bytes contains the data to upload.
        stream.Write(bytes, 0, bytes.Length);
    }

    request.BeginGetResponse((result2) =>
    {
        var response = request.EndGetResponse(result2);

        // Optionally handle the response.
        var responseStream = response.GetResponseStream();
        ...
    }
}, null);


问:
how to save bitmap to android gallery
unfortunately the solutions I've found didn't work on android 5.1.1.
I have a bitmap called source. I need to save it directly to my phone's gallery. My manifest contains  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Can you give me a working method to do this?

答:
Here is a fully working solution in Kotlin:</p>

```<code>fun saveToGallery(context: Context, bitmap: Bitmap, albumName: String) {
    val filename = "${System.currentTimeMillis()}.png"
    val write: (OutputStream) -> Boolean = {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
            put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
            put(MediaStore.MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_DCIM}/$albumName")
        }

        context.contentResolver.let {
            it.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)?.let { uri ->
                it.openOutputStream(uri)?.let(write)
            }
        }
    } else {
        val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString() + File.separator + albumName
        val file = File(imagesDir)
        if (!file.exists()) {
            file.mkdir()
        }
        val image = File(imagesDir, filename)
        write(FileOutputStream(image))
    }
}
</code>```

Title: how to save bitmap to android gallery

Body:
Here is a fully working solution in Kotlin:

fun saveToGallery(context: Context, bitmap: Bitmap, albumName: String) {
    val filename = "${System.currentTimeMillis()}.png"
    val write: (OutputStream) -> Boolean = {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
            put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
            put(MediaStore.MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_DCIM}/$albumName")
        }

        context.contentResolver.let {
            it.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)?.let { uri ->
                it.openOutputStream(uri)?.let(write)
            }
        }
    } else {
        val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString() + File.separator + albumName
        val file = File(imagesDir)
        if (!file.exists()) {
            file.mkdir()
        }
        val image = File(imagesDir, filename)
        write(FileOutputStream(image))
    }
}


问:
Could not establish secure channel for SSL/TLS with authority 'epayment.dubai.ae'. .NET Framework 4.5
I am getting this error from my website, it works when I reset IIS for a while, but then it starts to throw the same error and will work again after I reset it again.

I have tried to change the GLobal_asax application_start securityProtocol for:

```<code>System.Net.ServicePointManager.SecurityProtocol = CType(3072, System.Net.SecurityProtocolType)
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

If System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType.Ssl3 Or SecurityProtocolType.Tls) Then
   System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
</code>```

All of this returned the same result

I am using iis 8.5 , windows server 2012

答: we have installed a root certificate from the payment provider which solve the problem </p>

Body:
I am getting this error from my website, it works when I reset IIS for a while, but then it starts to throw the same error and will work again after I reset it again.

I have tried to change the GLobal_asax application_start securityProtocol for:

System.Net.ServicePointManager.SecurityProtocol = CType(3072, System.Net.SecurityProtocolType)
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

If System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType.Ssl3 Or SecurityProtocolType.Tls) Then
   System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

All of this returned the same result

I am using iis 8.5 , windows server 2012


问:
auth/web-storage-unsupported error thrown in AngularFire 2.0.1
When I try to login into my website using firebase-authentication with a Nokia Lumia 520 Phone 'auth/web-storage-unsupported' error code is thrown. I'm using AngularFire 2.0.1. Is there any way I can work around this issue becuase some of my users still use these phones with older version of Internet Explorer.</p>

答: Third-party cookies may be disabled in your browser. Enable them and try again. It worked for me.</p>


问:
How to write function overloads with --noImplicitAny?
How to do function overloading with --noImplicitAny ?

This is my example code:

function plus(a: string, b: string): string;
function plus(a: number, b: number): number;
// Error -> Parameter 'a' implicitly has an 'any' type.
// Error -> Parameter 'b' implicitly has an 'any' type.
function plus(a, b): any {
  return a + b;
}
```

<p>This is the code copied from TypeScript's documentation:</p>

<pre class="lang-js prettyprint-override"><code>function pickCard(x: { suit: string; card: number }[]): number;
function pickCard(x: number): { suit: string; card: number };
// Error -> Parameter 'x' implicitly has an 'any' type.
function pickCard(x): any {
  if (typeof x === 'object'){
    const pickedCard = Math.floor(Math.random() * x.length);
    return pickedCard;
  } else if (typeof x === 'number'){
    const pickedSuit = Math.floor(x / 13);
    return { suit: suits[pickedSuit], card: x % 13 };
  }
}
</code>```

The implicit-any error is happening in both cases, even in the code of their own docs.

So how should we properly write function overloads with noImplicitAny enabled?

答:
Option 1: No type-check in the implementation, simply using any

You can make it type-check by adding types to the parameters of the implementation, such as adding : any to the parameters in this case. This will still cause proper type-checking of any usage of the overloaded function, but will not have type-checking of the implementation, which may or may not be desirable. It might make the implementation of the overloaded function easier to write, but it may also make it more error-prone to implement, and callers from Javascript that do not use type-checking will not get any runtime errors if they call it with wrong arguments.

Playground Link

function plus(a: string, b: string): string;
function plus(a: number, b: number): number;

function plus(a: any, b: any): any {

    return a + b;
}

console.log("Number: " + plus(3, 4));
console.log("String: " + plus("asdf", "qwer"));
// Does not compile.
//console.log("Mixed: " + plus(3, "testing"));
```

<h2>Option 2: Type-check in the implementation, here using <code>string | number</code> for the parameters and return type</h2>

<p>You can add more precise types to the parameters. In this case, it makes the overloaded function implementation more bothersome to implement, but it does enable type-checking of the implementation, and it also gives a runtime error if any callers from Javascript give wrong input to the overloaded function.</p>

<p>Playground Link</p>

<pre class="lang-js prettyprint-override"><code>function plus(a: string, b: string): string;
function plus(a: number, b: number): number;

function plus(a: string | number, b: string | number): string | number {

    if (typeof a === "string" && typeof b === "string") {
        return a + b;
    }

    if (typeof a === "number" && typeof b === "number") {
        return a + b;
    }

    throw new Error("Expected pair of strings or pair of numbers, but got: " + a + ", " + b);
}

console.log("Number: " + plus(3, 4));
console.log("String: " + plus("asdf", "qwer"));
// Does not compile.
//console.log("Mixed: " + plus(3, "testing"));
</code>```

Side-notes.

Good catch that the official documentation does not compile either under ǹoImplicitAny. I have created a pull request for fixing the example here: https://github.com/microsoft/TypeScript-Website/pull/652 .

Body:
How to do function overloading with --noImplicitAny ?

This is my example code:

function plus(a: string, b: string): string;
function plus(a: number, b: number): number;
// Error -> Parameter 'a' implicitly has an 'any' type.
// Error -> Parameter 'b' implicitly has an 'any' type.
function plus(a, b): any {
  return a + b;
}

This is the code copied from TypeScript's documentation:

function pickCard(x: { suit: string; card: number }[]): number;
function pickCard(x: number): { suit: string; card: number };
// Error -> Parameter 'x' implicitly has an 'any' type.
function pickCard(x): any {
  if (typeof x === 'object'){
    const pickedCard = Math.floor(Math.random() * x.length);
    return pickedCard;
  } else if (typeof x === 'number'){
    const pickedSuit = Math.floor(x / 13);
    return { suit: suits[pickedSuit], card: x % 13 };
  }
}

The implicit-any error is happening in both cases, even in the code of their own docs.

So how should we properly write function overloads with noImplicitAny enabled?

Body:
Option 1: No type-check in the implementation, simply using any

You can make it type-check by adding types to the parameters of the implementation, such as adding : any to the parameters in this case. This will still cause proper type-checking of any usage of the overloaded function, but will not have type-checking of the implementation, which may or may not be desirable. It might make the implementation of the overloaded function easier to write, but it may also make it more error-prone to implement, and callers from Javascript that do not use type-checking will not get any runtime errors if they call it with wrong arguments.

Playground Link

function plus(a: string, b: string): string;
function plus(a: number, b: number): number;

function plus(a: any, b: any): any {

    return a + b;
}

console.log("Number: " + plus(3, 4));
console.log("String: " + plus("asdf", "qwer"));
// Does not compile.
//console.log("Mixed: " + plus(3, "testing"));

Option 2: Type-check in the implementation, here using string | number for the parameters and return type

You can add more precise types to the parameters. In this case, it makes the overloaded function implementation more bothersome to implement, but it does enable type-checking of the implementation, and it also gives a runtime error if any callers from Javascript give wrong input to the overloaded function.

<a href="https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABABwDYgM4AoCGAuRDKAJxjAHMAaRAIwKNIoEp6SzyBuAKFElgRTps+RGBABbGgFNi1OqInTiLBZJnce4aPCRpMuVo3KIAPqqVzD7U+ZkqG1s2LXFEAby5dE3xDGCIsKABPZCk4fxxEAF4YxAAiBwo4xAAyFMRg0PDaaNiEtiSmdy8fUuIpKBBiJEiAalpuUoBfT1K-AMywiNyo+OclZLSMkK6cmN64-pk4oo9SsoqqmsR6mkafFpLvKAALYjgAd1EpI4BRYn3iLDjTgA9Q6CkAExQcGFdsxPIMRDhXZDeH38U2IGDkICgiHIcCgBGS9Tq8Wo8NoTG4mwgCAwcFQUgAdKg4ORrgA5RQyOErQT6ADM1AALEw0VxMWBsbiCUTrgBlArkSn1PTYOI4DBPYBxZEARwO0yZ3AA9ArEAAROBSH5gGGITHiZAwDlcJWs9n4wnEuIAWRgt2eAup2Dp8SgGtghWZQA" rel="nofollow noreferrer">Playground Link

function plus(a: string, b: string): string;
function plus(a: number, b: number): number;

function plus(a: string | number, b: string | number): string | number {

    if (typeof a === "string" && typeof b === "string") {
        return a + b;
    }

    if (typeof a === "number" && typeof b === "number") {
        return a + b;
    }

    throw new Error("Expected pair of strings or pair of numbers, but got: " + a + ", " + b);
}

console.log("Number: " + plus(3, 4));
console.log("String: " + plus("asdf", "qwer"));
// Does not compile.
//console.log("Mixed: " + plus(3, "testing"));

Side-notes.

Good catch that the official documentation does not compile either under ǹoImplicitAny. I have created a pull request for fixing the example here: https://github.com/microsoft/TypeScript-Website/pull/652 .