问:
Typescript inject and arguments in class
I use InversifyJS and container.

I want inject templateEngine and pass args (host, port, etc...) in constructor.

```<code>const container = new Container();
container.bind<MailerInterface>(TYPES.Mailer).to(NodeMailer);
</code>```

And my Mailer class:

```<code>import * as nodemailer from "nodemailer";
import {TemplateEngineInterface} from "../../Domain/TemplateEngine/TemplateEngineInterface";
import TYPES from "../../../../config/inversify.types";
import {inject, injectable, named} from "inversify";

@injectable()
export class NodeMailer implements MailerInterface {

    private transporter: any;
    private templateEngine: TemplateEngineInterface;

    constructor(
        @inject(TYPES.TemplateEngine) templateEngine: TemplateEngineInterface,
        host: string,
        port: number,
        secure: boolean,
        username: string,
        password: string
    ) {

        this.templateEngine = templateEngine;

        this.transporter = nodemailer.createTransport({
            host: host,
            port: port,
            secure: secure,
            auth: {
                user: username,
                pass: password
            }
        });

    }

}
</code>```

How I can pass arguments in constructor with inject or others methods?

答:
You have a few options.

A) Inject the config

```<code>constructor(
    @inject(TYPES.TemplateEngine) templateEngine: TemplateEngineInterface,
    @inject(TYPES.MailerConfig) @named("host") host: string,
    @inject(TYPES.MailerConfig) @named("port") port: number,
    @inject(TYPES.MailerConfig) @named("secure") secure: boolean,
    @inject(TYPES.MailerConfig) @named("username") username: string,
    @inject(TYPES.MailerConfig) @named("password") password: string
) {
</code>```

The type is just:

```<code>const TYPES = { MailerConfig: Symbol.for("MailerConfig") }
</code>```

And the bindings:

```<code>type MailerConfig = string|boolean|number;

container.bind<MailerConfig>(TYPES.MailerConfig)
         .toConstantValue("localhost")
         .whenTargetNamed("host");

container.bind<MailerConfig>(TYPES.MailerConfig)
         .toConstantValue(2525)
         .whenTargetNamed("port");

container.bind<MailerConfig>(TYPES.MailerConfig)
         .toConstantValue(true)
         .whenTargetNamed("secure");

container.bind<MailerConfig>(TYPES.MailerConfig)
         .toConstantValue("root")
         .whenTargetNamed("username");

container.bind<MailerConfig>(TYPES.MailerConfig)
         .toConstantValue("toor")
         .whenTargetNamed("password");
</code>```

Tip: Reducing boilerplate

If you are going to do this, I recommend creating helpers to reduce the required boilerplate.

Bindings

```<code>type MailerConfig = string|boolean|number;

const bindMailerConfig = (ctr: Container, key: string, val: MailerConfig) =>
        ctr.bind<MailerConfig>(TYPES.MailerConfig)
       .toConstantValue(key)
       .whenTargetNamed(val);

bindMailerConfig(container, "localhost", "host");
bindMailerConfig(container, 2525, "port");
bindMailerConfig(container, true, "secure");
bindMailerConfig(container, "root", "username");
bindMailerConfig(container,"toor", "password");
</code>```

Decorators

```<code>const injectNamed = (typeId: any) => (name: string) =>
    (target: any, targetKey: string, index?: number) => {
        inject(typeId)(target, targetKey, number);
        named(name)(target, targetKey, number);
    };

const injectMailerConfig = injectNamed(TYPES.TemplateEngine);

constructor(
    @inject(TYPES.TemplateEngine) templateEngine: TemplateEngineInterface,
    @injectMailerConfig("host") host: string,
    @injectMailerConfig("port") port: number,
    @injectMailerConfig("secure") secure: boolean,
    @injectMailerConfig("username") username: string,
    @injectMailerConfig("password") password: string
) {
</code>```

B) Two-step initialization

```<code>@injectable()
export class NodeMailer implements MailerInterface {

    private transporter: any;
    private templateEngine: TemplateEngineInterface;

    constructor(
        @inject(TYPES.TemplateEngine) templateEngine: TemplateEngineInterface,
    ) {
        this.templateEngine = templateEngine;
        this.transporter = null;
    }

    public initialize(host, port, secure, username, password) {
        if (this.transporter) {
            return this.transporter;
        }
        this.transporter = nodemailer.createTransport({
            host: host,
            port: port,
            secure: secure,
            auth: {
                user: username,
                pass: password
            }
        });
        return this.transporter;
    }

    public send() {
        if (this.transporter === null) {
            throw new Error("You must invoke initialize!");
        }
        // ...
    }

}
</code>```

The two-step initialization can play nicely with a factory.

Body:
I use InversifyJS and container.

I want inject templateEngine and pass args (host, port, etc...) in constructor.

const container = new Container();
container.bind<MailerInterface>(TYPES.Mailer).to(NodeMailer);

And my Mailer class:

import * as nodemailer from "nodemailer";
import {TemplateEngineInterface} from "../../Domain/TemplateEngine/TemplateEngineInterface";
import TYPES from "../../../../config/inversify.types";
import {inject, injectable, named} from "inversify";

@injectable()
export class NodeMailer implements MailerInterface {

    private transporter: any;
    private templateEngine: TemplateEngineInterface;

    constructor(
        @inject(TYPES.TemplateEngine) templateEngine: TemplateEngineInterface,
        host: string,
        port: number,
        secure: boolean,
        username: string,
        password: string
    ) {

        this.templateEngine = templateEngine;

        this.transporter = nodemailer.createTransport({
            host: host,
            port: port,
            secure: secure,
            auth: {
                user: username,
                pass: password
            }
        });

    }

}

How I can pass arguments in constructor with inject or others methods?

Body:
You have a few options.

A) Inject the config

