问:
Python fitting sinus cardinal and LMFIT library
I have a set of data from a physic experiment (simple-slit experiment) in university and i am trying to fit this data to a model that i build from the lmfit library.
I want a sinus cardinal square, in this form:

I(X)= I0.sinc²(pi.a.X/(lambda.D))

with a : the width of the slit,
lambda : wavelenght of the light
D : distance camera/slit
I0 : original intensity

```<code>import csv as csv
from math import pi
import matplotlib.pyplot as plt
import numpy as np
from lmfit import *

# create data to be fitted
with open('data_1.csv', 'r') as f:
    values = list(csv.reader(f, delimiter=','))
values = np.array(values[1:], dtype=np.float)

position = values[:, 0]
intensity = values[:, 1]

#define function model
def fct(x, I0, a, D, b):
    return I0 * np.square(np.sinc(pi * a * (x + b) / (0.00000063 * D)))
    #b is for the horizontal shift because my experience
    #was centered on 700 due to the camera

# do fit
vmodel = Model(fct)
vmodel.set_param_hint('I0', min=0., max=300.)
vmodel.set_param_hint('a', value=0.0005, min=0.0, max=1.)
vmodel.set_param_hint('D', value=0.53, min=0.0, max=1.)
vmodel.set_param_hint('b', min=0., max=2000.)
pars = vmodel.make_params()
result = vmodel.fit(intensity, pars, x=position)

# write report
print(result.fit_report())

#after we plot the data, with position on x and intensity on y
</code>```

It returns totally wrong values and an error :

```<code>RuntimeWarning: invalid value encountered in double_scalars spercent =
'({0:.2%})'.format(abs(par.stderr/par.value))

[[Model]]
    Model(fct)
[[Fit Statistics]]
    # function evals   = 7
    # data points      = 1280
    # variables        = 4
    chi-square         = 4058147.794
    reduced chi-square = 3180.367
    Akaike info crit   = 10326.876
    Bayesian info crit = 10347.494
[[Variables]]
    I0:   0          +/- 0        (nan%) (init= 0)
    a:    0.00050000 +/- 0        (0.00%) (init= 0.0005)
    D:    0.50000000 +/- 0        (0.00%) (init= 0.5)
    b:    400        +/- 0        (0.00%) (init= 400)
</code>```

Could you help me please ? I tried lots of type models from this library but nothing work correctly and i really need it. I already solved 2D problems with a np.square, and other reading things, the major problem is the model.
Waiting for answers,
Thanks,

答:
You probably want to provide reasonable starting values for all your parameter values.  As you wrote it, there are no initial values for I0 or b  but conveniently(?) these parameters have bounds set, so that initial values can be inferred (probably poorly) as the lower bound -- I don't know how b became 400.  Maybe a typo?

Anyway, I would recommend trying

```<code>pars = vmodel.make_params(I0=150, b=400)
</code>```

and then try the fit again.

Body:
I have a set of data from a physic experiment (simple-slit experiment) in university and i am trying to fit this data to a model that i build from the lmfit library.
I want a sinus cardinal square, in this form:

I(X)= I0.sinc²(pi.a.X/(lambda.D))

with a : the width of the slit,
lambda : wavelenght of the light
D : distance camera/slit
I0 : original intensity

import csv as csv
from math import pi
import matplotlib.pyplot as plt
import numpy as np
from lmfit import *

# create data to be fitted
with open('data_1.csv', 'r') as f:
    values = list(csv.reader(f, delimiter=','))
values = np.array(values[1:], dtype=np.float)

position = values[:, 0]
intensity = values[:, 1]

#define function model
def fct(x, I0, a, D, b):
    return I0 * np.square(np.sinc(pi * a * (x + b) / (0.00000063 * D)))
    #b is for the horizontal shift because my experience
    #was centered on 700 due to the camera

# do fit
vmodel = Model(fct)
vmodel.set_param_hint('I0', min=0., max=300.)
vmodel.set_param_hint('a', value=0.0005, min=0.0, max=1.)
vmodel.set_param_hint('D', value=0.53, min=0.0, max=1.)
vmodel.set_param_hint('b', min=0., max=2000.)
pars = vmodel.make_params()
result = vmodel.fit(intensity, pars, x=position)

# write report
print(result.fit_report())

#after we plot the data, with position on x and intensity on y

It returns totally wrong values and an error :

RuntimeWarning: invalid value encountered in double_scalars spercent =
'({0:.2%})'.format(abs(par.stderr/par.value))

[[Model]]
    Model(fct)
[[Fit Statistics]]
    # function evals   = 7
    # data points      = 1280
    # variables        = 4
    chi-square         = 4058147.794
    reduced chi-square = 3180.367
    Akaike info crit   = 10326.876
    Bayesian info crit = 10347.494
[[Variables]]
    I0:   0          +/- 0        (nan%) (init= 0)
    a:    0.00050000 +/- 0        (0.00%) (init= 0.0005)
    D:    0.50000000 +/- 0        (0.00%) (init= 0.5)
    b:    400        +/- 0        (0.00%) (init= 400)

Could you help me please ? I tried lots of type models from this library but nothing work correctly and i really need it. I already solved 2D problems with a np.square, and other reading things, the major problem is the model.
Waiting for answers,
Thanks,

Body:
You probably want to provide reasonable starting values for all your parameter values.  As you wrote it, there are no initial values for I0 or b  but conveniently(?) these parameters have bounds set, so that initial values can be inferred (probably poorly) as the lower bound -- I don't know how b became 400.  Maybe a typo?

Anyway, I would recommend trying

pars = vmodel.make_params(I0=150, b=400)

and then try the fit again.


来源: stackexchange

问:
Object conforming to a protocol should hide the protocol methods
I have an app designed with Viper architecture. To avoid exeptions, each module is created by a factory class which comply to BaseFactory protocol.

Two of one hundred (2%) modules in my app should be created with a custom factory method which is not enforced via protocol, a factory method which accept an argument.

Is it possible to "hide/disable" a function createViperModule() in the MemberProfileFactory class?

```<code>protocol BaseFactory {

    static func createViperModule () -> UIViewController

}

class HelloFactory: BaseFactory {

    static func creatViperModule() -> UIViewController {

        let p = HelloPresenter()
        let storyboard = UIStoryboard.init(name: "Hello", bundle: nil)
        let vc = (storyboard.instantiateInitialViewController() as? HelloVC)!

        p.vc = vc
        vc.p = p

        return vc
    }
}

class MemberProfileFactory: BaseFactory {

    static func createViperModule() -> UIViewController {

        return PublicProfileVC()
    }

    static func createViperModule(withMember member: MemberModel) -> UIViewController {

        let p = MemberProfilePresenter()
        let storyboard = UIStoryboard.init(name: "MemberProfile", bundle: nil)
        let vc = (storyboard.instantiateInitialViewController() as? MemberProfileVC)!

        p.vc = vc
        p.user = user
        vc.p = p

        return vc
    }
}
</code>```

答:
You can't make 'createViperModule' private because of 'createViperModule' declared as internal in 'BaseFactory'. but you can declare it optional so it is not mandatory to implement.</p>

