问:
How can I pass encoded values by `Link` using react-router?
Sorry to disturb, guys. I'm so new to react and react-router and I've been struggling for few days already.

Actually I am trying to pass some values before jumping to a new page (using Link attribute target="_blank") and in the new page, I want to use these values to communicate with the server and when the data from the server comes, the new page will load its content.

the route path is something like this

```<code><Route path="/root/the_page" component={the_component} />
</code>```

and the link will be like this:

```<code><Link to="/root/the_page" target="_blank" />
</code>```

What I have checked is this discussion about using a function to pass the value, but I really cannot re-produce it. As for the query-params, I cannot retrieve the query in this.props.location even I set the link as follows:

```<code><Link to={{pathname:"/root/the_page", query: {the_key: the_value}}} target="_blank" />
</code>```

Any advice will be helpful.

Thank you in advance!

答:
I don't see any reason why you would want to use React-Router to navigate to an external page. React-Router is meant for navigation in single-page applications but opening a link with target="_blank" would mean leaving that single-page app and opening new window/tab.

As such, why not just use a regular anchor tag? That's perfectly viable for external navigation.

```<code><a href="/root/the_page?the_key=the_value" target="_blank">Click me</a>
</code>```

Obviously, your history object won't be carried over because you are opening a new window/tab - so you won't be able to go "back" or do any of that.

Body:
Sorry to disturb, guys. I'm so new to react and react-router and I've been struggling for few days already.

Actually I am trying to pass some values before jumping to a new page (using Link attribute target="_blank") and in the new page, I want to use these values to communicate with the server and when the data from the server comes, the new page will load its content.

the route path is something like this

<Route path="/root/the_page" component={the_component} />

and the link will be like this:

<Link to="/root/the_page" target="_blank" />

What I have checked is this discussion about using a function to pass the value, but I really cannot re-produce it. As for the query-params, I cannot retrieve the query in this.props.location even I set the link as follows:

<Link to={{pathname:"/root/the_page", query: {the_key: the_value}}} target="_blank" />

Any advice will be helpful.

Thank you in advance!

Body:
I don't see any reason why you would want to use React-Router to navigate to an external page. React-Router is meant for navigation in single-page applications but opening a link with target="_blank" would mean leaving that single-page app and opening new window/tab.

As such, why not just use a regular anchor tag? That's perfectly viable for external navigation.

<a href="/root/the_page?the_key=the_value" target="_blank">Click me</a>

Obviously, your history object won't be carried over because you are opening a new window/tab - so you won't be able to go "back" or do any of that.


来源: stackexchange

问:
React Native: can't call a parent method from child
I have this function in parent component, and I am trying to call this method/function in child , like so:

```<code>buttonPressed = () => {
  console.log('button pressed')
}

<childComp ref={ref => this.feedback = ref}
           onPress={this.buttonPressed}
/>
</code>```

in child:

```<code><Animated.View>
  ...   // other views
  <View>
    <TouchableOpacity onPress={this.props.buttonPressed}> // calling here
     ...
    </TouchableOpacity>

  </View>
</Animated.View>
</code>```

No matter what I tried , it didn't work.

答:
you are passing onPress prop to child and calling buttonPressed in child. it should be like this :

<Animated.View>
  ...   // other views
  <View>
    <TouchableOpacity onPress={this.props.onPress}> // calling here
     ...
    </TouchableOpacity>

  </View>
</Animated.View>```

ContentLicense: CC BY-SA 3.0

Body:
I have this function in parent component, and I am trying to call this method/function in child , like so:

buttonPressed = () => {
  console.log('button pressed')
}

<childComp ref={ref => this.feedback = ref}
           onPress={this.buttonPressed}
/>

in child:

<Animated.View>
  ...   // other views
  <View>
    <TouchableOpacity onPress={this.props.buttonPressed}> // calling here
     ...
    </TouchableOpacity>

  </View>
</Animated.View>

No matter what I tried , it didn't work.


问:
Vertically align the text of each cell
I would like to know if there exists a technique to make the text set at the same line or at the same level because what I did is to add a line-height for my two first blocks but if I add a line-height for the others there is still a difference. It creates a weird look because my titles are not the same in each cell.

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();

    $(this).closest('table').find('[class^="cat"]').toggle();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  color: #002642;
}

.center {
  text-align: center;
}

.toggler,
.cat1 {
  font-family: 'Varela Round';
  color: white;
}

td {
  display: block;
  width: auto;
  border: 1px dotted #c4a77d;
  background-color: #c4a77d;
  color: white;
  margin-bottom: 10px;
}

@media only screen and (min-width: 70em) {
  td {
    display: table-cell;
    border: 1px dotted #c4a77d;
    background-color: #c4a77d;
    color: white;
    margin-bottom: 0px;
  }
}

p {
  font-family: 'Varela Round';
  font-weight: bold;
  text-align: center;
}</code>```

SOCIÉTÉS: 230

            + En savoir plus

            Part CAC 40 : 90

            Part Filiales +100M€: 120

CONTACTS : 16 700

            + En savoir plus

            Part CAC 40 : 10 000

            Part Filiales +100M€: 6 700

            % contacts IT: 21%

EMAIL NOMINATIFS: 16 700

OPT OUT: 3%

LIGNES DIRECTES: 35%

```

答:
All you need is vertical-align:baseline on the table cells. td elements have vertical-align:middle by default.

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();

    $(this).closest('table').find('[class^="cat"]').toggle();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  color: #002642;
}

.center {
  text-align: center;
}

.toggler,
.cat1 {
  font-family: 'Varela Round';
  color: white;
}

td {
  display: block;
  width: auto;
  border: 1px dotted #c4a77d;
  background-color: #c4a77d;
  color: white;
  margin-bottom: 10px;
  vertical-align:baseline;
}

@media only screen and (min-width: 70em) {
  td {
    display: table-cell;
    border: 1px dotted #c4a77d;
    background-color: #c4a77d;
    color: white;
    margin-bottom: 0px;
  }
}

p {
  font-family: 'Varela Round';
  font-weight: bold;
  text-align: center;
}</code>```

SOCIÉTÉS: 230

            + En savoir plus

            Part CAC 40 : 90

            Part Filiales +100M€: 120

CONTACTS : 16 700

            + En savoir plus

            Part CAC 40 : 10 000

            Part Filiales +100M€: 6 700

            % contacts IT: 21%

EMAIL NOMINATIFS: 16 700

OPT OUT: 3%

LIGNES DIRECTES: 35%

```

Title: Vertically align the text of each cell

Body:
I would like to know if there exists a technique to make the text set at the same line or at the same level because what I did is to add a line-height for my two first blocks but if I add a line-height for the others there is still a difference. It creates a weird look because my titles are not the same in each cell.

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();

    $(this).closest('table').find('[class^="cat"]').toggle();
  });
});

a {
  color: #002642;
}

.center {
  text-align: center;
}

.toggler,
.cat1 {
  font-family: 'Varela Round';
  color: white;
}

td {
  display: block;
  width: auto;
  border: 1px dotted #c4a77d;
  background-color: #c4a77d;
  color: white;
  margin-bottom: 10px;
}

@media only screen and (min-width: 70em) {
  td {
    display: table-cell;
    border: 1px dotted #c4a77d;
    background-color: #c4a77d;
    color: white;
    margin-bottom: 0px;
  }
}

p {
  font-family: 'Varela Round';
  font-weight: bold;
  text-align: center;
}

SOCIÉTÉS: 230

            + En savoir plus

            Part CAC 40 : 90

            Part Filiales +100M€: 120

CONTACTS : 16 700

            + En savoir plus

            Part CAC 40 : 10 000

            Part Filiales +100M€: 6 700

            % contacts IT: 21%

EMAIL NOMINATIFS: 16 700

OPT OUT: 3%

LIGNES DIRECTES: 35%

Body:
All you need is vertical-align:baseline on the table cells. td elements have vertical-align:middle by default.

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();

    $(this).closest('table').find('[class^="cat"]').toggle();
  });
});

a {
  color: #002642;
}

.center {
  text-align: center;
}

.toggler,
.cat1 {
  font-family: 'Varela Round';
  color: white;
}

td {
  display: block;
  width: auto;
  border: 1px dotted #c4a77d;
  background-color: #c4a77d;
  color: white;
  margin-bottom: 10px;
  vertical-align:baseline;
}

@media only screen and (min-width: 70em) {
  td {
    display: table-cell;
    border: 1px dotted #c4a77d;
    background-color: #c4a77d;
    color: white;
    margin-bottom: 0px;
  }
}

p {
  font-family: 'Varela Round';
  font-weight: bold;
  text-align: center;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="table-layout: fixed; width:100%" width="100%" cellpadding="0" cellspacing="0">
  <tbody>
    <tr>
      <td>
        <table width="100%" class="center">
          <tr>
            <td style="line-height:100px;">
              <p style="vertical-align:middle;">SOCIÉTÉS: 230</p>
            </td>
          </tr>
          <tr>
            <td><a href="#" class="toggler" data-prod-cat="1">+ En savoir plus</a></td>
          </tr>
          <tr class="cat1" style="display:none">
            <td>Part CAC 40 : 90</td>
          </tr>
          <tr class="cat1" style="display:none">
            <td>Part Filiales +100M€: 120</td>
          </tr>
        </table>
      </td>
      <td>
        <table width="100%" class="center">
          <tr>
            <td style="line-height:100px;">
              <p style="vertical-align:middle;">CONTACTS : 16 700</p>
            </td>
          </tr>
          <tr>
            <td><a href="#" class="toggler" data-prod-cat="1">+ En savoir plus</a></td>
          </tr>
          <tr class="cat1" style="display:none">
            <td>Part CAC 40 : 10 000 </td>
          </tr>
          <tr class="cat1" style="display:none">
            <td>Part Filiales +100M€: 6 700</td>
          </tr>
          <tr class="cat1" style="display:none">
            <td>% contacts IT: 21%</td>
          </tr>
        </table>
      </td>
      <td>
        <p>EMAIL NOMINATIFS: 16 700</p>
      </td>
      <td>
        <p>OPT OUT: 3%</p>
      </td>
      <td>
        <p>LIGNES DIRECTES: 35%</p>
      </td>
    </tr>
  </tbody>
</table>


问:
Sharing results of asynchronous call using promises
I am new to JavaScript promises and would like to know if this is the common/idiomatic way of doing sharing results asynchronously in JavaScript/Node.js.

I have a method, say calc, that computes a list of items asynchronously. I only want the result to be calculated once, and other cals either get the already calculated results or wait until the result is calculated. I've come up with the following design (a minimal example to demonstrate it).

```<code>let result: Promise<number[]>;

