问:
why does this code give error as actual formal parameter?
```<code> class A {
    int a, b;

    A(int i, int j) {
        a = i;
        b = j;
    }
}

class B extends A {
    int c, d;

    B(int i, int j) {
        c = i;
        d = j;
    }
}

public class HelloWorld {

    public static void main(String[] args) {
        A aa = new A(5, 6);
        B bb = new B(3, 4);
        System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);

    }
}
</code>```

<p>it gives error as </p>

```<code>HelloWorld.java:9: error: constructor A in class A cannot be applied to given types;
{
^
  required: int,int
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error
</code>```

答:
As you class B extends class A, you somewhere have to call the constructor of the class you are extending.

As your class A does not have a constructor with no arguments, you need to explicitly call the super constructor (the constructor from class A) as the first statement inside the constructor of your class B:

```<code>B(int i, int j) {
  super(i, j);
  // Your code
}
</code>```

If you would have a no-args constructor in A, you would not need to do this, as the no-args constructor is implicitly called if no constructor call is specified:

```<code>B(int i, int j) {
  // Your code
}
</code>```

Is actually doing:

```<code>B() {
  super();
  // Your code
}
</code>```

And as you do not have A() as a constructor, you get the error.

Body:
 class A {
    int a, b;

    A(int i, int j) {
        a = i;
        b = j;
    }
}

class B extends A {
    int c, d;

    B(int i, int j) {
        c = i;
        d = j;
    }
}

public class HelloWorld {

    public static void main(String[] args) {
        A aa = new A(5, 6);
        B bb = new B(3, 4);
        System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);

    }
}

it gives error as

HelloWorld.java:9: error: constructor A in class A cannot be applied to given types;
{
^
  required: int,int
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

Body:
As you class B extends class A, you somewhere have to call the constructor of the class you are extending.

As your class A does not have a constructor with no arguments, you need to explicitly call the super constructor (the constructor from class A) as the first statement inside the constructor of your class B:

B(int i, int j) {
  super(i, j);
  // Your code
}

If you would have a no-args constructor in A, you would not need to do this, as the no-args constructor is implicitly called if no constructor call is specified:

B(int i, int j) {
  // Your code
}

Is actually doing:

B() {
  super();
  // Your code
}

And as you do not have A() as a constructor, you get the error.


来源: stackexchange

问:
Kafka and Microservices using Producer Consumer

I need to use Apache Kafka in my project of Micro-Services. I need my one micro-service to produce data and another to consume the same data. How can I make Kafka do the same between the two services

答:
I would recommend you to take a look at Spring Cloud Stream as it does exactly what you need.

From docs:

Framework for building message-driven microservices. Spring Cloud Stream builds upon Spring Boot to create DevOps friendly microservice applications and Spring Integration to provide connectivity to message brokers. Spring Cloud Stream provides an opinionated configuration of message brokers, introducing the concepts of persistent pub/sub semantics, consumer groups and partitions across several middleware vendors. This opinionated configuration provides the basis to create stream processing applications.

By adding @EnableBinding to your main application, you get immediate connectivity to a message broker and by adding @StreamListener to a method, you will receive events for stream processing.

ContentLicense: CC BY-SA 3.0


问:
Tap Gesture on List View Items
I am trying to open another view after tapping on an item in the list view.
I have tried adding a TapGestureRegonizer and even adding ViewCell with grids etc. None of these seem to work. I have added a tap gesture to a label and that seemed to work but the same does not work for list view items. This seems like a simple problem for something like list view, but there doesnt seem to be a built in functionality for this.

The Xaml:

```<code><ListView x:Name="dataList"
      ItemsSource="{Binding routeLabels}"
      HasUnevenRows="True"
      Grid.Row="1"
      Grid.Column="0"
      Grid.ColumnSpan="3">
</ListView>
</code>```

The code behind:

```<code>var listviewgesture = new TapGestureRecognizer();
listviewgesture.SetBinding(TapGestureRecognizer.CommandProperty,"LoadRoutePage");
dataList.GestureRecognizers.Add(listviewgesture);
</code>```

The view model:

```<code>public ICommand LoadRoutePage { get; protected set; }

public DriverDashboardViewModel(INavigation navigation,MessagDatabase database)
    {
        this._database = database;
        this.Navigation = navigation;
        this.LoadNotifications = new Command(async () => await OpenNotificationsPage());
        this.LoadRoutePage = new Command(async () => await OpenRoutePage());

    }

public async Task OpenRoutePage()
    {

        await Navigation.PushAsync(new RoutePageView());
    }
</code>```

Just to be clear the LoadNotifications method does work in opening a page but LoadRoutePage does not. So I know there is some level of communication between the view and viewmodel.

答:
You should not be adding a TapGestureRecognizer to a ListView. Every cell already has events that handle tapping on them and a GestureRecognizer would probably only confuse the ListView regarding what the tap should be doing. There are a few ways to go about this.

1. SelectedItem binding

Bind a SelectedItem property to the ListView and handle your method calls in the setter of that property.

```<code><ListView x:Name="dataList" ItemsSource="{Binding routeLabels}"
          HasUnevenRows="True" Grid.Row="1" Grid.Column="0"
          Grid.ColumnSpan="3" SelectedItem="{Binding SelectedItem}">
</ListView>
</code>```

And in your viewmodel:

```<code>string _selectedItem;

public string SelectedItem {
    get {return _selectedItem; }
    set
    {
        _selectedItem = value;
        // Additional code
    }
}
</code>```

2. Use the built in events ItemSelected or ItemTapped

A ListView has some events you can hook up named ItemSelected and ItemTapped. These can be caught in code-behind and can handle what you're trying to achieve.

```<code><ListView x:Name="dataList" ItemsSource="{Binding routeLabels}"
          HasUnevenRows="True" Grid.Row="1" Grid.Column="0"
          Grid.ColumnSpan="3" ItemSelected="Handle_ItemSelected" ItemTapped="Handle_ItemTapped">
</ListView>
</code>```

3. Use event to command binding with behaviors

Since you use viewmodels you ideally don't want these events since they're handled on the UI side. There are NuGet packages out there that can translate an event to a Command that you can handle in your viewmodel. Take a look at Corcav.Behaviors for example.

4. Create a behavior of your own

I have one I use regularly which looks like this:

```<code>public class ListViewSelectedItemBehavior : Behavior<ListView>
{
    public static readonly BindableProperty CommandProperty = BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(ListViewSelectedItemBehavior));

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public ListView AssociatedObject { get; private set; }

    protected override void OnAttachedTo(ListView bindable)
    {
        base.OnAttachedTo(bindable);
        AssociatedObject = bindable;
        bindable.BindingContextChanged += OnBindingContextChanged;
        bindable.ItemSelected += OnListViewItemSelected;
    }

    protected override void OnDetachingFrom(ListView bindable)
    {
        base.OnDetachingFrom(bindable);
        bindable.BindingContextChanged -= OnBindingContextChanged;
        bindable.ItemSelected -= OnListViewItemSelected;
        AssociatedObject = null;
    }

    private void OnBindingContextChanged(object sender, EventArgs e)
    {
        OnBindingContextChanged();
    }

    private void OnListViewItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        if (Command == null)
            return;

        if (Command.CanExecute(e.SelectedItem))
            Command.Execute(e.SelectedItem);
    }

    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();
        BindingContext = AssociatedObject.BindingContext;
    }
}
</code>```

To add this to your ListView you simply add a behavior to it:

```<code><ListView x:Name="dataList" ItemsSource="{Binding routeLabels}"
          HasUnevenRows="True" Grid.Row="1" Grid.Column="0"
          Grid.ColumnSpan="3">
    <ListView.Behaviors>
        <behaviors:ListViewSelectedItemBehavior Command="{Binding ItemSelectedCommand}" />
    </ListView.Behaviors>
</ListView>
</code>```

In this case ItemSelectedCommand is a Command object in your ViewModel.

Title: Tap Gesture on List View Items

Body:
I am trying to open another view after tapping on an item in the list view.
I have tried adding a TapGestureRegonizer and even adding ViewCell with grids etc. None of these seem to work. I have added a tap gesture to a label and that seemed to work but the same does not work for list view items. This seems like a simple problem for something like list view, but there doesnt seem to be a built in functionality for this.

The Xaml:

<ListView x:Name="dataList"
      ItemsSource="{Binding routeLabels}"
      HasUnevenRows="True"
      Grid.Row="1"
      Grid.Column="0"
      Grid.ColumnSpan="3">
</ListView>

The code behind:

var listviewgesture = new TapGestureRecognizer();
listviewgesture.SetBinding(TapGestureRecognizer.CommandProperty,"LoadRoutePage");
dataList.GestureRecognizers.Add(listviewgesture);

The view model:

public ICommand LoadRoutePage { get; protected set; }

public DriverDashboardViewModel(INavigation navigation,MessagDatabase database)
    {
        this._database = database;
        this.Navigation = navigation;
        this.LoadNotifications = new Command(async () => await OpenNotificationsPage());
        this.LoadRoutePage = new Command(async () => await OpenRoutePage());

    }

public async Task OpenRoutePage()
    {

        await Navigation.PushAsync(new RoutePageView());
    }

Just to be clear the LoadNotifications method does work in opening a page but LoadRoutePage does not. So I know there is some level of communication between the view and viewmodel.

Body:
You should not be adding a TapGestureRecognizer to a ListView. Every cell already has events that handle tapping on them and a GestureRecognizer would probably only confuse the ListView regarding what the tap should be doing. There are a few ways to go about this.

1. SelectedItem binding

Bind a SelectedItem property to the ListView and handle your method calls in the setter of that property.

<ListView x:Name="dataList" ItemsSource="{Binding routeLabels}"
          HasUnevenRows="True" Grid.Row="1" Grid.Column="0"
          Grid.ColumnSpan="3" SelectedItem="{Binding SelectedItem}">
</ListView>

And in your viewmodel:

string _selectedItem;

public string SelectedItem {
    get {return _selectedItem; }
    set
    {
        _selectedItem = value;
        // Additional code
    }
}

2. Use the built in events ItemSelected or ItemTapped

A ListView has some events you can hook up named ItemSelected and ItemTapped. These can be caught in code-behind and can handle what you're trying to achieve.

<ListView x:Name="dataList" ItemsSource="{Binding routeLabels}"
          HasUnevenRows="True" Grid.Row="1" Grid.Column="0"
          Grid.ColumnSpan="3" ItemSelected="Handle_ItemSelected" ItemTapped="Handle_ItemTapped">
</ListView>

3. Use event to command binding with behaviors

Since you use viewmodels you ideally don't want these events since they're handled on the UI side. There are NuGet packages out there that can translate an event to a Command that you can handle in your viewmodel. Take a look at Corcav.Behaviors for example.

4. Create a behavior of your own

I have one I use regularly which looks like this:

public class ListViewSelectedItemBehavior : Behavior<ListView>
{
    public static readonly BindableProperty CommandProperty = BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(ListViewSelectedItemBehavior));

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public ListView AssociatedObject { get; private set; }

    protected override void OnAttachedTo(ListView bindable)
    {
        base.OnAttachedTo(bindable);
        AssociatedObject = bindable;
        bindable.BindingContextChanged += OnBindingContextChanged;
        bindable.ItemSelected += OnListViewItemSelected;
    }

    protected override void OnDetachingFrom(ListView bindable)
    {
        base.OnDetachingFrom(bindable);
        bindable.BindingContextChanged -= OnBindingContextChanged;
        bindable.ItemSelected -= OnListViewItemSelected;
        AssociatedObject = null;
    }

    private void OnBindingContextChanged(object sender, EventArgs e)
    {
        OnBindingContextChanged();
    }

    private void OnListViewItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        if (Command == null)
            return;

        if (Command.CanExecute(e.SelectedItem))
            Command.Execute(e.SelectedItem);
    }

    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();
        BindingContext = AssociatedObject.BindingContext;
    }
}

