问:
Calculate the sum of the child objects of the parent entities in the list
My list is structured like this:

```<code>public class Custo{
      public int id { get; set; }
      public int idParent { get; set; }
      public decimal amount{ get; set; }
      public decimal unitaryValue{ get; set; }

}

List<Custo> myLIst  = new List<Custo>();
</code>```

I want my list to return like this:

```<code>Name              Total Amount      Total Value

Projetos           17,00            $70

  Arquitetura      15,00            $60

    Estrutura      10,00            $35
    Modulo          5,00            $25

  Desenho           2,00            $10
    Artistico       2,00            $10

Projetos Eletricos  0,00            $0
</code>```

答:
Essentially in a composite pattern you would need three classes. One would be the treenode and the other two would inherit from that. One would be a project capable of holding children. The other would be a child/leaf node and would be the individual Custos.

When you use the classes you would create a new Projectos and add child nodes, then call the Display method when you wanted them to display. You could obviously add logic for other functions. This is similar to code found here: http://www.dofactory.com/net/composite-design-pattern

Usage might be
Main

```<code>Projectos project = new Projectos("Projetos");
project.Add(new Custos("Arquitetura", 15, 70.00);

Projectos electricos = new Projectos("Electricos");
electricos.Add(new Custos("custo1", 20, 80.00);
project.Add(electricos);

project.Display();
</code>```

Projectos

```<code>using System;
using System.Collections.Generic;

namespace CompositePatternExercise
{
    class Projectos : CustosNode
    {
        private List<CustosNode> elements = new List<CustosNode>();

        // Constructor
        public Projectos(string name) : base(name)
        {
        }

        public override void Add(CustosNode d)
        {
            elements.Add(d);
        }

        public override void Remove(CustosNode d)
        {
            elements.Remove(d);
        }
        public override void Display()
        {
            decimal totalValue = 0;
            decimal totalAmount = 0;

            Console.WriteLine(_name);

            // Display each child element on this node
            foreach (CustosNode d in elements)
            {
                d.Display();
                totalAmount += d.Amount;
                totalValue += d.Value;
            }

            Console.Write("Project total:" + totalAmount.ToString("C") + " " + totalAmount.ToString("C"));

        }
    }
}
</code>```

Custos

```<code>namespace CompositePatternExercise
{
    class Custos : CustosNode
    {
            // Constructor
            public Custos(string name, decimal amount, decimal value) : base(name, amount, value)
            {
            }
            public override void Add(CustosNode c)
            {
                Console.WriteLine(
                  "Cannot add to a custo");
            }
            public override void Remove(CustosNode c)
            {
                Console.WriteLine(
                  "Cannot remove from a custo");
            }
            public override void Display()
            {
                Console.WriteLine(_name + " " + Amount.ToString("C") + " " + Value.ToString("C"));
            }
        }
    }
}
</code>```

CustosNode

```<code>namespace CompositePatternExercise
{
    abstract class CustosNode
    {
        protected string _name;
        protected decimal _amount = 0m;
        protected decimal _value = 0m;

        public decimal Value { get => _value; }
        public decimal Amount { get => _amount; }

        // Constructor
        public CustosNode(string name)
        {
            this._name = name;
        }
        public CustosNode(string name, decimal amount, decimal value)
        {
            this._name = name;
            this._amount = amount;
            this._value = value;
        }
        public abstract void Add(CustosNode c);
        public abstract void Remove(CustosNode c);
        public abstract void Display();
    }
}
</code>```

Body:
My list is structured like this:

public class Custo{
      public int id { get; set; }
      public int idParent { get; set; }
      public decimal amount{ get; set; }
      public decimal unitaryValue{ get; set; }

}

List<Custo> myLIst  = new List<Custo>();

I want my list to return like this:

Name              Total Amount      Total Value

Projetos           17,00            $70

  Arquitetura      15,00            $60

    Estrutura      10,00            $35
    Modulo          5,00            $25

  Desenho           2,00            $10
    Artistico       2,00            $10

Projetos Eletricos  0,00            $0

Body:
Essentially in a composite pattern you would need three classes. One would be the treenode and the other two would inherit from that. One would be a project capable of holding children. The other would be a child/leaf node and would be the individual Custos.

When you use the classes you would create a new Projectos and add child nodes, then call the Display method when you wanted them to display. You could obviously add logic for other functions. This is similar to code found here: http://www.dofactory.com/net/composite-design-pattern

Usage might be
Main