```<code>@objc protocol BaseFactory {
    @objc optional static func createViperModule () -> UIViewController
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an app designed with Viper architecture. To avoid exeptions, each module is created by a factory class which comply to BaseFactory protocol.

Two of one hundred (2%) modules in my app should be created with a custom factory method which is not enforced via protocol, a factory method which accept an argument.

Is it possible to "hide/disable" a function createViperModule() in the MemberProfileFactory class?

protocol BaseFactory {

    static func createViperModule () -> UIViewController

}

class HelloFactory: BaseFactory {

    static func creatViperModule() -> UIViewController {

        let p = HelloPresenter()
        let storyboard = UIStoryboard.init(name: "Hello", bundle: nil)
        let vc = (storyboard.instantiateInitialViewController() as? HelloVC)!

        p.vc = vc
        vc.p = p

        return vc
    }
}

class MemberProfileFactory: BaseFactory {

    static func createViperModule() -> UIViewController {

        return PublicProfileVC()
    }

    static func createViperModule(withMember member: MemberModel) -> UIViewController {

        let p = MemberProfilePresenter()
        let storyboard = UIStoryboard.init(name: "MemberProfile", bundle: nil)
        let vc = (storyboard.instantiateInitialViewController() as? MemberProfileVC)!

        p.vc = vc
        p.user = user
        vc.p = p

        return vc
    }
}

Body:
You can't make 'createViperModule' private because of 'createViperModule' declared as internal in 'BaseFactory'. but you can declare it optional so it is not mandatory to implement.

@objc protocol BaseFactory {
    @objc optional static func createViperModule () -> UIViewController
}


问:
How to obtain optimal basis matrix B for LP in MATLAB?
I am solving a standard LP problem:

```<code>min C'*x
S.t. A*x=b;x>=0;
</code>```

After obtaining the solution through linprog, I want to obtain the optimal basis B corresponding to that solution. Simplex codes other than provided by MATLAB are very slow for the large-scale problems.

My problem has degeneracy.

答:
The optimal basis of a non-degenerate LP is given by lambda = 0, where, lambda is the Lagrangian multipliers. Within MATLAB, lambda is available as the final output, i.e.

[x,fval,exitflag,output,lambda] = linprog(___)

So to find the basis, simply type k = find(lambda == 0).

However, the value of zero is problematic from a numerical perspective (almost nothing is ever completely 0 in floating-point arithmetic), so you might want to settle for something like k = find(lambda <= 1e-5). However, again, depending on the problem (and how well-behaved it is), this might not be correct either.

So, what can you do? There are basically two ways around this:

Use a commercial solver: commercial solvers tend to be much better in the accuracy of the Lagragian multipliers, especially for badly defined problems. Try Gurobi or CPLEX, and if you are a University student they are for free anyways. They have a similar way of getting lambda out, but are much more reliable in my experience.

Use the constraint values: you basically do k = find(x > 1e-5), and look what it gives you as results. This suffers from the same setbacks as using the Lagrangian, but it might help.

However, you then still need to deal with primal and dual degeneracy, if it occurs. Not to dive in too much, but basically you need to always check that you have exactly n active constraints (n being the number of optimization variables). If you have more or less than that, you have a problem, and you need to put an appropriate check into your code for that.

Body:
I am solving a standard LP problem:

min C'*x
S.t. A*x=b;x>=0;

After obtaining the solution through linprog, I want to obtain the optimal basis B corresponding to that solution. Simplex codes other than provided by MATLAB are very slow for the large-scale problems.

My problem has degeneracy.


问:
jquery plugin, multi-type (value, control id, function) options
I have a plugin I am writing that accepts options.  It looks something like this.

```<code>$('#myObject').myPlugin({
    option1: someValue
});
</code>```

Where somevalue can either be a value, a control id, or a function.

I have a default settings defined like this

```<code>var settings = {
    option1: null
};
</code>```

Then, inside my plugin I use this to merge what the user passes in with my empty settings object

```<code>if (options) {
    $.extend(settings, options);
}
</code>```

This works fine when the option is a control ID or value.

My first issue is when I use a function like this

```<code>$('#myObject').myPlugin({
    option1: function(){ return doStuff(); }
});
</code>```

$.extend() seems to ignore the function in this case.  The default value from settings is always passed into my parser.  I'm also having a problem when I pass in a value instead of a control id.  I parse the settings to get the value like this

```<code>function parseValue(value, defaultValue) {
    if ($.isFunction(value))
        return value();

    if (!value)
        return defaultValue ? defaultValue : '';

    if ($('#' + value))
        return $('#' + value).val();

    return value;
};
</code>```

if I pass in a date or a decimal, $('#' + value) evaluates to true.

Any ideas on how I make this work?

EDIT:

This may be wrong, but this is how I defined my plugin.  It's actually a collection of plugins

```<code>(function ($) {

    //shared methods here
    function parseValue(value, defaultValue) { /*...*/ }

    $.fn.myplugin = function (options) {
        var settings = { };

        $(this).live("submit", function (event) {
            //NEVER EVER EVER allow the form to submit to the server
            event.preventDefault();

            //logic for "posting" cross domain
        });
    };

    $.fn.myplugin2 = function (options) {
        var settings = { };

        $(this).live("submit", function (event) {
            //NEVER EVER EVER allow the form to submit to the server
            event.preventDefault();

            //logic for "posting" cross domain
        });
    };

})(jQuery);
</code>```

The plugins hijack a form and make it submit cross domain through a jsonp get request.  Each plugin submits different data to a different url, but the overall logic is the same.

答:
I found out what I was doing wrong.

The selector test I was doing was always returning false because jquery doesn't return undefined if nothing was found.  So, I changed my parser to look like this:

```<code>function parseValue(value, defaultValue) {
    if ($.isFunction(value))
        return value();

    if (!value)
        return defaultValue;

    if ($.type(value) === 'string' && $(value).length)
        return $(value).val();

    return value;
};
</code>```

and my code now looks something like this

```<code>$.fn.myPlugin= function (options) {

    var settings = {
        setting1: undefined
    }

    $(this).live('click', function{
        var setting = parseValue(settings.setting1, '');
    });
}
</code>```

and now all three types (value, selector, or function) can be passed in as my query options.

ContentLicense: CC BY-SA 2.5

Body:
I have a plugin I am writing that accepts options.  It looks something like this.

$('#myObject').myPlugin({
    option1: someValue
});

Where somevalue can either be a value, a control id, or a function.

I have a default settings defined like this

var settings = {
    option1: null
};

Then, inside my plugin I use this to merge what the user passes in with my empty settings object

if (options) {
    $.extend(settings, options);
}

This works fine when the option is a control ID or value.

My first issue is when I use a function like this

$('#myObject').myPlugin({
    option1: function(){ return doStuff(); }
});

$.extend() seems to ignore the function in this case.  The default value from settings is always passed into my parser.  I'm also having a problem when I pass in a value instead of a control id.  I parse the settings to get the value like this

function parseValue(value, defaultValue) {
    if ($.isFunction(value))
        return value();

    if (!value)
        return defaultValue ? defaultValue : '';

    if ($('#' + value))
        return $('#' + value).val();

    return value;
};

if I pass in a date or a decimal, $('#' + value) evaluates to true.

Any ideas on how I make this work?

EDIT:

This may be wrong, but this is how I defined my plugin.  It's actually a collection of plugins

(function ($) {

    //shared methods here
    function parseValue(value, defaultValue) { /*...*/ }

    $.fn.myplugin = function (options) {
        var settings = { };

        $(this).live("submit", function (event) {
            //NEVER EVER EVER allow the form to submit to the server
            event.preventDefault();

            //logic for "posting" cross domain
        });
    };

    $.fn.myplugin2 = function (options) {
        var settings = { };

        $(this).live("submit", function (event) {
            //NEVER EVER EVER allow the form to submit to the server
            event.preventDefault();

            //logic for "posting" cross domain
        });
    };

})(jQuery);

The plugins hijack a form and make it submit cross domain through a jsonp get request.  Each plugin submits different data to a different url, but the overall logic is the same.

Body:
I found out what I was doing wrong.

The selector test I was doing was always returning false because jquery doesn't return undefined if nothing was found.  So, I changed my parser to look like this:

function parseValue(value, defaultValue) {
    if ($.isFunction(value))
        return value();

    if (!value)
        return defaultValue;

    if ($.type(value) === 'string' && $(value).length)
        return $(value).val();

    return value;
};

and my code now looks something like this

$.fn.myPlugin= function (options) {

    var settings = {
        setting1: undefined
    }

    $(this).live('click', function{
        var setting = parseValue(settings.setting1, '');
    });
}

and now all three types (value, selector, or function) can be passed in as my query options.


问:
Filtering data by Navigation Property in EF Core
I have this small model:

```<code>class User
{
    public int Id { get; set; }
    public Community { get; set; }
}

class Community
{
    public int Id { get; set; }
    public Country { get; set; }
}

class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

The DbContext is this:

```<code>public class SmallDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
}
</code>```