To add this to your ListView you simply add a behavior to it:

<ListView x:Name="dataList" ItemsSource="{Binding routeLabels}"
          HasUnevenRows="True" Grid.Row="1" Grid.Column="0"
          Grid.ColumnSpan="3">
    <ListView.Behaviors>
        <behaviors:ListViewSelectedItemBehavior Command="{Binding ItemSelectedCommand}" />
    </ListView.Behaviors>
</ListView>

In this case ItemSelectedCommand is a Command object in your ViewModel.


问:
What does yarn --prefer-offline do?
I assume when I install npm package say react for the first time with

```<code>yarn add react
</code>```

this will save react file in local cache. I found .yarn-cache to contain many files. I assume it is yarn local cache folder so that when I install react again in the future, it will be installed from local cache, no??

If I need to install react again in the future, should I simply write this:

```<code>yarn add react
</code>```

or this:

```<code>yarn add react --prefer-offline
</code>```

答:
My understanding is that by default, yarn will always try to download the package from the internet when you install/restore it, and will also store that in the cache, which means that in the future if you try to install/restore and don't have an internet connection, it can fall back on the cache and install from there if necessary. By specifying --prefer-offline, you are reversing this behaviour so that it will check the cache first, and only try to download the package from the internet if it cannot find it in the cache. This can make your install/restores significantly quicker, and will allow you perform repeatable builds, but you may not get the latest versions available (e.g. if you're using version specs like ~1.2.3). There is also an --offline option, which will throw an error if it can't find a package in your local cache (i.e. it won't ever try to download from the internet).

More info at https://yarnpkg.com/blog/2016/11/24/offline-mirror/

ContentLicense: CC BY-SA 4.0

Title: What does yarn --prefer-offline do?

Body:
I assume when I install npm package say react for the first time with

yarn add react

this will save react file in local cache. I found .yarn-cache to contain many files. I assume it is yarn local cache folder so that when I install react again in the future, it will be installed from local cache, no??

If I need to install react again in the future, should I simply write this:

yarn add react

or this:

yarn add react --prefer-offline


问:
Powershell: regex replacement with inline calculation
I have the files named with yyyymm and I need to rename this files with mmyyyy but the mm in the new name have to be less for a one. And I need to do it inline during the replacement process.

I can do regex replace of the string abc201706.txt to the abc062017.txt with pattern

'abc201706.txt' -replace '^(.*)([0-9]{4})([0-9]{2})(\..*)$','$1$3$2$4'

How can I do regex replace to the abc052017.txt?

In other words I need inline subtraction of the one month from $3 which means the initial month.

I have searched for the answer to my question a lot of posts but without the result. Please do not mark my question as duplicate and answer to it.

答:
One way to do it is to use .NET regex match evaluators, basically callback functions that can calculate the replacement value.

Powershell script blocks can be used as match evaluators. They receive the match object as first argument and the value they produce will be used as the replacement.

```<code>Get-ChildItem -Filter "*.txt" | Foreach-Object {
    $_.Name = [Regex]::Replace($_.Name, "(\d{6})(\.txt)$", {
        $match = $args[0]
        try {
            [DateTime]::ParseExact($match.Groups[1], "yyyyMM", $null).AddMonths(-1).ToString("MMyyyy") + $match.Groups[2]
        } catch {
            $match
        }
    })
}
</code>```

The try block attempts to parse the six digits from match group 1 as a DateTime, subtracts a month and puts everything back together again.

The catch block simply outputs the original match in case the conversion to DateTime fails.

Body:
One way to do it is to use .NET regex match evaluators, basically callback functions that can calculate the replacement value.

Powershell script blocks can be used as match evaluators. They receive the match object as first argument and the value they produce will be used as the replacement.

Get-ChildItem -Filter "*.txt" | Foreach-Object {
    $_.Name = [Regex]::Replace($_.Name, "(\d{6})(\.txt)$", {
        $match = $args[0]
        try {
            [DateTime]::ParseExact($match.Groups[1], "yyyyMM", $null).AddMonths(-1).ToString("MMyyyy") + $match.Groups[2]
        } catch {
            $match
        }
    })
}

The try block attempts to parse the six digits from match group 1 as a DateTime, subtracts a month and puts everything back together again.

The catch block simply outputs the original match in case the conversion to DateTime fails.


问:
avplayer not loading https url
Downloaded ios 11 beta 2 today, app is not loading urls coming from facebook.

I thought it was related to app transport security but since urls are linking to https adresses it shouldn't be a problem?

Any thoughts?

答:
So apple developper certificate was expired and it seems an unsigned app cannot load https url with avplayer.

As long as you don't choose another team to sign your app you will still try to sign it with your previous team even though the certificate is expired and you won't have an error at compile time, which is why I didn't see it in the first place

Title: avplayer not loading https url


问:
Sql: average of a dates
I have to write a query to calculate the average number days between the shopping for each customer(without using subqueries).

```<code>    create table data {
customer varchar(20) not null,
bought date not null,
primary key (customer,bought)
}
</code>```

For example,

```<code>insert into data (customer,bought)
values (‘John Smith’, date ‘2011-02-01’),
(‘Alice Cooper’, date ‘2011-02-01’),
(‘Bob Baker’, date ‘2011-02-01’),
(‘John Smith’, date ‘2011-02-02’),
(‘Bob Baker’, date ‘2011-02-02’),
(‘Bob Baker’, date ‘2011-02-03’),
(‘Bob Baker’, date ‘2011-02-04’),
(‘Bob Baker’, date ‘2011-02-05’),
(‘Bob Baker’, date ‘2011-02-06’),
(‘Bob Baker’, date ‘2011-02-07’),
(‘John Smith’, date ‘2011-02-07’),
(‘Alice Cooper’, date ‘2011-02-08’);
</code>```

should return that John Smith waited 1 day then 5 days, so his average is 3 days. Alice Cooper(!) waited 7 days so her
average is 7. Bob Baker is a daily runner so his average is 1.

I have done something like this

```<code>select distinct customer, avg (bought) as average from data;
</code>```

but it doesn't work.

Any help will be greatly appreciated.

答:
selecting max-min/count is NOT the average. try:</p>

```<code> timestamp 'epoch' + avg(date_part(epoch, date_column))  * interval '1 second'
</code>```

ContentLicense: CC BY-SA 2.5

Title: Sql: average of a dates

Body:
I have to write a query to calculate the average number days between the shopping for each customer(without using subqueries).

    create table data {
customer varchar(20) not null,
bought date not null,
primary key (customer,bought)
}

For example,

insert into data (customer,bought)
values (‘John Smith’, date ‘2011-02-01’),
(‘Alice Cooper’, date ‘2011-02-01’),
(‘Bob Baker’, date ‘2011-02-01’),
(‘John Smith’, date ‘2011-02-02’),
(‘Bob Baker’, date ‘2011-02-02’),
(‘Bob Baker’, date ‘2011-02-03’),
(‘Bob Baker’, date ‘2011-02-04’),
(‘Bob Baker’, date ‘2011-02-05’),
(‘Bob Baker’, date ‘2011-02-06’),
(‘Bob Baker’, date ‘2011-02-07’),
(‘John Smith’, date ‘2011-02-07’),
(‘Alice Cooper’, date ‘2011-02-08’);

should return that John Smith waited 1 day then 5 days, so his average is 3 days. Alice Cooper(!) waited 7 days so her
average is 7. Bob Baker is a daily runner so his average is 1.

I have done something like this

select distinct customer, avg (bought) as average from data;

but it doesn't work.

Any help will be greatly appreciated.

Body:
selecting max-min/count is NOT the average. try:

 timestamp 'epoch' + avg(date_part(epoch, date_column))  * interval '1 second'


