问:
azure-mobile-apps nodes sdk, unable to make a api call
I am closely following this documentation And When i try creating the api as they have done. But when i am making a call from postman, I am unable to make get request.

```<code>module.exports = {
    "get": function (request, response, next) {
        try{
            var query = {
                sql: 'UPDATE EmailVerification SET verified = @completed where id = @unique',
                    parameters: [
                        { name: 'completed', value: request.query.completed,
                            name: 'unique', value: request.query.unique }
                    ]
                };

        request.azureMobile.data.execute(query)
        .then(function (results) {
            console.log(results);
            response.json("Verfied successfully");
        }).catch(function (err) { console.log(err);
            response.send(err);});
        }
        catch(ex)
        {
            console.log(ex);
            response.send(ex);
        }
    }
};
</code>```

And in the postman, I am making the call

```<code>https://<appname>.azurewebsites.net/api/emailtoken?completed=true&unique=4a642af0-75be-45dd-bd8d-3c91e93a8b9d
</code>```

Any lead will be helpful.

Here is the screenshot of the output:

PS: I have updated my question with more details and changes.

答:
You need to change the following lines of code:

```<code>parameters: [
    { name: 'completed', value: request.query.completed,
      name: 'unique', value: request.query.unique }
]
</code>```

to:

```<code>parameters: [
    { name: 'completed', value: request.query.completed },
    { name: 'unique', value: request.query.unique }
]
</code>```

Body:
I am closely following this documentation And When i try creating the api as they have done. But when i am making a call from postman, I am unable to make get request.

module.exports = {
    "get": function (request, response, next) {
        try{
            var query = {
                sql: 'UPDATE EmailVerification SET verified = @completed where id = @unique',
                    parameters: [
                        { name: 'completed', value: request.query.completed,
                            name: 'unique', value: request.query.unique }
                    ]
                };

        request.azureMobile.data.execute(query)
        .then(function (results) {
            console.log(results);
            response.json("Verfied successfully");
        }).catch(function (err) { console.log(err);
            response.send(err);});
        }
        catch(ex)
        {
            console.log(ex);
            response.send(ex);
        }
    }
};

And in the postman, I am making the call

https://<appname>.azurewebsites.net/api/emailtoken?completed=true&unique=4a642af0-75be-45dd-bd8d-3c91e93a8b9d

Any lead will be helpful.

Here is the screenshot of the output:

PS: I have updated my question with more details and changes.

Body:
You need to change the following lines of code:

parameters: [
    { name: 'completed', value: request.query.completed,
      name: 'unique', value: request.query.unique }
]

to:

parameters: [
    { name: 'completed', value: request.query.completed },
    { name: 'unique', value: request.query.unique }
]


来源: stackexchange

问:
npm - package existing js code
I'm learning about npm modules and I'm trying to package this module as npm package.

I have read the docs on how to create an npm

https://docs.npmjs.com/getting-started/creating-node-modules

I understand an export function is required, my question is, should I wrap the following function as an export statement!? :-/

```<code>/*!
 * fullcalendar-rightclick v1.8
 * Docs & License: https://github.com/mherrmann/fullcalendar-rightclick
 * (c) 2015 Michael Herrmann
 */

(function($) {
    function monkeyPatchViewClass(View) {
        View = View.class || View;
        var renderFn = 'render' in View.prototype ? 'render' : 'renderDates';
        var originalRender = View.prototype[renderFn];
        View.prototype[renderFn] = function() {
            originalRender.call(this);
            if (! this.el.data('fullcalendar-rightclick')) {
                this.registerRightclickListener();
                this.el.data('fullcalendar-rightclick', true)
            }
        };
        View.prototype.registerRightclickListener = function() {
            var that = this;
            this.el.on('contextmenu', function(ev) {
                var eventElt = $(ev.target).closest('.fc-event');
                if (eventElt.length) {
                    var seg = eventElt.data('fc-seg');
                    return that.trigger('eventRightclick', this, seg.event, ev);
                } else {
                    // Users of this library may add custom content inside
                    // FullCalendar's DOM structure, eg. popovers. We don't want
                    // to catch rightclicks on these custom elements, so we
                    // check that the clicked element actually lies inside one
                    // of FullCalendars default containers:
                    var fcContainer = $(ev.target).closest(
                        '.fc-bg, .fc-slats, .fc-content-skeleton, ' +
                        '.fc-bgevent-skeleton, .fc-highlight-skeleton'
                    );
                    if (fcContainer.length) {
                        var cell;
                        if (that.coordMap) {
                            // FullCalendar < 2.5.0:
                            that.coordMap.build();
                            cell = that.coordMap.getCell(ev.pageX, ev.pageY);
                        } else {
                            // FullCalendar >= 2.5.0:
                            that.prepareHits();
                            var hit = that.queryHit(ev.pageX, ev.pageY);
                            cell = that.getHitSpan(hit);
                        }
                        if (cell)
                            return that.trigger(
                                'dayRightclick', null, cell.start, ev
                            );
                    }
                }
            });
        }
    }
    var fc = $.fullCalendar;
    monkeyPatchViewClass(fc.views.agenda);
    monkeyPatchViewClass(fc.views.basic);
})(jQuery);
</code>```

答:
No you dont need to wrap you module code into a function scope.

The contents of the nodejs module is executed in its own private scope and you use module.exports for exposing its contents to other modules.

You might be interested in reading about nodejs modules to learn more.

EDIT:

Just realized you are trying to use a 3rd party library targeting browser environment. What you normally would do if you want to use npm to build browser libraries is to use it together with browserify or webpack as part of a build process which would transpile your nodejs modules into browser loadable scripts and insert all necessary baggage for you.

ContentLicense: CC BY-SA 3.0

Title: npm - package existing js code

Body:
I'm learning about npm modules and I'm trying to package this module as npm package.

I have read the docs on how to create an npm

https://docs.npmjs.com/getting-started/creating-node-modules

I understand an export function is required, my question is, should I wrap the following function as an export statement!? :-/

/*!
 * fullcalendar-rightclick v1.8
 * Docs & License: https://github.com/mherrmann/fullcalendar-rightclick
 * (c) 2015 Michael Herrmann
 */

(function($) {
    function monkeyPatchViewClass(View) {
        View = View.class || View;
        var renderFn = 'render' in View.prototype ? 'render' : 'renderDates';
        var originalRender = View.prototype[renderFn];
        View.prototype[renderFn] = function() {
            originalRender.call(this);
            if (! this.el.data('fullcalendar-rightclick')) {
                this.registerRightclickListener();
                this.el.data('fullcalendar-rightclick', true)
            }
        };
        View.prototype.registerRightclickListener = function() {
            var that = this;
            this.el.on('contextmenu', function(ev) {
                var eventElt = $(ev.target).closest('.fc-event');
                if (eventElt.length) {
                    var seg = eventElt.data('fc-seg');
                    return that.trigger('eventRightclick', this, seg.event, ev);
                } else {
                    // Users of this library may add custom content inside
                    // FullCalendar's DOM structure, eg. popovers. We don't want
                    // to catch rightclicks on these custom elements, so we
                    // check that the clicked element actually lies inside one
                    // of FullCalendars default containers:
                    var fcContainer = $(ev.target).closest(
                        '.fc-bg, .fc-slats, .fc-content-skeleton, ' +
                        '.fc-bgevent-skeleton, .fc-highlight-skeleton'
                    );
                    if (fcContainer.length) {
                        var cell;
                        if (that.coordMap) {
                            // FullCalendar < 2.5.0:
                            that.coordMap.build();
                            cell = that.coordMap.getCell(ev.pageX, ev.pageY);
                        } else {
                            // FullCalendar >= 2.5.0:
                            that.prepareHits();
                            var hit = that.queryHit(ev.pageX, ev.pageY);
                            cell = that.getHitSpan(hit);
                        }
                        if (cell)
                            return that.trigger(
                                'dayRightclick', null, cell.start, ev
                            );
                    }
                }
            });
        }
    }
    var fc = $.fullCalendar;
    monkeyPatchViewClass(fc.views.agenda);
    monkeyPatchViewClass(fc.views.basic);
})(jQuery);


问:
Octopus not sending reads to slave
I have the following configuration for a slave:

```<code>octopus:
  replicated: true
  fully_replicated: true
  environments:
    - staging
    # - production

  staging:
    shards:
      slave1:
        host: database_ip
        username: <%= ENV['DATABASE_USERNAME'] %>
        password: <%= ENV['DATABASE_PASSWORD'] %>
        database: <%= ENV['DATABASE_NAME'] %>
</code>```

I checked pg_stat_activity from this slave and there is nothing, not a single query is running except from mine.

Am I missing something from octopus configuration? I went through the wiki but couldn't find anything else than shards.yml

答:
You can try (without shards key):

```<code>octopus:
  replicated: true
  fully_replicated: true
  environments:
    - staging
    # - production

  staging:
    slave1:
      host: database_ip
      username: <%= ENV['DATABASE_USERNAME'] %>
      password: <%= ENV['DATABASE_PASSWORD'] %>
      database: <%= ENV['DATABASE_NAME'] %>
</code>```

From Config file wiki

Title: Octopus not sending reads to slave

Body:
I have the following configuration for a slave:

octopus:
  replicated: true
  fully_replicated: true
  environments:
    - staging
    # - production

  staging:
    shards:
      slave1:
        host: database_ip
        username: <%= ENV['DATABASE_USERNAME'] %>
        password: <%= ENV['DATABASE_PASSWORD'] %>
        database: <%= ENV['DATABASE_NAME'] %>

I checked pg_stat_activity from this slave and there is nothing, not a single query is running except from mine.

Am I missing something from octopus configuration? I went through the wiki but couldn't find anything else than shards.yml

Body:
You can try (without shards key):

octopus:
  replicated: true
  fully_replicated: true
  environments:
    - staging
    # - production

  staging:
    slave1:
      host: database_ip
      username: <%= ENV['DATABASE_USERNAME'] %>
      password: <%= ENV['DATABASE_PASSWORD'] %>
      database: <%= ENV['DATABASE_NAME'] %>

From Config file wiki


问:
Does a CSS3 animation still run when its display property is set to none?
I have a progressbar, which I animate using CSS while my page loads. After my page has finished loading, I set the progressbar's display property to none using Javascript, so  the page content will be displayed instead. The question is: Will the animation still run in the background while it's display property is set to none?

答:
The answer is NO.

When you set element display:none, the animation stop. When the element display: block again, the animation start again at beginning point.

See the example:

let test1 = document.getElementById('test1');
let test2 = document.getElementById('test2');
let test3 = document.getElementById('test3');
setTimeout(() => {
  test1.style.display = 'none';
}, 1000)
setTimeout(() => {
  test1.style.display = 'block';
}, 2000);

setTimeout(() => {
  test2.style.display = 'none';
}, 6000)
setTimeout(() => {
  test2.style.display = 'block';
}, 7000);

document.getElementById('btn').addEventListener('click', () => {
  location.reload();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.test {
  width: 30px;
  height: 30px;
  background-color: #123;
  animation: test 4s;
}

#test2 {
  background-color: green
}

#test3 {
  background-color: blue
}

@keyframes test {
  0% {
    width: 30px
  }
  100% {
    width: 1000px;
  }
}</code>```

div 1: 1s display none, 2s display block

div 2: 6s display none, 7s display block

div 3: no change

<button id="btn">Reload</button>```

Body:
The answer is NO.

When you set element display:none, the animation stop. When the element display: block again, the animation start again at beginning point.

See the example:

let test1 = document.getElementById('test1');
let test2 = document.getElementById('test2');
let test3 = document.getElementById('test3');
setTimeout(() => {
  test1.style.display = 'none';
}, 1000)
setTimeout(() => {
  test1.style.display = 'block';
}, 2000);

setTimeout(() => {
  test2.style.display = 'none';
}, 6000)
setTimeout(() => {
  test2.style.display = 'block';
}, 7000);

