答:
Find online demo</p>

```<code>import re
links = [
  '<a href="http://127.0.0.1:5000/project/24/portfolio/">Packaging Only Demo</a>',
  '<a href="http://127.0.0.1:5000/project/38/portfolio/">QA Source</a>',
  '<a href="http://127.0.0.1:5000/project/44/portfolio/">Complete Demo</a>'
]
def custom_function(k):
  return re.search(r'\>(.*)\<', k).group(1)
print(sorted(links, key=custom_function))
</code>```

Title: sort the list of links by the name of the link

Body:
I have list of links

links = [
  'Packaging Only Demo',
  'QA Source',
  'Complete Demo'
]

And I need to sort the list by the name of the link.

I tried to sort it with a regular expression but it lasted too long. The list consists of a multitude of references

import re
def sorted(x):
  return re.search(r'\>(.*)<', x).group(1)

links = sorted(links, key=sorted)
print(links)

Body:
Find online demo

import re
links = [
  '<a href="http://127.0.0.1:5000/project/24/portfolio/">Packaging Only Demo</a>',
  '<a href="http://127.0.0.1:5000/project/38/portfolio/">QA Source</a>',
  '<a href="http://127.0.0.1:5000/project/44/portfolio/">Complete Demo</a>'
]
def custom_function(k):
  return re.search(r'\>(.*)\<', k).group(1)
print(sorted(links, key=custom_function))


来源: stackexchange

问:
ASP.NET MVC - Remove dependency from DAL in GUI
I'm building a MVC web app that consist of 3 projects. One for the GUI, one for the BusinessLogic and one for the Data access.