问:
solr faceted search - how do I specify multiple fields on the Solr Query UI?
I'm a newbie to solr and tying my hands at solr.
Can some one here please explain how to specify multiple facet fields for a given search.

I'm using the Solr Admin UI/ query ink and it allows me to specify only one field.
I would however like to facet on multiple fields like region industry stock-exchange etc on my company search.

I have gone through the solr wiki and relevant doc links like the one below
http://docs.lucidworks.com/display/solr/Query+Screen

but none of them seem to explain how to specify multiple fields.
I want to build something like the usual Amazon/Walmart etc search ui that provides multiple facets and counts when trying to search for a product on my planned cmpany search page.

答:
You are looking for json.facet

It's available from solr 5(some advanced features are available from solr 6).
Basically that means you can insert your facet search parameters via json to the url.

It looks like this(live example):

```<code>&facet=true&json.facet={"filed1":{"type":"terms","field":"filed1","limit":2000},"filed2":{"type":"terms","field":"filed2","limit":2000}}
</code>```

There is also a shorter version:

```<code>&facet=true&json.facet={"field1":{"terms":"field1"},"field2":{"terms":"field2"}}
</code>```

You can find more information here

Body:
You are looking for json.facet

It's available from solr 5(some advanced features are available from solr 6).
Basically that means you can insert your facet search parameters via json to the url.

It looks like this(live example):

&facet=true&json.facet={"filed1":{"type":"terms","field":"filed1","limit":2000},"filed2":{"type":"terms","field":"filed2","limit":2000}}

There is also a shorter version:

&facet=true&json.facet={"field1":{"terms":"field1"},"field2":{"terms":"field2"}}

You can find more information here


问:
RoR app deployed on Heroku and working with SQL Server database
Is it feasible to have a Ruby on Rails app, which is:

a) deployed on Heroku, and

b) working with a remote SQL Server database?

I take it that I'll need unixODBC installed on Heroku, but I cannot find a way to do so. Is this possible?
Or, is there any other way (without ODBC?) to accomplish this?

Thank you very much for any guidance or tip.

Updated:
Some info on the subject:

1) Heroku pre-installs both unixODBC and FreeTDS by default, so you already have them.

2) Also, it is possible to run shell commands via Heroku Console in backticks, e.g.:

```<code>  heroku console
  `odbcinst`
</code>```

(runs "odbcinst" command in Heroku shell and shows the result)

3) You do not have access to filesystem outside of your slice where the packages are installed. If you only need a driver path, Heroku support can provide it (/usr/lib/odbc/libtdsodbc.so in my case).

4) You cannot run sudo commands in Heroku shell.

At the moment, to connect to MS SQL Server you at least need to append  ‘freetds.conf’ file. Even when using tinyTDS (there is an open ticket#2 in tinyTDS gitgub issue page). DSN-less connection instructions from "wiki.rubyonrails.org SLASH database-support SLASH ms-sql" didn’t work for me, I guess this connection requires some extra-configuration either.

‘freetds.conf’ cannot be modified without sudo. Therefore, I conclude that currently there is no way to make MS SQL and Heroku work together.

I’ve managed to set up this connection with EngineYard and activerecord-sqlserver-adapter.

I followed these instructions:
https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/wiki/Platform-Installation---Ubuntu
(there are only some filepath differences, e.g. ‘odbc.ini’ is located in ‘/etc/unicodbc’, not in ‘/etc’ - this is easy to work out).

I installed 'unixODBC' and 'freetds' packages using EY Unix Packages feature, and made all configurations manually through SSH. Sudo is available in EY (no password required). There is also Chef Recepes feature to automate those configurations (seems to be pretty easy, I'm going to try it tomorrow).

Hope this is helpful.

答:
It is possible.

Because Heroku copies/symlinks its own config/database.yml over whatever you supply in your repository, you may need to take additional steps (e.g. in config/environments/production.rb or in config/initializers/remote_mssql_from_heroku.rb) to set up your application appropriately.

You will face the challenge, however, that traffic from Heroku to your MSSQL database will traverse the public internet. By default, this traffic will not be encrypted. Potentially everyone in the world will be able to monitor your traffic between your Heroku application and your database, and even alter the traffic in-flight, whether for benign or malicious purpose, without you being able to detect it. MS SQL offers the capability to connect over SSL. This capability requires explicit configuration in the MSSQL server, so you must be able to access and modify that configuration. Additionally, this configuration requires that your client library be up-to-date and capable of talking with MSSQL over SSL. Note that MSSQL server will enforce that your server certificate list a Common Name or Subject Alternative Name exactly matching or wildcard-matching the server's FQDN (at least, the FQDN that the server knows about), and that the client use an FQDN for the server exactly matching or wildcard-matching one of the names on the certificate.

Body:
Is it feasible to have a Ruby on Rails app, which is:

a) deployed on Heroku, and

b) working with a remote SQL Server database?

I take it that I'll need unixODBC installed on Heroku, but I cannot find a way to do so. Is this possible?
Or, is there any other way (without ODBC?) to accomplish this?

Thank you very much for any guidance or tip.

Updated:
Some info on the subject:

1) Heroku pre-installs both unixODBC and FreeTDS by default, so you already have them.

2) Also, it is possible to run shell commands via Heroku Console in backticks, e.g.:

  heroku console
  `odbcinst`

(runs "odbcinst" command in Heroku shell and shows the result)

3) You do not have access to filesystem outside of your slice where the packages are installed. If you only need a driver path, Heroku support can provide it (/usr/lib/odbc/libtdsodbc.so in my case).

4) You cannot run sudo commands in Heroku shell.