document.getElementById('btn').addEventListener('click', () => {
  location.reload();
})

.test {
  width: 30px;
  height: 30px;
  background-color: #123;
  animation: test 4s;
}

#test2 {
  background-color: green
}

#test3 {
  background-color: blue
}

@keyframes test {
  0% {
    width: 30px
  }
  100% {
    width: 1000px;
  }
}

<div>div 1: 1s display none, 2s display block</div>
<div class="test" id="test1"> </div>
<div>div 2: 6s display none, 7s display block</div>
<div class="test" id="test2"> </div>
<div>div 3: no change</div>
<div class="test" id="test3"> </div>
<br>
<button id="btn">Reload</button>


问:
How to hide
 within a certain
? Jquery
I'm working on a project where I get names of clients:

```<code><ol>J <li>John Doe</li> </ol>
</code>```

and I want to show a list of ol's but with their list items hidden, so that when you click on a certain ol it will show the items within it.

答:
Just simple select elements with jquery and hide() or show()

https://jsfiddle.net/29dnq7un/1/

Title: How to hide <li> within a certain <ol>? Jquery

Body:
I'm working on a project where I get names of clients:

J
John Doe

and I want to show a list of ol's but with their list items hidden, so that when you click on a certain ol it will show the items within it.


问:
XCUITest get URL value
I am using XCUITest with XCode version 8.3.3.  The application has a login button which launches a browser window.  Was wondering if someone could tell me how I can access the value of the URL that gets opened.  I want to verify we launch the correct URL when selecting the Login button.

```<code>let app = XCUIApplication()
let loginButton = app.buttons["Login"]
loginButton.tap()
</code>```

At this point the browser window is open:

How can I get the value of xyz.com?

Using the Accessibility Inspector, I can see:

Title: XCUITest get URL value

Body:
I am using XCUITest with XCode version 8.3.3.  The application has a login button which launches a browser window.  Was wondering if someone could tell me how I can access the value of the URL that gets opened.  I want to verify we launch the correct URL when selecting the Login button.

let app = XCUIApplication()
let loginButton = app.buttons["Login"]
loginButton.tap()

At this point the browser window is open:

How can I get the value of xyz.com?

Using the Accessibility Inspector, I can see:

Body:
I created a small project that loading google.com in an SFSafariViewController on launch. When I run UI tests against this app and prints the debug description of the window, I get the following:

(lldb) po XCUIApplication().windows.descendants(matching: .any)
    t =    29.26s     Use cached accessibility hierarchy for com.tito.Safari
    t =    29.27s     Find: Descendants matching type Window
    t =    29.27s     Find: Descendants matching type Any
Find: Target Application 0x6000000afa20
  Output: {
    Application 0x6000001684c0: {{0.0, 0.0}, {375.0, 667.0}}, label: 'Safari'
  }
  ↪Find: Descendants matching type Window
    Output: {
      Window 0x600000169a80: Main Window, {{0.0, 0.0}, {375.0, 667.0}}
      Window 0x60000016a8c0: {{0.0, 0.0}, {375.0, 667.0}}
      Window 0x60000016fb40: {{0.0, 0.0}, {375.0, 667.0}}
      Window 0x60000016c780: {{0.0, 0.0}, {375.0, 667.0}}
      Window 0x600000169e40: {{-0.0, -0.0}, {375.0, 667.0}}
    }
    ↪Find: Descendants matching type Any
      Output: {
        Button 0x608000169900: traits: 8589934593, {{9.5, 22.0}, {43.0, 34.0}}, label: 'Done'
        Other 0x608000165b80: traits: 8589935104, {{68.5, 24.5}, {295.0, 29.0}}, identifier: 'URL', label: 'Address', value: 10%
        Button 0x608000169840: traits: 8589934593, {{336.5, 24.5}, {29.0, 29.0}}, identifier: 'StopButton', label: 'stop'
        Button 0x600000168100: traits: 146028888065, {{66.5, 24.5}, {299.0, 29.0}}, identifier: 'URL', label: 'Address', value: google.com
        Other 0x6080001696c0: traits: 8589934592, {{0.0, 20.0}, {375.0, 44.0}}
        WebView 0x608000167ec0: traits: 8589934592, {{0.0, 0.0}, {375.0, 667.0}}
        Other 0x608000167e00: traits: 8589934592, {{0.0, 0.0}, {375.0, 667.0}}
        Other 0x608000169b40: traits: 8589934592, {{0.0, 0.0}, {375.0, 667.0}}
        Other 0x608000167a40: traits: 8589934592, {{0.0, 622.5}, {375.0, 0.5}}
        Button 0x6080001675c0: traits: 8589934849, {{0.5, 625.0}, {42.0, 40.0}}, label: 'Back'
        Button 0x600000167bc0: traits: 8589934849, {{104.0, 625.0}, {42.0, 40.0}}, label: 'Forward'
        Button 0x600000167c80: traits: 8589934593, {{207.5, 624.0}, {51.0, 40.0}}, label: 'Share'
        Button 0x60000016fa80: traits: 8589934593, {{320.5, 625.5}, {55.0, 40.0}}, label: 'Open in Safari'
        Toolbar 0x608000167b00: traits: 35192962023424, {{0.0, 623.0}, {375.0, 44.0}}
        Other 0x608000165ac0: traits: 8589934592, {{0.0, 0.0}, {375.0, 667.0}}
        Other 0x608000169780: traits: 8589934592, {{0.0, 0.0}, {375.0, 667.0}}
        Other 0x608000169480:
        Other 0x608000169180: traits: 8589934592, {{0.0, 0.0}, {375.0, 667.0}}
        Other 0x60000016cc00: traits: 8589934592, {{0.0, 64.0}, {24.0, 603.0}}
        Other 0x6080001690c0: traits: 8589934592, {{0.0, 0.0}, {375.0, 667.0}}
        Other 0x600000168400: {{0.0, 0.0}, {375.0, 667.0}}
        Other 0x600000169180: traits: 8589934592, {{0.0, 0.0}, {375.0, 667.0}}
        Other 0x600000169f00:
        Other 0x60000016a680: traits: 8589934592, {{0.0, 0.0}, {375.0, 667.0}}
        Other 0x600000167b00: {{0.0, 0.0}, {375.0, 20.0}}
        Other 0x60000016fd80: traits: 8388608, {{6.0, 0.0}, {39.0, 20.0}}
        Other 0x60000016e340: traits: 8388608, {{50.0, 0.0}, {13.0, 20.0}}, label: '3 of 3 Wi-Fi bars', value: SSID
        Other 0x60000016fe40: traits: 8389120, {{161.0, 0.0}, {57.0, 20.0}}, label: '10:33 AM'
        Other 0x60000016e880: traits: 8388608, {{337.0, 0.0}, {33.0, 20.0}}, label: '-100% battery power'
        Other 0x60000016dc80: {{0.0, 0.0}, {375.0, 20.0}}
        StatusBar 0x600000169240: {{0.0, 0.0}, {375.0, 20.0}}
        Other 0x60000016a440: traits: 8589934592, {{0.0, 0.0}, {375.0, 667.0}}
        Other 0x600000170140:
        Other 0x60000016da40: traits: 8589934592, {{-0.0, -0.0}, {375.0, 667.0}}
        Other 0x60000016c600:
        Other 0x60000016af80: traits: 8589934592, {{-0.0, -0.0}, {375.0, 667.0}}
      }

You can see that the element that contain the value google.com is seen as a Button that the Accessibility framework.

Button 0x600000168100: traits: 146028888065, {{66.5, 24.5}, {299.0, 29.0}}, identifier: 'URL', label: 'Address', value:

It seems wrong but it is how it is and there's nothing you can do about that. The way to access this element's value would be the following

XCUIApplication().buttons['URL'].value!

The only problem is that it's returns the following

gen.xyz, secure and validated connection

So the last thing to do is to parse this and you'll get the address

let value = XCUIApplication().buttons["URL"].value as! String
let address = value.components(separatedBy: ",").first!

This is definitely hacky though and might change in the future if Apple decides to apply their own advices to their own products when it comes to Accessibility.


问:
building jenkins docker image from official Dockerfile
I am trying to build a jenkins docker image from official jenkins git repo:
https://github.com/jenkinsci/docker.

But when I try to run the container of the image using docker run -it -dP jenkins, it exits immediately and when i check the docker logs, I get the following error:

```<code>: invalid option
</code>```

I read that the error could be because the pid of tini is not 1. I looked at the documents and saw that if we do the following, it should solve the issue.
    Passing the -s argument to Tini (tini -s -- ...)
    Setting the environment variable TINI_SUBREAPER (e.g. export TINI_SUBREAPER=).

But it did not solve anything.

The following is the exact copy of the Dockerfile being built with docker build -t jenkins .:

```<code>FROM openjdk:8-jdk

RUN apt-get update && apt-get install -y git curl && rm -rf /var/lib/apt/lists/*

ARG user=jenkins
ARG group=jenkins
ARG uid=1000
ARG gid=1000
ARG http_port=8080
ARG agent_port=50000

ENV JENKINS_HOME /var/jenkins_home
ENV JENKINS_SLAVE_AGENT_PORT ${agent_port}
ENV TINI_SUBREAPER=

# Jenkins is run with user `jenkins`, uid = 1000
# If you bind mount a volume from the host or a data container,
# ensure you use the same uid
RUN groupadd -g ${gid} ${group} \
    && useradd -d "$JENKINS_HOME" -u ${uid} -g ${gid} -m -s /bin/bash ${user}

# Jenkins home directory is a volume, so configuration and build history
# can be persisted and survive image upgrades
VOLUME /var/jenkins_home

# `/usr/share/jenkins/ref/` contains all reference configuration we want
# to set on a fresh new installation. Use it to bundle additional plugins
# or config file with your custom jenkins Docker image.
RUN mkdir -p /usr/share/jenkins/ref/init.groovy.d

ENV TINI_VERSION 0.14.0
ENV TINI_SHA 6c41ec7d33e857d4779f14d9c74924cab0c7973485d2972419a3b7c7620ff5fd

# Use tini as subreaper in Docker container to adopt zombie processes
RUN curl -fsSL https://github.com/krallin/tini/releases/download/v${TINI_VERSION}/tini-static-amd64 -o /bin/tini && chmod +x /bin/tini \
  && echo "$TINI_SHA  /bin/tini" | sha256sum -c -

COPY init.groovy /usr/share/jenkins/ref/init.groovy.d/tcp-slave-agent-port.groovy

# jenkins version being bundled in this docker image
ARG JENKINS_VERSION
ENV JENKINS_VERSION ${JENKINS_VERSION:-2.60.1}

# jenkins.war checksum, download will be validated using it
ARG JENKINS_SHA=34fde424dde0e050738f5ad1e316d54f741c237bd380bd663a07f96147bb1390

# Can be used to customize where jenkins.war get downloaded from
ARG JENKINS_URL=https://repo.jenkins-ci.org/public/org/jenkins-ci/main/jenkins-war/${JENKINS_VERSION}/jenkins-war-${JENKINS_VERSION}.war

# could use ADD but this one does not check Last-Modified header neither does it allow to control checksum
# see https://github.com/docker/docker/issues/8331
RUN curl -fsSL ${JENKINS_URL} -k -o /usr/share/jenkins/jenkins.war \
  && echo "${JENKINS_SHA}  /usr/share/jenkins/jenkins.war" | sha256sum -c -

ENV JENKINS_UC https://updates.jenkins.io
RUN chown -R ${user} "$JENKINS_HOME" /usr/share/jenkins/ref

# for main web interface:
EXPOSE ${http_port}

# will be used by attached slave agents:
EXPOSE ${agent_port}

ENV COPY_REFERENCE_FILE_LOG $JENKINS_HOME/copy_reference_file.log

USER ${user}

COPY jenkins-support /usr/local/bin/jenkins-support
COPY jenkins.sh /usr/local/bin/jenkins.sh
ENTRYPOINT ["/bin/tini", "--", "/usr/local/bin/jenkins.sh"]

# from a derived Dockerfile, can use `RUN plugins.sh active.txt` to setup /usr/share/jenkins/ref/plugins from a support bundle
COPY plugins.sh /usr/local/bin/plugins.sh
COPY install-plugins.sh /usr/local/bin/install-plugins.sh
</code>```