Projectos project = new Projectos("Projetos");
project.Add(new Custos("Arquitetura", 15, 70.00);

Projectos electricos = new Projectos("Electricos");
electricos.Add(new Custos("custo1", 20, 80.00);
project.Add(electricos);

project.Display();

Projectos

using System;
using System.Collections.Generic;

namespace CompositePatternExercise
{
    class Projectos : CustosNode
    {
        private List<CustosNode> elements = new List<CustosNode>();

        // Constructor
        public Projectos(string name) : base(name)
        {
        }

        public override void Add(CustosNode d)
        {
            elements.Add(d);
        }

        public override void Remove(CustosNode d)
        {
            elements.Remove(d);
        }
        public override void Display()
        {
            decimal totalValue = 0;
            decimal totalAmount = 0;

            Console.WriteLine(_name);

            // Display each child element on this node
            foreach (CustosNode d in elements)
            {
                d.Display();
                totalAmount += d.Amount;
                totalValue += d.Value;
            }

            Console.Write("Project total:" + totalAmount.ToString("C") + " " + totalAmount.ToString("C"));

        }
    }
}

Custos

namespace CompositePatternExercise
{
    class Custos : CustosNode
    {
            // Constructor
            public Custos(string name, decimal amount, decimal value) : base(name, amount, value)
            {
            }
            public override void Add(CustosNode c)
            {
                Console.WriteLine(
                  "Cannot add to a custo");
            }
            public override void Remove(CustosNode c)
            {
                Console.WriteLine(
                  "Cannot remove from a custo");
            }
            public override void Display()
            {
                Console.WriteLine(_name + " " + Amount.ToString("C") + " " + Value.ToString("C"));
            }
        }
    }
}

CustosNode

namespace CompositePatternExercise
{
    abstract class CustosNode
    {
        protected string _name;
        protected decimal _amount = 0m;
        protected decimal _value = 0m;

        public decimal Value { get => _value; }
        public decimal Amount { get => _amount; }

        // Constructor
        public CustosNode(string name)
        {
            this._name = name;
        }
        public CustosNode(string name, decimal amount, decimal value)
        {
            this._name = name;
            this._amount = amount;
            this._value = value;
        }
        public abstract void Add(CustosNode c);
        public abstract void Remove(CustosNode c);
        public abstract void Display();
    }
}


来源: stackexchange

问:
django unittest without database connection
I'm trying to write a unittest that will check if the correct error message is returned in case the database connection hits exception. I've tried to use connection.creation.destroy_test_db(':memory:') but it didn't work as I expected. I suppose I should either remove the tables or somehow cut the db connection. Is any of those possible?

答:
I was looking for django's actual http response code in case of a database connection timeout when using pymysql. The following test confirmed it's a 401 Unauthorized when pymysql raises an OperationalError.

from unittest.mock import patch

import pymysql
from django.test import TestCase, Client

class TestDatabaseOutage(TestCase):
    client = None

    def setUp(self):
        self.client = Client()

    def test_database_connection_timeout_returns_401(self):
        with patch.object(pymysql, 'connect') as connect_method:
            message = "Can't connect to MySQL server on 'some_database.example.com' ([Errno 110] Connection timed out)"
            connect_method.side_effect = pymysql.OperationalError(2003, message)
            response = self.client.get('/')
            self.assertEqual(response.status_code, 401)
```

ContentLicense: CC BY-SA 3.0


问:
Table disappears after adding an item
i'm using datatables to display a list of project names and I'm using a button to add an item to the displayed array, but when i do so, my table disappears.

Here's the code:

view.html

```<code><button ng-click="vm.add()">Add item</button>
<table datatable="ng" dt-instance="vm.dtInstance" dt-options="vm.dtOptions" dt-column-defs="vm.dtColumnDefs"
       class="table table-hover table-striped table-bordered table-condensed">
    <thead>
    <tr style="background-color: #00b3ee; color: white; border:none">
        <th style="text-align: center">Nom</th>
        <th style="text-align: center">Actions</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="project in vm.project.projects">
        <td style="width: 90%; vertical-align: middle">{{project}}</td>
        <td align="center" style="vertical-align: middle">
            <button data-toggle="modal" ng-click="vm.setProject(project)"
                    data-target="#deleteEureciaProjectModal" type="button" class="btn btn-danger">
                <i class="fa fa-trash">  </i>Supprimer
            </button>
        </td>
    </tr>
    </tbody>
</table>
</code>```

controller.js

```<code>vm.add = () => vm.project.projects.push('new project');

fetchProject().then(result => {
    vm.project = result;

    // vm.project = {
    //     projects: [
    //         "project1",
    //         "project2",
    //         "project3",
    //         "project4"
    //     ],
    //     etc...
    // }

    vm.project.projects.push("newProject"); //it's working here, which is normal

    //init datatable
    vm.dtInstance = {};
    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withBootstrap();
    vm.dtColumnDefs = [];
    for (var i = 0; i < 2; i++) {
        if (i == 1) {
            vm.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i).notSortable());
        } else {
            vm.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i));
        }
    }
})
</code>```

I've tried using objects instead of strings.. doesn't work either. I don't know what's going on.
I cannot use server side processing. This has to be done using the angular way.

答:
Ok, so i found it :

For some reason, it worked when i initialized vm.project.project before the promise call. So i created the vm.project object, and i added the project property to it by adding an empty array. I was then able to add items without having my table disappearing.

Title: Table disappears after adding an item

Body:
i'm using datatables to display a list of project names and I'm using a button to add an item to the displayed array, but when i do so, my table disappears.

Here's the code:

view.html

<button ng-click="vm.add()">Add item</button>

        Nom
        Actions

        {{project}}

            <button data-toggle="modal" ng-click="vm.setProject(project)"
                    data-target="#deleteEureciaProjectModal" type="button" class="btn btn-danger">
                  Supprimer
            </button>

controller.js

vm.add = () => vm.project.projects.push('new project');

fetchProject().then(result => {
    vm.project = result;

    // vm.project = {
    //     projects: [
    //         "project1",
    //         "project2",
    //         "project3",
    //         "project4"
    //     ],
    //     etc...
    // }

    vm.project.projects.push("newProject"); //it's working here, which is normal

    //init datatable
    vm.dtInstance = {};
    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withBootstrap();
    vm.dtColumnDefs = [];
    for (var i = 0; i < 2; i++) {
        if (i == 1) {
            vm.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i).notSortable());
        } else {
            vm.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i));
        }
    }
})

I've tried using objects instead of strings.. doesn't work either. I don't know what's going on.
I cannot use server side processing. This has to be done using the angular way.


问:
Nesting conditionals in Java
The Problem

Given the following code:

```<code>if (enforceLength && rawContents.length != recordLength) {
</code>```

Right now if enforceLength and rawContents does not match recordLength, it returns true and triggers our warning system. Some of our recordLength however are HEADER_DIFF characters longer than the rawContents.length.

So we are hoping to put an or on rawContents.length so that it can either match recordLength or recordLength + HEADER_DIFF.

Question

Is there a straightforward way to create an OR conditional on just the second part of this if statement? i.e. so that it triggers the alert if rawContents.length does not equal recordLength but it does not if recordLength happens to be exactly HEADER_DIFF longer than expected.

A failed attempt

One attempt that failed:

```<code>if (enforceLength && rawContents.length != recordLength + HEADER_DIFF
  || rawContents.length != recordLength)
</code>```

答:
The not-or-ious logic knot

```<code>if (enforceLength && rawContents.length != recordLength
        && rawContents.length != recordLength + HEADER_DIFF) {
</code>```

Maybe negatives are more understandable

```<code>if (enforceLength && !(rawContents.length == recordLength
        || rawContents.length == recordLength + HEADER_DIFF)) {
</code>```

Title: Nesting conditionals in Java

Body:
The Problem

Given the following code:

if (enforceLength && rawContents.length != recordLength) {

Right now if enforceLength and rawContents does not match recordLength, it returns true and triggers our warning system. Some of our recordLength however are HEADER_DIFF characters longer than the rawContents.length.

So we are hoping to put an or on rawContents.length so that it can either match recordLength or recordLength + HEADER_DIFF.

Question

Is there a straightforward way to create an OR conditional on just the second part of this if statement? i.e. so that it triggers the alert if rawContents.length does not equal recordLength but it does not if recordLength happens to be exactly HEADER_DIFF longer than expected.

A failed attempt

One attempt that failed:

if (enforceLength && rawContents.length != recordLength + HEADER_DIFF
  || rawContents.length != recordLength)

Body:
The not-or-ious logic knot

if (enforceLength && rawContents.length != recordLength
        && rawContents.length != recordLength + HEADER_DIFF) {

Maybe negatives are more understandable

if (enforceLength && !(rawContents.length == recordLength
        || rawContents.length == recordLength + HEADER_DIFF)) {


问:
Output positive and negative number in a random array in C
I have to create a program that separates the positive and the negative numbers
from a random array.

I tried to create void to separate only the positive numbers at first (visualizzaVettorePos) but I keep getting the Id return 1 exit status.

Any thoughts?

Code :

```<code>#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define DIM 100
#define NUM 20

void caricaVettore(int*, int);
void visualizzaVettore(int*, int);
void visualizzaVettorePos(int[], int[], int);

int main(){
    int mioVettore[DIM];
    int vettorePos[DIM];
    srand((unsigned)time(NULL));
    caricaVettore(mioVettore, DIM);
    visualizzaVettore(mioVettore, DIM);
    visualizzaVettorePos(mioVettore, vettorePos, DIM);
    system("PAUSE");
    return 0;
}

void caricaVettore(int* vettore, int quanti){
    int i;
    printf("Inizio fase caricamento (input)\n");
    for(i=1; i<=quanti; i++){
        vettore[i]=rand()%(NUM*2+1)+(-NUM);
    }
    printf("Fine fase caricamento (input)\n");
}

void visualizzaVettore(int* vettore, int quanti){
    int i;
    printf("Inizio fase visualizzazione (output)\n");
    for(i=1; i<=quanti; i++){
        printf("Valore indice %d: %d\n", i, vettore[i]);
    }
    printf("Fine fase visualizzazione (output)\n");
}

void visualizzaVettoriPos(int vettore[], int vettorepos[], int quanti){
    int i,j;
    j=1;
    for(i=0; i<quanti; i++ && j++){
        if (vettore[i]>=0){
            vettorepos[j]=vettore[i];
        }
    }
}
</code>```

答:
Your program exhibits undefined behaviour. In C array indexes start at 0 and not at 1.

Therefore you need to change your for loops like this:

```<code>for (i = 0; i < quanti; i++)
</code>```

instead of:

```<code>for (i = 1; i <= quanti; i++)
</code>```

And for the same reason in the visualizzaVettoriPos function

```<code>j = 1;
</code>```

should be

```<code>j = 0;
</code>```

Body:
I have to create a program that separates the positive and the negative numbers
from a random array.

I tried to create void to separate only the positive numbers at first (visualizzaVettorePos) but I keep getting the Id return 1 exit status.

Any thoughts?

Code :

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define DIM 100
#define NUM 20

void caricaVettore(int*, int);
void visualizzaVettore(int*, int);
void visualizzaVettorePos(int[], int[], int);

int main(){
    int mioVettore[DIM];
    int vettorePos[DIM];
    srand((unsigned)time(NULL));
    caricaVettore(mioVettore, DIM);
    visualizzaVettore(mioVettore, DIM);
    visualizzaVettorePos(mioVettore, vettorePos, DIM);
    system("PAUSE");
    return 0;
}

void caricaVettore(int* vettore, int quanti){
    int i;
    printf("Inizio fase caricamento (input)\n");
    for(i=1; i<=quanti; i++){
        vettore[i]=rand()%(NUM*2+1)+(-NUM);
    }
    printf("Fine fase caricamento (input)\n");
}

void visualizzaVettore(int* vettore, int quanti){
    int i;
    printf("Inizio fase visualizzazione (output)\n");
    for(i=1; i<=quanti; i++){
        printf("Valore indice %d: %d\n", i, vettore[i]);
    }
    printf("Fine fase visualizzazione (output)\n");
}

void visualizzaVettoriPos(int vettore[], int vettorepos[], int quanti){
    int i,j;
    j=1;
    for(i=0; i<quanti; i++ && j++){
        if (vettore[i]>=0){
            vettorepos[j]=vettore[i];
        }
    }
}

Body:
Your program exhibits undefined behaviour. In C array indexes start at 0 and not at 1.

Therefore you need to change your for loops like this:

for (i = 0; i < quanti; i++)

instead of:

for (i = 1; i <= quanti; i++)

And for the same reason in the visualizzaVettoriPos function

j = 1;

should be

j = 0;


问:
PHP password recovery
I realize that for security that passwords should not be stored in a DB as plaintext.  If I hash them, I can validate them for login purposes.

But if I want to set up a password recovery system, what's the best strategy since there is no undoing of the hashing?

Could someone give me a brief overview of a good and secure strategy for storing and recovering passwords?

答: You can create a new (and randomly generated) password for user, and md5 it , and then send user via email. </p>

Title: PHP password recovery

ContentLicense: CC BY-SA 2.5


问:
Typescript .length return undefined
This issue makes me crazy ...

I have this code :

```<code>if (control.value==null||control.value == "" || control.value == " " || control.value.length != 5) {
     // do something
}
</code>```

My problem : control.value.length always returns 'undefined'.

I try to use a string variable like this but the result is the same.

```<code>var curVal: string = control.value;
if (curVal==null||curVal== "" || curVal == " " || curVal != 5) {
     // do something
}
</code>```

Where am I wrong ?

Edit: Precision : my control.value is not null or empty, I test with the value 59000

This code :

```<code>console.log(control.value + ' - ' + control.value.length);
</code>```

log this : 59000 - undefined

EDIT 2 : Thank's you, it's solved. The problem was my control.value was a number and not a string.

答:
Sometimes there is this bug on Angular, since version 5.0.0 I think, even when the variable is not a number, I've to convert it to a number to use the '.length' property like below :

```<code>if (control.value==null||control.value == "" || control.value == " " || +(control.value.length) != 5) {
 // do something
</code>```

It may works, just by adding the sign '+' before your var.length like: +(var.length)

Title: Typescript .length return undefined

Body:
This issue makes me crazy ...

I have this code :

if (control.value==null||control.value == "" || control.value == " " || control.value.length != 5) {
     // do something
}

My problem : control.value.length always returns 'undefined'.

I try to use a string variable like this but the result is the same.

var curVal: string = control.value;
if (curVal==null||curVal== "" || curVal == " " || curVal != 5) {
     // do something
}

Where am I wrong ?

Edit: Precision : my control.value is not null or empty, I test with the value 59000

This code :

console.log(control.value + ' - ' + control.value.length);

log this : 59000 - undefined

EDIT 2 : Thank's you, it's solved. The problem was my control.value was a number and not a string.

Body:
Sometimes there is this bug on Angular, since version 5.0.0 I think, even when the variable is not a number, I've to convert it to a number to use the '.length' property like below :

if (control.value==null||control.value == "" || control.value == " " || +(control.value.length) != 5) {
 // do something

It may works, just by adding the sign '+' before your var.length like: +(var.length)


问:
ICommand predicate not being read when updating property
In an application I'm using for control of one or more devices on a serial communication bus, I'm using an IsAlive property in my DeviceModel class to tell if the communication link with the device is up (i.e. replies are received on the expected address).  The property fires a PropertyChanged event notification.

I'm using the IsAlive property both for setting the background color on a data template and for controlling the command predicate for the buttons in the data template.  By yanking out the communication cable, I'm forcing the link to time out and set IsAlive to false.  This works fine on the template background color, but the buttons aren't responding on the predicate change until I click anywhere on the View.

Any idea why this is?  And how I can get the buttons to update immediately when setting the IsAlive property?

C# command predicate:

```<code>private bool CanPressMovementButton(object obj) {
    if (IsAlive == true && Address > -1 && Address < 31) {
        return true;
    }
    return false;
}
</code>```

Here's a screenshot where the buttons are disabled even though the IsAlive property is set true.  The buttons are enabled immediatly when I click the View.

答:
After Anton Semenov's tip about using the RaiseCanExecuteChanged method in Prism's DelegateCommand implementation, it worked like a charm.  Setting IsAlive from the model now updates the View immediately without any need to give focus to the View.  Since I'll be supporting several device types with different commands depending on device type, I'm setting the DelegateCommand objects like this:

```<code>public bool IsAlive {
    get { return _isAlive; }
    set {
        bool newValue = SetNotify(ref _isAlive, value);
        if (newValue) {
            var properties = GetType().GetProperties();
            foreach (var property in properties) {
                if (property != null && property.PropertyType == typeof(DelegateCommand)) {
                    var command = (DelegateCommand)property.GetValue(this, null);
                    command.RaiseCanExecuteChanged();
                    Console.WriteLine("Raised!");
                }
            }
        }
    }
}
</code>```

Body:
In an application I'm using for control of one or more devices on a serial communication bus, I'm using an IsAlive property in my DeviceModel class to tell if the communication link with the device is up (i.e. replies are received on the expected address).  The property fires a PropertyChanged event notification.

I'm using the IsAlive property both for setting the background color on a data template and for controlling the command predicate for the buttons in the data template.  By yanking out the communication cable, I'm forcing the link to time out and set IsAlive to false.  This works fine on the template background color, but the buttons aren't responding on the predicate change until I click anywhere on the View.

Any idea why this is?  And how I can get the buttons to update immediately when setting the IsAlive property?

C# command predicate:

private bool CanPressMovementButton(object obj) {
    if (IsAlive == true && Address > -1 && Address < 31) {
        return true;
    }
    return false;
}

Here's a screenshot where the buttons are disabled even though the IsAlive property is set true.  The buttons are enabled immediatly when I click the View.

Body:
After Anton Semenov's tip about using the RaiseCanExecuteChanged method in Prism's DelegateCommand implementation, it worked like a charm.  Setting IsAlive from the model now updates the View immediately without any need to give focus to the View.  Since I'll be supporting several device types with different commands depending on device type, I'm setting the DelegateCommand objects like this:

public bool IsAlive {
    get { return _isAlive; }
    set {
        bool newValue = SetNotify(ref _isAlive, value);
        if (newValue) {
            var properties = GetType().GetProperties();
            foreach (var property in properties) {
                if (property != null && property.PropertyType == typeof(DelegateCommand)) {
                    var command = (DelegateCommand)property.GetValue(this, null);
                    command.RaiseCanExecuteChanged();
                    Console.WriteLine("Raised!");
                }
            }
        }
    }
}


答:
Fail if neither of the 2 conditions is true:</p>

```<code>if (enforceLength && !(rawContents.length == recordLength + HEADER_DIFF || rawContents.length == recordLength))
</code>```

Title: Nesting conditionals in Java

Body:
Fail if neither of the 2 conditions is true:

if (enforceLength && !(rawContents.length == recordLength + HEADER_DIFF || rawContents.length == recordLength))


问:
Ramda ifElse is not executed for function with multiple arguments
Can somebody explain me this behavior, or is it a bug?

```<code>const firstTest = (a) => console.log(a, 'this will be executed');
const secTest = (a, b) => console.log(a, 'this will not be executed');

const firstIfElse = R.ifElse(R.T, firstTest, () => null);
const unexpectedIfElse = R.ifElse(R.T, secTest, () => null);

firstIfElse('logging appears as expected');
unexpectedIfElse('no logging');
</code>```

example in REPL

答:
Your second function is a curried binary function.  ifElse chooses the maximum arity of the three functions passed to it, predicate, ifTrue, and ifFalse.  R.T has arity 1, as does () => null, but secTest has arity 2, so unexpectedIfElse also has arity 2.

When you call unexpectedIfElse with 'no logging', you get back a function waiting for the (useless) b parameter.

There are reasons not to like this additional complexity, but there are times when it's very useful, especially for the predicate.

You can fix your issue by calling it like

```<code>unexpectedIfElse('no logging', 'ignored');
</code>```

or like

```<code>unexpectedIfElse('no logging')('ignored')
</code>```

Body:
Can somebody explain me this behavior, or is it a bug?

const firstTest = (a) => console.log(a, 'this will be executed');
const secTest = (a, b) => console.log(a, 'this will not be executed');

const firstIfElse = R.ifElse(R.T, firstTest, () => null);
const unexpectedIfElse = R.ifElse(R.T, secTest, () => null);

firstIfElse('logging appears as expected');
unexpectedIfElse('no logging');

<a href="http://ramdajs.com/repl/?v=0.25.0#?const%20firstTest%20%3D%20%28a%29%20%3D%3E%20console.log%28a%2C%20%27this%20will%20be%20executed%27%29%3B%0Aconst%20secTest%20%3D%20%28a%2C%20b%29%20%3D%3E%20console.log%28a%2C%20%27this%20will%20not%20be%20executed%27%29%3B%0A%0Aconst%20firstIfElse%20%3D%20R.ifElse%28R.T%2C%20firstTest%2C%20%28%29%20%3D%3E%20null%29%3B%0Aconst%20unexpectedIfElse%20%3D%20R.ifElse%28R.T%2C%20secTest%2C%20%28%29%20%3D%3E%20null%29%3B%0A%0AfirstIfElse%28%27logging%20appears%20as%20expected%27%29%3B%0AunexpectedIfElse%28%27no%20logging%27%29%3B" rel="nofollow noreferrer">example in REPL

Body:
Your second function is a curried binary function.  ifElse chooses the maximum arity of the three functions passed to it, predicate, ifTrue, and ifFalse.  R.T has arity 1, as does () => null, but secTest has arity 2, so unexpectedIfElse also has arity 2.

When you call unexpectedIfElse with 'no logging', you get back a function waiting for the (useless) b parameter.

There are reasons not to like this additional complexity, but there are times when it's very useful, especially for the predicate.

You can fix your issue by calling it like

unexpectedIfElse('no logging', 'ignored');

or like

unexpectedIfElse('no logging')('ignored')


问:
AWS Lambda NodeJS - OAuth to Google API
I'm using my own gmail user to read a public calendar. Got program working locally, and displayed the credentials/token with console.log (value altered to protect my token):

```<code>Got Token
OAuth2Client {
  transporter: DefaultTransporter {},
  _certificateCache: null,
  _certificateExpiry: null,
  _clientId: 'xxxxxxxxxxxxxx',
  _clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  _redirectUri: 'urn:ietf:wg:oauth:2.0:oob',
  _opts: {},
  credentials:
   { access_token: 'xxxxxxx',
     refresh_token: 'xxxxxxxxxxxxxxxxxx',
     token_type: 'Bearer',
     expiry_date: 1512151860704 } }
</code>```

I also did what StackOverflow said: How to oAuth Google API from Lambda AWS? and it gave me the same access_token as displayed above.

So, if I understand, I need to take the access token and put it in my program or a file, and I'm not sure how to do that.  My code came from the Google example here:  https://developers.google.com/google-apps/calendar/quickstart/nodejs

Do I put this token somewhere in my client_secret.json file or what? I tried just passing it straight to the listEvents method as the value of TOKEN but got "400 Bad Request".

Update 1:
 I tried storing the file to disk and then reading it as follows:

```<code>exports.getCalendarJSONEventsNew =
  function getCalendarJSONEvents(callback) {
    console.log("started getCalendarJSONEventsNew");
    fs.readFile('OAuth2Client.json', 'utf8',
      function processedFile(err, content) {
          if (err) {
            console.log('Error loading OAuth2Client.json: ' + err);
            return;
          }

          console.log("content=");
          console.log(content);
          var tokenFromFile = JSON.parse(content);
          listEvents(tokenFromFile, function(jsonResult) {
                      console.log("Json Callback Events=");
                      console.log(jsonResult);
                      callback(jsonResult);
          });
    });

}
</code>```

Error: It doesn't seem to be exactly be JSON, so not how to deserialize it back into object:

```<code>OAuth2Client {
^

SyntaxError: Unexpected token O in JSON at position 0
</code>```

Update 2: Then I had another idea, I saved the following as

```<code>credentials: {
    access_token: 'xxxxx',
    refresh_token: 'xxxxxx',
    token_type: 'Bearer',
    expiry_date: 1512151860704
}
</code>```

as .credentials/calendar-nodejs-quickstart.json.

Then when I ran on the server, I got this response back:

```<code>Authorize this app by visiting this url: https://accounts.google.com/o/oauth2/auth?etc...
</code>```

答:
Here's how I got it to work so far.

1) Created a file called calendar-nodejs-quickstart.json in the root directory.
I kept getting errors when trying to read .credentials/calendar-nodejs-quickstart.json.  I tried setting the environment variables, but ended up changing sample code as follows:

```<code>var TOKEN_DIR = '.credentials/';
var TOKEN_PATH = 'calendar-nodejs-quickstart.json';
</code>```

2) Had to remove "credentials :" from the beginning of the file, and add the double quotes (and also changed single quotes to double quotes).  This was to get past various JSON parsing errors.
{
    "access_token": "xxxxx",
    "refresh_token": "xxxx",
    "token_type": "Bearer",
    "expiry_date": 1512151860704
}

3) I also added the 'utf8' below, and added some debug code to see what was going on:

```<code>  // Check if we have previously stored a token.
  console.log("TOKEN_PATH=" + TOKEN_PATH);
  fs.readFile(TOKEN_PATH, 'utf8', function(err, token) {
    if (err) {
      console.log("err=" + err);
      getNewToken(oauth2Client, callback);
    } else {
      console.log("Use stored tokens from " + TOKEN_PATH);
      console.log(token);
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
</code>```

Seems critical to me to show the value of the "err" variable.

Title: AWS Lambda NodeJS - OAuth to Google API

Body:
I'm using my own gmail user to read a public calendar. Got program working locally, and displayed the credentials/token with console.log (value altered to protect my token):

Got Token
OAuth2Client {
  transporter: DefaultTransporter {},
  _certificateCache: null,
  _certificateExpiry: null,
  _clientId: 'xxxxxxxxxxxxxx',
  _clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  _redirectUri: 'urn:ietf:wg:oauth:2.0:oob',
  _opts: {},
  credentials:
   { access_token: 'xxxxxxx',
     refresh_token: 'xxxxxxxxxxxxxxxxxx',
     token_type: 'Bearer',
     expiry_date: 1512151860704 } }

I also did what StackOverflow said: How to oAuth Google API from Lambda AWS? and it gave me the same access_token as displayed above.

So, if I understand, I need to take the access token and put it in my program or a file, and I'm not sure how to do that.  My code came from the Google example here:  https://developers.google.com/google-apps/calendar/quickstart/nodejs

Do I put this token somewhere in my client_secret.json file or what? I tried just passing it straight to the listEvents method as the value of TOKEN but got "400 Bad Request".

Update 1:
 I tried storing the file to disk and then reading it as follows:

exports.getCalendarJSONEventsNew =
  function getCalendarJSONEvents(callback) {
    console.log("started getCalendarJSONEventsNew");
    fs.readFile('OAuth2Client.json', 'utf8',
      function processedFile(err, content) {
          if (err) {
            console.log('Error loading OAuth2Client.json: ' + err);
            return;
          }

          console.log("content=");
          console.log(content);
          var tokenFromFile = JSON.parse(content);
          listEvents(tokenFromFile, function(jsonResult) {
                      console.log("Json Callback Events=");
                      console.log(jsonResult);
                      callback(jsonResult);
          });
    });

}

Error: It doesn't seem to be exactly be JSON, so not how to deserialize it back into object:

OAuth2Client {
^

SyntaxError: Unexpected token O in JSON at position 0

Update 2: Then I had another idea, I saved the following as

credentials: {
    access_token: 'xxxxx',
    refresh_token: 'xxxxxx',
    token_type: 'Bearer',
    expiry_date: 1512151860704
}

as .credentials/calendar-nodejs-quickstart.json.

Then when I ran on the server, I got this response back:

Authorize this app by visiting this url: https://accounts.google.com/o/oauth2/auth?etc...

Body:
Here's how I got it to work so far.

1) Created a file called calendar-nodejs-quickstart.json in the root directory.
I kept getting errors when trying to read .credentials/calendar-nodejs-quickstart.json.  I tried setting the environment variables, but ended up changing sample code as follows:

var TOKEN_DIR = '.credentials/';
var TOKEN_PATH = 'calendar-nodejs-quickstart.json';

2) Had to remove "credentials :" from the beginning of the file, and add the double quotes (and also changed single quotes to double quotes).  This was to get past various JSON parsing errors.
{
    "access_token": "xxxxx",
    "refresh_token": "xxxx",
    "token_type": "Bearer",
    "expiry_date": 1512151860704
}

3) I also added the 'utf8' below, and added some debug code to see what was going on:

  // Check if we have previously stored a token.
  console.log("TOKEN_PATH=" + TOKEN_PATH);
  fs.readFile(TOKEN_PATH, 'utf8', function(err, token) {
    if (err) {
      console.log("err=" + err);
      getNewToken(oauth2Client, callback);
    } else {
      console.log("Use stored tokens from " + TOKEN_PATH);
      console.log(token);
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });

Seems critical to me to show the value of the "err" variable.


问:
Do yarn workspaces work with npm, too?
I checked out a repo which uses yarn instead of npm as build tool.

in the package.json, it defines workspaces to deal with multiple sub-projects:

```<code>{
  "workspaces": [
    "packages/*"
  ],
  "dependencies": [],
  "devDependencies": [
    // long list
  ]
}
</code>```

As a result, the root package.json does not contain any runtime dependency. Just the packages/*/package.json contain those.

To compile (and start in dev mode) I do:

```<code>yarn install
yarn start
</code>```

I have found no documentation, that workspaces is also recognized and correctly used by npm.

Is there a way to make it work with npm, too?

答:
Managing dependencies in a monorepo is not supported with npm.  The Lerna package is used to manage JavaScript projects with cross dependencies.  I believe Lerna uses Yarn under the hood, but with Yarn as your project's package manager, this feature is supported out of the box.

Here is a repo that might be helpful to see how Yarn and Lerna work together: https://github.com/Quramy/lerna-yarn-workspaces-example

Title: Do yarn workspaces work with npm, too?

Body:
I checked out a repo which uses yarn instead of npm as build tool.

in the package.json, it defines workspaces to deal with multiple sub-projects:

{
  "workspaces": [
    "packages/*"
  ],
  "dependencies": [],
  "devDependencies": [
    // long list
  ]
}

As a result, the root package.json does not contain any runtime dependency. Just the packages/*/package.json contain those.

To compile (and start in dev mode) I do:

yarn install
yarn start

I have found no documentation, that workspaces is also recognized and correctly used by npm.

Is there a way to make it work with npm, too?


问:
Function only returning first letter capitalised
I have a function that is meant to do this:

```<code>accum("abcd");    // "A-Bb-Ccc-Dddd"
accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
</code>```

We can see the first "for" loop repeats each substring by it's current (index + 1). It pushes it to the array and the output would be [ 'a', 'bb', 'ccc', 'dddd' ]

It is then obvious that I need to iterate over this array and capitalise each string which I have done by the second for loop below.
The problem is when I return the array it is returning like this: [ 'A', 'B', 'C', 'D' ]

It is returning the first substring of each string but it isn't returning the rest of them.

```<code>function accum(s) {
    var splitstring = s.split("")
    var newarray = []
    for(var i = 0; i < splitstring.length; i++) {
        newarray.push(splitstring[i].repeat(i + 1))
    }
    for (var i = 0; i < newarray.length; i++) {
        newarray[i]  = newarray[i].charAt(0).toUpperCase()
    }
    return newarray
}
accum("abcd")
</code>```

答:
That's because you're overwriting the string with only the first character. you need to concatenate the rest of the string.

```<code>  for (var i = 0; i < newarray.length; i++) {
    newarray[i]  = newarray[i].charAt(0).toUpperCase() + newarray[i].slice(1);
  }
</code>```

Here's a shorter version of your code:

function accum(s) {
  return s.split("").map((ss, i) => ss.toUpperCase() + ss.repeat(i)).join("-");
}

console.log(accum("abcd"));```

It also adds the separator that you seem to want. If you actually wanted the array, then remove .join("-").

Body:
I have a function that is meant to do this:

accum("abcd");    // "A-Bb-Ccc-Dddd"
accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"

We can see the first "for" loop repeats each substring by it's current (index + 1). It pushes it to the array and the output would be [ 'a', 'bb', 'ccc', 'dddd' ]

It is then obvious that I need to iterate over this array and capitalise each string which I have done by the second for loop below.
The problem is when I return the array it is returning like this: [ 'A', 'B', 'C', 'D' ]

It is returning the first substring of each string but it isn't returning the rest of them.

function accum(s) {
    var splitstring = s.split("")
    var newarray = []
    for(var i = 0; i < splitstring.length; i++) {
        newarray.push(splitstring[i].repeat(i + 1))
    }
    for (var i = 0; i < newarray.length; i++) {
        newarray[i]  = newarray[i].charAt(0).toUpperCase()
    }
    return newarray
}
accum("abcd")

Body:
That's because you're overwriting the string with only the first character. you need to concatenate the rest of the string.

  for (var i = 0; i < newarray.length; i++) {
    newarray[i]  = newarray[i].charAt(0).toUpperCase() + newarray[i].slice(1);
  }

Here's a shorter version of your code:

function accum(s) {
  return s.split("").map((ss, i) => ss.toUpperCase() + ss.repeat(i)).join("-");
}

console.log(accum("abcd"));

It also adds the separator that you seem to want. If you actually wanted the array, then remove .join("-").


问:
Add a JIRA link to karate/cucumber report
While using Serenity with JBehave addition of @Title renders a link to JIRA.

Is there a way to add a Meta @issue #<jira number>?

The other way could be integrating the existing Serenity @Title as a gherkin syntax dsl with Karate?

Before I get on this path, wanted to know if there is an inbuilt way which I might have overlooked.

答:
Dev of Karate here. I guess you mean the cucumber-reports-plugin.

First: I have never experimented with rendering links, but it looks doable, for e.g refer to this thread: https://github.com/damianszczepanik/cucumber-reporting/issues/610

Second: Karate has enhanced cucumber tags so that name-value-pairs are supported, so even within a test you would be able to grab the value of a tag, here is an example: tags.feature.

In current state of Karate you can certainly get the value of the tag and generate a hyperlink. Rendering a hyperlink into the HTML report may need some digging.


问:
How do I remove the italics on the words in my navigation bar?
On all the other pages of the website the navigation bar is in normal font but for some reason the font on the home page nav bar is in italics. I've completely forgotten how to make it so it doesn't have italics or where to search to change it so please help

http://surbaisse.com/index.html

```<code>#tabsJ {
  float:left;
  width:100%;
  background:#F4F4F4;
  font-size:93%;
  line-height:normal;
      border-bottom:1px solid #24618E;
  }
#tabsJ ul {
    margin:0;
    padding:10px 10px 0 50px;
    list-style:none;
    text-align: center;
  }
#tabsJ li {
  display:inline-block;
  margin:0;
  padding:0;
  }
#tabsJ li a:hover {
  background color: #111
  }
#tabsJ a {
  float:left;
  background:url(file:///C|/Users/xw4600/Documents/Bugatti Dave/tableftJ.gif) no-repeat left top;
  margin:0;
  padding:0 0 0 5px;
  text-decoration:none;
  }
#tabsJ a span {
  float:left;
  display:block;
  background:url(file:///C|/Users/xw4600/Documents/Bugatti Dave/tabrightJ.gif) no-repeat right top;
  padding:5px 15px 4px 6px;
  color:#24618E;
  }
/* Commented Backslash Hack hides rule from IE5-Mac \*/
#tabsJ a span {float:none;}
/* End IE5-Mac hack */
#tabsJ a:hover span {
  color:#FFF;
  }
#tabsJ a:hover {
  background-position:0% -42px;
  }
#tabsJ a:hover span {
  background-position:100% -42px;
  }

    #tabsJ #current a {
            background-position:0% -42px;
    }
    #tabsJ #current a span {
            background-position:100% -42px;
            color:#FFF;
    }
</code>```

答:
After reviewing your site, the reason the text is in italics is because you put it in an  tag. As you can see on w3schools,  makes any string between it's opening and closing tags emphasized, making them appear as italics.

Remove the 3 em blocks from under #Layer3.

Also, and please, don't take this the wrong way, but your HTML-structure is horrible. Please, consider rebuilding your site's structure so it will be easier to maintain in the future.

For example, em is an inline type element, while div is a block type element. Putting block elements in inline ones, while not impossible, should be avoided. It makes building maintainable structure and sane CSS harder, and only leads to headache, tears and swearing in the future.

Body:
On all the other pages of the website the navigation bar is in normal font but for some reason the font on the home page nav bar is in italics. I've completely forgotten how to make it so it doesn't have italics or where to search to change it so please help

http://surbaisse.com/index.html

#tabsJ {
  float:left;
  width:100%;
  background:#F4F4F4;
  font-size:93%;
  line-height:normal;
      border-bottom:1px solid #24618E;
  }
#tabsJ ul {
    margin:0;
    padding:10px 10px 0 50px;
    list-style:none;
    text-align: center;
  }
#tabsJ li {
  display:inline-block;
  margin:0;
  padding:0;
  }
#tabsJ li a:hover {
  background color: #111
  }
#tabsJ a {
  float:left;
  background:url(file:///C|/Users/xw4600/Documents/Bugatti Dave/tableftJ.gif) no-repeat left top;
  margin:0;
  padding:0 0 0 5px;
  text-decoration:none;
  }
#tabsJ a span {
  float:left;
  display:block;
  background:url(file:///C|/Users/xw4600/Documents/Bugatti Dave/tabrightJ.gif) no-repeat right top;
  padding:5px 15px 4px 6px;
  color:#24618E;
  }
/* Commented Backslash Hack hides rule from IE5-Mac \*/
#tabsJ a span {float:none;}
/* End IE5-Mac hack */
#tabsJ a:hover span {
  color:#FFF;
  }
#tabsJ a:hover {
  background-position:0% -42px;
  }
#tabsJ a:hover span {
  background-position:100% -42px;
  }

    #tabsJ #current a {
            background-position:0% -42px;
    }
    #tabsJ #current a span {
            background-position:100% -42px;
            color:#FFF;
    }