At the moment, to connect to MS SQL Server you at least need to append  ‘freetds.conf’ file. Even when using tinyTDS (there is an open ticket#2 in tinyTDS gitgub issue page). DSN-less connection instructions from "wiki.rubyonrails.org SLASH database-support SLASH ms-sql" didn’t work for me, I guess this connection requires some extra-configuration either.

‘freetds.conf’ cannot be modified without sudo. Therefore, I conclude that currently there is no way to make MS SQL and Heroku work together.

I’ve managed to set up this connection with EngineYard and activerecord-sqlserver-adapter.

I followed these instructions:
https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/wiki/Platform-Installation---Ubuntu
(there are only some filepath differences, e.g. ‘odbc.ini’ is located in ‘/etc/unicodbc’, not in ‘/etc’ - this is easy to work out).

I installed 'unixODBC' and 'freetds' packages using EY Unix Packages feature, and made all configurations manually through SSH. Sudo is available in EY (no password required). There is also Chef Recepes feature to automate those configurations (seems to be pretty easy, I'm going to try it tomorrow).

Hope this is helpful.


问:
Double for loop MATLAB
I need to do an estimation procedure for n time series (n vectors of T observations). I have the formula to evaluate my variable (using a for loop) but I need to repeat this n times (the number of vectors).

```<code>h0 = var(residuals);
ht=zeros(T,n); ht(T,1)=h0;
for i=2:T
    ht(i) = theta(1) + theta(2)*residuals(i-1)^2 + theta(3)*ht(i-1);
end
</code>```

So this loop calculates ht for all of the observations in series one, but I need another for loop that helps me to use this formula for all of the series.

Edit: This is what I've done based on the below answer:

```<code>function ht = VarEQ(theta,residuals)
    [T,n] = size(residuals)
    for k=1:n
        h0 = var(residuals(:,k));
        ht=zeros(T,n); ht(1,k)=h0;
        for i=2:T
            ht(i,k) = theta(1,k) + theta(2,k)*residuals(i-1,k)^2 + theta(3,k)*ht(i-1,k);
        end
    end
end
</code>```

Current problem:
Now ht is all columns of zero and just the last column of correct values.

Variables

var is a 1xn row vector of variances. Using k, I want just the scalar for each residual.

theta is a 3xn matrix of parameters.

residuals is a Txn matrix.

答:
This seems simple given what you already have set up:

```<code>function ht = VarEQ(theta,residuals)
    [T,n] = size(residuals)
    ht=zeros(T,n);  % Initialise matrix OUTSIDE loop so it isn't over-written!
    for k=1:n       % additional loop for series 1 to n
        ht(1,k) = var(residuals(:,k));;
        for i = 2:T
            % Ensure you are referencing the kth series
            ht(i,k) = theta(1,k) + theta(2,k)*residuals(i-1,k)^2 + theta(3,k)*ht(i-1,k);
        end
    end
end
</code>```

Note: previously, all columns of ht were the same, because theta and residuals were the same for each series!

With your updated code, and the updated code in this answer, that has been fixed.

Title: Double for loop MATLAB

Body:
I need to do an estimation procedure for n time series (n vectors of T observations). I have the formula to evaluate my variable (using a for loop) but I need to repeat this n times (the number of vectors).

h0 = var(residuals);
ht=zeros(T,n); ht(T,1)=h0;
for i=2:T
    ht(i) = theta(1) + theta(2)*residuals(i-1)^2 + theta(3)*ht(i-1);
end

So this loop calculates ht for all of the observations in series one, but I need another for loop that helps me to use this formula for all of the series.

Edit: This is what I've done based on the below answer:

function ht = VarEQ(theta,residuals)
    [T,n] = size(residuals)
    for k=1:n
        h0 = var(residuals(:,k));
        ht=zeros(T,n); ht(1,k)=h0;
        for i=2:T
            ht(i,k) = theta(1,k) + theta(2,k)*residuals(i-1,k)^2 + theta(3,k)*ht(i-1,k);
        end
    end
end

Current problem:
Now ht is all columns of zero and just the last column of correct values.

Variables

var is a 1xn row vector of variances. Using k, I want just the scalar for each residual.

theta is a 3xn matrix of parameters.

residuals is a Txn matrix.

Body:
This seems simple given what you already have set up:

function ht = VarEQ(theta,residuals)
    [T,n] = size(residuals)
    ht=zeros(T,n);  % Initialise matrix OUTSIDE loop so it isn't over-written!
    for k=1:n       % additional loop for series 1 to n
        ht(1,k) = var(residuals(:,k));;
        for i = 2:T
            % Ensure you are referencing the kth series
            ht(i,k) = theta(1,k) + theta(2,k)*residuals(i-1,k)^2 + theta(3,k)*ht(i-1,k);
        end
    end
end

Note: previously, all columns of ht were the same, because theta and residuals were the same for each series!

With your updated code, and the updated code in this answer, that has been fixed.


问:
Is there a way to clear the variables read using source < (grep = ...)?
It's possible to read variables from the .ini file with source <(grep = test.ini):

```<code>$ cat test.ini
[head]
  shoulders=/hahaha/
  knees=/lololol/
  toes=/kekeke/

$ source <(grep = test.ini)

$ echo $shoulders
/hahaha/

$ echo $knees
/lololol/

$ echo $toes
/kekeke/
</code>```

I can manually clear variables read from the source <(grep = ...) command, e.g.

```<code>$ unset toes
$ echo toes
</code>```

But is there a way to automatically track which variables are added from the source command and unset them all together?

答:
```<code>unset $(awk -F\= '/=/ { printf gensub(" ","","g",$1)" " }' test.ini)
</code>```

Use awk to create a list of the variables being set and then use this output to run the unset. We use gensub to get rid of any spaces around the variables being set.

Body:
It's possible to read variables from the .ini file with source <(grep = test.ini):

$ cat test.ini
[head]
  shoulders=/hahaha/
  knees=/lololol/
  toes=/kekeke/

$ source <(grep = test.ini)

$ echo $shoulders
/hahaha/

$ echo $knees
/lololol/

$ echo $toes
/kekeke/

I can manually clear variables read from the source <(grep = ...) command, e.g.

$ unset toes
$ echo toes

But is there a way to automatically track which variables are added from the source command and unset them all together?

Body:
unset $(awk -F\= '/=/ { printf gensub(" ","","g",$1)" " }' test.ini)

Use awk to create a list of the variables being set and then use this output to run the unset. We use gensub to get rid of any spaces around the variables being set.


问:
Changing "if" python statement to apply to any obstacle instead of specific obstacles
(Disclaimer: I'm very new to coding so sorry if this is a ridiculously stupid question!)

I'm currently trying to change the Python code below so that instead of needing 4 obstacles to not be false in order to call the obstacle_detection method (which is defined earlier in the program), it will call the method if any number of obstacles are not False.

```<code>if obstacle is not False and obstacle2 is not False and obstacle3 is not False and obstacle4 is not False:
    test = obstacle_detection(obstacle, pos)
    test2 = obstacle_detection(obstacle2, pos)
    test3 = obstacle_detection(obstacle3, pos)
    test4 = obstacle_detection(obstacle4, pos)

else:
    test = 0
    test2 = 0
    test3 = 0
    test4 = 0
</code>```

I the tried changing it to something like below but I get the error of "iteration over non sequence" (and I wouldn't be surprised if this is completely the wrong idea):

```<code>if any(obstacle) is not False:
    for i in obstacle:
        test = obstacle_detection(obstacle, pos)

else:
    test = 0
</code>```

答:
Suppose you put your obstacle variables in a list.

```<code>obstacles = [obstacle, obstacle1, obstacle2, obstacle3]
</code>```

If I read you right, for any of these that not False (though this is a pretty odd way to be using False), you want to call obstacle_detection, and assign the result to a test variable.

```<code>tests = []
for obstacle in obstacles:
    if obstacle:
        tests.append(obstacle_detection(obstacle, pos))
    else:
        tests.append(0)
</code>```

Or more succinctly:

```<code>tests = [obstacle_detection(obstacle, pos) if obstacle else 0 for obstacle in obstacles]
</code>```

Body:
(Disclaimer: I'm very new to coding so sorry if this is a ridiculously stupid question!)

I'm currently trying to change the Python code below so that instead of needing 4 obstacles to not be false in order to call the obstacle_detection method (which is defined earlier in the program), it will call the method if any number of obstacles are not False.

if obstacle is not False and obstacle2 is not False and obstacle3 is not False and obstacle4 is not False:
    test = obstacle_detection(obstacle, pos)
    test2 = obstacle_detection(obstacle2, pos)
    test3 = obstacle_detection(obstacle3, pos)
    test4 = obstacle_detection(obstacle4, pos)

else:
    test = 0
    test2 = 0
    test3 = 0
    test4 = 0

I the tried changing it to something like below but I get the error of "iteration over non sequence" (and I wouldn't be surprised if this is completely the wrong idea):

if any(obstacle) is not False:
    for i in obstacle:
        test = obstacle_detection(obstacle, pos)

else:
    test = 0

Body:
Suppose you put your obstacle variables in a list.

obstacles = [obstacle, obstacle1, obstacle2, obstacle3]

If I read you right, for any of these that not False (though this is a pretty odd way to be using False), you want to call obstacle_detection, and assign the result to a test variable.

tests = []
for obstacle in obstacles:
    if obstacle:
        tests.append(obstacle_detection(obstacle, pos))
    else:
        tests.append(0)

Or more succinctly:

tests = [obstacle_detection(obstacle, pos) if obstacle else 0 for obstacle in obstacles]


问:
Polling to Backend API in regular interval for certain number of times in a regular interval - Retrofit & RxJava
I am looking to poll the backend call for certain number of times for a predefined regular intervals. I would like to exit the loop if I have received an expected payload in between the loop and update the UI else terminate the polling.

Below is the code I normally do when I make standard http call.

```<code>//Response Model from backend API
public class ApplicationStatusResponse
{
public boolean isActive;
}

//Retrofit facade
@POST(v1/api/applicationStatus)
Single<ApplicationStatusResponse> checkApplicationStatus(@Body ApplicationStatusRequest applicationRequest);

-----

DisposableSingleObserver<ApplicationStatusResponse> disposableSingleObserver = new DisposableSingleObserver<ApplicationStatusResponse>() {
    @Override
    public void onSuccess(ApplicationStatusResponse response) {
            // Update UI Here
    }

    @Override
    public void onError(Throwable e) {

    }
};

CompositeDisposable compositeDisposable = new CompositeDisposable();

// Following call works alaways works
DisposableSingleObserver<ApplicationStatusResponse> disposable = originationRepo.checkApplicationStatus(applicationStatusRequest)
        .observeOn(schedulerProvider.mainThread())
        .subscribeWith(disposableSingleObserver);

compositeDisposable.add(disposable);
</code>```

But I am kind of lost here in the following code with the syntax error and I am not able to use the same disposableSingleObserver when calling from the Flowable.interval and need help with my use case where I need to update the UI the status regularly until the time is elapsed or status is active which ever happens first and also I am not after terminating the polling if I received HTTP Status Code of 500 instead repeat until the mentioned conditions are met.

```<code> //Help Needed here  when I need polling in regular interval - I am kind of the syntax error complain from Android Studio

int INITIAL_DELAY = 0;
int POLLING_INTERVAL = 1000;
int POLL_COUNT = 8;

disposable = Flowable
            .interval(INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS)
            .map(x -> originationRepo.checkApplicationStatus(applicationStatusRequest))
            .take(POLL_COUNT) ??
            // How can I receive the response payload and update the UI

compositeDisposable.add(disposable);
</code>```

Appreciate your help in advance.

答:
Option #1 Use filter + take(1)

```<code>disposable = Flowable
            .interval(INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS)
            .map(x -> originationRepo.checkApplicationStatus(applicationStatusRequest))
            .take(POLL_COUNT) //YES
            .doOnNext() // update UI here
            .map(response -> ) // should stop condition. true - stop, false - continue
            .filter(!shouldContinue)
            .take(1)
</code>```

Option #2 Use Subject + takeUntil

```<code>Subject<Boolean> stopSubject = PublishSubject.create();
disposable = Flowable
            .interval(INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS)
            .takeUntil(stopSubject.asObservable())
            .map(x -> originationRepo.checkApplicationStatus(applicationStatusRequest))
            .take(POLL_COUNT) //YES
            .subscribe(
                response -> {
                    //update UI
                    boolean shouldStop = ... // calculate
                    if (shouldStop) {
                        stopSubject.onNext(true);
                    }
                }
            ...
             )
</code>```

PS. This is pseudo code. I hope you get idea.

Body:
I am looking to poll the backend call for certain number of times for a predefined regular intervals. I would like to exit the loop if I have received an expected payload in between the loop and update the UI else terminate the polling.

Below is the code I normally do when I make standard http call.

//Response Model from backend API
public class ApplicationStatusResponse
{
public boolean isActive;
}

//Retrofit facade
@POST(v1/api/applicationStatus)
Single<ApplicationStatusResponse> checkApplicationStatus(@Body ApplicationStatusRequest applicationRequest);

-----

DisposableSingleObserver<ApplicationStatusResponse> disposableSingleObserver = new DisposableSingleObserver<ApplicationStatusResponse>() {
    @Override
    public void onSuccess(ApplicationStatusResponse response) {
            // Update UI Here
    }

    @Override
    public void onError(Throwable e) {

    }
};

CompositeDisposable compositeDisposable = new CompositeDisposable();

// Following call works alaways works
DisposableSingleObserver<ApplicationStatusResponse> disposable = originationRepo.checkApplicationStatus(applicationStatusRequest)
        .observeOn(schedulerProvider.mainThread())
        .subscribeWith(disposableSingleObserver);

compositeDisposable.add(disposable);

But I am kind of lost here in the following code with the syntax error and I am not able to use the same disposableSingleObserver when calling from the Flowable.interval and need help with my use case where I need to update the UI the status regularly until the time is elapsed or status is active which ever happens first and also I am not after terminating the polling if I received HTTP Status Code of 500 instead repeat until the mentioned conditions are met.

 //Help Needed here  when I need polling in regular interval - I am kind of the syntax error complain from Android Studio

int INITIAL_DELAY = 0;
int POLLING_INTERVAL = 1000;
int POLL_COUNT = 8;

disposable = Flowable
            .interval(INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS)
            .map(x -> originationRepo.checkApplicationStatus(applicationStatusRequest))
            .take(POLL_COUNT) ??
            // How can I receive the response payload and update the UI

compositeDisposable.add(disposable);

Appreciate your help in advance.

Body:
Option #1 Use filter + take(1)

disposable = Flowable
            .interval(INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS)
            .map(x -> originationRepo.checkApplicationStatus(applicationStatusRequest))
            .take(POLL_COUNT) //YES
            .doOnNext() // update UI here
            .map(response -> ) // should stop condition. true - stop, false - continue
            .filter(!shouldContinue)
            .take(1)

Option #2 Use Subject + takeUntil

Subject<Boolean> stopSubject = PublishSubject.create();
disposable = Flowable
            .interval(INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS)
            .takeUntil(stopSubject.asObservable())
            .map(x -> originationRepo.checkApplicationStatus(applicationStatusRequest))
            .take(POLL_COUNT) //YES
            .subscribe(
                response -> {
                    //update UI
                    boolean shouldStop = ... // calculate
                    if (shouldStop) {
                        stopSubject.onNext(true);
                    }
                }
            ...
             )

PS. This is pseudo code. I hope you get idea.


问:
Wordpress Site Images not displaying in IE11 & Firefox Browser
I have an interesting problem with this website.  When the site is viewed through Chrome or Safari, all images are displayed & the site appears as intended.

When the site is viewed in Firefox (V54) & reportedly in IE11, neither the logo, nor any other images are visible on the page.

When I inspect the code in Firefox, I can see the images in the code, so there isn't an inherent issue with the client device accessing the image:

Any thoughts as to what would be causing this?

答: Works on my laptop. Try to clear the cache.</p>


问:
Convert from List into IEnumerable format
```<code>IEnumerable<Book> _Book_IE
List<Book> _Book_List
</code>```

How shall I do in order to convert _Book_List into IEnumerable format?

答:
You need to

```<code>using System.Linq;
</code>```

to use IEnumerable options at your List.

Body:
IEnumerable<Book> _Book_IE
List<Book> _Book_List

How shall I do in order to convert _Book_List into IEnumerable format?

Body:
You need to

using System.Linq;

to use IEnumerable options at your List.


问:
Laravel 5 Auth Post Submit - TokenMismatchException in VerifyCsrfToken.php line 46
Have just statred a new app in Laravel 5 and I am having some trouble using the out of the box auth...

I keep getting : TokenMismatchException in VerifyCsrfToken.php line 46:
on submitting the login or signup forms...

I can see on the login form page the token codes that are in the hidden form field and Session at that point are the same...

As a test I have also tried as some other posts suggested commenting out
//'App\Http\Middleware\VerifyCsrfToken', in app/Http/kernal.php to see what would happen. After doing this every time I submit a form I get a message which says redirecting to: /auth/login or /auth/register depending on where I came from with no success.

The weird thing was this was working when I first installed the framework. All I have done since then is run a few migrations and setup some of my models and controllers and seeded the db with some user data.

UPDATE:

Looking into this further in the function tokensMatch() on line 55 of VerifyCsrfToken.php if I :

```<code>var_dump($request->session()->token());

var_dump($request->input('_token'));
</code>```

I can see the two tokens are different but at the form using:

```<code>var_dump(Session::all());

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

They are the same. The Session token has changed some how before it gets to the function tokensMatch() on line 55 of VerifyCsrfToken.php

My stack trace is as follows:

```<code>in VerifyCsrfToken.php line 46
at VerifyCsrfToken->handle(object(Request), object(Closure)) in VerifyCsrfToken.php line 17
at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 55
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 61
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 36
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 40
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101
at Pipeline->then(object(Closure)) in Kernel.php line 111
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 84
at Kernel->handle(object(Request)) in index.php line 53
</code>```

答: Interestingly, I encounter the similar problem recently. I found there're two different tokens generated by my Laravel 5.1 app. I tackled the issue by generating a new application key [php artisan key:generate]!</p>

Body:
Have just statred a new app in Laravel 5 and I am having some trouble using the out of the box auth...

I keep getting : TokenMismatchException in VerifyCsrfToken.php line 46:
on submitting the login or signup forms...

I can see on the login form page the token codes that are in the hidden form field and Session at that point are the same...

As a test I have also tried as some other posts suggested commenting out
//'App\Http\Middleware\VerifyCsrfToken', in app/Http/kernal.php to see what would happen. After doing this every time I submit a form I get a message which says redirecting to: /auth/login or /auth/register depending on where I came from with no success.

The weird thing was this was working when I first installed the framework. All I have done since then is run a few migrations and setup some of my models and controllers and seeded the db with some user data.

UPDATE:

Looking into this further in the function tokensMatch() on line 55 of VerifyCsrfToken.php if I :

var_dump($request->session()->token());

var_dump($request->input('_token'));

I can see the two tokens are different but at the form using:

var_dump(Session::all());

{{{ csrf_token() }}}

They are the same. The Session token has changed some how before it gets to the function tokensMatch() on line 55 of VerifyCsrfToken.php

My stack trace is as follows:

in VerifyCsrfToken.php line 46
at VerifyCsrfToken->handle(object(Request), object(Closure)) in VerifyCsrfToken.php line 17
at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 55
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 61
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 36
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 40
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101
at Pipeline->then(object(Closure)) in Kernel.php line 111
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 84
at Kernel->handle(object(Request)) in index.php line 53


问:
Call on_press callback multiple times on key held down event
I am trying to record from my microphone while i press down a button, problem is that the library I am using is not able to detect on hold event. It only detect on press, which happens once, which means that the microphone only records one sample..

```<code>import pyaudio
import wave
from pynput import keyboard

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)
frames = []

def on_press(key):
    if key == keyboard.Key.cmd_l:
        print('- Started recording -'.format(key))
        try:
            data = stream.read(CHUNK)
            frames.append(data)
        except IOError:
            print 'warning: dropped frame' # can replace with 'pass' if no message desired
    else:
        print('incorrect character {0}, press cmd_l'.format(key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.cmd_l:
        print('{0} stop'.format(key))
        keyboard.Listener.stop
        return False

print("* recording")

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
</code>```

I am using pynput for keyboard events and pyaudio for recording.
it seems to record when cmd_l is pressed down and stops when i release. problem is the audio file generated doesn't contain anything, or is pretty short as in 0.19s long.

I guess it could have to do with stream.read has to be called multiple times, and the keypress is only being recorded once hence only one sample is being recorded.

but if that is the case how do i make it call stream.read multiple times, while also detecting also detecting when it is being released?
or are there libraries that support on_hold mechanism on keyboards?

Updated approach with threading:

```<code>from pynput import keyboard
import time
import pyaudio
import wave

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
frames = []

def callback(in_data, frame_count, time_info, status):
    return (in_data, pyaudio.paContinue)

class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(self.on_press, self.on_release)
        self.key_pressed = None

        self.stream = p.open(format=FORMAT,
                             channels=CHANNELS,
                             rate=RATE,
                             input=True,
                             frames_per_buffer=CHUNK,
                             stream_callback = self.callback)
        print self.stream.is_active()

    def on_press(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = True

    def on_release(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = False

    def callback(self,in_data, frame_count, time_info, status):
        if self.key_pressed == True:
            return (in_data, pyaudio.paContinue)
        elif self.key_pressed == False:
            return (in_data, pyaudio.paComplete)
        else:
            return (in_data,pyaudio.paAbort)

listener = MyListener()
listener.start()
started = False

while True:
    time.sleep(0.1)
    if listener.key_pressed == True and started == False:
        started = True
        listener.stream.start_stream()
        print "start Stream"

    elif listener.key_pressed == False and started == True:
        print "Something coocked"
        listener.stream.stop_stream()
        listener.stream.close()
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

        started = False
</code>```

I tried a different approach introducing two threads, which one monitoring the keyboard, and the other one sorts out the recording. But this solution keeps dropping the frames, hence nothing is actually being recorded?..

how come?

答: You can do something like in this answer where you run a function periodically on a separate thread. Seems to be the easiest solution.</p>

Body:
I am trying to record from my microphone while i press down a button, problem is that the library I am using is not able to detect on hold event. It only detect on press, which happens once, which means that the microphone only records one sample..

import pyaudio
import wave
from pynput import keyboard

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)
frames = []

def on_press(key):
    if key == keyboard.Key.cmd_l:
        print('- Started recording -'.format(key))
        try:
            data = stream.read(CHUNK)
            frames.append(data)
        except IOError:
            print 'warning: dropped frame' # can replace with 'pass' if no message desired
    else:
        print('incorrect character {0}, press cmd_l'.format(key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.cmd_l:
        print('{0} stop'.format(key))
        keyboard.Listener.stop
        return False

print("* recording")

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

I am using pynput for keyboard events and pyaudio for recording.
it seems to record when cmd_l is pressed down and stops when i release. problem is the audio file generated doesn't contain anything, or is pretty short as in 0.19s long.

I guess it could have to do with stream.read has to be called multiple times, and the keypress is only being recorded once hence only one sample is being recorded.

but if that is the case how do i make it call stream.read multiple times, while also detecting also detecting when it is being released?
or are there libraries that support on_hold mechanism on keyboards?

Updated approach with threading:

from pynput import keyboard
import time
import pyaudio
import wave

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
frames = []

def callback(in_data, frame_count, time_info, status):
    return (in_data, pyaudio.paContinue)

class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(self.on_press, self.on_release)
        self.key_pressed = None

        self.stream = p.open(format=FORMAT,
                             channels=CHANNELS,
                             rate=RATE,
                             input=True,
                             frames_per_buffer=CHUNK,
                             stream_callback = self.callback)
        print self.stream.is_active()

    def on_press(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = True

    def on_release(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = False

    def callback(self,in_data, frame_count, time_info, status):
        if self.key_pressed == True:
            return (in_data, pyaudio.paContinue)
        elif self.key_pressed == False:
            return (in_data, pyaudio.paComplete)
        else:
            return (in_data,pyaudio.paAbort)

listener = MyListener()
listener.start()
started = False

while True:
    time.sleep(0.1)
    if listener.key_pressed == True and started == False:
        started = True
        listener.stream.start_stream()
        print "start Stream"

    elif listener.key_pressed == False and started == True:
        print "Something coocked"
        listener.stream.stop_stream()
        listener.stream.close()
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

        started = False

I tried a different approach introducing two threads, which one monitoring the keyboard, and the other one sorts out the recording. But this solution keeps dropping the frames, hence nothing is actually being recorded?..

how come?


问:
UILabel multiline truncate middle as a whole string not working
I am using a UILabel which is of 2 lines.
I want to make it like

"Had the best experience ever!
She is very gener... – Mary" truncating middle portion but I am unable to achieve the same result.

Also consider that label must be of 2 line and name at the end must appear.
My code for label for initialisation is as follow

```<code>    self.labelMessage = [[VTUIKit labelSecondary] addToSuperview:self];
    self.labelMessage.numberOfLines = 2;
    self.labelMessage.font = kVTFontSecondaryVeryTiny;
    self.labelMessage.textColor = kVTColorGrey300;
    self.labelMessage.lineBreakMode = NSLineBreakByTruncatingMiddle;
    self.labelMessage.f_width = [VTReviewDisplayCell cellSize].width - 16;
</code>```

And for setting label text

```<code>    NSString *reviewString = [NSString stringWithFormat:@"%@ - %@", self.model.message, self.model.customer_user.first_name];
    self.labelMessage.text = reviewString;
</code>```

I dont understand why its not working properly.

Any help would be much appreciated.

答:
Try with below code

```<code>UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(40,100, 250, 60)];
    contentLabel.numberOfLines = 2;
    contentLabel.text = @"Had the best experience ever! She is very generally uwuq wuqe iwqwq – Mary";
    contentLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    [self.view addSubview:contentLabel];
</code>```

Body:
I am using a UILabel which is of 2 lines.
I want to make it like

"Had the best experience ever!
She is very gener... – Mary" truncating middle portion but I am unable to achieve the same result.

Also consider that label must be of 2 line and name at the end must appear.
My code for label for initialisation is as follow

    self.labelMessage = [[VTUIKit labelSecondary] addToSuperview:self];
    self.labelMessage.numberOfLines = 2;
    self.labelMessage.font = kVTFontSecondaryVeryTiny;
    self.labelMessage.textColor = kVTColorGrey300;
    self.labelMessage.lineBreakMode = NSLineBreakByTruncatingMiddle;
    self.labelMessage.f_width = [VTReviewDisplayCell cellSize].width - 16;

And for setting label text

    NSString *reviewString = [NSString stringWithFormat:@"%@ - %@", self.model.message, self.model.customer_user.first_name];
    self.labelMessage.text = reviewString;

I dont understand why its not working properly.

Any help would be much appreciated.

Body:
Try with below code

UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(40,100, 250, 60)];
    contentLabel.numberOfLines = 2;
    contentLabel.text = @"Had the best experience ever! She is very generally uwuq wuqe iwqwq – Mary";
    contentLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    [self.view addSubview:contentLabel];


问:
CSS Hover on a div to show another div not working
I'm trying to change the opacity of a div when I hover on another div, but it isn't working at all. Here's the HTML:

.chatdate {
  padding-top: 10px;
  opacity: 0.5;
  transition: opacity 1s ease-in-out;
}

.workstream-comment:hover .chatdate {
  background: red;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-lg-12">
  <div class="row">
    <div class="col-lg-10">
      <div class="workstream-comment">
        ...
      </div>
    </div>
    <div class="col-lg-2">
      <div class="chatdate text-center">
        <h6>15/07/2017</h6>
        <br>
        <h1>11:07</h1>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-lg-10">
      <div class="workstream-comment">
        ...
      </div>
    </div>
    <div class="col-lg-2">
      <div class="chatdate text-center">
        <h6>15/07/2017</h6>
        <br>
        <h1>11:07</h1>
      </div>
    </div>
  </div>
</div></code>```

Can anyone tell me what I'm doing wrong?
Thanks

答:
Why not a javascript function? I dont think you can succeed using only css.

```<code>$('.workstream-comment').hover(function(){
          $('.chatdate').css("background", "red");
          $('.chatdate').css("opacity", "1");
        }
    )
</code>```

(I did not test it btw)

Body:
I'm trying to change the opacity of a div when I hover on another div, but it isn't working at all. Here's the HTML:

.chatdate {
  padding-top: 10px;
  opacity: 0.5;
  transition: opacity 1s ease-in-out;
}

.workstream-comment:hover .chatdate {
  background: red;
  opacity: 1;
}

        ...

15/07/2017

11:07

        ...

15/07/2017

11:07

Can anyone tell me what I'm doing wrong?
Thanks

Body:
Why not a javascript function? I dont think you can succeed using only css.

$('.workstream-comment').hover(function(){
          $('.chatdate').css("background", "red");
          $('.chatdate').css("opacity", "1");
        }
    )

(I did not test it btw)


问:
Android sockets: listening doesn't work through 4G
I'm learning Android and Java programming on my own. To practise, I've developed a couple of apps, and now I'm trying to write a chat-like application. So basically, I want to to something like WhatsApp. I have a server program also coded by me running in my computer, and it's what the chat in the Android system uses to communicate. So basically, everything is sent to the server and the server does what required to deliver the messages.

So here is what I have:

First, my app sends a "Hello" to my server (known IP and port)

The server stores the IP and the port (also the username) used by each user

When the server is asked to deliver a message to a user, it sends it to the IP and port stored

I use a socket for the "Hello", but I can't use the same one for sending back messages (because of how I programmed the server). But this is not the problem. When the server receives the "Hello", it's listening on the corresponding port. But when the server is the one who has to start the connection, it's the app the one who has to. In order to do this, the app must know on what port it must listen (it doesn't know because of NAT), and I tell it so sending back the port used through the first socket used for the "Hello" message. Despite this, my app is unable to receive messages and stays in the receive call.

Here you have the code:

Server:

```<code>    DatagramSocket client = new DatagramSocket(2048); //Predefined port
    DatagramPacket receivePacket;
    byte[] receiveData = new byte[1024];
    receivePacket = new DatagramPacket(receiveData,
            receiveData.length);
    System.out.println("Ready to receive");
    client.receive(receivePacket);
    System.out.println("Received successfuly");
    String receivedPort = String.valueOf(receivePacket.getPort());
    byte[] sendData = receivedPort.getBytes();
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
    client.send(sendPacket); //Send back the port used by the app
    System.out.println("Sent successfuly");
    client.close();
    Thread.sleep(1000); //To make sure the app is ready to listen
    DatagramSocket socket = new DatagramSocket();
    byte[] sendData2 = "Working like a charm".getBytes();
    InetAddress ip = receivePacket.getAddress();
    int port = receivePacket.getPort();
    System.out.println(ip + " " + port);
    DatagramPacket sendPacket2 = new DatagramPacket(sendData2, sendData2.length, ip, port);
    socket.send(sendPacket);
    System.out.println("Sent successfuly 2nd time");
    socket.close();
</code>```

Client (Android app):

```<code>EditText eT = (EditText) findViewById(R.id.messageText);
String message = eT.getText().toString();
DatagramSocket socket = new DatagramSocket();
byte[] sendData = message.getBytes();
InetAddress ip = InetAddress.getByName(MY_COMPUTER'S_IP);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, 2048);
socket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket); //Receive the port used (and that must be opened and redirecting the traffic to this device due to NAT)
socket.close();
String receivedMessage = new String(receivePacket.getData());
String receivedData = new String(receivePacket.getData());
String actualData = receivedData.substring(0, receivePacket.getLength());
Log.d("Port", actualData);
int port = Integer.parseInt(actualData);
DatagramSocket socket2 = new DatagramSocket(port);
DatagramPacket receivePacket2;
byte[] receiveData2 = new byte[1024];
receivePacket2 = new DatagramPacket(receiveData2,
        receiveData2.length);
socket2.receive(receivePacket2); //Here is where it gets blocked
String data = new String(receivePacket2.getData());
Log.d("Finally received", data.substring(receivePacket2.getLength()));
socket2.close();
</code>```

Does anybody know why my messages aren't making it back through the second socket? I've checked and the IP and ports are correct.

Thanks in advance for answering, and I apologize for my formatting.

答:
Many mobile phone companies currently assign a private IP to 3G-4G connected devices.

It is as if the devices were inside a LAN. You do not have access to the gateway router of this LAN and without a NAT the listening ports of your device are inaccessible from outside.

To know if your IP is public or private compare the IP of the device with the one sites like showmyip.com say, if they are different your device is in your phone company LAN.

To obtain the device IP some application like PingTools can help.

Body:
I'm learning Android and Java programming on my own. To practise, I've developed a couple of apps, and now I'm trying to write a chat-like application. So basically, I want to to something like WhatsApp. I have a server program also coded by me running in my computer, and it's what the chat in the Android system uses to communicate. So basically, everything is sent to the server and the server does what required to deliver the messages.

So here is what I have:

First, my app sends a "Hello" to my server (known IP and port)

The server stores the IP and the port (also the username) used by each user

When the server is asked to deliver a message to a user, it sends it to the IP and port stored

I use a socket for the "Hello", but I can't use the same one for sending back messages (because of how I programmed the server). But this is not the problem. When the server receives the "Hello", it's listening on the corresponding port. But when the server is the one who has to start the connection, it's the app the one who has to. In order to do this, the app must know on what port it must listen (it doesn't know because of NAT), and I tell it so sending back the port used through the first socket used for the "Hello" message. Despite this, my app is unable to receive messages and stays in the receive call.

Here you have the code:

Server:

    DatagramSocket client = new DatagramSocket(2048); //Predefined port
    DatagramPacket receivePacket;
    byte[] receiveData = new byte[1024];
    receivePacket = new DatagramPacket(receiveData,
            receiveData.length);
    System.out.println("Ready to receive");
    client.receive(receivePacket);
    System.out.println("Received successfuly");
    String receivedPort = String.valueOf(receivePacket.getPort());
    byte[] sendData = receivedPort.getBytes();
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
    client.send(sendPacket); //Send back the port used by the app
    System.out.println("Sent successfuly");
    client.close();
    Thread.sleep(1000); //To make sure the app is ready to listen
    DatagramSocket socket = new DatagramSocket();
    byte[] sendData2 = "Working like a charm".getBytes();
    InetAddress ip = receivePacket.getAddress();
    int port = receivePacket.getPort();
    System.out.println(ip + " " + port);
    DatagramPacket sendPacket2 = new DatagramPacket(sendData2, sendData2.length, ip, port);
    socket.send(sendPacket);
    System.out.println("Sent successfuly 2nd time");
    socket.close();

Client (Android app):

EditText eT = (EditText) findViewById(R.id.messageText);
String message = eT.getText().toString();
DatagramSocket socket = new DatagramSocket();
byte[] sendData = message.getBytes();
InetAddress ip = InetAddress.getByName(MY_COMPUTER'S_IP);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, 2048);
socket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket); //Receive the port used (and that must be opened and redirecting the traffic to this device due to NAT)
socket.close();
String receivedMessage = new String(receivePacket.getData());
String receivedData = new String(receivePacket.getData());
String actualData = receivedData.substring(0, receivePacket.getLength());
Log.d("Port", actualData);
int port = Integer.parseInt(actualData);
DatagramSocket socket2 = new DatagramSocket(port);
DatagramPacket receivePacket2;
byte[] receiveData2 = new byte[1024];
receivePacket2 = new DatagramPacket(receiveData2,
        receiveData2.length);
socket2.receive(receivePacket2); //Here is where it gets blocked
String data = new String(receivePacket2.getData());
Log.d("Finally received", data.substring(receivePacket2.getLength()));
socket2.close();

Does anybody know why my messages aren't making it back through the second socket? I've checked and the IP and ports are correct.

Thanks in advance for answering, and I apologize for my formatting.


问:
Bootstrap4 vertical align column
Is there a quick flexbox classes to vertically align content within columns?

For example

```<code>  <div class="row">
      <div class="col">
        unknown height
      </div>
      <div class="col h100 d-flex justify-content-center">
        set same height as previous + flex center
      </div>
  </div>
</code>```

Above doesnt obviously work but you get the point...

Same height rows can be achieved with this https://scotch.io/quick-tips/different-tricks-on-how-to-make-bootstrap-columns-all-the-same-height#toc-option-4-use-flexbox

-> Does not feel the smoothest solution, isnt there native bootstrap class?

And well its still not aligned middle

答:
ok this is enough:</p>

```<code><div class="row align-items-center"></div>
</code>```

Title: Bootstrap4 vertical align column

Body:
Is there a quick flexbox classes to vertically align content within columns?

For example

        unknown height

        set same height as previous + flex center

Above doesnt obviously work but you get the point...

Same height rows can be achieved with this https://scotch.io/quick-tips/different-tricks-on-how-to-make-bootstrap-columns-all-the-same-height#toc-option-4-use-flexbox

-> Does not feel the smoothest solution, isnt there native bootstrap class?

And well its still not aligned middle

Body:
ok this is enough:

<div class="row align-items-center"></div>


问:
How to insert data in excel Spreadsheet using php Excel
how to insert data in excel spreadsheet using phpExcel?

please help me.

答:
This is assuming all the libraries loaded and imported into the page</p>

```<code>function report($result){
//result is the data to be filled

    $ea = new \PHPExcel();
    $ea->getProperties()
        ->setCreator('YOURNAME')
        ->setTitle('PHPExcel');

    $ews = $ea->getSheet(0);

    $ews->setCellValue('a1', 'ID'); // Sets cell 'a1' to value 'ID
    $ews->setCellValue('b1', 'first Name');
    $ews->setCellValue('c1', 'Last Name');

//this is to set header colour
    $header = 'a1:c1';
    $ews->getStyle($header)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('0000ffe6');
    $style = array(
        'font' => array('bold' => true,),
        'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
    );
    $ews->getStyle($header)->applyFromArray($style);

    $ews->fromArray($result, '-', 'A2');

//this is to autosize columns to fit data
    for ($col = ord('a'); $col <= ord('c'); $col++)
    {
        $ews->getColumnDimension(chr($col))->setAutoSize(true);
    }

// Redirect output to a clients web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="report.xlsx"');
    header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
//
//// If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0

    $objWriter = PHPExcel_IOFactory::createWriter($ea, 'Excel2007');
    $objWriter->save('php://output');
    exit;

}
</code>```

Body:
This is assuming all the libraries loaded and imported into the page

function report($result){
//result is the data to be filled

    $ea = new \PHPExcel();
    $ea->getProperties()
        ->setCreator('YOURNAME')
        ->setTitle('PHPExcel');

    $ews = $ea->getSheet(0);

    $ews->setCellValue('a1', 'ID'); // Sets cell 'a1' to value 'ID
    $ews->setCellValue('b1', 'first Name');
    $ews->setCellValue('c1', 'Last Name');

//this is to set header colour
    $header = 'a1:c1';
    $ews->getStyle($header)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('0000ffe6');
    $style = array(
        'font' => array('bold' => true,),
        'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
    );
    $ews->getStyle($header)->applyFromArray($style);

    $ews->fromArray($result, '-', 'A2');

//this is to autosize columns to fit data
    for ($col = ord('a'); $col <= ord('c'); $col++)
    {
        $ews->getColumnDimension(chr($col))->setAutoSize(true);
    }

// Redirect output to a clients web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="report.xlsx"');
    header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
//
//// If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0

    $objWriter = PHPExcel_IOFactory::createWriter($ea, 'Excel2007');
    $objWriter->save('php://output');
    exit;

}


答:
If you want all your obstacles to be True use all():

```<code>obstacles = [obstacle1, obstacle2, obstacle3, obstacle4]
evaluate = all(obstacles)
for index, obstacle in enumerate(obstacles)
    locals()["test{}".format(index+1)] = obstacle_detection(obstacle, pos) if evaluate else 0
</code>```

If you really don't want to define your obstacle list upfront (bad design, but...) you can pick them up automatically:

```<code>obstacles = [globals()[x] for x in globals() if x.startswith("obstacle")]
</code>```

But keep in mind that you might get clashes that way so make sure all your obstacle variables have a number following them. Also, this addresses only the global scope, you can use local() for the local scope.

If you really want to do it with no change to your variables whatsoever, you can do it as:

```<code>all_obstacles = {x[8:]: globals()[x] for x in globals() if x.startswith("obstacle")}
evaluate = all(all_obstacles.values())
for k, v in all_obstacles.items():
    globals()["test{}".format(k)] = obstacle_detection(v, pos) if evaluate else 0
</code>```

This will produce a test<x> variable for every obstacle<x> variable in the global space (including test for obstacle) and either evaluate it through the obstacle_detection() function or set it to 0 if all of the obstacles don't evaluate to True.

Title: Changing "if" python statement to apply to any obstacle instead of specific obstacles

Body:
If you want all your obstacles to be True use all():

obstacles = [obstacle1, obstacle2, obstacle3, obstacle4]
evaluate = all(obstacles)
for index, obstacle in enumerate(obstacles)
    locals()["test{}".format(index+1)] = obstacle_detection(obstacle, pos) if evaluate else 0

If you really don't want to define your obstacle list upfront (bad design, but...) you can pick them up automatically:

obstacles = [globals()[x] for x in globals() if x.startswith("obstacle")]

But keep in mind that you might get clashes that way so make sure all your obstacle variables have a number following them. Also, this addresses only the global scope, you can use local() for the local scope.

If you really want to do it with no change to your variables whatsoever, you can do it as:

all_obstacles = {x[8:]: globals()[x] for x in globals() if x.startswith("obstacle")}
evaluate = all(all_obstacles.values())
for k, v in all_obstacles.items():
    globals()["test{}".format(k)] = obstacle_detection(v, pos) if evaluate else 0

This will produce a test<x> variable for every obstacle<x> variable in the global space (including test for obstacle) and either evaluate it through the obstacle_detection() function or set it to 0 if all of the obstacles don't evaluate to True.


问:
How to create chat functionality same as linkedIn using signalR
I need to create chat functionality (same as linkedIn messaging) in DNN. How to do that in DNN(C#)?</p>

答:
Not supprisngly, example that Microsoft uses to explain SignalR usage is chat app

And chat is also common target for many SignalR tutorials on the web


问:
php ajax error ...not showing the data
///this is the form part .where i am trying get data from database and show it in "txt" part.the script part is in same file and getService.php is in the same directory as this file.why showing nothing when i select something.

```<code><form>
<select name="parent">
<option selected="users" onchange="showService(this.value)">Select a Service:</option>
<?php
$res=$mysqli->query("SELECT * FROM service");
while($row=$res->fetch_array())
{
  ?>
    <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
    <?php
}
?>
</select>
</br>

</form>

<div id="txt"><b>Service info will be show here...</b></div>

    </center>

    </div>
</code>```

//script part. in same file.

```<code><script>
function showService(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txt").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","getService.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>
</code>```

//getService.php

```<code><?php

session_start();
include_once'db_connect.php';

?>

<!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$sql="SELECT * FROM service WHERE id = '".$q."'";
$result = mysqli_query($mysqli,$sql);

echo "<table>
<tr>

<th>id</th>
<th>Service name</th>
<th>Detail</th>

</tr>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td>" . $row['name'] . "</td>";
    echo "<td>" . $row['detail'] . "</td>";
    echo "</tr>";
}
echo "</table>";
mysqli_close($mysqli);
?>

</body>
</html>
</code>```

答:
There are a number of issues with your code. In order of direct relevance to your question:

1) onchange="showService(this.value)" should be an attribute of the <select> not the first <option>. So it isn't firing the change event at all, meaning your ajax call never runs.

2) document.getElementById("txtHint") is wrong (in two places) - you don't have any element with this ID in your HTML. document.getElementById("txt") should work.

3) Your getService.php should not return a whole new HTML page (with DocType, html, body tags etc) to insert inside a div in another page, this is not really valid markup. Instead return only the
 part which is actually required to go within the specific part of the main page. If you need the CSS which is in getService.php, move it into your main page, or a separate CSS file which is included in the main page.

4) You process q as an int (using intval()) but then pass it to mySQL as if it is a string (by putting single quotes around it in the SQL statement). If the id field in your database is an integer, this will cause the values not to be considered equal to each other and so no results will be returned. If this is the case then you should remove the single quotes.

5) However, point 4 above is a symptom of another problem, in that you should not be adding variables into your query simply by joining PHP strings together. This leaves you vulnerable to SQL Injection attacks where a malicious user could steal, corrupt or delete your data by inserting SQL into the variable itself. Instead you should use parameterised queries to guard against this, and also remove the potential for problems as described in point 4. http://bobby-tables.com/ is a good resource which explains both the dangers of injection attacks and contains resources explaining how to use parameterised queries and other techniques to guard against it, including examples using PHP. This is a good habit to get into now and will safeguard the data in your application.

Title: php ajax error ...not showing the data

Body:
///this is the form part .where i am trying get data from database and show it in "txt" part.the script part is in same file and getService.php is in the same directory as this file.why showing nothing when i select something.

<form>
<select name="parent">
<option selected="users" onchange="showService(this.value)">Select a Service:</option>
<?php
$res=$mysqli->query("SELECT * FROM service");
while($row=$res->fetch_array())
{
  ?>
    <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
    <?php
}
?>
</select>

</form>

Service info will be show here...

//script part. in same file.

//getService.php

<?php

session_start();
include_once'db_connect.php';

?>

<!DOCTYPE html>

<?php
$q = intval($_GET['q']);

$sql="SELECT * FROM service WHERE id = '".$q."'";
$result = mysqli_query($mysqli,$sql);

echo "

id
Service name
Detail

";
while($row = mysqli_fetch_array($result)) {
    echo "
";
    echo "" . $row['id'] . "	";
    echo "" . $row['name'] . "	";
    echo "" . $row['detail'] . "	";
    echo "
";
}
echo "
";
mysqli_close($mysqli);
?>

Body:
There are a number of issues with your code. In order of direct relevance to your question:

1) onchange="showService(this.value)" should be an attribute of the <select> not the first <option>. So it isn't firing the change event at all, meaning your ajax call never runs.

2) document.getElementById("txtHint") is wrong (in two places) - you don't have any element with this ID in your HTML. document.getElementById("txt") should work.