async function calc(): Promise<number[]> {
    if (result) {
        return result;
    }

    result = new Promise<number[]>(async (resolve, reject) => {
        await delay(5000);
        resolve([1, 2, 3, 4, 5]);
    });
    return result;
}

async function delay(time: number) {
    return new Promise<void>((resolve, reject) => setTimeout(resolve, time));
}
</code>```

Is there any flaws with this design? Is the calc method always asynchronous? i.e., the results run in a different stack than the caller?

答:
Is the calc method always asynchronous?

Consuming the result from the promise calc returns will always be asynchronous (which is probably what you really mean). This is guaranteed by the specification: then and catch callbacks are always called asynchronously, whether the promise is already settled or not.

Note that if you're returning a promise (which you are in all code paths in calc) and not using await in the immediate body of calc (which you aren't), you don't need to declare calc as async. Doing so conceptually adds a layer of promises (which is largely harmless, but...).

Is there any flaws with this design?

A couple of minor ones. delay is, of course, just standing in for the real work that you're going to do. Using await delay(); in your async promise executor callback without a try/catch means you will miss it if the promise from delay rejects. You want to ensure you handle rejection (perhaps with a try/catch in the executor callback, or by not using await in it).

Related to that, the code is also falling prey to the Promise creation antipattern. Since delay provides a promise, here's no need for new Promise in calc. Just use the one from delay.

So calc could just look like this:

```<code>function calc(): Promise<number[]> {
    if (result) {
        return result;
    }

    return result = delay(5000).then(() => [1, 2, 3, 4, 5]);
}
</code>```

Since you're explicitly handling the promise, I probably wouldn't use async on it.

Live Demo (just for fun; I've made the delay 800ms instead of 5000ms):

let result;
function calc() {
    if (result) {
        return result;
    }

    return result = delay(800).then(() => [1, 2, 3, 4, 5]);
}
function delay(time) {
  return new Promise(resolve => {
    setTimeout(resolve, time);
  });
}

console.log("A");
calc().then(() => { console.log("C"); });
console.log("B");
calc().then(() => { console.log("D"); });
setTimeout(() => {
  console.log("E");
  calc().then(() => { console.log("G"); });
  console.log("F");
}, 1000);```

As you can see, it outputs A B, waits 800ms, outputs C D, waits a further ~200ms, and then outputs E F G, proving that consuming calc's promise is always asynchronous.

Body:
I am new to JavaScript promises and would like to know if this is the common/idiomatic way of doing sharing results asynchronously in JavaScript/Node.js.

I have a method, say calc, that computes a list of items asynchronously. I only want the result to be calculated once, and other cals either get the already calculated results or wait until the result is calculated. I've come up with the following design (a minimal example to demonstrate it).

let result: Promise<number[]>;

async function calc(): Promise<number[]> {
    if (result) {
        return result;
    }

    result = new Promise<number[]>(async (resolve, reject) => {
        await delay(5000);
        resolve([1, 2, 3, 4, 5]);
    });
    return result;
}

async function delay(time: number) {
    return new Promise<void>((resolve, reject) => setTimeout(resolve, time));
}

Is there any flaws with this design? Is the calc method always asynchronous? i.e., the results run in a different stack than the caller?

Body:
Is the calc method always asynchronous?

Consuming the result from the promise calc returns will always be asynchronous (which is probably what you really mean). This is guaranteed by the specification: then and catch callbacks are always called asynchronously, whether the promise is already settled or not.

Note that if you're returning a promise (which you are in all code paths in calc) and not using await in the immediate body of calc (which you aren't), you don't need to declare calc as async. Doing so conceptually adds a layer of promises (which is largely harmless, but...).

Is there any flaws with this design?

A couple of minor ones. delay is, of course, just standing in for the real work that you're going to do. Using await delay(); in your async promise executor callback without a try/catch means you will miss it if the promise from delay rejects. You want to ensure you handle rejection (perhaps with a try/catch in the executor callback, or by not using await in it).

Related to that, the code is also falling prey to the Promise creation antipattern. Since delay provides a promise, here's no need for new Promise in calc. Just use the one from delay.

So calc could just look like this:

function calc(): Promise<number[]> {
    if (result) {
        return result;
    }

    return result = delay(5000).then(() => [1, 2, 3, 4, 5]);
}

Since you're explicitly handling the promise, I probably wouldn't use async on it.