答: The problem was with the docker version. My Docker version was old. Not sure which command was not supported, but the new docker built the dockerfile.</p>

Body:
I am trying to build a jenkins docker image from official jenkins git repo:
https://github.com/jenkinsci/docker.

But when I try to run the container of the image using docker run -it -dP jenkins, it exits immediately and when i check the docker logs, I get the following error:

: invalid option

I read that the error could be because the pid of tini is not 1. I looked at the documents and saw that if we do the following, it should solve the issue.
    Passing the -s argument to Tini (tini -s -- ...)
    Setting the environment variable TINI_SUBREAPER (e.g. export TINI_SUBREAPER=).

But it did not solve anything.

The following is the exact copy of the Dockerfile being built with docker build -t jenkins .:

FROM openjdk:8-jdk

RUN apt-get update && apt-get install -y git curl && rm -rf /var/lib/apt/lists/*

ARG user=jenkins
ARG group=jenkins
ARG uid=1000
ARG gid=1000
ARG http_port=8080
ARG agent_port=50000

ENV JENKINS_HOME /var/jenkins_home
ENV JENKINS_SLAVE_AGENT_PORT ${agent_port}
ENV TINI_SUBREAPER=

# Jenkins is run with user `jenkins`, uid = 1000
# If you bind mount a volume from the host or a data container,
# ensure you use the same uid
RUN groupadd -g ${gid} ${group} \
    && useradd -d "$JENKINS_HOME" -u ${uid} -g ${gid} -m -s /bin/bash ${user}

# Jenkins home directory is a volume, so configuration and build history
# can be persisted and survive image upgrades
VOLUME /var/jenkins_home

# `/usr/share/jenkins/ref/` contains all reference configuration we want
# to set on a fresh new installation. Use it to bundle additional plugins
# or config file with your custom jenkins Docker image.
RUN mkdir -p /usr/share/jenkins/ref/init.groovy.d

ENV TINI_VERSION 0.14.0
ENV TINI_SHA 6c41ec7d33e857d4779f14d9c74924cab0c7973485d2972419a3b7c7620ff5fd

# Use tini as subreaper in Docker container to adopt zombie processes
RUN curl -fsSL https://github.com/krallin/tini/releases/download/v${TINI_VERSION}/tini-static-amd64 -o /bin/tini && chmod +x /bin/tini \
  && echo "$TINI_SHA  /bin/tini" | sha256sum -c -

COPY init.groovy /usr/share/jenkins/ref/init.groovy.d/tcp-slave-agent-port.groovy

# jenkins version being bundled in this docker image
ARG JENKINS_VERSION
ENV JENKINS_VERSION ${JENKINS_VERSION:-2.60.1}

# jenkins.war checksum, download will be validated using it
ARG JENKINS_SHA=34fde424dde0e050738f5ad1e316d54f741c237bd380bd663a07f96147bb1390

# Can be used to customize where jenkins.war get downloaded from
ARG JENKINS_URL=https://repo.jenkins-ci.org/public/org/jenkins-ci/main/jenkins-war/${JENKINS_VERSION}/jenkins-war-${JENKINS_VERSION}.war

# could use ADD but this one does not check Last-Modified header neither does it allow to control checksum
# see https://github.com/docker/docker/issues/8331
RUN curl -fsSL ${JENKINS_URL} -k -o /usr/share/jenkins/jenkins.war \
  && echo "${JENKINS_SHA}  /usr/share/jenkins/jenkins.war" | sha256sum -c -

ENV JENKINS_UC https://updates.jenkins.io
RUN chown -R ${user} "$JENKINS_HOME" /usr/share/jenkins/ref

# for main web interface:
EXPOSE ${http_port}

# will be used by attached slave agents:
EXPOSE ${agent_port}

ENV COPY_REFERENCE_FILE_LOG $JENKINS_HOME/copy_reference_file.log

USER ${user}

COPY jenkins-support /usr/local/bin/jenkins-support
COPY jenkins.sh /usr/local/bin/jenkins.sh
ENTRYPOINT ["/bin/tini", "--", "/usr/local/bin/jenkins.sh"]

# from a derived Dockerfile, can use `RUN plugins.sh active.txt` to setup /usr/share/jenkins/ref/plugins from a support bundle
COPY plugins.sh /usr/local/bin/plugins.sh
COPY install-plugins.sh /usr/local/bin/install-plugins.sh


问:
Can vector be a container for queue in c++?
What is the reason why vector cannot be a container adapter of a queue?  </p>

<p>Your input is highly appreciated. </p>

答:
Note that the question has been subtly but significantly changed after this answer is submitted.

"backing container" is not a professional term in C++. It is a casually constructed noun phrase consists of adjective "backing" and noun "container".

"container" is an STL container obviously.

"backing" is the present participle of the verb "back", where "to back" means to support. Present participle of a verb can be used as an adjective. "backing" decorates "container" to mean the container is supporting something.

In the STL, there are container adapters, e.g. std::stack, std::queue. They are not containers by themselves. Each relies on a real container to store things. In some casual conversations, people use the casual noun phrase "backing container" to mean the actual container behind a container adapter.

So, which containers can be so-called "backing containers" and which cannot? It depends on the container adapter. For example, std::stack can be backed by vector, deque and list; but std::queue can only be backed by deque and list.

Body:
What is the reason why vector cannot be a container adapter of a queue?

Your input is highly appreciated.


问:
Automatic mySQLi HTML Table Value Refresh
I want to be able refresh the values in a HTML table (retrieved from SQL Database), without reloading the page. I want this to be done without a button that needs to be pressed.

```<code><div id="display" class="myCustom1">
       <script>
$(document).ready(function () {
    // will call refreshPartial every 5 seconds
    setInterval(refreshPartial, 5000)

});

// calls action refreshing the partial
function refreshPartial() {
  $.ajax({
    url: "data.php", //where the table is
    dataType: 'script',
    format: 'js'
 })
}
</script>
    </div>
</code>```

This is currently what I have, but it doesn't display anything.

答:
From what I can see, you dont have the "success"

```<code>function refreshPartial() {
$.ajax({
url: "data.php", //where you process the data
dataType: 'script',
format: 'js',
success: function(data)
{
$("#idOfElementWhereYouWantToPutTheData").html(data);
}

})
}
</code>```

and also the "url" is where you process your data not where you get the data

Body:
I want to be able refresh the values in a HTML table (retrieved from SQL Database), without reloading the page. I want this to be done without a button that needs to be pressed.

This is currently what I have, but it doesn't display anything.

Body:
From what I can see, you dont have the "success"

function refreshPartial() {
$.ajax({
url: "data.php", //where you process the data
dataType: 'script',
format: 'js',
success: function(data)
{
$("#idOfElementWhereYouWantToPutTheData").html(data);
}

})
}

and also the "url" is where you process your data not where you get the data


问:
Save data in python
I'm a little stuck here. I'm running a twitter api request loop and I need to store these tweets in a csv file. I'm doing something like:

```<code>for tweet in tweepy.Cursor(api.search,q=search+ lang="en").items(num_tweets):
    data = tweet.text
    print (tweet.text)
</code>```

My question is what's the easiest way to save tweets in this format:

```<code>["Hello world. I love Reddit!", "Lorem ipsum dolor sit amaet."]
</code>```

答:
You can use the csv library:

```<code>import csv
f = open("output.csv", 'w')
csvWriter = csv.writer(f)
# generate list of tweets here, or put this line in the for loop you already have
csvWriter.writerow(tweet.text)
</code>```

You'll get an output csv file (comma separated value, use an application like excel to open it).

Title: Save data in python

Body:
I'm a little stuck here. I'm running a twitter api request loop and I need to store these tweets in a csv file. I'm doing something like:

for tweet in tweepy.Cursor(api.search,q=search+ lang="en").items(num_tweets):
    data = tweet.text
    print (tweet.text)

My question is what's the easiest way to save tweets in this format:

["Hello world. I love Reddit!", "Lorem ipsum dolor sit amaet."]

Body:
You can use the csv library:

import csv
f = open("output.csv", 'w')
csvWriter = csv.writer(f)
# generate list of tweets here, or put this line in the for loop you already have
csvWriter.writerow(tweet.text)

You'll get an output csv file (comma separated value, use an application like excel to open it).


问:
Flexbox item with overflowing content only works on Chrome
Please take a look at this pen:

https://codepen.io/linck5/pen/gRKJbY?editors=1100

body{ margin: 0;}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.top-bar {
  background-color: darksalmon;
  height: 50px;
}

.inner-container {
  flex: 1;
  background-color: chocolate;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.top {
  background-color: blueviolet;
  flex: 1;
  overflow: auto;
  font-size: 40px;
  line-height: 5rem;
}

.bottom {
  background-color: darkkhaki;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="top-bar">Top bar</div>

  <div class="inner-container">

    <div class="top">
      O<br>v<br>e<br>r<br>f<br>l<br>o<br>w<br>i<br>n<br>g<br>C<br>o<br>n<br>t<br>e<br>n<br>t
    </div>
    <div class="bottom">Bottom part</div>

  </div>

</div></code>```

I want to have only the .top div be scrollable, not the entire page. I don't want the .top div to push down the .bottom div.

And this is exactly what happens on Chrome, everything works perfectly. But on Firefox and Edge, a scrollbar appears on the entire page, and the .bottom div is pushed down.

Also the .top-bar div gets shrunk down instead of having its desired 50px height.

Could you guys help me with this?

答:
Three things to consider:

An initial setting on flex items is flex-shrink: 1. This means that items are permitted to shrink in order to create more space in the container. To disable this feature use flex-shrink: 0.

See this post for a full explanation: What are the differences between flex-basis and width?

An initial setting on flex items is min-height: auto. This means that items cannot be smaller than the height of their content. To override this behavior use min-height: 0.

See this post for a full explanation: Why doesn't flex item shrink past content size?

In your code, Firefox and Edge are adhering strictly to the spec. Chrome, it appears, considers the spec a foundation, but factors in common sense scenarios and expected user behavior.

For your layout to work across browsers, make the following adjustments:

body{ margin: 0;}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.top-bar {
  background-color: darksalmon;
  height: 50px;
  flex-shrink: 0; /* NEW */
  /* Or remove height and flex-shrink and just use this:
     flex: 0 0 50px; */
}

.inner-container {
  flex: 1;
  background-color: chocolate;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0; /* NEW */
}

.top {
  background-color: blueviolet;
  flex: 1;
  overflow: auto;
  font-size: 40px;
  line-height: 5rem;
}