3) Your getService.php should not return a whole new HTML page (with DocType, html, body tags etc) to insert inside a div in another page, this is not really valid markup. Instead return only the <table> part which is actually required to go within the specific part of the main page. If you need the CSS which is in getService.php, move it into your main page, or a separate CSS file which is included in the main page.

4) You process q as an int (using intval()) but then pass it to mySQL as if it is a string (by putting single quotes around it in the SQL statement). If the id field in your database is an integer, this will cause the values not to be considered equal to each other and so no results will be returned. If this is the case then you should remove the single quotes.

5) However, point 4 above is a symptom of another problem, in that you should not be adding variables into your query simply by joining PHP strings together. This leaves you vulnerable to SQL Injection attacks where a malicious user could steal, corrupt or delete your data by inserting SQL into the variable itself. Instead you should use parameterised queries to guard against this, and also remove the potential for problems as described in point 4. http://bobby-tables.com/ is a good resource which explains both the dangers of injection attacks and contains resources explaining how to use parameterised queries and other techniques to guard against it, including examples using PHP. This is a good habit to get into now and will safeguard the data in your application.


问:
Calling method Design in Java
I have one interface named HasDescription

```<code>public interface HasDescription {

    String getDescription();

    void setDescription(String description);
}
</code>```

It has getter and setter method declarations.