I would like to create query that will retrieve the Users of a given Country

My bet using is this:

```<code>int countryId = 2:
var usersOfAGivenCountry = dbContext.Users
                                    .Where(community => community.Country.Id == countryId);
</code>```

But I'm not sure if I'm doing it right. Is this correct way to do it?

Also, I wonder how this will handle a null Community in a User.

答:
It's almost that, i advice you to add condition in null case, and you have to declare the foreign keys in your models like :

```<code>class User
{
    public int Id { get; set; }
    public int CommunityId { get; set; }
    [ForeignKey("CommunityId")] // facultative because it respects naming convention Modelname + "Id"
    public Community { get; set; }
}

class Community
{
    public int Id { get; set; }
    public int CountryId { get;set; }
    [ForeignKey("CountryId")] // facultative because it respects naming convention Modelname + "Id"
    public Country { get; set; }
}
var usersOfAGivenCountry = dbContext.Users
      .Include(p => p.Community)
      .Where(community => community != null
             && community.CountryId == countryId);
</code>```

And the line .Include(p => p.Community) is facultative if you enabled Lazy Loading mode, but i advice you to disable it

ContentLicense: CC BY-SA 4.0

Body:
I have this small model:

class User
{
    public int Id { get; set; }
    public Community { get; set; }
}

class Community
{
    public int Id { get; set; }
    public Country { get; set; }
}

class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
}

The DbContext is this:

public class SmallDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
}

I would like to create query that will retrieve the Users of a given Country

My bet using is this:

int countryId = 2:
var usersOfAGivenCountry = dbContext.Users
                                    .Where(community => community.Country.Id == countryId);

But I'm not sure if I'm doing it right. Is this correct way to do it?

Also, I wonder how this will handle a null Community in a User.

Body:
It's almost that, i advice you to add condition in null case, and you have to declare the foreign keys in your models like :

class User
{
    public int Id { get; set; }
    public int CommunityId { get; set; }
    [ForeignKey("CommunityId")] // facultative because it respects naming convention Modelname + "Id"
    public Community { get; set; }
}

class Community
{
    public int Id { get; set; }
    public int CountryId { get;set; }
    [ForeignKey("CountryId")] // facultative because it respects naming convention Modelname + "Id"
    public Country { get; set; }
}
var usersOfAGivenCountry = dbContext.Users
      .Include(p => p.Community)
      .Where(community => community != null
             && community.CountryId == countryId);

And the line .Include(p => p.Community) is facultative if you enabled Lazy Loading mode, but i advice you to disable it


问:
Add html link in anyone of ng-grid
I want to add link to ng-grid.
Here is my code for your reference

```<code><html ng-app="myApp">
<head lang="en">
    <meta charset="utf-8">
    <title>Getting Started With ngGrid Example</title>
    <link href="../../Content/ng-grid.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>
    <script src="../../Scripts/angular.js" type="text/javascript"></script>
    <script src="../../Scripts/ng-grid.js" type="text/javascript"></script>
    <script src="../../Scripts/main.js" type="text/javascript"></script>
    <script type="text/javascript">
        var app = angular.module('myApp', ['ngGrid']);
        app.controller('MyCtrl', function ($scope) {
            $scope.myData = [{ name: "RK.PRABAKAR", age: 25, href: "<a href='#'>Link1</a>" },
                 { name: "Yoga", age: 27, href: "<a href='#'>Link1</a>" },
                 { name: "James", age: 27, href: "<a href='#'>Link1</a>" },
                 { name: "Siva", age: 35, href: "<a href='#'>Link1</a>" },
                 { name: "KK", age: 27, href: "<a href='#'>Link1</a>"}];

            $scope.pagingOptions = {
                pageSizes: [2, 4, 6],
                pageSize: 2,
                currentPage: 1
            };

            $scope.gridOptions = {
                data: 'myData',
                enablePaging: true,
                showFooter: true,
                enableCellSelection: true,
                enableRowSelection: false,
                enablePinning: true,
                pagingOptions: $scope.pagingOptions,
                enableCellEdit: true,
                columnDefs: [{ field: 'name', displayName: 'Name', enableCellEdit: true },
                 { field: 'age', displayName: 'Age', enableCellEdit: true },
                 { field: 'href', displayName: 'Link', enableCellEdit: false }]
            };
        });
    </script>
    <style>
    .gridStyle {
border: 1px solid rgb(212,212,212);
width: 500px;
height: 300px;
}
    </style>
</head>
<body data-ng-controller="MyCtrl">
    <div class="gridStyle" data-ng-grid="gridOptions"></div>
</body>
</code>```

Right now data grid is working fine except href link in grid.
Link is not rendered to html tag it is displayed as normal string.
I want to add link to ng-grid from myData

答:
This worked for me with ui-grid 4.0.7 and angular 1.6.6, my properties are easily accessible in row.entity:

```<code>cellTemplate: '<div class="ngCellText">
                  <a href="Users/{{row.entity.userId}}">{{row.entity.name}}</a>
               </div>'
</code>```

(added line breaks for clarity, remove when pasting)

Title: Add html link in anyone of ng-grid

Body:
I want to add link to ng-grid.
Here is my code for your reference

    <meta charset="utf-8">
    <title>Getting Started With ngGrid Example</title>
    <link href="../../Content/ng-grid.css" rel="stylesheet" type="text/css" />

Right now data grid is working fine except href link in grid.
Link is not rendered to html tag it is displayed as normal string.
I want to add link to ng-grid from myData

Body:
This worked for me with ui-grid 4.0.7 and angular 1.6.6, my properties are easily accessible in row.entity:

cellTemplate: '<div class="ngCellText">
                  <a href="Users/{{row.entity.userId}}">{{row.entity.name}}</a>
               </div>'

(added line breaks for clarity, remove when pasting)


问:
EnableEurekaServer import doesn't exist
I build a Spring-Service with gradle and I wanted to use a Eureka-Server with it.
My java-file looks like this:

```<code>import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
public class Welcome {
   ....
}
</code>```

but when I try to build it with my gradle-file it says:

org.springframework.cloud.netflix.eureka.server does not exist

I searched for a solution for this problem but I seem to be alone with it. Does someone know why it is not working? Do I have to write something specific into the build.gradle-file?

答:
Assuming you use a bill of materials to manage Spring Cloud dependencies:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
```

<p>Just add the following depedency to your project:</p>

<pre class="lang-xml prettyprint-override"><code><dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
</code>```

Spring Cloud releases have names instead of numbers. And you must ensure that Spring Cloud version is compatible with the Spring Boot version you are using. See more details here.

Title: EnableEurekaServer import doesn't exist

Body:
I build a Spring-Service with gradle and I wanted to use a Eureka-Server with it.
My java-file looks like this:

import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
public class Welcome {
   ....
}

but when I try to build it with my gradle-file it says:

org.springframework.cloud.netflix.eureka.server does not exist

I searched for a solution for this problem but I seem to be alone with it. Does someone know why it is not working? Do I have to write something specific into the build.gradle-file?

Body:
Assuming you use a bill of materials to manage Spring Cloud dependencies:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Just add the following depedency to your project:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>

Spring Cloud releases have names instead of numbers. And you must ensure that Spring Cloud version is compatible with the Spring Boot version you are using. See more details here.


问:
How to match a regexp with receive in Erlang?
There is the following block:

```<code>receive
...
  {raw, Text} ->
      send(Socket, Text),
      master(State);
...
end.
</code>```

I am wondering if it is possible to match a regexp in Text and have a simple clause if the Text matches.

答:
You can't do this directly in a pattern match (in this case a receive pattern) as there's no regular expression pattern. There is a regular expression library, so you can try the match after you receive the {text, Text} message, but it isn't the same as selectively receiving the message only if it matches a regular expression.

The one case you can do better than this is if your regular expression is a constant prefix of Text, like "^some prefix", where you can use the "some prefix" ++ _Var syntax:

```<code>receive
...
    {raw, Text = "some prefix" ++ _} ->
        send(Socket, Text),
        master(State);
...
end
</code>```

Body:
There is the following block:

receive
...
  {raw, Text} ->
      send(Socket, Text),
      master(State);
...
end.

I am wondering if it is possible to match a regexp in Text and have a simple clause if the Text matches.

Body:
You can't do this directly in a pattern match (in this case a receive pattern) as there's no regular expression pattern. There is a regular expression library, so you can try the match after you receive the {text, Text} message, but it isn't the same as selectively receiving the message only if it matches a regular expression.

The one case you can do better than this is if your regular expression is a constant prefix of Text, like "^some prefix", where you can use the "some prefix" ++ _Var syntax:

receive
...
    {raw, Text = "some prefix" ++ _} ->
        send(Socket, Text),
        master(State);
...
end


问:
Json allows trailing comma
I have trailing comma in my .json file in asp solution.

```<code>    { "key": "Value1", "text": "Add new value" },
    { "key": "Value2", "text": "value 2" },
    { "key": "Value3", "text": "value 3" },
]
</code>```

I was very surprised when my teamlead told me "it won't work" while reviewing my code changes, because it works =) I have not known before about this detail and that this comma is prohibited in json. Our question is why does it work in  VS2017 solution? Probably compilator does anything with this comma.
I use this code to deserialize:

```<code>JsonFormat value = JsonConvert.DeserializeObject<JsonFormat>(jsonText);
</code>```

答:
Json allows trailing comma

Nope, no it doesn't. That isn't valid JSON. Some parsers will allow it, but then: some parsers will allow comments which are also invalid.

Trailing commas are not valid in JSON.

Our question is why does it work in VS2017 solution?

Because some parsers will try to parse as much as they can, without enforcing strict conformity. Presumably this is one such case.

Title: Json allows trailing comma

Body:
I have trailing comma in my .json file in asp solution.

    { "key": "Value1", "text": "Add new value" },
    { "key": "Value2", "text": "value 2" },
    { "key": "Value3", "text": "value 3" },
]

I was very surprised when my teamlead told me "it won't work" while reviewing my code changes, because it works =) I have not known before about this detail and that this comma is prohibited in json. Our question is why does it work in  VS2017 solution? Probably compilator does anything with this comma.
I use this code to deserialize:

JsonFormat value = JsonConvert.DeserializeObject<JsonFormat>(jsonText);


问:
how to append to json file in java
I have this js.json file

i want to add another block to the file.

the file now ->

```<code>[
{
"diff":"Easy",
"qus":"John1"
}
]
</code>```

how i want it to be ->

```<code>[
{
"diff":"Easy",
"qus":"John1"
},
{
"diff":"Avg",
"qus":"John2"
}
]
</code>```

答:
You can use org.json library as follow:

```<code>JSONArray jsonarray = new JSONArray(jsonStr); //from the file
JSONObject jsonobject = new JSONObject(yourNewlyJsonObject);
jsonarray.put(jsonobject);
System.out.println(jsonarray.toString()); // or write it back to the file
</code>```

Title: how to append to json file in java

Body:
I have this js.json file

i want to add another block to the file.

the file now ->

[
{
"diff":"Easy",
"qus":"John1"
}
]

how i want it to be ->

[
{
"diff":"Easy",
"qus":"John1"
},
{
"diff":"Avg",
"qus":"John2"
}
]

Body:
You can use org.json library as follow:

JSONArray jsonarray = new JSONArray(jsonStr); //from the file
JSONObject jsonobject = new JSONObject(yourNewlyJsonObject);
jsonarray.put(jsonobject);
System.out.println(jsonarray.toString()); // or write it back to the file


问:
MySQL - SELECT equal amount of each in UNION by total LIMIT
In a MySQL database I have 3 tables: customers, projects and tasks. For a search that I am implementing, I want to search through all 3 tables and select found matches. The problem is that I would like to equally limit the amount of results returned by MySQL.

This is an example with the query that I currently have:

```<code>SELECT id, title, type
FROM (
    (
    SELECT id, title, 'customer' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM customers
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (
    SELECT id, title, 'project' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM projects
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (
    SELECT id, title, 'task' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM tasks
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
) res
LIMIT 6;
</code>```

In this example, I want to limit the results to 6.

My desired endresult for this example is the following:

1) If all tables have at least 2 results, show 2 results for each.

```<code>id     title                      type
20     'First test customer'      'customer'
22     'Test customer 2'          'customer
48     'A project for testing'    'project'
17     'Test Project'             'project'
1      'Task test'                'task'
2      'Second test'              'task'
</code>```

2) If one table does not have any results, show 3 results for each of the 2 other tables. (If only one table has results, show 6 results for that table.)

```<code>id     title                      type
20     'First test customer'      'customer'
22     'Test customer 2'          'customer
56     'Customer test 56'         'customer'
1      'Task test'                'task'
2      'Second test'              'task'
3      'Test task'                'task'
</code>```

3) If 2 of the tables have more than 2 results, and the third table only has 1 result, show 3 results for one of the tables with enough results, 2 results for the other one of the two and 1 for the table with only 1 result.

```<code>id     title                      type
20     'First test customer'      'customer'
48     'A project for testing'    'project'
17     'Test Project'             'project'
34     'Testing project'          'project'
1      'Task test'                'task'
2      'Second test'              'task'
</code>```

Can anyone please help me with this?

Thanks in advance!