For my Data access I have a generated file by EF and therefore I have a generated class named "Customer". To make validation attributes for this class I need to make MetaDataType (which needs to be done in the same namespace and therefore I'm bound to do it in the DAL layer) - by doing this I refer to the Data access layer from my GUI which spoils the whole idea of splitting the project up, because that my GUI now refer both my DAL and BL layer. Is there anyhow I can keep my GUI and DAL layers seperated but still be abe to use Validation attributes like [Required] and so on?

Thanks in advance.

答:
That's what ViewModels are about. But that means you will have a new set of DTO's for the view-controller communication... Which is a good thing IMHO, since your views should not know anything about the real domain model.

Regarding all distinct ways of making your views communicate with the model, please take a look at this.

ContentLicense: CC BY-SA 2.5


问:
How do I use variables with HtmlWebpackPlugin and a twig-loader?
I made a small engine to create a multi-language template.
With HtmlWebpackPlugin from twig to HTML, with some dynamic variables loaded from a json file.
But after compiling I still see my variables in my HTML files...

Does someone see where I can make some improvement?
Or where I did something wrong?

Webpack.config.js:

```<code>'use strict';
var path = require('path');
var _ = require('lodash');
var webpack = require('webpack');
var timestamp = require('time-stamp');
var packageJson = require('./package.json');
var autoprefixer = require('autoprefixer');
var htmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var pages = require('./templates.json');

var templatePages = _.map(pages, function(page) {
let translation = require('./src/assets/translations/lang.'+page.lang+'.json');
return new htmlWebpackPlugin({
    filename: page.filename,
    template: page.template,
    trans: translation
 });
});

const DEV_DIR = './src';
const DIST_DIR = './dist';

module.exports = {
    devtool: "source-map",
    entry: {
        app: [DEV_DIR+'/js/app.js',DEV_DIR+'/css/main.scss']
    },
    output: {
        path: path.resolve(__dirname, 'tmp'),
        filename: "[name].js",
        library: "[name]"
    },
resolve: {
    extensions: ['', '.js', '.twig']
},
module: {
    preLoaders: [{
        test: /\.js$/,
        exclude: /(bin|node_modules|bower_components|grunt|gulp|bower)/,
        loaders: ['eslint-loader']
    }],
    loaders: [{
        test: /\.js$/,
        exclude: /(bin|node_modules|bower_components|grunt|gulp|bower)/,
        loader: 'babel',
        query: {
            presets: ['es2015'],
            babelrc: false
        }
    }, {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract(
            'style-loader',
            'css-loader!postcss-loader!sass-loader'
        )
    }, {
        test: /\.(jpe?g|png|gif|svg|ico)$/i,
        loaders : [
            'file-loader?hash=sha512&digest=hex&name=/assets/img/[name].[ext]',
        ]
    },{
        test: /\.(json)$/i,
        loaders : [
            'file-loader?hash=sha512&digest=hex&name=/assets/translations/[name].[ext]',
        ]
    }, {
        test: /\.twig$/,
        loader: "twig-loader"
    }]
},
devServer : {
    contentBase : 'tmp',
    inline      : true
},
eslint: {
    configFile: './.eslintrc'
},
sasslint: {
    configFile: './sass-lint.yml',
    emitError: true
},
plugins: [
    new ExtractTextPlugin(
        '/css/main.css',
        { allChunks: true }
    ),
    new webpack.DefinePlugin({
        __DEBUG     : JSON.stringify(true),
        __NAME      : JSON.stringify(packageJson.name),
        __DESC      : JSON.stringify(packageJson.description),
        __VERSION   : JSON.stringify(packageJson.version),
        __TIMESTAMP : JSON.stringify(timestamp('YYYY/MM/DD HH:mm:ss:ms'))
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        },
        output: {
            comments: false
        }
    }),
    new webpack.ProvidePlugin({
        Logger   : path.resolve(__dirname, 'libs/Logger')
    })
].concat(templatePages),
};
</code>```

Templates Json:

```<code>[
    {
        "filename": "./nl/index.html",
        "template": "./src/twig/index.twig",
        "lang": "nl"
    },
    {
        "filename": "./fr/index.html",
        "template": "./src/twig/index.twig",
        "lang": "fr"
    },
    {
        "filename": "./de/index.html",
        "template": "./src/twig/index.twig",
        "lang": "de"
    }
]
</code>```

Translation file:

```<code>{"toggle_mobile":"Menu",
"menu_primary_introduction":"Introductie",
"menu_primary_reference":"Referenties",
"menu_primary_information":"Aanpak",
"menu_primary_contact":"Contact",}
</code>```

Index.twig:

```<code><!DOCTYPE html>
<html lang="<%= htmlWebpackPlugin.options.trans.menu_lang_short %>">
<head>
    <meta charset="utf-8" />
    <meta name="keywords" content="" />
    <meta name="description" content="Title CMS" />
    <meta name="author" content="Company BVBA" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Title CMS</title>
    <link type="image/x-icon" href="/assets/img/favicon.ico" rel="shortcut icon" />
    <script src="https://use.typekit.net/oww0qak.js"></script>
    <script>try{Typekit.load({ async: true });}catch(e){}</script>
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
</head>
<body>
    <div class="page-body">

        <header class="header-primary">
            <%= htmlWebpackPlugin.options.trans.menu_primary_introduction %>
        </header>
    </div>
</body>
</html>
</code>```

答:
Fixed!

I was confused with the method for JS/HTML <%= =%> and twig.
For twig it's not necessary to use <%= =%>. I must use only {{ }}.

So my working result, e.g.:

```<code><span class="navbar-toggler-text">{{ htmlWebpackPlugin.options.trans.toggle_mobile }}</span>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I made a small engine to create a multi-language template.
With HtmlWebpackPlugin from twig to HTML, with some dynamic variables loaded from a json file.
But after compiling I still see my variables in my HTML files...

Does someone see where I can make some improvement?
Or where I did something wrong?

Webpack.config.js:

'use strict';
var path = require('path');
var _ = require('lodash');
var webpack = require('webpack');
var timestamp = require('time-stamp');
var packageJson = require('./package.json');
var autoprefixer = require('autoprefixer');
var htmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var pages = require('./templates.json');

var templatePages = _.map(pages, function(page) {
let translation = require('./src/assets/translations/lang.'+page.lang+'.json');
return new htmlWebpackPlugin({
    filename: page.filename,
    template: page.template,
    trans: translation
 });
});

const DEV_DIR = './src';
const DIST_DIR = './dist';

module.exports = {
    devtool: "source-map",
    entry: {
        app: [DEV_DIR+'/js/app.js',DEV_DIR+'/css/main.scss']
    },
    output: {
        path: path.resolve(__dirname, 'tmp'),
        filename: "[name].js",
        library: "[name]"
    },
resolve: {
    extensions: ['', '.js', '.twig']
},
module: {
    preLoaders: [{
        test: /\.js$/,
        exclude: /(bin|node_modules|bower_components|grunt|gulp|bower)/,
        loaders: ['eslint-loader']
    }],
    loaders: [{
        test: /\.js$/,
        exclude: /(bin|node_modules|bower_components|grunt|gulp|bower)/,
        loader: 'babel',
        query: {
            presets: ['es2015'],
            babelrc: false
        }
    }, {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract(
            'style-loader',
            'css-loader!postcss-loader!sass-loader'
        )
    }, {
        test: /\.(jpe?g|png|gif|svg|ico)$/i,
        loaders : [
            'file-loader?hash=sha512&digest=hex&name=/assets/img/[name].[ext]',
        ]
    },{
        test: /\.(json)$/i,
        loaders : [
            'file-loader?hash=sha512&digest=hex&name=/assets/translations/[name].[ext]',
        ]
    }, {
        test: /\.twig$/,
        loader: "twig-loader"
    }]
},
devServer : {
    contentBase : 'tmp',
    inline      : true
},
eslint: {
    configFile: './.eslintrc'
},
sasslint: {
    configFile: './sass-lint.yml',
    emitError: true
},
plugins: [
    new ExtractTextPlugin(
        '/css/main.css',
        { allChunks: true }
    ),
    new webpack.DefinePlugin({
        __DEBUG     : JSON.stringify(true),
        __NAME      : JSON.stringify(packageJson.name),
        __DESC      : JSON.stringify(packageJson.description),
        __VERSION   : JSON.stringify(packageJson.version),
        __TIMESTAMP : JSON.stringify(timestamp('YYYY/MM/DD HH:mm:ss:ms'))
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        },
        output: {
            comments: false
        }
    }),
    new webpack.ProvidePlugin({
        Logger   : path.resolve(__dirname, 'libs/Logger')
    })
].concat(templatePages),
};

Templates Json:

[
    {
        "filename": "./nl/index.html",
        "template": "./src/twig/index.twig",
        "lang": "nl"
    },
    {
        "filename": "./fr/index.html",
        "template": "./src/twig/index.twig",
        "lang": "fr"
    },
    {
        "filename": "./de/index.html",
        "template": "./src/twig/index.twig",
        "lang": "de"
    }
]

Translation file:

{"toggle_mobile":"Menu",
"menu_primary_introduction":"Introductie",
"menu_primary_reference":"Referenties",
"menu_primary_information":"Aanpak",
"menu_primary_contact":"Contact",}

Index.twig:

<!DOCTYPE html>
<html lang="<%= htmlWebpackPlugin.options.trans.menu_lang_short %>">

    <meta charset="utf-8" />
    <meta name="keywords" content="" />
    <meta name="description" content="Title CMS" />
    <meta name="author" content="Company BVBA" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Title CMS</title>
    <link type="image/x-icon" href="/assets/img/favicon.ico" rel="shortcut icon" />

    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">

            <%= htmlWebpackPlugin.options.trans.menu_primary_introduction %>

Body:
Fixed!

I was confused with the method for JS/HTML <%= =%> and twig.
For twig it's not necessary to use <%= =%>. I must use only {{ }}.

So my working result, e.g.:

<span class="navbar-toggler-text">{{ htmlWebpackPlugin.options.trans.toggle_mobile }}</span>


问:
Adding a custom field in log4j using SyslogAppender
I'm using the SyslogAppender in my java application and I'm trying to add a custom field to the resulting log. How can I add an additional field to my log4j.properties?

My current log4j.properties (the last line shows what I want to achieve):

```<code>log4j.appender.SYSLOG=org.apache.log4j.net.SyslogAppender
log4j.appender.SYSLOG.threshold=INFO
log4j.appender.SYSLOG.syslogHost=localhost
log4j.appender.SYSLOG.facility=LOCAL4
log4j.appender.SYSLOG.header=true
log4j.appender.SYSLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.SYSLOG.layout.conversionPattern=my-app: %m%n
log4j.appender.SYSLOG.applicationName=${STACKNAME}
</code>```

The ${STACKNAME} is a system property configured by the deployment job, depending on the environment (e.g. prod, test, dev).

答:
From this answer I get the answer: add the lines

```<code>log4j.appender.graylog2.additionalFields={'filed_name': 'field_value', 'field2_name': 'field2_value'}
log4j.appender.graylog2.addExtendedInformation=true
</code>```

to add field_name and field2_name with values field_value and field2_value. The property addExtendedInformation=true indicates Graylog to add those fields to all log entries.

Body:
I'm using the SyslogAppender in my java application and I'm trying to add a custom field to the resulting log. How can I add an additional field to my log4j.properties?

My current log4j.properties (the last line shows what I want to achieve):

log4j.appender.SYSLOG=org.apache.log4j.net.SyslogAppender
log4j.appender.SYSLOG.threshold=INFO
log4j.appender.SYSLOG.syslogHost=localhost
log4j.appender.SYSLOG.facility=LOCAL4
log4j.appender.SYSLOG.header=true
log4j.appender.SYSLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.SYSLOG.layout.conversionPattern=my-app: %m%n
log4j.appender.SYSLOG.applicationName=${STACKNAME}

The ${STACKNAME} is a system property configured by the deployment job, depending on the environment (e.g. prod, test, dev).

Body:
From this answer I get the answer: add the lines

log4j.appender.graylog2.additionalFields={'filed_name': 'field_value', 'field2_name': 'field2_value'}
log4j.appender.graylog2.addExtendedInformation=true

to add field_name and field2_name with values field_value and field2_value. The property addExtendedInformation=true indicates Graylog to add those fields to all log entries.


问:
table.rows().remove() does not work if serverSide: true
when i try to remove row from datatable
I simply use this

```<code>    var table = $('#tbl').DataTable();
   table.rows().remove().draw();
</code>```

its working but if i set datatable

```<code>"processing": true,"serverSide": true
</code>```

than

```<code>table.rows().remove().draw();
</code>```

it will not remove any row form datatable

答:
Method rows.remove() is pure client side. If you enable serverSide: true then you need to handle deletions manually. For example use Ajax to delete rows. Note that you need support from your server side also to remove rows.

Example code:

$('#delete').on('click', function() {
    var selectedRows = table.rows( $('#table tr.active') ).data().to$();

    $.ajax({
        url: url_to_delete_rows,
        method: 'POST',
        data: { rows: selectedRows.toArray() },
        dataType: 'json',
        success: function( data, status, xhr ) {
            table.rows( $('#table tr.active') ).remove().draw(false);
        }
    });
});
```

For more information please check this link.

Body:
when i try to remove row from datatable
I simply use this

    var table = $('#tbl').DataTable();
   table.rows().remove().draw();

its working but if i set datatable

"processing": true,"serverSide": true

than

table.rows().remove().draw();

it will not remove any row form datatable

Body:
Method rows.remove() is pure client side. If you enable serverSide: true then you need to handle deletions manually. For example use Ajax to delete rows. Note that you need support from your server side also to remove rows.

Example code:

$('#delete').on('click', function() {
    var selectedRows = table.rows( $('#table tr.active') ).data().to$();

    $.ajax({
        url: url_to_delete_rows,
        method: 'POST',
        data: { rows: selectedRows.toArray() },
        dataType: 'json',
        success: function( data, status, xhr ) {
            table.rows( $('#table tr.active') ).remove().draw(false);
        }
    });
});

For more information please check this link.


问:
Databases design and primary key composed
I have a table named minibar_bill and i use it for keeping evidence of client's expenditure. I'm trying to build a hotel/pension system management.

I thought that i could make a table

Minibar_bill with (id_bill, id_minibar_product, id_client)

And i would like to add those info on an invoice based on bill_id...

How should i do it ?

I mean i want to have something like that:

```<code>Id_bill(1)
id_minibar_product(1,2,3)
id_client(123)
</code>```

So first 3 records will be :

```<code>1, 1, 123
1, 2, 123
1, 3, 123
</code>```

And i want the id_bill to be on invoice ... maybe i could switch id_product with id_bill

Where id_bill(1) - would be the first bill record in database
id_minibar_product(1,2,3) - would be product 1,2,3 which has been consumed by client
id_client(123) - client id which we use on invoice to collect data from Client table in order to print them on invoice( i will use C# for UI ).

What I have tried:

I've tried to make a db with field id_bill and id_product but i think it's a wrong approach since i made them a composed primary key and i cannot add them to foreign key in Invoice table.

答:
Here are some suggestions for your design:

It's a good idea to name things descriptively, but if you create a table called Minibar_bill, that's going to be inconsistent and short sighted if  you want to start charging in-room movies and in-room dining, services etc. to the room. I suggest you call it something more generic - remove Minibar from all of your table names.

You must never put comma separated values into a single field.

There are a million sales data models online, including, as already suggested, templates in MS Access. There's no point reinventing the wheel

I suggest you have something like this

```<code>Client                  A list of clients
Products                A list of products you can be billed for (not just minibar)
Bill                    A client has zero or more bills (usually one)
BillLine                A bill has zero ore more lines. Each line represents
                        One product being charged for on a bll
</code>```

So Bill is the header. It's up to you whether you add a column indicating when / if it is invoiced, paid etc., or whether you want to create a seperate invoicing module.

With regards to this comment:

What i wish for is to link Invoice to minibar_bill in order to have the status on a single Invoice of all products from minibar which have been bought by a customer.

If you have a seperate invoice table you can write the BillID to it to link it.

I'm not sure if you understand that all this info exists across different tables, and when, for example, you print an invoice, you go and collect all the info from across the tables at that time.

Body:
I have a table named minibar_bill and i use it for keeping evidence of client's expenditure. I'm trying to build a hotel/pension system management.

I thought that i could make a table

Minibar_bill with (id_bill, id_minibar_product, id_client)

And i would like to add those info on an invoice based on bill_id...

How should i do it ?

I mean i want to have something like that:

Id_bill(1)
id_minibar_product(1,2,3)
id_client(123)

So first 3 records will be :

1, 1, 123
1, 2, 123
1, 3, 123

And i want the id_bill to be on invoice ... maybe i could switch id_product with id_bill

Where id_bill(1) - would be the first bill record in database
id_minibar_product(1,2,3) - would be product 1,2,3 which has been consumed by client
id_client(123) - client id which we use on invoice to collect data from Client table in order to print them on invoice( i will use C# for UI ).

What I have tried:

I've tried to make a db with field id_bill and id_product but i think it's a wrong approach since i made them a composed primary key and i cannot add them to foreign key in Invoice table.

Body:
Here are some suggestions for your design:

It's a good idea to name things descriptively, but if you create a table called Minibar_bill, that's going to be inconsistent and short sighted if  you want to start charging in-room movies and in-room dining, services etc. to the room. I suggest you call it something more generic - remove Minibar from all of your table names.

You must never put comma separated values into a single field.

There are a million sales data models online, including, as already suggested, templates in MS Access. There's no point reinventing the wheel

I suggest you have something like this

Client                  A list of clients
Products                A list of products you can be billed for (not just minibar)
Bill                    A client has zero or more bills (usually one)
BillLine                A bill has zero ore more lines. Each line represents
                        One product being charged for on a bll

So Bill is the header. It's up to you whether you add a column indicating when / if it is invoiced, paid etc., or whether you want to create a seperate invoicing module.

With regards to this comment:

What i wish for is to link Invoice to minibar_bill in order to have the status on a single Invoice of all products from minibar which have been bought by a customer.

If you have a seperate invoice table you can write the BillID to it to link it.

I'm not sure if you understand that all this info exists across different tables, and when, for example, you print an invoice, you go and collect all the info from across the tables at that time.


问:
MongoDb query condition on comparing 2 fields
I have a collection T, with 2 fields: Grade1 and Grade2, and I want to select those with condition Grade1 > Grade2, how can I get a query like in MySQL?

```<code>Select * from T Where Grade1 > Grade2
</code>```

答:
You can use a $where. Just be aware it will be fairly slow (has to execute Javascript code on every record) so combine with indexed queries if you can.

```<code>db.T.find( { $where: function() { return this.Grade1 > this.Grade2 } } );
</code>```

or more compact:

```<code>db.T.find( { $where : "this.Grade1 > this.Grade2" } );
</code>```

UPD for mongodb v.3.6+

you can use $expr as described in recent answer

Body:
I have a collection T, with 2 fields: Grade1 and Grade2, and I want to select those with condition Grade1 > Grade2, how can I get a query like in MySQL?

Select * from T Where Grade1 > Grade2

Body:
You can use a $where. Just be aware it will be fairly slow (has to execute Javascript code on every record) so combine with indexed queries if you can.

db.T.find( { $where: function() { return this.Grade1 > this.Grade2 } } );

or more compact:

db.T.find( { $where : "this.Grade1 > this.Grade2" } );

UPD for mongodb v.3.6+

you can use $expr as described in recent answer


问:
Determining if a user input field is empty
I've looked at some of the answers here but for some reason, I can't get this to work. I want the user to grade something and if they input nothing in the required field and press "Grade", I want for it to alert something.

function Script() {
  var G = document.getElementById("gradevalue").value
  if (G == null || G == undefined) {
    window.alert("Please input a grade");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label id="grade">|Please grade on a scale from 1 to 10 (10 is the best!)
    <input id="gradevalue" type="text"; size="2"; maxlength="2">
    </label>
<input type="button" value="GRADE!" id="nota" onclick="Script()"></code>```

I'm very new at this, so please don't be too harsh.

答:
You are also must there, in JavaScript you can just check if the variable has a value assigned to it, if it doesn't then the bool expression will be false. I have done a quick CodePen with the working code https://codepen.io/robdavis/pen/bRVxdm</p>

```<code>function Script() {
  var g = document.getElementById("gradevalue").value

  if (!g) {
    window.alert("Please enter a Grade");
  }
}
</code>```

Body:
I've looked at some of the answers here but for some reason, I can't get this to work. I want the user to grade something and if they input nothing in the required field and press "Grade", I want for it to alert something.

function Script() {
  var G = document.getElementById("gradevalue").value
  if (G == null || G == undefined) {
    window.alert("Please input a grade");
  }
}

|Please grade on a scale from 1 to 10 (10 is the best!)
    <input id="gradevalue" type="text"; size="2"; maxlength="2">

<input type="button" value="GRADE!" id="nota" onclick="Script()">

I'm very new at this, so please don't be too harsh.

Body:
You are also must there, in JavaScript you can just check if the variable has a value assigned to it, if it doesn't then the bool expression will be false. I have done a quick CodePen with the working code https://codepen.io/robdavis/pen/bRVxdm

function Script() {
  var g = document.getElementById("gradevalue").value

  if (!g) {
    window.alert("Please enter a Grade");
  }
}


问:
Compare large MySQL tables
I need to make a comparison between two (or more) tables with around 60.000 rows and about 60 columns.

In these tables there are two values on which I want to run a query. The purpose of the query is to count the rows which exists in TABLE_A but don't exist in TABLE_B based on two values in the row.

I've ran the following query:

```<code>SELECT id
FROM table_a ta
WHERE NOT EXISTS (
  SELECT id
  FROM table_b tb
  WHERE ta.value1=tb.value1 AND ta.value2=tb.value2
)
</code>```

As said, I've tried the code above and some variations on it. But to run this query it takes ages before it's finished. I hope to find a solution which runs in under 10 seconds.

Next query I tried, and of which I thought was working:

```<code>SELECT value1, value2
FROM (
    SELECT ta.value1, ta.value2
    FROM table_a ta
    UNION ALL
    SELECT tb.value1, tb.value2
    FROM table_b tb
) result
GROUP BY value1, value2
HAVING COUNT(*) = 1
ORDER BY value1
</code>```

The code shows me all differences between the two tables. So if valueX exists in TABLE_A but not in TABLE_B it's shown and vice versa.

So in short, I want to get all rows from TABLE_A which are not present in TABLE_B based on two values in the row.

Hope someone can help, thanks!

答:
Why not use a join?

```<code>/* Create a table called NAMES */
CREATE TABLE NAMES(Id integer PRIMARY KEY, Name text, LastName text);
CREATE TABLE OTHERNAMES(Id integer PRIMARY KEY, Name text, LastName text);

/* Create few records in this table */
INSERT INTO NAMES VALUES(1,'Tom','Riddle');
INSERT INTO NAMES VALUES(2,'Lucy','I love');
INSERT INTO NAMES VALUES(3,'Frank','Frankly');
INSERT INTO NAMES VALUES(4,'Jane','Austen');
INSERT INTO NAMES VALUES(5,'Robert','Downey');

INSERT INTO OTHERNAMES VALUES(2,'Lucy','I love');
INSERT INTO OTHERNAMES VALUES(3,'Frank','Frankly');
INSERT INTO OTHERNAMES VALUES(4,'Jane','Austen');
INSERT INTO OTHERNAMES VALUES(5,'Robert','Downey');

select * from NAMES
LEFT JOIN OTHERNAMES on
    NAMES.Name = OTHERNAMES.Name
    AND Names.LastName = OTHERNAMES.LastName
where OTHERNAMES.id is null
</code>```

See it online http://sqlfiddle.com/#!9/640c53/1

If you use a LEFT JOIN Items that don't exist in the right table will be replaced with null entries, which can be filtered with a where.

I don't know how efficient that is with your 60.000 database but this usually does the trick for me.

Title: Compare large MySQL tables

Body:
I need to make a comparison between two (or more) tables with around 60.000 rows and about 60 columns.

In these tables there are two values on which I want to run a query. The purpose of the query is to count the rows which exists in TABLE_A but don't exist in TABLE_B based on two values in the row.

I've ran the following query:

SELECT id
FROM table_a ta
WHERE NOT EXISTS (
  SELECT id
  FROM table_b tb
  WHERE ta.value1=tb.value1 AND ta.value2=tb.value2
)

As said, I've tried the code above and some variations on it. But to run this query it takes ages before it's finished. I hope to find a solution which runs in under 10 seconds.

Next query I tried, and of which I thought was working:

SELECT value1, value2
FROM (
    SELECT ta.value1, ta.value2
    FROM table_a ta
    UNION ALL
    SELECT tb.value1, tb.value2
    FROM table_b tb
) result
GROUP BY value1, value2
HAVING COUNT(*) = 1
ORDER BY value1

The code shows me all differences between the two tables. So if valueX exists in TABLE_A but not in TABLE_B it's shown and vice versa.

So in short, I want to get all rows from TABLE_A which are not present in TABLE_B based on two values in the row.

Hope someone can help, thanks!

Body:
Why not use a join?

/* Create a table called NAMES */
CREATE TABLE NAMES(Id integer PRIMARY KEY, Name text, LastName text);
CREATE TABLE OTHERNAMES(Id integer PRIMARY KEY, Name text, LastName text);

/* Create few records in this table */
INSERT INTO NAMES VALUES(1,'Tom','Riddle');
INSERT INTO NAMES VALUES(2,'Lucy','I love');
INSERT INTO NAMES VALUES(3,'Frank','Frankly');
INSERT INTO NAMES VALUES(4,'Jane','Austen');
INSERT INTO NAMES VALUES(5,'Robert','Downey');

INSERT INTO OTHERNAMES VALUES(2,'Lucy','I love');
INSERT INTO OTHERNAMES VALUES(3,'Frank','Frankly');
INSERT INTO OTHERNAMES VALUES(4,'Jane','Austen');
INSERT INTO OTHERNAMES VALUES(5,'Robert','Downey');

select * from NAMES
LEFT JOIN OTHERNAMES on
    NAMES.Name = OTHERNAMES.Name
    AND Names.LastName = OTHERNAMES.LastName
where OTHERNAMES.id is null

See it online http://sqlfiddle.com/#!9/640c53/1

If you use a LEFT JOIN Items that don't exist in the right table will be replaced with null entries, which can be filtered with a where.

I don't know how efficient that is with your 60.000 database but this usually does the trick for me.


问:
@Input() issues
I'm trying to get data from a variable from another component, but so far it hasn't been working.

The idea is that when I check a checkbox, the variables (Booleans) become true and some things on my page are visible and vice versa.

So basically I want the variables from InstellingenComponent to work in AfdelingDetailComponent. With @Input() it's not working... I'm getting undefined.

Here is my settings component:

```<code>export class InstellingenComponent implements OnInit {

  toonNaam = false;
  toonTijd = false;
  toonType = false;
  toonSanitair = false;
  toonKinder = false;
  toonSalon = false;
  toonKamerNummer = false;
  hulpKleur = "red";
  behandelKleur = "orange";
  volKleur = "green";
  leegKleur = "white";
</code>```

my settings html: (yes it's a dialog)

```<code><h1 md-dialog-title>Instellingen</h1>
<div md-dialog-content>Welke gegevens wil je zien? </div>
<md-checkbox class="check-margin" [(ngModel)]="toonKamerNummer">Kamernummer</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonNaam">Patiëntnaam</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonTijd">Tijdstip behandeling</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonType">Type behandeling</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonSanitair">sanitair</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonKinder">Kinderverzorgingsruimte</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonSalon">Salon</md-checkbox>
<div md-dialog-actions>
  <button md-button md-dialog-close="Option 1">Sluiten</button>

 </div>
  <app-afdelingdetail
    [toonKamerNummer]="toonKamerNummer"
    [toonNaam]="toonNaam"
    [toonTijd]="toonTijd"
    [toonType]="toonType"
    [toonSanitair]="toonSanitair"
    [toonKinder]="toonKinder"
    [toonSalon]="toonSalon"
    [behandelKleur]="behandelKleur"
    [hulpKleur]="hulpKleur"
    [leegKleur]="leegKleur"
    [volKleur]="volKleur"
  >
  </app-afdelingdetail>
</code>```

The other component with the inputs:

```<code> export class AfdelingdetailComponent implements OnInit {

  @Input() toonNaam:boolean;
  @Input() toonTijd:boolean;
  @Input() toonType:boolean;
  @Input() toonSanitair:boolean;
  @Input() toonKinder:boolean;
  @Input() toonSalon:boolean;
  @Input() toonKamerNummer:boolean;
  @Input() hulpKleur;
  @Input() behandelKleur;
  @Input() volKleur;
  @Input() leegKleur;
}
</code>```

And the html of the other component to give you an idea of what I want to do:

```<code><div class="container" *ngIf="selectedAfdeling"
fxLayout
fxLayout.xs="column"
fxLayoutAlign="center"
fxLayoutGap="10px"
fxLayoutGap.xs="0">
  <div *ngFor="let kamer of selectedAfdeling.kamers">
    <a  [routerLink]="['/patient', kamer.id]">
      <div class="kamer" [style.width.px]="kamer.width" [style.height.px]="kamer.height"
           [style.background-color]="getColor(kamer)">
        <div *ngIf="toonKamerNummer" id="kamernummer">Kamer {{kamer.kamernummer}}</div>
        <div *ngIf="toonNaam">{{kamer.naam}}</div>
        <div *ngIf="toonType">{{kamer.behandelingstype}}</div>
        <div *ngIf="toonTijd">{{kamer.behandelingstijd}}</div>
        <div *ngIf="toonSanitair && kamer.sanitair">
          <md-icon>wc</md-icon>
        </div>
        <div *ngIf="toonKinder && kamer.kinderverzorgingsruimte"><md-icon>child_care</md-icon></div>
        <div *ngIf="toonSalon && kamer.salon"><md-icon>event_seat</md-icon></div>
      </div>
    </a>

</div>
</div>
</code>```

答:
New answer

Ok, apparently it is about the way you bind a value with the Angular Material checkboxes. I tried with [(ngModel)] And I failed miserably too.

You should get rid of [(ngModel)] binding (IMHO), and bind your variables like this :

In your template :

```<code><md-checkbox [checked]="myVariable" (change)="myVariable=!myVariable">Check me!</md-checkbox>
</code>```

Don't forget to declare AND initialise your variable in the component :

```<code>myVariable: boolean = false; // or true
</code>```

It won't work as is if the variable is not initialized.

See this plunker : https://plnkr.co/edit/CFLsnh2MDreiEDXKfnXc?p=preview

Thanks to this related question :
Angular 2 Checkbox Two Way Data Binding

and to Angular Material doc here :
https://material.angular.io/components/component/checkbox

ContentLicense: CC BY-SA 4.0

Title: @Input() issues

Body:
I'm trying to get data from a variable from another component, but so far it hasn't been working.

The idea is that when I check a checkbox, the variables (Booleans) become true and some things on my page are visible and vice versa.

So basically I want the variables from InstellingenComponent to work in AfdelingDetailComponent. With @Input() it's not working... I'm getting undefined.

Here is my settings component:

export class InstellingenComponent implements OnInit {

  toonNaam = false;
  toonTijd = false;
  toonType = false;
  toonSanitair = false;
  toonKinder = false;
  toonSalon = false;
  toonKamerNummer = false;
  hulpKleur = "red";
  behandelKleur = "orange";
  volKleur = "green";
  leegKleur = "white";

my settings html: (yes it's a dialog)

Instellingen

Welke gegevens wil je zien?

<md-checkbox class="check-margin" [(ngModel)]="toonKamerNummer">Kamernummer</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonNaam">Patiëntnaam</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonTijd">Tijdstip behandeling</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonType">Type behandeling</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonSanitair">sanitair</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonKinder">Kinderverzorgingsruimte</md-checkbox>
<md-checkbox class="check-margin" [(ngModel)]="toonSalon">Salon</md-checkbox>

  <button md-button md-dialog-close="Option 1">Sluiten</button>

  <app-afdelingdetail
    [toonKamerNummer]="toonKamerNummer"
    [toonNaam]="toonNaam"
    [toonTijd]="toonTijd"
    [toonType]="toonType"
    [toonSanitair]="toonSanitair"
    [toonKinder]="toonKinder"
    [toonSalon]="toonSalon"
    [behandelKleur]="behandelKleur"
    [hulpKleur]="hulpKleur"
    [leegKleur]="leegKleur"
    [volKleur]="volKleur"
  >
  </app-afdelingdetail>

The other component with the inputs:

 export class AfdelingdetailComponent implements OnInit {

  @Input() toonNaam:boolean;
  @Input() toonTijd:boolean;
  @Input() toonType:boolean;
  @Input() toonSanitair:boolean;
  @Input() toonKinder:boolean;
  @Input() toonSalon:boolean;
  @Input() toonKamerNummer:boolean;
  @Input() hulpKleur;
  @Input() behandelKleur;
  @Input() volKleur;
  @Input() leegKleur;
}

And the html of the other component to give you an idea of what I want to do:

Kamer {{kamer.kamernummer}}

{{kamer.naam}}

{{kamer.behandelingstype}}

{{kamer.behandelingstijd}}

          <md-icon>wc</md-icon>

<md-icon>child_care</md-icon>

<md-icon>event_seat</md-icon>

Body:
New answer

Ok, apparently it is about the way you bind a value with the Angular Material checkboxes. I tried with [(ngModel)] And I failed miserably too.

You should get rid of [(ngModel)] binding (IMHO), and bind your variables like this :

In your template :

<md-checkbox [checked]="myVariable" (change)="myVariable=!myVariable">Check me!</md-checkbox>

Don't forget to declare AND initialise your variable in the component :

myVariable: boolean = false; // or true

It won't work as is if the variable is not initialized.

See this plunker : https://plnkr.co/edit/CFLsnh2MDreiEDXKfnXc?p=preview

Thanks to this related question :
Angular 2 Checkbox Two Way Data Binding

and to Angular Material doc here :
https://material.angular.io/components/component/checkbox


问:
Parse PHP variable in html template
I know it has been discussed many times, but I can not find any solution to this problem.

I have a PHP file with the following code

```<code>if (file_exists("email.html")) {
        $message = file_get_contents("email.html");
    } else {
        echo "No email.html file present";
        return;
    }
</code>```

in my file email.html I have something like:

```<code>  <p>Hello %recipient.UserName%, you receive this Email because you signed up at our site.</p>
</code>```

variable $UserName is declared in the php file (in array).

When looking at the html file output, I see the variable is not correctly passed and stays as % %

Any suggestion?
thanks!

答:
If you don't have a template engine you can't do it with % % OR other symbol . for your question simple approach is to use it like this :

```<code>  <p>Hello <? = $recipient['UserName'] ?>, you receive this Email because you signed up at our site.</p>
</code>```

EDIT

you have to include the file

```<code>ob_start();
include "email.html";
$message = ob_get_clean();
</code>```

Title: Parse PHP variable in html template

Body:
I know it has been discussed many times, but I can not find any solution to this problem.

I have a PHP file with the following code

if (file_exists("email.html")) {
        $message = file_get_contents("email.html");
    } else {
        echo "No email.html file present";
        return;
    }

in my file email.html I have something like:

Hello %recipient.UserName%, you receive this Email because you signed up at our site.

variable $UserName is declared in the php file (in array).

When looking at the html file output, I see the variable is not correctly passed and stays as % %

Any suggestion?
thanks!

Body:
If you don't have a template engine you can't do it with % % OR other symbol . for your question simple approach is to use it like this :

  <p>Hello <? = $recipient['UserName'] ?>, you receive this Email because you signed up at our site.</p>

EDIT

you have to include the file

ob_start();
include "email.html";
$message = ob_get_clean();


问:
AutoItX Can't load library jacob-1.18-M2-x64.dll
I'm trying to run AutoItX in a Java project. I can't find any useful guide to add .dlls to my project using IntelliJ. I added the .jars & .dlls I need in the File > Project Project Structure > Libraries but I still get the following error:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: Can't load library: C:\Users\mihai\Desktop\Autoit\lib\jacob-1.18-M2-x64.dll
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1827)
at java.lang.Runtime.load0(Runtime.java:809)
at java.lang.System.load(System.java:1086)
at com.jacob.com.LibraryLoader.loadJacobLibrary(LibraryLoader.java:151)
at com.jacob.com.JacobObject.<clinit>(JacobObject.java:110)
at autoitx4java.AutoItX.<init>(AutoItX.java:181)
at TestClass.main(TestClass.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code>```

答:
Solved the issue by adding the folder containing the .dll at Run > Debug > Add new Configuration then I added the main class and in the VM options I added

```<code>-Djul.library.dir="C:\Users\mihai\Desktop\Autoit\lib"
</code>```

Body:
I'm trying to run AutoItX in a Java project. I can't find any useful guide to add .dlls to my project using IntelliJ. I added the .jars & .dlls I need in the File > Project Project Structure > Libraries but I still get the following error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: Can't load library: C:\Users\mihai\Desktop\Autoit\lib\jacob-1.18-M2-x64.dll
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1827)
at java.lang.Runtime.load0(Runtime.java:809)
at java.lang.System.load(System.java:1086)
at com.jacob.com.LibraryLoader.loadJacobLibrary(LibraryLoader.java:151)
at com.jacob.com.JacobObject.<clinit>(JacobObject.java:110)
at autoitx4java.AutoItX.<init>(AutoItX.java:181)
at TestClass.main(TestClass.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Body:
Solved the issue by adding the folder containing the .dll at Run > Debug > Add new Configuration then I added the main class and in the VM options I added

-Djul.library.dir="C:\Users\mihai\Desktop\Autoit\lib"


问:
MySQL SELECT NOT IN
I have table:

```<code>+----+--------------+--------------------------+
| id | user         | mac                      |
+----+--------------+--------------------------+
|  3 | user003      | 148fc78371212b           |
|  4 | user004      |                          |
|  5 | user005      | 171248fc78312d           |
|  6 | user006      | 212e148fc78371           |
+----+--------------+--------------------------+
</code>```

I need to select only ID if mac encrypted value NOT EXISTS duplicate in row mac.

If for example:

user003 is having edit on form gui and leave old encrypted mac address 148fc78371212b it needs to get count from result in mysql 1

user003 is having edit on form gui and enter new encrypted mac address 212e148fc78371 it needs to get count from result in mysql 0 (so that i can then alert message Duplicate MAC address)

i need query that checks if user does not change its own mac address to allow editing (return 1) and if user change mac address and that address exists in mac address for another user (return 0) MAC address exists.

I try using this:

```<code>SELECT mac FROM users
WHERE user='user003' AND mac='148fc78371212b' OR mac NOT IN (SELECT mac FROM users);
</code>```

But i always get count result 1...i could not figure out how to archive above result?

So my query needs to look like this in theory:

```<code>SELECT mac FROM users WHERE user=? AND mac=? AND MAC DOES NOT EXISTS IN MAC
FIELD EXCEPT WHERE user=? AND mac=? (so to exclude searching duplicate mac
on defined user)
</code>```

答:
If there is just one record per user and if mac is also unique, then you can use the following query:

```<code>SELECT mac,
       CASE
          WHEN user_with_newmac IS NULL THEN 2
          WHEN user_with_newmac = user THEN 1
          ELSE 0
       END AS flag
FROM (
   SELECT mac,
          user,
          (SELECT user FROM users WHERE mac = ? ) AS user_with_newmac
   FROM users
   WHERE user = ?) AS t
</code>```

The subquery (SELECT user FROM users WHERE mac = ? ) returns the user (if any) having the new value of the mac address. The outer query uses this value to calculate the flag:

If user_with_mac is NULL, then the new mac address does not exist at all yet. So, 2 is returned.

If user_with_mac = user, then the mac address has not changed and 1 is returned.

Otherwise, if user_with_mac <> user, then some other user has the mac address, so 0 is returned.

Demo here

Title: MySQL SELECT NOT IN

Body:
I have table:

+----+--------------+--------------------------+
| id | user         | mac                      |
+----+--------------+--------------------------+
|  3 | user003      | 148fc78371212b           |
|  4 | user004      |                          |
|  5 | user005      | 171248fc78312d           |
|  6 | user006      | 212e148fc78371           |
+----+--------------+--------------------------+

I need to select only ID if mac encrypted value NOT EXISTS duplicate in row mac.

If for example:

user003 is having edit on form gui and leave old encrypted mac address 148fc78371212b it needs to get count from result in mysql 1

user003 is having edit on form gui and enter new encrypted mac address 212e148fc78371 it needs to get count from result in mysql 0 (so that i can then alert message Duplicate MAC address)

i need query that checks if user does not change its own mac address to allow editing (return 1) and if user change mac address and that address exists in mac address for another user (return 0) MAC address exists.

I try using this:

SELECT mac FROM users
WHERE user='user003' AND mac='148fc78371212b' OR mac NOT IN (SELECT mac FROM users);

But i always get count result 1...i could not figure out how to archive above result?

So my query needs to look like this in theory:

SELECT mac FROM users WHERE user=? AND mac=? AND MAC DOES NOT EXISTS IN MAC
FIELD EXCEPT WHERE user=? AND mac=? (so to exclude searching duplicate mac
on defined user)

Body:
If there is just one record per user and if mac is also unique, then you can use the following query:

SELECT mac,
       CASE
          WHEN user_with_newmac IS NULL THEN 2
          WHEN user_with_newmac = user THEN 1
          ELSE 0
       END AS flag
FROM (
   SELECT mac,
          user,
          (SELECT user FROM users WHERE mac = ? ) AS user_with_newmac
   FROM users
   WHERE user = ?) AS t

The subquery (SELECT user FROM users WHERE mac = ? ) returns the user (if any) having the new value of the mac address. The outer query uses this value to calculate the flag:

If user_with_mac is NULL, then the new mac address does not exist at all yet. So, 2 is returned.

If user_with_mac = user, then the mac address has not changed and 1 is returned.

Otherwise, if user_with_mac <> user, then some other user has the mac address, so 0 is returned.

Demo here


问:
Array of Task in Project VBA
I am trying to store Tasks in an Array but all my code (below) stores is the index of that task. How can I store all of the Task features in an array? Thanks.

```<code>Private Sub Project_Change(ByVal pj As Project)

            Dim tsk As Task
            Dim ol As Outlook.Application
            Dim mail As Outlook.MailItem
            Dim TarefasAtrasadas() As Variant

            'tsk.Flag1 = Activar Aviso Email?
            'tsk.Flag2 = Aviso Email
            i = 0
            For Each tsk In ActiveProject.Tasks
                If tsk.Flag1 = True And tsk.PercentComplete < 100 Then
                    If delayedTsk(tsk) = 1 Then
                        ReDim Preserve TarefasAtrasadas(i)
                        TarefasAtrasadas(i) = tsk
                        i = i + 1
                    End If
                End If
            Next tsk
End sub
</code>```

答:
I haven't tried it but

```<code>SET TarefasAtrasadas(i) = tsk
</code>```

might work. If not, use a collection.

Title: Array of Task in Project VBA

Body:
I am trying to store Tasks in an Array but all my code (below) stores is the index of that task. How can I store all of the Task features in an array? Thanks.

Private Sub Project_Change(ByVal pj As Project)

            Dim tsk As Task
            Dim ol As Outlook.Application
            Dim mail As Outlook.MailItem
            Dim TarefasAtrasadas() As Variant

            'tsk.Flag1 = Activar Aviso Email?
            'tsk.Flag2 = Aviso Email
            i = 0
            For Each tsk In ActiveProject.Tasks
                If tsk.Flag1 = True And tsk.PercentComplete < 100 Then
                    If delayedTsk(tsk) = 1 Then
                        ReDim Preserve TarefasAtrasadas(i)
                        TarefasAtrasadas(i) = tsk
                        i = i + 1
                    End If
                End If
            Next tsk
End sub

Body:
I haven't tried it but

SET TarefasAtrasadas(i) = tsk

might work. If not, use a collection.


问:
Wait for an event to occur within a function in Javascript for Skulpt
I want to change the Sk.inputfun() for Skulpt to let the user type in a <textarea> and hit the ENTER key to submit. I need to pass in a single function to Skulpt that gets user input, however, I can't find any way to do this other than prompt().

The only way I could think to do this was to delay the return using setTimeout() until an event triggered the enter key button and changed a flag.

```<code>var enterPressed = false;
$("#output").keyup(function(e){
    if((e.keyCode || e.which) == 13) { //Enter keycode
      enterPressed = true;
    }
});
</code>```

and then to wait for the change I had:

```<code> Sk.configure({
    inputfun: function (prompt) {
       function checkFlag() {
          if(enterPressed) {
             enterPressed = false
             return $('#output').val();
          } else {
             window.setTimeout(checkFlag, 100);
          }
       }
       return checkFlag();
    },
    inputfunTakesPrompt: true,
    output: outf,
    read: builtinRead
 });
</code>```

However this dosen't work for a few reasons. a) The timeout function can't return a value, and b) Timeout dosen't even delay the return function, and it simply returns nothing.

I have tried using .done() as well, but couldn't get it to work.

There doesn't seem to be any way to do this that I could find online, any help would be much appreciated!

答:
You need to return a Promise from your inputfun, which you then resolve when return gets pressed. (If you're not familiar with Promises, they are well worth a look - <grossSimplification>they let you write asynchronous code using synchronous logic</grossSimplification>).

Something like this (using your code as a base):

Sk.configure({
   inputfun: function () {
      // the function returns a promise to give a result back later...
      return new Promise(function(resolve,reject){
         $("#input").on("keyup",function(e){
             if (e.keyCode == 13)
             {
                 // remove keyup handler from #output
                 $("#input").off("keyup");
                 // resolve the promise with the value of the input field
                 resolve($("#input").val());
             }
         })
      })
   },
   output: outf,
   read: builtinRead
});
```

I've assumed an input element with an ID of input is receiving stdin. Looking at your OP, you were talking about a textarea (although JQuery .val() should work fine on this). On the basis of what you've called your textarea ("output") it seems that your intention was for both stdin and stdout to involve a shared textarea. If so, I'm not sure how you're going to be able to distinguish between what's been generated by stdin and what's been (subsequently) entered by the user. Thus the code above assumes a separate input field.

I had a similar use case to you, and the way I gave the illusion of an integrated console for both stdin and stdout was to have a span with contenteditable at the end of my output div. On keycode == 13, before I resolved the promise and sent back what the user had typed, I took the text out of the input span and appended it to the output div.

Body:
I want to change the Sk.inputfun() for Skulpt to let the user type in a <textarea> and hit the ENTER key to submit. I need to pass in a single function to Skulpt that gets user input, however, I can't find any way to do this other than prompt().

The only way I could think to do this was to delay the return using setTimeout() until an event triggered the enter key button and changed a flag.

var enterPressed = false;
$("#output").keyup(function(e){
    if((e.keyCode || e.which) == 13) { //Enter keycode
      enterPressed = true;
    }
});

and then to wait for the change I had:

 Sk.configure({
    inputfun: function (prompt) {
       function checkFlag() {
          if(enterPressed) {
             enterPressed = false
             return $('#output').val();
          } else {
             window.setTimeout(checkFlag, 100);
          }
       }
       return checkFlag();
    },
    inputfunTakesPrompt: true,
    output: outf,
    read: builtinRead
 });

However this dosen't work for a few reasons. a) The timeout function can't return a value, and b) Timeout dosen't even delay the return function, and it simply returns nothing.

I have tried using .done() as well, but couldn't get it to work.

There doesn't seem to be any way to do this that I could find online, any help would be much appreciated!

Body:
You need to return a Promise from your inputfun, which you then resolve when return gets pressed. (If you're not familiar with Promises, they are well worth a look - <grossSimplification>they let you write asynchronous code using synchronous logic</grossSimplification>).

Something like this (using your code as a base):

Sk.configure({
   inputfun: function () {
      // the function returns a promise to give a result back later...
      return new Promise(function(resolve,reject){
         $("#input").on("keyup",function(e){
             if (e.keyCode == 13)
             {
                 // remove keyup handler from #output
                 $("#input").off("keyup");
                 // resolve the promise with the value of the input field
                 resolve($("#input").val());
             }
         })
      })
   },
   output: outf,
   read: builtinRead
});

I've assumed an input element with an ID of input is receiving stdin. Looking at your OP, you were talking about a textarea (although JQuery .val() should work fine on this). On the basis of what you've called your textarea ("output") it seems that your intention was for both stdin and stdout to involve a shared textarea. If so, I'm not sure how you're going to be able to distinguish between what's been generated by stdin and what's been (subsequently) entered by the user. Thus the code above assumes a separate input field.

I had a similar use case to you, and the way I gave the illusion of an integrated console for both stdin and stdout was to have a span with contenteditable at the end of my output div. On keycode == 13, before I resolved the promise and sent back what the user had typed, I took the text out of the input span and appended it to the output div.


问:
Why does H2O integrate TensorFlow via Spark instead of directly?
I really like H2O especially because you can deploy the built models easily into any Java / JVM application... This is also my goal for TensorFlow: Build models and then run them in Java applications.

H2O uses Spark (Sparking Water) "in the middle" when using TensorFlow by running TensorFlow on the distributed Spark nodes. I learned this (hopefully correctly) in a H2O demo video.

Why do you not integrate TensorFlow (and others like MXNet) directly with H2O, but instead go through Apache Spark?

Frameworks like TensorFlow itself allow distributed training, so why use Spark "in the middle"? Doesn't this increase complexity a lot (and no need for it in many scenarios)?

For example, Google built Scikit Flow (Scikit-learn + TensorFlow)to allow easy usage of TensorFlow to build models.

Especially for smaller data sets and / or simpler use cases, this seems to be the easier option that using Spark in the middle? If I understand correctly, you could also use this model in Java then via TensorFlow4Java.

I want to leverage H2O much more in future projects and scenarios (like in the past, see e.g. here where I applied a H2O model to real time applications using Apache Kafka and its Streams API).
Though, I am not sure why I need the "overhead" of Spark for building models with H2O and TensorFlow (especially for smaller data sets and / or simple scenarios where a "small neural network" might be good enough?

答:
That is an old tutorial, which was made before distributed Tensorflow was released. At that time this was the easiest way to "integrate"/"distribute" it (by simply running TF on each worker node and then averaging the coefficients on the driver node).

Since then we have released project DeepWater which integrates several DL frameworks (TF, MXNet, Caffee) with H2O. This one doesn't require Spark, all you need to do (if you're running a linux machine) is to download H2O from here (H2O with GPU-Enabled Machine Learning) and run it. If you're running MacOS or Windows you'd have to build both DeepWater and H2O yourself as we don't provide those yet.

As a disclaimer: deepwater currently runs only on a single node, as none of the mentioned frameworks have Java APIs for distribution (for example TF only has Python API for that). I'm working on a distributed version but for now it's not really a #1 priority.


问:
how to spread out buttons, they are currently stacked?
I have a bunch of buttons on my page, my html is like:

```<code><div>
  <input ..>
  <input ...>
</dvi>
</code>```

They are currently just stacking up on each other, I want them all on one horizontal line spread out.

I tried doing:

display:inline

on the outer div, but that didn't work.

答: Try display:inline or float:left on the inputs.

Body:
I have a bunch of buttons on my page, my html is like:

  <input ..>
  <input ...>
</dvi>

They are currently just stacking up on each other, I want them all on one horizontal line spread out.

I tried doing:

display:inline

on the outer div, but that didn't work.


问:
Generate mobile builds using visual studio for windows, android and iOS
Was using Intel XDK tool to build an cordova mobile app. The XDK used to provide .apk , ipa and appxupload files(universal app) for each of the store.
Now that Intel XDK is on an EOL path, I wanted to set up the code in Visual Studio to generate the builds.
I selected BLankCordova app and replaced the www folder. Am able to develop and debug using the emulator.
However how do i generate the builds for windows and android?
In the config file I can specify the name of the app and version, but where to add the publisher ID
Similarly for android , how to choose the developer certificate?

Thanks for your help

答:
To be able to correctly package and sign Windows apps there are few things required:

A signing certificate

Identity details matching the provided signing certificate

I am not sure if the options are there in visual studio. But u can do in command line using (ex- Windows platform)-

```<code>cordova build -- --packageCertificateKeyFile="platforms\windows\CordovaApp_TemporaryKey.pfx" --packageThumbprint="ABCABCABCABC123123123123"
</code>```

Alternatively, these values could be specified using a build configuration file (build.json) using CLI (--buildConfig). A sample build configuration file:

```<code>{
"windows": {
    "debug": {
        "packageCertificateKeyFile": "platforms\\windows\\CordovaApp_TemporaryKey.pfx"
    },
    "release": {
        "packageCertificateKeyFile": "c:\\path-to-key\\keycert.pfx",
        "packageThumbprint": "ABCABCABCABC123123123123",
        "publisherId": "CN=FakeCorp.com, L=Redmond, S=Washington, C=US"
    }
}}
</code>```

For creating certificate keys -

certutil -user -p PASSWORD -importPFX FakeCorp.com.pfx

NOTE : Signing is required for distributing and installing Windows Store apps. This process is normally handled by Visual Studio when you deploy a package for release.

Please refer Platform Guides of cordova like this(windows).
Signing an Android App in cordova is given here.

Body:
To be able to correctly package and sign Windows apps there are few things required:

A signing certificate

Identity details matching the provided signing certificate

I am not sure if the options are there in visual studio. But u can do in command line using (ex- Windows platform)-

cordova build -- --packageCertificateKeyFile="platforms\windows\CordovaApp_TemporaryKey.pfx" --packageThumbprint="ABCABCABCABC123123123123"

Alternatively, these values could be specified using a build configuration file (build.json) using CLI (--buildConfig). A sample build configuration file:

{
"windows": {
    "debug": {
        "packageCertificateKeyFile": "platforms\\windows\\CordovaApp_TemporaryKey.pfx"
    },
    "release": {
        "packageCertificateKeyFile": "c:\\path-to-key\\keycert.pfx",
        "packageThumbprint": "ABCABCABCABC123123123123",
        "publisherId": "CN=FakeCorp.com, L=Redmond, S=Washington, C=US"
    }
}}

For creating certificate keys -

certutil -user -p PASSWORD -importPFX FakeCorp.com.pfx

NOTE : Signing is required for distributing and installing Windows Store apps. This process is normally handled by Visual Studio when you deploy a package for release.

Please refer Platform Guides of cordova like this(windows).
Signing an Android App in cordova is given here.


问:
How to send a message with "\0" to a Server via TCP
I've managed to create a connection between my Program(client) and a Server.
Now I want to send the following Text "TOR\0". The Server explicit needs this Info for starting an Operation.
The problem is, that everytime I try to define the text

```<code>char a[]="TOR\0";
</code>```

My client only sends three bytes... Without the NULL at the end.

I can send 5 different Characters like {"T","O","R","\","0"}, but I know I need 4 Bytes of Data. I also know the four Bytes need to have  the information "T", "O", "R", "\0". But everytime I try sending this my cpp only sends "T", "O", "R", because it stops reading at the NULL which represents the end of line.

I also tried fixing the length in the send-function. I know I have to specify the length by sending it. But by fixing the length on 4 doesn't work. I use this to see if it worked:

```<code>Result = send( ConnectSocket, a, (int)strlen(a), 0 );
cout << Result << endl;
</code>```

How do I attache the NULL at the end of the text without causing it C++ to stop reading the message at that exact point?

答:
String "TOR\0" has 5 characters for you, however C++ - in the same way as C - understands every sequence of \<character> as a single special character. So \0 is one single character NULL (code 0).

This notation is superfluous, as every string in C/C++ written as "string" has terminating NULL. For example "abc" is equivalent of {'a','b','c','\0'}. So "TOR\0" means {'T','O','R','\0','\0'}.

The strlen function returns the length of string defined as a number of characters from beginning of the string before NULL terminator. So, strlen("TOR\0") == 3 because there are three characters before NULL.

If you intention is to send literal characters as you wrote them: 'T', 'O', 'R', backslash and '0', you can do that in one of those ways:

```<code>char a[]={'T','O','R','\\','0','\0'};
char a[]="TOR\\0";
</code>```

Please mind the \\ which is interpreted by C/C++ as single backslash.

Body:
I've managed to create a connection between my Program(client) and a Server.
Now I want to send the following Text "TOR\0". The Server explicit needs this Info for starting an Operation.
The problem is, that everytime I try to define the text

char a[]="TOR\0";

My client only sends three bytes... Without the NULL at the end.

I can send 5 different Characters like {"T","O","R","\","0"}, but I know I need 4 Bytes of Data. I also know the four Bytes need to have  the information "T", "O", "R", "\0". But everytime I try sending this my cpp only sends "T", "O", "R", because it stops reading at the NULL which represents the end of line.

I also tried fixing the length in the send-function. I know I have to specify the length by sending it. But by fixing the length on 4 doesn't work. I use this to see if it worked:

Result = send( ConnectSocket, a, (int)strlen(a), 0 );
cout << Result << endl;

How do I attache the NULL at the end of the text without causing it C++ to stop reading the message at that exact point?

Body:
String "TOR\0" has 5 characters for you, however C++ - in the same way as C - understands every sequence of \<character> as a single special character. So \0 is one single character NULL (code 0).

This notation is superfluous, as every string in C/C++ written as "string" has terminating NULL. For example "abc" is equivalent of {'a','b','c','\0'}. So "TOR\0" means {'T','O','R','\0','\0'}.

The strlen function returns the length of string defined as a number of characters from beginning of the string before NULL terminator. So, strlen("TOR\0") == 3 because there are three characters before NULL.

If you intention is to send literal characters as you wrote them: 'T', 'O', 'R', backslash and '0', you can do that in one of those ways:

char a[]={'T','O','R','\\','0','\0'};
char a[]="TOR\\0";

Please mind the \\ which is interpreted by C/C++ as single backslash.


问:
How can I access all users from database?
Im using firebase database to save my coordinates.

this is how my database looks like:

I'm saving data by token:

```<code>        String token = FirebaseInstanceId.getInstance().getToken();
        if (token == null) return;
        databaseReference = FirebaseDatabase.getInstance().getReference(token);`
</code>```

So I need to access coordinates and add marker to a map

I'm doing it in valueEventListener in onMapReady method:

```<code>    DatabaseReference ref = FirebaseDatabase.getInstance().getReference(FirebaseInstanceId.getInstance().getToken());
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            double allLat = (double) dataSnapshot.child("lat").getValue();
            double allLng = (double) dataSnapshot.child("lng").getValue();

            mMap.addMarker(new MarkerOptions().position(new LatLng(allLat, allLng)).title("Пользователь"));
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(MapsActivity.this, "Не найдены пользователи", Toast.LENGTH_SHORT).show();
        }
    });
</code>```

but it set me only my marker, how I can access all users from my database?

答:
You have to loop through your values, inside your onDataChange():

```<code>for(DataSnapshot child : dataSnapshot.getChildren() ){
            //get your mulitple markers here
        }
</code>```

Body:
Im using firebase database to save my coordinates.

this is how my database looks like:

I'm saving data by token:

        String token = FirebaseInstanceId.getInstance().getToken();
        if (token == null) return;
        databaseReference = FirebaseDatabase.getInstance().getReference(token);`

So I need to access coordinates and add marker to a map

I'm doing it in valueEventListener in onMapReady method:

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference(FirebaseInstanceId.getInstance().getToken());
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            double allLat = (double) dataSnapshot.child("lat").getValue();
            double allLng = (double) dataSnapshot.child("lng").getValue();

            mMap.addMarker(new MarkerOptions().position(new LatLng(allLat, allLng)).title("Пользователь"));
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(MapsActivity.this, "Не найдены пользователи", Toast.LENGTH_SHORT).show();
        }
    });

but it set me only my marker, how I can access all users from my database?

Body:
You have to loop through your values, inside your onDataChange():

for(DataSnapshot child : dataSnapshot.getChildren() ){
            //get your mulitple markers here
        }


问:
Adding links to text from an html textarea
Is this possible? What I would like to do is designate certain text that the user writes in a text area as a link. This text is inserted into a MySQL database then pulled, and displayed elsewhere. Also the links will never really be in the same spot.</p>

答:
You could could use jQuery to grab the value of the textarea on change and use ajax to send it to a php page which logs it to a mysql db, then use jQuery setInterval/ajax combo to pull back results from the php/mysql to put elsewhere on your page :)

Also you can construct the link in the php then just send back html to your page


问:
How to Use Virtual Mode for large data in DataGridView
I am posting to see if there is a way to improve some legacy code. The code will populate a DataGridView with x amount of rows. Initially, the code worked fine as the populating data was of a small quantity. However, there has been an extreme increase in data and I am finding that the performance in populating the DataGridView to be very slow.

Basically, I know there are several considerations (Virtual Mode, for instance). However, the approach that I want to take is using an array or List (and then convert it to an array) and add the range of the row by calling Rows.AddRange(array). However, I am having trouble implementing it.

As it stands, this is what code exists:

```<code>if (value !=0)
{
 int row = 0;
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}

if (valueTwo !=0)
{
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}
</code>```

So, this is not efficient at all, of course. I know .AddRow() is a taxing method in itself and individually adding rows, one-by-one is not great.

I have tried something like:

```<code>object[] data = {"Test", 9, "Test Two", "Test Three"};
List<DataGridViewRow> list = new List<DataGridViewRow>();
for (int i = 0; i < data.Length; i++)
{
  DataGridViewRow row = new DataGridViewRow();
  row.SetValues(data[i]);
  list.Add(row);
 }
 dataGridViewRow1.Rows.AddRange(list.ToArray());
</code>```

However, doing this gets me a NullPointerException on the SetValues line.

I understand that the best way of doing this is either make a DataTable or use Virtual Mode but I want to try out using this method of adding the range and passing in a container for the data, rather than adding a row.

I hope I am clear with my explanation. Let me know if I need to further explain.

EDIT: I think using Virtual Mode is the best way to go. I am not sure how to really do it, though. I checked MSN's tutorial but I was slightly confused by it. If I were to implement Virtual Mode for 100,000 rows, how would I go about doing it. Nothing really fancy, just displaying a total of 10,000 rows.

答:
Try to use a BindingList that you populate with your data, you can have a class to map the propreties or use a dynamic one. You have to frist create the cols so you can Bind de data: here´s one example:</p>

```<code>        DataGridViewCell cell = new DataGridViewTextBoxCell();
        DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()
        {
            CellTemplate = cell,
            Name = "Value1",
            HeaderText = "Value 1",
            DataPropertyName = "Col1"
        };

        DataGridViewCell cell2 = new DataGridViewTextBoxCell();
        DataGridViewTextBoxColumn colFileName2 = new DataGridViewTextBoxColumn()
        {
            CellTemplate = cell2,
            Name = "Value2",
            HeaderText = "Value 2",
            DataPropertyName = "Col2"
        };
        dataGridView1.Columns.Add(colFileName);
        dataGridView1.Columns.Add(colFileName2);

        List<DataPopulate> list = new List<DataPopulate>();
        list.Add(new DataPopulate() { Col1 = "tes1", Col2 = "teste2"});
        list.Add(new DataPopulate() { Col1 = "tes1", Col2 = "teste2" });
        list.Add(new DataPopulate() { Col1 = "tes1", Col2 = "teste2" });

        var dataPopulateList = new BindingList<DataPopulate>(list);

        dataGridView1.DataSource = dataPopulateList;
</code>```

Body:
I am posting to see if there is a way to improve some legacy code. The code will populate a DataGridView with x amount of rows. Initially, the code worked fine as the populating data was of a small quantity. However, there has been an extreme increase in data and I am finding that the performance in populating the DataGridView to be very slow.

Basically, I know there are several considerations (Virtual Mode, for instance). However, the approach that I want to take is using an array or List (and then convert it to an array) and add the range of the row by calling Rows.AddRange(array). However, I am having trouble implementing it.

As it stands, this is what code exists:

if (value !=0)
{
 int row = 0;
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}

if (valueTwo !=0)
{
 dataGridView1.AddRow();
 dataGridView1.Rows[row].Cells[0] = "Test";
 dataGridView1.Rows[row].Cells[1] = 9;
 dataGridView1.Rows[row].Cells[2] = "Test Two";
 dataGridView1.Rows[row].Cells[3] = "Test Three";
 row++;
}

So, this is not efficient at all, of course. I know .AddRow() is a taxing method in itself and individually adding rows, one-by-one is not great.

I have tried something like:

object[] data = {"Test", 9, "Test Two", "Test Three"};
List<DataGridViewRow> list = new List<DataGridViewRow>();
for (int i = 0; i < data.Length; i++)
{
  DataGridViewRow row = new DataGridViewRow();
  row.SetValues(data[i]);
  list.Add(row);
 }
 dataGridViewRow1.Rows.AddRange(list.ToArray());

However, doing this gets me a NullPointerException on the SetValues line.

I understand that the best way of doing this is either make a DataTable or use Virtual Mode but I want to try out using this method of adding the range and passing in a container for the data, rather than adding a row.

I hope I am clear with my explanation. Let me know if I need to further explain.

EDIT: I think using Virtual Mode is the best way to go. I am not sure how to really do it, though. I checked MSN's tutorial but I was slightly confused by it. If I were to implement Virtual Mode for 100,000 rows, how would I go about doing it. Nothing really fancy, just displaying a total of 10,000 rows.

Body:
Try to use a BindingList that you populate with your data, you can have a class to map the propreties or use a dynamic one. You have to frist create the cols so you can Bind de data: here´s one example:

        DataGridViewCell cell = new DataGridViewTextBoxCell();
        DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()
        {
            CellTemplate = cell,
            Name = "Value1",
            HeaderText = "Value 1",
            DataPropertyName = "Col1"
        };

        DataGridViewCell cell2 = new DataGridViewTextBoxCell();
        DataGridViewTextBoxColumn colFileName2 = new DataGridViewTextBoxColumn()
        {
            CellTemplate = cell2,
            Name = "Value2",
            HeaderText = "Value 2",
            DataPropertyName = "Col2"
        };
        dataGridView1.Columns.Add(colFileName);
        dataGridView1.Columns.Add(colFileName2);

        List<DataPopulate> list = new List<DataPopulate>();
        list.Add(new DataPopulate() { Col1 = "tes1", Col2 = "teste2"});
        list.Add(new DataPopulate() { Col1 = "tes1", Col2 = "teste2" });
        list.Add(new DataPopulate() { Col1 = "tes1", Col2 = "teste2" });

        var dataPopulateList = new BindingList<DataPopulate>(list);

        dataGridView1.DataSource = dataPopulateList;


问:
Redefinitions when compiling CUDA with clang on Windows
Despite an almost identical question already asked, the answer is for OSX and no longer holds true (and is really hacky anyways).

The problem is when compiling cuda with clang on windows, there is tonnes of redefinitions in math_functions.hpp.

With some investigations, apparently cuda decided to put its math_functions.hpp and math_functions.h functions in namespace std (is this even legal?), and collided with all the libstdc++ functions in cmath and clang's own headers for compiling cuda.

How do I deal with this? Preferably not with the hacky way shown in the previous question?

Side note

According to clang's documentation, clang can overload based on __global__/__device__ qualifiers, shouldn't the code just compile anyways?

Details

Versions:

clang 4.0.0 (built like this)

libstdc++ came from gcc 7.1.0

cuda 8.0

windows 10

Full error output

```<code>clang++ hellocuda.cu  --cuda-path=E:\cuda\development --cuda-gpu-arch=sm_20 -LE:\cuda\development\lib\x64 -lcudart_static -ldl -lrt -std=c++1y -O2 -pedantic -Wall -Wextra -fms-extensions -o program.exe
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:1684:14: error: redefinition of
      '__isnan'
__func__(int __isnan(double a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:525:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __isnan (double _x)
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:1764:14: error: redefinition of
      '__signbit'
__func__(int __signbit(double a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:611:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __signbit (double x) {
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:1776:17: error: redefinition of
      'copysign'
__func__(double copysign(double a, double b))
                ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:1069:31: note:
      previous definition is here
  __CRT_INLINE double __cdecl copysign (double x, double y)
                              ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:3161:14: error: redefinition of
      '__signbitl'
__func__(int __signbitl(long double a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:636:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __signbitl (long double x) {
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:3166:14: error: redefinition of
      '__signbitf'
__func__(int __signbitf(float a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:624:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __signbitf (float x) {
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:3191:14: error: redefinition of
      '__isnanl'
__func__(int __isnanl(long double a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:565:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __isnanl (long double _x)
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:3196:14: error: redefinition of
      '__isnanf'
__func__(int __isnanf(float a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:546:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __isnanf (float _x)
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:3360:16: error: redefinition of
      'copysignf'
__func__(float copysignf(float a, float b))
               ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:1076:30: note:
      previous definition is here
  __CRT_INLINE float __cdecl copysignf (float x, float y)
                             ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:365:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isinf(double a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:107:17: note:
      previous declaration is here
__DEVICE__ bool isinf(double);
           ~~~~ ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:381:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isinf(float a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:108:17: note:
      previous declaration is here
__DEVICE__ bool isinf(float);
           ~~~~ ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:413:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isnan(double a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:115:17: note:
      previous declaration is here
__DEVICE__ bool isnan(double);
           ~~~~ ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:429:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isnan(float a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:116:17: note:
      previous declaration is here
__DEVICE__ bool isnan(float);
           ~~~~ ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:461:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isfinite(double a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:101:17: note:
      previous declaration is here
__DEVICE__ bool isfinite(double);
           ~~~~ ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:477:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isfinite(float a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:102:17: note:
      previous declaration is here
__DEVICE__ bool isfinite(float);
           ~~~~ ^
14 errors generated.
makefile:15: recipe for target 'all' failed
mingw32-make: *** [all] Error 1
</code>```

答:
I tried quite a bit of stuff. They failed. In the end I dug into the headers and literally macroed out anything that has a conflict, which are located in

cuda's math_functions.hpp

clang's __clang_cuda_math_forward_declares.h

clang's __clang_cuda_cmath.h

clang uses _MSC_VER to detect Windows, which is defined only if -fms-compatibility flag is used, but this causes a ton of other errors elsewhere for unknown reasons.

cuda uses a mixture of _WIN32 and _MSC_VER to detect Windows. As far as I can tell, just macroing away everything that is a redefinition is simply the easiest way to do this.

This seems to be working, as in no other header errors popped up.

Body:
Despite an almost identical question already asked, the answer is for OSX and no longer holds true (and is really hacky anyways).

The problem is when compiling cuda with clang on windows, there is tonnes of redefinitions in math_functions.hpp.

With some investigations, apparently cuda decided to put its math_functions.hpp and math_functions.h functions in namespace std (is this even legal?), and collided with all the libstdc++ functions in cmath and clang's own headers for compiling cuda.

How do I deal with this? Preferably not with the hacky way shown in the previous question?

Side note

According to clang's documentation, clang can overload based on __global__/__device__ qualifiers, shouldn't the code just compile anyways?

Details

Versions:

clang 4.0.0 (built like this)

libstdc++ came from gcc 7.1.0

cuda 8.0

windows 10

Full error output

clang++ hellocuda.cu  --cuda-path=E:\cuda\development --cuda-gpu-arch=sm_20 -LE:\cuda\development\lib\x64 -lcudart_static -ldl -lrt -std=c++1y -O2 -pedantic -Wall -Wextra -fms-extensions -o program.exe
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:1684:14: error: redefinition of
      '__isnan'
__func__(int __isnan(double a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:525:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __isnan (double _x)
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:1764:14: error: redefinition of
      '__signbit'
__func__(int __signbit(double a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:611:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __signbit (double x) {
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:1776:17: error: redefinition of
      'copysign'
__func__(double copysign(double a, double b))
                ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:1069:31: note:
      previous definition is here
  __CRT_INLINE double __cdecl copysign (double x, double y)
                              ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:3161:14: error: redefinition of
      '__signbitl'
__func__(int __signbitl(long double a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:636:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __signbitl (long double x) {
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:3166:14: error: redefinition of
      '__signbitf'
__func__(int __signbitf(float a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:624:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __signbitf (float x) {
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:3191:14: error: redefinition of
      '__isnanl'
__func__(int __isnanl(long double a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:565:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __isnanl (long double _x)
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:3196:14: error: redefinition of
      '__isnanf'
__func__(int __isnanf(float a))
             ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:546:28: note:
      previous definition is here
  __CRT_INLINE int __cdecl __isnanf (float _x)
                           ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:191:
E:\cuda\development/include\math_functions.hpp:3360:16: error: redefinition of
      'copysignf'
__func__(float copysignf(float a, float b))
               ^
E:\TDM-GCC\mingw64 7.1.0\mingw64\x86_64-w64-mingw32\include\math.h:1076:30: note:
      previous definition is here
  __CRT_INLINE float __cdecl copysignf (float x, float y)
                             ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:365:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isinf(double a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:107:17: note:
      previous declaration is here
__DEVICE__ bool isinf(double);
           ~~~~ ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:381:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isinf(float a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:108:17: note:
      previous declaration is here
__DEVICE__ bool isinf(float);
           ~~~~ ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:413:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isnan(double a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:115:17: note:
      previous declaration is here
__DEVICE__ bool isnan(double);
           ~~~~ ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:429:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isnan(float a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:116:17: note:
      previous declaration is here
__DEVICE__ bool isnan(float);
           ~~~~ ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:461:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isfinite(double a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:101:17: note:
      previous declaration is here
__DEVICE__ bool isfinite(double);
           ~~~~ ^
In file included from <built-in>:1:
In file included from E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_runtime_wrapper.h:250:
E:\cuda\development/include\math_functions.hpp:477:43: error: functions that differ
      only in their return type cannot be overloaded
static __inline__ __host__ __device__ int isfinite(float a)
                                      ~~~ ^
E:\LLVM\bin\..\lib\clang\4.0.0\include\__clang_cuda_math_forward_declares.h:102:17: note:
      previous declaration is here
__DEVICE__ bool isfinite(float);
           ~~~~ ^
14 errors generated.
makefile:15: recipe for target 'all' failed
mingw32-make: *** [all] Error 1


问:
Use the same random Typoscript IMG_RESOURCE several times
How can I use the same random Image several times?
With the following Typoscript I've got different Images in different sizes.  </p>

```<code>lib.headerimage = COA_INT
lib.headerimage {
  1 = IMG_RESOURCE
  1 {
    file {
      import.data = levelmedia:-1, slide
      treatIdAsReference = 1
      import.listNum = rand
    }
  }
}

lib.headerimageSmall =< lib.headerimage
lib.headerimageSmall.1.file.width = 768

lib.headerimageTab =< lib.headerimageSmall
lib.headerimageTab.1.file.width = 1280

lib.headerimageDesktop =< lib.headerimageTab
lib.headerimageDesktop.1.file.width = 1920

lib.headerimageHigh =< lib.headerimageDesktop
lib.headerimageHigh.1.file.width = 2880
</code>```

答:
You might use a register for your image.

This might only work if you use fluidvariables instead of lib-TS

as idea (not tested):

```<code>page {
  1 = STORE_REGISTER
  1 {
    randomImage.cObject = IMG_RESOURCE
    randomImage.cObject {
        file {
        import.data = levelmedia:-1, slide
        treatIdAsReference = 1
        import.listNum = rand
    }

  10 = FLUID_TEMPLATE
  10 {
     name = ...
     :
     variables {

         headerimageSmall = IMG_RESOURCE
         headerimageSmall {
             file.cObject = TEXT
             file.cobject.data = register:randomImage
             file.width = 768
         }

         headerimageTab < .headerimageSmall
         headerimageTab.file.width = 1280

         headerimageDesktop < lib.headerimageSmall
         headerimageDesktop.file.width = 1920

         headerimageHigh < lib.headerimageSmall
         headerimageHigh.file.width = 2880

     }
  }
}
</code>```

maybe you could use the file-id as register, maybe the rendering for the fluid-variabels needs some adjustements.

Body:
How can I use the same random Image several times?
With the following Typoscript I've got different Images in different sizes.

lib.headerimage = COA_INT
lib.headerimage {
  1 = IMG_RESOURCE
  1 {
    file {
      import.data = levelmedia:-1, slide
      treatIdAsReference = 1
      import.listNum = rand
    }
  }
}

lib.headerimageSmall =< lib.headerimage
lib.headerimageSmall.1.file.width = 768

lib.headerimageTab =< lib.headerimageSmall
lib.headerimageTab.1.file.width = 1280

lib.headerimageDesktop =< lib.headerimageTab
lib.headerimageDesktop.1.file.width = 1920

lib.headerimageHigh =< lib.headerimageDesktop
lib.headerimageHigh.1.file.width = 2880

Body:
You might use a register for your image.

This might only work if you use fluidvariables instead of lib-TS

as idea (not tested):

page {
  1 = STORE_REGISTER
  1 {
    randomImage.cObject = IMG_RESOURCE
    randomImage.cObject {
        file {
        import.data = levelmedia:-1, slide
        treatIdAsReference = 1
        import.listNum = rand
    }

  10 = FLUID_TEMPLATE
  10 {
     name = ...
     :
     variables {

         headerimageSmall = IMG_RESOURCE
         headerimageSmall {
             file.cObject = TEXT
             file.cobject.data = register:randomImage
             file.width = 768
         }

         headerimageTab < .headerimageSmall
         headerimageTab.file.width = 1280

         headerimageDesktop < lib.headerimageSmall
         headerimageDesktop.file.width = 1920

         headerimageHigh < lib.headerimageSmall
         headerimageHigh.file.width = 2880

     }
  }
}

maybe you could use the file-id as register, maybe the rendering for the fluid-variabels needs some adjustements.