Body:
After reviewing your site, the reason the text is in italics is because you put it in an <em> tag. As you can see on w3schools, <em> makes any string between it's opening and closing tags emphasized, making them appear as italics.

Remove the 3 em blocks from under #Layer3.

Also, and please, don't take this the wrong way, but your HTML-structure is horrible. Please, consider rebuilding your site's structure so it will be easier to maintain in the future.

For example, em is an inline type element, while div is a block type element. Putting block elements in inline ones, while not impossible, should be avoided. It makes building maintainable structure and sane CSS harder, and only leads to headache, tears and swearing in the future.


问:
Java regex for HTML "<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> " parsing
I am new to regexps, can someone help me in getting a regex for parsing the tag

```<code><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</code>```

with all the possiblities?

答:
To cover "all the possibilities", you really should be using HTML 5's Determining the character encoding rules. These aren't expressible as a regular expression.

There is an open source Java implementation of it in validator.nu

If you insist on using a regular expression, then this will probably cover most cases where the encoding it declared with a meta element (it won't, for instance, cover XML declarations). It is however, dirty, makes some assumptions that are usually (but may not always be) right and I do not recommend it.

```<code>/<meta[^>]+charset=['"]?(.*?)['"]?[\/\s>]/i
</code>```

Body:
I am new to regexps, can someone help me in getting a regex for parsing the tag

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

with all the possiblities?

Body:
To cover "all the possibilities", you really should be using HTML 5's Determining the character encoding rules. These aren't expressible as a regular expression.

There is an open source Java implementation of it in validator.nu

If you insist on using a regular expression, then this will probably cover most cases where the encoding it declared with a meta element (it won't, for instance, cover XML declarations). It is however, dirty, makes some assumptions that are usually (but may not always be) right and I do not recommend it.

/<meta[^>]+charset=['"]?(.*?)['"]?[\/\s>]/i


问:
ValueError: Feature not in features dictionary
I am attempting to write a simple deep machine learning model using TensorFlow.
I'm using a toy dataset I made up in Excel just to get the model working and accepting data. My code is as follows:

```<code>import pandas as pd
import numpy as np
import tensorflow as tf

raw_data = np.genfromtxt('ai/mock-data.csv', delimiter=',', dtype=str)
my_data = np.delete(raw_data, (0), axis=0) #deletes the first row, axis=0 indicates row, axis=1 indicates column
my_data = np.delete(my_data, (0), axis=1) #deletes the first column

policy_state = tf.feature_column.categorical_column_with_vocabulary_list('policy_state', [
    'AL', 'CA', 'MI'
])

modern_classic_ind = tf.feature_column.categorical_column_with_vocabulary_list('modern_classic_ind', [
    '0', '1'
])

h_plus_ind = tf.feature_column.categorical_column_with_vocabulary_list('h_plus_ind', [
    '0', '1'
])

retention_ind = tf.feature_column.categorical_column_with_vocabulary_list('retention_ind', [
    '0', '1'
])

feature_columns = [
    tf.feature_column.indicator_column(policy_state),
    tf.feature_column.indicator_column(modern_classic_ind),
    tf.feature_column.indicator_column(h_plus_ind)
]
classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns,
                                      hidden_units=[10, 20, 10],
                                      n_classes=3,
                                      model_dir="/tmp/ret_model")

train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(my_data[:, 0:3], dtype=str)},
y=np.array(np.array(my_data[:, 3], dtype=str)),
num_epochs=None,
shuffle=True)

classifier.train(input_fn=train_input_fn, steps=2000)
</code>```

Unfortunately, I am getting the following error. I have tried trimming the labels off the csv file versus leaving them, naming the feature columns different things, and changing the type of the numpy array. The error persists.

ValueError: Feature h_plus_ind is not in features dictionary.

If I remove h_plus_ind, it simply throws the error on a different column.

答:
When using tf.feature_columns, the data you feed in your input_fn should have the same keys as the feature columns previously created.
So, the x of your train_input_fn should be a dictionary, with keys named after the feature_columns.

A mock example :

```<code>x = {"policy_state": np.array(['AL','AL','AL','AL','AL']),
     "modern_classic_ind": np.array(['0','0','0','0','0']),
     "h_plus_ind": np.array(['0','0','0','0','0']),}
</code>```

Body:
I am attempting to write a simple deep machine learning model using TensorFlow.
I'm using a toy dataset I made up in Excel just to get the model working and accepting data. My code is as follows:

import pandas as pd
import numpy as np
import tensorflow as tf

raw_data = np.genfromtxt('ai/mock-data.csv', delimiter=',', dtype=str)
my_data = np.delete(raw_data, (0), axis=0) #deletes the first row, axis=0 indicates row, axis=1 indicates column
my_data = np.delete(my_data, (0), axis=1) #deletes the first column

policy_state = tf.feature_column.categorical_column_with_vocabulary_list('policy_state', [
    'AL', 'CA', 'MI'
])

modern_classic_ind = tf.feature_column.categorical_column_with_vocabulary_list('modern_classic_ind', [
    '0', '1'
])

h_plus_ind = tf.feature_column.categorical_column_with_vocabulary_list('h_plus_ind', [
    '0', '1'
])

retention_ind = tf.feature_column.categorical_column_with_vocabulary_list('retention_ind', [
    '0', '1'
])

feature_columns = [
    tf.feature_column.indicator_column(policy_state),
    tf.feature_column.indicator_column(modern_classic_ind),
    tf.feature_column.indicator_column(h_plus_ind)
]
classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns,
                                      hidden_units=[10, 20, 10],
                                      n_classes=3,
                                      model_dir="/tmp/ret_model")

train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(my_data[:, 0:3], dtype=str)},
y=np.array(np.array(my_data[:, 3], dtype=str)),
num_epochs=None,
shuffle=True)