.bottom {
  background-color: darkkhaki;
  /* height: 200px; */
  flex: 0 0 200px; /* NEW */

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="top-bar">Top bar</div>
  <div class="inner-container">
    <div class="top">
O<br>v<br>e<br>r<br>f<br>l<br>o<br>w<br>i<br>n<br>g<br>C<br>o<br>n<br>t<br>e<br>n<br>t
    </div>
    <div class="bottom">Bottom part</div>
  </div>
</div></code>```

revised pen

Body:
Please take a look at this pen:

https://codepen.io/linck5/pen/gRKJbY?editors=1100

body{ margin: 0;}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.top-bar {
  background-color: darksalmon;
  height: 50px;
}

.inner-container {
  flex: 1;
  background-color: chocolate;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.top {
  background-color: blueviolet;
  flex: 1;
  overflow: auto;
  font-size: 40px;
  line-height: 5rem;
}

.bottom {
  background-color: darkkhaki;
  height: 200px;
}

Top bar

      O
v
e
r
f
l
o
w
i
n
g
C
o
n
t
e
n
t

Bottom part

I want to have only the .top div be scrollable, not the entire page. I don't want the .top div to push down the .bottom div.

And this is exactly what happens on Chrome, everything works perfectly. But on Firefox and Edge, a scrollbar appears on the entire page, and the .bottom div is pushed down.

Also the .top-bar div gets shrunk down instead of having its desired 50px height.

Could you guys help me with this?

Body:
Three things to consider:

An initial setting on flex items is flex-shrink: 1. This means that items are permitted to shrink in order to create more space in the container. To disable this feature use flex-shrink: 0.

See this post for a full explanation: What are the differences between flex-basis and width?

An initial setting on flex items is min-height: auto. This means that items cannot be smaller than the height of their content. To override this behavior use min-height: 0.

See this post for a full explanation: Why doesn't flex item shrink past content size?

In your code, Firefox and Edge are adhering strictly to the spec. Chrome, it appears, considers the spec a foundation, but factors in common sense scenarios and expected user behavior.

For your layout to work across browsers, make the following adjustments:

body{ margin: 0;}

.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.top-bar {
  background-color: darksalmon;
  height: 50px;
  flex-shrink: 0; /* NEW */
  /* Or remove height and flex-shrink and just use this:
     flex: 0 0 50px; */
}

.inner-container {
  flex: 1;
  background-color: chocolate;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0; /* NEW */
}

.top {
  background-color: blueviolet;
  flex: 1;
  overflow: auto;
  font-size: 40px;
  line-height: 5rem;
}

.bottom {
  background-color: darkkhaki;
  /* height: 200px; */
  flex: 0 0 200px; /* NEW */

}

<div class="container">
  <div class="top-bar">Top bar</div>
  <div class="inner-container">
    <div class="top">
O<br>v<br>e<br>r<br>f<br>l<br>o<br>w<br>i<br>n<br>g<br>C<br>o<br>n<br>t<br>e<br>n<br>t
    </div>
    <div class="bottom">Bottom part</div>
  </div>
</div>

revised pen


问:
What are the most important functional differences between C# and VB.NET?
Certainly there's the difference in general syntax, but what other critical distinctions exist?  There are some differences, right?

答:
Although VB.NET supports try...catch type exception handling, it still has something similar to VB6's ON ERROR. ON ERROR can be seriously abused, and in the vast majority of cases, try...catch is far better; but ON ERROR can be useful when handling COM time-out operations where the error can be trapped, decoded, and the final "try again" is a simple one line.
You can do the same with try...catch but the code is a lot messier.</p>

OwnerDisplayName: Larsenal

ContentLicense: CC BY-SA 2.5


问:
Qt OpenGL (QOpenGLWidget) - Simple Triangle
As a newbee to QT+OpenGL using QOpenGLWidget, I am unable to color my triangle.
Please find my code here, using QMainWindow for GUI ...

```<code>// main.cpp
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}
</code>```

Here the GUI - window

```<code>// MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H
</code>```

Here implementation - file ...

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}
</code>```

Here is the widget rendering Opengl-Context.

```<code>#ifndef OPENGLWIDGET_H
#define OPENGLWIDGET_H

#include <QWidget>
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLContext>
#include <QOpenGLShaderProgram>
#include <QOpenGLBuffer>
#include <QOpenGLVertexArrayObject>
#include <QMatrix4x4>

class OpenglWidget : public QOpenGLWidget, public QOpenGLFunctions
{
public:
    OpenglWidget(QWidget *parent = 0);
    ~OpenglWidget();

protected:
    void initializeGL();
    void resizeGL(int width, int height);
    void paintGL();
    GLuint m_posAttr;
    GLuint m_colAttr;
    GLuint m_matrixUniform;
    QOpenGLShaderProgram *m_program;
};
#endif // OPENGLWIDGET_H
</code>```

Here is the implementation file ...

```<code>#include "openglwidget.h"

OpenglWidget::OpenglWidget(QWidget *parent) :
    QOpenGLWidget(parent)
{
    setFormat(QSurfaceFormat::defaultFormat());
}

OpenglWidget::~OpenglWidget()
{
}

static const char *vertexShaderSource =
    "attribute highp vec4 posAttr;\n"
    "attribute lowp vec4 colAttr;\n"
    "varying lowp vec4 col;\n"
    "uniform highp mat4 matrix;\n"
    "void main() {\n"
    "   col = vec4(1, 0, 0, 1);\n"
    "   gl_Position = matrix * posAttr;\n"
    "}\n";

static const char *fragmentShaderSource =
    "varying lowp vec4 col;\n"
    "void main() {\n"
    "   gl_FragColor = col;\n"
    "}\n";

void OpenglWidget::initializeGL()
{
    makeCurrent();
    initializeOpenGLFunctions();
    glClearColor(0.0f, 0.0f, 1.0f, 1.0f);

    // Create Shader (Do not release until VAO is created)
    m_program = new QOpenGLShaderProgram(this);
    m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource);
    m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource);
    m_program->link();
    m_posAttr = m_program->attributeLocation("posAttr");
    m_colAttr = m_program->attributeLocation("colAttr");
    m_matrixUniform = m_program->attributeLocation("matrix");

    m_program->release();
}

void OpenglWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT);
    makeCurrent();

    //m_program->bind();

    QMatrix4x4 matrix;
    matrix.perspective(60.0f, 4.0f/3.0f, 0.1f, 100.0f);
    matrix.translate(0, 0, -2);

    m_program->setUniformValue(m_matrixUniform, matrix);

    GLfloat vertices[] = {
        0.0f, 0.707f, 0.0f,
        -0.5f, -0.5f, 0.0f,
        0.5f, -0.5f, 0.0f
    };

    GLfloat colors[] = {
        1.0f, 0.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
        0.0f, 0.0f, 1.0f
    };

    glVertexAttribPointer(m_posAttr, 3, GL_FLOAT, GL_FALSE, 0, vertices);
    glVertexAttribPointer(m_colAttr, 3, GL_FLOAT, GL_FALSE, 0, colors);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(0);

    m_program->release();
}

void OpenglWidget::resizeGL(int width, int height)
{
    glViewport(0, 0, width, height);
}
</code>```

Here the rendered triangle is just white.
I am unable to understand whether the shader is compiled and attributes are linked but still, I am unable to color the triangle.

If I can get any guidance... ???Output

答:
Maybe you can use

```<code>m_colAttr = m_program->attributeLocation("col");
</code>```

instead of

```<code>m_colAttr = m_program->attributeLocation("colAttr");
</code>```

If you write in shader

```<code>gl_FragColor = col;
</code>```

col = col, colAttr != col

Change name of attribute, and if this doesn't help change this call in initializeGL

```<code>program->release();
</code>```

to

```<code>program->bind();
</code>```

Body:
As a newbee to QT+OpenGL using QOpenGLWidget, I am unable to color my triangle.
Please find my code here, using QMainWindow for GUI ...

// main.cpp
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

Here the GUI - window

// MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

Here implementation - file ...

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

Here is the widget rendering Opengl-Context.

#ifndef OPENGLWIDGET_H
#define OPENGLWIDGET_H

#include <QWidget>
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLContext>
#include <QOpenGLShaderProgram>
#include <QOpenGLBuffer>
#include <QOpenGLVertexArrayObject>
#include <QMatrix4x4>

class OpenglWidget : public QOpenGLWidget, public QOpenGLFunctions
{
public:
    OpenglWidget(QWidget *parent = 0);
    ~OpenglWidget();

protected:
    void initializeGL();
    void resizeGL(int width, int height);
    void paintGL();
    GLuint m_posAttr;
    GLuint m_colAttr;
    GLuint m_matrixUniform;
    QOpenGLShaderProgram *m_program;
};
#endif // OPENGLWIDGET_H

Here is the implementation file ...

#include "openglwidget.h"

OpenglWidget::OpenglWidget(QWidget *parent) :
    QOpenGLWidget(parent)
{
    setFormat(QSurfaceFormat::defaultFormat());
}

OpenglWidget::~OpenglWidget()
{
}

static const char *vertexShaderSource =
    "attribute highp vec4 posAttr;\n"
    "attribute lowp vec4 colAttr;\n"
    "varying lowp vec4 col;\n"
    "uniform highp mat4 matrix;\n"
    "void main() {\n"
    "   col = vec4(1, 0, 0, 1);\n"
    "   gl_Position = matrix * posAttr;\n"
    "}\n";

static const char *fragmentShaderSource =
    "varying lowp vec4 col;\n"
    "void main() {\n"
    "   gl_FragColor = col;\n"
    "}\n";

void OpenglWidget::initializeGL()
{
    makeCurrent();
    initializeOpenGLFunctions();
    glClearColor(0.0f, 0.0f, 1.0f, 1.0f);

    // Create Shader (Do not release until VAO is created)
    m_program = new QOpenGLShaderProgram(this);
    m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource);
    m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource);
    m_program->link();
    m_posAttr = m_program->attributeLocation("posAttr");
    m_colAttr = m_program->attributeLocation("colAttr");
    m_matrixUniform = m_program->attributeLocation("matrix");

    m_program->release();
}

void OpenglWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT);
    makeCurrent();

    //m_program->bind();

    QMatrix4x4 matrix;
    matrix.perspective(60.0f, 4.0f/3.0f, 0.1f, 100.0f);
    matrix.translate(0, 0, -2);

    m_program->setUniformValue(m_matrixUniform, matrix);

    GLfloat vertices[] = {
        0.0f, 0.707f, 0.0f,
        -0.5f, -0.5f, 0.0f,
        0.5f, -0.5f, 0.0f
    };

    GLfloat colors[] = {
        1.0f, 0.0f, 0.0f,
        0.0f, 1.0f, 0.0f,
        0.0f, 0.0f, 1.0f
    };

    glVertexAttribPointer(m_posAttr, 3, GL_FLOAT, GL_FALSE, 0, vertices);
    glVertexAttribPointer(m_colAttr, 3, GL_FLOAT, GL_FALSE, 0, colors);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(0);

    m_program->release();
}

void OpenglWidget::resizeGL(int width, int height)
{
    glViewport(0, 0, width, height);
}

Here the rendered triangle is just white.
I am unable to understand whether the shader is compiled and attributes are linked but still, I am unable to color the triangle.

If I can get any guidance... ???Output

Body:
Maybe you can use

m_colAttr = m_program->attributeLocation("col");

instead of

m_colAttr = m_program->attributeLocation("colAttr");

If you write in shader

gl_FragColor = col;

col = col, colAttr != col

Change name of attribute, and if this doesn't help change this call in initializeGL

program->release();

to

program->bind();


问:
One Sub for multiple VBA Userform Items
I am writing a program in VBA where I use multiple listboxes in a Userform. Is it possible to write one program for more than one listbox (a single program to control Private Sub Listbox1_Click, Private Sub Listbox2_Click, and Private Sub Listbox4_Click)

Thanks

答:
You can create a class to handle the Listbox Events and use a class level array or collection to hold references to the Listboxes.

ListboxEventsClass Code

```<code>Public WithEvents lBox As MSForms.ListBox

Private Sub lBox_Click()
    MsgBox "You clicked: " & lBox.Name _
    & vbCrLf & "Value: " & lBox.Value
End Sub
</code>```

Userform Code

```<code>Private lBoxes(3) As ListboxEventsClass

Private Sub UserForm_Initialize()
    Set lBoxes(0) = New ListboxEventsClass
    Set lBoxes(1) = New ListboxEventsClass
    Set lBoxes(2) = New ListboxEventsClass

    Set lBoxes(0).lBox = ListBox1
    Set lBoxes(1).lBox = ListBox2
    Set lBoxes(2).lBox = ListBox3

    ListBox1.List = Array("Red", "White", "Blue")
    ListBox2.List = Array("Dog", "Cat", "Horse")
    ListBox3.List = Array("VBA", "Java", "C++")
End Sub
</code>```

Title: One Sub for multiple VBA Userform Items