constructor(
    @inject(TYPES.TemplateEngine) templateEngine: TemplateEngineInterface,
    @inject(TYPES.MailerConfig) @named("host") host: string,
    @inject(TYPES.MailerConfig) @named("port") port: number,
    @inject(TYPES.MailerConfig) @named("secure") secure: boolean,
    @inject(TYPES.MailerConfig) @named("username") username: string,
    @inject(TYPES.MailerConfig) @named("password") password: string
) {

The type is just:

const TYPES = { MailerConfig: Symbol.for("MailerConfig") }

And the bindings:

type MailerConfig = string|boolean|number;

container.bind<MailerConfig>(TYPES.MailerConfig)
         .toConstantValue("localhost")
         .whenTargetNamed("host");

container.bind<MailerConfig>(TYPES.MailerConfig)
         .toConstantValue(2525)
         .whenTargetNamed("port");

container.bind<MailerConfig>(TYPES.MailerConfig)
         .toConstantValue(true)
         .whenTargetNamed("secure");

container.bind<MailerConfig>(TYPES.MailerConfig)
         .toConstantValue("root")
         .whenTargetNamed("username");

container.bind<MailerConfig>(TYPES.MailerConfig)
         .toConstantValue("toor")
         .whenTargetNamed("password");

Tip: Reducing boilerplate

If you are going to do this, I recommend creating helpers to reduce the required boilerplate.

Bindings

type MailerConfig = string|boolean|number;

const bindMailerConfig = (ctr: Container, key: string, val: MailerConfig) =>
        ctr.bind<MailerConfig>(TYPES.MailerConfig)
       .toConstantValue(key)
       .whenTargetNamed(val);

bindMailerConfig(container, "localhost", "host");
bindMailerConfig(container, 2525, "port");
bindMailerConfig(container, true, "secure");
bindMailerConfig(container, "root", "username");
bindMailerConfig(container,"toor", "password");

Decorators

const injectNamed = (typeId: any) => (name: string) =>
    (target: any, targetKey: string, index?: number) => {
        inject(typeId)(target, targetKey, number);
        named(name)(target, targetKey, number);
    };

const injectMailerConfig = injectNamed(TYPES.TemplateEngine);

constructor(
    @inject(TYPES.TemplateEngine) templateEngine: TemplateEngineInterface,
    @injectMailerConfig("host") host: string,
    @injectMailerConfig("port") port: number,
    @injectMailerConfig("secure") secure: boolean,
    @injectMailerConfig("username") username: string,
    @injectMailerConfig("password") password: string
) {

B) Two-step initialization

@injectable()
export class NodeMailer implements MailerInterface {

    private transporter: any;
    private templateEngine: TemplateEngineInterface;

    constructor(
        @inject(TYPES.TemplateEngine) templateEngine: TemplateEngineInterface,
    ) {
        this.templateEngine = templateEngine;
        this.transporter = null;
    }

    public initialize(host, port, secure, username, password) {
        if (this.transporter) {
            return this.transporter;
        }
        this.transporter = nodemailer.createTransport({
            host: host,
            port: port,
            secure: secure,
            auth: {
                user: username,
                pass: password
            }
        });
        return this.transporter;
    }

    public send() {
        if (this.transporter === null) {
            throw new Error("You must invoke initialize!");
        }
        // ...
    }

}

The two-step initialization can play nicely with a factory.


来源: stackexchange

问:
SQL: Joins with an OR?
I'm trying to pull data from two tables, and I've been reading up on JOINs both here and on Google, but nothing seems to be working properly.

What I need is to pull from a customer table and a customertype table. Here's the customer table layout:

```<code>CustomerID: int PRIMARY KEY UNIQUE
Customername: varstring
Customeraddress: varstring
Customertype: int
Customerdescription: text
</code>```

Example:

```<code>CustomerID: 1
CustomernName: John Smith
Customeraddress: 1 Fake St., New York, New York, 11111
Customertype: 1
Customerdescription: Customer makes a monthly purchase of this and that.
</code>```

Here's the customertype layout:

```<code>TypeID: int PRIMARY KEY UNIQUE
Typetitle: varstring
Typedescription: text
</code>```

Example:

```<code>TypeID: 1
Typetitle: In good standing
Typedescription: These customers are in good standing and owe nothing.
</code>```

The Type field in the customer table obviously should correspond with the Type field in the customertype table. So, if I need to know all John Smith's data, I want, in one query:

```<code>CustomerID: 1
Customername: John Smith
Customeraddress: 1 Fake St. New York, New York, 11111
Typetitle: In good standing
Customerdescription: Customer makes a monthly purchase of this and that.
</code>```

The snag is, sometimes the Customertype is 0, which doesn't correspond to any record in the customertype table. Their type is undefined.

I've read about JOINs in various places, but I can't seem to make a query that will handle both where the CustomerID=the TypeID or where the CustomerID=0. Does anyone have any suggestions or know what the query would be?

答:
This should work:

```<code>SELECT c.CustomerID, c.Customername, c.Customeraddress, t.Typetitle, c.Customerdescription
FROM Customer c
LEFT JOIN customertype t ON c.Customertype = t.TypeID
</code>```

A left join will not filter out those that don't have a match in the second table. You can add in the select which ever columns you want from either table.

ContentLicense: CC BY-SA 3.0

Title: SQL: Joins with an OR?

Body:
I'm trying to pull data from two tables, and I've been reading up on JOINs both here and on Google, but nothing seems to be working properly.

What I need is to pull from a customer table and a customertype table. Here's the customer table layout:

CustomerID: int PRIMARY KEY UNIQUE
Customername: varstring
Customeraddress: varstring
Customertype: int
Customerdescription: text

Example:

CustomerID: 1
CustomernName: John Smith
Customeraddress: 1 Fake St., New York, New York, 11111
Customertype: 1
Customerdescription: Customer makes a monthly purchase of this and that.

Here's the customertype layout:

TypeID: int PRIMARY KEY UNIQUE
Typetitle: varstring
Typedescription: text

Example:

TypeID: 1
Typetitle: In good standing
Typedescription: These customers are in good standing and owe nothing.

The Type field in the customer table obviously should correspond with the Type field in the customertype table. So, if I need to know all John Smith's data, I want, in one query:

CustomerID: 1
Customername: John Smith
Customeraddress: 1 Fake St. New York, New York, 11111
Typetitle: In good standing
Customerdescription: Customer makes a monthly purchase of this and that.

The snag is, sometimes the Customertype is 0, which doesn't correspond to any record in the customertype table. Their type is undefined.

I've read about JOINs in various places, but I can't seem to make a query that will handle both where the CustomerID=the TypeID or where the CustomerID=0. Does anyone have any suggestions or know what the query would be?

Body:
This should work:

SELECT c.CustomerID, c.Customername, c.Customeraddress, t.Typetitle, c.Customerdescription
FROM Customer c
LEFT JOIN customertype t ON c.Customertype = t.TypeID

A left join will not filter out those that don't have a match in the second table. You can add in the select which ever columns you want from either table.


问:
If a function creates and returns an object, should it be in the autorelease pool
I'm still pretty new to objective-c.

As far as I can understand, any object I do not get from alloc, new, copy, or mutableCopy should be assumed to be in the autorelease pool.

I assume that also means that if I create a function that creates and returns a new instance of an object, I should place that in the autorelease pool before returning.

For example, I have a function that parses xml, and returns an object representing the data in the xml, that object should be in the autorelease pool before returning.

My primary concern is iPhone development, but a general answer would be appreciated.

答:
You should read the Objective-C memory management guide.

Any object returned from a new, alloc or copy method is yours. You own it and you must release it.

Any object returned from any other method is in the autorelease pool. If you want to keep the object beyond your current scope, you must retain it.

The XML example is probably correct: If you're returning an object from a method and the name of that method does not contain new or copy in the name you should, by convention, return an autoreleased object.

ContentLicense: CC BY-SA 2.5


问:
Nashorn on Visual Studio Code
So, Java's Nashorn engine allows to embed javascript in a java application.
Nashorn's javascript has some non-vanilla javascript features, it is possible to write a function litteral like this :

```<code>function add(x,y)x+y
</code>```

Which is the same as function add(x,y){return x+y;}

There is also the for each loop :

```<code>for each(var i in myArray) print(i)
</code>```

I would like to edit the javascript files in Visual studio code. However, for the features above, since they are not vanilla javascript, VSCode detects an error.
I couldn't find an extension for visual studio to support Nashorn's javascript.

Is there any way to "extend" the javascript support on visual studio to allow the features above ?

答:
No. You'd need an extension that implements a Nashorn JS language server. VS Code's built-in JS support cannot be extended easily this way

You can suppress these error messages by setting:

```<code> "javascript.validate.enable": false
</code>```

IntelliSense and other language support will still not work however without a proper language extension

Title: Nashorn on Visual Studio Code

Body:
So, Java's Nashorn engine allows to embed javascript in a java application.
Nashorn's javascript has some non-vanilla javascript features, it is possible to write a function litteral like this :

function add(x,y)x+y

Which is the same as function add(x,y){return x+y;}

There is also the for each loop :

for each(var i in myArray) print(i)

I would like to edit the javascript files in Visual studio code. However, for the features above, since they are not vanilla javascript, VSCode detects an error.
I couldn't find an extension for visual studio to support Nashorn's javascript.

Is there any way to "extend" the javascript support on visual studio to allow the features above ?

Body:
No. You'd need an extension that implements a Nashorn JS language server. VS Code's built-in JS support cannot be extended easily this way

You can suppress these error messages by setting:

 "javascript.validate.enable": false

IntelliSense and other language support will still not work however without a proper language extension


问:
Is there a way to get a nice output for the flags register using lldb?
Here is the output I get when I read the rflags register using lldb

```<code>(lldb) register read rflags
  rflags = 0x0000000000000246
</code>```

I know each bit represents a certain flag, but it would be nice to have an output that gave me the value of those flags (e.g. carry flag, zero flag, etc...)

Is there any way to do that using lldb?

答:
There isn't an automatic way to do this.

You can't use the data formatters since they are linked to types and there isn't a "flags register type".  And the formats you can pass on the command line to register read format the whole value.

We've toyed with the idea of adding "register formatters" along the same lines as the data formatters, but haven't implemented that yet.

You could pretty easily write an lldb command to pretty-print the value however.  If you start from the example here:

http://llvm.org/svn/llvm-project/lldb/trunk/examples/python/cmdtemplate.py

you can see the example gets the frame here:

```<code>frame = exe_ctx.GetFrame()
</code>```

You could then get the register value from:

```<code>rflags_value = frame.FindRegister("rflags")
</code>```

You can either get the value as a whole

```<code>error = lldb.SBError()
uint_value = rflags_value.GetValueAsUnsigned(error)
</code>```

But it might be easier for your purposes to get the SBData for this:

```<code>data_value = rflags_value.GetData()
</code>```

The SBData object lets you see the value as a vector of uint8's.  It doesn't produce smaller chunks, but still this might help:

```<code>first_byte = data_value.uint8[0]
</code>```

etc.  When you have formatted this as you wish, write the description into the return object you were passed, and that's what the command will return.  The __init section shows how to make this into an lldb command.  Then just put:

```<code>command script import <path_to_py>/my_command.py
</code>```

and it will be available in all your future lldb sessions.

Here's more documentation on the lldb API's:

http://lldb.llvm.org/python_reference/index.html

and you can use the python "script interpreter" REPL in lldb (the script command) to play with these API's as you are developing the code.

Body:
Here is the output I get when I read the rflags register using lldb

(lldb) register read rflags
  rflags = 0x0000000000000246

I know each bit represents a certain flag, but it would be nice to have an output that gave me the value of those flags (e.g. carry flag, zero flag, etc...)

Is there any way to do that using lldb?

Body:
There isn't an automatic way to do this.

You can't use the data formatters since they are linked to types and there isn't a "flags register type".  And the formats you can pass on the command line to register read format the whole value.

We've toyed with the idea of adding "register formatters" along the same lines as the data formatters, but haven't implemented that yet.

You could pretty easily write an lldb command to pretty-print the value however.  If you start from the example here:

http://llvm.org/svn/llvm-project/lldb/trunk/examples/python/cmdtemplate.py

you can see the example gets the frame here:

frame = exe_ctx.GetFrame()

You could then get the register value from:

rflags_value = frame.FindRegister("rflags")

You can either get the value as a whole

error = lldb.SBError()
uint_value = rflags_value.GetValueAsUnsigned(error)

But it might be easier for your purposes to get the SBData for this:

data_value = rflags_value.GetData()

The SBData object lets you see the value as a vector of uint8's.  It doesn't produce smaller chunks, but still this might help:

first_byte = data_value.uint8[0]

etc.  When you have formatted this as you wish, write the description into the return object you were passed, and that's what the command will return.  The __init section shows how to make this into an lldb command.  Then just put:

command script import <path_to_py>/my_command.py

and it will be available in all your future lldb sessions.

Here's more documentation on the lldb API's:

http://lldb.llvm.org/python_reference/index.html

and you can use the python "script interpreter" REPL in lldb (the script command) to play with these API's as you are developing the code.


问:
Draw text pixel by pixel on canvas
I have a canvas where I use "fillText" with a string, saying for example "stackoverflow". Then I read the imagedata of the canvas in order to pick out each pixel of that text.

I want to pick the following from the pixel: x position, y position and its color. Then I would like to loop over that array with those pixels so I can draw back the text pixel by pixel so I have full control of each pixel, and can for example animate them.

However, I dont get it as smooth as I want. Look at my attach image, and you see the difference between the top text and then the text I've plotted out using fillRect for each pixel. Any help on how to make the new text look like the "fillText" text does?

Thanks

UPDATE: Added my code

```<code>var _particles = [];
var _canvas, _ctx, _width, _height;

(function(){
    init();
})();

function init(){
    setupParticles(getTextCanvasData());
}

function getTextCanvasData(){
    // var w = 300, h = 150, ratio = 2;

    _canvas = document.getElementById("textCanvas");
    // _canvas.width = w * ratio;
    // _canvas.height = h * ratio;
    // _canvas.style.width = w + "px";
    // _canvas.style.height = h + "px";

    _ctx = _canvas.getContext("2d");
    _ctx.fillStyle = "rgb(0, 154, 253)";
    // _ctx.setTransform(ratio, 0, 0, ratio, 0, 0);

    var str = "stackoverflow";
    _ctx.font = "32px EB Garamond";
    _ctx.fillText(str,0,23);

    _width = _canvas.width;
    _height = _canvas.height;

    var data32 = new Uint32Array(_ctx.getImageData(0, 0, _width, _height).data.buffer);
    var positions = [];

    for(i = 0; i < data32.length; i++) {

        if (data32[i] & 0xffff0000) {
            positions.push({
                x: (i % _width),
                y: ((i / _width)|0),
            });
        }
    }

    return positions;
}

function setupParticles(positions){
    var i = positions.length;
    var particles = [];
    while(i--){
        var p = new Particle();
        p.init(positions[i]);
        _particles.push(p);

        drawParticle(p);
    }
}

function drawParticle(particle){
    var x = particle.x;
    var y = particle.y;

    _ctx.beginPath();
    _ctx.fillRect(x, y, 1, 1);
    _ctx.fillStyle = 'green';
}

function Particle(){
    this.init = function(pos){
        this.x = pos.x;
        this.y = pos.y + 30;
        this.x0 = this.x;
        this.y0 = this.y;
        this.xDelta = 0;
        this.yDelta = 0;
    }
}
</code>```

答:
Here is an update to your code that reuses the alpha component of each pixel. There will still be some detail lost because we do not keep the antialiasing of the pixels (which in effect alters the actual color printed), but for this example the alpha is enough.

var _particles = [];
var _canvas, _ctx, _width, _height;

(function(){
    init();
})();

function init(){
    setupParticles(getTextCanvasData());
}

function getTextCanvasData(){
    // var w = 300, h = 150, ratio = 2;

    _canvas = document.getElementById("textCanvas");
    // _canvas.width = w * ratio;
    // _canvas.height = h * ratio;
    // _canvas.style.width = w + "px";
    // _canvas.style.height = h + "px";

    _ctx = _canvas.getContext("2d");
    _ctx.imageSmoothingEnabled= false;
    _ctx.fillStyle = "rgb(0, 154, 253)";
    // _ctx.setTransform(ratio, 0, 0, ratio, 0, 0);

    var str = "stackoverflow";
    _ctx.font = "32px EB Garamond";
    _ctx.fillText(str,0,23);

    _width = _canvas.width;
    _height = _canvas.height;

    var pixels = _ctx.getImageData(0, 0, _width, _height).data;
    var data32 = new Uint32Array(pixels.buffer);
    var positions = [];
        for(i = 0; i < data32.length; i++) {
        if (data32[i] & 0xffff0000) {
            positions.push({
                x: (i % _width),
                y: ((i / _width)|0),
                a: pixels[i*4 + 3] / 255
            });
        }
    }

    return positions;
}

function setupParticles(positions){
    var i = positions.length;
    var particles = [];
    while(i--){
        var p = new Particle();
        p.init(positions[i]);
        _particles.push(p);

        drawParticle(p);
    }
}

function drawParticle(particle){
    var x = particle.x;
    var y = particle.y;

    _ctx.beginPath();
    _ctx.fillStyle = `rgba(0,128,0,${particle.alpha})`;

    _ctx.fillRect(x, y, 1, 1);
}

function Particle(){
    this.init = function(pos){
        this.x = pos.x;
        this.y = pos.y + 30;
        this.x0 = this.x;
        this.y0 = this.y;
        this.xDelta = 0;
        this.yDelta = 0;
        this.alpha = pos.a;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="textCanvas"></canvas></code>```

Title: Draw text pixel by pixel on canvas

Body:
I have a canvas where I use "fillText" with a string, saying for example "stackoverflow". Then I read the imagedata of the canvas in order to pick out each pixel of that text.

I want to pick the following from the pixel: x position, y position and its color. Then I would like to loop over that array with those pixels so I can draw back the text pixel by pixel so I have full control of each pixel, and can for example animate them.

However, I dont get it as smooth as I want. Look at my attach image, and you see the difference between the top text and then the text I've plotted out using fillRect for each pixel. Any help on how to make the new text look like the "fillText" text does?

Thanks

UPDATE: Added my code

var _particles = [];
var _canvas, _ctx, _width, _height;

(function(){
    init();
})();

function init(){
    setupParticles(getTextCanvasData());
}

function getTextCanvasData(){
    // var w = 300, h = 150, ratio = 2;

    _canvas = document.getElementById("textCanvas");
    // _canvas.width = w * ratio;
    // _canvas.height = h * ratio;
    // _canvas.style.width = w + "px";
    // _canvas.style.height = h + "px";

    _ctx = _canvas.getContext("2d");
    _ctx.fillStyle = "rgb(0, 154, 253)";
    // _ctx.setTransform(ratio, 0, 0, ratio, 0, 0);

    var str = "stackoverflow";
    _ctx.font = "32px EB Garamond";
    _ctx.fillText(str,0,23);

    _width = _canvas.width;
    _height = _canvas.height;

    var data32 = new Uint32Array(_ctx.getImageData(0, 0, _width, _height).data.buffer);
    var positions = [];

    for(i = 0; i < data32.length; i++) {

        if (data32[i] & 0xffff0000) {
            positions.push({
                x: (i % _width),
                y: ((i / _width)|0),
            });
        }
    }

    return positions;
}

function setupParticles(positions){
    var i = positions.length;
    var particles = [];
    while(i--){
        var p = new Particle();
        p.init(positions[i]);
        _particles.push(p);

        drawParticle(p);
    }
}

function drawParticle(particle){
    var x = particle.x;
    var y = particle.y;

    _ctx.beginPath();
    _ctx.fillRect(x, y, 1, 1);
    _ctx.fillStyle = 'green';
}

function Particle(){
    this.init = function(pos){
        this.x = pos.x;
        this.y = pos.y + 30;
        this.x0 = this.x;
        this.y0 = this.y;
        this.xDelta = 0;
        this.yDelta = 0;
    }
}

Body:
Here is an update to your code that reuses the alpha component of each pixel. There will still be some detail lost because we do not keep the antialiasing of the pixels (which in effect alters the actual color printed), but for this example the alpha is enough.

var _particles = [];
var _canvas, _ctx, _width, _height;

(function(){
    init();
})();

function init(){
    setupParticles(getTextCanvasData());
}

function getTextCanvasData(){
    // var w = 300, h = 150, ratio = 2;

    _canvas = document.getElementById("textCanvas");
    // _canvas.width = w * ratio;
    // _canvas.height = h * ratio;
    // _canvas.style.width = w + "px";
    // _canvas.style.height = h + "px";

    _ctx = _canvas.getContext("2d");
    _ctx.imageSmoothingEnabled= false;
    _ctx.fillStyle = "rgb(0, 154, 253)";
    // _ctx.setTransform(ratio, 0, 0, ratio, 0, 0);

    var str = "stackoverflow";
    _ctx.font = "32px EB Garamond";
    _ctx.fillText(str,0,23);

    _width = _canvas.width;
    _height = _canvas.height;

    var pixels = _ctx.getImageData(0, 0, _width, _height).data;
    var data32 = new Uint32Array(pixels.buffer);
    var positions = [];
        for(i = 0; i < data32.length; i++) {
        if (data32[i] & 0xffff0000) {
            positions.push({
                x: (i % _width),
                y: ((i / _width)|0),
                a: pixels[i*4 + 3] / 255
            });
        }
    }

    return positions;
}

function setupParticles(positions){
    var i = positions.length;
    var particles = [];
    while(i--){
        var p = new Particle();
        p.init(positions[i]);
        _particles.push(p);

        drawParticle(p);
    }
}

function drawParticle(particle){
    var x = particle.x;
    var y = particle.y;

    _ctx.beginPath();
    _ctx.fillStyle = `rgba(0,128,0,${particle.alpha})`;

    _ctx.fillRect(x, y, 1, 1);
}

function Particle(){
    this.init = function(pos){
        this.x = pos.x;
        this.y = pos.y + 30;
        this.x0 = this.x;
        this.y0 = this.y;
        this.xDelta = 0;
        this.yDelta = 0;
        this.alpha = pos.a;
    }
}

<canvas id="textCanvas"></canvas>


问:
ArcGIS Convert IGeometryCollection to IEnumGeometry
I have a group of polylines mistakenly created with a geometry for each vertex pair. Typically they have thousands of geometries.
I would like to merge the geometries (note: NOT merge features) in each feature into one geometry. To do this I am using ITopologicalOperator5.ConstructUnion. ConstructUnion takes an IEnumGeometry parameter and I have an IGeometryCollection of geometries. I can create an IEnumGeometry using a GeometryBag but ConstructUnion does not accept GeometryBags.
If I use IEnumGeometry pEnum = (IEnumGeometry)pGeomCollection it throws an exception.
If I use IEnumGeometry pEnum = pGeomCollection as IEnumGeometry then pEnum is null.
In VB.NET Ctype(pGeomCollection, IEnumGeometry) works fine.
Can anyone tell me how to convert a (C#) Geometry Collection into an IEnumGeometry?

Thanks,

John

答:
The solution is to link the Geometry Bag and the Geometry Collection when they are initiated:</p>

```<code>IGeometryBag pGeomBag = new GeometryBagClass();
pGeomBag.SpatialReference = .......

IGeometryCollection pGeomColl = new PolylineClass();
pGeomColl = (IGeometryCollection)pGeomBag;

IEnumGeometry pEnum = new EnumFeatureGeometryClass();
pEnum = (IEnumGeometry)pGeomBag;
</code>```

Body:
The solution is to link the Geometry Bag and the Geometry Collection when they are initiated:

IGeometryBag pGeomBag = new GeometryBagClass();
pGeomBag.SpatialReference = .......

IGeometryCollection pGeomColl = new PolylineClass();
pGeomColl = (IGeometryCollection)pGeomBag;

IEnumGeometry pEnum = new EnumFeatureGeometryClass();
pEnum = (IEnumGeometry)pGeomBag;


问:
Dynamic SUM or SUMIF Formula
I want to get the SUM of the first column IF the next column has data. In this example, the second column has data for the first 6 rows, therefore the sum that I want to get is the sum of the first 6 numbers in column 1. How the second column gets its data is chronological, so there will be no skipped cells.

答:
You could use this formula:
=SUMIFS(A:A,B:B,">0")

It will sum the numbers in the first column, if the corresponding letters in the second column are greater than zero. Let me know if this does not cover all of your criteria, I'm sure I can help.

Thanks.

Title: Dynamic SUM or SUMIF Formula


问:
Making Variables Global in PHP?
Need to make $courseInfo and $row global so that they can be used for printing the row details in the header DIV.

Don't have a clue how to do this. Any help would be great.

```<code><?php

// Get Course ID From Link
$ID = mysql_real_escape_string($_REQUEST['ID']);

// Check the Course ID exists
$courseCheck = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");

if (mysql_num_rows($courseCheck) == 1) {

    $checkMember = mysql_query("SELECT * FROM CourseMembers WHERE CourseID = '".$ID."' AND UserID = '".$_SESSION['UserID']."'");

    if (mysql_num_rows($checkMember) == 1) {

        ?>
        <html>
        <head>
            <!-- Style Sheets -->
            <link rel="stylesheet" href="style/reset.css" type="text/css" media=screen />
            <link rel="stylesheet" href="style/style.css" type="text/css" media=screen />
        </head>
        <body>

        <?php
        if ($_SESSION['LoggedIn'] == 1){

            $courseInfo = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");
            $row = mysql_fetch_assoc($courseInfo);

        ?>

            <div id="container">
                <div id="side">
                    <?php include("lib/sidebar.php"); ?>
                </div>
                <div id="main">
                    <div id="mainbox">
                        <div id="header"><b><?php echo $row['CourseName']; ?></b></div>
                        <p>Hello world, this is a test.</p>
                    </div>
                </div>
            </div>
            <div class="clear"></div>

            <?php
            }
        else {
            echo "Not logged in.";
        }

    }

    else {
        echo "You are not a member of this Course";
    }

}

else {
    echo "No Course Found";
}

?>
</body>
</code>```

答:
You could also use php variable $GLOBALS for making your variables visible in all scopes but I would not recommend it for this kind of task. Also, beware - $GLOBALS contains superglobals like $_POST and $_GET, you should keep that in mind, when ie. iterating over it. Furthermore - when you can access $_GET and $_POST in functions, that have smaller scope you still have to use $GLOBALS to access custom ones.

Example for this kind behaviour:

```<code><?php
error_reporting(-1);

$GLOBALS['_customVar'] = 'foobar';
$GLOBALS['_GET']['id'] = 'myId';

    function myFnc() {
    echo $_customVar;
    }

    function myFnc2() {
    echo $_GET['id'];
    }

myFnc();
myFnc2();

?>
</code>```

Title: Making Variables Global in PHP?

Body:
Need to make $courseInfo and $row global so that they can be used for printing the row details in the header DIV.

Don't have a clue how to do this. Any help would be great.

<?php

// Get Course ID From Link
$ID = mysql_real_escape_string($_REQUEST['ID']);

// Check the Course ID exists
$courseCheck = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");

if (mysql_num_rows($courseCheck) == 1) {

    $checkMember = mysql_query("SELECT * FROM CourseMembers WHERE CourseID = '".$ID."' AND UserID = '".$_SESSION['UserID']."'");

    if (mysql_num_rows($checkMember) == 1) {

        ?>

            <link rel="stylesheet" href="style/reset.css" type="text/css" media=screen />
            <link rel="stylesheet" href="style/style.css" type="text/css" media=screen />

        <?php
        if ($_SESSION['LoggedIn'] == 1){

            $courseInfo = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");
            $row = mysql_fetch_assoc($courseInfo);

        ?>

                    <?php include("lib/sidebar.php"); ?>

<?php echo $row['CourseName']; ?>

Hello world, this is a test.

            <?php
            }
        else {
            echo "Not logged in.";
        }

    }

    else {
        echo "You are not a member of this Course";
    }

}

else {
    echo "No Course Found";
}

?>

Body:
You could also use php variable $GLOBALS for making your variables visible in all scopes but I would not recommend it for this kind of task. Also, beware - $GLOBALS contains superglobals like $_POST and $_GET, you should keep that in mind, when ie. iterating over it. Furthermore - when you can access $_GET and $_POST in functions, that have smaller scope you still have to use $GLOBALS to access custom ones.

Example for this kind behaviour:

<?php
error_reporting(-1);

$GLOBALS['_customVar'] = 'foobar';
$GLOBALS['_GET']['id'] = 'myId';

    function myFnc() {
    echo $_customVar;
    }

    function myFnc2() {
    echo $_GET['id'];
    }

myFnc();
myFnc2();

?>


问:
SQL Union on the Join subsets
I've got a specific requirement where the backend is supposed to send records that match on a certain criteria from a table. There is a version table that basically contains
[id, ..., modstamp, deleted]
The requirement is to get the records that match between timestamp t1 and t2.
I think I could explain with respect to the sql script:

```<code>create table test (id varchar(10), cv_modstamp DATETIMEOFFSET, sf_deleteddate DATETIMEOFFSET);
insert into test values ('aaa', '2017-10-27 18:45:44 +00:00', null);
insert into test values ('bbb', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('eee', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('aaa', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('bbb', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
insert into test values ('ccc', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('ddd', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
select * from test;

select D1.*, D2.* from
(
select A.*
FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                  GROUP BY id) T
WHERE A.id = T.T_ALIAS_ID
 AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
 AND   A.SF_Deleteddate IS NULL
) D1
INNER JOIN
 (
    select A.*
    FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
    WHERE A.id = T.T_ALIAS_ID
    AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
    AND   A.SF_Deleteddate IS NULL
 )
D2 ON D1.ID = D2.ID
</code>```

This gives out the response:

```<code>aaa 2017-10-28 22:45:44 +00:00      aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00      eee 2017-10-27 18:45:44 +00:00
</code>```

But what is required is:

```<code>aaa 2017-10-28 22:45:44 +00:00
aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
</code>```

Is there a way to display the joined sets on union?

Edit:
Thanks all for the solutions. Each one is good enough for SQL Server. I wanted this to be achieved in a single query. Might be porting similar queries to other database flavors too.

Edit2:
What if the entire columnset have to be selected?

This can be achieved with CTE queries

```<code>with subset1 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)
, subset2 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp > '2017-10-27 18:45:44 +00:00'
            AND CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)

select subset1.* from subset1, subset2 where subset1.id = subset2.id
union all
select subset2.* from subset1, subset2 where subset1.id = subset2.id
order by id, cv_modstamp;
</code>```

答:
To force output of one source row to 2 output rows you can just use a tiny cross join and a case expression:

```<code>select
       case when cj.n = 1 then d1.id          else d2.id end as id
     , case when cj.n = 1 then d1.CV_Modstamp else d2.CV_Modstamp end as CV_Modstamp
from (
     select A.*
     FROM TEST A
     INNER JOIN (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                       FROM TEST
                       WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                       GROUP BY id) T
             ON A.id = T.T_ALIAS_ID  AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
     WHERE  A.SF_Deleteddate IS NULL
     ) D1
INNER JOIN (
    select A.*
    FROM TEST A
    INNER JOIN (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
                ON A.id = T.T_ALIAS_ID AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
    WHERE   A.SF_Deleteddate IS NULL
    ) D2 ON D1.ID = D2.ID
CROSS JOIN (select 1 n union all select 2) cj
</code>```

dbfiddle demo here

Title: SQL Union on the Join subsets

Body:
I've got a specific requirement where the backend is supposed to send records that match on a certain criteria from a table. There is a version table that basically contains
[id, ..., modstamp, deleted]
The requirement is to get the records that match between timestamp t1 and t2.
I think I could explain with respect to the sql script:

create table test (id varchar(10), cv_modstamp DATETIMEOFFSET, sf_deleteddate DATETIMEOFFSET);
insert into test values ('aaa', '2017-10-27 18:45:44 +00:00', null);
insert into test values ('bbb', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('eee', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('aaa', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('bbb', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
insert into test values ('ccc', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('ddd', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
select * from test;

select D1.*, D2.* from
(
select A.*
FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                  GROUP BY id) T
WHERE A.id = T.T_ALIAS_ID
 AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
 AND   A.SF_Deleteddate IS NULL
) D1
INNER JOIN
 (
    select A.*
    FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
    WHERE A.id = T.T_ALIAS_ID
    AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
    AND   A.SF_Deleteddate IS NULL
 )
D2 ON D1.ID = D2.ID

This gives out the response:

aaa 2017-10-28 22:45:44 +00:00      aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00      eee 2017-10-27 18:45:44 +00:00

But what is required is:

aaa 2017-10-28 22:45:44 +00:00
aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00

Is there a way to display the joined sets on union?

Edit:
Thanks all for the solutions. Each one is good enough for SQL Server. I wanted this to be achieved in a single query. Might be porting similar queries to other database flavors too.

Edit2:
What if the entire columnset have to be selected?

This can be achieved with CTE queries

with subset1 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)
, subset2 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp > '2017-10-27 18:45:44 +00:00'
            AND CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)

select subset1.* from subset1, subset2 where subset1.id = subset2.id
union all
select subset2.* from subset1, subset2 where subset1.id = subset2.id
order by id, cv_modstamp;

Body:
To force output of one source row to 2 output rows you can just use a tiny cross join and a case expression:

select
       case when cj.n = 1 then d1.id          else d2.id end as id
     , case when cj.n = 1 then d1.CV_Modstamp else d2.CV_Modstamp end as CV_Modstamp
from (
     select A.*
     FROM TEST A
     INNER JOIN (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                       FROM TEST
                       WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                       GROUP BY id) T
             ON A.id = T.T_ALIAS_ID  AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
     WHERE  A.SF_Deleteddate IS NULL
     ) D1
INNER JOIN (
    select A.*
    FROM TEST A
    INNER JOIN (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
                ON A.id = T.T_ALIAS_ID AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
    WHERE   A.SF_Deleteddate IS NULL
    ) D2 ON D1.ID = D2.ID
CROSS JOIN (select 1 n union all select 2) cj

dbfiddle demo here


问:
Sails.js error trying to edit and update function
I'm trying to create edit function and update function using Sails.js but i get an error after i click on edit button.

    id
    name

    <% for(var i=0; i<categories.length; i++){ %>

     <%= categories[i].id %>
     <%= categories[i].name %>

    ">Edit //when click on this it should be appeared to edit page. but instead I got an error
    <% } %>

    ```

this is my controller

this is my edit page

this is routes

this is the error that i got

I'm sorry to post it as pictures, i don't know what to do.

答:
It looks like there are a couple issues with your code.

If you are looking to return your edit page as a view. The following steps should work.

Firstly, remove all references of your /category/edit route from the routes config file.

Then alter the edit function in your CategoryController to respond with a view and pass the data from the findOne model method into the response. To this replace

```<code>res.redirect('/category');
</code>```

with

```<code>res.view({ category : data });
</code>```

Finally, change the category edit view to work with the data passed in the response.

```<code>action="/category/update/<%= category.id %>"
</code>```

Any questions, let me know in the comments.

Body:
I'm trying to create edit function and update function using Sails.js but i get an error after i click on edit button.

    id
    name

    <% for(var i=0; i<categories.length; i++){ %>

     <%= categories[i].id %>
     <%= categories[i].name %>

    <a href="category/edit?id=<%= categories[i].id %>">Edit //when click on this it should be appeared to edit page. but instead I got an error
    <% } %>

this is my controller

this is my edit page

this is routes

this is the error that i got

I'm sorry to post it as pictures, i don't know what to do.

Body:
It looks like there are a couple issues with your code.

If you are looking to return your edit page as a view. The following steps should work.

Firstly, remove all references of your /category/edit route from the routes config file.

Then alter the edit function in your CategoryController to respond with a view and pass the data from the findOne model method into the response. To this replace

res.redirect('/category');

with

res.view({ category : data });

Finally, change the category edit view to work with the data passed in the response.

action="/category/update/<%= category.id %>"

Any questions, let me know in the comments.


问:
How to specify Python 3 source in Cython's setup.py?
I am trying to do a "Hello World" program in Cython, following this tutorial http://docs.cython.org/src/tutorial/cython_tutorial.html#cython-hello-world

I created helloworld.pyx

```<code>print("Hello World")
</code>```

and setup.py:

```<code>from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("helloworld.pyx")
)
</code>```

How can I change setup.py to specify that my source is Python 3, rather than Python 2 like in the tutorial? If I invoke "cython" command from the command line, it accepts -3 option. But if I compile with python setup.py build_ext --inplace like shown in the tutorial, how do I specify Python 3 source? It may not matter much for a Hello World program, but will matter as I start using Cython for real projects.

答:
According to official documentation on compilation, the Python language level can be specified using a directive through a special header comment at the top of the file, like this:

```<code>#!python
#cython: language_level=3
</code>```

There doesn't seem to be a way to specify this in setup.py. So if you have many Cython files, you'd have to add the compiler directive to each file. Although the only situation I've met so far that needs this directive is for print() as in your sample, and I've used Cython extensively.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to do a "Hello World" program in Cython, following this tutorial http://docs.cython.org/src/tutorial/cython_tutorial.html#cython-hello-world

I created helloworld.pyx

print("Hello World")

and setup.py:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("helloworld.pyx")
)

How can I change setup.py to specify that my source is Python 3, rather than Python 2 like in the tutorial? If I invoke "cython" command from the command line, it accepts -3 option. But if I compile with python setup.py build_ext --inplace like shown in the tutorial, how do I specify Python 3 source? It may not matter much for a Hello World program, but will matter as I start using Cython for real projects.

Body:
According to official documentation on compilation, the Python language level can be specified using a directive through a special header comment at the top of the file, like this:

#!python
#cython: language_level=3

There doesn't seem to be a way to specify this in setup.py. So if you have many Cython files, you'd have to add the compiler directive to each file. Although the only situation I've met so far that needs this directive is for print() as in your sample, and I've used Cython extensively.


问:
Multi-GPU model ( LSTM with Stateful ) on Keras is not working
I am working on LSTM model with stateful using keras (Tensorflow backend); I cannot parallelize it on multi-GPU platform. here is link to code. I am getting following error.

tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [256,75,39] vs. [512,75,39]

[[Node: training/cna/gradients/loss/concatenate_1_loss/mul_grad/BroadcastGradientArgs = BroadcastGradientArgs[T=DT_INT32, _class=["loc:@loss/concatenate_1_loss/mul"], _device="/job:localhost/replica:0/task:0/gpu:0"](training/cna/gradients/loss/concatenate_1_loss/mul_grad/Shape, training/cna/gradients/loss/concatenate_1_loss/mul_grad/Shape_1)]]

[[Node: replica_1/sequential_1/dense_1/truediv/_473 = _Recvclient_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:1", send_device_incarnation=1, tensor_name="edge_3032_replica_1/sequential_1/dense_1/truediv", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]]

I am using 2 GPU with batch size of 256. Please help.

Thanks in advance.

答:
I'm currently working on stateful_multi_gpu, an experimental utility to build stateful RNN models for multi GPU training.

In contrary to Daniel Möller's answer, I think you can explicitly state the order: what sub-batch is processed on which GPU and how the results are put back together.

I still need to test if it correctly trains on multiple GPUs, and if it can parallelise any arbitrary stateful model. Thus, I'm interested in anyones experience using this utility!


问:
Sql query to cakephp query using associations
Here is my correct sql query:

```<code>SELECT * FROM `messages` WHERE ( (sender_id=3 AND user_id=40) OR (sender_id=40 AND user_id=3)) AND offer_id=1
</code>```

I want to use this in Cakephp syntax:

```<code>$this->Message->find('all',array('conditions'=>array(

                'AND'=>array(
                    'OR'=>array(
                        'Message.offer_id'=>$offer_id,
                        'Message.sender_id'=>$sender_id,
                        'Message.user_id'=>$this->Auth->user('id'),
                    ),
                    'OR'=>array(
                        'Message.offer_id'=>$offer_id,
                        'Message.user_id'=>$sender_id,
                        'Message.sender_id'=>$this->Auth->user('id')
                    )
                )

                ),
                'recursive'=>2
                ));
</code>```

Is there anyone who can help me to figure out the issue. Basically I want to get all the messages whether I sent or received for an particular offer.

答:
You have the AND and OR operators reversed.

```<code>            'OR'=>array(
                'AND'=>array(
                    'Message.offer_id'=>$offer_id,
                    'Message.sender_id'=>$sender_id,
                    'Message.user_id'=>$this->Auth->user('id'),
                ),
                'AND'=>array(
                    'Message.offer_id'=>$offer_id,
                    'Message.user_id'=>$sender_id,
                    'Message.sender_id'=>$this->Auth->user('id')
                )
            )
</code>```

Body:
Here is my correct sql query:

SELECT * FROM `messages` WHERE ( (sender_id=3 AND user_id=40) OR (sender_id=40 AND user_id=3)) AND offer_id=1

I want to use this in Cakephp syntax:

$this->Message->find('all',array('conditions'=>array(

                'AND'=>array(
                    'OR'=>array(
                        'Message.offer_id'=>$offer_id,
                        'Message.sender_id'=>$sender_id,
                        'Message.user_id'=>$this->Auth->user('id'),
                    ),
                    'OR'=>array(
                        'Message.offer_id'=>$offer_id,
                        'Message.user_id'=>$sender_id,
                        'Message.sender_id'=>$this->Auth->user('id')
                    )
                )

                ),
                'recursive'=>2
                ));

Is there anyone who can help me to figure out the issue. Basically I want to get all the messages whether I sent or received for an particular offer.

Body:
You have the AND and OR operators reversed.

            'OR'=>array(
                'AND'=>array(
                    'Message.offer_id'=>$offer_id,
                    'Message.sender_id'=>$sender_id,
                    'Message.user_id'=>$this->Auth->user('id'),
                ),
                'AND'=>array(
                    'Message.offer_id'=>$offer_id,
                    'Message.user_id'=>$sender_id,
                    'Message.sender_id'=>$this->Auth->user('id')
                )
            )


问:
Optimization of long method chain in Java
Analyzing some pre-existing third-party Java code (which cannot be re-written) in an application, I discovered that it is almost entirely structured on long method chains, of the form

```<code>public Object process() {
  // Do some class-specific stuff
  return this.getChild().process();
}
</code>```

where there is a base class defining the process() method, inherited by subclasses that redefine that method and the getChild() call is repeated at the end.

Multiple such chains are created (branched off) at runtime as a result of conditional blocks, some of which may return relatively early (e.g., after 10-20 "links" in the chain), but most commonly the "length" of the chain is much bigger and can even exceed 100 consecutive method calls, before returning the result.

The application uses this code to process large files, with results changing for every invocation of the top level method, usually once every different line of each file.

So, two questions:

What performance implications should be expected from such a design, compared to a "regular" one?

Is there any trick to notably improve performance of that code as-is (e.g., by changing some JVM parameter)?

答:
Method calls are very fast (10s or 100s of millions per second), so make sure it's actually beneficial first by profiling the system.

Otherwise, you can use caching to improve efficiency, especially if your results are consistent (same input, same output).

Ex:

```<code>Object cache = null;

public Object process() {
   if (cache == null)
      cache = this.getChild().process();

   return cache;
}
</code>```

If there's some kind of input or state involved, then you could use a Map for the cache which uses keys of the input value and stores values of the output value.

Body:
Analyzing some pre-existing third-party Java code (which cannot be re-written) in an application, I discovered that it is almost entirely structured on long method chains, of the form

public Object process() {
  // Do some class-specific stuff
  return this.getChild().process();
}

where there is a base class defining the process() method, inherited by subclasses that redefine that method and the getChild() call is repeated at the end.

Multiple such chains are created (branched off) at runtime as a result of conditional blocks, some of which may return relatively early (e.g., after 10-20 "links" in the chain), but most commonly the "length" of the chain is much bigger and can even exceed 100 consecutive method calls, before returning the result.

The application uses this code to process large files, with results changing for every invocation of the top level method, usually once every different line of each file.

So, two questions:

What performance implications should be expected from such a design, compared to a "regular" one?

Is there any trick to notably improve performance of that code as-is (e.g., by changing some JVM parameter)?

Body:
Method calls are very fast (10s or 100s of millions per second), so make sure it's actually beneficial first by profiling the system.

Otherwise, you can use caching to improve efficiency, especially if your results are consistent (same input, same output).

Ex:

Object cache = null;

public Object process() {
   if (cache == null)
      cache = this.getChild().process();

   return cache;
}

If there's some kind of input or state involved, then you could use a Map for the cache which uses keys of the input value and stores values of the output value.


问:
I'm trying to create csv file with path.join
I want to save the part of dataframe to csv file with the following name and parameters:

```<code>train_file_name = "train/lastfm.train.0"
train_data[["user_id", "artist_id", "total-plays"]].to_csv(
path.join(data_dir, train_file_name),
sep="\t",
header=False,
index=False
)
</code>```

returns the Error:

```<code>FileNotFoundError: [Errno 2] No such file or directory: '/home/Documents/lastfm/train/lastfm.train.0'
</code>```

But the directory is correct

答:
If the directory of train is not made it will create this error, you may ensure the creation of the full directory path by calling this first

Run this before you call to_csv

```<code>directory = path.join(data_dir, "train/lastfm.train.0")
if not os.path.exists(directory):
        os.makedirs(directory)
</code>```

EDIT: Another issue will be a file permission issue.
Change the permission of the folder you are trying to write in

```<code>sudo chmod 755 train
</code>```

Or on windows right click the folder and uncheck read-only

Body:
I want to save the part of dataframe to csv file with the following name and parameters:

train_file_name = "train/lastfm.train.0"
train_data[["user_id", "artist_id", "total-plays"]].to_csv(
path.join(data_dir, train_file_name),
sep="\t",
header=False,
index=False
)

returns the Error:

FileNotFoundError: [Errno 2] No such file or directory: '/home/Documents/lastfm/train/lastfm.train.0'

But the directory is correct

Body:
If the directory of train is not made it will create this error, you may ensure the creation of the full directory path by calling this first

Run this before you call to_csv

directory = path.join(data_dir, "train/lastfm.train.0")
if not os.path.exists(directory):
        os.makedirs(directory)

EDIT: Another issue will be a file permission issue.
Change the permission of the folder you are trying to write in

sudo chmod 755 train

Or on windows right click the folder and uncheck read-only


问:
Do glue records in non-circular dns-lookups speed up domain resolution or not?
Doing a lookup for my domain on http://www.intodns.com/ I noticed theese two messages:

In Parent section:

DNS Parent sent Glue  The parent
  nameserver g.gtld-servers.net is not
  sending out GLUE for every nameservers
  listed, meaning he is sending out your
  nameservers host names without sending
  the A records of those nameservers.
  It's ok but you have to know that this
  will require an extra A lookup that
  can delay a little the connections to
  your site. This happens a lot if you
  have nameservers on different TLD
  (domain.com for example with
  nameserver ns.domain.org.)

and in NS section:

Glue for NS records   INFO: GLUE was not
  sent when I asked your nameservers for
  your NS records.This is ok but you
  should know that in this case an extra
  A record lookup is required in order
  to get the IPs of your NS records. The
  nameservers without glue are:
  109.230.225.96
  84.201.40.52 You can fix this for example by adding A records to your
  nameservers for the zones listed
  above.

I do perfectly understand that the primary objective of glue records is to resolve circular dependencies.

The classic use case:

my domain is example.com and I want to have the nameserver ns1.example.com. This will never work because i cannot know the ip of ns1.example.com if I don't fetch example.com and in order to do that I need to fetch it from ns1.example.com. To resolve this deadlock I add a glue record to ns1.example.com containing the ip adress of the nameserver, so this can work out.

So this problem does not occour if the nameservers are in a different TLD than the domain i want to look up. But however to fetch the zone information from the nameservers I need to know their ip adress right? And in order to know that i need to fetch the zone the nameservers are in from their respective nameservers, right? (or rather my ISP needs to do that in the background) So an extra lookup that takes time?

If I now have glue records, I know the IP adress right away without the need to look it up - so this should speed up the resolution of my domain, shouldnt it?

However my DNS zone provider (tecserver.at) replied that

this would make no sense because "we
  are not running ns1.ourdomain.com an
  ns1.ourdomain.com as authorative NS for
  ourdomain.com.

This would be the only sense for glue
  records.

Tecserver has a glue record because
  the NS for tecserver.at are
  ns1.tecserver.at and ns2.tecserver.at.
  Therefore a glue record is needed for
  resolution.

答:
simple answer for those interested:

glue records do speed up dns resolution, regardless if used for internal nameserver names or not.


问:
Xamarin Forms error while writing anim R$anim.class
Hello i am update to visual studio community 2017 15.5 on debug i have this error</p>

```<code>obj\Debug\android\src\android\support\compat\R.java:11: error: error while writing anim: obj\Debug\android\bin\classes\android\support\compat\R$anim.class (El proceso no tiene acceso al archivo porque est├í siendo utilizado por otro proceso)
3>      public static final class anim {
3>                          ^
3>  Note: Some input files use or override a deprecated API.
3>  Note: Recompile with -Xlint:deprecation for details.
3>  Note: Some input files use unchecked or unsafe operations.
3>  Note: Recompile with -Xlint:unchecked for details.
3>  1 error
</code>```

答:
EDIT: This bug should be fixed now if you update to Visual Studio version 15.5.2
https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#15.5.2
"Release Date: December 14, 2017 - Visual Studio 2017 version 15.5.2
Top Issues Fixed in this Release
These are the customer-reported issues addressed in this release:

Xamarin Android project cannot build because R$anim.class is in use."

Short Answer

1- Open the task manager, and kill the MSBuild.exe operation.

2- If 1 didnt work, close and re-open Visual Studio
2a. Also make sure you close the emulator. (edit)

Longer Answer-

I’ve started to occasionally get the same build errors which is some variation of
“Xamarin Android project cannot build because R$anim.class is in use”

I’m looking into it and it looks like this is a pretty recent issue they are having since the Xamarin Android 15.5 release.
Here’s a link to a thread where the bug is being reported and actively getting worked on. As of the time of this email a fix hasn’t has been pushed yet, but there is a quick fix that worked for me.
https://developercommunity.visualstudio.com/content/problem/155693/xamarin-android-project-cannot-build-because-ranim.html

It appears the issue is in some way tied to the MSBuild processes.
Open the task manager, and kill the MSBuild.exe operation.

After that, maybe a clean and rebuild, the android emulator seems to work.
If that doesn’t work, closing and re-opening VS seems to do the trick. But I would try the task manager first, it might be a faster way to clear the error.

Edit -
I also close the emulator while I'm restarting my visual studio. I could be wrong on this, but it looks like it keeps making extra instances of MSbuild.exe and needs a good close and re-launch.

Body:
Hello i am update to visual studio community 2017 15.5 on debug i have this error

obj\Debug\android\src\android\support\compat\R.java:11: error: error while writing anim: obj\Debug\android\bin\classes\android\support\compat\R$anim.class (El proceso no tiene acceso al archivo porque est├í siendo utilizado por otro proceso)
3>      public static final class anim {
3>                          ^
3>  Note: Some input files use or override a deprecated API.
3>  Note: Recompile with -Xlint:deprecation for details.
3>  Note: Some input files use unchecked or unsafe operations.
3>  Note: Recompile with -Xlint:unchecked for details.
3>  1 error


问:
Angular4/Javascript Date changing after Date constructor call with timezone
On my Angular 4 application I'm getting an date from my API call as '1990-03-31T23:00:00-06:00' string but when try to create a Date object and do getMonth() I'm getting the wrong day. After testing around in the console:

```<code>> var x = new Date('1990-03-31T23:00:00-06:00');
undefined
 > x
Sun Apr 01 1990 00:00:00 GMT-0500 (Central Daylight Time)
> var x = new Date('1990-03-31T23:00:00');
Sat Mar 31 1990 23:00:00 GMT-0500 (Central Daylight Time)
> new Date().getTimezoneOffset();
360
</code>```

and here's my code:

new Date(this.bsSelected.StatementDate).getMonth()

Not sure why this happening and how to avoid it. My temporary solution is to remove the TimeZone from the API output but I wonder if I understood the problem I could come up with a better solution.

答:
Because of Your browser is in different GMT that makes to become 1st of April.

I mean if in GMT-0600 is 31 March 1990 so in user's browser it's 01 April 1990

Try to remove offset part in string, browser will use that timestamp as current time.

check this one:

console.log('With timezone:', new Date('1990-03-31T23:00:00-06:00').getMonth());

console.log('Without timezone:', new Date('1990-03-31T23:00:00').getMonth());```

p.s. getMonth() returns number between 0 and 11

Body:
On my Angular 4 application I'm getting an date from my API call as '1990-03-31T23:00:00-06:00' string but when try to create a Date object and do getMonth() I'm getting the wrong day. After testing around in the console:

> var x = new Date('1990-03-31T23:00:00-06:00');
undefined
 > x
Sun Apr 01 1990 00:00:00 GMT-0500 (Central Daylight Time)
> var x = new Date('1990-03-31T23:00:00');
Sat Mar 31 1990 23:00:00 GMT-0500 (Central Daylight Time)
> new Date().getTimezoneOffset();
360

and here's my code:

new Date(this.bsSelected.StatementDate).getMonth()

Not sure why this happening and how to avoid it. My temporary solution is to remove the TimeZone from the API output but I wonder if I understood the problem I could come up with a better solution.

Body:
Because of Your browser is in different GMT that makes to become 1st of April.

I mean if in GMT-0600 is 31 March 1990 so in user's browser it's 01 April 1990

Try to remove offset part in string, browser will use that timestamp as current time.

check this one:

console.log('With timezone:', new Date('1990-03-31T23:00:00-06:00').getMonth());

console.log('Without timezone:', new Date('1990-03-31T23:00:00').getMonth());

p.s. getMonth() returns number between 0 and 11


问:
How to explore Dynamics NAV Native Database?
I have to prepare some queries and export data from Dynamics NAV Native Database.

I have an ODBC driver installed that connects to the database but I don't know how to explore it and check tables and data.

答: Please let me know what version of NAV you have. If you are using RTC, in any page you should be able to go to the "about to" page and see the table and the all of its fields. If you are using NAV classic, you will have to hit ctrl + f2 in order  to go to the designer mode and right click on the fields and view their properties. </p>


问:
INSERT INTO 2 tables query
I'm trying to insert with one query into 2 tables, but is not working.
I want to save all the _POST data into "tours" table and image gallery intro "poze_articol" table where "pid" from poze_articol is the id of tours id, some help is appreciated because i'm new with php, thank you!

Php code:

```<code><?php
$dbhost = '';
$dbuser = '';
$dbpass = '';
$myDBname = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $myDBname);
$db_selected = mysql_select_db('antonytravel', $conn);
if (!$db_selected) {
    die ('Can\'t use antonytravel : ' . mysql_error());
}
if(isset($_POST['addtour']))
{
if (!isset($_FILES['poza_caseta']['tmp_name'])) {
    echo "";
    }else{
    $file=$_FILES['poza_caseta']['tmp_name'];
    $image= addslashes(file_get_contents($_FILES['poza_caseta']['tmp_name']));
    $image_name= addslashes($_FILES['poza_caseta']['name']);

            move_uploaded_file($_FILES["poza_caseta"]["tmp_name"],"../../../../img/traseu_thmb/" . $_FILES["poza_caseta"]["name"]);

            $poza_caseta="img/traseu_thmb/" . $_FILES["poza_caseta"]["name"];

    if (!isset($_FILES['poza_header']['tmp_name'])) {
    echo "";
    }else{
    $files=$_FILES['poza_header']['tmp_name'];
    $images= addslashes(file_get_contents($_FILES['poza_header']['tmp_name']));
    $images_name= addslashes($_FILES['poza_header']['name']);

            move_uploaded_file($_FILES["poza_header"]["tmp_name"],"../../../../img/poze_header/" . $_FILES["poza_header"]["name"]);

            $poza_header="img/poze_header/" . $_FILES["poza_header"]["name"];

            ########### Poze Upload #########
error_reporting(0);
define ("MAX_SIZE","9000");
function getExtension($str)
{
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}
$valid_formats = array("jpg", "png", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{

    $uploaddir = "../../../../img/gallery/"; //image upload directory
    foreach ($_FILES['photos']['name'] as $name => $value)
    {

        $filename = stripslashes($_FILES['photos']['name'][$name]);
        $size=filesize($_FILES['photos']['tmp_name'][$name]);
        //get the extension of the file in a lower case format
          $ext = getExtension($filename);
          $ext = strtolower($ext);

         if(in_array($ext,$valid_formats))
         {
           if ($size < (MAX_SIZE*1024))
           {
           $image_name=time().$filename;

           $newname=$uploaddir.$image_name;

           if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
           {

$sqlz =  "INSERT INTO tours (titlu,durata,descriere,pret,ribbon,poza,titlu_slider,desc_slider,poza_slider,descriere_box,titlu_box1,desc_box1,titlu_box2,desc_box2,titlu_box3,desc_box3,titlu_box4,desc_box4,poze_articol) VALUES ('".$_POST["oras_caseta"]."','".$_POST["durata_caseta"]."','".$_POST["descriere_caseta"]."','".$_POST["pret_caseta"]."','".$_POST["icon_caseta"]."','$poza_caseta','".$_POST["titlu_slider"]."','".$_POST["descriere_slider"]."','$poza_header','".$_POST["descriere_overview"]."','".$_POST["titlu_box1"]."','".$_POST["desc_box1"]."','".$_POST["titlu_box2"]."','".$_POST["desc_box2"]."','".$_POST["titlu_box3"]."','".$_POST["desc_box3"]."','".$_POST["titlu_box4"]."','".$_POST["desc_box4"]."')";

$sqlz .=  "INSERT INTO poze_articol (poza_slider,pid) VALUES ('img/gallery/$image_name','1')";
$retval = mysql_query( $sqlz, $conn );

echo '<div class="alert alert-success" role="alert">
  <strong>Bravo!</strong> Ai adaugat cu succes un traseu pe site.
</div>';
}
 }
  }
   }
    }
     }
      }
}
?>
</code>```

答:
You can't concatenate your SQL instructions like you did with your $sqlz variable.

You have to execute your SQL insert queries one at a time.

So, right after your first INSERT into tours you need to execute mysql_query( $sqlz, $conn ). After doing that, you need to reuse your $sqlz again with your INSERT INTO poze_articol and then execute your mysql_query( $sqlz, $conn ) one more time. Please try something like the following:

```<code>$sqlz =  "INSERT INTO tours (titlu,durata,descriere,pret,ribbon,poza,titlu_slider,desc_slider,poza_slider,descriere_box,titlu_box1,desc_box1,titlu_box2,desc_box2,titlu_box3,desc_box3,titlu_box4,desc_box4,poze_articol) VALUES ('".$_POST["oras_caseta"]."','".$_POST["durata_caseta"]."','".$_POST["descriere_caseta"]."','".$_POST["pret_caseta"]."','".$_POST["icon_caseta"]."','$poza_caseta','".$_POST["titlu_slider"]."','".$_POST["descriere_slider"]."','$poza_header','".$_POST["descriere_overview"]."','".$_POST["titlu_box1"]."','".$_POST["desc_box1"]."','".$_POST["titlu_box2"]."','".$_POST["desc_box2"]."','".$_POST["titlu_box3"]."','".$_POST["desc_box3"]."','".$_POST["titlu_box4"]."','".$_POST["desc_box4"]."')";

mysql_query( $sqlz, $conn );

$sqlz =  "INSERT INTO poze_articol (poza_slider,pid) VALUES ('img/gallery/$image_name','1')";

mysql_query( $sqlz, $conn );
</code>```

Title: INSERT INTO 2 tables query

Body:
I'm trying to insert with one query into 2 tables, but is not working.
I want to save all the _POST data into "tours" table and image gallery intro "poze_articol" table where "pid" from poze_articol is the id of tours id, some help is appreciated because i'm new with php, thank you!

Php code:

<?php
$dbhost = '';
$dbuser = '';
$dbpass = '';
$myDBname = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $myDBname);
$db_selected = mysql_select_db('antonytravel', $conn);
if (!$db_selected) {
    die ('Can\'t use antonytravel : ' . mysql_error());
}
if(isset($_POST['addtour']))
{
if (!isset($_FILES['poza_caseta']['tmp_name'])) {
    echo "";
    }else{
    $file=$_FILES['poza_caseta']['tmp_name'];
    $image= addslashes(file_get_contents($_FILES['poza_caseta']['tmp_name']));
    $image_name= addslashes($_FILES['poza_caseta']['name']);

            move_uploaded_file($_FILES["poza_caseta"]["tmp_name"],"../../../../img/traseu_thmb/" . $_FILES["poza_caseta"]["name"]);

            $poza_caseta="img/traseu_thmb/" . $_FILES["poza_caseta"]["name"];

    if (!isset($_FILES['poza_header']['tmp_name'])) {
    echo "";
    }else{
    $files=$_FILES['poza_header']['tmp_name'];
    $images= addslashes(file_get_contents($_FILES['poza_header']['tmp_name']));
    $images_name= addslashes($_FILES['poza_header']['name']);

            move_uploaded_file($_FILES["poza_header"]["tmp_name"],"../../../../img/poze_header/" . $_FILES["poza_header"]["name"]);

            $poza_header="img/poze_header/" . $_FILES["poza_header"]["name"];

            ########### Poze Upload #########
error_reporting(0);
define ("MAX_SIZE","9000");
function getExtension($str)
{
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}
$valid_formats = array("jpg", "png", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{

    $uploaddir = "../../../../img/gallery/"; //image upload directory
    foreach ($_FILES['photos']['name'] as $name => $value)
    {

        $filename = stripslashes($_FILES['photos']['name'][$name]);
        $size=filesize($_FILES['photos']['tmp_name'][$name]);
        //get the extension of the file in a lower case format
          $ext = getExtension($filename);
          $ext = strtolower($ext);

         if(in_array($ext,$valid_formats))
         {
           if ($size < (MAX_SIZE*1024))
           {
           $image_name=time().$filename;

           $newname=$uploaddir.$image_name;

           if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
           {

$sqlz =  "INSERT INTO tours (titlu,durata,descriere,pret,ribbon,poza,titlu_slider,desc_slider,poza_slider,descriere_box,titlu_box1,desc_box1,titlu_box2,desc_box2,titlu_box3,desc_box3,titlu_box4,desc_box4,poze_articol) VALUES ('".$_POST["oras_caseta"]."','".$_POST["durata_caseta"]."','".$_POST["descriere_caseta"]."','".$_POST["pret_caseta"]."','".$_POST["icon_caseta"]."','$poza_caseta','".$_POST["titlu_slider"]."','".$_POST["descriere_slider"]."','$poza_header','".$_POST["descriere_overview"]."','".$_POST["titlu_box1"]."','".$_POST["desc_box1"]."','".$_POST["titlu_box2"]."','".$_POST["desc_box2"]."','".$_POST["titlu_box3"]."','".$_POST["desc_box3"]."','".$_POST["titlu_box4"]."','".$_POST["desc_box4"]."')";

$sqlz .=  "INSERT INTO poze_articol (poza_slider,pid) VALUES ('img/gallery/$image_name','1')";
$retval = mysql_query( $sqlz, $conn );

echo '

  Bravo! Ai adaugat cu succes un traseu pe site.

';
}
 }
  }
   }
    }
     }
      }
}
?>

Body:
You can't concatenate your SQL instructions like you did with your $sqlz variable.

You have to execute your SQL insert queries one at a time.

So, right after your first INSERT into tours you need to execute mysql_query( $sqlz, $conn ). After doing that, you need to reuse your $sqlz again with your INSERT INTO poze_articol and then execute your mysql_query( $sqlz, $conn ) one more time. Please try something like the following:

$sqlz =  "INSERT INTO tours (titlu,durata,descriere,pret,ribbon,poza,titlu_slider,desc_slider,poza_slider,descriere_box,titlu_box1,desc_box1,titlu_box2,desc_box2,titlu_box3,desc_box3,titlu_box4,desc_box4,poze_articol) VALUES ('".$_POST["oras_caseta"]."','".$_POST["durata_caseta"]."','".$_POST["descriere_caseta"]."','".$_POST["pret_caseta"]."','".$_POST["icon_caseta"]."','$poza_caseta','".$_POST["titlu_slider"]."','".$_POST["descriere_slider"]."','$poza_header','".$_POST["descriere_overview"]."','".$_POST["titlu_box1"]."','".$_POST["desc_box1"]."','".$_POST["titlu_box2"]."','".$_POST["desc_box2"]."','".$_POST["titlu_box3"]."','".$_POST["desc_box3"]."','".$_POST["titlu_box4"]."','".$_POST["desc_box4"]."')";

mysql_query( $sqlz, $conn );

$sqlz =  "INSERT INTO poze_articol (poza_slider,pid) VALUES ('img/gallery/$image_name','1')";

mysql_query( $sqlz, $conn );


问:
pytest - set environment variables with environment specific values
I am using pytest to run tests for my python services that run in AWS.

I am trying to test a service which triggers from an SNS topic. So my test writes to the SNS topic. The topic ARN is different for dev, staging, prod.

In the test I would like to be able to access the topic ARN using the same environment variable and pick up the right topic for each environment.

```<code>self.sns_topic_arn = os.environ['SNS_TOPIC']
</code>```

I have a service which does set, build, test which is independent of all my services and deployment environments.

I refer to this discussion on how to pass the env vars How to pass environment variables to pytest

However I am not able to figure out how to set the value per environment. Is there a template or a best practice?

答:
I am posting the solution which works for us. I am not sure this would be a useful answer in all use cases or that my question applies to many users.
The way our test & deployment is set up, this turned out to be simple. I didn't figure it out right away to start with :|.

I have a service which does set, build, test which is independent of all my services and deployment environments.

The service runs these tests in a docker container.
The tests are run as acceptance tests using AWS code pipeline and there's a Docker config for each environment.
So we are able to set the right 'SNS_TOPIC' as the environment variable in each config.

Body:
I am using pytest to run tests for my python services that run in AWS.

I am trying to test a service which triggers from an SNS topic. So my test writes to the SNS topic. The topic ARN is different for dev, staging, prod.

In the test I would like to be able to access the topic ARN using the same environment variable and pick up the right topic for each environment.

self.sns_topic_arn = os.environ['SNS_TOPIC']

I have a service which does set, build, test which is independent of all my services and deployment environments.

I refer to this discussion on how to pass the env vars How to pass environment variables to pytest

However I am not able to figure out how to set the value per environment. Is there a template or a best practice?


问:
removing or ignoreing duplicate lines from txt file C++
currently i am trying to read a text file and ignore the duplicate lines inside it. Here's the code sample of what i have done so far

```<code>string filename;
            cout<<"Please enter filename: "<<endl;
            cin>>filename;
            ifstream inFile(filename.data());

            typedef std::map<std::string, int> line_record;
            line_record lines;
            int line_number = 1;

            if(inFile.is_open())
            {
                while(std::getline(inFile, line))
                {
                    line_record::iterator existing = lines.find(line);
                    if(existing != lines.end())
                    {
                        existing->second = (-1);
                    }
                    else
                    {
                        lines.insert(std::make_pair(line,line_number));
                        ++line_number;
                        getline(inFile,line);
                        cout<<line<<endl;
                        noOfLine++;
                    }

                }
            }else
            {
                cout<<"Error opening file! Please try again!"<<endl;
            }
            cout<<"\n"<<noOfLine<<" record(s) read in successfully!\n"<<endl;
</code>```

The text file(below):

```<code>Point2D, [3, 2]
Line3D, [7, 12, 3], [-9, 13, 68]
Point3D, [1, 3, 8]
Line2D, [5, 7], [3, 8]
Point2D, [3, 2]
Line3D, [7, -12, 3], [9, 13, 68]
Point3D, [6, 9, 5]
Point2D, [3, 2]
Line3D, [70, -120, -3], [-29, 1, 268]
Line3D, [25, -69, -33], [-2, -41, 58]
Point3D, [6, 9, -50]
</code>```

But the results i am getting is:

```<code>Line3D, [7, 12, 3], [-9, 13, 68]
Line2D, [5, 7], [3, 8]
Point3D, [6, 9, 5]
Line3D, [25, -69, -33], [-2, -41, 58]
Point3D, [6, 9, -50]
</code>```

Any help?? Thanks!!

答:
i just edit few things  and it's work `if (myfile.is_open())

```<code>{

            while(getline(myfile, line)){

                line_record::iterator existing = lines.find(line);

                if(existing != lines.end())
                {
                    existing->second = (-1);

                }
                else
                {

                    lines.insert(make_pair(line,line_number));
                    ++line_number;
                    cout<<line<<endl;

                    count++;
                }

            }

            cout << "its -- > "<<count <<" record"<< endl;

    myfile.close();

}
</code>```

`

Body:
currently i am trying to read a text file and ignore the duplicate lines inside it. Here's the code sample of what i have done so far

string filename;
            cout<<"Please enter filename: "<<endl;
            cin>>filename;
            ifstream inFile(filename.data());

            typedef std::map<std::string, int> line_record;
            line_record lines;
            int line_number = 1;

            if(inFile.is_open())
            {
                while(std::getline(inFile, line))
                {
                    line_record::iterator existing = lines.find(line);
                    if(existing != lines.end())
                    {
                        existing->second = (-1);
                    }
                    else
                    {
                        lines.insert(std::make_pair(line,line_number));
                        ++line_number;
                        getline(inFile,line);
                        cout<<line<<endl;
                        noOfLine++;
                    }

                }
            }else
            {
                cout<<"Error opening file! Please try again!"<<endl;
            }
            cout<<"\n"<<noOfLine<<" record(s) read in successfully!\n"<<endl;

The text file(below):

Point2D, [3, 2]
Line3D, [7, 12, 3], [-9, 13, 68]
Point3D, [1, 3, 8]
Line2D, [5, 7], [3, 8]
Point2D, [3, 2]
Line3D, [7, -12, 3], [9, 13, 68]
Point3D, [6, 9, 5]
Point2D, [3, 2]
Line3D, [70, -120, -3], [-29, 1, 268]
Line3D, [25, -69, -33], [-2, -41, 58]
Point3D, [6, 9, -50]

But the results i am getting is:

Line3D, [7, 12, 3], [-9, 13, 68]
Line2D, [5, 7], [3, 8]
Point3D, [6, 9, 5]
Line3D, [25, -69, -33], [-2, -41, 58]
Point3D, [6, 9, -50]

Any help?? Thanks!!

Body:
i just edit few things  and it's work `if (myfile.is_open())

{

            while(getline(myfile, line)){

                line_record::iterator existing = lines.find(line);

                if(existing != lines.end())
                {
                    existing->second = (-1);

                }
                else
                {

                    lines.insert(make_pair(line,line_number));
                    ++line_number;
                    cout<<line<<endl;

                    count++;
                }

            }

            cout << "its -- > "<<count <<" record"<< endl;

    myfile.close();

}

`


问:
Does anyone have a good Proper Case algorithm
Does anyone have a trusted Proper Case or PCase algorithm (similar to a UCase or Upper)?  I'm looking for something that takes a value such as "GEORGE BURDELL" or "george burdell" and turns it into "George Burdell".

I have a simple one that handles the simple cases.  The ideal would be to have something that can handle things such as "O'REILLY" and turn it into "O'Reilly", but I know that is tougher.

I am mainly focused on the English language if that simplifies things.

UPDATE: I'm using C# as the language, but I can convert from almost anything (assuming like functionality exists).

I agree that the McDonald's scneario is a tough one.  I meant to mention that along with my O'Reilly example, but did not in the original post.

答:
I know this thread has been open for awhile, but as I was doing research for this problem I came across this nifty site, which allows you to paste in names to be capitalized quite quickly: https://dialect.ca/code/name-case/. I wanted to include it here for reference for others doing similar research/projects.

They release the algorithm they have written in php at this link: https://dialect.ca/code/name-case/name_case.phps

A preliminary test and reading of their code suggests they have been quite thorough.

LastEditorDisplayName: jttraino


问:
error: use of deleted function?
I am currently trying to implement a simple btree, but seem to have run into an issue here..

```<code>#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

struct element
{
    int x;
    int y;
    element (int x, int y)
    {
        this->x = x;
        this->y = y;
    }
};

int sum(element key)
{
    return key.x + key.y;
}

struct node
{
    element key;
    node *child_left;
    node *child_right;
};

class tree{

    void insert(element key);
    void insert(element key, node* leaf);
    node* root;
    tree()
    {
        this->root = NULL;
    }
};

void tree::insert(element key){
    if(this->root != NULL){
        insert(key, this->root);
    }else{
        this->root = new node;
        this->root->key.x = key.x;
        this->root->key.y = key.y;
        this->root->child_left = NULL;
        this->root->child_right = NULL;

    }
}

void tree::insert(element key, node* leaf){
    if(sum(key) < sum(leaf->key)){
        if(leaf->child_left != NULL){
            insert(key, leaf->child_left);
        }else{
          leaf->child_left = new node;
          leaf->child_left->key.x = key.x;
          leaf->child_left->key.y = key.y;
          leaf->child_left->child_left = NULL;
          leaf->child_left->child_right = NULL;
        }
    }else if(sum(key) >= sum(leaf->key)){
        if(leaf->child_right != NULL){
            insert(key, leaf->child_right);
        }else{
            leaf->child_right = new node;
            leaf->child_right->key.x = key.x;
            leaf->child_right->key.y = key.y;
            leaf->child_right->child_left = NULL;
            leaf->child_right->child_right = NULL;
        }
    }
}

int main()
{

    std::cout << "Somet"<< std::endl;

}
</code>```

https://wandbox.org/permlink/0InxxBLt59PFVppt

Which gives me error message:

```<code>Start
prog.cc: In member function 'void tree::insert(element)':
prog.cc:49:20: error: use of deleted function 'node::node()'
   this->root = new node;
                    ^~~~
prog.cc:26:8: note: 'node::node()' is implicitly deleted because the default definition would be ill-formed:
 struct node
        ^~~~
prog.cc:26:8: error: no matching function for call to 'element::element()'
prog.cc:14:5: note: candidate: 'element::element(int, int)'
     element (int x, int y)
     ^~~~~~~
prog.cc:14:5: note:   candidate expects 2 arguments, 0 provided
prog.cc:10:8: note: candidate: 'constexpr element::element(const element&)'
 struct element
        ^~~~~~~
prog.cc:10:8: note:   candidate expects 1 argument, 0 provided
prog.cc:10:8: note: candidate: 'constexpr element::element(element&&)'
prog.cc:10:8: note:   candidate expects 1 argument, 0 provided
prog.cc: In member function 'void tree::insert(element, node*)':
prog.cc:66:28: error: use of deleted function 'node::node()'
     leaf->child_left = new node;
                            ^~~~
prog.cc:76:28: error: use of deleted function 'node::node()'
    leaf->child_right = new node;
                            ^~~~
1
Finish
</code>```

I am not sure I understand why this is causing problems... So some explanations would be appreciated, does structs (and classes) by itself have a default constructor? so why is it complaining?

答:
The default constructor of node is deleted, because element has none (thats btw exactly what the error message is trying to tell you ;). There is no compiler generated default constructor for element because you provided your own constructor (which is not a default constructor, ie you cannot call it without arguments). Either write a default constructor for node that passes parameters to the element constructor:

```<code>node() : key(element(1,2)) {}
</code>```

or one for element:

```<code>element(int x=0,int y=0) : x(x),y(y) {}
</code>```

In the latter case, a default constructor for node can and will be generated by the compiler because it is really just this:

```<code>node() {}
</code>```

Title: error: use of deleted function?

Body:
I am currently trying to implement a simple btree, but seem to have run into an issue here..

#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

struct element
{
    int x;
    int y;
    element (int x, int y)
    {
        this->x = x;
        this->y = y;
    }
};

int sum(element key)
{
    return key.x + key.y;
}

struct node
{
    element key;
    node *child_left;
    node *child_right;
};

class tree{

    void insert(element key);
    void insert(element key, node* leaf);
    node* root;
    tree()
    {
        this->root = NULL;
    }
};

void tree::insert(element key){
    if(this->root != NULL){
        insert(key, this->root);
    }else{
        this->root = new node;
        this->root->key.x = key.x;
        this->root->key.y = key.y;
        this->root->child_left = NULL;
        this->root->child_right = NULL;

    }
}

void tree::insert(element key, node* leaf){
    if(sum(key) < sum(leaf->key)){
        if(leaf->child_left != NULL){
            insert(key, leaf->child_left);
        }else{
          leaf->child_left = new node;
          leaf->child_left->key.x = key.x;
          leaf->child_left->key.y = key.y;
          leaf->child_left->child_left = NULL;
          leaf->child_left->child_right = NULL;
        }
    }else if(sum(key) >= sum(leaf->key)){
        if(leaf->child_right != NULL){
            insert(key, leaf->child_right);
        }else{
            leaf->child_right = new node;
            leaf->child_right->key.x = key.x;
            leaf->child_right->key.y = key.y;
            leaf->child_right->child_left = NULL;
            leaf->child_right->child_right = NULL;
        }
    }
}

int main()
{

    std::cout << "Somet"<< std::endl;

}

https://wandbox.org/permlink/0InxxBLt59PFVppt

Which gives me error message:

Start
prog.cc: In member function 'void tree::insert(element)':
prog.cc:49:20: error: use of deleted function 'node::node()'
   this->root = new node;
                    ^~~~
prog.cc:26:8: note: 'node::node()' is implicitly deleted because the default definition would be ill-formed:
 struct node
        ^~~~
prog.cc:26:8: error: no matching function for call to 'element::element()'
prog.cc:14:5: note: candidate: 'element::element(int, int)'
     element (int x, int y)
     ^~~~~~~
prog.cc:14:5: note:   candidate expects 2 arguments, 0 provided
prog.cc:10:8: note: candidate: 'constexpr element::element(const element&)'
 struct element
        ^~~~~~~
prog.cc:10:8: note:   candidate expects 1 argument, 0 provided
prog.cc:10:8: note: candidate: 'constexpr element::element(element&&)'
prog.cc:10:8: note:   candidate expects 1 argument, 0 provided
prog.cc: In member function 'void tree::insert(element, node*)':
prog.cc:66:28: error: use of deleted function 'node::node()'
     leaf->child_left = new node;
                            ^~~~
prog.cc:76:28: error: use of deleted function 'node::node()'
    leaf->child_right = new node;
                            ^~~~
1
Finish

I am not sure I understand why this is causing problems... So some explanations would be appreciated, does structs (and classes) by itself have a default constructor? so why is it complaining?

Body:
The default constructor of node is deleted, because element has none (thats btw exactly what the error message is trying to tell you ;). There is no compiler generated default constructor for element because you provided your own constructor (which is not a default constructor, ie you cannot call it without arguments). Either write a default constructor for node that passes parameters to the element constructor:

node() : key(element(1,2)) {}

or one for element:

element(int x=0,int y=0) : x(x),y(y) {}

In the latter case, a default constructor for node can and will be generated by the compiler because it is really just this:

node() {}


问:
How to get better at UIKit/Core Animation with no design experience?
I've read through Aaron Hillegass's iPhone Programming: The Big Nerd Ranch Guide and I feel I have a solid understanding on the fundamental design patterns/APIs of UIKit. After searching on both here and on Google, it seems that to take the 'next step,' I should practice by writing apps. But: I have no design experience, and I feel that unless I'm doing some work that involves custom controls or any sort of other custom elements, re-writing apps with the same standard controls isn't helping me get better at iPhone dev. So, here are my options:

1) Learn design

2) Find a designer who has some app ideas (note that this is just in my spare time, and I'm not yet looking to make it my full time job, so finding a designer who would just give me free controls/designs would probably be hard)

3) ???

Anybody have other ideas?

TL;DR: I want to get better at iPhone dev by writing more apps for practice, but I'm not good at visual design.

EDIT: To be clear, I am not trying to make these apps with the intention of releasing for the App Store. I am writing these apps to practice iPhone dev and to get better at it.

答:
I'd suggest, you just start to create some apps. Skill comes with practice.

You will surely have ideas for some apps. Just start with a simple idea.

Even if you are just using the standard UIKit classes you will learn something new. It's easy to think you have understood everything you just read, but in practice you will be facing some little problems you wouldn't even know exist, before.

Also, you can create some good-looking apps, using just the standard UIKit classes, even if you don't have a design background. Interface Builder helps a lot to stick to the iOS Human Interface Guidelines (which you should read).