classifier.train(input_fn=train_input_fn, steps=2000)

Unfortunately, I am getting the following error. I have tried trimming the labels off the csv file versus leaving them, naming the feature columns different things, and changing the type of the numpy array. The error persists.

ValueError: Feature h_plus_ind is not in features dictionary.

If I remove h_plus_ind, it simply throws the error on a different column.

Body:
When using tf.feature_columns, the data you feed in your input_fn should have the same keys as the feature columns previously created.
So, the x of your train_input_fn should be a dictionary, with keys named after the feature_columns.

A mock example :

x = {"policy_state": np.array(['AL','AL','AL','AL','AL']),
     "modern_classic_ind": np.array(['0','0','0','0','0']),
     "h_plus_ind": np.array(['0','0','0','0','0']),}

ContentLicense: CC BY-SA 4.0


问:
Issue with Sorting and Filtering on WPF DataGrid
I'm having some issues trying to get a filter box, which is added to the header of a datagrid column through styling, working. When I do not sort the column everything is working fine, no issues there, but the moment I sort, I don't see what's typed anymore and I can only filter on one char (can't clear the filter either as there're no characters to delete and trigger the TextChanged event).

What's also odd is that the TextBox is nowhere to be found in the visual tree, starting from the DataGridColumnHeader instance, when the column is sorted. If I could find it, I could reset the text at the end of the cycle and the issue would probably be solved.