I have another abstract class called ResidentialProperty that implements this interface.

```<code>public abstract class ResidentialProperty
        extends AbstractProperty
        implements HasDescription {
    .....
    private String description;

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public void setDescription(String description) {
        this.description = description;
    }

}
</code>```

I have another class called Flat. In this class, i have delegated one descriptionSupportinstance. My thought is that, using this instance, i want to call ResidentialProperty's getter and setter method. I am coding this DescriptionSupport. Please assist me how i can do this?

```<code>public class Flat
extends ResidentialProperty {
 private final DescriptionSupport descriptionSupport = new DescriptionSupport();
 @Override
 public String getDescription() {
  return descriptionSupport.getDescription(this);
 }

 @Override
 public void setDescription(String description) {
  descriptionSupport.setDescription(this, description);
 }
}

public class DescriptionSupport {
 public < T extends HasDescription > String getDescription(T property) {
  //i want to call ResidentialProperty's getDescription method

 }

 public < T extends HasDescription > void setDescription(T property, String description) {
  //i want to call ResidentialProperty's setDescription method
 }
}
</code>```

答:
The DescriptionSupport helper class isn't needed. The Flat is subtype of ResidentialProperty - it inherits the implementation of setters and getters from its parent so you don't need to override them again.

If you still need to override the two methods, you can call their implementation from parent class using super, for example super.setDescription(description).