Body:
You can create a class to handle the Listbox Events and use a class level array or collection to hold references to the Listboxes.

ListboxEventsClass Code

Public WithEvents lBox As MSForms.ListBox

Private Sub lBox_Click()
    MsgBox "You clicked: " & lBox.Name _
    & vbCrLf & "Value: " & lBox.Value
End Sub

Userform Code

Private lBoxes(3) As ListboxEventsClass

Private Sub UserForm_Initialize()
    Set lBoxes(0) = New ListboxEventsClass
    Set lBoxes(1) = New ListboxEventsClass
    Set lBoxes(2) = New ListboxEventsClass

    Set lBoxes(0).lBox = ListBox1
    Set lBoxes(1).lBox = ListBox2
    Set lBoxes(2).lBox = ListBox3

    ListBox1.List = Array("Red", "White", "Blue")
    ListBox2.List = Array("Dog", "Cat", "Horse")
    ListBox3.List = Array("VBA", "Java", "C++")
End Sub


问:
MySQL automatic insert data, count between two date in different column
I'm new in sql.
Now I want to count days between two date in different column (TGL_PEMINJAMAN and TGL_PENGEMBALIAN), and automatic insert on another column (SISA_HARI)

TGL_PEMINJAMAN -> date

TGL_PENGEMBALIAN -> date

SISA_HARI -> int

Here's screenshoot my table

for example in ID_PEMINJAMAN = 3

TGL_PEMINJAMAN -> 2017-07-02

TGL_PENGEMBALIAN -> 2017-07-07

and in SISA_HARI must be automatic insert -> 5

So, what should I do? May I try to use trigger on sql?
Thanks

答:
If you want to compute the difference between the two dates TGL_PEMINJAMAN  and TGL_PENGEMBALIAN as a selection, you may try this sql

```<code>SELECT TO_DATE(TGL_PEMINJAMAN,'DD-MM-YYYY') - TO_DATE(TGL_PENGEMBALIAN,'DD-MM-YYYY') as Datediff FROM YOURTABLENAME;
</code>```

You are right, If it must be automatically updated and your MYSQL version is compatible, you can try with trigger.

Body:
If you want to compute the difference between the two dates TGL_PEMINJAMAN  and TGL_PENGEMBALIAN as a selection, you may try this sql

SELECT TO_DATE(TGL_PEMINJAMAN,'DD-MM-YYYY') - TO_DATE(TGL_PENGEMBALIAN,'DD-MM-YYYY') as Datediff FROM YOURTABLENAME;

You are right, If it must be automatically updated and your MYSQL version is compatible, you can try with trigger.


问:
How do I take max value of a pandas dataframe column and find the corresponding value in another column?
I want to take max value of a pandas dataframe column and find the corresponding value in another column? Let's assume there are not duplicates in the maximum value, so you are always returning only one value. For example,

```<code>GPA   ID
2.3  Tina1
3.4  Bob1
3.6  Lia1
2.9  Tina2
4.0  Blake1
4.5  Conor2
</code>```

Here the max GPA is 4.5, but I want to return the corresponding id for the max GPA, so I would return Conor2. I am unsure of how to do this, so help would be greatly appreciated :) Thanks!

答:
Let's use idxmax:

```<code>df.set_index('ID').idxmax()
</code>```

Output:

```<code>GPA    Conor2
dtype: object
</code>```

A series with a single value Conor2.

Body:
I want to take max value of a pandas dataframe column and find the corresponding value in another column? Let's assume there are not duplicates in the maximum value, so you are always returning only one value. For example,

GPA   ID
2.3  Tina1
3.4  Bob1
3.6  Lia1
2.9  Tina2
4.0  Blake1
4.5  Conor2

Here the max GPA is 4.5, but I want to return the corresponding id for the max GPA, so I would return Conor2. I am unsure of how to do this, so help would be greatly appreciated :) Thanks!

Body:
Let's use idxmax:

df.set_index('ID').idxmax()

Output:

GPA    Conor2
dtype: object

A series with a single value Conor2.

ContentLicense: CC BY-SA 4.0


问:
Proper way to use PDO/PHP to insert data into a preset database and table in mySQL
So, I've been using PDO/PHP to build a login/sign-up form for my website.  Now that I've managed to use PDO to connect and build a complete database and table that I want the data to go in.  I want to know what would the proper way to insert data into that table using the $_POST superglobal. Thanks.</p>

答:
```<code>$query = "INSERT INTO table (column1, column2, column3) VALUES  (:insert_value1, :insert_value2,:insert_value3";
$stmt = $db->prepare($query);
$stmt->bindParam(':insert_value1', $_POST[value1]);
$stmt->bindParam(':insert_value2', $_POST[value2]);
$stmt->bindParam(':insert_value3', $_POST[value3]);
$stmt->execute();
</code>```


问:
Why don't Scala Lists have an Ordering?
Is there a reason why there is no implicit Ordering for Lists in Scala?

```<code>val lists = List(List(2, 3, 1), List(2, 1, 3))
lists.sorted

error: could not find implicit value for parameter ord: Ordering[List[Int]]
</code>```

EDIT

Yes, my question is why there is no built-in Ordering that's already implicitly in scope. To me, it seems obvious that the second list should be "less than" the first list since the items at 0 are equal and the second list has the lower item at 1. I was wondering if maybe it's that there's no good answer when the Lists are two different sizes.

答:
You can use sortWith. This doesn't take differently sized lists into account because zip will throw out the difference, but I think it does something like what you're after:</p>

```<code>lists.sortWith((a,b) => {
  a.zip(b).filterNot(x => x._1 == x._2) match {
    case Nil => true
    case t => t._1 < t._2
  }
})
</code>```

Title: Why don't Scala Lists have an Ordering?

Body:
Is there a reason why there is no implicit Ordering for Lists in Scala?

val lists = List(List(2, 3, 1), List(2, 1, 3))
lists.sorted

error: could not find implicit value for parameter ord: Ordering[List[Int]]

EDIT

Yes, my question is why there is no built-in Ordering that's already implicitly in scope. To me, it seems obvious that the second list should be "less than" the first list since the items at 0 are equal and the second list has the lower item at 1. I was wondering if maybe it's that there's no good answer when the Lists are two different sizes.

Body:
You can use sortWith. This doesn't take differently sized lists into account because zip will throw out the difference, but I think it does something like what you're after:

lists.sortWith((a,b) => {
  a.zip(b).filterNot(x => x._1 == x._2) match {
    case Nil => true
    case t => t._1 < t._2
  }
})


问:
How to correctly write this "simple" T-SQL query
I took a test with a bunch T-SQL exercises. I did well in all but one of them. I took a picture of it to find out later the correct answer. I don't consider myself an expert but I know my way around SQL. Yet, I cannot write what should be a not so hard query to come up with.

Here is the exercise:

I probably need to group by Name and Sum the price but I am still kinda lost. Help with this one! Thank you

答:
You also can try this</p>

```<code>SELECT
p.Name
,ISNULL(s.Total_Sales,0) AS Total_Sales
,ISNULL(s.Total_Amount,0) AS Total_Amount
FROM people p
LEFT JOIN
(
    SELECT
    fk_people
    ,COUNT(*) AS Total_Sales
    ,SUM(Price) AS Total_Amount
    FROM Sales
    GROUP BY fk_people
) s ON p.ID = s.fk_people
</code>```

Body:
You also can try this

SELECT
p.Name
,ISNULL(s.Total_Sales,0) AS Total_Sales
,ISNULL(s.Total_Amount,0) AS Total_Amount
FROM people p
LEFT JOIN
(
    SELECT
    fk_people
    ,COUNT(*) AS Total_Sales
    ,SUM(Price) AS Total_Amount
    FROM Sales
    GROUP BY fk_people
) s ON p.ID = s.fk_people


问:
three.js mousedown not working when trackball controls enabled
Trackball works well in my three.js program along with onMouseClick and onMouseUp event listeners.
I enable Trackball using the line:-

```<code>controls = new THREE.TrackballControls( scene01camera02 , DOM_container);
</code>```

But  the onMouseDown event listener does not work.

If I disable trackball (by commenting out the line of code shown above) and disable any other related code
then onMouseDown works fine.

Is there some way to use both onMouseDown and Trackball control at the same time?

The reason is so that when a mousedown event occurs I can detect where on screen it occurred
and then toggle the controls variable so Trackball controls the apropriate scene_camera_container.

```<code>    In HTML
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <div id="ThreeJScontainer" style="position: absolute; left:0px; top:0px"></div>

    In F_Init()
    renderer = new THREE.WebGLRenderer( {antialias:true} );
    DOM_container = document.getElementById( 'ThreeJScontainer' );
    DOM_container.appendChild( renderer.domElement );

    renderer.setSize( window.innerWidth, window.innerHeight );

    controls = new THREE.TrackballControls( scene01camera02 , DOM_container);

    document.addEventListener( 'mousemove', onDocumentMouseMove, false );  //works OK
    document.addEventListener( 'mousedown', onDocumentMouseDown, false );
    document.addEventListener('click', SOW_onDocumentMouseClick, false);  //works OK

    //in SOW_onDocumentMouseClick event handler
    // I reset the controls to point to a new scene_camera according to the viewport clicked on.
    //Example:-
    controls = new THREE.TrackballControls( scene01camera01 , DOM_container);

    //if onDocumentMouseDown was working as I expected I would do the resetting in there

    In F_Update()
    controls.update();

    In F_Render()
    renderer.setViewport( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );
    renderer.clear();

    //...BOTTOM STRIP (DASHBOARD)
    renderer.setViewport( bottomPanelXmin, bottomPanelYmin, bottomPanelWidth, bottomPanelHeight );
    renderer.render( scene02, scene02camera04 );
    // etc
    // etc for other "Panels" (my name for viewports)
</code>```

Example prototype running at:- http://www.zen226082.zen.co.uk/TRI_VP.html (best in Chrome or Opera, alignment problem in Firefox).