Visually it looks like this, I typed a "P" in all 3 cases:

The relevant styling that's behind this is the following:

```<code><Page.Resources>
    <Style x:Key="Filter" TargetType="TextBox">
        <EventSetter Event="TextChanged" Handler="Filter_TextBox_TextChanged"/>
    </Style>
    <Style TargetType="{x:Type DataGrid}">
        <!-- Some visual styling like margins and colors on the grid -->
        <Style.Resources>
            <Style TargetType="{x:Type DataGridColumnHeader}">
                <!-- Some visual styling like margins and colors on the header -->
                <Setter Property="ContentTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <StackPanel>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"/>
                                        <RowDefinition Height="Auto"/>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*"/>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="Auto"/>
                                    </Grid.ColumnDefinitions>
                                    <TextBlock Grid.Column="0" Grid.Row="0" Margin="10,0,10,0" TextWrapping="WrapWithOverflow" Text="{Binding}"/>
                                    <fa:FontAwesome Grid.Column="1" Grid.Row="0"  Icon="LongArrowUp" Foreground="#dbdbdb" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
                                    <fa:FontAwesome Grid.Column="2" Grid.Row="0" Margin="0,0,10,0" Icon="LongArrowDown" Foreground="#dbdbdb" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
                                    <StackPanel Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="1" Margin="0,10,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Background="#dbdbdb">
                                        <TextBox Style="{StaticResource Filter}" />
                                    </StackPanel>
                                </Grid>
                            </StackPanel>
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <Trigger Property="SortDirection" Value="Ascending">
                        <Setter Property="Background" Value="#F0F0F0"/>
                        <Setter Property="ContentTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <StackPanel>
                                        <Grid>
                                            <Grid.RowDefinitions>
                                                <RowDefinition Height="Auto"/>
                                                <RowDefinition Height="Auto"/>
                                            </Grid.RowDefinitions>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="*"/>
                                                <ColumnDefinition Width="Auto"/>
                                            </Grid.ColumnDefinitions>
                                            <TextBlock Grid.Column="0" Grid.Row="0" Margin="5,0,10,0" TextWrapping="WrapWithOverflow" Text="{Binding}"/>
                                            <fa:FontAwesome Grid.Column="1" Grid.Row="0" Margin="0,0,10,0" Icon="SortAmountAsc" Foreground="#919191" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
                                            <StackPanel Grid.Column="0" Grid.ColumnSpan="3" Margin="0,10,0,0" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="#dbdbdb">
                                                <TextBox Style="{StaticResource Filter}" />
                                            </StackPanel>
                                        </Grid>
                                    </StackPanel>
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                    <Trigger Property="SortDirection" Value="Descending">
                        <Setter Property="Background" Value="#F0F0F0"/>
                        <Setter Property="ContentTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <StackPanel>
                                        <Grid>
                                            <Grid.RowDefinitions>
                                                <RowDefinition Height="Auto"/>
                                                <RowDefinition Height="Auto"/>
                                            </Grid.RowDefinitions>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="*"/>
                                                <ColumnDefinition Width="Auto"/>
                                            </Grid.ColumnDefinitions>
                                            <TextBlock Grid.Row="0" Grid.Column="0" Margin="5,0,10,0" TextWrapping="WrapWithOverflow" Text="{Binding}"/>
                                            <fa:FontAwesome Grid.Row="0" Grid.Column="1" Margin="0,0,10,0" Icon="SortAmountDesc" Foreground="#919191" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
                                            <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" Margin="0,10,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="#dbdbdb">
                                                <TextBox Style="{StaticResource Filter}" />
                                            </StackPanel>
                                        </Grid>
                                    </StackPanel>
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
</code>```