Title: Calling method Design in Java

Body:
I have one interface named HasDescription

public interface HasDescription {

    String getDescription();

    void setDescription(String description);
}

It has getter and setter method declarations.

I have another abstract class called ResidentialProperty that implements this interface.

public abstract class ResidentialProperty
        extends AbstractProperty
        implements HasDescription {
    .....
    private String description;

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public void setDescription(String description) {
        this.description = description;
    }

}

I have another class called Flat. In this class, i have delegated one descriptionSupportinstance. My thought is that, using this instance, i want to call ResidentialProperty's getter and setter method. I am coding this DescriptionSupport. Please assist me how i can do this?

public class Flat
extends ResidentialProperty {
 private final DescriptionSupport descriptionSupport = new DescriptionSupport();
 @Override
 public String getDescription() {
  return descriptionSupport.getDescription(this);
 }

 @Override
 public void setDescription(String description) {
  descriptionSupport.setDescription(this, description);
 }
}

public class DescriptionSupport {
 public < T extends HasDescription > String getDescription(T property) {
  //i want to call ResidentialProperty's getDescription method

 }

 public < T extends HasDescription > void setDescription(T property, String description) {
  //i want to call ResidentialProperty's setDescription method
 }
}


问:
How to create a six character password in MySQL 5.7
I need to create a user with a six character password in new MySQL on my mac. I know that the lowest setting in 5.7 will allows only eight characters. Is there any way to go around that?

