问:
Laravel: Generating and downloading a CSV file using StreamedResponse produces ERR_INVALID_RESPONSE
I have a controller method like so:

```<code>use Symfony\Component\HttpFoundation\StreamedResponse;

public function downloadTransactions($type)
{
    $this->authorize('download', Invoice::class);

    $filename = 'invoices-' . strtolower($type) . '.csv';

    $response = new StreamedResponse(function() {

        Invoice::generateTransactionsCsv($type);

    }, 200, [
        'Content-Type' => 'text/csv',
        'Content-Disposition' => 'attachment; filename="' . $filename . '"',
    ]);

    return $response;

}
</code>```

and then in my Invoice model I am populating the file:

```<code>public static function generateTransactionsCsv($type = null)
{
    // Open output stream
    $handle = fopen('php://output', 'w');

    // Add CSV headers
    fputcsv($handle, [
        'ID',
        'REF',
        'DESCRIPTION',
        'DATE',
        'AMOUNT',
    ]);

    // Close the output stream
    fclose($handle);
}
</code>```

but I get an ERR_INVALID_RESPONSE in Chrome, although I would assume the browser doesn't matter. I've checked similar questions which suggest installing the zip extension but I already have it installed. Using PHP 7.1 locally. Also tried looking at the logs but there doesn't seem to be anything there (using Valet locally).

If I move the logic from the model to the controller then it works fine but my example above is simplified to just the header row of the csv, in reality, there's a bit more to it so I'd like to keep the logic in the model if possible.

I've also tried opening and closing the file handle in the controller and passing it the model but that didn't work either.

答:
Looks like it was because the $type variable wasn't being passed correctly:

```<code>$response = new StreamedResponse(function() use ($type) {
    ....
}
</code>```

Was able to figure it out thanks to Safari, it downloaded a csv with the Laravel error trace in it which was weird, I didn't think it would be any different from Chrome.

Body:
I have a controller method like so:

use Symfony\Component\HttpFoundation\StreamedResponse;

public function downloadTransactions($type)
{
    $this->authorize('download', Invoice::class);

    $filename = 'invoices-' . strtolower($type) . '.csv';

    $response = new StreamedResponse(function() {

        Invoice::generateTransactionsCsv($type);

    }, 200, [
        'Content-Type' => 'text/csv',
        'Content-Disposition' => 'attachment; filename="' . $filename . '"',
    ]);

    return $response;

}

and then in my Invoice model I am populating the file:

public static function generateTransactionsCsv($type = null)
{
    // Open output stream
    $handle = fopen('php://output', 'w');

    // Add CSV headers
    fputcsv($handle, [
        'ID',
        'REF',
        'DESCRIPTION',
        'DATE',
        'AMOUNT',
    ]);

    // Close the output stream
    fclose($handle);
}

but I get an ERR_INVALID_RESPONSE in Chrome, although I would assume the browser doesn't matter. I've checked similar questions which suggest installing the zip extension but I already have it installed. Using PHP 7.1 locally. Also tried looking at the logs but there doesn't seem to be anything there (using Valet locally).

If I move the logic from the model to the controller then it works fine but my example above is simplified to just the header row of the csv, in reality, there's a bit more to it so I'd like to keep the logic in the model if possible.

I've also tried opening and closing the file handle in the controller and passing it the model but that didn't work either.

Body:
Looks like it was because the $type variable wasn't being passed correctly:

$response = new StreamedResponse(function() use ($type) {
    ....
}

Was able to figure it out thanks to Safari, it downloaded a csv with the Laravel error trace in it which was weird, I didn't think it would be any different from Chrome.


来源: stackexchange

问:
jQuery .delay() not delaying the .html() function
I'm trying to do a little javascript trick to fade out a div, replace its content, and fade it back in.  The .html event is replacing the content before the fadeOut is complete...

```<code>$("#products").fadeOut(500)
              .delay(600)
              .html($("#productPage" + pageNum).html())
              .fadeIn(500);
</code>```

It appears that the .html() is not being delayed by the .delay() method.

答:
Maybe the "queue" way it's ok,
But this javascript solution works better for me:</p>

```<code>    setTimeout (function(){
      $("#products").html('Product Added!');
    },1000);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to do a little javascript trick to fade out a div, replace its content, and fade it back in.  The .html event is replacing the content before the fadeOut is complete...

$("#products").fadeOut(500)
              .delay(600)
              .html($("#productPage" + pageNum).html())
              .fadeIn(500);

It appears that the .html() is not being delayed by the .delay() method.

Body:
Maybe the "queue" way it's ok,
But this javascript solution works better for me:

    setTimeout (function(){
      $("#products").html('Product Added!');
    },1000);

ContentLicense: CC BY-SA 3.0


问:
Access Token/Authorization Between Microservices
I'm creating an online store REST API that will mainly be used by a mobile app. The plan is for a microservices architecture using the Spring Cloud framework and Spring Cloud OAuth for security.

My question is really on best practices for communication between microservices: Should I have each service register for their own token, or should they just pass the user's token around?

For example, I have 3 services: user-service, account-service, order-service.
I've been able to implement two procedures for creating an order: One passes the user's token around, and in the other each service gets their own token. I use Feign for both approaches.

So for option 1: order-service -> GET account-service/account/current

order-service calls the account-service which returns the account based on a userId in the token. Then the order-service creates an order for the account.

Or for option 2: order-service -> GET account-service/account/user-id/{userId}

order-service gets the userId from the sent token, calls the account-service with it's own token, then creates the order with the retrieved account.

I'm really not sure which option is best to use. One better separates information but then requires two Feign Clients. However the other doesn't require the 2 clients and it becomes easier to block off end certain endpoints to outside clients, however it requires extra endpoints to be created and almost every service to go digging into the Authentication object.

What are all your thoughts? Has anyone implemented their system in one way or another way entirely? Or perhaps I've got the completely wrong idea.

Any help is appreciated.

答:
I have found below 3 options:

If each microservice is verifying the token then we can pass the same token. But the problem is - in between same token can be expired.

If we use client_credentials grant then there we are having two issues: one is, we need to send the username/id in next microservice. Another one is, we need to request two times - first for getting the access token, next for actual call.

If we do the token verification in API gateway only (not in microservices) then from the API gateway we need to send the username in every microservices. And microservices implementation needs to be changed to accept that param/header.


问:
The SQL command requires 1 parameter, but the parameter mapping only has 0 when using OLE DB Source and SQL Command from Variable, SSIS
I'm creating a SSIS package where I have an Expression Task connected to a Data Flow Task in the Control Flow.

The Expression task is:

@[User::DateVariable] = year(DATEADD("day", - @[$Project::DaystoReload] , getdate() ))*10000

The OLE DB Source uses a SQL Command from Variable as the source, and it has the appearence:

"SELECT Country, Population, Region, Date

INNER JOIN [" + @[User::DatabaseName] + "].[dbo].[Country]
where Date >= ?"

User::DatabaseName has EvaluateAsExpression set to TRUE, it is a string. DateVariable which is created from the Expression Task Before the Data Flow task is of data type Int32.

When I use the Query in SSMS, and I use the value which Expression Task evaluates DateVariable to "hard-coded" then I get the correct output, but in SSIS I get the error that

The SQL command requires 1 parameter, but the parameter mapping only has 0

I've been trying to Google this issue, but I haven't found a solution for when the OLE DB Source uses SQL Command from Variable, but rather just the SQL command in which you have a option called Parameter which you can map to the parameter. I haven't found such an option using Sql command from variable.

Does anyone have any insight into this?

答:
You cant pass parameters inside OLEDB SOURCE with SQL Command via Variable.

You have to pass a variable instead. And since you already stored a value inside your Date Variable, it should be possible to use

So your SQL Variable should be like this:

```<code>"SELECT Country, Population, Region, Date

INNER JOIN [" + @[User::DatabaseName] + "].[dbo].[Country]  where date >= "+  (DT_WSTR,20)@[User::Date]
</code>```

Body:
You cant pass parameters inside OLEDB SOURCE with SQL Command via Variable.

You have to pass a variable instead. And since you already stored a value inside your Date Variable, it should be possible to use

So your SQL Variable should be like this:

"SELECT Country, Population, Region, Date

INNER JOIN [" + @[User::DatabaseName] + "].[dbo].[Country]  where date >= "+  (DT_WSTR,20)@[User::Date]


问:
C# how to get a list of open "TcpListeners"
I want to add multiplayersupport to one of my games, so i created a "Create Server" button which opens a TcpListener and listens to connecting requests, and a "Join Server" button, I want this button to display a List of all open TcpListeners (so the user can click on them an connect)
are there any in-built functions for this in c#?</p>

答:
If you're limiting to a local area network you could broadcast on the port your game servers are listening on and have them reply with some kind of registration message.

To keep it from interfering with the game you could even separate it and have a separate registration service that listens on a different port than your game listens on.


问:
Can not show list with ngIf
Here is the component.ts file code;

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';

    const DISH = {
      name: 'Uthappizza',
      image: '/assets/images/uthappizza.png',
      category: 'mains',
      label: 'Hot',
      price: '4.99',
      description: 'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
      comments: [
        {
          rating: 5,
          comment: "Imagine all the eatables, living in conFusion!",
          author: "John Lemon",
          date: "2012-10-16T17:57:28.556094Z"
        },
        {
          rating: 4,
          comment: "Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
          author: "Paul McVites",
          date: "2014-09-05T17:57:28.556094Z"
        },
        {
          rating: 3,
          comment: "Eat it, just eat it!",
          author: "Michael Jaikishan",
          date: "2015-02-13T17:57:28.556094Z"
        },
        {
          rating: 4,
          comment: "Ultimate, Reaching for the stars!",
          author: "Ringo Starry",
          date: "2013-12-02T17:57:28.556094Z"
        },
        {
          rating: 2,
          comment: "It's your birthday, we're gonna party!",
          author: "25 Cent",
          date: "2011-12-02T17:57:28.556094Z"
        }
      ]
    };

    @Component({
      selector: 'app-dishdetail',
      templateUrl: './dishdetail.component.html',
      styleUrls: ['./dishdetail.component.scss'],
      encapsulation: ViewEncapsulation.None
    })
    export class DishdetailComponent implements OnInit {

      dish = DISH;

      constructor() { }

      ngOnInit() {
      }

    }
</code>```

And here is the html code

```<code>    <div class="container"
     fxLayout="row"
     fxLayout.sm="column"
     fxLayout.xs="column"
     fxLayoutAlign.gt-md="space-around center"
     fxLayoutGap="10px"
     fxLayoutGap.xs="0">

  <div fxFlex="40">
    <md-card>
      <md-card-header>
        <md-card-title>
          <h3>{{dish.name | uppercase}}</h3>
        </md-card-title>
      </md-card-header>
      <img md-card-image src={{dish.image}} alt={{dish.name}}>
      <md-card-content>
        <p>{{dish.description}}
        </p>
      </md-card-content>
      <md-card-actions>
        <button md-button>LIKE</button>
        <button md-button>SHARE</button>
      </md-card-actions>
    </md-card>
  </div>

  <div fxFlex="40">
    <md-card>
      <md-card-header>
        <md-card-title>
          <h3>Comments</h3>
        </md-card-title>
      </md-card-header>
      <md-card-content>
        <md-list *ngIf="dish.comments">
          <p>{{dish.comments}}</p>
        </md-list>
      </md-card-content>
    </md-card>
  </div>

</div>
</code>```

I am trying to show each comment in the DISH object, but can not list the comments.

It shows me like this

Comments

[object Object],[object Object],[object Object],[object Object],[object Object]**

Can anyone help me what is the missing part? What am i doing wrong?

答:
dish.comments is an array. You cannot print it out like that, you should use an *ngFor and access the properties appropriately. Something like this:

```<code><md-list *ngFor="let comment of dish.comments">
  <p>{{comment.comment}}</p>
  <p>{{comment.author}}</p>
</md-list>
</code>```

Title: Can not show list with ngIf

Body:
Here is the component.ts file code;

import { Component, OnInit, ViewEncapsulation } from '@angular/core';

    const DISH = {
      name: 'Uthappizza',
      image: '/assets/images/uthappizza.png',
      category: 'mains',
      label: 'Hot',
      price: '4.99',
      description: 'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
      comments: [
        {
          rating: 5,
          comment: "Imagine all the eatables, living in conFusion!",
          author: "John Lemon",
          date: "2012-10-16T17:57:28.556094Z"
        },
        {
          rating: 4,
          comment: "Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
          author: "Paul McVites",
          date: "2014-09-05T17:57:28.556094Z"
        },
        {
          rating: 3,
          comment: "Eat it, just eat it!",
          author: "Michael Jaikishan",
          date: "2015-02-13T17:57:28.556094Z"
        },
        {
          rating: 4,
          comment: "Ultimate, Reaching for the stars!",
          author: "Ringo Starry",
          date: "2013-12-02T17:57:28.556094Z"
        },
        {
          rating: 2,
          comment: "It's your birthday, we're gonna party!",
          author: "25 Cent",
          date: "2011-12-02T17:57:28.556094Z"
        }
      ]
    };

    @Component({
      selector: 'app-dishdetail',
      templateUrl: './dishdetail.component.html',
      styleUrls: ['./dishdetail.component.scss'],
      encapsulation: ViewEncapsulation.None
    })
    export class DishdetailComponent implements OnInit {

      dish = DISH;

      constructor() { }

      ngOnInit() {
      }

    }

And here is the html code

    <md-card>
      <md-card-header>
        <md-card-title>

{{dish.name | uppercase}}

        </md-card-title>
      </md-card-header>

      <md-card-content>

{{dish.description}}

      </md-card-content>
      <md-card-actions>
        <button md-button>LIKE</button>
        <button md-button>SHARE</button>
      </md-card-actions>
    </md-card>

    <md-card>
      <md-card-header>
        <md-card-title>

Comments

        </md-card-title>
      </md-card-header>
      <md-card-content>
        <md-list *ngIf="dish.comments">

{{dish.comments}}

        </md-list>
      </md-card-content>
    </md-card>

I am trying to show each comment in the DISH object, but can not list the comments.

It shows me like this

Comments

[object Object],[object Object],[object Object],[object Object],[object Object]**

Can anyone help me what is the missing part? What am i doing wrong?

Body:
dish.comments is an array. You cannot print it out like that, you should use an *ngFor and access the properties appropriately. Something like this:

<md-list *ngFor="let comment of dish.comments">
  <p>{{comment.comment}}</p>
  <p>{{comment.author}}</p>
</md-list>


问:
Redirect to welcome page on pressing back button in react Single page application
I have a react single page application, so on pressing back button, its redirecting me to welcome page as expected. Now due to some requirement, I have to update the URL of the app in between and due to which if now I press back button, its first redirect me to old url page and then welcome page.
How can I control this behavior, means even after updating the URL, user should directly redirected to welcome page on pressing back button.</p>

答:
I think you can make use of react-router-dom here. There is Link element available in react-router-dom which can solve your problem.

For eg:, you can try something like this
  <Link to="/welcomePage" >Back</Link>

For more information, go through below document react-router-dom document


问:
Node + Express use NodeMailer appwide
I am trying to setup NodeMailer on my existing application. I am trying to setup the NodeMailer configuration on my main app.ts, then use it app wide to send mails wherever needed. This is what I have in my app.ts:

```<code>import * as mailer from 'nodemailer';

const app = express();
dotenv.load({ path: '.env' });
app.set('port', (process.env.PORT || 3000));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

let mongodbURI = process.env.MONGODB_URI;
mongoose.Promise = global.Promise;
const mongodb = mongoose.connect(mongodbURI, { useMongoClient: true });

var mailConfig = {
  host: process.env.MAIL_HOST,
  port: process.env.MAIL_PORT,
  auth: {
    user: process.env.MAIL_USERNAME,
    pass: process.env.MAIL_PASSWORD
  }
};
let transporter = mailer.createTransport(mailConfig);

mongodb
  .then((db) => {
    console.log('Connected to MongoDB on', db.host + ':' + db.port);
    setRoutes(app);
    if (!module.parent) {
      app.listen(app.get('port'), () => {
        console.log('API listening on port ' + app.get('port'));
      });
    }
  })
  .catch((err) => {
    console.error(err);
  });

export { app };
</code>```

I tried things like app.use(transporter) and app.set('transporter',transporter). But seems that not quite the way to do it. How can I declare it app wide and use the object at other places like the controller/user.ts?

答:
Create a separate js file for your transport and import it inside whichever module it is required.

transport.js

```<code>var mailer = require('nodemailer');
var mailConfig = {
  host: process.env.MAIL_HOST,
  port: process.env.MAIL_PORT,
  auth: {
    user: process.env.MAIL_USERNAME,
    pass: process.env.MAIL_PASSWORD
  }
};

var transporter = mailer.createTransport(mailConfig);

module.exports = transporter;
</code>```

app.js or any other module where you want to use nodemailer

```<code>var transporter = require('./transport');

transporter.sendMail(mailOptions, function(error, info) {
    if (error) {
        //Error
    } else {
        //Success
    }
});
</code>```

Title: Node + Express use NodeMailer appwide

Body:
I am trying to setup NodeMailer on my existing application. I am trying to setup the NodeMailer configuration on my main app.ts, then use it app wide to send mails wherever needed. This is what I have in my app.ts:

import * as mailer from 'nodemailer';

const app = express();
dotenv.load({ path: '.env' });
app.set('port', (process.env.PORT || 3000));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

let mongodbURI = process.env.MONGODB_URI;
mongoose.Promise = global.Promise;
const mongodb = mongoose.connect(mongodbURI, { useMongoClient: true });

var mailConfig = {
  host: process.env.MAIL_HOST,
  port: process.env.MAIL_PORT,
  auth: {
    user: process.env.MAIL_USERNAME,
    pass: process.env.MAIL_PASSWORD
  }
};
let transporter = mailer.createTransport(mailConfig);

mongodb
  .then((db) => {
    console.log('Connected to MongoDB on', db.host + ':' + db.port);
    setRoutes(app);
    if (!module.parent) {
      app.listen(app.get('port'), () => {
        console.log('API listening on port ' + app.get('port'));
      });
    }
  })
  .catch((err) => {
    console.error(err);
  });

export { app };

I tried things like app.use(transporter) and app.set('transporter',transporter). But seems that not quite the way to do it. How can I declare it app wide and use the object at other places like the controller/user.ts?

Body:
Create a separate js file for your transport and import it inside whichever module it is required.

transport.js

var mailer = require('nodemailer');
var mailConfig = {
  host: process.env.MAIL_HOST,
  port: process.env.MAIL_PORT,
  auth: {
    user: process.env.MAIL_USERNAME,
    pass: process.env.MAIL_PASSWORD
  }
};

var transporter = mailer.createTransport(mailConfig);

module.exports = transporter;

app.js or any other module where you want to use nodemailer

var transporter = require('./transport');

transporter.sendMail(mailOptions, function(error, info) {
    if (error) {
        //Error
    } else {
        //Success
    }
});


问:
Companion objects benefits of posibility to implement interfaces
Why in Kotlin/Scala companion objects can implements some interfaces, what benefits this can have? When is useful to use this feature?</p>

答:
You can use companion objects and inheritance for some level of class-lavel or static polymorphism.

Example 1: Factories

Consider an interface

```<code>interface Factory<T> {
    fun create(): T
}
</code>```

Now, we create a class whose companion object implements it

```<code>class Foo {
    companion object: Factory<Foo> {
        override fun create() = Foo()
    }
}
</code>```

Now we can create an extension function for all factories to create and e.g. log the object.

```<code>fun <T> Factory<T>.createAndLog(): T {
    val t = create()
    println(t)
    return t
}
</code>```

Und use it like so

```<code>Foo.createAndLog()
</code>```

Example 2: Queries

Consider a marker interface

```<code>interface Queryable<T>
</code>```

We now have two classes User and Article that represent tables in a database whose companion object implements the interface.

```<code>class User(val id: String) {
    companion object: Queryable<User> {}
}

class Article(val authorId: String) {
    companion object: : Queryable<Article> {}
}
</code>```

We can now define an extension function to create a query from the class

```<code>fun <T> Queryable<T>.query() = db.createQuery<T>()
</code>```

which we can call as

```<code>User.query()
//or
Article.query()
</code>```

Body:
You can use companion objects and inheritance for some level of class-lavel or static polymorphism.

Example 1: Factories

Consider an interface

interface Factory<T> {
    fun create(): T
}

Now, we create a class whose companion object implements it

class Foo {
    companion object: Factory<Foo> {
        override fun create() = Foo()
    }
}

Now we can create an extension function for all factories to create and e.g. log the object.

fun <T> Factory<T>.createAndLog(): T {
    val t = create()
    println(t)
    return t
}

Und use it like so

Foo.createAndLog()

Example 2: Queries

Consider a marker interface

interface Queryable<T>

We now have two classes User and Article that represent tables in a database whose companion object implements the interface.

class User(val id: String) {
    companion object: Queryable<User> {}
}

class Article(val authorId: String) {
    companion object: : Queryable<Article> {}
}

We can now define an extension function to create a query from the class

fun <T> Queryable<T>.query() = db.createQuery<T>()

which we can call as

User.query()
//or
Article.query()


问:
Replace multiple words in string
I have multiple words I want to replace with values, whats the best way to do this?

Example:
This is what I have done but it feels and looks so wrong

```<code>string s ="Dear <Name>, your booking is confirmed for the <EventDate>";
string s1 = s.Replace("<Name>", client.FullName);
string s2 =s1.Replace("<EventDate>", event.EventDate.ToString());

txtMessage.Text = s2;
</code>```

There has to be a better way?

thanks

答:
You can chain the Replace operations together:

```<code>s = s.Replace(...).Replace(...);
</code>```

Note that you don't need to create other strings to do this.

Using String.Format is the appropriate way, but only if you can change the original string to suit the brace formatting.

Title: Replace multiple words in string

Body:
I have multiple words I want to replace with values, whats the best way to do this?

Example:
This is what I have done but it feels and looks so wrong

string s ="Dear <Name>, your booking is confirmed for the <EventDate>";
string s1 = s.Replace("<Name>", client.FullName);
string s2 =s1.Replace("<EventDate>", event.EventDate.ToString());

txtMessage.Text = s2;

There has to be a better way?

thanks

Body:
You can chain the Replace operations together:

s = s.Replace(...).Replace(...);

Note that you don't need to create other strings to do this.

Using String.Format is the appropriate way, but only if you can change the original string to suit the brace formatting.


问:
How to remove/delete last character from printed list in python
I am creating simple program which finds the smallest multiplicators of a number (not sure if this is the right term). However, I can not find a way to delete last "*" from the listed result. What am I doing wrong? Please help.

```<code>num = int(input("write number: "))
print(num, end = "=")
div = 2
while num > 1:
    if num % div == 0:
        num = num / div
        print(div, end = "*")
    else:
        div += 1
</code>```

Result I got:

```<code>24=2*2*2*3*
</code>```

Result I want:

```<code>24=2*2*2*3
</code>```

I tried to use sep="" instead of end="", tried \b, [:-1] but this does not work or I am just doing it wrong.
Thank you.

答:
One option is simply to check whether or not num =1 before printing the "*"

```<code>num = num / div
if num == 1 :
    print(div)
else :
    print(div, end = "*")
</code>```

Since you only want to print a * if there are more multipliers to come, and there will always be another multiplier if div is more than 1.

Body:
I am creating simple program which finds the smallest multiplicators of a number (not sure if this is the right term). However, I can not find a way to delete last "*" from the listed result. What am I doing wrong? Please help.

num = int(input("write number: "))
print(num, end = "=")
div = 2
while num > 1:
    if num % div == 0:
        num = num / div
        print(div, end = "*")
    else:
        div += 1

Result I got:

24=2*2*2*3*

Result I want:

24=2*2*2*3

I tried to use sep="" instead of end="", tried \b, [:-1] but this does not work or I am just doing it wrong.
Thank you.

Body:
One option is simply to check whether or not num =1 before printing the "*"

num = num / div
if num == 1 :
    print(div)
else :
    print(div, end = "*")

Since you only want to print a * if there are more multipliers to come, and there will always be another multiplier if div is more than 1.


问:
Cookie doesn't get deleted
:D

I have a problem with a login and registration script. It has "remember me" functionality and it works great unless i log out. It stores that cookie in a database(just to check on it later) and when i log out it gets deleted from that db(which is the way it's supposed to work) the problem however is that it doesn't get deleted from the browser(even tho it doesn't get deleted from the browser when i come back i'll be logged out because of the check it's makeing on that, previously mentioned, db).

Here is my user class(you can see there a logout method(line 85)

```<code><?php

class User{
    private $_db,
        $_data,
        $_sessionName,
        $_cookieName,
        $_isLoggedIn;

    public function __construct($user = null){
        $this->_db = DB::getInstance();

        $this->_sessionName = Config::get('session/session_name');
        $this->_cookieName = Config::get('remember/cookie_name');

        if(!$user){
            if(Session::exists($this->_sessionName)){
                $user = Session::get($this->_sessionName);

                if($this->find($user)){
                    $this->_isLoggedIn = true;
                } else{
                    //process logout
                }
            }
        } else{
            $this->find($user);
        }
    }

    public function create($fields = array()){
        if(!$this->_db->insert('users', $fields)){
            throw new Exception('There was a problem creating an account');
        }
    }

    public function find($user = null){
        if($user){
            $field = (is_numeric($user)) ? 'id' : 'username';
            $data = $this->_db->get('users', array($field, '=', $user));

            if($data->count()){
                $this->_data = $data->first();
                return true;
            }
        }
        return false;
    }

    public function login($username = null, $password = null, $remember = false){
        if(!$username && !$password && $this->exists()){
            Session::put($this->_sessionName, $this->data()->id);
        } else{
            $user = $this->find($username);
            if($user){
                if($this->data()->password === Hash::make($password, $this->data()->salt)){
                    Session::put($this->_sessionName, $this->data()->id);

                    if($remember){
                        $hash = Hash::unique();
                        $hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));

                        if(!$hashCheck->count()){
                            $this->_db->insert('users_session',array(
                                'user_id' => $this->data()->id,
                                'hash' => $hash
                            ));
                        } else{
                            $hash = $hashCheck->first()->hash;
                        }
                    Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
                    }
                    return true;
                }
            }
        }
        return false;
    }

    public function exists(){
        return(!empty($this->_data)) ? true : false;
    }

    public function logout(){
        $this->_db->delete('users_session', array('user_id', '=', $this->data()->id));

        Session::delete($this->_sessionName);
        Cookie::delete(Config::get('remember/cookie_name'));
    }

    public function data(){
        return $this->_data;
    }

    public function isLoggedIn(){
        return $this->_isLoggedIn;
        }
}
</code>```

And here is my Cookie class(you can see a delete cookie method on line 19)

```<code><?php

class Cookie{
    public static function exists($name){
        return(isset($_COOKIE[$name])) ? true : false;
    }

    public static function get($name){
        return $_COOKIE[$name];
    }

    public static function put($name, $value, $expiry){
        if(setcookie($name, $value, time() + $expiry, '/')){
            return true;
        }
        return false;
    }

    public static function delete($name){
        self::put($name, '', time() - 1);
    }
}
</code>```

答:
I think you are sending an wrong as timestamp to setcookie :

self::put($name, '', time() - 1);

you should call like this:

self::put($name, '', - 1);

Because if use "time() -1 " will result a timestamp in the future : time() + time() -1

Title: Cookie doesn't get deleted

Body:
:D

I have a problem with a login and registration script. It has "remember me" functionality and it works great unless i log out. It stores that cookie in a database(just to check on it later) and when i log out it gets deleted from that db(which is the way it's supposed to work) the problem however is that it doesn't get deleted from the browser(even tho it doesn't get deleted from the browser when i come back i'll be logged out because of the check it's makeing on that, previously mentioned, db).

Here is my user class(you can see there a logout method(line 85)

<?php

class User{
    private $_db,
        $_data,
        $_sessionName,
        $_cookieName,
        $_isLoggedIn;

    public function __construct($user = null){
        $this->_db = DB::getInstance();

        $this->_sessionName = Config::get('session/session_name');
        $this->_cookieName = Config::get('remember/cookie_name');

        if(!$user){
            if(Session::exists($this->_sessionName)){
                $user = Session::get($this->_sessionName);

                if($this->find($user)){
                    $this->_isLoggedIn = true;
                } else{
                    //process logout
                }
            }
        } else{
            $this->find($user);
        }
    }

    public function create($fields = array()){
        if(!$this->_db->insert('users', $fields)){
            throw new Exception('There was a problem creating an account');
        }
    }

    public function find($user = null){
        if($user){
            $field = (is_numeric($user)) ? 'id' : 'username';
            $data = $this->_db->get('users', array($field, '=', $user));

            if($data->count()){
                $this->_data = $data->first();
                return true;
            }
        }
        return false;
    }

    public function login($username = null, $password = null, $remember = false){
        if(!$username && !$password && $this->exists()){
            Session::put($this->_sessionName, $this->data()->id);
        } else{
            $user = $this->find($username);
            if($user){
                if($this->data()->password === Hash::make($password, $this->data()->salt)){
                    Session::put($this->_sessionName, $this->data()->id);

                    if($remember){
                        $hash = Hash::unique();
                        $hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));

                        if(!$hashCheck->count()){
                            $this->_db->insert('users_session',array(
                                'user_id' => $this->data()->id,
                                'hash' => $hash
                            ));
                        } else{
                            $hash = $hashCheck->first()->hash;
                        }
                    Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
                    }
                    return true;
                }
            }
        }
        return false;
    }

    public function exists(){
        return(!empty($this->_data)) ? true : false;
    }

    public function logout(){
        $this->_db->delete('users_session', array('user_id', '=', $this->data()->id));

        Session::delete($this->_sessionName);
        Cookie::delete(Config::get('remember/cookie_name'));
    }

    public function data(){
        return $this->_data;
    }

    public function isLoggedIn(){
        return $this->_isLoggedIn;
        }
}

And here is my Cookie class(you can see a delete cookie method on line 19)

<?php

class Cookie{
    public static function exists($name){
        return(isset($_COOKIE[$name])) ? true : false;
    }

    public static function get($name){
        return $_COOKIE[$name];
    }

    public static function put($name, $value, $expiry){
        if(setcookie($name, $value, time() + $expiry, '/')){
            return true;
        }
        return false;
    }

    public static function delete($name){
        self::put($name, '', time() - 1);
    }
}


问:
Python: Removing a specific item that has a duplicate only knowing its index in a list
What I want this program to do is to delete all the 1's that are in the list that follow by index all the 2's.

This is the code:

```<code>a = [3, 1, 2, 1]
a.remove(a[3])
print(a)
</code>```

I really put this program into the basics but the point is that I have only got the index of the 1 that follows the 2, tho when I do this the result is:

```<code>[3, 2, 1]
</code>```

This means that it doesn't delete the 1 I want but just the first 1 it finds. Tho this is really a problem in a real program situation where the first 1 is an important value.

How can I fix it? Thanks

答:
If you want to remove a specific index you use del.

```<code>a = [3, 1, 2, 1]
del a[3]
print(a)
</code>```

Output:

```<code>[3, 1, 2]
</code>```

Body:
What I want this program to do is to delete all the 1's that are in the list that follow by index all the 2's.

This is the code:

a = [3, 1, 2, 1]
a.remove(a[3])
print(a)

I really put this program into the basics but the point is that I have only got the index of the 1 that follows the 2, tho when I do this the result is:

[3, 2, 1]

This means that it doesn't delete the 1 I want but just the first 1 it finds. Tho this is really a problem in a real program situation where the first 1 is an important value.

How can I fix it? Thanks

Body:
If you want to remove a specific index you use del.

a = [3, 1, 2, 1]
del a[3]
print(a)

Output:

[3, 1, 2]


问:
UNION ALL, semi-overall COUNT, DIFFERENT TABLES
I got four table fiche_visite_autre, fiche_visite_dpf, fiche_visite and Magasin, in the first three tables I have dates corresponding to the dates when a store was visited.

With this request i get the number of visit in each store from the three tables :

```<code>SELECT * FROM(
SELECT fiche_visite_autre.Code_CM as Code_CM, magasin.Nom_Mag,
COUNT(fiche_visite_autre.Date_Visite) as Nombre_visite, cible_visite.Cible as Cible
FROM magasin, cible_visite, fiche_visite_autre
WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM =
fiche_visite_autre.Code_CM GROUP BY fiche_visite_autre.Code_CM

UNION ALL

SELECT fiche_visite_dpf.Code_CM as Code_CM,magasin.Nom_Mag,
COUNT(fiche_visite_dpf.Date_Visite) as Nombre_visite, cible_visite.Cible as
Cible
FROM magasin, cible_visite, fiche_visite_dpf
WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM = fiche_visite_dpf.Code_CM GROUP BY fiche_visite_dpf.Code_CM

UNION ALL

SELECT fiche_visite.Code_CM as Code_CM,magasin.Nom_Mag,
COUNT(fiche_visite.Date_Visite) as Nombre_visite, cible_visite.Cible as Cible
FROM magasin, cible_visite, fiche_visite
WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM =
fiche_visite.Code_CM GROUP BY fiche_visite.Code_CM) as tmp GROUP BY Code_CM
ORDER BY Nombre_visite DESC
</code>```

Table of visit returned

The problem is that I got two time the store 'BAGNOLES DE L'ORNE' in two differents table but only one apear here.

My aim is to got the right number of visit like i got for the store 'NANTERRE' which got 2 visits in the same table.

(Sorry for my english I'm french :)

答:
My solution :</p>

```<code>SELECT Code_CM, Nom_Mag, SUM(Nombre_visite) as Nombre_visite, Cible FROM (
            SELECT fiche_visite_autre.Date_Visite as DateVisite, fiche_visite_autre.Code_CM as Code_CM, magasin.Nom_Mag as Nom_Mag, COUNT(fiche_visite_autre.Date_Visite) as Nombre_visite, cible_visite.Cible as Cible
            FROM magasin, cible_visite, fiche_visite_autre
            WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM = fiche_visite_autre.Code_CM GROUP BY Code_CM

            UNION ALL

            SELECT fiche_visite_dpf.Date_Visite as DateVisite, fiche_visite_dpf.Code_CM as Code_CM,magasin.Nom_Mag as Nom_Mag, COUNT(fiche_visite_dpf.Date_Visite) as Nombre_visite, cible_visite.Cible as Cible
            FROM magasin, cible_visite, fiche_visite_dpf
            WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM = fiche_visite_dpf.Code_CM GROUP BY Code_CM

            UNION ALL

            SELECT fiche_visite.Date_Visite as DateVisite, fiche_visite.Code_CM as Code_CM,magasin.Nom_Mag as Nom_Mag, COUNT(fiche_visite.Date_Visite) as Nombre_visite, cible_visite.Cible as Cible
            FROM magasin, cible_visite, fiche_visite
            WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM = fiche_visite.Code_CM GROUP BY Code_CM
            ) as tmp WHERE DateVisite BETWEEN 'start' AND 'end' GROUP BY Code_CM ORDER BY Nombre_visite DESC
</code>```

Body:
I got four table fiche_visite_autre, fiche_visite_dpf, fiche_visite and Magasin, in the first three tables I have dates corresponding to the dates when a store was visited.

With this request i get the number of visit in each store from the three tables :

SELECT * FROM(
SELECT fiche_visite_autre.Code_CM as Code_CM, magasin.Nom_Mag,
COUNT(fiche_visite_autre.Date_Visite) as Nombre_visite, cible_visite.Cible as Cible
FROM magasin, cible_visite, fiche_visite_autre
WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM =
fiche_visite_autre.Code_CM GROUP BY fiche_visite_autre.Code_CM

UNION ALL

SELECT fiche_visite_dpf.Code_CM as Code_CM,magasin.Nom_Mag,
COUNT(fiche_visite_dpf.Date_Visite) as Nombre_visite, cible_visite.Cible as
Cible
FROM magasin, cible_visite, fiche_visite_dpf
WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM = fiche_visite_dpf.Code_CM GROUP BY fiche_visite_dpf.Code_CM

UNION ALL

SELECT fiche_visite.Code_CM as Code_CM,magasin.Nom_Mag,
COUNT(fiche_visite.Date_Visite) as Nombre_visite, cible_visite.Cible as Cible
FROM magasin, cible_visite, fiche_visite
WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM =
fiche_visite.Code_CM GROUP BY fiche_visite.Code_CM) as tmp GROUP BY Code_CM
ORDER BY Nombre_visite DESC

Table of visit returned

The problem is that I got two time the store 'BAGNOLES DE L'ORNE' in two differents table but only one apear here.

My aim is to got the right number of visit like i got for the store 'NANTERRE' which got 2 visits in the same table.

(Sorry for my english I'm french :)

Body:
My solution :

SELECT Code_CM, Nom_Mag, SUM(Nombre_visite) as Nombre_visite, Cible FROM (
            SELECT fiche_visite_autre.Date_Visite as DateVisite, fiche_visite_autre.Code_CM as Code_CM, magasin.Nom_Mag as Nom_Mag, COUNT(fiche_visite_autre.Date_Visite) as Nombre_visite, cible_visite.Cible as Cible
            FROM magasin, cible_visite, fiche_visite_autre
            WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM = fiche_visite_autre.Code_CM GROUP BY Code_CM

            UNION ALL

            SELECT fiche_visite_dpf.Date_Visite as DateVisite, fiche_visite_dpf.Code_CM as Code_CM,magasin.Nom_Mag as Nom_Mag, COUNT(fiche_visite_dpf.Date_Visite) as Nombre_visite, cible_visite.Cible as Cible
            FROM magasin, cible_visite, fiche_visite_dpf
            WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM = fiche_visite_dpf.Code_CM GROUP BY Code_CM

            UNION ALL

            SELECT fiche_visite.Date_Visite as DateVisite, fiche_visite.Code_CM as Code_CM,magasin.Nom_Mag as Nom_Mag, COUNT(fiche_visite.Date_Visite) as Nombre_visite, cible_visite.Cible as Cible
            FROM magasin, cible_visite, fiche_visite
            WHERE magasin.Code_CM = cible_visite.Code_CM AND cible_visite.Code_CM = fiche_visite.Code_CM GROUP BY Code_CM
            ) as tmp WHERE DateVisite BETWEEN 'start' AND 'end' GROUP BY Code_CM ORDER BY Nombre_visite DESC


问:
jquery validation plugin on blur
Friends i am new to javascripting & jQuery and need your your help to solve 2 problems. I am using jquery validation plugin https://jqueryvalidation.org for a project which contains multiple forms on different pages.

PROBLEM #1

I included a custom JS file which already has the

```<code>$(document).ready(function() {
  //some codes
});
</code>```

To execute this plugin with different properties on different pages it is required to initialize it in document.ready i.e.

```<code>$(document).ready(function() {
  $("#theForm").validate();
});
</code>```

so is it ok to have document ready 2 times this way?

PROBLEM #2

This plugin works after the submit button is clicked. I want it to also validate onblur for input fields. It do have the property to validate on onfocusout also but that also works to handle errors after the submit button is clicked.
So is there anyway to make the validations to also work on blur or focusout before the submit button is clicked?

Any help will be highly appreciated. Thank you friends in advance.

答:
Use this to validate on blur:

```<code>$(document).ready(function() {
    var $theForm = $("#theForm"),
        $form = $theForm.validate();
    //changed to check every textbox type input inside #theForm:
    $theForm.on("blur", "input[type='text']", function(e){
        //use element() to test only one element:
        if ($form.element(this)) {
            console.log("is valid");
        }
    });

});
</code>```

Validator.form()

Description: Validates the form, returns true if it is valid, false
  otherwise.

Validator.element( element )

Description: Validates a single element, returns true if it is valid,
  false otherwise.

More info:

https://jqueryvalidation.org/Validator.form/

https://jqueryvalidation.org/Validator.element/

Working example:

https://codepen.io/anon/pen/wPOrrx

Title: jquery validation plugin on blur

Body:
Friends i am new to javascripting & jQuery and need your your help to solve 2 problems. I am using jquery validation plugin https://jqueryvalidation.org for a project which contains multiple forms on different pages.

PROBLEM #1

I included a custom JS file which already has the

$(document).ready(function() {
  //some codes
});

To execute this plugin with different properties on different pages it is required to initialize it in document.ready i.e.

$(document).ready(function() {
  $("#theForm").validate();
});

so is it ok to have document ready 2 times this way?

PROBLEM #2

This plugin works after the submit button is clicked. I want it to also validate onblur for input fields. It do have the property to validate on onfocusout also but that also works to handle errors after the submit button is clicked.
So is there anyway to make the validations to also work on blur or focusout before the submit button is clicked?

Any help will be highly appreciated. Thank you friends in advance.

Body:
Use this to validate on blur:

$(document).ready(function() {
    var $theForm = $("#theForm"),
        $form = $theForm.validate();
    //changed to check every textbox type input inside #theForm:
    $theForm.on("blur", "input[type='text']", function(e){
        //use element() to test only one element:
        if ($form.element(this)) {
            console.log("is valid");
        }
    });

});

Validator.form()

Description: Validates the form, returns true if it is valid, false
  otherwise.

Validator.element( element )

Description: Validates a single element, returns true if it is valid,
  false otherwise.

More info:

https://jqueryvalidation.org/Validator.form/

https://jqueryvalidation.org/Validator.element/

Working example:

https://codepen.io/anon/pen/wPOrrx


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
There is no real advice I can give you, because you are completely right : it has to click. OOP is hard to explain so everyone gets it, just like one may have a hard time understanding windows messages, foreign primary keys, and just about every other topic worth mentioning.

What I would suggest is that you try to do a real project on your own. It doesn't have to be complex, but it has to include several classes, so you can get your hands dirty with inheritance and other sweet OOP stuff.

I don't think that any amount of reading can ever replace your own experience ... Until it does click just pretend you're playing Alone in the Dark or something ...

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: Rekreativc


答:
Use String.Format:</p>

```<code>const string message = "Dear {0}, Please call {1} to get your {2} from {3}";
string name = "Bob";
string callName = "Alice";
string thingy = "Book";
string thingyKeeper = "Library";
string customMessage = string.Format(message, name, callName, thingy, thingyKeeper);
</code>```

Title: Replace multiple words in string

Body:
Use String.Format:

const string message = "Dear {0}, Please call {1} to get your {2} from {3}";
string name = "Bob";
string callName = "Alice";
string thingy = "Book";
string thingyKeeper = "Library";
string customMessage = string.Format(message, name, callName, thingy, thingyKeeper);


问:
yaml dependency in R won't update in Windows
I'm on a windows machine and I'm trying  to knit an RMarkdown  document with RStudio. When I press the 'knit' button in  RStudio,  I  get a "requires an updated version of the yaml package" message. I install.packages("yaml") to find a message saying  something along the  lines of "binary source needs_compilation." I check the  CRAN page  for yaml and it seems that the Microsoft binaries are not up to date  with the the more recent Mac version (2.1.14 < 2.1.15). I think this is the reason why I can't knit an RMarkdown document, but I do not  know how to work around this.

This  error popped  up a few days ago and I'm not really sure  how to fix it.  I've been  knitting documents pretty  consistently until  now and don't really know what to do.

Any help or guidance would be  greatly appreciated.

答: @cedric's link helped out. I had to install() the yaml package using devtools


问:
Best way to databind a group of radiobuttons in WinForms
I'm currently working on databinding some of my existing Windows Forms, and I've ran into an issue figuring out the proper way of databinding a group of radiobutton controls within a group box.

My business object has an integer property which I want to databind against 4 radiobuttons (where each of them represents the values 0 - 3).

I'm currently binding against a presenter object which works as the binder between the form and the business object, and the way I've done it now is to have 4 separate properties which each binds against each of these values (I do use INotifyPropertyChanged, but not including that here):

```<code>Private int _propValue;

Public bool PropIsValue0
{
  get { return _propValue == 0; }
  set
  {
    if (value)
      _propValue = 0;
  }
}

Public bool PropIsValue1 { // As above, but with value == 1 }
Public bool PropIsValue2 { // As above, but with value == 2 }
Public bool PropIsValue3 { // As above, but with value == 3 }
</code>```

And I then bind each of the radiobuttons to their respective property as above.

This does not seem right to me, so any advice are highly appreciated.

答:
I would like to make an observation about the code block that might be helpful to people reading these posts.  The following code may not always work as expected due to it's structure.

```<code>try
    {
      val = System.Enum.Parse(this.enumType, rb.Text) as System.Enum;
    }
    catch(Exception ex)
    {
      // cannot occurred if code is safe
      System.Windows.Forms.MessageBox.Show("No enum value for this radio button : " + ex.ToString());
    }
    object obj = this.bindingSource.Current;
    obj.GetType().GetProperty(propertyName).SetValue(obj, val, new object[] {
    }
  );
  this.bindingSource.CurrencyManager.Refresh();
</code>```

If an error occurs in the try block, the catch block will be executed.  The code will continue to execute after the catch block.  Since there was no handling of binding source, the variables following the catch could end up in a indeterminate state and may throw another exception that may or may not be handled.

A better approach is as follows

```<code> try
        {
            val = System.Enum.Parse(this.enumType, rb.Text) as System.Enum;

        object obj = this.bindingSource.Current;
        obj.GetType().GetProperty(propertyName).SetValue(obj, val, new object[] { });
        this.bindingSource.CurrencyManager.Refresh();
        }
        catch(EntityException ex)
        {
            // handle error
        }
        catch(Exception ex)
        {
            // cannot occurred if code is safe
            System.Windows.Forms.MessageBox.Show("No enum value for this radio button : " + ex.ToString());
        }
</code>```

This allows the enum value error to be handled as well as other errors that may occur.  However use the EntityException or variations of it before the Exception block (all decendents of Exception have to come first). One can get specific entity state information for a entity framework error by using the entity framework classes instead of the Exception base class. This can be helpful for debugging or providing clearer run time messages for the user.

When I setup try-catch blocks I like to view it as a "layer" on top of the code.  I make decisions about the flow of the exceptions through out the program, their display to the user, and what ever cleanup is required to allow the program to continue working properly without objects in a indeterminate state that can cascade to other errors.

OwnerDisplayName: Geir-Tore Lindsve

Body:
I'm currently working on databinding some of my existing Windows Forms, and I've ran into an issue figuring out the proper way of databinding a group of radiobutton controls within a group box.

My business object has an integer property which I want to databind against 4 radiobuttons (where each of them represents the values 0 - 3).

I'm currently binding against a presenter object which works as the binder between the form and the business object, and the way I've done it now is to have 4 separate properties which each binds against each of these values (I do use INotifyPropertyChanged, but not including that here):

Private int _propValue;

Public bool PropIsValue0
{
  get { return _propValue == 0; }
  set
  {
    if (value)
      _propValue = 0;
  }
}

Public bool PropIsValue1 { // As above, but with value == 1 }
Public bool PropIsValue2 { // As above, but with value == 2 }
Public bool PropIsValue3 { // As above, but with value == 3 }

And I then bind each of the radiobuttons to their respective property as above.

This does not seem right to me, so any advice are highly appreciated.

Body:
I would like to make an observation about the code block that might be helpful to people reading these posts.  The following code may not always work as expected due to it's structure.

try
    {
      val = System.Enum.Parse(this.enumType, rb.Text) as System.Enum;
    }
    catch(Exception ex)
    {
      // cannot occurred if code is safe
      System.Windows.Forms.MessageBox.Show("No enum value for this radio button : " + ex.ToString());
    }
    object obj = this.bindingSource.Current;
    obj.GetType().GetProperty(propertyName).SetValue(obj, val, new object[] {
    }
  );
  this.bindingSource.CurrencyManager.Refresh();

If an error occurs in the try block, the catch block will be executed.  The code will continue to execute after the catch block.  Since there was no handling of binding source, the variables following the catch could end up in a indeterminate state and may throw another exception that may or may not be handled.

A better approach is as follows

 try
        {
            val = System.Enum.Parse(this.enumType, rb.Text) as System.Enum;

        object obj = this.bindingSource.Current;
        obj.GetType().GetProperty(propertyName).SetValue(obj, val, new object[] { });
        this.bindingSource.CurrencyManager.Refresh();
        }
        catch(EntityException ex)
        {
            // handle error
        }
        catch(Exception ex)
        {
            // cannot occurred if code is safe
            System.Windows.Forms.MessageBox.Show("No enum value for this radio button : " + ex.ToString());
        }

This allows the enum value error to be handled as well as other errors that may occur.  However use the EntityException or variations of it before the Exception block (all decendents of Exception have to come first). One can get specific entity state information for a entity framework error by using the entity framework classes instead of the Exception base class. This can be helpful for debugging or providing clearer run time messages for the user.

When I setup try-catch blocks I like to view it as a "layer" on top of the code.  I make decisions about the flow of the exceptions through out the program, their display to the user, and what ever cleanup is required to allow the program to continue working properly without objects in a indeterminate state that can cascade to other errors.


问:
JavaScript - Array newLength from MDN tutorial
I'm working through a tutorial on Arrays from MDN and I can't understand HOW the code line "newLength" is returning the value of 7? I understand that there are 7 items in the array but how is it doing it when there is no ".length" on the end.

My Code -

```<code>var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';

var myArray = myData.split(',');

var newLength = myArray.push('Bristol');

console.log(myArray);

console.log(newLength);
</code>```

This is the return result within console -

```<code>[ 'Manchester',

  'London',

  'Liverpool',

  'Birmingham',

  'Leeds',

  'Carlisle',

  'Bristol' ]

7
</code>```

Thx for your help!

答: Array.prototype.push() returns the new length of the array you pushed on: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/push</p>

Body:
I'm working through a tutorial on Arrays from MDN and I can't understand HOW the code line "newLength" is returning the value of 7? I understand that there are 7 items in the array but how is it doing it when there is no ".length" on the end.

My Code -

var myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';

var myArray = myData.split(',');

var newLength = myArray.push('Bristol');

console.log(myArray);

console.log(newLength);

This is the return result within console -

[ 'Manchester',

  'London',

  'Liverpool',

  'Birmingham',

  'Leeds',

  'Carlisle',

  'Bristol' ]

7

Thx for your help!


问:
Safe to release UINavigationController?
I am creating a (UIPopoverController) popover controller and (UINavigationController) navigation controller for the popover, where both controllers are declared in the header file.  Then, when they are created:

```<code>myNavController = [[UINavigationController alloc] initWithRootViewController:[[[MyPopoverControllerClass alloc] initWithNibName:@"MyPopoverNib" bundle:[NSBundle mainBundle]]autorelease]];

myPopoverController = [[UIPopoverController alloc] initWithContentViewController:myNavController];
</code>```

At this point, is it safe to release myNavController?

答: If myNavController is an instance variable, then you shouldn't release it until your dealloc method. If it's just a local variable, you should release it after the last reference to it in that method.

Title: Safe to release UINavigationController?

Body:
I am creating a (UIPopoverController) popover controller and (UINavigationController) navigation controller for the popover, where both controllers are declared in the header file.  Then, when they are created:

myNavController = [[UINavigationController alloc] initWithRootViewController:[[[MyPopoverControllerClass alloc] initWithNibName:@"MyPopoverNib" bundle:[NSBundle mainBundle]]autorelease]];

myPopoverController = [[UIPopoverController alloc] initWithContentViewController:myNavController];

At this point, is it safe to release myNavController?


答:
it's quite simple...
The function push returns the new length of your array.

```<code>var newLength = myArray.push('Bristol'); //Returns the new length
</code>```

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

Title: JavaScript - Array newLength from MDN tutorial

Body:
it's quite simple...
The function push returns the new length of your array.

var newLength = myArray.push('Bristol'); //Returns the new length

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push


问:
Apachectl command does not work properly on mac
I started learning Apache server with my macbook, and I typed apachectl on the Terminal.

Unfortunately I could only see the following message.

```<code>AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using Marshalls-MacBook-Air.local. Set the 'ServerName' directive globally to suppress this message
(13)Permission denied: AH00072: make_sock: could not bind to address [::]:80
(13)Permission denied: AH00072: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
AH00015: Unable to open logs
</code>```

What do you think is the matter, and how should I fix?

答:
I typed apachectl

You need prefix apachectl with sudo, so:

```<code>sudo apachectl start
</code>```

otherwise the command has no enough privileges to bind into port 80.

AH00558: httpd: Could not reliably determine the server's fully qualified domain name

You need to edit your httpd.conf Apache configuration file and uncomment ServerName line.

To locate the file, run: apachectl -t -D DUMP_INCLUDES first.

Body:
I started learning Apache server with my macbook, and I typed apachectl on the Terminal.

Unfortunately I could only see the following message.

AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using Marshalls-MacBook-Air.local. Set the 'ServerName' directive globally to suppress this message
(13)Permission denied: AH00072: make_sock: could not bind to address [::]:80
(13)Permission denied: AH00072: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
AH00015: Unable to open logs

What do you think is the matter, and how should I fix?

Body:
I typed apachectl

You need prefix apachectl with sudo, so:

sudo apachectl start

otherwise the command has no enough privileges to bind into port 80.

AH00558: httpd: Could not reliably determine the server's fully qualified domain name

You need to edit your httpd.conf Apache configuration file and uncomment ServerName line.

To locate the file, run: apachectl -t -D DUMP_INCLUDES first.


答:
There's nothing wrong with V1 except that it's 1D while V2 and V3 are 2D. According to the docs for hstack, all the input arrays have to have the same shape on all except the second axis. V1 in your code doesn't have a second axis.

You can easily add an empty second axis to V1 during your call to hstack like this:

```<code>new_v = hstack((V1[:, None], V2, V3))
</code>```

That should achieve your desired output.

Note: The V1[:, None] bit is one of three ways that NumPy has available to add empty dimensions to arrays. The other two are V1[:, np.newaxis] and the function version np.expand_dims(V1, axis=1).

You could use any of these in place of V1[:, None] in that line of code and it would work. Check out the docs for numpy.expand_dims for more on adding dimensions to arrays.

Title: ValueError: all the input arrays must have same number of dimensions . Stacking vectors

Body:
l have three arrays to append.
Here a sample of my vectors :

V1=array([ 0.03317591, -0.01624349, -0.01151019])
V2=array([[ 0.06865846, -0.00223798],
       [-0.02872752, -0.00369226],
       [-0.02063454, -0.00231726]])
V3=
array([[ 0.01160267,  0.12610824, -0.01634712,  0.01217519],
       [-0.00727594, -0.0501376 , -0.01641992,  0.00933081],
       [-0.05305551,  0.01195211,  0.04031831, -0.04476306]])

in order to append the three vectors and get one vector l did the following :

new_v=np.hstack((V1,V2,V3))

l got the following error :

ValueError: all the input arrays must have same number of dimensions

However :

 V2_V3=np.hstack((V2,V3))

works, it returns :

array([[ 0.06865846, -0.00223798,  0.01160267,  0.12610824, -0.01634712,
         0.01217519],
       [-0.02872752, -0.00369226, -0.00727594, -0.0501376 , -0.01641992,
         0.00933081],
       [-0.02063454, -0.00231726, -0.05305551,  0.01195211,  0.04031831,
        -0.04476306]])

What l would like to get is the following :

array([[0.03317591, 0.06865846, -0.00223798,  0.01160267,  0.12610824, -0.01634712,
         0.01217519],
       [-0.01624349, -0.02872752, -0.00369226, -0.00727594, -0.0501376 , -0.01641992,
         0.00933081],
       [-0.01151019, -0.02063454, -0.00231726, -0.05305551,  0.01195211,  0.04031831,
        -0.04476306]])

What is wrong with V1 ?

Body:
There's nothing wrong with V1 except that it's 1D while V2 and V3 are 2D. According to the docs for hstack, all the input arrays have to have the same shape on all except the second axis. V1 in your code doesn't have a second axis.

You can easily add an empty second axis to V1 during your call to hstack like this:

new_v = hstack((V1[:, None], V2, V3))

That should achieve your desired output.

Note: The V1[:, None] bit is one of three ways that NumPy has available to add empty dimensions to arrays. The other two are V1[:, np.newaxis] and the function version np.expand_dims(V1, axis=1).

You could use any of these in place of V1[:, None] in that line of code and it would work. Check out the docs for numpy.expand_dims for more on adding dimensions to arrays.


问:
Flickering issue when overriding WM_PAINT in windows forms
I guess this is generic issue and not limited to ComboBox, however I have specifically problem with ComboBox. I extended ComboBox object with MyCB MyCB : ComboBox)

What happens is every time I hover over the control, leave the control, expand selection box or select a value, the control flickers. For a short while I can see default (non-replaced) control which is being instantly replaced with mine.

I believe what's happening is that Windows first draws the "original" control (by calling base.WndProc()) and then repaints it with mine.

The question is, can I somehow stop windows from painting it's own control and instantly paint mine?

Below is code overriding WndProc

```<code>protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);

    if (m.Msg == WM_PAINT)
    {
        Graphics gg = this.CreateGraphics();
        gg.FillRectangle(BorderBrush, this.ClientRectangle);

        // ... //

        //Draw the arrow
        gg.FillPath(ArrowBrush, pth);

        // ... //

        if(this.Text == "")
            gg.DrawString("-- SELECT --", this.Font, new SolidBrush(Color.Black), rf, sf);
        else
            gg.DrawString(this.Text, this.Font, new SolidBrush(Color.Black), rf, sf);

        gg.Dispose();
    }
}
</code>```

What have I tried so far:

I know that I can't do this:

```<code>if (m.Msg == WM_PAINT)
{
    ...
}
else
{
    base.WndProc(ref m);
}
</code>```

as that will cause control to repaint itself infinitely (not sure why)

I was able to remove flickering which happened when mouse leaves/enters the control by adding this code

```<code>if (m.Msg == WM_MOUSEFIRST || m.Msg == WM_MOUSELEAVE) // 0x0200 0x02A3
{
    m.Result = (IntPtr)1;
}
else
{
    base.WndProc(ref m);

    if (m.Msg == WM_PAINT)
    {
        ...
    }
}
</code>```

however this doesn't solve the problem completely

I looked into ILSpy to check on ComboBox's WndProc but there were so many windows messages that I didn't know which of those I could possibly immitate to achive my goal

答:
```<code>    public CustomComboBox()
    {
        SetStyle(ControlStyles.DoubleBuffer, true);
        SetStyle(ControlStyles.ResizeRedraw, true);
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
    }

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == Win32.WM_MOUSEFIRST || m.Msg == Win32.WM_MOUSELEAVE || m.Msg == Win32.WM_MOUSEHOVER) //0x0200, 0x02A3, 0x02A1
        {
            m.Result = (IntPtr)1;
            return;
        }

        base.WndProc(ref m);
        if (m.Msg == Win32.WM_PAINT)
        {
            IntPtr hDC = Win32.GetWindowDC(m.HWnd);
            Graphics g = Graphics.FromHdc(hDC);

            g.SmoothingMode = SmoothingMode.HighSpeed;
            g.PixelOffsetMode = PixelOffsetMode.HighSpeed;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            if (Text.Length == 0)
            {
                StringFormat stringFormat = new StringFormat
                {
                    Alignment = StringAlignment.Near,
                    LineAlignment = StringAlignment.Near
                };
                g.DrawString("Water Marks", Font, new SolidBrush(Color.FromArgb(51, 51, 51)), (Bounds.Width - 2), FontHeight + 2, stringFormat);
            }

            Pen border = new Pen(ui_BorderLineColor, 1);
            g.DrawRectangle(border, 0, 0, this.Width - 1, this.Height - 1);

            g.Dispose();
            Win32.ReleaseDC(m.HWnd, hDC);

        }
    }

    protected override void InitLayout()
    {
        base.InitLayout();
        DropDownStyle = ComboBoxStyle.DropDownList; //Works only in DropDownList
    }

// Edit completing Moses comment
public class Win32
    {
        public const int WM_MOUSEFIRST = 0x0200;
        public const int WM_MOUSELEAVE = 0x02A3;
        public const int WM_MOUSEHOVER = 0x02A1;
        public const int WM_PAINT = 0x000F;
        [DllImport("user32")]
        public static extern IntPtr GetWindowDC(IntPtr hwnd);
        [DllImport("user32.dll")]
        public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
        [DllImport("user32.dll")]
        public static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprc, IntPtr hrgn, uint flags);
    }
</code>```

Body:
I guess this is generic issue and not limited to ComboBox, however I have specifically problem with ComboBox. I extended ComboBox object with MyCB MyCB : ComboBox)

What happens is every time I hover over the control, leave the control, expand selection box or select a value, the control flickers. For a short while I can see default (non-replaced) control which is being instantly replaced with mine.

I believe what's happening is that Windows first draws the "original" control (by calling base.WndProc()) and then repaints it with mine.

The question is, can I somehow stop windows from painting it's own control and instantly paint mine?

Below is code overriding WndProc

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);

    if (m.Msg == WM_PAINT)
    {
        Graphics gg = this.CreateGraphics();
        gg.FillRectangle(BorderBrush, this.ClientRectangle);

        // ... //

        //Draw the arrow
        gg.FillPath(ArrowBrush, pth);

        // ... //

        if(this.Text == "")
            gg.DrawString("-- SELECT --", this.Font, new SolidBrush(Color.Black), rf, sf);
        else
            gg.DrawString(this.Text, this.Font, new SolidBrush(Color.Black), rf, sf);

        gg.Dispose();
    }
}

What have I tried so far:

I know that I can't do this:

if (m.Msg == WM_PAINT)
{
    ...
}
else
{
    base.WndProc(ref m);
}

as that will cause control to repaint itself infinitely (not sure why)

I was able to remove flickering which happened when mouse leaves/enters the control by adding this code

if (m.Msg == WM_MOUSEFIRST || m.Msg == WM_MOUSELEAVE) // 0x0200 0x02A3
{
    m.Result = (IntPtr)1;
}
else
{
    base.WndProc(ref m);

    if (m.Msg == WM_PAINT)
    {
        ...
    }
}

however this doesn't solve the problem completely

I looked into ILSpy to check on ComboBox's WndProc but there were so many windows messages that I didn't know which of those I could possibly immitate to achive my goal

ContentLicense: CC BY-SA 4.0


问:
Promise.map and callback on each resolved
I have an array of URLs which I am mapping (with bluebird's Promise.map) to http GET requests with max concurrency set:

```<code>const fetchingPages = Promise.map(urls, async url => {
  const data = await fetchPage(url)
  return data
}, { concurrency: 100 })
const pages = await fetchingPages
</code>```

How can I listen to each promise being resolved and do some side effect in an organized manner, i.e. don't put side effects inside .map callback?

Ideally, I would like to have array of "empty/dummy" promises ahead of time, so I can set callback to any of them before corresponding GET request is even sent.

I can do it like this:

```<code>const pagesUtils = urls.map((url) => {
  let resolve, reject
  const promise = new Promise((res, rej) => {
    resolve = res
    reject = rej
  })
  return {
    url,
    promise,
    resolve,
    reject,
  }
})

const pagesPromises = pagesUtils.map(x => x.promise)

Promise.map(urlsFinal, async (url, i) => {
  const data = await fetchPageData(url)
  pagesUtils[i].resolve(data)
  return data
}, { concurrency: CONCURRENCY })

pagesPromises.forEach(p => {
  p.then((result) => {
    // side-effect
    console.log(result)
  })
})

const results = await Promise.all(pagesPromises)
</code>```

How can this be done in ideal way? Thanks.

答:
How about using a custom event-handler?</p>

```<code>function URLFetcher(urls) {
    var onCallback = () => {};

    this.on = cb => {
        onCallback = cb;
    }

    this.fetch = () => {
        return Promise.map(urls, async (url, idx) => {
          const data = await fetchPage(url);
          onCallback(idx, url, data);
          return data
        }, { concurrency: 100 })
    }
}

var fetcher = new URLFetcher(urls);
fetcher.on( (idx, url, data) => {
    console.log(`URL #${idx} i.e ${url} was returned with data`, data);
})
const pages = await fetcher.fetch()
</code>```

Body:
I have an array of URLs which I am mapping (with bluebird's Promise.map) to http GET requests with max concurrency set:

const fetchingPages = Promise.map(urls, async url => {
  const data = await fetchPage(url)
  return data
}, { concurrency: 100 })
const pages = await fetchingPages

How can I listen to each promise being resolved and do some side effect in an organized manner, i.e. don't put side effects inside .map callback?

Ideally, I would like to have array of "empty/dummy" promises ahead of time, so I can set callback to any of them before corresponding GET request is even sent.

I can do it like this:

const pagesUtils = urls.map((url) => {
  let resolve, reject
  const promise = new Promise((res, rej) => {
    resolve = res
    reject = rej
  })
  return {
    url,
    promise,
    resolve,
    reject,
  }
})

const pagesPromises = pagesUtils.map(x => x.promise)

Promise.map(urlsFinal, async (url, i) => {
  const data = await fetchPageData(url)
  pagesUtils[i].resolve(data)
  return data
}, { concurrency: CONCURRENCY })

pagesPromises.forEach(p => {
  p.then((result) => {
    // side-effect
    console.log(result)
  })
})

const results = await Promise.all(pagesPromises)

How can this be done in ideal way? Thanks.

Body:
How about using a custom event-handler?

function URLFetcher(urls) {
    var onCallback = () => {};

    this.on = cb => {
        onCallback = cb;
    }

    this.fetch = () => {
        return Promise.map(urls, async (url, idx) => {
          const data = await fetchPage(url);
          onCallback(idx, url, data);
          return data
        }, { concurrency: 100 })
    }
}

var fetcher = new URLFetcher(urls);
fetcher.on( (idx, url, data) => {
    console.log(`URL #${idx} i.e ${url} was returned with data`, data);
})
const pages = await fetcher.fetch()


问:
Add each value from each iterations from a for loop c#
I want to add each A value of each iteration together. In this loop it will go around ten times, so i will have 10 different A values. I want the total value of every A. I have solved it, but i feel like its must be an easier way to do it. So my question is, is there an easier way to do it?</p>

```<code>int a = 0;
int b = 0;
int c = 0;
int e = 0;
for (int i = 1; i <= 10; i++)
{
     a = i * i;
     c = a + b;
     c = e + c;
     e = c;
}
Console.WriteLine(c);
Console.Read();
</code>```

答:
Your code doesn't really make sense. For example, why are you assigning a value to c, but then assigning another value in the next line? The result is that the first value is not used.

But to answer your question specifically to "I want the total value of every A.".

```<code>int a = 0;
int b = 0;
int c = 0;
int e = 0;
int total = 0;

for (int i = 1; i <= 10; i++)
{
    a = i * i;
    c = a + b;
    c = e + c;
    e = c;
    total += a;
}
Console.WriteLine(total);
Console.Read();
</code>```

Body:
I want to add each A value of each iteration together. In this loop it will go around ten times, so i will have 10 different A values. I want the total value of every A. I have solved it, but i feel like its must be an easier way to do it. So my question is, is there an easier way to do it?

int a = 0;
int b = 0;
int c = 0;
int e = 0;
for (int i = 1; i <= 10; i++)
{
     a = i * i;
     c = a + b;
     c = e + c;
     e = c;
}
Console.WriteLine(c);
Console.Read();

Body:
Your code doesn't really make sense. For example, why are you assigning a value to c, but then assigning another value in the next line? The result is that the first value is not used.

But to answer your question specifically to "I want the total value of every A.".

int a = 0;
int b = 0;
int c = 0;
int e = 0;
int total = 0;

for (int i = 1; i <= 10; i++)
{
    a = i * i;
    c = a + b;
    c = e + c;
    e = c;
    total += a;
}
Console.WriteLine(total);
Console.Read();


问:
Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0
Git Extensions: Everything was working fine until yesterday.

But suddenly I am get this error when I try to pull some repositories using git extensions

```<code>C:\Program Files\Git\bin\git.exe pull --progress "origin"
Done
    0 [main] us 0 init_cheap: VirtualAlloc pointer is null, Win32 error 487
AllocationBase 0x0, BaseAddress 0x68560000, RegionSize 0x390000, State 0x10000
C:\Program Files\Git\bin\sh.exe: *** Couldn't reserve space for cygwin's heap, Win32 error 0
</code>```

It is happening for all the repositories which I have cloned.
But, my git bash is working fine.
I don't have any idea what is going on. Any idea as to why this is happening?

答: Deleting old version of %USERPROFILE%\AppData\Local\SourceTree\app-x.x.x worked for me. Not sure how it was connected to command line git...</p>

Body:
Git Extensions: Everything was working fine until yesterday.

But suddenly I am get this error when I try to pull some repositories using git extensions

C:\Program Files\Git\bin\git.exe pull --progress "origin"
Done
    0 [main] us 0 init_cheap: VirtualAlloc pointer is null, Win32 error 487
AllocationBase 0x0, BaseAddress 0x68560000, RegionSize 0x390000, State 0x10000
C:\Program Files\Git\bin\sh.exe: *** Couldn't reserve space for cygwin's heap, Win32 error 0

It is happening for all the repositories which I have cloned.
But, my git bash is working fine.
I don't have any idea what is going on. Any idea as to why this is happening?


问:
Processing Calculations With TemplateTag Returns None
I have a model Coper and a field that ask user to select whether they need to get price quotes dynamically or not. So if a user selects 'dynamic', the user will get the quote for the product and other charges.

So I wrote a template tag that will take the id of the product, filter the currency of the seller and lookup for the rate in another model and finish up the quote.

```<code>@register.filter(name='get_total_quote')
def get_total_quote(value):
    tap = Coper.objects.get(pk=value)
    get_cnd = VAM.objects.get(money_code = tap.seller.profile.currency)
    ratex = get_cnd.money_rate
    if tap.margin_type == 'plus':
        percent = tap.margin_figure / 100
        addup =  ratex * percent
        total_amt = ratex + addup
        return total_amt
    if tap.margin_type == 'minus':
        percent = tap.margin_figure / 100
        addup =  ratex * percent
        total_namt = ratex - addup
        return total_namt
</code>```

Template

```<code>{% load quote_filter %}
    {% for m in all_quotes %}
        {% if m.pricing == 'dynamic' %}
            {{m.id|get_total_quote }}
        {% else %}
           <p> Fixed price is $3500 </p>
        {% endif %}
    {% empty %}
       <p> No product yet. </p>
     {% endfor %}
</code>```

When I load the site, I got NONE as the price of the dynamic quote instead of the actual figure.

What am I missing?

答:
If neither if statement is True, your tag returns None.

```<code>if tap.margin_type == 'plus':
    ...
    return total_amt
if tap.margin_type == 'minus':
    ...
    return total_amt
# if code gets to this point, you are implicitly returning None
</code>```

As Daniel suggested in the Comments, you can pass the Coper object directly to the tag:

```<code>{{m|get_total_quote }}
</code>```

then change the filter to accept tap and remove tap = Coper.objects.get(pk=value):

```<code>@register.filter(name='get_total_quote')
def get_total_quote(tap):
    get_cnd = VAM.objects.get(money_code = tap.seller.profile.currency)
    ...
</code>```

Body:
I have a model Coper and a field that ask user to select whether they need to get price quotes dynamically or not. So if a user selects 'dynamic', the user will get the quote for the product and other charges.

So I wrote a template tag that will take the id of the product, filter the currency of the seller and lookup for the rate in another model and finish up the quote.

@register.filter(name='get_total_quote')
def get_total_quote(value):
    tap = Coper.objects.get(pk=value)
    get_cnd = VAM.objects.get(money_code = tap.seller.profile.currency)
    ratex = get_cnd.money_rate
    if tap.margin_type == 'plus':
        percent = tap.margin_figure / 100
        addup =  ratex * percent
        total_amt = ratex + addup
        return total_amt
    if tap.margin_type == 'minus':
        percent = tap.margin_figure / 100
        addup =  ratex * percent
        total_namt = ratex - addup
        return total_namt

Template

{% load quote_filter %}
    {% for m in all_quotes %}
        {% if m.pricing == 'dynamic' %}
            {{m.id|get_total_quote }}
        {% else %}

 Fixed price is $3500

        {% endif %}
    {% empty %}

 No product yet.

     {% endfor %}

When I load the site, I got NONE as the price of the dynamic quote instead of the actual figure.

What am I missing?

Body:
If neither if statement is True, your tag returns None.

if tap.margin_type == 'plus':
    ...
    return total_amt
if tap.margin_type == 'minus':
    ...
    return total_amt
# if code gets to this point, you are implicitly returning None

As Daniel suggested in the Comments, you can pass the Coper object directly to the tag:

{{m|get_total_quote }}

then change the filter to accept tap and remove tap = Coper.objects.get(pk=value):

@register.filter(name='get_total_quote')
def get_total_quote(tap):
    get_cnd = VAM.objects.get(money_code = tap.seller.profile.currency)
    ...


问:
Adding an active class according to URL
I have a php/mysql driven menu. I am trying to add an active class to the menu item whenever the URI reflects that menu item (basically, when I am on that page) but every example I find is with a menu that is not populated through an array or repeater like mine.

How can manipulate the active class you see below so that it shows only when I am on that page?

Here is my menu

```<code><?php
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            if($row['id'] == 2){
                // below is the active class that is now being populated accross all items equally
                echo '<li class="nav-item dropdown active">';
                echo '<a href="#" class="nav-link dropdown-toggle animated fadeIn animation-delay-7" data-toggle="dropdown" data-hover="dropdown" role="button" aria-haspopup="true" aria-expanded="false" data-name="services">';
                echo $row["pagename"];
                echo '<i class="zmdi zmdi-chevron-down"></i>';
                echo '</a>';
                // create a new list
                echo '<ul class="dropdown-menu">';
                    // loop second/submenu query results
                    while($sub_row = $result2->fetch_assoc()) {
                        echo '<li>';
                        echo '<a href="' . $sub_row["link"] . '" class="dropdown-item">' . $sub_row["pagename"] . '</a>';
                        echo '</li>';
                    }
                echo "</ul>";
                echo '</li>';
            } else { // for all other menu links
                echo '<li class="nav-item dropdown active">';
                echo '<a href="' . $row["link"] . '" class="nav-link dropdown-toggle animated fadeIn animation-delay-7">' . $row["pagename"] . '</a>';
                echo '</li>';
            }
        }
    } else {
        echo "0 results";
    }
?>
</code>```

The screenshot below shows the result after it renders. Notice the active class highlighted in yellow, it is added to every item in my main menu (the way I have it coded, which it's wrong of course). The green is the $sub_row["link"] (to answer Mark's question below

Notice, the active class is only needed to be added programmatically on the main menu. (the else portion of my code).

The screenshot below shows how the active class affects the menu item if the user was in the www.domain.com/how-it-works.php page. The active class contians the styles to make the menu item appear that way.

Thanks in advance

答:
Hard to test with not having the DB outputs to match against mate but try this, basically you want an if statement to get the current page URL and match it against the url you get back from the DB.

```<code><?php
    if ($result->num_rows > 0) {
        $pageURL = str_replace('/', '', $_SERVER['REQUEST_URI']);
        $homeURL = $_SERVER['REQUEST_URI'];
        // output data of each row

        while($row = $result->fetch_assoc()) {
            if($row['id'] == 2){ ?>
                <li class="nav-item dropdown">
                    <a href="" class="nav-link dropdown-toggle animated fadeIn animation-delay-7" data-toggle="dropdown" data-hover="dropdown" role="button" aria-haspopup="true" aria-expanded="false" data-name="services">
                        <?php echo $row["pagename"];?>
                        <i class="zmdi zmdi-chevron-down"></i>
                    </a>
                    <ul class="dropdown-menu">
                        <?php while($sub_row = $result2->fetch_assoc()) {?>
                            <li>
                                <a href="<?php echo $sub_row["link"]; ?>" class="dropdown-item">
                                    <?php echo $sub_row["pagename"] ?>
                                </a>
                             </li>
                        <?php } ?>
                    </ul>
                </li>
            <?php
            } else if($row['id'] == 1){ ?>
                <li class="nav-item dropdown <?php echo ($homeURL == $row["link"])? 'active' : '';?>">
                    <a href="<?php echo $row["link"]; ?>" class="nav-link dropdown-toggle animated fadeIn animation-delay-7">
                        <?php echo $row["pagename"]; ?>
                    </a>
                </li>
            <?php
            } else { ?>
                <li class="nav-item dropdown <?php echo ($pageURL == $row["link"])? 'active' : '';?>">
                    <a href="<?php echo $row["link"]; ?>" class="nav-link dropdown-toggle animated fadeIn animation-delay-7">
                        <?php echo $row["pagename"]; ?>
                    </a>
                </li>
            <?php }
        }
    } else {
        echo "0 results";
    }
?>
</code>```

Edit:

Bit that gets the current page url is:

```<code>$pageURL  = end(explode('/', $_SERVER['REQUEST_URI']));
</code>```

Bit that does the check is (this is just a shorthand if statement:

```<code><?php echo ($pageURL == $row["link"])? 'active' : '';?>
</code>```

Title: Adding an active class according to URL

Body:
I have a php/mysql driven menu. I am trying to add an active class to the menu item whenever the URI reflects that menu item (basically, when I am on that page) but every example I find is with a menu that is not populated through an array or repeater like mine.

How can manipulate the active class you see below so that it shows only when I am on that page?

Here is my menu

<?php
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            if($row['id'] == 2){
                // below is the active class that is now being populated accross all items equally
                echo '
';
                echo '';
                echo $row["pagename"];
                echo '';
                echo '';
                // create a new list
                echo '
';
                    // loop second/submenu query results
                    while($sub_row = $result2->fetch_assoc()) {
                        echo '
';
                        echo '' . $sub_row["pagename"] . '';
                        echo '
';
                    }
                echo "
";
                echo '
';
            } else { // for all other menu links
                echo '
';
                echo '' . $row["pagename"] . '';
                echo '
';
            }
        }
    } else {
        echo "0 results";
    }
?>

The screenshot below shows the result after it renders. Notice the active class highlighted in yellow, it is added to every item in my main menu (the way I have it coded, which it's wrong of course). The green is the $sub_row["link"] (to answer Mark's question below

Notice, the active class is only needed to be added programmatically on the main menu. (the else portion of my code).

The screenshot below shows how the active class affects the menu item if the user was in the www.domain.com/how-it-works.php page. The active class contians the styles to make the menu item appear that way.

Thanks in advance

Body:
Hard to test with not having the DB outputs to match against mate but try this, basically you want an if statement to get the current page URL and match it against the url you get back from the DB.

<?php
    if ($result->num_rows > 0) {
        $pageURL = str_replace('/', '', $_SERVER['REQUEST_URI']);
        $homeURL = $_SERVER['REQUEST_URI'];
        // output data of each row

        while($row = $result->fetch_assoc()) {
            if($row['id'] == 2){ ?>
                <li class="nav-item dropdown">
                    <a href="" class="nav-link dropdown-toggle animated fadeIn animation-delay-7" data-toggle="dropdown" data-hover="dropdown" role="button" aria-haspopup="true" aria-expanded="false" data-name="services">
                        <?php echo $row["pagename"];?>
                        <i class="zmdi zmdi-chevron-down"></i>
                    </a>
                    <ul class="dropdown-menu">
                        <?php while($sub_row = $result2->fetch_assoc()) {?>
                            <li>
                                <a href="<?php echo $sub_row["link"]; ?>" class="dropdown-item">
                                    <?php echo $sub_row["pagename"] ?>
                                </a>
                             </li>
                        <?php } ?>
                    </ul>
                </li>
            <?php
            } else if($row['id'] == 1){ ?>
                <li class="nav-item dropdown <?php echo ($homeURL == $row["link"])? 'active' : '';?>">
                    <a href="<?php echo $row["link"]; ?>" class="nav-link dropdown-toggle animated fadeIn animation-delay-7">
                        <?php echo $row["pagename"]; ?>
                    </a>
                </li>
            <?php
            } else { ?>
                <li class="nav-item dropdown <?php echo ($pageURL == $row["link"])? 'active' : '';?>">
                    <a href="<?php echo $row["link"]; ?>" class="nav-link dropdown-toggle animated fadeIn animation-delay-7">
                        <?php echo $row["pagename"]; ?>
                    </a>
                </li>
            <?php }
        }
    } else {
        echo "0 results";
    }
?>

Edit:

Bit that gets the current page url is:

$pageURL  = end(explode('/', $_SERVER['REQUEST_URI']));

Bit that does the check is (this is just a shorthand if statement:

<?php echo ($pageURL == $row["link"])? 'active' : '';?>


问:
Render then append new component after click
Is it possible to render and append a new component after click? I have my calendar component

```<code>return (
  <span
    key={date.toString()}
    className={"day" + (isToday ? " today" : "") + (isCurrentMonth ? "" : " different-month") + (date.isSame(selected) ? " selected" : "")}
    onClick={()=>select(day)}>{number}</span>
);
</code>```

onClick I want to render my jsWindow Component

```<code>render(){
    return (
        <div className="js-window">
        {console.log(this.props)}
            <Icon icon={close} className="closeBtn" size={24} onClick={(e)=>e.target.parentNode.parentNode.remove()}/>
            {this.props.children}
        </div>
    )
}
</code>```

After click close icon I want remove JsWindow.

答:
Put the selected day in component state and render your component based on that. On click you set or reset the state, which will trigger a rerender.

Basic example to get you started:

```<code>state = {
    day: undefined
}

selectDay = day => {
    this.setState({day});
};

resetDay = () => {
    this.setState({day: undefined});
};

render(){
    const day = this.state.day;
    return  day ? (
            <div className="js-window">
                <Icon icon={close} className="closeBtn" size={24} onClick={this.resetDay}/>
                {this.props.children}
            </div>
        ) : (
            <span key={date.toString()} className={} onClick={()=>this.selectDay(day)}>{number}</span>
        )
    )
}
</code>```

Body:
Is it possible to render and append a new component after click? I have my calendar component

return (
  select(day)}>{number}
);

onClick I want to render my jsWindow Component

render(){
    return (

        {console.log(this.props)}
            <Icon icon={close} className="closeBtn" size={24} onClick={(e)=>e.target.parentNode.parentNode.remove()}/>
            {this.props.children}

    )
}

After click close icon I want remove JsWindow.

Body:
Put the selected day in component state and render your component based on that. On click you set or reset the state, which will trigger a rerender.

Basic example to get you started:

state = {
    day: undefined
}

selectDay = day => {
    this.setState({day});
};

resetDay = () => {
    this.setState({day: undefined});
};

render(){
    const day = this.state.day;
    return  day ? (
            <div className="js-window">
                <Icon icon={close} className="closeBtn" size={24} onClick={this.resetDay}/>
                {this.props.children}
            </div>
        ) : (
            <span key={date.toString()} className={} onClick={()=>this.selectDay(day)}>{number}</span>
        )
    )
}