Nothing special in the definition of the DataGrid:

```<code><DataGrid x:Name="History_DataGrid" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" HeadersVisibility="Column" GridLinesVisibility="None" ItemsSource="{Binding history}" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" SelectionMode="Single" SelectionUnit="FullRow" CanUserAddRows="false" SelectionChanged="History_DataGrid_SelectionChanged" Sorting="History_DataGrid_Sorting">
        <DataGrid.Columns>
            <DataGridTextColumn Header="{x:Static resx:Resources.Product}" Binding="{Binding Path=Product}" Width="*" ElementStyle="{StaticResource Wrap}" />
            <DataGridTextColumn Header="{x:Static resx:Resources.Label}" Binding="{Binding Path=Label}" Width="*" ElementStyle="{StaticResource Wrap}" />
            <DataGridTextColumn Header="{x:Static resx:Resources.Color}" Binding="{Binding Path=Color}" Width="*" ElementStyle="{StaticResource Wrap}" />
            <DataGridTextColumn Header="{x:Static resx:Resources.Volume}" Binding="{Binding Path=Volume}" Width="Auto" ElementStyle="{StaticResource Wrap}" />
            <DataGridTextColumn Header="{x:Static resx:Resources.LastPrinted}" Binding="{Binding Path=LastPrinted, StringFormat=\{0:yyyy-MM-dd\}}" Width="Auto" ElementStyle="{StaticResource Wrap}" />
            <DataGridTextColumn Header="{x:Static resx:Resources.TimesPrinted}" Binding="{Binding Path=TimesPrinted}" Width="Auto" ElementStyle="{StaticResource Wrap}" />
        </DataGrid.Columns>
    </DataGrid>
</code>```

Possible ways to bypass the issue, though I have no idea how to accomplish them:

Create a second header row with the filter boxes that doesn't changes
after sorting.

Setting the value of the filter textbox at the end of
the event cycle, I have a function where I prepare the paging
controls that is triggered after the datagrid is rebound, though I
need to be able to access the textbox instances for that. I can if
it's unsorted, but I can't find the box when the colums is sorted.

Any idea how to get this fixed, it's really a breaking issue and none of the search results have come up with anything usefull.

EDIT: Some scenarios for clarification

How it should work and how it works as long as I don't sort:

I type 'A' in the textbox.

The source of the datagrid is filtered on the the text "A" and rebound.

The textbox shows "A" as the filter.

I type 'B' in the textbox.

The source of the datagrid is filtered on the the text "AB" and rebound.

The textbox shows "AB" as the filter.

When the column is sorted, it behaves quite differently:

I sort the column and it loses the text that was already in the textbox.

I type 'A' in the textbox.

The source of the datagrid is filtered on the the text "A" and rebound.

The textbox stays empty and does not show "A" as the filter.

I type 'B' in the textbox.

The source of the datagrid is filtered on the the text "B", not "AB" (it lost the "A"), and rebound.

The textbox stays empty and does not show "A", "B" or "AB" as the filter.