Live Demo (just for fun; I've made the delay 800ms instead of 5000ms):

let result;
function calc() {
    if (result) {
        return result;
    }

    return result = delay(800).then(() => [1, 2, 3, 4, 5]);
}
function delay(time) {
  return new Promise(resolve => {
    setTimeout(resolve, time);
  });
}

console.log("A");
calc().then(() => { console.log("C"); });
console.log("B");
calc().then(() => { console.log("D"); });
setTimeout(() => {
  console.log("E");
  calc().then(() => { console.log("G"); });
  console.log("F");
}, 1000);

As you can see, it outputs A B, waits 800ms, outputs C D, waits a further ~200ms, and then outputs E F G, proving that consuming calc's promise is always asynchronous.


问:
How to select an item in UiPath that starts with a string
I'm using UiPath to select an item from a combobox in a windows rich client application.  The items are formatted in the list as "Code - Description".  I'd like to select the item by code only, rather than needing to know the description also.

As a UIPath newbie, thoughts on the best way to achieve this?

答:
Just use a wildcard in selector. Given that Code is unique i.e 0001 and attribute name equals to id:

```<code><id = 0001* />
</code>```

Additionally, this link should be helpfull:

https://studio.uipath.com/v2017.1/docs/selectors-with-wildcards

Body:
Just use a wildcard in selector. Given that Code is unique i.e 0001 and attribute name equals to id:

<id = 0001* />

Additionally, this link should be helpfull:

https://studio.uipath.com/v2017.1/docs/selectors-with-wildcards


问:
How to upgrade Magento 1.6 to magento 1.9
I am having my current website running on Magento 1.6. I am looking to upgrade it to 1.9 but don't know how to start. I went through the below articles but was not able to move ahead.

http://www.customerparadigm.com/magento-development/upgrade/how-to-upgrade-magento/

http://www.crucialwebhost.com/kb/installing-magento-via-ssh/

Can anyone please help me from ground level. I need to know it from scratch. I wanted to replace the below code but was not able to locate the file in my database. I am currently using filezilla to access my server file. My database is maintained by a different company called nexcess.

```<code>wget http://www.magentocommerce.com/index.php/getmagento/1.9.1.0/magento-1.9.1.0.tar.gz
wget http://www.magentocommerce.com/downloads/assets/1.9.0.0/magento-sample-data-1.9.0.0.tar.gz
tar xvf magento-1.9.1.0.tar.gz
tar xvf magento-sample-data-1.9.0.0.tar.gz
mv magento-sample-data-1.9.0.0/media/* magento/media/
mv magento-sample-data-1.9.0.0/magento_sample_data_for_1.9.0.0.sql magento/data.sql
mv magento/* magento/.htaccess .
mysql -h DBHOST -u DBUSER -pDBPASS DBNAME < data.sql
rm -rf *.sample magento/ magento-sample-data-1.9.0.0/
rm -rf magento-1.9.1.0.tar.gz magento-sample-data-1.9.0.0.tar.gz data.sql
</code>```

Please help me how to go through with it

答:
Use The  Below terminal commands</p>

```<code>chmod 550 mage

./mage mage-setup .

./mage config-set preferred_state stable

./mage sync

./mage install http://connect20.magentocommerce.com/community Mage_All_Latest --force

php shell/indexer.php reindexall
rm -rf downloader/.cache/ var/cache/
</code>```

Body:
I am having my current website running on Magento 1.6. I am looking to upgrade it to 1.9 but don't know how to start. I went through the below articles but was not able to move ahead.

http://www.customerparadigm.com/magento-development/upgrade/how-to-upgrade-magento/

http://www.crucialwebhost.com/kb/installing-magento-via-ssh/

Can anyone please help me from ground level. I need to know it from scratch. I wanted to replace the below code but was not able to locate the file in my database. I am currently using filezilla to access my server file. My database is maintained by a different company called nexcess.

wget http://www.magentocommerce.com/index.php/getmagento/1.9.1.0/magento-1.9.1.0.tar.gz
wget http://www.magentocommerce.com/downloads/assets/1.9.0.0/magento-sample-data-1.9.0.0.tar.gz
tar xvf magento-1.9.1.0.tar.gz
tar xvf magento-sample-data-1.9.0.0.tar.gz
mv magento-sample-data-1.9.0.0/media/* magento/media/
mv magento-sample-data-1.9.0.0/magento_sample_data_for_1.9.0.0.sql magento/data.sql
mv magento/* magento/.htaccess .
mysql -h DBHOST -u DBUSER -pDBPASS DBNAME < data.sql
rm -rf *.sample magento/ magento-sample-data-1.9.0.0/
rm -rf magento-1.9.1.0.tar.gz magento-sample-data-1.9.0.0.tar.gz data.sql

Please help me how to go through with it

Body:
Use The  Below terminal commands

chmod 550 mage

./mage mage-setup .

./mage config-set preferred_state stable

./mage sync

./mage install http://connect20.magentocommerce.com/community Mage_All_Latest --force

php shell/indexer.php reindexall
rm -rf downloader/.cache/ var/cache/


问:
Authorization issue in netsuite using oauth
I am working on Netsuite and I'm new to it, so I need help. After creating roles and assigning a user to that specific role, I want to assign them to an application created using the integration record. When I wanted to create an access token, after selecting the application in the application name drop down, I am not finding any users or roles in the user drop down box and the role drop down box:

This is where I am facing the problem. So I need a solution to select users in the drop down box.

答:
This link tells you all you need to know about setting up TBA and the correct basic permissions needed:
Token Based Authentication

Your user needs to have a role assigned to it with the following basic permissions:

User Access Token: Full

Access Token Management: Full

Web Services: Full

Once this role has been assigned to your user, the user will be available for selection when creating a token.


问:
How do I access external hosts from within my cluster?
I have a container with a specialized application that needs to connect to hosts, via DNS lookup, outside of the Kubernetes cluster. When I run the container standalone in Docker, things work fine.

When I run the container using Kubernetes though, I'm getting "host not found" errors. If I run bash inside the container, and do a "ping myhost.mydomain.com
", it fail to resolve myhost.mydomain.com.

Reading through the Kubernetes pages, it appears all I need to do is this add this service:

apiVersion: v1
kind: Service
metadata:
  name: myhost
spec:
  type: ExternalName
  externalName: myhost.mydomain.com

But, this doesn't seem to work; the container still can't ping myhost or myhost.mydomain.com. Is there something else I need to add? Is there some way to have a "fallback" DNS so that any external hostname can be resolved? It doesn't seem like this should be this difficult...

Thanks,
John

答: Try to add dnsPolicy: ClusterFirstWithHostNet to the spec.


问:
Angular Material + Angular Universal
I'm trying to render Angular app with Angular Universal on Nodejs + Expressjs on server side. After building app via ng build --prod --app 1 and compiling with webpack and run app via node server.js. When I open app in browser get error Current document does not have a doctype. This may cause some Angular Material components not to behave as expected.

```<code>// Load zone.js for the server.
require('zone.js/dist/zone-node');
require('reflect-metadata');

import * as express from 'express';
import { enableProdMode, ValueProvider } from '@angular/core';
import { renderModuleFactory } from '@angular/platform-server';
import { join } from 'path';
import { readFileSync } from 'fs';
const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist-
server/main.bundle');

const template = readFileSync('./src/index.html', { encoding: 'utf8' });

const app = express();

app.engine('html', (_, options, callback) => {
  const opts = {
    document: template,
    url: options.req.url,
    extraProviders: [
      <ValueProvider>{
        provide: 'REQUEST',
        useValue: options.req,
      },
      provideModuleMap(LAZY_MODULE_MAP)
    ]
 };

renderModuleFactory(AppServerModuleNgFactory, opts)
  .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src');

app.get('*.*', express.static(join(__dirname, 'dist-server')));

app.get('*', (req, res) => {
  res.render('index', {req});
});

app.listen(5000, () => {
  console.log('listening on http://localhost:5000!');
});
</code>```

Looks like this bug related to @angular/material and will be fixed in the future, but is there any workaround?

答:
Currently Angular Material 2 are not supported by Angular Universal.
 https://github.com/angular/universal#in-progress</p>

Title: Angular Material + Angular Universal

Body:
I'm trying to render Angular app with Angular Universal on Nodejs + Expressjs on server side. After building app via ng build --prod --app 1 and compiling with webpack and run app via node server.js. When I open app in browser get error Current document does not have a doctype. This may cause some Angular Material components not to behave as expected.

// Load zone.js for the server.
require('zone.js/dist/zone-node');
require('reflect-metadata');

import * as express from 'express';
import { enableProdMode, ValueProvider } from '@angular/core';
import { renderModuleFactory } from '@angular/platform-server';
import { join } from 'path';
import { readFileSync } from 'fs';
const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist-
server/main.bundle');

const template = readFileSync('./src/index.html', { encoding: 'utf8' });

const app = express();

app.engine('html', (_, options, callback) => {
  const opts = {
    document: template,
    url: options.req.url,
    extraProviders: [
      <ValueProvider>{
        provide: 'REQUEST',
        useValue: options.req,
      },
      provideModuleMap(LAZY_MODULE_MAP)
    ]
 };

renderModuleFactory(AppServerModuleNgFactory, opts)
  .then(html => callback(null, html));
});

app.set('view engine', 'html');
app.set('views', 'src');

app.get('*.*', express.static(join(__dirname, 'dist-server')));

app.get('*', (req, res) => {
  res.render('index', {req});
});

app.listen(5000, () => {
  console.log('listening on http://localhost:5000!');
});

Looks like this bug related to @angular/material and will be fixed in the future, but is there any workaround?


问:
how do I add openlayers as a library to my oracle jet project?
I created an oracle jet project using ojet create, build, serve commands. Alternatively, I have also created the project using NetBeans 8.2 IDE. I am not able to add open layers as a library. I want to create a web application which would consist of maps.</p>

答:
My main.js file looks like this..</p>

```<code>/**
 * Copyright (c) 2014, 2017, Oracle and/or its affiliates.
 * The Universal Permissive License (UPL), Version 1.0
 */
'use strict';

/**
 * Example of Require.js boostrap javascript
 */

requirejs.config(
{
  baseUrl: 'js',

  // Path mappings for the logical module names
  // Update the main-release-paths.json for release mode when updating the mappings
  paths:
  //injector:mainReleasePaths
  {
    'knockout': 'libs/knockout/knockout-3.4.0.debug',
    'jquery': 'libs/jquery/jquery-3.1.1',
    'jqueryui-amd': 'libs/jquery/jqueryui-amd-1.12.0',
    'promise': 'libs/es6-promise/es6-promise',
    'hammerjs': 'libs/hammer/hammer-2.0.8',
    'ojdnd': 'libs/dnd-polyfill/dnd-polyfill-1.0.0',
    'ojs': 'libs/oj/v3.2.0/debug',
    'ojL10n': 'libs/oj/v3.2.0/ojL10n',
    'ojtranslations': 'libs/oj/v3.2.0/resources',
    'text': 'libs/require/text',
    'signals': 'libs/js-signals/signals',
    'customElements': 'libs/webcomponents/CustomElements',
    'proj4': 'libs/proj4js/dist/proj4-src',
    'css': 'libs/require-css/css',
  }
  //endinjector
  ,
  // Shim configurations for modules that do not expose AMD
  shim:
  {
    'jquery':
    {
      exports: ['jQuery', '$']
    }
  }
}
);

/**
 * A top-level require call executed by the Application.
 * Although 'ojcore' and 'knockout' would be loaded in any case (they are specified as dependencies
 * by the modules themselves), we are listing them explicitly to get the references to the 'oj' and 'ko'
 * objects in the callback
 */
require(['ojs/ojcore', 'knockout', 'appController', 'ojs/ojknockout',
  'ojs/ojmodule', 'ojs/ojrouter', 'ojs/ojnavigationlist', 'ojs/ojbutton', 'ojs/ojtoolbar','libs/ol'],
  function (oj, ko, app) { // this callback gets executed when all required modules are loaded

    $(function() {

      function init() {
        oj.Router.sync().then(
          function () {
            // Bind your ViewModel for the content of the whole page body.
            ko.applyBindings(app, document.getElementById('globalBody'));
          },
          function (error) {
            oj.Logger.error('Error in root start: ' + error.message);
          }
        );
      }

      // If running in a hybrid (e.g. Cordova) environment, we need to wait for the deviceready
      // event before executing any code that might interact with Cordova APIs or plugins.
      if ($(document.body).hasClass('oj-hybrid')) {
        document.addEventListener("deviceready", init);
      } else {
        init();
      }

    });

  }
);
</code>```

Body:
My main.js file looks like this..

/**
 * Copyright (c) 2014, 2017, Oracle and/or its affiliates.
 * The Universal Permissive License (UPL), Version 1.0
 */
'use strict';

/**
 * Example of Require.js boostrap javascript
 */

requirejs.config(
{
  baseUrl: 'js',

  // Path mappings for the logical module names
  // Update the main-release-paths.json for release mode when updating the mappings
  paths:
  //injector:mainReleasePaths
  {
    'knockout': 'libs/knockout/knockout-3.4.0.debug',
    'jquery': 'libs/jquery/jquery-3.1.1',
    'jqueryui-amd': 'libs/jquery/jqueryui-amd-1.12.0',
    'promise': 'libs/es6-promise/es6-promise',
    'hammerjs': 'libs/hammer/hammer-2.0.8',
    'ojdnd': 'libs/dnd-polyfill/dnd-polyfill-1.0.0',
    'ojs': 'libs/oj/v3.2.0/debug',
    'ojL10n': 'libs/oj/v3.2.0/ojL10n',
    'ojtranslations': 'libs/oj/v3.2.0/resources',
    'text': 'libs/require/text',
    'signals': 'libs/js-signals/signals',
    'customElements': 'libs/webcomponents/CustomElements',
    'proj4': 'libs/proj4js/dist/proj4-src',
    'css': 'libs/require-css/css',
  }
  //endinjector
  ,
  // Shim configurations for modules that do not expose AMD
  shim:
  {
    'jquery':
    {
      exports: ['jQuery', '$']
    }
  }
}
);

/**
 * A top-level require call executed by the Application.
 * Although 'ojcore' and 'knockout' would be loaded in any case (they are specified as dependencies
 * by the modules themselves), we are listing them explicitly to get the references to the 'oj' and 'ko'
 * objects in the callback
 */
require(['ojs/ojcore', 'knockout', 'appController', 'ojs/ojknockout',
  'ojs/ojmodule', 'ojs/ojrouter', 'ojs/ojnavigationlist', 'ojs/ojbutton', 'ojs/ojtoolbar','libs/ol'],
  function (oj, ko, app) { // this callback gets executed when all required modules are loaded

    $(function() {

      function init() {
        oj.Router.sync().then(
          function () {
            // Bind your ViewModel for the content of the whole page body.
            ko.applyBindings(app, document.getElementById('globalBody'));
          },
          function (error) {
            oj.Logger.error('Error in root start: ' + error.message);
          }
        );
      }

      // If running in a hybrid (e.g. Cordova) environment, we need to wait for the deviceready
      // event before executing any code that might interact with Cordova APIs or plugins.
      if ($(document.body).hasClass('oj-hybrid')) {
        document.addEventListener("deviceready", init);
      } else {
        init();
      }

    });

  }
);


问:
How do you get the current process ID in Mac kernel extension code?
I was initially trying to use getpid() in my kernel module for OS X/macOS, is there a way to get the PID (process ID) of the process in whose context my kext is running in the kernel? Is there an existing function or variable that I can use ?

答: To get the PID of the process with which the currently running kernel thread is associated, call the proc_selfpid() function; you'll need to #include <sys/proc.h> in your kext's code to get the prototype. The PID will of course only correspond to a user process if your code is running in the context of some kind of callback for a syscall.


问:
What is the difference between Serialization and Marshaling?
I know that in terms of several distributed techniques (such as RPC), the term "Marshaling" is used but don't understand how it differs from Serialization. Aren't they both transforming objects into series of bits?

Related:

What is Serialization?

What is Object Marshalling?

答:
Marshaling uses Serialization process actually but the major difference is that it in Serialization only data members and object itself get serialized not signatures  but in Marshalling Object + code base(its implementation) will also get transformed into bytes.

Marshalling is the process to convert java object to xml objects using JAXB so that it can be used in web services.


问:
Live update highcharts-gauge from dweet
I would like to have the gauge chart update live dweet data, which is success.

The problem is that every time a new data is pushed to the array humidityData, a new pointer is added in the gauge chart as shown here:
guage chart Though I'd like to have one live-updating-pointer instead.

Could this be done by pop() the prev data?

```<code><script language="JavaScript">

    //Array to store sensor data
    var humidityData = []

    <!--START-->
    $(document).ready(function() {
       //My Dweet thing's name
       var name = 'dweetThingName'

       //Humidity chart
       var setupSecondChart = function() {

       var chart2 = {
                type: 'gauge'
       };

       var title = {...};

        var pane = {...};

       var yAxis = {...};

            var tooltip = {
                formatter: function () {
                    return '<b>' + "Humidity: "  + Highcharts.numberFormat(this.y, 2)  + "%";
                }
            };

            //Series_Humidity
            humiditySeries = [{
                name: 'Humidity %',
                data: humidityData,
                    tooltip: {
                        valueSuffix: '%'
                    }
            }]

            //Json_Humidity
            var humJson = {};
            humJson.chart = chart2;
            humJson.title = title;
            humJson.tooltip = tooltip;
            humJson.xAxis = xAxis;
            humJson.yAxis = yAxis;
            humJson.legend = legend;
            humJson.exporting = exporting;
            humJson.series = humiditySeries;
            humJson.plotOptions = plotOptions;

            console.log("Sereies: : " +humJson)
           //Container_Humidity
           $('#containerHumidity').highcharts(humJson);
        }

        var humiditySeries = []  ....

        dweetio.get_all_dweets_for(name, function(err, dweets){
            for(theDweet in dweets.reverse())
            {
                var dweet = dweets[theDweet];
                //Dweet's variables' names
                val2 = dweet.content["Humidity"]
                //Add the vals into created arrayDatas
                humidityData.push(val2)
                console.log("HumidityData: " + humidityData)
            }
           //Call other charts
           setupSecondChart()

        });
</code>```

答: When you initialize/update your chart make sure that data array contains only one element. The dial is created for every point in this array (to visualize it on the plot).

Title: Live update highcharts-gauge from dweet


问:
How can I create a HTML login that connects to a database with PHP?
I am trying to create a working HTML Login Page with a PHP script that compares the login data with the Database.
I have been trying to get this working for some time now but it doesent really work. This is the Error Code I get when I press on the Login Button:

```<code>Cannot POST /connectivity.php
</code>```

I created a Database (called leftover_youth)with XAMPP.

```<code>UserNameID
userName
pass
</code>```

This at the moment the HTML code for the whole page.

```<code><html>
    <head lang="en">
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
        <meta content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui" name="viewport">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script type="text/javascript" src="scripts/app.js"></script>
        <link  rel="stylesheet" href="css/stylesheet.css"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
        <title>Project Bootstrap</title>
    </head>
    <body>
        <header>
                <div class="navlogo">
                    <a href="index.html">
                        <h1 class="Logo">Leftover Youth</h1>
                    </a>
                    <a href="index.html">
                        <img class="logoo" src="img/logoo.png" alt="firstimage">
                    </a>
                </div>
        </header>
        <div>
        <fieldset style="width:30%">
            <legend>LOG-IN HERE</legend>
            <form method="POST" action="connectivity.php"> User <br>
                <input type="text" name="user" size="40"><br> Password <br>
                <input type="password" name="pass" size="40"><br>
                <input id="button" type="submit" name="submit" value="Log-In">
            </form>
        </fieldset>
        </div>
    </body>
</html>
</code>```

PHP:

```<code><?php define('DB_HOST', 'localhost');
define('DB_NAME', 'leftover_youth');
define('DB_USER','root');
define('DB_PASSWORD','');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

$ID = $_POST['user'];
$Password = $_POST['pass'];

function SignIn()
{
session_start(); //starting the session
if(!empty($_POST['user'])) //checking User data
{
        $query = mysql_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
        $row = mysql_fetch_array($query) or die(mysql_error());
        if(!empty($row['userName']) AND !empty($row['pass']))
        {
            $_SESSION['userName'] = $row['pass'];
            echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";

        }
        else
        {
                echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
        }
}
}
if(isset($_POST['submit'])) { SignIn();
}
?>
</code>```

答:
You need to check the directory/path of connectivity.php

also move the $ID and  $Password in to the post check

```<code>if(isset($_POST['submit'])) { SignIn();
 $ID = $_POST['user'];
 $Password = $_POST['pass'];
}
</code>```

Body:
I am trying to create a working HTML Login Page with a PHP script that compares the login data with the Database.
I have been trying to get this working for some time now but it doesent really work. This is the Error Code I get when I press on the Login Button:

Cannot POST /connectivity.php

I created a Database (called leftover_youth)with XAMPP.

UserNameID
userName
pass

This at the moment the HTML code for the whole page.

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
        <meta content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui" name="viewport">

        <link  rel="stylesheet" href="css/stylesheet.css"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
        <title>Project Bootstrap</title>

Leftover Youth

        <fieldset style="width:30%">
            <legend>LOG-IN HERE</legend>
            <form method="POST" action="connectivity.php"> User

                <input type="text" name="user" size="40">
 Password

                <input type="password" name="pass" size="40">

                <input id="button" type="submit" name="submit" value="Log-In">
            </form>
        </fieldset>

PHP:

<?php define('DB_HOST', 'localhost');
define('DB_NAME', 'leftover_youth');
define('DB_USER','root');
define('DB_PASSWORD','');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

$ID = $_POST['user'];
$Password = $_POST['pass'];

function SignIn()
{
session_start(); //starting the session
if(!empty($_POST['user'])) //checking User data
{
        $query = mysql_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
        $row = mysql_fetch_array($query) or die(mysql_error());
        if(!empty($row['userName']) AND !empty($row['pass']))
        {
            $_SESSION['userName'] = $row['pass'];
            echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";

        }
        else
        {
                echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
        }
}
}
if(isset($_POST['submit'])) { SignIn();
}
?>

Body:
You need to check the directory/path of connectivity.php

also move the $ID and  $Password in to the post check

if(isset($_POST['submit'])) { SignIn();
 $ID = $_POST['user'];
 $Password = $_POST['pass'];
}


问:
Firefox locks places.sqlite
Platform: Firefox 3.6.13, Python 2.7 stackless, and Windows 7 (not yet tested on Ubuntu, I will...)

I tried with the apsw library:

```<code>conn = apsw.Connection( dir + profile + '/places.sqlite', apsw.SQLITE_OPEN_READONLY )
</code>```

And I got the error:

File "c:\apsw\src\statementcache.c",
  line 386, in sqlite3_prepare
  apsw.BusyError: BusyError: database is
  locked

I see "SQLite manager" can open the database also with Firefox running.

I just want to open and read, I think a trouble free operation. And I cannot use "SQLite manager". I need to code my Python (or PHP or Perl) script.

1) Which type of lock does Firefox use on the SQLite file? Why?

2) How does "SQLite manager" work?

Q2) SQLite Manager works in JavaScript, inside Firefox, so it can access the database.

This is not what I am looking for: An external application reading places while Firefox is running.

答:
Firefox uses SQLite to obtain an EXCLUSIVE lock on the database, which is why you cannot open it:
https://www.sqlite.org/pragma.html#pragma_locking_mode</p>

Title: Firefox locks places.sqlite

Body:
Platform: Firefox 3.6.13, Python 2.7 stackless, and Windows 7 (not yet tested on Ubuntu, I will...)

I tried with the apsw library:

conn = apsw.Connection( dir + profile + '/places.sqlite', apsw.SQLITE_OPEN_READONLY )

And I got the error:

File "c:\apsw\src\statementcache.c",
  line 386, in sqlite3_prepare
  apsw.BusyError: BusyError: database is
  locked

I see "SQLite manager" can open the database also with Firefox running.

I just want to open and read, I think a trouble free operation. And I cannot use "SQLite manager". I need to code my Python (or PHP or Perl) script.

1) Which type of lock does Firefox use on the SQLite file? Why?

2) How does "SQLite manager" work?

Q2) SQLite Manager works in JavaScript, inside Firefox, so it can access the database.

This is not what I am looking for: An external application reading places while Firefox is running.

ContentLicense: CC BY-SA 4.0


问:
How exactly do macros in a Turing Machine work?
I have a screenshot from my textbook here (Sudkamp, 3e), and I am trying to understand how macros are used with the Turing Machine. I am having a hard time grasping it, especially since I have never learned about macros before. If anyone can help with an explanation here, I would really appreciate it.

The only thing I really understand is that the CPY just copies the input, and then there ends up being 3 n’s. Otherwise, I don't really get how to come to that conclusion. I can try to be more specific if I am being too vague, let me know.

答:
For the specific problem: yes, via CPY you get three times n. For computing f(n) = 3n the machine then computes n+n+n = 3n via the addition A.

About macros in general: they do not really work in the way suggested by the diagram. You cannot just put a machine for copying in a "place" in the computation of another machine. Adaptions for alphabet, start state etc. are necessary. The problem is that with TMs programs become very big, many states transition etc. and unreadable. So we suppose that these little adaptions can be done in principle. Now we do not specify complex machines in detail anymore, but use such macros for tasks that have been shown to be computable by a TM (like copying and adding). The resulting description is more understandable. A bit like a higher-level programming language, where you can use complex constructs and data structures without caring about their assembler implementation.


问:
TensorFlow: getting all states from a RNN
How do you get all the hidden states from tf.nn.rnn() or tf.nn.dynamic_rnn() in TensorFlow? The API only gives me the final state.

The first alternative would be to write a loop when building a model that operates directly on RNNCell. However, the number of timesteps is not fixed for me, and depends on the incoming batch.

Some options are to either use a GRU or to write my own RNNCell that concatenates the state to the output. The former choice isn't general enough and the latter sounds too hacky.

Another option is to do something like the answers in this question, getting all the variables from an RNN. However, I'm not sure how to separate the hidden states from other variables in a standard fashion here.

Is there a nice way to get all the hidden states from an RNN while still using the library-provided RNN APIs?

答:
tf.nn.dynamic_rnn(also tf.nn.static_rnn) has two return values; "outputs", "state" (https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn)

As you said, "state" is the final state of RNN, but "outputs" are all hidden states of RNN(which shape is [batch_size, max_time, cell.output_size])

You can use "outputs" as hidden states of RNN, because in most library-provided RNNCell, "output" and "state" are same. (except LSTMCell)

Basic https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn_cell_impl.py#L347

GRU https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn_cell_impl.py#L441


问:
PHP code to get particular portion from an array
I have a version variable like

```<code>$version = "3.4.5";
</code>```

And a verison  array like

```<code>$verison= ["3.7.8", "3.5.2", "3.4.6", "3.3.2", "3.3.1", "3.2.1"];
</code>```

I have to return an array from the $verison array which is greater than the verison string  "3.4.5";
The resultant array will be

```<code>$final=["3.7.8", "3.5.2", "3.4.6"]
</code>```

How it can be perform with PHP code

答:
Using array_filter and version_compare :

```<code>$versions= ["3.7.8", "3.5.2", "3.4.6", "3.3.2", "3.3.1", "3.2.1"];
$version = "3.4.5";

$result = array_filter($versions, function($v) use ($version){return version_compare($v, $version, '>=');});

print_r($result);
</code>```

outputs :

```<code>Array
(
    [0] => 3.7.8
    [1] => 3.5.2
    [2] => 3.4.6
)
</code>```

Ref :
http://php.net/array_filter
http://php.net/version_compare

Body:
I have a version variable like

$version = "3.4.5";

And a verison  array like

$verison= ["3.7.8", "3.5.2", "3.4.6", "3.3.2", "3.3.1", "3.2.1"];

I have to return an array from the $verison array which is greater than the verison string  "3.4.5";
The resultant array will be

$final=["3.7.8", "3.5.2", "3.4.6"]

How it can be perform with PHP code

Body:
Using array_filter and version_compare :

$versions= ["3.7.8", "3.5.2", "3.4.6", "3.3.2", "3.3.1", "3.2.1"];
$version = "3.4.5";

$result = array_filter($versions, function($v) use ($version){return version_compare($v, $version, '>=');});

print_r($result);

outputs :

Array
(
    [0] => 3.7.8
    [1] => 3.5.2
    [2] => 3.4.6
)

Ref :
http://php.net/array_filter
http://php.net/version_compare


问:
How can I find the smallest word in an array for a form application?
I am making a program that takes in lines of user input and finds the largest word in that list. I have everything set up but that last bit and am not sure where to even start. I think I need to make a function and then call it to display it in a text box.</p>

答:
If you have an array, for ex: string[] initArray={"one","twoo","threeeee"};

then

```<code>public string ReturnSmalles(string[] initArray)
{
return initArray.OrderBy(n => n.Length).FirstOrDefault();
}
</code>```

Body:
If you have an array, for ex: string[] initArray={"one","twoo","threeeee"};

then

public string ReturnSmalles(string[] initArray)
{
return initArray.OrderBy(n => n.Length).FirstOrDefault();
}


问:
cargo ssl download error behind proxy on windows
I cannot get cargo to commence any downloads under windows behind an authenticated proxy.

Here are my proxy settings:-

```<code>C:\Users\ukb99427\Downloads
λ set | grep http
https_proxy=http://user:pass@corporate.proxy:8080
http_proxy=http://user:pass@corporate.proxy:8080
</code>```

Note the https_proxy has a http address. This allows something like git and incidentally rustup-init and rustup to work fine. Output from those are

```<code>λ rustup update
info: syncing channel updates for 'stable-x86_64-pc-windows-msvc'
info: syncing channel updates for 'nightly-x86_64-pc-windows-msvc'
info: latest update on 2017-11-10, rust version 1.23.0-nightly (d6b06c63a 2017-11-09)
info: downloading component 'rustc'
 33.4 MiB /  33.4 MiB (100 %)   2.7 MiB/s ETA:   0 s
</code>```

But when running an equivalent cargo install command I get the following

```<code>λ cargo install libc
    Updating registry `https://github.com/rust-lang/crates.io-index`
warning: spurious network error (2 tries remaining): [12/-2] [56] Failure when receiving data from the peer
warning: spurious network error (1 tries remaining): [12/-2] [56] Failure when receiving data from the peer
</code>```

As a test I can run curl

```<code>λ curl --insecure https://github.com/rust-lang/crates.io-index -o registry.html
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  785k    0  785k    0     0   389k      0 --:--:--  0:00:02 --:--:--  393k
</code>```

Alternatively I try setting the https_proxy to https://user:pass@corporate.proxy:8080

and get the following

```<code>λ cargo install libc
    Updating registry `https://github.com/rust-lang/crates.io-index`
warning: spurious network error (2 tries remaining): [12/-2] [4] A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. (Unsupported proxy 'https://user:pass@corporate.proxy:8080', libcurl is built without the HTTPS-proxy support.)
warning: spurious network error (1 tries remaining): [12/-2] [4] A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. (Unsupported proxy 'https://user:pass@corporate.proxy:8080', libcurl is built without the HTTPS-proxy support.)
error: failed to fetch `https://github.com/rust-lang/crates.io-index`

Caused by:
  [12/-2] [4] A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. (Unsupported proxy 'https://user:pass@corporate.proxy:8080', libcurl is built without the HTTPS-proxy support.)
</code>```

For reference curl --version outputs

```<code>λ curl --version
curl 7.53.0 (x86_64-w64-mingw32) libcurl/7.53.0 OpenSSL/1.0.2k zlib/1.2.11 libssh2/1.8.0 nghttp2/1.19.0 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp scp sftp smtp smtps telnet tftp
Features: IPv6 Largefile SSPI Kerberos SPNEGO NTLM **SSL** libz TLS-SRP HTTP2 HTTPS-proxy Metalink
</code>```

Cargo version

```<code>λ cargo version
cargo 0.24.0-nightly (b83550edc 2017-11-04)
</code>```

Is there any way to get cargo to use the same settings as rustup,git or curl? Other apps work ok, with sslverify=false (such as git), which is at best a work around, but would get me somewhere as opposed to nowhere.

This is all on Windows10, behind a authenticated proxy. With no user/pass given, it (and any application) exits with http error 407 which makes sense. For windows apps, they use the IE settings which work fine (for applications like Visual Studio Code or anything similar)

The only alternative I can think of is to force everything to use http only, but I don't know of any settings to make that happen for cargo.

Any thoughts on what else I can try?

答:
I struggled with this a while but finally figured out a work around. I post this here as a possible solution for those behind corporate firewalls. It does, sadly, reduce adoption of rust if people can't install it easily at work.

Download the crates-io from github

```<code>git clone --bare https://github.com/rust-lang/crates.io-index.git
</code>```

In $HOME/.cargo/config file set the registry like

```<code>[registry]
index = "file:///C:/Users/someuser/crates.io-index.git"
</code>```

This stops the registry download via libgit-curl which apparently doesn't support https_proxy.

A longer term solution I think (but I've not tested this yet), is to rebuild cargo with libgit-curl supporting https.

Body:
I cannot get cargo to commence any downloads under windows behind an authenticated proxy.

Here are my proxy settings:-

C:\Users\ukb99427\Downloads
λ set | grep http
https_proxy=http://user:pass@corporate.proxy:8080
http_proxy=http://user:pass@corporate.proxy:8080

Note the https_proxy has a http address. This allows something like git and incidentally rustup-init and rustup to work fine. Output from those are

λ rustup update
info: syncing channel updates for 'stable-x86_64-pc-windows-msvc'
info: syncing channel updates for 'nightly-x86_64-pc-windows-msvc'
info: latest update on 2017-11-10, rust version 1.23.0-nightly (d6b06c63a 2017-11-09)
info: downloading component 'rustc'
 33.4 MiB /  33.4 MiB (100 %)   2.7 MiB/s ETA:   0 s

But when running an equivalent cargo install command I get the following

λ cargo install libc
    Updating registry `https://github.com/rust-lang/crates.io-index`
warning: spurious network error (2 tries remaining): [12/-2] [56] Failure when receiving data from the peer
warning: spurious network error (1 tries remaining): [12/-2] [56] Failure when receiving data from the peer

As a test I can run curl

λ curl --insecure https://github.com/rust-lang/crates.io-index -o registry.html
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  785k    0  785k    0     0   389k      0 --:--:--  0:00:02 --:--:--  393k

Alternatively I try setting the https_proxy to https://user:pass@corporate.proxy:8080

and get the following

λ cargo install libc
    Updating registry `https://github.com/rust-lang/crates.io-index`
warning: spurious network error (2 tries remaining): [12/-2] [4] A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. (Unsupported proxy 'https://user:pass@corporate.proxy:8080', libcurl is built without the HTTPS-proxy support.)
warning: spurious network error (1 tries remaining): [12/-2] [4] A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. (Unsupported proxy 'https://user:pass@corporate.proxy:8080', libcurl is built without the HTTPS-proxy support.)
error: failed to fetch `https://github.com/rust-lang/crates.io-index`

Caused by:
  [12/-2] [4] A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. (Unsupported proxy 'https://user:pass@corporate.proxy:8080', libcurl is built without the HTTPS-proxy support.)

For reference curl --version outputs

λ curl --version
curl 7.53.0 (x86_64-w64-mingw32) libcurl/7.53.0 OpenSSL/1.0.2k zlib/1.2.11 libssh2/1.8.0 nghttp2/1.19.0 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp scp sftp smtp smtps telnet tftp
Features: IPv6 Largefile SSPI Kerberos SPNEGO NTLM **SSL** libz TLS-SRP HTTP2 HTTPS-proxy Metalink

Cargo version

λ cargo version
cargo 0.24.0-nightly (b83550edc 2017-11-04)

Is there any way to get cargo to use the same settings as rustup,git or curl? Other apps work ok, with sslverify=false (such as git), which is at best a work around, but would get me somewhere as opposed to nowhere.

This is all on Windows10, behind a authenticated proxy. With no user/pass given, it (and any application) exits with http error 407 which makes sense. For windows apps, they use the IE settings which work fine (for applications like Visual Studio Code or anything similar)

The only alternative I can think of is to force everything to use http only, but I don't know of any settings to make that happen for cargo.

Any thoughts on what else I can try?

Body:
I struggled with this a while but finally figured out a work around. I post this here as a possible solution for those behind corporate firewalls. It does, sadly, reduce adoption of rust if people can't install it easily at work.

Download the crates-io from github

git clone --bare https://github.com/rust-lang/crates.io-index.git

In $HOME/.cargo/config file set the registry like

[registry]
index = "file:///C:/Users/someuser/crates.io-index.git"

This stops the registry download via libgit-curl which apparently doesn't support https_proxy.

A longer term solution I think (but I've not tested this yet), is to rebuild cargo with libgit-curl supporting https.


问:
Set PDF to print with no scaling
I am generating a PDF (using fpdf) and I am wondering if there is a way to set the document's properties to to default to print with no scaling.

So when you select print from the print dialogue menu, scaling is set to none. I'm trying to determine if this is a user setting or something I can control in the creation of the PDF.

Thanks in advance.

答: Scaling is controlled by the PDF application - it is not set in the file.</p>

ContentLicense: CC BY-SA 2.5

Title: Set PDF to print with no scaling


问:
Alternate of like in oracle select query
I have a table with single column.
 TABLE T with data like:

```<code> A11
B1
As112
DF123
VG112
</code>```

I'm lookingfor alternate of like (VG% and DF%) ... Because i think if there will be more to compare it may effect performance

答:
Here are some of the alternatives you could try. Performance may improve if you have function based index specific to these expressions in where clause (substr).

```<code>select * FROM t where SUBSTR(data,1,2) = 'VG'; -- If you are always comparing first 2 characters.

select * FROM t where SUBSTR(data,1,2) IN (  'VG' , 'DF');  -- Multiple comparisions
</code>```

INSTR is another option but you cannot have an index which suits this comparison.

```<code>select * FROM t where INSTR(data,'VG') = 1;
</code>```

Body:
I have a table with single column.
 TABLE T with data like:

 A11
B1
As112
DF123
VG112

I'm lookingfor alternate of like (VG% and DF%) ... Because i think if there will be more to compare it may effect performance

Body:
Here are some of the alternatives you could try. Performance may improve if you have function based index specific to these expressions in where clause (substr).

select * FROM t where SUBSTR(data,1,2) = 'VG'; -- If you are always comparing first 2 characters.

select * FROM t where SUBSTR(data,1,2) IN (  'VG' , 'DF');  -- Multiple comparisions

INSTR is another option but you cannot have an index which suits this comparison.

select * FROM t where INSTR(data,'VG') = 1;


问:
CrossGeolocator's GetPositionAsync does not work
I am using CrossGeolocator to retrieve the current latitude and longitude of the device. However I am using it inside an OnAppearing override method and it is not working. The GetPositionAsync method hangs the App.

```<code> protected override void OnAppearing()
 {
     base.OnAppearing();

     var position = GetPosition().Result;
     var lat = position.Latitude;
     var lon = position.Longitude;
 }

 private static async Task<Position> GetPosition()
 {
     var locator = CrossGeolocator.Current;
     locator.DesiredAccuracy = 50;

     var position = await locator.GetPositionAsync(10000);
     return position;
 }
</code>```

Detail is that I am using this same GetPosition method in buttons in the application and works perfectly.

Could someone help me in this matter?

答:
This worked for me.

Set up the xamarin forms maps as stated in the link.
https://developer.xamarin.com/guides/xamarin-forms/user-interface/map/

set permissions as stated in below link
https://jamesmontemagno.github.io/GeolocatorPlugin/GettingStarted.html

you may make use of https://jamesmontemagno.github.io/GeolocatorPlugin/CurrentLocation.html

```<code>using Plugin.Geolocator;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
namespace MapApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MapPage : ContentPage
    {
        private Position _position;
        public MapPage()
        {
            InitializeComponent();

            var map = new Map(
              MapSpan.FromCenterAndRadius(
                      new Position(37, -122), Distance.FromMiles(0.3)))
            {
                IsShowingUser = true,
                HeightRequest = 100,
                WidthRequest = 960,
                VerticalOptions = LayoutOptions.FillAndExpand
            };

            if (IsLocationAvailable())
            {
                GetPosition();
                map.MoveToRegion(MapSpan.FromCenterAndRadius(_position, Distance.FromMiles(1)));

            }

            map.MapType = MapType.Street;
            var stack = new StackLayout { Spacing = 0 };
            stack.Children.Add(map);
            Content = stack;

        }

        public bool IsLocationAvailable()
        {
            if (!CrossGeolocator.IsSupported)
                return false;

            return CrossGeolocator.Current.IsGeolocationAvailable;
        }
        public async void GetPosition()
        {
            Plugin.Geolocator.Abstractions.Position position = null;
            try
            {
                var locator = CrossGeolocator.Current;
                locator.DesiredAccuracy = 100;

                position = await locator.GetLastKnownLocationAsync();

                if (position != null)
                {
                    _position = new Position(position.Latitude, position.Longitude);
                    //got a cahched position, so let's use it.
                    return;
                }

                if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
                {
                    //not available or enabled
                    return;
                }

                position = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true);

            }
            catch (Exception ex)
            {
                throw ex;
                //Display error as we have timed out or can't get location.
            }
            _position = new Position(position.Latitude, position.Longitude);
            if (position == null)
                return;

        }

    }
}
</code>```

Body:
I am using CrossGeolocator to retrieve the current latitude and longitude of the device. However I am using it inside an OnAppearing override method and it is not working. The GetPositionAsync method hangs the App.

 protected override void OnAppearing()
 {
     base.OnAppearing();

     var position = GetPosition().Result;
     var lat = position.Latitude;
     var lon = position.Longitude;
 }

 private static async Task<Position> GetPosition()
 {
     var locator = CrossGeolocator.Current;
     locator.DesiredAccuracy = 50;

     var position = await locator.GetPositionAsync(10000);
     return position;
 }

Detail is that I am using this same GetPosition method in buttons in the application and works perfectly.

Could someone help me in this matter?

Body:
This worked for me.

Set up the xamarin forms maps as stated in the link.
https://developer.xamarin.com/guides/xamarin-forms/user-interface/map/

set permissions as stated in below link
https://jamesmontemagno.github.io/GeolocatorPlugin/GettingStarted.html

you may make use of https://jamesmontemagno.github.io/GeolocatorPlugin/CurrentLocation.html

using Plugin.Geolocator;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
namespace MapApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MapPage : ContentPage
    {
        private Position _position;
        public MapPage()
        {
            InitializeComponent();

            var map = new Map(
              MapSpan.FromCenterAndRadius(
                      new Position(37, -122), Distance.FromMiles(0.3)))
            {
                IsShowingUser = true,
                HeightRequest = 100,
                WidthRequest = 960,
                VerticalOptions = LayoutOptions.FillAndExpand
            };

            if (IsLocationAvailable())
            {
                GetPosition();
                map.MoveToRegion(MapSpan.FromCenterAndRadius(_position, Distance.FromMiles(1)));

            }

            map.MapType = MapType.Street;
            var stack = new StackLayout { Spacing = 0 };
            stack.Children.Add(map);
            Content = stack;

        }

        public bool IsLocationAvailable()
        {
            if (!CrossGeolocator.IsSupported)
                return false;

            return CrossGeolocator.Current.IsGeolocationAvailable;
        }
        public async void GetPosition()
        {
            Plugin.Geolocator.Abstractions.Position position = null;
            try
            {
                var locator = CrossGeolocator.Current;
                locator.DesiredAccuracy = 100;

                position = await locator.GetLastKnownLocationAsync();

                if (position != null)
                {
                    _position = new Position(position.Latitude, position.Longitude);
                    //got a cahched position, so let's use it.
                    return;
                }

                if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
                {
                    //not available or enabled
                    return;
                }

                position = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true);

            }
            catch (Exception ex)
            {
                throw ex;
                //Display error as we have timed out or can't get location.
            }
            _position = new Position(position.Latitude, position.Longitude);
            if (position == null)
                return;

        }

    }
}


问:
CUDA wrapper for Qt
Qt have released a nice wrapper for Opencl ( QtOpencl ) which does a very good job of hiding a lot of boiler plate and making OpenCL play nicely with Qt's display widget and Opengl.

But there are a few things that I can do better in Cuda than OpenCL and the Cuda tools are much more mature.

It's relatively easy to make a simple Cuda C++ wrapper and integrate into the Qt build process but I wondered if anybody had done anything more? Ideally an equivalent QtCuda library.

The Qt people aren't interested in Cuda support because it's not cross platform enough

edit: Just for search, there is a Qt CUDA wrapper for openGL PBO. It's based on the Dr Dobbs simplePBO example. There are a couple of bugs fixes needed to make it play nicely with Cuda4 but it's a good start.

ps there is no way to contact the author of the blog and comments don't work - if he finds this let me know and i will send the fixes.

答:
The Qt people aren't interested in Cuda support because it's not cross platform enough

Exactly. If you want to ignore this, you don't understand Qt's philosophy. And why create even more legacy-code, while it's easy to translate your existing kernels to OpenCL with MultiscaleLab Swan?

But the source of the library is free to download and used as a base.

Title: CUDA wrapper for Qt


问:
How create Key event and pass it to document?
I'd like to test key event handler.
I searched and found the result that uses 'createEvent', 'dispatchEvent'.

```<code>var e = document.createEvent('HTMLEvents');
e.keyCode = 83;
e.initEvent(onkeydown, false, true);
document.dispathEvent(e);
</code>```

I did like above but not working.
Could you somebody give me a sample or link?

答:
This is an obsolete way of handling events

Deprecated

This feature has been removed from the Web standards.
  Though some browsers may still support it, it is in the process of
  being dropped. Avoid using it and update existing code if possible;
  see the compatibility table at the bottom of this page to guide your
  decision. Be aware that this feature may cease to work at any time.

If you want to handle keyup events on the entire document, here's the way from the MDN Documentation of Keyboard events :

window.addEventListener("keyup", function(event) {
  let str = "KeyboardEvent: key='" + event.key + "' | code='" +
            event.code + "'";
  let el = document.createElement("span");
  el.innerHTML = str + "
";

  document.getElementById("output").appendChild(el);
}, true);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output"></div></code>```

Body:
I'd like to test key event handler.
I searched and found the result that uses 'createEvent', 'dispatchEvent'.

var e = document.createEvent('HTMLEvents');
e.keyCode = 83;
e.initEvent(onkeydown, false, true);
document.dispathEvent(e);

I did like above but not working.
Could you somebody give me a sample or link?

Body:
This is an obsolete way of handling events

Deprecated

This feature has been removed from the Web standards.
  Though some browsers may still support it, it is in the process of
  being dropped. Avoid using it and update existing code if possible;
  see the compatibility table at the bottom of this page to guide your
  decision. Be aware that this feature may cease to work at any time.

If you want to handle keyup events on the entire document, here's the way from the MDN Documentation of Keyboard events :

window.addEventListener("keyup", function(event) {
  let str = "KeyboardEvent: key='" + event.key + "' | code='" +
            event.code + "'";
  let el = document.createElement("span");
  el.innerHTML = str + "<br/>";

  document.getElementById("output").appendChild(el);
}, true);

<div id="output"></div>


问:
R - Convert SpatialLines to a unique SpatialPolygon
I have a SpatialLines object that I want to convert into a SpatialPolygons object. More precisely, my goal is to transform a SpatiaLines(DataFrame in the following example) into a single polygon.

The only solution I found is with PBSmapping package. But I'm not really confortable with the PolySet concept of this package and the result is not completely satisfying.

So I'm looking for a way with 'classic' packages (sp, rgeos, rgdal) and their classes.

Here is my code :

```<code>library(sp) ; library(rgdal)
library(rgeos) ; library(maptools)

my_directory <- "" # fill with your own directory

# Load the data
my_map <- readOGR(dsn = paste0(my_directory, "Departements"),
                  layer = "LIMITE_DEPARTEMENT")

borders_map <- my_map [my_map $NATURE %in% c("Fronti\xe8re internationale",
                                             "Limite c\xf4ti\xe8re"), ]

class(borders_map) # a SpatialLinesDataFrame in this example

# Convert SpatialLinesDataFrame into SpatialPolygons
library(PBSmapping)

var_temp <- SpatialLines2PolySet(borders_map)
sp_try <- PolySet2SpatialPolygons(var_temp)

proj4string(sp_try) <- proj4string(borders_map)

class(sp_try)

plot(sp_try)
</code>```

The file SPH "Departements" is here :
https://drive.google.com/file/d/1wksMnkufQPdOfSbhWoZbPKMqlcLcll_j

And the result (especially I don't understand the overlay of "two" polygons) :

答:
I read in the DEPARTMENT dataset, and it was SpatialPolygon object. Afterwards, I combined all counties into one unique Polygon.</p>

```<code>my_map <- readOGR(dsn = paste0(my_directory, "Departements"),
                  layer = "DEPARTEMENT")
border <- unionSpatialPolygons(my_map, IDs=rep(1, 96))
plot(border)
str(border,2)

 Formal class 'SpatialPolygons' [package "sp"] with 4 slots
  ..@ polygons   :List of 1
  ..@ plotOrder  : int 1
  ..@ bbox       : num [1:2, 1:2] 99226 6049647 1242375 7110524
  .. ..- attr(*, "dimnames")=List of 2
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
</code>```

Body:
I have a SpatialLines object that I want to convert into a SpatialPolygons object. More precisely, my goal is to transform a SpatiaLines(DataFrame in the following example) into a single polygon.

The only solution I found is with PBSmapping package. But I'm not really confortable with the PolySet concept of this package and the result is not completely satisfying.

So I'm looking for a way with 'classic' packages (sp, rgeos, rgdal) and their classes.

Here is my code :

library(sp) ; library(rgdal)
library(rgeos) ; library(maptools)

my_directory <- "" # fill with your own directory

# Load the data
my_map <- readOGR(dsn = paste0(my_directory, "Departements"),
                  layer = "LIMITE_DEPARTEMENT")

borders_map <- my_map [my_map $NATURE %in% c("Fronti\xe8re internationale",
                                             "Limite c\xf4ti\xe8re"), ]

class(borders_map) # a SpatialLinesDataFrame in this example

# Convert SpatialLinesDataFrame into SpatialPolygons
library(PBSmapping)

var_temp <- SpatialLines2PolySet(borders_map)
sp_try <- PolySet2SpatialPolygons(var_temp)

proj4string(sp_try) <- proj4string(borders_map)

class(sp_try)

plot(sp_try)

The file SPH "Departements" is here :
https://drive.google.com/file/d/1wksMnkufQPdOfSbhWoZbPKMqlcLcll_j

And the result (especially I don't understand the overlay of "two" polygons) :

Body:
I read in the DEPARTMENT dataset, and it was SpatialPolygon object. Afterwards, I combined all counties into one unique Polygon.

my_map <- readOGR(dsn = paste0(my_directory, "Departements"),
                  layer = "DEPARTEMENT")
border <- unionSpatialPolygons(my_map, IDs=rep(1, 96))
plot(border)
str(border,2)

 Formal class 'SpatialPolygons' [package "sp"] with 4 slots
  ..@ polygons   :List of 1
  ..@ plotOrder  : int 1
  ..@ bbox       : num [1:2, 1:2] 99226 6049647 1242375 7110524
  .. ..- attr(*, "dimnames")=List of 2
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot


答:
First of all avoid using mysql which is long back deprecated, instead use mysqli

There are few solutions for your problem.

The way with MySQLi would be like this:

```<code>$connection = mysqli_connect('localhost', 'username', 'password', 'database');
</code>```

To run database queries is also simple and nearly identical with the old way:

```<code>// Old way
 $query = mysql_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
// New way
 $query = mysqli_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
</code>```

Title: How can I create a HTML login that connects to a database with PHP?

Body:
First of all avoid using mysql which is long back deprecated, instead use mysqli

There are few solutions for your problem.

The way with MySQLi would be like this:

$connection = mysqli_connect('localhost', 'username', 'password', 'database');

To run database queries is also simple and nearly identical with the old way:

// Old way
 $query = mysql_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
// New way
 $query = mysqli_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());


问:
Setting up connection string in ASP.NET to SQL SERVER
I'm trying to set up a connecting string in my web.config file (Visual Studio 2008/ASP.NET 3.5) to a local server (SQL server 2008).

In my web.config, how and where do I place the connection string?

Here's what web.config file looks like right now: http://imwired.net/aspnet/Online_web.config

答:
You can try this. It is very simple</p>

```<code><connectionStrings>
    <add name="conString" connectionString="Data Source=SQLServerAddress;Initial Catalog=YourDatabaseName; User Id=SQLServerLoginId; Password=SQLServerPassword"/>
</connectionStrings>
</code>```

Body:
You can try this. It is very simple

<connectionStrings>
    <add name="conString" connectionString="Data Source=SQLServerAddress;Initial Catalog=YourDatabaseName; User Id=SQLServerLoginId; Password=SQLServerPassword"/>
</connectionStrings>


答:
I think you need merge with left join:

```<code>df = pd.merge(df1, df2, how='left')
</code>```

Or if possible more common columns names in both DataFrames:

```<code>df = pd.merge(df1, df2, how='left', on='id')
</code>```

```<code>print (df)
  id  payment  res_number      type  group  unique_num
0  a    20000           1      toys      1        1231
1  a    30000           2  clothing      1        1231
2  a    40000           3      food      1        1231
3  b    40000           4      food      2        1234
4  c    30000           5    laptop      1        1241
</code>```

Title: Merging two dataframes which has duplicated 'on' value on one side

Body:
I have two dataframes, and the standard dataframe has some same values(=id) which i have to use as merging point.

+----+------------+------------+------------+
| id | res_number |    type    | payment    |
+----+------------+------------+------------+
|  a |     1      |    toys    | 20000      |
|  a |     2      |  clothing  | 30000      |
|  a |     3      |    food    | 40000      |
|  b |     4      |    food    | 40000      |
|  c |     5      |   laptop   | 30000      |
+----+------------+------------+------------+

\I want to merge this dataframe with below dataframe.

+----+------------+------------+
| id |   group    | unique_num |
+----+------------+------------+
|  a |     1      |    1231    |
|  b |     2      |    1234    |
|  c |     1      |    1241    |
+----+------------+------------+

and i want to make dataframe like this.

+----+------------+------------+------------+------------+------------+
| id | res_number |    type    | payment    |   group    | unique_num |
+----+------------+------------+------------+------------+------------+
|  a |     1      |    toys    | 20000      |      1     |    1231    |
|  a |     2      |  clothing  | 30000      |      1     |    1231    |
|  a |     3      |    food    | 40000      |      1     |    1231    |
|  b |     4      |    food    | 40000      |      2     |    1234    |
|  c |     5      |   laptop   | 30000      |      3     |    1241    |
+----+------------+------------+------------+------------+------------+

As you can notice i want to merge dataframes with 'id', but the standard dataframe has some same values on 'id'. My target is just pasting values whatever values on 'id' has.

Can you give me good example of this problem?

Body:
I think you need merge with left join:

df = pd.merge(df1, df2, how='left')

Or if possible more common columns names in both DataFrames:

df = pd.merge(df1, df2, how='left', on='id')

print (df)
  id  payment  res_number      type  group  unique_num
0  a    20000           1      toys      1        1231
1  a    30000           2  clothing      1        1231
2  a    40000           3      food      1        1231
3  b    40000           4      food      2        1234
4  c    30000           5    laptop      1        1241


问:
How to move wordpress website from hosting account to localhost
I'm getting 404 error while accessing relative paths on
Wordpress website copied from hosting and deployed locally as Apache vhost.

Local website is basically git clone of the existing remote website.

The following steps were performed to make it work:

DB urls were searched and replaced using wp-cli to be http://local.webiste.com

VHost configured according to apache documentation.

/etc/hosts modified.

So website can be accessed successfully via http://local.website.com.

Media in http://local.website.com/wp-content/uploads/2017 can be viewed successfully.

Though, accessing a Wordrpess page identified by /relative path (relative to current domain/site) causes "The requested URL /relative/ was not found on this server" error.

I'm using the same .htaccess from the remote public_html folder.

How to achive equivalent to hosting behaviour for local vhost website?

Is .htaccess, apache2 configuration, vhost configurations should be changed?

答: You can use the WP Migrate DB plugin to fix URLs and PHP paths, and them you need to fix the .htaccess file (PHP path) and maybe wp-config.php.


问:
How to solve flavor "normal" has no flavor dimension in Android studio 3.0?
While I was opening an google project called iosched, the gradle building was failed and kept warning me something about flavor. I tried to solve it follow some suggestions online but it turned out to warn me this. What should I do?? My Android studio version is 3.0 btw.

答:
In the build.gradle of app module you must define flavorDimensions which is from Android studio 3.0. so do something like :

android {
    flavorDimensions "example"
}

and inside ProductFlavors on same module use it as:

productFlavors {
a {
dimension "example"
}
b{dimension "example"
}

here a and b are the types of product flavors.
For more information refer to this link Configure Build Variants


问:
How to test a PrivateObject in a .net standard test project?
I am following this tutorial, https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-mstest

but I don't have the type PrivateObject available, so I am wondering if it would be possible to test private objects with a .net standard 2.0 project.

答:
You can always use a reflection

```<code>ClassToTest obj = new ClassToTest();
Type t = typeof(ClassToTest);

FieldInfo f = t.GetField("field",  BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
f.SetValue(obj, "Don't panic");

t.InvokeMember("PrintField",
    BindingFlags.InvokeMethod | BindingFlags.NonPublic |
    BindingFlags.Public | BindingFlags.Instance,
    null, obj, null);
</code>```

You should write a helper class for this, or else your tests will conatin a  lot of identical code

P.S. Sample of code is from here

Body:
You can always use a reflection

ClassToTest obj = new ClassToTest();
Type t = typeof(ClassToTest);

FieldInfo f = t.GetField("field",  BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
f.SetValue(obj, "Don't panic");

t.InvokeMember("PrintField",
    BindingFlags.InvokeMethod | BindingFlags.NonPublic |
    BindingFlags.Public | BindingFlags.Instance,
    null, obj, null);

You should write a helper class for this, or else your tests will conatin a  lot of identical code

P.S. Sample of code is from here


问:
PHP date format vs Symfony RFC 3339 format
As per http://php.net/manual/en/class.datetime.php

PHP follows "ATOM" date format. To produce a date like "2017-11-14" we need date format string "Y-m-d". I am able to produce it using php date function and class. It works as expected.

```<code>/////Using date function////
echo date("Y-m-d");

/////Using DateTime class////
$date = new DateTime();
echo $date->format('Y-m-d');
</code>```

Now I want to use these date formats dynamically in my Symfony3 application. As per docs, format for dateType field must be according to "RFC3339" because it uses IntlDateFormatter class for formatting.
https://symfony.com/doc/current/reference/forms/types/date.html#format

So to produce date same as previous one, we need different format string

```<code>$date = new DateTime();
$dateFormat = new IntlDateFormatter(
    "en_US",
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd'
);
echo $dateFormat->format($date->getTimestamp());
</code>```

To render datepicker fields on my forms, I am using bootstrap datepicker (https://bootstrap-datepicker.readthedocs.io/en/stable/options.html#format). Format demand to produce same previous date here is bit different "yyyy-mm-dd".

Although I can understand datepicker format can be different from PHP one. But I am unable to understand why there is difference between PHP and symfony date format requirements.

I am not sure how to make it working, as there can be plenty of formats, user can choose from. So a user chooses his date format preferences and I need to produce same date string everywhere.

I am thinking about some converter which can transform PHP date string to symfony and javascript formats or if I can manage to change dateformatter for symfony it can help also in my opinion.

答:
You are confusing the symfony format and html5 one. There is no symfony format, the rfc refers to the html specifications.

You should, for your frontend:

Create a twig filter that output any datetime in the user format preference

Use a javascript date widget instead of html date input. Mainly because the format of html date widget can't be changed and you won't be able to use the user format preference of your application. It is the format that is given to the request that is at the RFC3339 format: YYYY-mm-dd

That's all, your controllers and model should just handle Datetimes object

Body:
As per http://php.net/manual/en/class.datetime.php

PHP follows "ATOM" date format. To produce a date like "2017-11-14" we need date format string "Y-m-d". I am able to produce it using php date function and class. It works as expected.

/////Using date function////
echo date("Y-m-d");

/////Using DateTime class////
$date = new DateTime();
echo $date->format('Y-m-d');

Now I want to use these date formats dynamically in my Symfony3 application. As per docs, format for dateType field must be according to "RFC3339" because it uses IntlDateFormatter class for formatting.
https://symfony.com/doc/current/reference/forms/types/date.html#format

So to produce date same as previous one, we need different format string

$date = new DateTime();
$dateFormat = new IntlDateFormatter(
    "en_US",
    IntlDateFormatter::NONE,
    IntlDateFormatter::NONE,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'yyyy-MM-dd'
);
echo $dateFormat->format($date->getTimestamp());

To render datepicker fields on my forms, I am using bootstrap datepicker (https://bootstrap-datepicker.readthedocs.io/en/stable/options.html#format). Format demand to produce same previous date here is bit different "yyyy-mm-dd".

Although I can understand datepicker format can be different from PHP one. But I am unable to understand why there is difference between PHP and symfony date format requirements.

I am not sure how to make it working, as there can be plenty of formats, user can choose from. So a user chooses his date format preferences and I need to produce same date string everywhere.

I am thinking about some converter which can transform PHP date string to symfony and javascript formats or if I can manage to change dateformatter for symfony it can help also in my opinion.


问:
Making ajax call and showing contents in qtip
I am writing code for a dropdown list. The dropdown list is being populated from the data from the database. So I am making 2 ajax calls one is on event onmouseover to populate the contents of dropdown list and the other on selection of specific option making ajax call to bring related contents on the screen.

Now I want to make another ajax call to get the contents which can be populated on hovering over the specific option. The contents got from ajax call can be displayed in the small dialog box. For achieving this I have installed the qtip libraries.

Problem

I am not getting how the ajax call be made. Which even will be appropriate for achieving this? I know the qtip is loaded onload of the page. But since I want to make ajax call to get the contents of the message to be shown on hovering over the option. Any suggestions?

I have also read somewhere that you can't make more than 2 ajax calls at a time.

** The contents for the 3 ajax calls are different. And I have separate JSP files for each of them.

答:
You could do this

```<code>$('.link').mouseover(function(){
    $.ajax(
        /* Retrieve de options for the select and fill each
        title attribute with the information*/);
        url: "retrieveinfo.jsp",
        type: "GET",
        data: ({id : 'itemsId'}), //pass the data in JSON form
        dataType: "html",
        success: function(msg){   //msg contains the html output or you could request XML (or JSON)
            $('#info').html(msg);
            NFinit();
            tooltip.init();
        }
});
</code>```

That would make one AJAX call, populate the select and init niceforms and qtip.

Body:
You could do this

$('.link').mouseover(function(){
    $.ajax(
        /* Retrieve de options for the select and fill each
        title attribute with the information*/);
        url: "retrieveinfo.jsp",
        type: "GET",
        data: ({id : 'itemsId'}), //pass the data in JSON form
        dataType: "html",
        success: function(msg){   //msg contains the html output or you could request XML (or JSON)
            $('#info').html(msg);
            NFinit();
            tooltip.init();
        }
});

That would make one AJAX call, populate the select and init niceforms and qtip.


问:
Angular 4 | how can i set a timer and will update my API data?
How can i set timer that will update my API data when the countdown is done, and will back to original countdown when the API data is updated.

Example i want to count to 10 and after that my API data will be updated and so on.

Below is my code with timer.

```<code>import { Component, ViewEncapsulation, Pipe, PipeTransform, VERSION  } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { SlicePipe, DatePipe } from '@angular/common';
import {Observable} from 'rxjs/Observable'
import 'rxjs/add/observable/timer'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/take'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
})

export class AppComponent{

public data: any;
countDown;
counter = 10;

constructor( private http: Http ) {
    this.countDown = Observable.timer(0,1000)
  .take(this.counter)
  .map(() => --this.counter);
}

ngOnInit() {
    this.getVoicepicData();
    this.getData();
    console.log('hi');
}

getData(){
    let headers = new Headers({
        'token': "MY TOKEN GOES HERE",
        'Content-Type': 'application/json'
    });

    let options: RequestOptions = new RequestOptions({ headers: headers });

    return this.http.get('http://my.apidatahere.com/api/', options)
        .map((res: Response) => res.json())
}

getVoicepicData() {
    this.getData().subscribe(data => {
        this.data = data
    })
}
}
</code>```

答:
You can use set interval method in Javascript to trigger any function at the interval n seconds and you can stop the timer by clear Interval.

```<code>apiTimer : any
    ngOnInit() {
    this.getVoicepicData();
   this.apiTimer= setInterval(() => {
              this.getData()
            }, (this.counter*1000));
}
</code>```

call the below line whenever you want to stop the timer. If you missed to call clearInterval, API will be triggered continously after every n seconds

```<code>clearInterval(this.apiTimer);
</code>```

Body:
How can i set timer that will update my API data when the countdown is done, and will back to original countdown when the API data is updated.

Example i want to count to 10 and after that my API data will be updated and so on.

Below is my code with timer.

import { Component, ViewEncapsulation, Pipe, PipeTransform, VERSION  } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { SlicePipe, DatePipe } from '@angular/common';
import {Observable} from 'rxjs/Observable'
import 'rxjs/add/observable/timer'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/take'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
})

export class AppComponent{

public data: any;
countDown;
counter = 10;

constructor( private http: Http ) {
    this.countDown = Observable.timer(0,1000)
  .take(this.counter)
  .map(() => --this.counter);
}

ngOnInit() {
    this.getVoicepicData();
    this.getData();
    console.log('hi');
}

getData(){
    let headers = new Headers({
        'token': "MY TOKEN GOES HERE",
        'Content-Type': 'application/json'
    });

    let options: RequestOptions = new RequestOptions({ headers: headers });

    return this.http.get('http://my.apidatahere.com/api/', options)
        .map((res: Response) => res.json())
}

getVoicepicData() {
    this.getData().subscribe(data => {
        this.data = data
    })
}
}

Body:
You can use set interval method in Javascript to trigger any function at the interval n seconds and you can stop the timer by clear Interval.

apiTimer : any
    ngOnInit() {
    this.getVoicepicData();
   this.apiTimer= setInterval(() => {
              this.getData()
            }, (this.counter*1000));
}

call the below line whenever you want to stop the timer. If you missed to call clearInterval, API will be triggered continously after every n seconds

clearInterval(this.apiTimer);


答:
This should be what you want to achieve I think.

  document.querySelector('.trigger-event').addEventListener('click', function(e){
    e.preventDefault();

    var e = new Event("keydown");
    e.key="a";    // just enter the char you want to send
    e.keyCode=e.key.charCodeAt(0);
    e.which=e.keyCode;
    e.altKey=false;
    e.ctrlKey=true;
    e.shiftKey=false;
    e.metaKey=false;
    e.bubbles=true;
    this.dispatchEvent(e);

  }, false);
  document.querySelector('.trigger-event').addEventListener('keydown', function(e){
    e.preventDefault();
    alert('Got keydown ' + e.key);
  },false);

  document.addEventListener('keydown', function(e){
    e.preventDefault();
    document.getElementById('keyValue').innerHTML = e.key;
    document.getElementById('charCode').innerHTML = e.keyCode;
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Demo</title>
</head>
<body>

  <h3>Demo</h3>
  <p>
    <button class="btn-flat-blue trigger-event">Trigger Keydown event</button>
  </p>

  <h3> Press a key to see the key code</h3>
  <p>
    key <span id="keyValue"></span> = charCode <span id="charCode"></span>
  </p>

</div>
</body>
</html></code>```

Title: How create Key event and pass it to document?

Body:
This should be what you want to achieve I think.

  document.querySelector('.trigger-event').addEventListener('click', function(e){
    e.preventDefault();

    var e = new Event("keydown");
    e.key="a";    // just enter the char you want to send
    e.keyCode=e.key.charCodeAt(0);
    e.which=e.keyCode;
    e.altKey=false;
    e.ctrlKey=true;
    e.shiftKey=false;
    e.metaKey=false;
    e.bubbles=true;
    this.dispatchEvent(e);

  }, false);
  document.querySelector('.trigger-event').addEventListener('keydown', function(e){
    e.preventDefault();
    alert('Got keydown ' + e.key);
  },false);

  document.addEventListener('keydown', function(e){
    e.preventDefault();
    document.getElementById('keyValue').innerHTML = e.key;
    document.getElementById('charCode').innerHTML = e.keyCode;
  });

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Demo</title>
</head>
<body>

  <h3>Demo</h3>
  <p>
    <button class="btn-flat-blue trigger-event">Trigger Keydown event</button>
  </p>

  <h3> Press a key to see the key code</h3>
  <p>
    key <span id="keyValue"></span> = charCode <span id="charCode"></span>
  </p>

</div>
</body>
</html>