I type in CREATE USER 'newsier'@'localhost' IDENTIFIED BY 'special'

It outputs the error

```<code>ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
</code>```

答:
This might help:

GRANT ALL ON wordpress.* TO 'user'@'localhost' IDENTIFIED WITH mysql_native_password AS'yourpassword';

Body:
I need to create a user with a six character password in new MySQL on my mac. I know that the lowest setting in 5.7 will allows only eight characters. Is there any way to go around that?

I type in CREATE USER 'newsier'@'localhost' IDENTIFIED BY 'special'

It outputs the error

ERROR 1819 (HY000): Your password does not satisfy the current policy requirements


问:
How do you keep relative positioning from poping out of the box?
I am trying to use relative positioning for other reasons, and data in my div is popuping out of the container div in ie7.

Can you guys give me some idea what is going?

Also, I can just remove position: relative;.   That is need for my line highlighting code.

Thanks,
Grae

Here is the code:

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
<html>
<head></p>

<p></head>
<body>
    <div style="overflow:auto; height:350px; border: 1px solid #00ff00">
        <table>
            <tr><br>
                <td>
                    <div style="position:relative;">
                        <PRE>
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
                        </PRE>
                    </div>
                </td>
            </tr>
        </table>
    </div>
</body>
```

答: You'll want to add overflow: hidden; to your inline (or CSS) style for the containing element.

Body:
I am trying to use relative positioning for other reasons, and data in my div is popuping out of the container div in ie7.

Can you guys give me some idea what is going?

Also, I can just remove position: relative;.   That is need for my line highlighting code.

Thanks,
Grae

Here is the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >

Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line


问:
IP blocking on hosting
I am trying to block my website's access by a particular router, but that router has a dynamic IP. It changes the IP dynamically, so even after blocking one IP of the router it can still access the website after it has changed its IP. How do I block that specific router from accessing my website?</p>

答:
You could block an IP range (if you see within which range the router gets its IP addresses)

120.120.0.0 - 120.120.255.255

Title: IP blocking on hosting