As a result removing the filter is quite hard as well as there's no text to delete and trigger the TextChanged event.

答:
I got into contact with some WPF specialists in my company and they helped me reach a workable solution.

The edited Style looks as followed:

```<code><Page.Resources>
<Style x:Key="Filter" TargetType="TextBox">
    <EventSetter Event="TextChanged" Handler="Filter_TextBox_TextChanged"/>
</Style>
<Style TargetType="{x:Type DataGrid}">
    <!-- Some visual styling like margins and colors on the grid -->
    <Style.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}">
            <!-- Some visual styling like margins and colors on the header -->
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition Height="Auto"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="Auto"/>
                                    <ColumnDefinition Width="Auto"/>
                                </Grid.ColumnDefinitions>
                                <TextBlock Grid.Column="0" Grid.Row="0" Margin="10,0,10,0" TextWrapping="WrapWithOverflow" Text="{Binding}"/>
                                    <fa:FontAwesome Grid.Column="1" Grid.Row="0" x:Name="SortIcon1" Icon="LongArrowUp" Foreground="#dbdbdb" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
                                    <fa:FontAwesome Grid.Column="2" Grid.Row="0" x:Name="SortIcon2" Margin="0,0,10,0" Icon="LongArrowDown" Foreground="#dbdbdb" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
                                <StackPanel Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="1" Margin="0,10,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Background="#dbdbdb">
                                    <TextBox Style="{StaticResource Filter}" />
                                </StackPanel>
                            </Grid>
                        </StackPanel>
                        <DataTemplate.Triggers>
                            <DataTrigger Binding="{Binding SortDirection, RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}}" Value="Ascending">
                                <Setter TargetName="SortIcon1" Property="Icon" Value="SortAmountAsc" />
                                <Setter TargetName="SortIcon2" Property="Visibility" Value="Hidden" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding SortDirection, RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}}" Value="Descending">
                                <Setter TargetName="SortIcon1" Property="Icon" Value="SortAmountDesc" />
                                <Setter TargetName="SortIcon2" Property="Visibility" Value="Hidden" />
                            </DataTrigger>
                        </DataTemplate.Triggers>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="SortDirection" Value="Ascending">
                    <Setter Property="Background" Value="#F0F0F0"/>
                </Trigger>
                <Trigger Property="SortDirection" Value="Descending">
                    <Setter Property="Background" Value="#F0F0F0"/>
                </Trigger>
            </Style.Triggers>
        </Style>
</code>```

Basically my main mistake was to have a DataTemplate per sort state. They pointed out that I could add a trigger to the Datatemplate bound to the Header's event. Adding a name to my sort icons made me able to change them with the TargetName attribute in the new trigger sections.

As there's now only one instance of the textbox, the issue is resolved.

Body:
I'm having some issues trying to get a filter box, which is added to the header of a datagrid column through styling, working. When I do not sort the column everything is working fine, no issues there, but the moment I sort, I don't see what's typed anymore and I can only filter on one char (can't clear the filter either as there're no characters to delete and trigger the TextChanged event).

What's also odd is that the TextBox is nowhere to be found in the visual tree, starting from the DataGridColumnHeader instance, when the column is sorted. If I could find it, I could reset the text at the end of the cycle and the issue would probably be solved.

Visually it looks like this, I typed a "P" in all 3 cases:

The relevant styling that's behind this is the following:

<Page.Resources>

            </Style>

Nothing special in the definition of the DataGrid:

<DataGrid x:Name="History_DataGrid" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" HeadersVisibility="Column" GridLinesVisibility="None" ItemsSource="{Binding history}" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" SelectionMode="Single" SelectionUnit="FullRow" CanUserAddRows="false" SelectionChanged="History_DataGrid_SelectionChanged" Sorting="History_DataGrid_Sorting">
        <DataGrid.Columns>
            <DataGridTextColumn Header="{x:Static resx:Resources.Product}" Binding="{Binding Path=Product}" Width="*" ElementStyle="{StaticResource Wrap}" />
            <DataGridTextColumn Header="{x:Static resx:Resources.Label}" Binding="{Binding Path=Label}" Width="*" ElementStyle="{StaticResource Wrap}" />
            <DataGridTextColumn Header="{x:Static resx:Resources.Color}" Binding="{Binding Path=Color}" Width="*" ElementStyle="{StaticResource Wrap}" />
            <DataGridTextColumn Header="{x:Static resx:Resources.Volume}" Binding="{Binding Path=Volume}" Width="Auto" ElementStyle="{StaticResource Wrap}" />
            <DataGridTextColumn Header="{x:Static resx:Resources.LastPrinted}" Binding="{Binding Path=LastPrinted, StringFormat=\{0:yyyy-MM-dd\}}" Width="Auto" ElementStyle="{StaticResource Wrap}" />
            <DataGridTextColumn Header="{x:Static resx:Resources.TimesPrinted}" Binding="{Binding Path=TimesPrinted}" Width="Auto" ElementStyle="{StaticResource Wrap}" />
        </DataGrid.Columns>
    </DataGrid>

Possible ways to bypass the issue, though I have no idea how to accomplish them:

Create a second header row with the filter boxes that doesn't changes
after sorting.

Setting the value of the filter textbox at the end of
the event cycle, I have a function where I prepare the paging
controls that is triggered after the datagrid is rebound, though I
need to be able to access the textbox instances for that. I can if
it's unsorted, but I can't find the box when the colums is sorted.

Any idea how to get this fixed, it's really a breaking issue and none of the search results have come up with anything usefull.

EDIT: Some scenarios for clarification

How it should work and how it works as long as I don't sort:

I type 'A' in the textbox.

The source of the datagrid is filtered on the the text "A" and rebound.

The textbox shows "A" as the filter.

I type 'B' in the textbox.

The source of the datagrid is filtered on the the text "AB" and rebound.

The textbox shows "AB" as the filter.

When the column is sorted, it behaves quite differently:

I sort the column and it loses the text that was already in the textbox.

I type 'A' in the textbox.

The source of the datagrid is filtered on the the text "A" and rebound.

The textbox stays empty and does not show "A" as the filter.

I type 'B' in the textbox.

The source of the datagrid is filtered on the the text "B", not "AB" (it lost the "A"), and rebound.

The textbox stays empty and does not show "A", "B" or "AB" as the filter.

As a result removing the filter is quite hard as well as there's no text to delete and trigger the TextChanged event.

Body:
I got into contact with some WPF specialists in my company and they helped me reach a workable solution.

The edited Style looks as followed:

<Page.Resources>
<Style x:Key="Filter" TargetType="TextBox">
    <EventSetter Event="TextChanged" Handler="Filter_TextBox_TextChanged"/>
</Style>
<Style TargetType="{x:Type DataGrid}">
    <!-- Some visual styling like margins and colors on the grid -->
    <Style.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}">
            <!-- Some visual styling like margins and colors on the header -->
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel>
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition Height="Auto"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="Auto"/>
                                    <ColumnDefinition Width="Auto"/>
                                </Grid.ColumnDefinitions>
                                <TextBlock Grid.Column="0" Grid.Row="0" Margin="10,0,10,0" TextWrapping="WrapWithOverflow" Text="{Binding}"/>
                                    <fa:FontAwesome Grid.Column="1" Grid.Row="0" x:Name="SortIcon1" Icon="LongArrowUp" Foreground="#dbdbdb" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
                                    <fa:FontAwesome Grid.Column="2" Grid.Row="0" x:Name="SortIcon2" Margin="0,0,10,0" Icon="LongArrowDown" Foreground="#dbdbdb" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
                                <StackPanel Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="1" Margin="0,10,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Background="#dbdbdb">
                                    <TextBox Style="{StaticResource Filter}" />
                                </StackPanel>
                            </Grid>
                        </StackPanel>
                        <DataTemplate.Triggers>
                            <DataTrigger Binding="{Binding SortDirection, RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}}" Value="Ascending">
                                <Setter TargetName="SortIcon1" Property="Icon" Value="SortAmountAsc" />
                                <Setter TargetName="SortIcon2" Property="Visibility" Value="Hidden" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding SortDirection, RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}}" Value="Descending">
                                <Setter TargetName="SortIcon1" Property="Icon" Value="SortAmountDesc" />
                                <Setter TargetName="SortIcon2" Property="Visibility" Value="Hidden" />
                            </DataTrigger>
                        </DataTemplate.Triggers>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="SortDirection" Value="Ascending">
                    <Setter Property="Background" Value="#F0F0F0"/>
                </Trigger>
                <Trigger Property="SortDirection" Value="Descending">
                    <Setter Property="Background" Value="#F0F0F0"/>
                </Trigger>
            </Style.Triggers>
        </Style>

Basically my main mistake was to have a DataTemplate per sort state. They pointed out that I could add a trigger to the Datatemplate bound to the Header's event. Adding a name to my sort icons made me able to change them with the TargetName attribute in the new trigger sections.

As there's now only one instance of the textbox, the issue is resolved.


问:
Common Lisp: Optimizing functions in SBCL
For 2D graphics I need to optimize my functions, but in SBCL I get lots of comments about SBCL not being able to inline arithmetic operations. I tried all sorts of declarations but it doesn't seem to make the compiler happy. Here is a simple example:

```<code>(defun test-floor (x div)
  (declare (type single-float x)
           (type (signed-byte 64) div)
           (optimize (speed 3)))
  (floor x div))
</code>```