答: I found that the trackball controls module assumes an animation loop is running, but in my case, not so. I needed to modify the code to call _this.update(); as events were being processed (pretty much whenever it calls _this.dispatchEvent, e.g at the end of mousewheel and other event processing functions.

Body:
Trackball works well in my three.js program along with onMouseClick and onMouseUp event listeners.
I enable Trackball using the line:-

controls = new THREE.TrackballControls( scene01camera02 , DOM_container);

But  the onMouseDown event listener does not work.

If I disable trackball (by commenting out the line of code shown above) and disable any other related code
then onMouseDown works fine.

Is there some way to use both onMouseDown and Trackball control at the same time?

The reason is so that when a mousedown event occurs I can detect where on screen it occurred
and then toggle the controls variable so Trackball controls the apropriate scene_camera_container.

    In HTML
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

    In F_Init()
    renderer = new THREE.WebGLRenderer( {antialias:true} );
    DOM_container = document.getElementById( 'ThreeJScontainer' );
    DOM_container.appendChild( renderer.domElement );

    renderer.setSize( window.innerWidth, window.innerHeight );

    controls = new THREE.TrackballControls( scene01camera02 , DOM_container);

    document.addEventListener( 'mousemove', onDocumentMouseMove, false );  //works OK
    document.addEventListener( 'mousedown', onDocumentMouseDown, false );
    document.addEventListener('click', SOW_onDocumentMouseClick, false);  //works OK

    //in SOW_onDocumentMouseClick event handler
    // I reset the controls to point to a new scene_camera according to the viewport clicked on.
    //Example:-
    controls = new THREE.TrackballControls( scene01camera01 , DOM_container);

    //if onDocumentMouseDown was working as I expected I would do the resetting in there

    In F_Update()
    controls.update();

    In F_Render()
    renderer.setViewport( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );
    renderer.clear();

    //...BOTTOM STRIP (DASHBOARD)
    renderer.setViewport( bottomPanelXmin, bottomPanelYmin, bottomPanelWidth, bottomPanelHeight );
    renderer.render( scene02, scene02camera04 );
    // etc
    // etc for other "Panels" (my name for viewports)

Example prototype running at:- http://www.zen226082.zen.co.uk/TRI_VP.html (best in Chrome or Opera, alignment problem in Firefox).


问:
Webpack not found when app deployed to Heroku
I'm getting the error sh: 1: webpack: not found when the app is deployed to production. I've tried moving all the dependencies related to webpack from the devDependency list to the dependency list in the package.json file to avail. The Heroku error log can be seen here for greater insight. What steps could be taken to solve this issue?

答:
Can you try running npm run build on postinstall? This works for me.

package.json

```<code>{
  ...
  "scripts": {
    "start": "node server.js",
    "postinstall": "npm run build",
    ...
  }
  ...
}
</code>```

Body:
Can you try running npm run build on postinstall? This works for me.

package.json

{
  ...
  "scripts": {
    "start": "node server.js",
    "postinstall": "npm run build",
    ...
  }
  ...
}


问:
How to work with abstract type members in Scala
I'm running into issues with the following code (heavily simplified). Looks like the problem may be with the way I use abstract type members. I would appreciate someone pointing out and explaining what I'm doing wrong here. Compiler error at the bottom.
I'm using Scala version 2.12.

```<code>trait DataType {
    type A

    def convert(value: String): A
    def convertToString(value: A): String
}

case object IntType extends DataType {
    type A = Int

    def convert(value: String): A = value.toInt
    def convertToString(value: A): String = value.toString
}

trait Codec[T <: DataType] {
    val dtype: T

    def encode(data: Array[String]): Array[T#A]
    def decode(data: Array[T#A]): Array[String]
}

class CodecImp[T <: DataType](val dtype: T)(implicit tag: ClassTag[T#A]) extends Codec[T] {
    def encode(data: Array[String]): Array[T#A] = {
        Array[T#A](dtype.convert(data(0)))
    }

    def decode(data: Array[T#A]): Array[String] = {
        Array[String](dtype.convertToString(data(0)))
    }
}

val cod = new CodecImp(IntType)
val encoded = cod.encode(Array("1", "2", "3")) // expecting: Array[IntType.A]
val decoded = cod.decode(encoded) // expecting: Array[String]
</code>```

Compiler error.

```<code>Error:(30, 50) type mismatch;
 found   : T#A
 required: CodecImp.this.dtype.A
        Array[String](dtype.convertToString(data(0)))
                 ^
</code>```

答:
I found What does the # operator mean in Scala? explained the '#' operator pretty well.

Each instance of DataType has it's own path dependent type A.

The difference between: T#A meaning A is a nested class of any T and dtype.A meaning the A class of dtype

You could change the Codec trait method signatures to something like:

```<code>def encode(data: Array[String]): Array[dtype.A]
def decode(data: Array[dtype.A]): Array[String]
</code>```

But type parameters might be a better way to express the relation.

Body:
I'm running into issues with the following code (heavily simplified). Looks like the problem may be with the way I use abstract type members. I would appreciate someone pointing out and explaining what I'm doing wrong here. Compiler error at the bottom.
I'm using Scala version 2.12.

trait DataType {
    type A

    def convert(value: String): A
    def convertToString(value: A): String
}

case object IntType extends DataType {
    type A = Int

    def convert(value: String): A = value.toInt
    def convertToString(value: A): String = value.toString
}

trait Codec[T <: DataType] {
    val dtype: T

    def encode(data: Array[String]): Array[T#A]
    def decode(data: Array[T#A]): Array[String]
}

class CodecImp[T <: DataType](val dtype: T)(implicit tag: ClassTag[T#A]) extends Codec[T] {
    def encode(data: Array[String]): Array[T#A] = {
        Array[T#A](dtype.convert(data(0)))
    }

    def decode(data: Array[T#A]): Array[String] = {
        Array[String](dtype.convertToString(data(0)))
    }
}

val cod = new CodecImp(IntType)
val encoded = cod.encode(Array("1", "2", "3")) // expecting: Array[IntType.A]
val decoded = cod.decode(encoded) // expecting: Array[String]

Compiler error.

Error:(30, 50) type mismatch;
 found   : T#A
 required: CodecImp.this.dtype.A
        Array[String](dtype.convertToString(data(0)))
                 ^

Body:
I found What does the # operator mean in Scala? explained the '#' operator pretty well.

Each instance of DataType has it's own path dependent type A.

The difference between: T#A meaning A is a nested class of any T and dtype.A meaning the A class of dtype

You could change the Codec trait method signatures to something like:

def encode(data: Array[String]): Array[dtype.A]
def decode(data: Array[dtype.A]): Array[String]

But type parameters might be a better way to express the relation.


问:
Relocating Alaska and Hawaii on thematic map of the USA with ggplot2
I am trying to create a thematic map showing all 50 US states, but I am having trouble relocating Alaska and Hawaii in a reliable way. I have a couple of ideas but none of them work well. I will demonstrate them now.

First we need to import the data; using the data in the maps package is not enough because it does not include Hawaii and Alaska.

```<code>setwd(tempdir())
download.file("https://dl.dropbox.com/s/wl0z5rpygtowqbf/states_21basic.zip?dl=1",
              "usmapdata.zip",
              method = "curl")
# This is a mirror of http://www.arcgis.com/home/item.html?
# id=f7f805eb65eb4ab787a0a3e1116ca7e5
unzip("usmapdata.zip")

require(rgdal)
all_states <- readOGR("states_21basic/", "states")

require(ggplot2); require(maptools); require(rgeos); require(mapproj);
all_states <- fortify(all_states, region = "STATE_NAME")
</code>```

Now we define some plot aesthetics:

```<code>p <- ggplot() + geom_polygon(
  aes(x=long, y=lat, group = group, fill = as.numeric(as.factor(id))),
  colour="white", size = 0.25
) + coord_map(projection="azequalarea") +
scale_fill_gradient(limits = c(1,50))
</code>```

Now we remove all background etc so they don't clash when we overlap the non-contiguous states:

```<code>p <-   p + theme(axis.line=element_blank(),
            axis.text.x=element_blank(),
            axis.text.y=element_blank(),
            axis.ticks=element_blank(),
            axis.title.x=element_blank(),
            axis.title.y=element_blank(),
            panel.background=element_blank(),
            panel.border=element_blank(),
            panel.grid.major=element_blank(),
            panel.grid.minor=element_blank(),
            plot.background=element_blank())
</code>```

Using viewports

The first idea I had was to use viewports:

```<code>AK <- p %+% subset(all_states, id == "Alaska") + theme(legend.position = "none")
HI <- p %+% subset(all_states, id == "Hawaii") + theme(legend.position = "none")
contiguous <- p %+% subset(all_states, id != "Alaska" & id != "Hawaii")

grid.newpage()
vp <- viewport(width = 1, height = 1)
print(contiguous, vp = vp)
subvp1 <- viewport(width = 0.25, height = 0.25, x = 0.18, y = 0.33)
print(AK, vp = subvp1)
subvp2 <- viewport(width = 0.12, height = 0.12, x = 0.32, y = 0.27)
print(HI, vp = subvp2)
</code>```

This looks nice but it is not satisfactory because it is very sensitive to slight changes in the figure, for example resizing or changes in the size and shape of the legend.

Manually moving Alaska and Hawaii

```<code>all_states_AKHImoved <- within(all_states, {
  lat[id == "Alaska"] <- lat[id == "Alaska"] - 45
  long[id == "Alaska"] <- long[id == "Alaska"] + 40
  lat[id == "Hawaii"] <- lat[id == "Hawaii"] + 0
  long[id == "Hawaii"] <- long[id == "Hawaii"] + 70
})
p %+% all_states_AKHImoved
</code>```

This is not satisfactory because Alaska is usually not to scale on most US maps so it looks very big. Also relocating Alaska and Hawaii changes the distortion introduced by the map projection.

Question

Does anyone have any better approaches?

答:
I've published the fiftystater R package on GitHub (devtools::install_github("wmurphyrd/fiftystater")) to provide a simple solution. It is based on the steps from Spacedman's answer (would link but insufficient rep) and is published as a ggplot2::geom_map ready shape data frame named fifty_states to remove the need to install dependencies, track down a source shape file, or tweak elide values.

```<code>library(ggplot2)
library(mapproj)
library(fiftystater)

crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)

p <- ggplot(crimes, aes(map_id = state)) +
  geom_map(aes(fill = Assault), map = fifty_states) +
  expand_limits(x = fifty_states$long, y = fifty_states$lat) +
  coord_map()
p
</code>```

fifty states map

Plot noise can be cleaned up in the usual way, and there is also the fifty_states_inset_boxes function in the package to add inset boxes:

```<code>p + scale_x_continuous(breaks = NULL) +
  scale_y_continuous(breaks = NULL) +
  labs(x = "", y = "") +
  theme(panel.background = element_blank()) +
  fifty_states_inset_boxes()
</code>```

fifty states with inset boxes

Body:
I am trying to create a thematic map showing all 50 US states, but I am having trouble relocating Alaska and Hawaii in a reliable way. I have a couple of ideas but none of them work well. I will demonstrate them now.

First we need to import the data; using the data in the maps package is not enough because it does not include Hawaii and Alaska.

setwd(tempdir())
download.file("https://dl.dropbox.com/s/wl0z5rpygtowqbf/states_21basic.zip?dl=1",
              "usmapdata.zip",
              method = "curl")
# This is a mirror of http://www.arcgis.com/home/item.html?
# id=f7f805eb65eb4ab787a0a3e1116ca7e5
unzip("usmapdata.zip")

require(rgdal)
all_states <- readOGR("states_21basic/", "states")

require(ggplot2); require(maptools); require(rgeos); require(mapproj);
all_states <- fortify(all_states, region = "STATE_NAME")

Now we define some plot aesthetics:

p <- ggplot() + geom_polygon(
  aes(x=long, y=lat, group = group, fill = as.numeric(as.factor(id))),
  colour="white", size = 0.25
) + coord_map(projection="azequalarea") +
scale_fill_gradient(limits = c(1,50))

Now we remove all background etc so they don't clash when we overlap the non-contiguous states:

p <-   p + theme(axis.line=element_blank(),
            axis.text.x=element_blank(),
            axis.text.y=element_blank(),
            axis.ticks=element_blank(),
            axis.title.x=element_blank(),
            axis.title.y=element_blank(),
            panel.background=element_blank(),
            panel.border=element_blank(),
            panel.grid.major=element_blank(),
            panel.grid.minor=element_blank(),
            plot.background=element_blank())

Using viewports

The first idea I had was to use viewports:

AK <- p %+% subset(all_states, id == "Alaska") + theme(legend.position = "none")
HI <- p %+% subset(all_states, id == "Hawaii") + theme(legend.position = "none")
contiguous <- p %+% subset(all_states, id != "Alaska" & id != "Hawaii")

grid.newpage()
vp <- viewport(width = 1, height = 1)
print(contiguous, vp = vp)
subvp1 <- viewport(width = 0.25, height = 0.25, x = 0.18, y = 0.33)
print(AK, vp = subvp1)
subvp2 <- viewport(width = 0.12, height = 0.12, x = 0.32, y = 0.27)
print(HI, vp = subvp2)

This looks nice but it is not satisfactory because it is very sensitive to slight changes in the figure, for example resizing or changes in the size and shape of the legend.

Manually moving Alaska and Hawaii

all_states_AKHImoved <- within(all_states, {
  lat[id == "Alaska"] <- lat[id == "Alaska"] - 45
  long[id == "Alaska"] <- long[id == "Alaska"] + 40
  lat[id == "Hawaii"] <- lat[id == "Hawaii"] + 0
  long[id == "Hawaii"] <- long[id == "Hawaii"] + 70
})
p %+% all_states_AKHImoved

This is not satisfactory because Alaska is usually not to scale on most US maps so it looks very big. Also relocating Alaska and Hawaii changes the distortion introduced by the map projection.

Question

Does anyone have any better approaches?

Body:
I've published the fiftystater R package on GitHub (devtools::install_github("wmurphyrd/fiftystater")) to provide a simple solution. It is based on the steps from Spacedman's answer (would link but insufficient rep) and is published as a ggplot2::geom_map ready shape data frame named fifty_states to remove the need to install dependencies, track down a source shape file, or tweak elide values.

library(ggplot2)
library(mapproj)
library(fiftystater)

crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)

p <- ggplot(crimes, aes(map_id = state)) +
  geom_map(aes(fill = Assault), map = fifty_states) +
  expand_limits(x = fifty_states$long, y = fifty_states$lat) +
  coord_map()
p

fifty states map

Plot noise can be cleaned up in the usual way, and there is also the fifty_states_inset_boxes function in the package to add inset boxes:

p + scale_x_continuous(breaks = NULL) +
  scale_y_continuous(breaks = NULL) +
  labs(x = "", y = "") +
  theme(panel.background = element_blank()) +
  fifty_states_inset_boxes()

fifty states with inset boxes


问:
How do you make an etag that matches Apache?
I want to make an etag that matches what Apache produces.  How does apache create it's etags?</p>

答:
Apache uses the standard format of inode-filesize-mtime.  The only caveat to this is that the mtime must be epoch time and padded with zeros so it is 16 digits.  Here is how to do it in PHP:</p>

```<code>$fs = stat($file);
header("Etag: ".sprintf('"%x-%x-%s"', $fs['ino'], $fs['size'],base_convert(str_pad($fs['mtime'],16,"0"),10,16)));
</code>```

OwnerDisplayName: Chris Bartow

LastEditorDisplayName: Stu Thompson

Body:
Apache uses the standard format of inode-filesize-mtime.  The only caveat to this is that the mtime must be epoch time and padded with zeros so it is 16 digits.  Here is how to do it in PHP:

$fs = stat($file);
header("Etag: ".sprintf('"%x-%x-%s"', $fs['ino'], $fs['size'],base_convert(str_pad($fs['mtime'],16,"0"),10,16)));


问:
How to prevent unauthorized spidering
I want to prevent automated html scraping from one of our sites while not affecting legitimate spidering (googlebot, etc.). Is there something that already exists to accomplish this? Am I even using the correct terminology?

EDIT: I'm mainly looking to prevent people that would be doing this maliciously. I.e. they aren't going to abide by robots.txt

EDIT2: What about preventing use by "rate of use" ... i.e. captcha to continue browsing if automation is detected and the traffic isn't from a legitimate (google, yahoo, msn, etc.) IP.

答: robots.txt only works if the spider honors it.  You can create a HttpModule to filter out spiders that you don't want crawling your site.</p>

OwnerDisplayName: Kyle West

Title: How to prevent unauthorized spidering

LastEditorDisplayName: Kyle West

OwnerDisplayName: Todd

LastEditorDisplayName: Todd


问:
Updating view model from object not working
I want to be able to observe an object inside the view model. I have a simple example that doesn't work as expected, can anyone see the problem?

Using knockout 1.1.1, have 2 inputs as such:

<form data-bind="submit: save">
    <input type="text" data-bind="value: deckName" />
    <input type="text" data-bind="value: deck().Name" />
    <button type="submit">Go</button>
</form>
```

<p>When the page loads, the inputs get the default values, but on submitting the form <code>viewModel.deck().Name</code> is not updated but <code>viewModel.deckName</code> is.</p>

<pre class="lang-html prettyprint-override"><code><script type="text/javascript">
    var initialData = {"Name":"test"};

    var viewModel = {
        deck: ko.observable(initialData),
        deckName: initialData.Name,
        save: function() {
            ko.utils.postJson(location.href, { deck: this.deck, deckName: this.deckName });
        }
    };
    ko.applyBindings(viewModel);
</script>
</code>```

On the form POST, deck will still send "test" no matter the input whilst deckName will be the corresponding input value.

What I really want is to be able to observe an object viewModel.deck and then bind its properties to inputs, but the properties don't get updated.

答:
There are several problems with what you have provided.

You've only set up a one time value setter for your second input since deck().Name is a static value (as opposed to a ko.observable or a ko.observableArray).  (To prove this add viewModel.deck({"Name":"updated test"}); to the end of your script after ko.applyBindings(viewModel);)

deckName is a one way binding - it's written during the initial applyBindings and viewModel will be updated by changes made by the user or scripts to the <input>.  However, if you make programmatic changes to the viewModel your input field will not be updated to match.  You'll want to take a look at the last part of Knockout.js' value binding documentation.

A slightly improved version:

```<code><form data-bind="submit: save">
    <input type="text" data-bind="value: deckName" />
    <input type="text" data-bind="value: deck().Name" />
    <button type="submit">Go</button>
</form>
<script type="text/javascript">
    var initialData = {"Name":"test"};

    var viewModel = {
        deck: ko.observable(initialData),
        // Set up a two way binding
        deckName: ko.observable(initialData.Name),
        // Set up a one time value setter
        save: function() {
            ko.utils.postJson(location.href, ko.toJSON(this));
            // When we save the model we post *it* back, rather than
            // serializing it by hand.
        }
    };
    ko.applyBindings(viewModel);
    viewModel.deck({"Name":"updated test"});
</script>
</code>```

An alternate version using fromJS:

```<code><form data-bind="submit: save">
    <input type="text" data-bind="value: Name" />
    <button type="submit">Go</button>
</form>
<script type="text/javascript">
    var initialData = {"Name":"test"};

    var viewModel = ko.mapping.fromJS(initialData);
    viewModel.save = function() {
        ko.utils.postJson(location.href, ko.toJSON(this));
        // When we save the model we post *it* back, rather than
        // serializing it by hand.
    }
    ko.applyBindings(viewModel);
</script>
</code>```

You'll want to look at Knockout's fromJSON and fromJS funcitons (implemented in its mapping plugin).

Body:
I want to be able to observe an object inside the view model. I have a simple example that doesn't work as expected, can anyone see the problem?

Using knockout 1.1.1, have 2 inputs as such:

<form data-bind="submit: save">
    <input type="text" data-bind="value: deckName" />
    <input type="text" data-bind="value: deck().Name" />
    <button type="submit">Go</button>
</form>

When the page loads, the inputs get the default values, but on submitting the form viewModel.deck().Name is not updated but viewModel.deckName is.

On the form POST, deck will still send "test" no matter the input whilst deckName will be the corresponding input value.

What I really want is to be able to observe an object viewModel.deck and then bind its properties to inputs, but the properties don't get updated.

Body:
There are several problems with what you have provided.

You've only set up a one time value setter for your second input since deck().Name is a static value (as opposed to a ko.observable or a ko.observableArray).  (To prove this add viewModel.deck({"Name":"updated test"}); to the end of your script after ko.applyBindings(viewModel);)

deckName is a one way binding - it's written during the initial applyBindings and viewModel will be updated by changes made by the user or scripts to the <input>.  However, if you make programmatic changes to the viewModel your input field will not be updated to match.  You'll want to take a look at the last part of Knockout.js' value binding documentation.

A slightly improved version:

<form data-bind="submit: save">
    <input type="text" data-bind="value: deckName" />
    <input type="text" data-bind="value: deck().Name" />
    <button type="submit">Go</button>
</form>
<script type="text/javascript">
    var initialData = {"Name":"test"};

    var viewModel = {
        deck: ko.observable(initialData),
        // Set up a two way binding
        deckName: ko.observable(initialData.Name),
        // Set up a one time value setter
        save: function() {
            ko.utils.postJson(location.href, ko.toJSON(this));
            // When we save the model we post *it* back, rather than
            // serializing it by hand.
        }
    };
    ko.applyBindings(viewModel);
    viewModel.deck({"Name":"updated test"});
</script>

An alternate version using fromJS:

<form data-bind="submit: save">
    <input type="text" data-bind="value: Name" />
    <button type="submit">Go</button>
</form>
<script type="text/javascript">
    var initialData = {"Name":"test"};

    var viewModel = ko.mapping.fromJS(initialData);
    viewModel.save = function() {
        ko.utils.postJson(location.href, ko.toJSON(this));
        // When we save the model we post *it* back, rather than
        // serializing it by hand.
    }
    ko.applyBindings(viewModel);
</script>

You'll want to look at Knockout's fromJSON and fromJS funcitons (implemented in its mapping plugin).


问:
Adding text files to binaries with objcopy, but objcopy complains about architecture
I've read about embedding text files (or any other resource for that matter) into binaries, and I'm doing it like so:

```<code>objcopy -I binary -O elf32-littlearm --binary-architecture arm myfile.txt myfile.txt.o
</code>```

However, unlike in the tutorial, I get the following response:

```<code>ld: unknown architecture of input file `myfile.txt' is incompatible with arm output
</code>```

The example uses i386 but this doesn't seem to be the issue either as I can't do it that way either.

Is there a way I can force objcopy to ignore the fact it's a text file and not a valid compatible binary so it just copies it byte-for-byte into my program?

答:
For data only object file (no code), you can skip binary-architecture option.

So the following should work

objcopy -I binary -O elf32-littlearm myfile.txt myfile.txt.o to generate object file.

Body:
I've read about embedding text files (or any other resource for that matter) into binaries, and I'm doing it like so:

objcopy -I binary -O elf32-littlearm --binary-architecture arm myfile.txt myfile.txt.o

However, unlike in the tutorial, I get the following response:

ld: unknown architecture of input file `myfile.txt' is incompatible with arm output

The example uses i386 but this doesn't seem to be the issue either as I can't do it that way either.

Is there a way I can force objcopy to ignore the fact it's a text file and not a valid compatible binary so it just copies it byte-for-byte into my program?


问:
Row Difference along a column in Access
I have at table with 114 different site ID and numericresult and date collected. There are multiple numericresult for each Site ID as we collect data monthly. Now I am trying to get the difference of numeric result according to respective site ID. The table is:

```<code>Site ID      CollectDate           NumericResult
1H-1          2/15/2014                 3.2
1H-1          6/22/205                  3.5
2H-4          3/16/2015                 3.0
2H-4          4/20/2014                 2.8
2H-4          2/15/2014                 3.3
1H-11         3/16/2015                 2.9
1H-11         5/12/2016                 3.4
</code>```

I have around 22000 of the data with 114 'Site ID' here.

I would like to get something as:

```<code>Site ID                 NumericResult      Diff
1H-1                           3.2          0
1H-1                           3.5          0.3
2H-4                           3.0          0
2H-4                           2.8          0.2
2H-4                           3.3          0.5
1H-11                          2.9          0
1H-11                          3.4          0.5
</code>```

For the negative value I want to use absolute of that one too.

I would appreciate any help on this.
Update: Following the site and looking over the same site given I got this:

```<code>SELECT GIS_allCL2.[Site ID], GIS_allCL2.NumericResult, GIS_allCL2.NumericResult-(SELECT TOP 1 NumericResult FROM GIS_allCL2 AS Q
WHERE GIS_allCL2.[Site ID]=Q.[Site ID]
AND Q.NumericResult < GIS_allCL2.NumericResult
ORDER BY Q.[Site ID] DESC) AS Diff

FROM GIS_allCL2
WHERE
 (SELECT TOP 1 NumericResult FROM GIS_allCL2 AS Q
WHERE GIS_allCL2.[Site ID]=Q.[Site ID] AND Q.NumericResult< GIS_allCL2.NumericResult) Is Not Null

ORDER BY GIS_allCL2.[Site ID], GIS_allCL2.NumericResult;
</code>```

Doesn't work :(

I have my table as GIS_allCL2.
more help please.

UPdate:

I have updated the table as there are numericresult for same date in muliple siteID. It is still not working.
Please help!

Update:

The query works fine with sql provided by 'June7', however at the end it throws error: AT MOST ONE RECORD CAN BE RETURNED BY THIS SUBQUERY.
I know I have 114 site ID with different dates from 2014-2017 and numericresult for the dates. SO one Site ID has multiple collectdate and some site ID may have exact same collectdate. so getting rid of error is a challenge here.
Please Help!

答:
With Allen Browne subquery basics as guide, consider:

```<code>SELECT SiteID, NumericResult, CollectDate,
Abs(NumericResult-(SELECT TOP 1 Dupe.NumericResult FROM GIS_allCL2 As Dupe WHERE Dupe.SiteID=GIS_allCL2.SiteID AND Dupe.CollectDate<GIS_allCL2.CollectDate ORDER BY Dupe.CollectDate DESC)) AS Diff
FROM GIS_allCL2 ORDER BY SiteID, CollectDate;
</code>```

Suggestion for when a SiteID has multiple same date records. Requires a unique record identifier, such as an autonumber field, here it is called ID:

```<code>SELECT SiteID, NumericResult, CollectDate,
Abs(NumericResult-(SELECT TOP 1 Dupe.NumericResult FROM GIS_allCL2 As Dupe WHERE Dupe.SiteID=GIS_allCL2.SiteID AND Format(Dupe.CollectDate, "yyyymmdd") & Format(Dupe.ID,"0000")<Format(GIS_allCL2.CollectDate,"yyyymmdd") & Format(GIS_allCL2.ID,"0000") ORDER BY Dupe.CollectDate DESC, Dupe.ID DESC)) AS Diff
FROM GIS_allCL2 ORDER BY SiteID, CollectDate, ID;
</code>```

Title: Row Difference along a column in Access

Body:
I have at table with 114 different site ID and numericresult and date collected. There are multiple numericresult for each Site ID as we collect data monthly. Now I am trying to get the difference of numeric result according to respective site ID. The table is:

Site ID      CollectDate           NumericResult
1H-1          2/15/2014                 3.2
1H-1          6/22/205                  3.5
2H-4          3/16/2015                 3.0
2H-4          4/20/2014                 2.8
2H-4          2/15/2014                 3.3
1H-11         3/16/2015                 2.9
1H-11         5/12/2016                 3.4

I have around 22000 of the data with 114 'Site ID' here.

I would like to get something as:

Site ID                 NumericResult      Diff
1H-1                           3.2          0
1H-1                           3.5          0.3
2H-4                           3.0          0
2H-4                           2.8          0.2
2H-4                           3.3          0.5
1H-11                          2.9          0
1H-11                          3.4          0.5

For the negative value I want to use absolute of that one too.

I would appreciate any help on this.
Update: Following the site and looking over the same site given I got this:

SELECT GIS_allCL2.[Site ID], GIS_allCL2.NumericResult, GIS_allCL2.NumericResult-(SELECT TOP 1 NumericResult FROM GIS_allCL2 AS Q
WHERE GIS_allCL2.[Site ID]=Q.[Site ID]
AND Q.NumericResult < GIS_allCL2.NumericResult
ORDER BY Q.[Site ID] DESC) AS Diff

FROM GIS_allCL2
WHERE
 (SELECT TOP 1 NumericResult FROM GIS_allCL2 AS Q
WHERE GIS_allCL2.[Site ID]=Q.[Site ID] AND Q.NumericResult< GIS_allCL2.NumericResult) Is Not Null

ORDER BY GIS_allCL2.[Site ID], GIS_allCL2.NumericResult;

Doesn't work :(

I have my table as GIS_allCL2.
more help please.

UPdate:

I have updated the table as there are numericresult for same date in muliple siteID. It is still not working.
Please help!

Update:

The query works fine with sql provided by 'June7', however at the end it throws error: AT MOST ONE RECORD CAN BE RETURNED BY THIS SUBQUERY.
I know I have 114 site ID with different dates from 2014-2017 and numericresult for the dates. SO one Site ID has multiple collectdate and some site ID may have exact same collectdate. so getting rid of error is a challenge here.
Please Help!

Body:
With Allen Browne subquery basics as guide, consider:

SELECT SiteID, NumericResult, CollectDate,
Abs(NumericResult-(SELECT TOP 1 Dupe.NumericResult FROM GIS_allCL2 As Dupe WHERE Dupe.SiteID=GIS_allCL2.SiteID AND Dupe.CollectDate<GIS_allCL2.CollectDate ORDER BY Dupe.CollectDate DESC)) AS Diff
FROM GIS_allCL2 ORDER BY SiteID, CollectDate;

Suggestion for when a SiteID has multiple same date records. Requires a unique record identifier, such as an autonumber field, here it is called ID:

SELECT SiteID, NumericResult, CollectDate,
Abs(NumericResult-(SELECT TOP 1 Dupe.NumericResult FROM GIS_allCL2 As Dupe WHERE Dupe.SiteID=GIS_allCL2.SiteID AND Format(Dupe.CollectDate, "yyyymmdd") & Format(Dupe.ID,"0000")<Format(GIS_allCL2.CollectDate,"yyyymmdd") & Format(GIS_allCL2.ID,"0000") ORDER BY Dupe.CollectDate DESC, Dupe.ID DESC)) AS Diff
FROM GIS_allCL2 ORDER BY SiteID, CollectDate, ID;


问:
Why UDP hole punching does not work for public IP address?
There are two Groovy sub programs below sending messages to each other via plain UDP sockets. They does receive the messages successfully when they are sent to 127.0.0.1. But the messages aren't received when sending them to the public IP address (the machine is behind NAT).

Why the hole is not punched? And how to fix that?

I tried querying a public STUN server via a Java library earlier but it responded with the same public IP address to me, so I use wtfismyip.com here.

```<code>class GroovyTest {

static String PUBLIC_IP = new URL('https://wtfismyip.com/text').text.trim()
//static String PUBLIC_IP = '127.0.0.1' // works fine

static void main(String[] args) {
    runInstance(11111, 22222)
    runInstance(22222, 11111)
}

static void runInstance(int thisPort, int anotherPort) {
    def socket = new DatagramSocket(thisPort)
    Thread.start {
        // message listener
        byte[] buf = new byte[1024]
        while (true) {
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);
            InetAddress remoteAddr = packet.getAddress();
            int remotePort = packet.getPort();
            String sentence = new String(packet.getData(), 0, packet.length);
            println("server-$thisPort: received [$sentence] from ${remoteAddr.hostAddress}:${remotePort}")
        }
    }
    Thread.start {
        // message sender
        while (true) {
            println("client-$thisPort: sending to ${PUBLIC_IP}:${anotherPort}...")
            byte[] buf = ("Hello " + System.currentTimeMillis()).bytes
            DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(PUBLIC_IP), anotherPort)
            socket.send(packet)
            Thread.sleep(2000)
        }
    }
}

}
</code>```

答: Your problem stems from the fact that the IP address returned by wtfismyip is the IP address of the router on your network, which is not assigned to your computer.  When you try and send a datagram to your router's public IP you'll probably get and ICMP Destination Unreachable error message from your router.    If you need this behavior, your router may have some port forwarding capabilities that can forward inbound UDP traffic to your local IP address.</p>

Body:
There are two Groovy sub programs below sending messages to each other via plain UDP sockets. They does receive the messages successfully when they are sent to 127.0.0.1. But the messages aren't received when sending them to the public IP address (the machine is behind NAT).

Why the hole is not punched? And how to fix that?

I tried querying a public STUN server via a Java library earlier but it responded with the same public IP address to me, so I use wtfismyip.com here.

class GroovyTest {

static String PUBLIC_IP = new URL('https://wtfismyip.com/text').text.trim()
//static String PUBLIC_IP = '127.0.0.1' // works fine

static void main(String[] args) {
    runInstance(11111, 22222)
    runInstance(22222, 11111)
}

static void runInstance(int thisPort, int anotherPort) {
    def socket = new DatagramSocket(thisPort)
    Thread.start {
        // message listener
        byte[] buf = new byte[1024]
        while (true) {
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);
            InetAddress remoteAddr = packet.getAddress();
            int remotePort = packet.getPort();
            String sentence = new String(packet.getData(), 0, packet.length);
            println("server-$thisPort: received [$sentence] from ${remoteAddr.hostAddress}:${remotePort}")
        }
    }
    Thread.start {
        // message sender
        while (true) {
            println("client-$thisPort: sending to ${PUBLIC_IP}:${anotherPort}...")
            byte[] buf = ("Hello " + System.currentTimeMillis()).bytes
            DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(PUBLIC_IP), anotherPort)
            socket.send(packet)
            Thread.sleep(2000)
        }
    }
}

}


问:
individual simple_form radio button
I am using SimpleForm 3.2.1 with Rails 4.  I am trying to convert a rails form into a simple_form.  Here is the code that works for radio buttons with the regular rails form:

```<code>  <ul class="list-radios list-multiplier">
    <% @organization_plans.each_with_index do |plan, index| %>

      <li>
        <div class="radio custom-radio">
          <%= f.radio_button :plan_id, plan.id, id: "field-rad#{index}", data: {price: plan.total_price} %>

          <label class="form-label" for='field-rad<%= index %>'>
            <span></span>

            <%= plan.description %>
          </label>
        </div><!-- /.radio -->
      </li>
    <% end %>
  </ul><!-- /.list-radios -->
</code>```

I have tried converting it to SimpleForm with the following code:

```<code>  <ul class="list-radios list-multiplier">
    <% @organization_plans.each_with_index do |plan, index| %>

      <li>
        <div class="radio custom-radio">
          <%= f.input :plan_id, value: plan.id, input_html: {id: "field-rad#{index}"}, data: {price: plan.total_price}, label: false, as: :radio %>

          <label class="form-label" for='field-rad<%= index %>'>
            <span></span>

            <%= plan.description %>
          </label>
        </div><!-- /.radio -->
      </li>
    <% end %>
  </ul><!-- /.list-radios -->
</code>```

However, when I open the page in the browser I get the error:

```<code>No input found for radio
</code>```

How do I get this form to start working with simple_form?

答:
There's nothing wrong with using the regular rails helpers. You can nest them inside the input if you'd like consistent wrappers. It can look something like

```<code>= f.input :plan_id, label: false do
  ul
    - @organization_plans.each do |plan|
      li
        = f.radio_button :plan_id, plan.id
        = f.label :plan_id, plan.description, value: plan.id
</code>```

Of course, you may also use the collection if you don't need too much customization

```<code>= f.input :plan_id, collection: @organization_plans.pluck(:id, :description), as: :radio_buttons, label: false
</code>```

Title: individual simple_form radio button

Body:
I am using SimpleForm 3.2.1 with Rails 4.  I am trying to convert a rails form into a simple_form.  Here is the code that works for radio buttons with the regular rails form:

    <% @organization_plans.each_with_index do |plan, index| %>

          <%= f.radio_button :plan_id, plan.id, id: "field-rad#{index}", data: {price: plan.total_price} %>

          <label class="form-label" for='field-rad<%= index %>'>

            <%= plan.description %>

    <% end %>

I have tried converting it to SimpleForm with the following code:

    <% @organization_plans.each_with_index do |plan, index| %>

          <%= f.input :plan_id, value: plan.id, input_html: {id: "field-rad#{index}"}, data: {price: plan.total_price}, label: false, as: :radio %>

          <label class="form-label" for='field-rad<%= index %>'>

            <%= plan.description %>

    <% end %>

However, when I open the page in the browser I get the error:

No input found for radio

How do I get this form to start working with simple_form?

Body:
There's nothing wrong with using the regular rails helpers. You can nest them inside the input if you'd like consistent wrappers. It can look something like

= f.input :plan_id, label: false do
  ul
    - @organization_plans.each do |plan|
      li
        = f.radio_button :plan_id, plan.id
        = f.label :plan_id, plan.description, value: plan.id

Of course, you may also use the collection if you don't need too much customization

= f.input :plan_id, collection: @organization_plans.pluck(:id, :description), as: :radio_buttons, label: false