答:
You might use a row number for every single SELECT and then order the UNION with that calculated field to balance the results obtained from the single queries (I've not tested this code, please take it as a starting point):

```<code>SET @rank1=0;
SET @rank2=0;
SET @rank3=0;
SELECT id, title, type, rank
FROM (
    (

    SELECT @rank1:=@rank1+1 AS rank, id, title, 'customer' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM customers
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (

    SELECT @rank2:=@rank2+1 AS rank, id, title, 'project' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM projects
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (

    SELECT @rank3:=@rank3+1 AS rank, id, title, 'task' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM tasks
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
) res
ORDER BY rank
LIMIT 6;
</code>```

Body:
In a MySQL database I have 3 tables: customers, projects and tasks. For a search that I am implementing, I want to search through all 3 tables and select found matches. The problem is that I would like to equally limit the amount of results returned by MySQL.

This is an example with the query that I currently have:

SELECT id, title, type
FROM (
    (
    SELECT id, title, 'customer' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM customers
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (
    SELECT id, title, 'project' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM projects
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (
    SELECT id, title, 'task' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM tasks
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
) res
LIMIT 6;

In this example, I want to limit the results to 6.

My desired endresult for this example is the following:

1) If all tables have at least 2 results, show 2 results for each.

id     title                      type
20     'First test customer'      'customer'
22     'Test customer 2'          'customer
48     'A project for testing'    'project'
17     'Test Project'             'project'
1      'Task test'                'task'
2      'Second test'              'task'

2) If one table does not have any results, show 3 results for each of the 2 other tables. (If only one table has results, show 6 results for that table.)

id     title                      type
20     'First test customer'      'customer'
22     'Test customer 2'          'customer
56     'Customer test 56'         'customer'
1      'Task test'                'task'
2      'Second test'              'task'
3      'Test task'                'task'

3) If 2 of the tables have more than 2 results, and the third table only has 1 result, show 3 results for one of the tables with enough results, 2 results for the other one of the two and 1 for the table with only 1 result.

id     title                      type
20     'First test customer'      'customer'
48     'A project for testing'    'project'
17     'Test Project'             'project'
34     'Testing project'          'project'
1      'Task test'                'task'
2      'Second test'              'task'

Can anyone please help me with this?

Thanks in advance!

Body:
You might use a row number for every single SELECT and then order the UNION with that calculated field to balance the results obtained from the single queries (I've not tested this code, please take it as a starting point):

SET @rank1=0;
SET @rank2=0;
SET @rank3=0;
SELECT id, title, type, rank
FROM (
    (

    SELECT @rank1:=@rank1+1 AS rank, id, title, 'customer' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM customers
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (

    SELECT @rank2:=@rank2+1 AS rank, id, title, 'project' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM projects
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
    UNION DISTINCT
    (

    SELECT @rank3:=@rank3+1 AS rank, id, title, 'task' AS type, MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE) AS score
    FROM tasks
    WHERE MATCH (title) AGAINST ('+test* ' IN BOOLEAN MODE)
    )
) res
ORDER BY rank
LIMIT 6;


问:
How to place the last
 on the right side of my page?
I want to move the last li to right side but my CSS is not working.

.gCountryFlag {
    margin-left: 0;
    padding-left: 0;
}
ul li {
    list-style: none;

}
.navbar-collapse ul li:last-child {
     float: right;
}
.gCountryFlag li {
    float: left;
    display: inline-block;
    margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>Home</li>
                <li>About</li>
                <li>Contact</li>
                <li>
                    <div class="flagChangeCountry">
                        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
                        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</div></code>```

i want to move this image to right side which is in div. here it is.

```<code><li>
    <div class="flagChangeCountry">
        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>
    </div>
</li>
</code>```

Also, I want to align the flag image with other text in same line. Here is screenshot for how the flag is looking which is not right side and also which is not aligned with other text.

答:
All you need is to set float: right for the last li item. And don't forget about clearfix.

ul {
  border: 1px solid red;
  padding: 0;
  margin: 50px;
}

ul:after {
  /* clearfix */
  content: "";
  display: table;
  clear: both;
}

li {
  float: left; /* all li items */

  padding: 0;
  margin: 0;
  border: 1px solid green;
  list-style: none;
}

li:last-child {
  float: right; /* last li item */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul></code>```

Title: How to place the last <li> on the right side of my page?

Body:
I want to move the last li to right side but my CSS is not working.

.gCountryFlag {
    margin-left: 0;
    padding-left: 0;
}
ul li {
    list-style: none;

}
.navbar-collapse ul li:last-child {
     float: right;
}
.gCountryFlag li {
    float: left;
    display: inline-block;
    margin: 5px;
}

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

            </button>

Home

About

Contact

                        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
                        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>

i want to move this image to right side which is in div. here it is.

        <asp:Image CssClass="topFlag" runat="server" ID="currentCultureFlagImage" />
        <%--<asp:Literal runat="server" Text="<%$Resources:LocalisedText, ChangeCountryText %>" />--%>

Also, I want to align the flag image with other text in same line. Here is screenshot for how the flag is looking which is not right side and also which is not aligned with other text.

Body:
All you need is to set float: right for the last li item. And don't forget about clearfix.

ul {
  border: 1px solid red;
  padding: 0;
  margin: 50px;
}

ul:after {
  /* clearfix */
  content: "";
  display: table;
  clear: both;
}

li {
  float: left; /* all li items */

  padding: 0;
  margin: 0;
  border: 1px solid green;
  list-style: none;
}

li:last-child {
  float: right; /* last li item */
}

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>


问:
Javascript returns only one timestamp inside for loop
I want to generate a timestamp for each item inside the for loop but i am getting only one timestamp inside the loop.How can i make new timestamp for each item in the for loop in javascript.

```<code>for (var i = 0 ; i < 5; i++ ) { vm.workers[i].id = (new Date()).getTime(); }
</code>```

This one provides only one timestamp instead of 5 different timestamp can anyone tell me how to generate multiple timestamps inside the loop.

答:
Answering the original question which had this loop:

```<code>for (var i = 0 ; i < 5; i++ ) { new Date().getTime(); }
</code>```

You're not doing anything with them so it will only print the last one or none at all if you're not using the console.

Try logging each one with console.log.

```<code>for (var i = 0 ; i < 5; i++ ) { console.log(new Date().getTime()); }
</code>```

assign them to a an array and add them like so like so will give you an array of date/time stanmps:

```<code>var list = [];
for (var i = 0 ; i < 5; i++ ) { list.push(new Date().getTime()); }
console.log(list);
</code>```

Body:
I want to generate a timestamp for each item inside the for loop but i am getting only one timestamp inside the loop.How can i make new timestamp for each item in the for loop in javascript.

for (var i = 0 ; i < 5; i++ ) { vm.workers[i].id = (new Date()).getTime(); }

This one provides only one timestamp instead of 5 different timestamp can anyone tell me how to generate multiple timestamps inside the loop.

Body:
Answering the original question which had this loop:

for (var i = 0 ; i < 5; i++ ) { new Date().getTime(); }

You're not doing anything with them so it will only print the last one or none at all if you're not using the console.

Try logging each one with console.log.

for (var i = 0 ; i < 5; i++ ) { console.log(new Date().getTime()); }

assign them to a an array and add them like so like so will give you an array of date/time stanmps:

var list = [];
for (var i = 0 ; i < 5; i++ ) { list.push(new Date().getTime()); }
console.log(list);


问:
Is it worth creating an interface for a trivial return type?
Consider the following interfaces:

```<code>public interface IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id);
}

public interface IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}
</code>```

and the associated implementations:

```<code>public class PlayerRepository : IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id)
  {
    // read from external data store
    return new PlayerInfo();
  }
}

public class PlayerInfo : IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}
</code>```

Is there any value in having the separate IPlayerInfo interface, given that the class only exists as a collection of properties to be returned by this method?  Would it be preferable to just have the IPlayerRepository.GetPlayerInfo method return a concrete PlayerInfo object?

答: If you think you can have more than one kind of PlayerInfo (which is likely to be the case if PlayerInfo is a class and not a struct), then yes. If it's something that'll probably never change, then probably not.

Body:
Consider the following interfaces:

public interface IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id);
}

public interface IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}

and the associated implementations:

public class PlayerRepository : IPlayerRepository
{
  IPlayerInfo GetPlayerInfo(int id)
  {
    // read from external data store
    return new PlayerInfo();
  }
}

public class PlayerInfo : IPlayerInfo
{
  public int Id { get; set; }
  public int GamesPlayed { get; set; }
  public int GamesWon { get; set; }
}

Is there any value in having the separate IPlayerInfo interface, given that the class only exists as a collection of properties to be returned by this method?  Would it be preferable to just have the IPlayerRepository.GetPlayerInfo method return a concrete PlayerInfo object?


答:
All the ids are the same because the loop takes no time at all to run. So how can you generate a unique number for each? Add one each time you use it.</p>

```<code>var ts = (new Date()).getTime();
for (var i = 0 ; i < 5; i++ ) {
  vm.workers[i].id = ts++
}
</code>```

Title: Javascript returns only one timestamp inside for loop

Body:
All the ids are the same because the loop takes no time at all to run. So how can you generate a unique number for each? Add one each time you use it.

var ts = (new Date()).getTime();
for (var i = 0 ; i < 5; i++ ) {
  vm.workers[i].id = ts++
}


问:
How to show the content of a list in a second table once the first table has no more space
I want to pull data from DB and list it in a table.
The screen size is fixed and they shall not be extended(no scrolling).
Once there is no more "space" for table1, I want that the following items to be listed on a sided table2. So I don't want that the screen gets extended, scrolled.

This is how my code is.

```<code><html>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="background-color: transparent">TIME</th>
                            <th style="background-color: transparent">LOCATION</th>
                            <th style="background-color: transparent">MESSAGE</th>
                        </tr>
                    </thead>
                </table>
            </div>
            <div class="col-md-6">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="background-color: transparent">TIME</th>
                            <th style="background-color: transparent">LOCATION</th>
                            <th style="background-color: transparent">MESSAGE</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
</body>
</code>```

This picture shows how I want my implementation:

Thanks in advance.

答:
The solution was to use the JSTL core begin and end attributes:</p>

```<code><div class="col-md-6">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="background-color: transparent">TIME</th>
                            <th style="background-color: transparent">LOCATION</th>
                            <th style="background-color: transparent">MESSAGE</th>
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach items="${somedata}" var="data" begin = "0" end = "5">
                            <tr>
                                <td>${data.time}</td>
                                <td>${data.message}</td>
                                <td>${data.location}</td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
            </div>
            <div class="col-md-6">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="background-color: transparent">TIME</th>
                            <th style="background-color: transparent">LOCATION</th>
                            <th style="background-color: transparent">MESSAGE</th>
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach items="${somedata}" var="data" begin = "6" end = "11">
                            <tr>
                                <td>${data.time}</td>
                                <td>${data.location}</td>
                                <td>${data.message}</td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
            </div>
</code>```

Body:
I want to pull data from DB and list it in a table.
The screen size is fixed and they shall not be extended(no scrolling).
Once there is no more "space" for table1, I want that the following items to be listed on a sided table2. So I don't want that the screen gets extended, scrolled.

This is how my code is.

                            TIME
                            LOCATION
                            MESSAGE

                            TIME
                            LOCATION
                            MESSAGE

This picture shows how I want my implementation:

Thanks in advance.

Body:
The solution was to use the JSTL core begin and end attributes:

<div class="col-md-6">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="background-color: transparent">TIME</th>
                            <th style="background-color: transparent">LOCATION</th>
                            <th style="background-color: transparent">MESSAGE</th>
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach items="${somedata}" var="data" begin = "0" end = "5">
                            <tr>
                                <td>${data.time}</td>
                                <td>${data.message}</td>
                                <td>${data.location}</td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
            </div>
            <div class="col-md-6">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="background-color: transparent">TIME</th>
                            <th style="background-color: transparent">LOCATION</th>
                            <th style="background-color: transparent">MESSAGE</th>
                        </tr>
                    </thead>
                    <tbody>
                        <c:forEach items="${somedata}" var="data" begin = "6" end = "11">
                            <tr>
                                <td>${data.time}</td>
                                <td>${data.location}</td>
                                <td>${data.message}</td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
            </div>


答:
you can check this code.

```<code>JSONObject obj = new JSONObject({
    "diff":"Avg",
    "qus":"John2"
    });

JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));   // reading the file and creating a json array of it.

a.put(obj);   // adding your created object into the array

// writing the JSONObject into a file(info.json)
        try {
            FileWriter fileWriter = new FileWriter("c:\\exer4-courses.json");         // writing back to the file
            fileWriter.write(a.toJSONString());
            fileWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

References:

https://www.javatpoint.com/json-tutorial

http://www.vogella.com/tutorials/JavaIO/article.html

Title: how to append to json file in java

Body:
you can check this code.

JSONObject obj = new JSONObject({
    "diff":"Avg",
    "qus":"John2"
    });

JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));   // reading the file and creating a json array of it.

a.put(obj);   // adding your created object into the array

// writing the JSONObject into a file(info.json)
        try {
            FileWriter fileWriter = new FileWriter("c:\\exer4-courses.json");         // writing back to the file
            fileWriter.write(a.toJSONString());
            fileWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

References:

https://www.javatpoint.com/json-tutorial

http://www.vogella.com/tutorials/JavaIO/article.html


问:
own len function with recursion in Go
I'm trying to build simple function to count elements in slice (like len) It must be simple (without additional libs) and with recursion. The problem is when i try to check is slice is empty (is nul).

```<code>package main
import "fmt"

func main() {
  x := []int{1, 2, 3}
  fmt.Println(len2(x))
}
func len2(s []int) int {
  if s == nil {
    return 0
  }
  return 1 + len2(s[1:])
}
</code>```

the result it should be in this example '3'.

It's broken in if s == nil:

```<code>panic: runtime error: slice bounds out of range
</code>```

答:
If you can leave without recursion here is a function that does not use len() and should be faster then re-slicing recursively.

```<code>func len2(s []int) (count int) {
  for i := range s {
    count = i + 1
  }
}
</code>```

Title: own len function with recursion in Go

Body:
I'm trying to build simple function to count elements in slice (like len) It must be simple (without additional libs) and with recursion. The problem is when i try to check is slice is empty (is nul).

package main
import "fmt"

func main() {
  x := []int{1, 2, 3}
  fmt.Println(len2(x))
}
func len2(s []int) int {
  if s == nil {
    return 0
  }
  return 1 + len2(s[1:])
}

the result it should be in this example '3'.

It's broken in if s == nil:

panic: runtime error: slice bounds out of range

Body:
If you can leave without recursion here is a function that does not use len() and should be faster then re-slicing recursively.

func len2(s []int) (count int) {
  for i := range s {
    count = i + 1
  }
}


问:
XE7 copy text to clipboard
http://www.swissdelphicenter.com/torry/showcode.php?id=640 has an example for copy list item to clipboard.  The code works on WIN-XP and Delphi 7.  It doesn't work on XE7.  I'm guessing the 16 bit char or string type is causing issues because the data in the list came from a USB peripheral that works with 8 bit characters.
But the code looks correct.</p>

答:
In order to copy the ListBox content into clipboard, you can use the following code:</p>

```<code>uses
  Vcl.Clipbrd;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Clipboard.AsText := ListBox1.Items.Text;
end;
</code>```

Title: XE7 copy text to clipboard

Body:
In order to copy the ListBox content into clipboard, you can use the following code:

uses
  Vcl.Clipbrd;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Clipboard.AsText := ListBox1.Items.Text;
end;


问:
How can I center an element's side to middle of an other element?
I'm using ConstraintLayout and would like to center an element's left side to the middle of an element which is above it.

```<code>[I'm Element 1]

        | // middle of element 1

        [Element 2 should start at middle of element 1]
</code>```

Is this possible without writing code, and if yes, how?

答:
You can align element 2 using constraints. To center an element you can constraint the left side to the left side of element 1 and do the same for the right side. So in xml it would be something like:

```<code><Element2
    android:id="@+id/element2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="@+id/element1"
    app:layout_constraintRight_toRightOf="@+id/element1" />
</code>```

That should center it horizontally. If you also want to center it vertically simply add the top and bottom constraints.

Edit: Misunderstood the question, if you want to align the left side of an element to the center of another element you can use a GuideLine

Create a Guideline and position it's baseline to the baseline of Element1:

```<code><android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBaseline_toBaselineOf="@+id/element1"/>
</code>```

Then align the left side of your element2 to the GuideLine

```<code><Element2
    android:id="@+id/element2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="@+id/guideline" />
</code>```

Body:
I'm using ConstraintLayout and would like to center an element's left side to the middle of an element which is above it.

[I'm Element 1]

        | // middle of element 1

        [Element 2 should start at middle of element 1]

Is this possible without writing code, and if yes, how?

Body:
You can align element 2 using constraints. To center an element you can constraint the left side to the left side of element 1 and do the same for the right side. So in xml it would be something like:

<Element2
    android:id="@+id/element2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="@+id/element1"
    app:layout_constraintRight_toRightOf="@+id/element1" />

That should center it horizontally. If you also want to center it vertically simply add the top and bottom constraints.

Edit: Misunderstood the question, if you want to align the left side of an element to the center of another element you can use a GuideLine

Create a Guideline and position it's baseline to the baseline of Element1:

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBaseline_toBaselineOf="@+id/element1"/>

Then align the left side of your element2 to the GuideLine

<Element2
    android:id="@+id/element2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="@+id/guideline" />


问:
Shorthand for extracting a high-dimensional sub-array, i.e. array[beg[0]:end[0],beg[1]:end[1],...]
I am looking for a concise way of extracting a subarray from a high-dimensional array.

For example let's take an array a. I want to extract a subarray, for which I have the beginning and end coordinates stored in two arrays b and e.

Currently, to extract the desired subarray, I type

```<code>a[b[0]:e[0],b[1]:e[1],b[2]:e[2],b[3]:e[3],...]
</code>```

I was wondering if there is a built-in, concise way of slicing such an array. I would love calling something like a[b:e], but this does not work.

答:
zip the two arrays and construct a tuple of slice objects from the resulting tuples from zip:

```<code>from itertools import starmap

a[tuple(starmap(slice, zip(b, e)))]
</code>```

Body:
I am looking for a concise way of extracting a subarray from a high-dimensional array.

For example let's take an array a. I want to extract a subarray, for which I have the beginning and end coordinates stored in two arrays b and e.

Currently, to extract the desired subarray, I type

a[b[0]:e[0],b[1]:e[1],b[2]:e[2],b[3]:e[3],...]

I was wondering if there is a built-in, concise way of slicing such an array. I would love calling something like a[b:e], but this does not work.

Body:
zip the two arrays and construct a tuple of slice objects from the resulting tuples from zip:

from itertools import starmap

a[tuple(starmap(slice, zip(b, e)))]


问:
How to remove .modal-backdrop class from $ionicModal?
I want to remove the .modal-backdrop class from my ionicModal but as the class is automatically added, I am unable to remove it.
I don't want to permanently remove the class. But want to remove it and then add later on.
I tried this:

```<code>angular.element(document.querySelector('div')).removeClass("modal-backdrop");
</code>```

but it is not working.

Can you plz suggest how to do it?

Thanks in advance for any help.

答:
One solution to hide the backdrop is changing the opacity of the backdrop modal when this is active! For that, put the following CSS Styles:</p>

```<code>.active .modal-backdrop-bg {
    opacity: 0;
}
</code>```

Body:
I want to remove the .modal-backdrop class from my ionicModal but as the class is automatically added, I am unable to remove it.
I don't want to permanently remove the class. But want to remove it and then add later on.
I tried this:

angular.element(document.querySelector('div')).removeClass("modal-backdrop");

but it is not working.

Can you plz suggest how to do it?

Thanks in advance for any help.

Body:
One solution to hide the backdrop is changing the opacity of the backdrop modal when this is active! For that, put the following CSS Styles:

.active .modal-backdrop-bg {
    opacity: 0;
}


问:
Experiencing TypeError (expected string or Unicode object, NoneType found) when saving a form instance to request.session
I'm running into trouble trying to save an instance of a form class in Django's request.session dictionary. I get TypeError: expected string or Unicode object, NoneType found. The whole traceback being:

```<code>File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response
    response = middleware_method(request, response)
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 331, in wrapper
    return wrapped(*args, **kwargs)
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/user_sessions/middleware.py", line 46, in process_response
    request.session.save()
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/user_sessions/backends/db.py", line 73, in save
    session_data=self.encode(self._get_session(no_load=must_create)),
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py", line 86, in encode
    pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
TypeError: expected string or Unicode object, NoneType found
</code>```

What's the scenario?

I'm testing form validation for image uploading. I'm disallowing file sizes beyond a certain limit, raising a validation error. The form instance bound to request.POST is saved in request.session, e.g.:

```<code>form = PhotoForm(request.POST,request.FILES)
request.session["photo_form"] = form
request.session.modified = True
</code>```

and then I redirect to a different view to use the said form instance.

I've noticed all this works successfully most of the times, but for certain very, very big files where I'm supposed to raise a validation error, I instead get the error shown above. Not all validation errors result in this. For now, the pattern is that only extremely large files induce this. I can't make sense of that.

Can anyone shed light on what might be going on, and a possible fix? An illustrative answer would be great. My primary use case is to show validation errors on the form in case of erroneous input.

If I print the bound form before assigning it to request.session, here's how it looks for big files that fail validation:

```<code><tr><td colspan="2"><ul class="errorlist"><li>File is beyond acceptable limit (10MB)</li></ul></td></tr>
<tr><th><label for="browse_image_btn">Image:</label></th><td><input accept="image/*" id="browse_image_btn" name="image" style="width: 0.1px;height: 0.1px;opacity: 0;overflow: hidden;position: absolute;z-index: -1;" type="file" /></td></tr>
<tr><th><label for="id_reply">Reply:</label></th><td><textarea autocomplete="off" class="cxl" cols="40" id="id_reply" name="reply" rows="3" style="width:99%;height:70px;border-radius:10px;border: 1px #CFD8DC solid; background-color:#FAFAFA;">
</textarea></td></tr>
</code>```

If I manually try to pickle it using:

```<code>import pickle
request.session["photo_form"] = pickle.dumps(form)
</code>```

I get PicklingError: Can't pickle <built-in method write of file object at 0x7f024f1d9db0>: it's not found as __main__.write

答:
You can try to use pickle to dump form object before putting it into session and load it using pickle from session.

```<code>import pickle
request.session["photo_form"] = pickle.dumps(form)
form = pickle.loads(request.session["photo_form"])
</code>```

Sorry,You can just make simple type data into session。

or Your can put the template output of form object into session if this is enough for you。

for example: The content returned from as_p() method. But essentially in architecture design of Django， form is middle accesing object,it is not designed for storaged，the object to be storaged may be model object or input data. sorry, English is very poor.

Body:
I'm running into trouble trying to save an instance of a form class in Django's request.session dictionary. I get TypeError: expected string or Unicode object, NoneType found. The whole traceback being:

File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response
    response = middleware_method(request, response)
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 331, in wrapper
    return wrapped(*args, **kwargs)
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/user_sessions/middleware.py", line 46, in process_response
    request.session.save()
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/user_sessions/backends/db.py", line 73, in save
    session_data=self.encode(self._get_session(no_load=must_create)),
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py", line 86, in encode
    pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
TypeError: expected string or Unicode object, NoneType found

What's the scenario?

I'm testing form validation for image uploading. I'm disallowing file sizes beyond a certain limit, raising a validation error. The form instance bound to request.POST is saved in request.session, e.g.:

form = PhotoForm(request.POST,request.FILES)
request.session["photo_form"] = form
request.session.modified = True

and then I redirect to a different view to use the said form instance.

I've noticed all this works successfully most of the times, but for certain very, very big files where I'm supposed to raise a validation error, I instead get the error shown above. Not all validation errors result in this. For now, the pattern is that only extremely large files induce this. I can't make sense of that.

Can anyone shed light on what might be going on, and a possible fix? An illustrative answer would be great. My primary use case is to show validation errors on the form in case of erroneous input.

If I print the bound form before assigning it to request.session, here's how it looks for big files that fail validation:

File is beyond acceptable limit (10MB)

Image:	<input accept="image/*" id="browse_image_btn" name="image" style="width: 0.1px;height: 0.1px;opacity: 0;overflow: hidden;position: absolute;z-index: -1;" type="file" />

Reply:	<textarea autocomplete="off" class="cxl" cols="40" id="id_reply" name="reply" rows="3" style="width:99%;height:70px;border-radius:10px;border: 1px #CFD8DC solid; background-color:#FAFAFA;">
</textarea>

If I manually try to pickle it using:

import pickle
request.session["photo_form"] = pickle.dumps(form)

I get PicklingError: Can't pickle <built-in method write of file object at 0x7f024f1d9db0>: it's not found as __main__.write

Body:
You can try to use pickle to dump form object before putting it into session and load it using pickle from session.

import pickle
request.session["photo_form"] = pickle.dumps(form)
form = pickle.loads(request.session["photo_form"])

Sorry,You can just make simple type data into session。

or Your can put the template output of form object into session if this is enough for you。

for example: The content returned from as_p() method. But essentially in architecture design of Django， form is middle accesing object,it is not designed for storaged，the object to be storaged may be model object or input data. sorry, English is very poor.


问:
portable print and compare pthread_t
What I actually need is portable compare and print for *nix pthread identifiers (pthread_t).
pthread_equal function exists to compare two thread id's for equality, however it's not possible to compare them with operators < <= >= > (portable I mean of course) because on some of implementations pthread_t is a pointer to structure. So I found solution which I would like to share and discuss it's portability.

Suppose we have thred_id class wrapper, which should be less-then-comparable, equality-comparable and of course printable. I'm making template class with two partial specialization - one for pointers and one for arithmetic types

```<code>template <typename T, bool A = is_arithmetic<T>::value>
struct hash
{
    static unsigned long calculate(T thread_id)
    {
        return hash<T*, A>::calculate(&thread_id);
    }
};

template <typename T>
struct hash<T*, false>
{
    static unsigned long calculate(T* thread_id)
    {
        std::size_t hash = 0;
        if (char* data = reinterpret_cast<char*>(thread_id))
        {
            for (int i = 0; i < sizeof(T); ++i)
            {
                hash = (hash << 6) ^ (hash >> 26) ^ data[i];
            }
        }
        return hash;
    }
};

template <typename T>
struct hash<T, true>
{
    static unsigned long calculate(T thread_id)
    {
        return static_cast<unsigned long>(thread_id);
    }
};
</code>```

So how does it work. If we need to compare two thread ids we just simply call

```<code>pthread_equal(tid1, tid2);
</code>```

but for operator < we use hash to compare

```<code>hash<pthread_t>::calculate(tid1) < hash<pthread_t>::calculate(tid2)
</code>```

So here

if pthread_t is implemented as a pointer then we will calculate hash for the pointed object.

If it is arithmetic type then we will just try to cast it to unsigned int.

If it is implemented as a structure - we will calculate hash for the structure object itself.

Hash value is going to be used only for operator less and thread id output.

What do you think of it? How portable is this solution and is there anything better then that?

Thanks everybody in advance.

答:
Data type of pthread_t is not fixed by standard, threfore I guess pthread_compare() is provided.

In my appl I also maps pthread_t to some unique id, as Mark proposed.

See here

Title: portable print and compare pthread_t

Body:
What I actually need is portable compare and print for *nix pthread identifiers (pthread_t).
pthread_equal function exists to compare two thread id's for equality, however it's not possible to compare them with operators < <= >= > (portable I mean of course) because on some of implementations pthread_t is a pointer to structure. So I found solution which I would like to share and discuss it's portability.

Suppose we have thred_id class wrapper, which should be less-then-comparable, equality-comparable and of course printable. I'm making template class with two partial specialization - one for pointers and one for arithmetic types

template <typename T, bool A = is_arithmetic<T>::value>
struct hash
{
    static unsigned long calculate(T thread_id)
    {
        return hash<T*, A>::calculate(&thread_id);
    }
};

template <typename T>
struct hash<T*, false>
{
    static unsigned long calculate(T* thread_id)
    {
        std::size_t hash = 0;
        if (char* data = reinterpret_cast<char*>(thread_id))
        {
            for (int i = 0; i < sizeof(T); ++i)
            {
                hash = (hash << 6) ^ (hash >> 26) ^ data[i];
            }
        }
        return hash;
    }
};

template <typename T>
struct hash<T, true>
{
    static unsigned long calculate(T thread_id)
    {
        return static_cast<unsigned long>(thread_id);
    }
};

So how does it work. If we need to compare two thread ids we just simply call

pthread_equal(tid1, tid2);

but for operator < we use hash to compare

hash<pthread_t>::calculate(tid1) < hash<pthread_t>::calculate(tid2)

So here

if pthread_t is implemented as a pointer then we will calculate hash for the pointed object.

If it is arithmetic type then we will just try to cast it to unsigned int.

If it is implemented as a structure - we will calculate hash for the structure object itself.

Hash value is going to be used only for operator less and thread id output.

What do you think of it? How portable is this solution and is there anything better then that?

Thanks everybody in advance.


问:
StopPropagation in HTML with Angular
I am having a problem with stopPropagation, I don't know how to write in html and typescript for angular.
It opens the dialog but at the same time makes a propagation.

Here is my code in HTML:

```<code><label for="tab-two">PROJECTS
    <a class="plus" (click)="opentestdialog()">+</a>
</label>
</code>```

And here is my code in TypeScript:

```<code>opentestdialog() {
    this.dialog.open(TestdialogComponent);
}
</code>```

答:
```<code>(click)="$event.stopPropagation();opentestdialog()"
</code>```

or

```<code>(click)="opentestdialog($event)"
</code>```

```<code>opentestdialog(e) {
  e.stopPropagation()
  this.dialog.open(TestdialogComponent);
}
</code>```

Title: StopPropagation in HTML with Angular

Body:
I am having a problem with stopPropagation, I don't know how to write in html and typescript for angular.
It opens the dialog but at the same time makes a propagation.

Here is my code in HTML:

PROJECTS
    +

And here is my code in TypeScript:

opentestdialog() {
    this.dialog.open(TestdialogComponent);
}

Body:
(click)="$event.stopPropagation();opentestdialog()"

or

(click)="opentestdialog($event)"

opentestdialog(e) {
  e.stopPropagation()
  this.dialog.open(TestdialogComponent);
}


问:
want to remove legend in mpAndroidchart graph
want to remove legend in mpAndroidchart graph

答:
Following code is solution for you!
    BarChart barchart = (BarChart) findViewById(R.id.mybarchart);</p>

```<code>barchart.getLegend().setEnabled(false);
</code>```

Body:
Following code is solution for you!
    BarChart barchart = (BarChart) findViewById(R.id.mybarchart);

barchart.getLegend().setEnabled(false);


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

答:
When you call floor, you have to deal with different subtypes of numbers: the code divides a float by an integer (that may involve coercing the integer as a float), and then have to coerce the result back to an integer. This is the amount of work that must be done, correctly, and you are unlikely to bypass it if you don't restrict your input types.

If instead you use ffloor, then the primary result is a float (you can still round it to an integer later,  when you really need it (e.g. convert to pixels coordinates)). The following code does not give compilation notes:

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

You may even declare div as being a float, which would push the responsibility of providing appropriately typed values (and performing runtime checks) to the callers.

Note also that you should probably (declaim (inline test-floor)) before you define the function; that helps because then the compiler can put shortcuts in the code to avoid checking input parameter types and boxing results.

Edit:

The range of a float cover a large possible domain (due to the exponent): more densely packed near zero, more spaced towards infinity. Integer values are linearly spaced, but cover a smaller range with the same number of bits. So if you want to guarantee your output fits in a fixnum, you have to make sure the float in your inputs does not go outside the range of fixnum, too. I tried the following:

```<code>(defun test-round (x)
  (declare (type (single-float #.(float most-negative-fixnum 0f0)
                               #.(float (/ most-positive-fixnum 2) 0f0)) x)
           (optimize (speed 3)))
  (round x))
</code>```

I had to half the upper range of the floats because when you test:

```<code>(typep (round (coerce most-positive-fixnum 'single-float)) 'fixnum)
</code>```

... it returns NIL. I don't have much time to see why this happens, but this depends on your implementation and architecture. Taking half the most positive fixnum ensures the value is low enough to be converted as a fixnum. Now, I have no more compilation notes.

(the same goes for (signed-byte 64)))

NB. Unlike in the above example, you should use deftype and avoid repeating the same declarations everywhere.

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:
When you call floor, you have to deal with different subtypes of numbers: the code divides a float by an integer (that may involve coercing the integer as a float), and then have to coerce the result back to an integer. This is the amount of work that must be done, correctly, and you are unlikely to bypass it if you don't restrict your input types.

If instead you use ffloor, then the primary result is a float (you can still round it to an integer later,  when you really need it (e.g. convert to pixels coordinates)). The following code does not give compilation notes:

(defun test-floor (x div)
  (declare (type single-float x)
           (type fixnum div)
           (optimize (speed 3)))
  (ffloor x div))

You may even declare div as being a float, which would push the responsibility of providing appropriately typed values (and performing runtime checks) to the callers.

Note also that you should probably (declaim (inline test-floor)) before you define the function; that helps because then the compiler can put shortcuts in the code to avoid checking input parameter types and boxing results.

Edit:

The range of a float cover a large possible domain (due to the exponent): more densely packed near zero, more spaced towards infinity. Integer values are linearly spaced, but cover a smaller range with the same number of bits. So if you want to guarantee your output fits in a fixnum, you have to make sure the float in your inputs does not go outside the range of fixnum, too. I tried the following:

(defun test-round (x)
  (declare (type (single-float #.(float most-negative-fixnum 0f0)
                               #.(float (/ most-positive-fixnum 2) 0f0)) x)
           (optimize (speed 3)))
  (round x))

I had to half the upper range of the floats because when you test:

(typep (round (coerce most-positive-fixnum 'single-float)) 'fixnum)

... it returns NIL. I don't have much time to see why this happens, but this depends on your implementation and architecture. Taking half the most positive fixnum ensures the value is low enough to be converted as a fixnum. Now, I have no more compilation notes.

(the same goes for (signed-byte 64)))

NB. Unlike in the above example, you should use deftype and avoid repeating the same declarations everywhere.