gives the following 4 notes below. I'm completely lost as #'floor is a builtin function. I tried to find information/tutorials on how to properly give the compiler hints in SBCL and didn't find the right information, so any info would be very appreciated! Unfortunately optimization in Common Lisp is quite unknown territory for me. I'm using SBCL 1.3.20 on a Linux machine.

```<code>; file: /tmp/file595dqU
; in: defun test-floor
;     (FLOOR CL-FLOCKS::X CL-FLOCKS::DIV)
; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL TRUNCATE LET*
; ==>
;   (SB-KERNEL:%UNARY-TRUNCATE/SINGLE-FLOAT (/ SB-C::X SB-C::F))
;
; note: forced to do full call
;       unable to do inline float truncate (cost 5) because:
;       The result is a (values integer &optional), not a (values
;                                                          (signed-byte 64) &rest
;                                                          t).

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL TRUNCATE LET* VALUES - *
; ==>
;   (SB-KERNEL:%SINGLE-FLOAT SB-C::RES)
;
; note: forced to do full call
;       unable to do inline float coercion (cost 5) because:
;       The first argument is a integer, not a (signed-byte 64).

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL FUNCTION IF VALUES 1-
; ==>
;   (- SB-C::TRU 1)
;
; note: forced to do generic-- (cost 10)
;       unable to do inline fixnum arithmetic (cost 1) because:
;       The first argument is a integer, not a fixnum.
;       The result is a (values integer &optional), not a (values fixnum &rest t).
;       unable to do inline fixnum arithmetic (cost 2) because:
;       The first argument is a integer, not a fixnum.
;       The result is a (values integer &optional), not a (values fixnum &rest t).
;       etc.

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL FUNCTION IF VALUES
; ==>
;   (+ REM SB-C::DIVISOR)
;
; note: doing signed word to integer coercion (cost 20) from div, for:
;       the second argument of generic-+
;
; compilation unit finished
;   printed 4 notes

CL-USER>
</code>```

答:
If you want to specify the return value of an expression you can use THE:

```<code>(the fixnum (1+ 3))
</code>```

But you really want to make sure that the value is actually a fixnum. If you 'lie', then Lisp may believe you and you have unspecified runtime effects. SBCL may warn at compile time, but you really should take care of that. If you provide wrong types are return wrong types, data may get corrupted and/or Lisp may crash.

Another way to specify a return value is the FTYPE declaration:

For example a function ith may take an integer and a list as arguments. It returns an arbitrary type -> T or any subtype.

```<code>(declaim (ftype (function (integer list) t)
                ith))
</code>```

For example:

```<code>(the fixnum (+ (the fixnum a) (the fixnum b)))
</code>```

There you need to be sure that:

a is an fixnum

b is an fixnum

the sum of a and b is also always a fixnum

Here this is easier, since the sum of a and b is definitely a fixnum:

```<code>CL-USER 3 > (let ((a 3) (b 12))
              (the fixnum (+ (the (integer 0 10) a)
                             (the (integer 3 20) b))))
15
</code>```

Lisp may check that at runtime and/or compile-time. The addition now can be a simple fixnum operation and does not need to deal with fixnum overflows and bignums. If you set the safety value to something low, then the runtime check may also be omitted. But: you should never call this code with the wrong types.

Body:
For 2D graphics I need to optimize my functions, but in SBCL I get lots of comments about SBCL not being able to inline arithmetic operations. I tried all sorts of declarations but it doesn't seem to make the compiler happy. Here is a simple example:

(defun test-floor (x div)
  (declare (type single-float x)
           (type (signed-byte 64) div)
           (optimize (speed 3)))
  (floor x div))

gives the following 4 notes below. I'm completely lost as #'floor is a builtin function. I tried to find information/tutorials on how to properly give the compiler hints in SBCL and didn't find the right information, so any info would be very appreciated! Unfortunately optimization in Common Lisp is quite unknown territory for me. I'm using SBCL 1.3.20 on a Linux machine.

; file: /tmp/file595dqU
; in: defun test-floor
;     (FLOOR CL-FLOCKS::X CL-FLOCKS::DIV)
; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL TRUNCATE LET*
; ==>
;   (SB-KERNEL:%UNARY-TRUNCATE/SINGLE-FLOAT (/ SB-C::X SB-C::F))
;
; note: forced to do full call
;       unable to do inline float truncate (cost 5) because:
;       The result is a (values integer &optional), not a (values
;                                                          (signed-byte 64) &rest
;                                                          t).

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL TRUNCATE LET* VALUES - *
; ==>
;   (SB-KERNEL:%SINGLE-FLOAT SB-C::RES)
;
; note: forced to do full call
;       unable to do inline float coercion (cost 5) because:
;       The first argument is a integer, not a (signed-byte 64).

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL FUNCTION IF VALUES 1-
; ==>
;   (- SB-C::TRU 1)
;
; note: forced to do generic-- (cost 10)
;       unable to do inline fixnum arithmetic (cost 1) because:
;       The first argument is a integer, not a fixnum.
;       The result is a (values integer &optional), not a (values fixnum &rest t).
;       unable to do inline fixnum arithmetic (cost 2) because:
;       The first argument is a integer, not a fixnum.
;       The result is a (values integer &optional), not a (values fixnum &rest t).
;       etc.

; --> MULTIPLE-VALUE-BIND MULTIPLE-VALUE-CALL FUNCTION IF VALUES
; ==>
;   (+ REM SB-C::DIVISOR)
;
; note: doing signed word to integer coercion (cost 20) from div, for:
;       the second argument of generic-+
;
; compilation unit finished
;   printed 4 notes

CL-USER>

Body:
If you want to specify the return value of an expression you can use THE:

(the fixnum (1+ 3))

But you really want to make sure that the value is actually a fixnum. If you 'lie', then Lisp may believe you and you have unspecified runtime effects. SBCL may warn at compile time, but you really should take care of that. If you provide wrong types are return wrong types, data may get corrupted and/or Lisp may crash.

Another way to specify a return value is the FTYPE declaration:

For example a function ith may take an integer and a list as arguments. It returns an arbitrary type -> T or any subtype.

(declaim (ftype (function (integer list) t)
                ith))

For example:

(the fixnum (+ (the fixnum a) (the fixnum b)))

There you need to be sure that:

a is an fixnum

b is an fixnum

the sum of a and b is also always a fixnum

Here this is easier, since the sum of a and b is definitely a fixnum:

CL-USER 3 > (let ((a 3) (b 12))
              (the fixnum (+ (the (integer 0 10) a)
                             (the (integer 3 20) b))))
15

Lisp may check that at runtime and/or compile-time. The addition now can be a simple fixnum operation and does not need to deal with fixnum overflows and bignums. If you set the safety value to something low, then the runtime check may also be omitted. But: you should never call this code with the wrong types.


问:
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.

答:
Learning about interfaces did it for me. Coming from a scripting background and switching to OO, I didn't see how creating all these classes was any more efficient. Then I read Head First Design Patterns, and suddenly I saw the why. It's not the most detailed book, but it's a fantastic first step to explaining the "why" of OO programming, something that I struggled with immensely.

Hope this helps.

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: Mike Robinson

LastEditorDisplayName: Mike Robinson


问:
WPF Extending Window
So I have a bunch of WPF Windows in my Windows Application.
I want each window to have a context menu that has one item ( see the code bellow ). However, I don't feel like copying and pasting this code everywhere. I would like to somehow extend the WPF Window class ( and call it PrintableWindow ) and somehow make every window be an extension of the PrintableWindow ....Is this possible ??? </p>

```<code><Window.ContextMenu>
    <ContextMenu>
        <ContextMenu.Items>
            <MenuItem Header="Print"
                      Click="mnuPrint_Click">
            </MenuItem>
        </ContextMenu.Items>
    </ContextMenu>
</Window.ContextMenu>
</code>```

答:
You shouldn't need to extend window to do accomplish this, just created a global style for all windows.

In your app.xaml file:

```<code><Style TargetType="{x:Type Window}">
    <Setter Property="ContextMenu">
        <Setter.Value>
            <ContextMenu>
                <ContextMenu.Items>
                    <MenuItem Header="Print" Command="Print" />
                </ContextMenu.Items>
            </ContextMenu>
        </Setter.Value>
    </Setter>
</Style>
</code>```

You will have to create a handler for the print command in the window if you want to print from a particular window.  Even better, if you are using a view model you can just bind to your command.

Title: WPF Extending Window

Body:
So I have a bunch of WPF Windows in my Windows Application.
I want each window to have a context menu that has one item ( see the code bellow ). However, I don't feel like copying and pasting this code everywhere. I would like to somehow extend the WPF Window class ( and call it PrintableWindow ) and somehow make every window be an extension of the PrintableWindow ....Is this possible ???

<Window.ContextMenu>
    <ContextMenu>
        <ContextMenu.Items>
            <MenuItem Header="Print"
                      Click="mnuPrint_Click">
            </MenuItem>
        </ContextMenu.Items>
    </ContextMenu>
</Window.ContextMenu>

Body:
You shouldn't need to extend window to do accomplish this, just created a global style for all windows.

In your app.xaml file:

<Style TargetType="{x:Type Window}">
    <Setter Property="ContextMenu">
        <Setter.Value>
            <ContextMenu>
                <ContextMenu.Items>
                    <MenuItem Header="Print" Command="Print" />
                </ContextMenu.Items>
            </ContextMenu>
        </Setter.Value>
    </Setter>
</Style>

You will have to create a handler for the print command in the window if you want to print from a particular window.  Even better, if you are using a view model you can just bind to your command.