问:
One dropdown field leading to updated values for another dropdown field
I have two drop downs, when dropdown-1 is changed, selected option of dropdown-2 should be changed to the same as dropdown-1

Dropdown-1:

```<code><div className="select-style-right joiner-select">
    <select className="selectalljoiners" onChange={this.handleMainSelectChanged} value={this.state.selectedJoinerValue}>
        <option value="">Select</option>
        <option value="Permanent">Permanent</option>
        <option value="Probationary">Probationary</option>
        <option value="Contractual">Contractual</option>
        <option value="Intern">Intern</option>
    </select>
</div>
</code>```

Dropdown-2:

```<code><div className="select-style-right joiner-select">
    <select className={index} value={this.state.selectedJoinerValue}>
        <option value="">Select</option>
        <option value="Permanent">Permanent</option>
        <option value="Probationary">Probationary</option>
        <option value="Contractual">Contractual</option>
        <option value="Intern">Intern</option>
    </select>
</div>
</code>```

handleMainSelectChanged:

```<code>handleMainSelectChanged = (e) => {
        thisclass.setState({
            selectedJoinerValue: e.target.value
        })
}
</code>```

New to React, don't know how to achieve this. Please help out.

答:
If one of dropdowns changed the second one will take same selected option.

https://jsfiddle.net/b1atetou/

```<code>class Example extends React.Component {
    constructor() {
        super();
        this.state = { value: "" }
    }

    handleDropDownChage = (event) => {
        this.setState({value: event.target.value});
    }

    render() {
        return (
            <div>
                <div>
                    <select onChange={this.handleDropDownChage} value={this.state.value}>
                        <option value="">Select</option>
                        <option value="Permanent">Permanent</option>
                        <option value="Probationary">Probationary</option>
                        <option value="Contractual">Contractual</option>
                        <option value="Intern">Intern</option>
                    </select>
                </div>

                <div>
                    <select onChange={this.handleDropDownChage} value={this.state.value}>
                        <option value="">Select</option>
                        <option value="Permanent">Permanent</option>
                        <option value="Probationary">Probationary</option>
                        <option value="Contractual">Contractual</option>
                        <option value="Intern">Intern</option>
                    </select>
                </div>
            </div>
        );
    }
}
</code>```

Body:
I have two drop downs, when dropdown-1 is changed, selected option of dropdown-2 should be changed to the same as dropdown-1

Dropdown-1:

    <select className="selectalljoiners" onChange={this.handleMainSelectChanged} value={this.state.selectedJoinerValue}>
        <option value="">Select</option>
        <option value="Permanent">Permanent</option>
        <option value="Probationary">Probationary</option>
        <option value="Contractual">Contractual</option>
        <option value="Intern">Intern</option>
    </select>

Dropdown-2:

    <select className={index} value={this.state.selectedJoinerValue}>
        <option value="">Select</option>
        <option value="Permanent">Permanent</option>
        <option value="Probationary">Probationary</option>
        <option value="Contractual">Contractual</option>
        <option value="Intern">Intern</option>
    </select>

handleMainSelectChanged:

handleMainSelectChanged = (e) => {
        thisclass.setState({
            selectedJoinerValue: e.target.value
        })
}

New to React, don't know how to achieve this. Please help out.

Body:
If one of dropdowns changed the second one will take same selected option.

https://jsfiddle.net/b1atetou/

class Example extends React.Component {
    constructor() {
        super();
        this.state = { value: "" }
    }

    handleDropDownChage = (event) => {
        this.setState({value: event.target.value});
    }

    render() {
        return (
            <div>
                <div>
                    <select onChange={this.handleDropDownChage} value={this.state.value}>
                        <option value="">Select</option>
                        <option value="Permanent">Permanent</option>
                        <option value="Probationary">Probationary</option>
                        <option value="Contractual">Contractual</option>
                        <option value="Intern">Intern</option>
                    </select>
                </div>

                <div>
                    <select onChange={this.handleDropDownChage} value={this.state.value}>
                        <option value="">Select</option>
                        <option value="Permanent">Permanent</option>
                        <option value="Probationary">Probationary</option>
                        <option value="Contractual">Contractual</option>
                        <option value="Intern">Intern</option>
                    </select>
                </div>
            </div>
        );
    }
}


来源: stackexchange

问:
Run Selenium with chromedriver in Jenkins
I'm trying to run a basic script using Selenium with chromedriver within Jenkins (CI).

Basically I did all the steps that should be taken to run the script but still i'm getting an errors like:

WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 127

or

'chrome' executable needs to be in PATH.

I've installed the chrome driver plugin in Jenkins (basically i've installed any plugin that can be related) but still i'm not able to run the script.

the script is:

```<code>import os
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys

def chat():

# setting Chrome headless webdriver
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=1920x1080")
chrome_driver = os.getcwd() + "/chromedriver"
driver = webdriver.Chrome(chrome_options=chrome_options,
executable_path=chrome_driver)

# set url's
website_url = "<some url>"

# verify the website and BO are live
web = requests.get(website_url)
if web.status_code != 200:
    raise Exception("Error in URL's")
else:
    driver.get(website_url)
    driver.find_element_by_id("some_id").click()
    driver.quit()
</code>```

The code is just to show how i call chromedriver

What am i doing wrong? am i missing a set to run this kind of script?

答:
The error 'chrome' executable needs to be in PATH says it all.

Probable reasons are :

Google Chrome was not installed at the default location.

Actual Chrome Browser Binary path doesn't matches as set within Environmental Variables

Solution :

Ensure actual Chrome Browser Binary path matches with the settings within Environmental Variables

Uninstall Chrome Browser completely through Revo Uninstaller and ensure Registry Entries related to Chrome are deleted.

Install Chrome Browser.

Execute your Test.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to run a basic script using Selenium with chromedriver within Jenkins (CI).

Basically I did all the steps that should be taken to run the script but still i'm getting an errors like:

WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 127

or

'chrome' executable needs to be in PATH.

I've installed the chrome driver plugin in Jenkins (basically i've installed any plugin that can be related) but still i'm not able to run the script.

the script is:

import os
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys

def chat():

# setting Chrome headless webdriver
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=1920x1080")
chrome_driver = os.getcwd() + "/chromedriver"
driver = webdriver.Chrome(chrome_options=chrome_options,
executable_path=chrome_driver)

# set url's
website_url = "<some url>"

# verify the website and BO are live
web = requests.get(website_url)
if web.status_code != 200:
    raise Exception("Error in URL's")
else:
    driver.get(website_url)
    driver.find_element_by_id("some_id").click()
    driver.quit()

The code is just to show how i call chromedriver

What am i doing wrong? am i missing a set to run this kind of script?


问:
Why doesn't Future.get(...) kill the thread?
I have an application that is using future for asynchronous execution.

I set the parameter on get method, that the thread should get killed after 10 seconds, when it does not get the response:

```<code> Future<RecordMetadata> meta = producer.send(record, new ProducerCallBack());
      RecordMetadata data = meta.get(10, TimeUnit.SECONDS);
</code>```

But the thread get killed after 60 second:

```<code>java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms.
    at org.apache.kafka.clients.producer.KafkaProducer$FutureFailure.<init>(KafkaProducer.java:1124)
    at org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:823)
    at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:760)
    at io.khinkali.KafkaProducerClient.main(KafkaProducerClient.java:49)
Caused by: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms.
</code>```

What am I doing wrong?

答:
From the docs:

The threshold for time to block is determined by max.block.ms after
  which it throws a TimeoutException.

Check Kafka Appender config in logback.xml, look for:

```<code><producerConfig>max.block.ms=60000</producerConfig>
</code>```

Body:
I have an application that is using future for asynchronous execution.

I set the parameter on get method, that the thread should get killed after 10 seconds, when it does not get the response:

 Future<RecordMetadata> meta = producer.send(record, new ProducerCallBack());
      RecordMetadata data = meta.get(10, TimeUnit.SECONDS);

But the thread get killed after 60 second:

java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms.
    at org.apache.kafka.clients.producer.KafkaProducer$FutureFailure.<init>(KafkaProducer.java:1124)
    at org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:823)
    at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:760)
    at io.khinkali.KafkaProducerClient.main(KafkaProducerClient.java:49)
Caused by: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms.

What am I doing wrong?

Body:
From the docs:

The threshold for time to block is determined by max.block.ms after
  which it throws a TimeoutException.

Check Kafka Appender config in logback.xml, look for:

<producerConfig>max.block.ms=60000</producerConfig>


问:
Difference between Interface and Class in Java
As per multiple articles in Java Interface and Class are completely different. Let me write an Interface.

```<code>package com.main.service;

public interface SomeService{
   public void someMethod();
}
</code>```

But why below code is allowed in Java?

```<code> com.main.service.SomeService.class;
</code>```

I am using this code to get beans from Spring application context like below:-

```<code> SomeService someservice = applicationContext
            .getBean(com.main.service.SomeService.class);
</code>```

答:
The .class syntax at the end of a type (com.main.service.SomeService.class; in this case) references the class literal, which is an object of type Class. You can use this on any Java type, be it a concrete class, abstract class or an interface.

As per the Javadoc from the link above:

Instances of the class Class represent classes and interfaces in a running Java application

This may be confusing if you're new, and are used to having the distinction between class and interface drummed into you, but simply speaking it's how the underlying system works (all classes and interfaces are compiled to bytecode class files.)

You commonly see the syntax used in dependency injection (or other uses where you need to pass the "type" of something around), as it's the easiest way of doing so.

Body:
As per multiple articles in Java Interface and Class are completely different. Let me write an Interface.

package com.main.service;

public interface SomeService{
   public void someMethod();
}

But why below code is allowed in Java?

 com.main.service.SomeService.class;

I am using this code to get beans from Spring application context like below:-

 SomeService someservice = applicationContext
            .getBean(com.main.service.SomeService.class);


问:
MVVM Light: Adding EventToCommand in XAML without Blend, easier way or snippet?
Can anyone tell me what the actual syntax is for EventToCommand class. From what I believe is that EventToCommand class works with Silverlight / WPF and WP7, hence I think its a better choice to go down.

From what I believe, I can add any click event and get it forced into my ViewModel, but I am having an issue in finding the best way to do this.

I know you can add it without Blend, but are there snippets available?

Or is there an easier way to add it via VS 2010? Any help or if anyone knows of a good tutorial on this would be great.

答:
0) if you dont't know WPF and MVVM, then read Josh Smith article about WPF and MVVM pattern https://msdn.microsoft.com/en-us/magazine/dd419663.aspx

1) In your project add package (through NuGet) MvvmLightLibs

2) add reference to System.Windows.Interactivity

3) In "View" XAML add:

a)

```<code>xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:command="http://www.galasoft.ch/mvvmlight"
</code>```

b)

```<code><i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
      <command:EventToCommand Command="{Binding OnClosingCommand}"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Window>
</code>```

4) In ViewModel add necessary property

```<code>public ICommand OnClosingCommand
{
  get
  {
    return new RelayCommand(() => SomeMethod());
  }
}
</code>```

P.S. In your View should be specified DataContext (XAML)

```<code>  <Window.DataContext>
    <vm:MainWindowViewModel/>
  </Window.DataContext>
</code>```

It is work. I myself just learned.

Body:
0) if you dont't know WPF and MVVM, then read Josh Smith article about WPF and MVVM pattern https://msdn.microsoft.com/en-us/magazine/dd419663.aspx

1) In your project add package (through NuGet) MvvmLightLibs

2) add reference to System.Windows.Interactivity

3) In "View" XAML add:

a)

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:command="http://www.galasoft.ch/mvvmlight"

b)

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
      <command:EventToCommand Command="{Binding OnClosingCommand}"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Window>

4) In ViewModel add necessary property

public ICommand OnClosingCommand
{
  get
  {
    return new RelayCommand(() => SomeMethod());
  }
}

P.S. In your View should be specified DataContext (XAML)

  <Window.DataContext>
    <vm:MainWindowViewModel/>
  </Window.DataContext>

It is work. I myself just learned.


问:
Map JSON values in Elixir
I have parsed the following JSON using Posion.decode!

```<code>json = %{"color-Black|size:10" =>
    %{"attributes" => %{"color" => "Black","size" => "11"},
      "isAvailable" => true,
    "pricing" => %{"standard" => "$415.00", "sale" => 415}},
 "color|size-EU:9.5" =>
    %{"attributes" => %{"color" => "Black","size" => "11"},
      "isAvailable" => true,
    "pricing" => %{"standard" => "$415.00", "sale" => 415}}}
</code>```

I want to map this and I'm unable to get JSON elements as the text in the node element changes.
So far I've tried.

```<code>Enum.map(json , fn(item) ->
%{
  color: item.attributes["color"],
  size: item.attributes["size"],
  price: item.pricing["standard"] * 100,
  isAvailable: item.isAvailable
 }
end)
</code>```

But this code gives some error related to accessing.

答:
Three things:

You have a map so Enum.map will give you a tuple of key and value. You just want the value here, so do:

```<code>fn {_, item} ->
</code>```

The keys in your map are strings. The dot syntax only works for atom keys. You need to do:

```<code>item["attributes"]
</code>```

instead of

```<code>item.attributes
</code>```

and similar for other keys.

The price you have is a string. You'll need to convert it to a Float before you can multiply it. You can do it like this using String.trim_leading and String.to_float:

```<code>iex(1)> "$123.45" |> String.trim_leading("$") |> String.to_float
123.45
</code>```

```<code>Enum.map(json, fn {_, item} ->
  %{
    color: item["attributes"]["color"],
    size: item["attributes"]["size"],
    price: item["pricing"]["standard"] |> String.trim_leading("$") |> String.to_float |> Kernel.*(100),
    isAvailable: item["isAvailable"]
  }
end)
|> IO.inspect
</code>```

Output:

```<code>[%{color: "Black", isAvailable: true, price: 4.15e4, size: "11"},
 %{color: "Black", isAvailable: true, price: 4.15e4, size: "11"}]
</code>```

Title: Map JSON values in Elixir

Body:
I have parsed the following JSON using Posion.decode!

json = %{"color-Black|size:10" =>
    %{"attributes" => %{"color" => "Black","size" => "11"},
      "isAvailable" => true,
    "pricing" => %{"standard" => "$415.00", "sale" => 415}},
 "color|size-EU:9.5" =>
    %{"attributes" => %{"color" => "Black","size" => "11"},
      "isAvailable" => true,
    "pricing" => %{"standard" => "$415.00", "sale" => 415}}}

I want to map this and I'm unable to get JSON elements as the text in the node element changes.
So far I've tried.

Enum.map(json , fn(item) ->
%{
  color: item.attributes["color"],
  size: item.attributes["size"],
  price: item.pricing["standard"] * 100,
  isAvailable: item.isAvailable
 }
end)

But this code gives some error related to accessing.

Body:
Three things:

You have a map so Enum.map will give you a tuple of key and value. You just want the value here, so do:

fn {_, item} ->

The keys in your map are strings. The dot syntax only works for atom keys. You need to do:

item["attributes"]

instead of

item.attributes

and similar for other keys.

The price you have is a string. You'll need to convert it to a Float before you can multiply it. You can do it like this using String.trim_leading and String.to_float:

iex(1)> "$123.45" |> String.trim_leading("$") |> String.to_float
123.45

Enum.map(json, fn {_, item} ->
  %{
    color: item["attributes"]["color"],
    size: item["attributes"]["size"],
    price: item["pricing"]["standard"] |> String.trim_leading("$") |> String.to_float |> Kernel.*(100),
    isAvailable: item["isAvailable"]
  }
end)
|> IO.inspect

Output:

[%{color: "Black", isAvailable: true, price: 4.15e4, size: "11"},
 %{color: "Black", isAvailable: true, price: 4.15e4, size: "11"}]


问:
How to use a define inside a format string?
Say I have a character array:

```<code>#define LEN 10
char arr[LEN + 1];
</code>```

Lets do some scanf operation to it:

```<code>scanf("Name: %s", arr);
</code>```

This could be dangerous if someone is typing a name that is longer than 10 characters. So better use this:

```<code>scanf("Name: %10s", arr);
</code>```

Well now I would run into trouble if LEN is changed. I would have to go through the whole code to correct every line where I used the 10 in context of arr. So I thought about somehting like this:

```<code>scanf("Name: %LENs", arr);
</code>```

But this will not work.LEN is not resolved by the preprocessor beacuse it is used inside a string.

How to use a define inside a format string?

答:
C joins adjacent string literals and you can stringify a preprocessor parameter with #, so the following should do the trick:

```<code>#define LEN 10

// this converts to string
#define STR_(X) #X

// this makes sure the argument is expanded before converting to string
#define STR(X) STR_(X)

[...]

scanf("Name: %" STR(LEN) "s", arr);
</code>```

The macros are needed because with just #LEN, you'd end up with LEN expanded to 10, and with only one macro applying # to its argument, the result would be "LEN" (the argument wouldn't be expanded).

The preprocessor / compiler will transform this in the following steps:

```<code>1. scanf("Name: %" STR_(10) "s", arr);
2. scanf("Name: %" "10" "s", arr);
3. scanf("Name: %10s", arr);
</code>```

In the last step, the string literals are joined into a single one.

On a side note, your scanf() format string would require the user to literally enter

Name: xyz
```

<p>to actually match. I doubt this is what you wanted. You probably want something like this:</p>

```fputs("Name: ", stdout);
fflush(stdout);
scanf("%" STR(LEN) "s", arr);
```

Also consider not using scanf() at all. With e.g. fgets(), this whole preprocessor magic is obsolete. For reasons why you shouldn't use scanf(), see my beginners' guide away from scanf().

Body:
Say I have a character array:

#define LEN 10
char arr[LEN + 1];

Lets do some scanf operation to it:

scanf("Name: %s", arr);

This could be dangerous if someone is typing a name that is longer than 10 characters. So better use this:

scanf("Name: %10s", arr);

Well now I would run into trouble if LEN is changed. I would have to go through the whole code to correct every line where I used the 10 in context of arr. So I thought about somehting like this:

scanf("Name: %LENs", arr);

But this will not work.LEN is not resolved by the preprocessor beacuse it is used inside a string.

How to use a define inside a format string?

Body:
C joins adjacent string literals and you can stringify a preprocessor parameter with #, so the following should do the trick:

#define LEN 10

// this converts to string
#define STR_(X) #X

// this makes sure the argument is expanded before converting to string
#define STR(X) STR_(X)

[...]

scanf("Name: %" STR(LEN) "s", arr);

The macros are needed because with just #LEN, you'd end up with LEN expanded to 10, and with only one macro applying # to its argument, the result would be "LEN" (the argument wouldn't be expanded).

The preprocessor / compiler will transform this in the following steps:

1. scanf("Name: %" STR_(10) "s", arr);
2. scanf("Name: %" "10" "s", arr);
3. scanf("Name: %10s", arr);

In the last step, the string literals are joined into a single one.

On a side note, your scanf() format string would require the user to literally enter

Name: xyz

to actually match. I doubt this is what you wanted. You probably want something like this:

fputs("Name: ", stdout);
fflush(stdout);
scanf("%" STR(LEN) "s", arr);

Also consider not using scanf() at all. With e.g. fgets(), this whole preprocessor magic is obsolete. For reasons why you shouldn't use scanf(), see my beginners' guide away from scanf().


问:
TabLayout not filling width when tabMode set to 'scrollable'
I have added TabLayout (from support library v22.2.1) to my Fragment as:

```<code><android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        style="@style/MyColorAccentTabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"/>
</code>```

The issue is that when the Fragment's orientation is landscape (before or after the initial creation of the fragment), the TabLayout doesn't match the width of the Fragment (yes the parent has its width set to match_parent as well).

When screen width is small (i.e not all tabs can be shown at same time):

When screen width is big enough to show all tabs (see the blank space at the right):

If I change tabMode to fixed, width is filled but tabs are too small. Is there any proper solution out there?

答:
You should set app:tabMode="fixed" when you want to show tabs 'fill'.</p>

```<code>**<android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="#353535"
            app:tabMode="fixed"
            android:minHeight="?attr/actionBarSize"
            app:tabIndicatorColor="@color/red"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />**
</code>```

Body:
I have added TabLayout (from support library v22.2.1) to my Fragment as:

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        style="@style/MyColorAccentTabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"/>

The issue is that when the Fragment's orientation is landscape (before or after the initial creation of the fragment), the TabLayout doesn't match the width of the Fragment (yes the parent has its width set to match_parent as well).

When screen width is small (i.e not all tabs can be shown at same time):

When screen width is big enough to show all tabs (see the blank space at the right):

If I change tabMode to fixed, width is filled but tabs are too small. Is there any proper solution out there?

Body:
You should set app:tabMode="fixed" when you want to show tabs 'fill'.

**<android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="#353535"
            app:tabMode="fixed"
            android:minHeight="?attr/actionBarSize"
            app:tabIndicatorColor="@color/red"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />**


问:
Angular 4/5 unit test case .toBe in Services
I am trying to write test case for calling Service and getting response from HTTP. Reference

Now the problem is as following :

expect(data.length).toBe(12); Even though data.length is 100, This code does not throw any exception

```<code>it('Should call HTTP!', inject([SampleDataService], (sampleDataService) => {
  expect(100).toBe(12); //<== This gives me correct exception i.e Expected 100 to be 12.
  sampleDataService.getData().subscribe(
    (data) => {
      console.log('ngOnInit', data.length); // here data.length is 100
      expect(data.length).toBe(12); // This does not throw any exception
    });
}));
</code>```

SampleDataService.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class SampleDataService {

  constructor(private http:HttpClient) { }

  getData(){
    return this.http.get("http://jsonplaceholder.typicode.com/posts");
  }
}
</code>```

app.component.spec.ts

```<code>import { TestBed, async, ComponentFixture,inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { SampleDataService } from './services/sample-data.service';
import { HttpClientModule,HttpClient } from '@angular/common/http';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        HttpClientModule,
        FormsModule,
        ReactiveFormsModule
      ],
      declarations: [
        AppComponent
      ],
      providers:[SampleDataService]
    }).compileComponents();
  }));
  it('Should call HTTP!', inject([SampleDataService], (sampleDataService) => {
    expect(100).toBe(12);
    sampleDataService.getData().subscribe(
      (data) => {
        console.log('ngOnInit', data.length);
        expect(data.length).toBe(12);
      });
  }));
});
</code>```

答:
You typically want to mock Http calls during unit tests. But if really you don't want to, then since http is asynchronous, you need to only end the test once you received the response:</p>

```<code>  it('Should call HTTP!', (done) => {
    const service = TestBed.get(SampleDataService);
    service.getData().subscribe(
      (data) => {
        console.log('ngOnInit', data.length);
        expect(data.length).toBe(12);
        done();
      });
  });
</code>```

Body:
I am trying to write test case for calling Service and getting response from HTTP. Reference

Now the problem is as following :

expect(data.length).toBe(12); Even though data.length is 100, This code does not throw any exception

it('Should call HTTP!', inject([SampleDataService], (sampleDataService) => {
  expect(100).toBe(12); //<== This gives me correct exception i.e Expected 100 to be 12.
  sampleDataService.getData().subscribe(
    (data) => {
      console.log('ngOnInit', data.length); // here data.length is 100
      expect(data.length).toBe(12); // This does not throw any exception
    });
}));

SampleDataService.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class SampleDataService {

  constructor(private http:HttpClient) { }

  getData(){
    return this.http.get("http://jsonplaceholder.typicode.com/posts");
  }
}

app.component.spec.ts

import { TestBed, async, ComponentFixture,inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { SampleDataService } from './services/sample-data.service';
import { HttpClientModule,HttpClient } from '@angular/common/http';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        HttpClientModule,
        FormsModule,
        ReactiveFormsModule
      ],
      declarations: [
        AppComponent
      ],
      providers:[SampleDataService]
    }).compileComponents();
  }));
  it('Should call HTTP!', inject([SampleDataService], (sampleDataService) => {
    expect(100).toBe(12);
    sampleDataService.getData().subscribe(
      (data) => {
        console.log('ngOnInit', data.length);
        expect(data.length).toBe(12);
      });
  }));
});

Body:
You typically want to mock Http calls during unit tests. But if really you don't want to, then since http is asynchronous, you need to only end the test once you received the response:

  it('Should call HTTP!', (done) => {
    const service = TestBed.get(SampleDataService);
    service.getData().subscribe(
      (data) => {
        console.log('ngOnInit', data.length);
        expect(data.length).toBe(12);
        done();
      });
  });


问:
Installing node with brew fails on Mac OS Sierra
I'm trying to install node with homebrew on macOS Sierra.
I run

```<code> brew install node
</code>```

After a seemingly successful install I get the following when trying to run node:

```<code>dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.58.dylib
  Referenced from: /usr/local/bin/node
  Reason: image not found
Abort trap: 6
</code>```

答:
Well I got this error trying to install @angular/cli, realized node might be out of date. Following @mircealungu 's exact steps didn't quite work for me, here is the modified version that worked for me.

```<code>brew uninstall --ignore-dependencies --force node
brew uninstall --ignore-dependencies --force icu4c
brew install icu4c
brew unlink icu4c && brew link icu4c --force
brew install node
</code>```

Body:
I'm trying to install node with homebrew on macOS Sierra.
I run

 brew install node

After a seemingly successful install I get the following when trying to run node:

dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.58.dylib
  Referenced from: /usr/local/bin/node
  Reason: image not found
Abort trap: 6

Body:
Well I got this error trying to install @angular/cli, realized node might be out of date. Following @mircealungu 's exact steps didn't quite work for me, here is the modified version that worked for me.

brew uninstall --ignore-dependencies --force node
brew uninstall --ignore-dependencies --force icu4c
brew install icu4c
brew unlink icu4c && brew link icu4c --force
brew install node


问:
Groovy map method of collections
Is there a map method in Groovy? I want to do something like I do with the following Scala snippet:

```<code>scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)

scala> l.map(_ + 1)
res0: List[Int] = List(2, 3, 4)
</code>```

答:
There is such a method in groovy, it is called collect, for example:

```<code>assert [1, 2, 3].collect { it * 2 } == [2, 4, 6]
</code>```

https://groovy-lang.org/groovy-dev-kit.html#_iterating_on_a_list

ContentLicense: CC BY-SA 2.5

Title: Groovy map method of collections

Body:
Is there a map method in Groovy? I want to do something like I do with the following Scala snippet:

scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)

scala> l.map(_ + 1)
res0: List[Int] = List(2, 3, 4)

Body:
There is such a method in groovy, it is called collect, for example:

assert [1, 2, 3].collect { it * 2 } == [2, 4, 6]

https://groovy-lang.org/groovy-dev-kit.html#_iterating_on_a_list

ContentLicense: CC BY-SA 4.0


问:
Can I depend on check constraint to ensure non-negative balance?
I currently have a table as follows:

```<code>CREATE TABLE Account (
 ID int NOT NULL,
 Balance int,
 CHECK (Balance>=0)
);
</code>```

I also have some application pseudo-code as follows:

```<code>function updateBalance(id Int, howMuch Int) {
 check howMuch is non zero (can be negative or positive)
 read balance for id as bal
 if bal + howMuch >= 0 update else throw error
}
</code>```

I feel that reading balance and checking >= 0 is unnecessary and time consuming, since the database I plan to use supports check constraints (most likely PostgreSQL or H2). Certain ones (such as MySQL) don't support check constraints and will silently ignore them in the create statement).

Should I rely on the database to ensure non-negative balance or do it also within my app?

答:
When considering the MVC architecture, we generally build the business logic in the Controller component. We can rely blindly on PostgreSQL check constraint as well for checking the non-zero constraint. Since yours is an application that is dealing with the database, it is better to handle the check constraint within the application rather than at Data Definition Layer.

It gives us more control over delivering the response of an exception and what message to convey.

Body:
I currently have a table as follows:

CREATE TABLE Account (
 ID int NOT NULL,
 Balance int,
 CHECK (Balance>=0)
);

I also have some application pseudo-code as follows:

function updateBalance(id Int, howMuch Int) {
 check howMuch is non zero (can be negative or positive)
 read balance for id as bal
 if bal + howMuch >= 0 update else throw error
}

I feel that reading balance and checking >= 0 is unnecessary and time consuming, since the database I plan to use supports check constraints (most likely PostgreSQL or H2). Certain ones (such as MySQL) don't support check constraints and will silently ignore them in the create statement).

Should I rely on the database to ensure non-negative balance or do it also within my app?


问:
How to create a class extension in asp.net core?
I want to create my custom service via using userManager. But I don't know how to access to dbContext.

```<code>public static class UserManagerExtensions
{
    public static async Task<IdentityResult> AddProfileAsync(this UserManager<ApplicationUser> userManager, UserProfileModel model)
    {

        // how to access to dbContext here???

        if (await dbContext.SaveChangesAsync() > 0)
        {
            return IdentityResult.Success;
        }

        return IdentityResult.Failed();
    }
}
</code>```

Usage:

```<code>public class UserController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public UserController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IActionResult> Update(UserProfileModel model)
    {
        await _userManager.AddProfileAsync(model);

        return View();
    }
}
</code>```

How to access DbContext class inside a static class?

Thank you!

答: It's generally best to only create a DbContext as needed and discard after "SaveChanges". To be able to create it you just need a connection string, which is usually something you store in a central configuration store.</p>

Body:
I want to create my custom service via using userManager. But I don't know how to access to dbContext.

public static class UserManagerExtensions
{
    public static async Task<IdentityResult> AddProfileAsync(this UserManager<ApplicationUser> userManager, UserProfileModel model)
    {

        // how to access to dbContext here???

        if (await dbContext.SaveChangesAsync() > 0)
        {
            return IdentityResult.Success;
        }

        return IdentityResult.Failed();
    }
}

Usage:

public class UserController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public UserController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IActionResult> Update(UserProfileModel model)
    {
        await _userManager.AddProfileAsync(model);

        return View();
    }
}

How to access DbContext class inside a static class?

Thank you!


问:
Android SDK manager throw Exception with Java 9
Using sdk-tools-darwin-4333796 (26.1.1) with Java 9 when running sdkmanager is throwing :

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
        at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
        at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
        at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
        at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
        at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
        ... 5 more
</code>```

答:
Edit sdkmanager file, find DEFAULT_JVM_OPTS and add --add-modules java.xml.bind argument to it.

For instance, if your sdkmanager file has

```<code>DEFAULT_JVM_OPTS='"-Dcom.android.sdklib.toolsdir=$APP_HOME"'
</code>```

change it to

```<code>DEFAULT_JVM_OPTS='"-Dcom.android.sdklib.toolsdir=$APP_HOME" --add-modules java.xml.bind'
</code>```

Update:  the above works for Java 9 and 10.  The java.xml.bind module was removed in Java 11, and will not be found.

https://www.oracle.com/java/technologies/javase/jdk-11-relnote.html#JDK-8190378

Additional Update: Apparently there are two versions of the sdkmanager, a deprecated one that requires Java8 and a new one that works with Java 11.  See this answer on StackOverflow

Body:
Using sdk-tools-darwin-4333796 (26.1.1) with Java 9 when running sdkmanager is throwing :

Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
        at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
        at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
        at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
        at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
        at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
        ... 5 more

Body:
Edit sdkmanager file, find DEFAULT_JVM_OPTS and add --add-modules java.xml.bind argument to it.

For instance, if your sdkmanager file has

DEFAULT_JVM_OPTS='"-Dcom.android.sdklib.toolsdir=$APP_HOME"'

change it to

DEFAULT_JVM_OPTS='"-Dcom.android.sdklib.toolsdir=$APP_HOME" --add-modules java.xml.bind'

Update:  the above works for Java 9 and 10.  The java.xml.bind module was removed in Java 11, and will not be found.

https://www.oracle.com/java/technologies/javase/jdk-11-relnote.html#JDK-8190378

Additional Update: Apparently there are two versions of the sdkmanager, a deprecated one that requires Java8 and a new one that works with Java 11.  See this answer on StackOverflow


问:
If distinct count reaches 10 in column then just return true/false instead checking laks of rows in spark
//Actually it iterates through laks of columns for distinct rows it is costlier approach because I need to check if distinct count reaches 10 then return true/false.  </p>

```<code>    val distcnt = dfFilter.select(dfFilter.col("colName")).distinct().count()

    if (distcnt > 10) {
      //I need to do stuff here if it greater than 10 distinct rows
    }
</code>```

答: Costly or not its the only approach, distinct count will not be interrupted in between with some condition it will iterate through the whole column and then return a distinct count value and there is no alternative approach as well as per my knowledge but if somebody knows any alternative will be glad to know.</p>

Body:
//Actually it iterates through laks of columns for distinct rows it is costlier approach because I need to check if distinct count reaches 10 then return true/false.

    val distcnt = dfFilter.select(dfFilter.col("colName")).distinct().count()

    if (distcnt > 10) {
      //I need to do stuff here if it greater than 10 distinct rows
    }


问:
How to add text file in my project so that it is not visible to user..?
Sir,

I am developing an application in which i am to save some information in text file. During execution, I wish to read/write data from/to the file(.txt file). I dont want the file to be visible to user. Or if it is visible then it must be in programfile folder of the system and user could not delete the data of the file. What should i do? I tried to add the file in Resource file but could not read and write the file. PLease help me to read/write OR provide some other way to implement the same(described above).

Thanks in advance....

答: you could use IsolatedStorage, it's not fully hidden but at least not easily discoverable as well.</p>


问:
One-to-many relationship only one entry of the many needed
At first, thank you for taking the time to read this

Problem:

Example

```<code>SELECT Article.ID, Article.Name, Article.Price, EV.EV, Pic.Upload_Datum
FROM Article
LEFT JOIN Pic ON Articel.ID = Pic.Artikle_ID
LEFT JOIN Stock ON Stock.ID = Article.Lager_ID
LEFT JOIN EV ON EV.ID = Article.EV_ID
WHERE Article.Activ = "1"
AND Stock.trader_ID = "2"
AND Article.stock_ID = "1"
AND pic.Uploaddate IS NOT BETWEEN 1510903702 AND 1503127702
LIMIT 10
</code>```

Example resutl

ID       Upload

2624919 1489736525

2624919 1489736528

2624920 1507295386

2624920 1507295389

2624920 1507295397

thats one of the results i get but i only need this two:

2624919 1489736525

2624920 1507295386

Now i get foreach Article.ID more than one record, because in the "pic" table there are more than one pictures of any article. The problem is, that i only need the first picture that the sql finds.

I hope its the right way to ask.

Greetings
B3rgi

答:
If you dont really care of which data to take for your pic, see below sample, it will take the first pic of your Article.</p>

```<code>SELECT Article.ID, Article.Name, Article.Price, EV.EV,

         SELECT  Pic.Upload_Datum
         FROM    Pic
         WHERE   Articel.ID = Pic.Artikle_ID
         LIMIT 1) AS Upload_Datum
FROM Article
LEFT JOIN Stock ON Stock.ID = Article.Lager_ID
LEFT JOIN EV ON EV.ID = Article.EV_ID
WHERE Article.Activ = "1"
  AND Stock.trader_ID = "2"
  AND Article.stock_ID = "1"
LIMIT 10
</code>```

Body:
At first, thank you for taking the time to read this

Problem:

Example

SELECT Article.ID, Article.Name, Article.Price, EV.EV, Pic.Upload_Datum
FROM Article
LEFT JOIN Pic ON Articel.ID = Pic.Artikle_ID
LEFT JOIN Stock ON Stock.ID = Article.Lager_ID
LEFT JOIN EV ON EV.ID = Article.EV_ID
WHERE Article.Activ = "1"
AND Stock.trader_ID = "2"
AND Article.stock_ID = "1"
AND pic.Uploaddate IS NOT BETWEEN 1510903702 AND 1503127702
LIMIT 10

Example resutl

ID       Upload

2624919 1489736525

2624919 1489736528

2624920 1507295386

2624920 1507295389

2624920 1507295397

thats one of the results i get but i only need this two:

2624919 1489736525

2624920 1507295386

Now i get foreach Article.ID more than one record, because in the "pic" table there are more than one pictures of any article. The problem is, that i only need the first picture that the sql finds.

I hope its the right way to ask.

Greetings
B3rgi

Body:
If you dont really care of which data to take for your pic, see below sample, it will take the first pic of your Article.

SELECT Article.ID, Article.Name, Article.Price, EV.EV,

         SELECT  Pic.Upload_Datum
         FROM    Pic
         WHERE   Articel.ID = Pic.Artikle_ID
         LIMIT 1) AS Upload_Datum
FROM Article
LEFT JOIN Stock ON Stock.ID = Article.Lager_ID
LEFT JOIN EV ON EV.ID = Article.EV_ID
WHERE Article.Activ = "1"
  AND Stock.trader_ID = "2"
  AND Article.stock_ID = "1"
LIMIT 10


问:
Best way to minify html in an asp.net mvc 5 application
I came across several articles about this topic but most of them are outdated. So what is the best way to minify/get rid of the whitespaces when outputing my views html?</p>

答:
I built a very trivial minifier called RazorHtmlMinifier.Mvc5.

It's operating in compile-time when the cshtml Razor files are converted to C# classes, so it won't have any performance overhead at runtime.

The minification is very trivial, basically just replacing multiple spaces with one (because sometimes a space is still significant, e.g. Hello World is different to HelloWorld).

The source code is very recent and very simple (just one file with less than 100 lines of code) and installation involves just a NuGet package and changing one line in Web.config file.

And all of this is built for the latest version of ASP.NET MVC 5.

Usually, it's recommended to use gzip encoding to minify HTTP responses, but I found out that if you minify the HTML before gzipping, you can still get around 11% smaller responses on average. In my opinion, it's still worth it.

Body:
I built a very trivial minifier called RazorHtmlMinifier.Mvc5.

It's operating in compile-time when the cshtml Razor files are converted to C# classes, so it won't have any performance overhead at runtime.

The minification is very trivial, basically just replacing multiple spaces with one (because sometimes a space is still significant, e.g. <span>Hello</span> <span>World</span> is different to <span>Hello</span><span>World</span>).

The source code is very recent and very simple (just one file with less than 100 lines of code) and installation involves just a NuGet package and changing one line in Web.config file.

And all of this is built for the latest version of ASP.NET MVC 5.

Usually, it's recommended to use gzip encoding to minify HTTP responses, but I found out that if you minify the HTML before gzipping, you can still get around 11% smaller responses on average. In my opinion, it's still worth it.


答:
You should look at the Java docs of the method that you are using:

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html#getBean-java.lang.Class-

Importantly the javadoc states:

Return the bean instance that uniquely matches the given object type,
  if any.

NoUniqueBeanDefinitionException - if more than one bean of the given
  type was found

So if you have more that one beans extending the interface you will get exception.

Title: Difference between Interface and Class in Java

Body:
As per multiple articles in Java Interface and Class are completely different. Let me write an Interface.

package com.main.service;

public interface SomeService{
   public void someMethod();
}

But why below code is allowed in Java?

 com.main.service.SomeService.class;

I am using this code to get beans from Spring application context like below:-

 SomeService someservice = applicationContext
            .getBean(com.main.service.SomeService.class);


问:
print"we don't found this letter" java with loop
this my program

```<code>import java.util.*;
public class LeTter { //open class name
    static Scanner keyboard = new Scanner(System.in); // Scanner
    public static void main(String[] args) { //open main class
        char letter; //decl
        int y, x, z; //decl
        boolean check = false;
        System.out.println("Enter 8 letters: "); // print sentince
        char[] des = new char[8]; //array
        for (y = 0; y < des.length; y++) { // for without semicolon :), open for loop
            des[y] = keyboard.next().charAt(0); //initialize
        } // close for loop
        System.out.println("Enter any letter to check about it: "); //will apper to the user
        letter = keyboard.next().charAt(0); //initi
        for (x = 0; x < des.length; x++) { //for loop opens
            if (des[x] == letter) { //open if loop
                System.out.println("we found it's " + des[x] + " and the index of it is " + x);
                System.out.println("so we will show you this letters " + x + " times");
                for (z = 0; z < x; z++)
                    System.out.println(des[x] + "  ");
                check = false;
            } //close if loop
            if (true)
                System.out.println("are you sure about the letter's you enterd it? we didnt found it ");
        } // close for loop
    } //close main
} //close class
</code>```

put if the user didn't put the letter that not look like 8 letter was enter i want to print this statement "we don't found it"
how can I do it

example:
enter 8 letters
a s d f g h j k
enter any letter
t
we don't found it  << how can I do this??

another example:
enter 8 letters
a s d f g h j k
enter any letter
a
we found it  << i did this , i want the first one ""onlly""

答:
I skip the input and begin from the loop of your code, change it to:</p>

```<code>for (x = 0; x < des.length; x++)
{ // for loop opens
    if (des[x] == letter)
    { // open if loop
        check = true;
        System.out.println("we found it's " + des[x] + " and the index of it is " + x);
        break; // you want to show 1st one only, right?
    } // close if loop
} // close for loop
if (!check)
    System.out.println("are you sure about the letter's you enterd it? we didnt found it ");
</code>```

Body:
this my program

import java.util.*;
public class LeTter { //open class name
    static Scanner keyboard = new Scanner(System.in); // Scanner
    public static void main(String[] args) { //open main class
        char letter; //decl
        int y, x, z; //decl
        boolean check = false;
        System.out.println("Enter 8 letters: "); // print sentince
        char[] des = new char[8]; //array
        for (y = 0; y < des.length; y++) { // for without semicolon :), open for loop
            des[y] = keyboard.next().charAt(0); //initialize
        } // close for loop
        System.out.println("Enter any letter to check about it: "); //will apper to the user
        letter = keyboard.next().charAt(0); //initi
        for (x = 0; x < des.length; x++) { //for loop opens
            if (des[x] == letter) { //open if loop
                System.out.println("we found it's " + des[x] + " and the index of it is " + x);
                System.out.println("so we will show you this letters " + x + " times");
                for (z = 0; z < x; z++)
                    System.out.println(des[x] + "  ");
                check = false;
            } //close if loop
            if (true)
                System.out.println("are you sure about the letter's you enterd it? we didnt found it ");
        } // close for loop
    } //close main
} //close class

put if the user didn't put the letter that not look like 8 letter was enter i want to print this statement "we don't found it"
how can I do it

example:
enter 8 letters
a s d f g h j k
enter any letter
t
we don't found it  << how can I do this??

another example:
enter 8 letters
a s d f g h j k
enter any letter
a
we found it  << i did this , i want the first one ""onlly""

Body:
I skip the input and begin from the loop of your code, change it to:

for (x = 0; x < des.length; x++)
{ // for loop opens
    if (des[x] == letter)
    { // open if loop
        check = true;
        System.out.println("we found it's " + des[x] + " and the index of it is " + x);
        break; // you want to show 1st one only, right?
    } // close if loop
} // close for loop
if (!check)
    System.out.println("are you sure about the letter's you enterd it? we didnt found it ");


问:
How to align Floating Action Button to center
I have one FloatingActionButton. I want it to be middle of 2 LinearLayouts and center of screen like this.

Currently My design is like this

I want it to be at the exact center of the screen. How to do that?

This is my whole xml code

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:id="@+id/viewA"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.6"
        android:orientation="horizontal"/>
    <LinearLayout
        android:id="@+id/viewB"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:orientation="horizontal"/>
</LinearLayout>
<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:src="@drawable/ic_plus"
    app:layout_anchor="@id/viewA"
    android:layout_centerHorizontal="true"
    app:layout_anchorGravity="bottom"
    android:layout_centerInParent="true" />
</code>```

答:
Above solutions did not work for me somehow.
I changed the android:layout_gravity to

android:layout_gravity="bottom|center"

Hope it helps :-)

Body:
I have one FloatingActionButton. I want it to be middle of 2 LinearLayouts and center of screen like this.

Currently My design is like this

I want it to be at the exact center of the screen. How to do that?

This is my whole xml code

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:id="@+id/viewA"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.6"
        android:orientation="horizontal"/>
    <LinearLayout
        android:id="@+id/viewB"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:orientation="horizontal"/>
</LinearLayout>
<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:src="@drawable/ic_plus"
    app:layout_anchor="@id/viewA"
    android:layout_centerHorizontal="true"
    app:layout_anchorGravity="bottom"
    android:layout_centerInParent="true" />


问:
Working with TIFFs (import, export) in Python using numpy
I need a python method to open and import TIFF images into numpy arrays so I can analyze and modify the pixel data and then save them as TIFFs again. (They are basically light intensity maps in greyscale, representing the respective values per pixel)

I couldn't find any documentation on PIL methods concerning TIFF. I tried to figure it out, but only got "bad mode" or "file type not supported" errors.

What do I need to use here?

答:
You can also use pytiff of which I am the author.

```<code>import pytiff

with pytiff.Tiff("filename.tif") as handle:
    part = handle[100:200, 200:400]

# multipage tif
with pytiff.Tiff("multipage.tif") as handle:
    for page in handle:
        part = page[100:200, 200:400]
</code>```

It's a fairly small module and may not have as many features as other modules, but it supports tiled TIFFs and BigTIFF, so you can read parts of large images.

Body:
You can also use pytiff of which I am the author.

import pytiff

with pytiff.Tiff("filename.tif") as handle:
    part = handle[100:200, 200:400]

# multipage tif
with pytiff.Tiff("multipage.tif") as handle:
    for page in handle:
        part = page[100:200, 200:400]

It's a fairly small module and may not have as many features as other modules, but it supports tiled TIFFs and BigTIFF, so you can read parts of large images.


问:
Retrieve inserted row ID in SQL
How do I retrieve the ID of an inserted row in SQL?

Users Table:

```<code>Column  | Type
--------|--------------------------------
ID      | * Auto-incrementing primary key
Name    |
Age     |
</code>```

Query Sample:

```<code>insert into users (Name, Age) values ('charuka',12)
</code>```

答:
In Oracle and PostgreSQL you can do this:

```
INSERT INTO some_table (name, age)
VALUES
('charuka', 12)
RETURNING ID
```

When doing this through JDBC you can also do that in a cross-DBMS manner (without the need for RETURNING) by calling getGeneratedKeys() after running the INSERT

Title: Retrieve inserted row ID in SQL

Body:
How do I retrieve the ID of an inserted row in SQL?

Users Table:

Column  | Type
--------|--------------------------------
ID      | * Auto-incrementing primary key
Name    |
Age     |

Query Sample:

insert into users (Name, Age) values ('charuka',12)

Body:
In Oracle and PostgreSQL you can do this:

INSERT INTO some_table (name, age)
VALUES
('charuka', 12)
RETURNING ID

When doing this through JDBC you can also do that in a cross-DBMS manner (without the need for RETURNING) by calling getGeneratedKeys() after running the INSERT


问:
Is there a single Retransmission Timer for each sent TCP packet?
I have a question concerning the Retransmission Timer of TCP. I have read a lot of articles, blog entries and other stuff about TCP Congestion Control and of course I have came across the Retransmission Timer.

Maybe it is a stupid question but sometimes it is mentioned that for each sent segment a timer is started and at other places it is said that the timer is reset for each sent segment.

So is there a single Retransmission Timer for each sent segment, so that there are as many timers as sent segments, or is there only one Retransmission Timer?

答:
Below lines come from "TCPIP Illustrated, volume 1", so seems only one timer exists, the new one replaces the old one.

Once a sending TCP has established its RTO based upon measurements of the time-varying values of effective RTT, whenever it sends a segment it ensures that a retransmission timer is set appropriately. When setting a retransmission timer, the sequence number of the so-called timed segment is recorded, and if an ACK is received in time, the retransmission timer is canceled. The next time the sender emits a packet with data in it, a new retransmission timer is set, the old one is canceled, and the new sequence number is recorded. The sending TCP therefore continuously sets and cancels one retransmission timer per connection; if no data is ever lost, no retransmission timer ever expires


问:
Laravel intervention/imagecache not found
I am using Laravel 5.3 with intervention image and image cache.
Today I noticed, that there's an error when I want to create a cached image (but it already worked before).

Whoops, looks like something went wrong.

1/1
MissingDependencyException in ImageManager.php line 91:
Please install package intervention/imagecache before running this function.

intervention/imagecache is installed.

I tried to reinstall it (not only intervention/imagecache, but also intervention/image), also I cleared the laravel config cache and tried "composer dump-autoload".

Unfortionately nothing helped.

答:
I found the problem inside the composer.json file
There was the following code:

"autoload-dev": {
         "classmap": [
             "tests/TestCase.php"
         ]
     },

I don't know how it got there, but after I removed it and run "composer dump-autoload" it worked again.


问:
How to prevent controls visually lagging behind on resize inside TableLayoutPanel?
I have a layout of medium complexity based on several nested TableLayoutPanels. Resizing the form causes the controls inside the deeper nested tables to visually lag behind the resize. Firstly, this makes them look like they move around while the form is being resized, but worse, the edges of the controls are visibly clipped when they lag enough to leave their allocated table cells.

Is there any way to prevent this or is this the best TableLayoutPanel can do?

Edit: Having experimented with a bunch of programs I came to the conclusion that lag on resize is a ubiquitous problem. To me, it seems that everyone has resigned that this is inevitable and acceptable. Of course if it's actually inevitable then accepting this is that much easier :)

The easiest way to see the lag in your favourite "good UI" program: resize it by holding the left boundary and watch all right-aligned controls jump around (or alternatively, top boundary & bottom-aligned controls, like statusbars). It's broken all around.

If anyone could provide good reasons why this is inevitable when using native windows controls I will accept that answer. Also, if you find a program using native controls that doesn't suffer this please say so, this could help...

答: Set DoubleBuffered = true. You can set it on the forms.


问:
Map JSON values in Elixir
I have parsed the following JSON using Posion.decode!

```<code>json = %{"color-Black|size:10" =>
    %{"attributes" => %{"color" => "Black","size" => "11"},
      "isAvailable" => true,
    "pricing" => %{"standard" => "$415.00", "sale" => 415}},
 "color|size-EU:9.5" =>
    %{"attributes" => %{"color" => "Black","size" => "11"},
      "isAvailable" => true,
    "pricing" => %{"standard" => "$415.00", "sale" => 415}}}
</code>```

I want to map this and I'm unable to get JSON elements as the text in the node element changes.
So far I've tried.

```<code>Enum.map(json , fn(item) ->
%{
  color: item.attributes["color"],
  size: item.attributes["size"],
  price: item.pricing["standard"] * 100,
  isAvailable: item.isAvailable
 }
end)
</code>```

But this code gives some error related to accessing.

答:
While mapping the map, the iterated key-value pairs come to the mapper as tuples {key, value}:

Enum.map(json, fn {_, %{"attributes" => attributes,
                        "isAvailable" => isAvailable,
                        "pricing" => pricing}} ->
  %{
    color: attributes["color"],
    size: attributes["size"],
    price: pricing["standard"],
    isAvailable: isAvailable
   }
end)

#⇒ [
#    %{color: "Black", isAvailable: true, price: "$415.00", size: "11"},
#    %{color: "Black", isAvailable: true, price: "$415.00", size: "11"}
# ]
```

Here we use an inplace pattern matching for values in mapper to simplify the code of matcher itself and make it less error-prone in a case of bad input.

Title: Map JSON values in Elixir

Body:
I have parsed the following JSON using Posion.decode!

json = %{"color-Black|size:10" =>
    %{"attributes" => %{"color" => "Black","size" => "11"},
      "isAvailable" => true,
    "pricing" => %{"standard" => "$415.00", "sale" => 415}},
 "color|size-EU:9.5" =>
    %{"attributes" => %{"color" => "Black","size" => "11"},
      "isAvailable" => true,
    "pricing" => %{"standard" => "$415.00", "sale" => 415}}}

I want to map this and I'm unable to get JSON elements as the text in the node element changes.
So far I've tried.

Enum.map(json , fn(item) ->
%{
  color: item.attributes["color"],
  size: item.attributes["size"],
  price: item.pricing["standard"] * 100,
  isAvailable: item.isAvailable
 }
end)

But this code gives some error related to accessing.

Body:
While mapping the map, the iterated key-value pairs come to the mapper as tuples {key, value}:

Enum.map(json, fn {_, %{"attributes" => attributes,
                        "isAvailable" => isAvailable,
                        "pricing" => pricing}} ->
  %{
    color: attributes["color"],
    size: attributes["size"],
    price: pricing["standard"],
    isAvailable: isAvailable
   }
end)

#⇒ [
#    %{color: "Black", isAvailable: true, price: "$415.00", size: "11"},
#    %{color: "Black", isAvailable: true, price: "$415.00", size: "11"}
# ]

Here we use an inplace pattern matching for values in mapper to simplify the code of matcher itself and make it less error-prone in a case of bad input.


问:
Submitting html-form data and iframe input simultaneously
I have a page ( index.html ) with a form. On submit the data is posted to a php-file which then stores said data in a (temporary) xml-file, however, I also have a number of iframes which also contain forms.
At first, I was planning on simply posting the input-data from the iframes to a seperate php file but I encountered several problems:

-I have several iframes, but I don't have a fixed amount since the user is supposed to be able to delete/ add iframes. Therefore I can't just tell iframe 1 to send its data to php-file no. 1, iframe 2 to send its data to php-file no.2 etc.., I need a flexible solution.

-I tried to submit all iframe inputs to ONE php file and was hoping it'd work since the xml-file this php-file sends the data to is only updated and not completely overwritten. As you might guess, this did not work.

-Another problem I encountered is that the user may go back and edit whatever he entered into the iframe. The data should only be saved once he clicks on the save button in the html-file to prevent that.

I also tried submitting the data via JavaScript, as people in similar questions suggested, but that did not work out for me. So I guess what I would like, is a suggestion as to how I should go about this. How can I send all the data once the "main" save button is clicked, it doesn't matter if the data goes to several php files. The solution shouldn't depend on a fixed amount of elements as that amount is not always the same.

Here's the iframe-html:

```<code><form method="POST" action="php/iframe.php">

    <label>Your thoughts:</label>
    <input type="text" name="header">

    <label>Suggestions:</label>
    <textarea type="text" name="textbox"></textarea>

    <input type="button" value="submit">
</form>
</code>```

(It's basically the same for all Iframes).
Please let me know if you need any additional information.
Edit: I read that submitting forms at the same time may cause interference, I know that much

Edit:

Relevant index.html:

```<code><form method="post" action="main.php">

    <div id="firstSection"
       <label>First input</label>
       <input type="text" name="input[]">
       <button type="button" onclick="openIframe1()">Read more</button>
    </div>
    <div id="secondSection"
       <label>Second input</label>
       <input type="text" name="input[]">
       <button type="button" onclick="openIframe2()">Read more</button>
    </div>

    <button type="submit" value="submit"></button>

</form>

    <div class="iframe">
        <button type="button" class="close">Close</button>
        <iframe src="iframe1.html"></iframe>

    </div>
    <div class="iframe">
        <button type="button" class="close">Close</button>
        <iframe src="iframe2.html"></iframe>

    </div>
</code>```

答: Define an array of your iframe inputs in the main page as hidden element, on click submit in the main page loop through the iframe by getting the datas and append to your hidden element from where you can now post that to your back end.. try this: Access jQuery data from iframe element </p>

Body:
I have a page ( index.html ) with a form. On submit the data is posted to a php-file which then stores said data in a (temporary) xml-file, however, I also have a number of iframes which also contain forms.
At first, I was planning on simply posting the input-data from the iframes to a seperate php file but I encountered several problems:

-I have several iframes, but I don't have a fixed amount since the user is supposed to be able to delete/ add iframes. Therefore I can't just tell iframe 1 to send its data to php-file no. 1, iframe 2 to send its data to php-file no.2 etc.., I need a flexible solution.

-I tried to submit all iframe inputs to ONE php file and was hoping it'd work since the xml-file this php-file sends the data to is only updated and not completely overwritten. As you might guess, this did not work.

-Another problem I encountered is that the user may go back and edit whatever he entered into the iframe. The data should only be saved once he clicks on the save button in the html-file to prevent that.

I also tried submitting the data via JavaScript, as people in similar questions suggested, but that did not work out for me. So I guess what I would like, is a suggestion as to how I should go about this. How can I send all the data once the "main" save button is clicked, it doesn't matter if the data goes to several php files. The solution shouldn't depend on a fixed amount of elements as that amount is not always the same.

Here's the iframe-html:

<form method="POST" action="php/iframe.php">

    Your thoughts:
    <input type="text" name="header">

    Suggestions:
    <textarea type="text" name="textbox"></textarea>

    <input type="button" value="submit">
</form>

(It's basically the same for all Iframes).
Please let me know if you need any additional information.
Edit: I read that submitting forms at the same time may cause interference, I know that much

Edit:

Relevant index.html:

<form method="post" action="main.php">

    <div id="firstSection"
       First input
       <input type="text" name="input[]">
       <button type="button" onclick="openIframe1()">Read more</button>

    <div id="secondSection"
       Second input
       <input type="text" name="input[]">
       <button type="button" onclick="openIframe2()">Read more</button>

    <button type="submit" value="submit"></button>

</form>

        <button type="button" class="close">Close</button>

        <button type="button" class="close">Close</button>


问:
Unexpected Connection Reset: A PHP or an Apache issue?
I have a PHP script that keeps stopping at the same place every time and my browser reports:

The connection to the server was reset
  while the page was loading.

I have tested this on Firefox and IE, same thing happens. So, I am guessing this is an Apache/PHP config problem. Here are few things I have set.

PHP.ini

```<code>max_execution_time = 300000
max_input_time = 300000
memory_limit = 256M
</code>```

Apache (httpd.conf)

```<code>Timeout 300000
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 0
</code>```

Are the above correct? What can be causing this and what can I set?

I am running PHP (5.2.12.12) as a
  module on Apache (2.2) on a Windows
  Server 2003.

It is very likely this is an Apache or PHP issue as all browsers do the same thing. I think the script runs for exactly 10 mins (600 seconds).

答:
Differences between 2 PHP configs were indeed the root cause of the issue on my end. My app is based on the NuSOAP library.

On config 1 with PHP 5.2, it was running fine as PHP's SOAP extension was off.

On config 2 with PHP 5.3, it was giving "Connection Reset" errors as PHP's SOAP extension was on.

Switching the extension off allowed to get my app running on PHP 5.3 without having to rewrite everything.

Body:
I have a PHP script that keeps stopping at the same place every time and my browser reports:

The connection to the server was reset
  while the page was loading.

I have tested this on Firefox and IE, same thing happens. So, I am guessing this is an Apache/PHP config problem. Here are few things I have set.

PHP.ini

max_execution_time = 300000
max_input_time = 300000
memory_limit = 256M

Apache (httpd.conf)

Timeout 300000
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 0

Are the above correct? What can be causing this and what can I set?

I am running PHP (5.2.12.12) as a
  module on Apache (2.2) on a Windows
  Server 2003.

It is very likely this is an Apache or PHP issue as all browsers do the same thing. I think the script runs for exactly 10 mins (600 seconds).


问:
How can I extract links from HTML?
I want to extract URLs from HTML to store in a CLOB datatype within an Oracle database.

Part of the HTML file looks like this:

```<code><a class="href_class" href="/download/file.zip"></a>
</code>```

I only need to take this part from HTML: /download/file.zip and put all the download links in the database. How, in regexp, can I indicate that the class name is matching a specific value like href_class?

I want to know what is the best way to resolve this problem with regexp or some other methods?

答:
Since html is a structured document, you can load it as an XMLType in oracle and apply the appropriate xpath expressions to get the information required:

```<code>declare
    html CLOB := '<html><a class="href_class" href="/download/file.zip"></a><a class="href_class" href="/download/file2.zip"></a></html>';
    xml XMLType;
    idx NUMBER := 1;
begin
    xml := XMLType(html);
    WHILE xml.existsNode('//a[@class=''href_class''][' || idx || ']/@href') = 1 LOOP
        dbms_output.put_line(xml.extract('//a[@class=''href_class''][' || idx || ']/@href').getStringVal());
        idx := idx + 1;
    END LOOP;
end;
</code>```

https://docs.oracle.com/cd/B28359_01/appdev.111/b28419/t_xml.htm#BABHCHHJ

Title: How can I extract links from HTML?

Body:
I want to extract URLs from HTML to store in a CLOB datatype within an Oracle database.

Part of the HTML file looks like this:

I only need to take this part from HTML: /download/file.zip and put all the download links in the database. How, in regexp, can I indicate that the class name is matching a specific value like href_class?

I want to know what is the best way to resolve this problem with regexp or some other methods?

Body:
Since html is a structured document, you can load it as an XMLType in oracle and apply the appropriate xpath expressions to get the information required:

declare
    html CLOB := '<html><a class="href_class" href="/download/file.zip"></a><a class="href_class" href="/download/file2.zip"></a></html>';
    xml XMLType;
    idx NUMBER := 1;
begin
    xml := XMLType(html);
    WHILE xml.existsNode('//a[@class=''href_class''][' || idx || ']/@href') = 1 LOOP
        dbms_output.put_line(xml.extract('//a[@class=''href_class''][' || idx || ']/@href').getStringVal());
        idx := idx + 1;
    END LOOP;
end;

https://docs.oracle.com/cd/B28359_01/appdev.111/b28419/t_xml.htm#BABHCHHJ


问:
Need to display 2 input text after selecting a specific value in drop down in angular 4
I have a specific requirement. I need to display 2 input text fields after selecting a specific value from a drop down which is 'Add New...'
My code snippet is below -

```<code>    <td>
    <div *ngIf="item.showOperationField">
        <p-checkbox
            value ="inflationaryImpactCheck"
            label="Save for Inflationary Impact"
            name = "calculationSaveInflation"
            [(ngModel)]="item.inflationaryImpact"
            pTooltip="Check the Inflationary Impact box to map this calculation to an index for Inflationary Pressure calculation."
            binary="true">
        </p-checkbox>
    </div>
    </td>
    <td>
    <div *ngIf="item.inflationaryImpact">
        <p-dropdown
            [style]="{'width':'200px'}"
            [options]="inflation"
            name = "calculationInflation"
            [(ngModel)]="item.selectedInflation">
        </p-dropdown>
    </div>
    </td>
<td>
<div *ngIf="item.selectedInflation=='Add New...'">
   <input
    [style]="{'width':'200px'}"
    type="text"
    name="catValue"
    pInputText
    [(ngModel)]="item.catValue"
    />
</div>
</td>
</code>```

Now I need to display 2 input boxes while selecting a specific value from the drop down "inflation" which is 'Add New...'. I have tried with the above  code snippet but nothing happened.
Please help me.

答:
Hope you have not changed the change detection, and left it as default.
If change detection is On-push, then trigger change detection manually.</p>

Body:
I have a specific requirement. I need to display 2 input text fields after selecting a specific value from a drop down which is 'Add New...'
My code snippet is below -

   <input
    [style]="{'width':'200px'}"
    type="text"
    name="catValue"
    pInputText
    [(ngModel)]="item.catValue"
    />

Now I need to display 2 input boxes while selecting a specific value from the drop down "inflation" which is 'Add New...'. I have tried with the above  code snippet but nothing happened.
Please help me.


问:
how to define a Scala function that takes multiple return values
I want to write a generic function that returns both session(Cassandra database) and connection(MySQL) is it possible?

Here is my code:

```<code>def getdb: Session = {
    var cluster = Cluster.builder().addContactPoint("127.0.0.1").build()
    var session: Session = cluster.connect("keyspace")
    if (session.getState != null) {
      currentDB = "cassandra"
      return session
      }
      else{
      //code for mysql connection
      return Connection
      }
}
</code>```

How should I define my function such that get db should return to whichever it is connected.

答:
I think you can return both of them in a tuple. Whichever is null should be returned as Option.

Some usefeul links that might help:

How to define Scala methods that return multiple items (tuples)

How to check for null in a single statement in scala?

Body:
I want to write a generic function that returns both session(Cassandra database) and connection(MySQL) is it possible?

Here is my code:

def getdb: Session = {
    var cluster = Cluster.builder().addContactPoint("127.0.0.1").build()
    var session: Session = cluster.connect("keyspace")
    if (session.getState != null) {
      currentDB = "cassandra"
      return session
      }
      else{
      //code for mysql connection
      return Connection
      }
}

How should I define my function such that get db should return to whichever it is connected.


问:
Uitableview Cell Animation like Secret App
Any idea, How can i implement-
Secret App Settings list cell animation.

I was trying with this, but not any success because its adding all rows same time.

[self.tableview reloadSections:sectionIndexSet
  withRowAnimation:UITableViewRowAnimationBottom];

If i am inserting one by one row then this animation is not working from bottom to top animation.

Any suggestion how can i do this ?

答:
Swift-4 Version of Claudio's Answer

```<code>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

        let rect = tableView.rectForRow(at: indexPath)

        cell.frame = CGRect(x: cell.frame.origin.x,
                            y: cell.frame.origin.y + 568,
                            width: cell.frame.size.width,
                            height: cell.frame.size.height)

        UIView.animate(withDuration: 0.5, delay: 0.1*Double(indexPath.row), options: UIViewAnimationOptions.curveEaseInOut, animations: {
            cell.frame = CGRect(x: rect.origin.x,
                                y: rect.origin.y-30,
                                width: rect.width,
                                height: rect.height)
        }) { (completed) in
            UIView.animate(withDuration: 0.5, animations: {
                cell.frame = rect
            })
        }

    }
</code>```

Body:
Swift-4 Version of Claudio's Answer

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

        let rect = tableView.rectForRow(at: indexPath)

        cell.frame = CGRect(x: cell.frame.origin.x,
                            y: cell.frame.origin.y + 568,
                            width: cell.frame.size.width,
                            height: cell.frame.size.height)

        UIView.animate(withDuration: 0.5, delay: 0.1*Double(indexPath.row), options: UIViewAnimationOptions.curveEaseInOut, animations: {
            cell.frame = CGRect(x: rect.origin.x,
                                y: rect.origin.y-30,
                                width: rect.width,
                                height: rect.height)
        }) { (completed) in
            UIView.animate(withDuration: 0.5, animations: {
                cell.frame = rect
            })
        }

    }


问:
Paginate TEMPORARY TABLE in Cakephp?
Let say I have a table named 'products' and Model named 'Product'.

'products' table has 3 fields id,title,price,created

I want to calculate cal_price (which varies per record and day of search) and create a temporary table with 4 fields i.e. id,title,price,cal_price  with order by cal_price

Now, all I want is to paginate this temporary table.

using $this->paginate();

eg.

```<code>table_products

 id    title    price   created
 3      demo1    23     2011-12-12
 4      demo2    43     2011-12-13
 56     demo3    26     2011-12-16
</code>```

sort 'temp_table' order by cal_price and paginate

```<code>temp_table

 id    title    price   cal_price created
 3      demo1    23        12       2011-12-12
 4      demo2    43        43       2011-12-13
 56     demo3    26        88       2011-12-16
</code>```

*The underlying problem to the solution is HOW DO I assign temp_table to a model at run time because once I do it I can use $this->paginate('temp_model') and solve the problem*

答:
you dont need a model for your temporary table if you have respected the conventions for the tables' names, so "temp_table" wont work, cause the name must be plural.

Let's say that your temporary table is called "temp_prices" (i'm not using prefixes on tables)
,the name of the Model should be "TempPrice". To paginate the table use this on your controller

```<code>$this->loadModel('TempPrice'); //will load the model on the controller
$this->paginate['TempPrice'] = array(); //you can change the pagination options here
$resp = $this->paginate('TempPrices');
</code>```

Good Luck

Title: Paginate TEMPORARY TABLE in Cakephp?

Body:
Let say I have a table named 'products' and Model named 'Product'.

'products' table has 3 fields id,title,price,created

I want to calculate cal_price (which varies per record and day of search) and create a temporary table with 4 fields i.e. id,title,price,cal_price  with order by cal_price

Now, all I want is to paginate this temporary table.

using $this->paginate();

eg.

table_products

 id    title    price   created
 3      demo1    23     2011-12-12
 4      demo2    43     2011-12-13
 56     demo3    26     2011-12-16

sort 'temp_table' order by cal_price and paginate

temp_table

 id    title    price   cal_price created
 3      demo1    23        12       2011-12-12
 4      demo2    43        43       2011-12-13
 56     demo3    26        88       2011-12-16

*The underlying problem to the solution is HOW DO I assign temp_table to a model at run time because once I do it I can use $this->paginate('temp_model') and solve the problem*

Body:
you dont need a model for your temporary table if you have respected the conventions for the tables' names, so "temp_table" wont work, cause the name must be plural.

Let's say that your temporary table is called "temp_prices" (i'm not using prefixes on tables)
,the name of the Model should be "TempPrice". To paginate the table use this on your controller

$this->loadModel('TempPrice'); //will load the model on the controller
$this->paginate['TempPrice'] = array(); //you can change the pagination options here
$resp = $this->paginate('TempPrices');

Good Luck


问:
Mean of a column I filtered using outlier parameters
I am working on a function which basically filters out rows based on two outliers in a column. I am passing in the column name, the lower outlier and the upper outlier. Even though I got the table filtering to work in a somewhat ugly way (suggestions to do it in one line appreciated), I am having trouble returning the mean of that particular column afterwards. I tried using get(), as the column name is a string, but get an error instead. I also had a look at colMeans() but could not make it work.

```<code>findMean <- function(colname, outlier_lower, outlier_upper) {
  initial.data <- survey %>%
    filter_(paste0(colname, "<", outlier_upper))
  filtered.data <- initial.data %>%
    filter_(paste0(colname, ">=", outlier_lower))
  mena <- mean(get(filtered.data$colname))
  return(mean)
}
</code>```

答:
Never mind, I got it to work.</p>

```<code>findMean <- function(colname, outlier_lower, outlier_upper) {
  initial.data <- survey %>%
    filter_(paste0(colname, "<", outlier_upper))
  filtered.data <- initial.data %>%
    filter_(paste0(colname, ">=", outlier_lower)) %>%
    summarise(mean = mean(get(colname)))

  return(filtered.data$mean)
}
</code>```

Body:
I am working on a function which basically filters out rows based on two outliers in a column. I am passing in the column name, the lower outlier and the upper outlier. Even though I got the table filtering to work in a somewhat ugly way (suggestions to do it in one line appreciated), I am having trouble returning the mean of that particular column afterwards. I tried using get(), as the column name is a string, but get an error instead. I also had a look at colMeans() but could not make it work.

findMean <- function(colname, outlier_lower, outlier_upper) {
  initial.data <- survey %>%
    filter_(paste0(colname, "<", outlier_upper))
  filtered.data <- initial.data %>%
    filter_(paste0(colname, ">=", outlier_lower))
  mena <- mean(get(filtered.data$colname))
  return(mean)
}

Body:
Never mind, I got it to work.

findMean <- function(colname, outlier_lower, outlier_upper) {
  initial.data <- survey %>%
    filter_(paste0(colname, "<", outlier_upper))
  filtered.data <- initial.data %>%
    filter_(paste0(colname, ">=", outlier_lower)) %>%
    summarise(mean = mean(get(colname)))

  return(filtered.data$mean)
}


问:
Circular bitmap with Universal Image Loader
We are showing a notification with a large icon get from an URL. So, in order to load the image we are using Universal Image Loader with the following code:

```<code>mImageLoader.loadImage(imagePath, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            notificationBuilder.setLargeIcon(loadedImage);
            notificationManager.notify(notification.getId(), notificationBuilder.build());
        }
});
</code>```

This code is working fine and the image is successfully shown. Our problem is that we want to show a circular large icon, so we need the bitmap to be circular. We have tried by setting:

```<code>    final DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
            .displayer(new RoundedBitmapDisplayer(1000))
            .build();
</code>```

But this is not working, we've tried with RoundedBitmapDrawable, but we need a bitmap and not a bitmapdrawable.
Please, how could we do in order to get a circular bitmap?

Thanks in advance.

答:
Did you try setting the option .displayer(new CircleBitmapDisplayer()) ? For example:

```<code>DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
 .displayer(new CircleBitmapDisplayer())
 .build();
</code>```

Body:
We are showing a notification with a large icon get from an URL. So, in order to load the image we are using Universal Image Loader with the following code:

mImageLoader.loadImage(imagePath, new SimpleImageLoadingListener() {
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            notificationBuilder.setLargeIcon(loadedImage);
            notificationManager.notify(notification.getId(), notificationBuilder.build());
        }
});

This code is working fine and the image is successfully shown. Our problem is that we want to show a circular large icon, so we need the bitmap to be circular. We have tried by setting:

    final DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
            .displayer(new RoundedBitmapDisplayer(1000))
            .build();

But this is not working, we've tried with RoundedBitmapDrawable, but we need a bitmap and not a bitmapdrawable.
Please, how could we do in order to get a circular bitmap?

Thanks in advance.

Body:
Did you try setting the option .displayer(new CircleBitmapDisplayer()) ? For example:

DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
 .displayer(new CircleBitmapDisplayer())
 .build();


问:
how to access WSL on Windows Server on AWS EC2?
WSL stands for Windows Subsystem for Linux. Is it even available on EC2?

All the guide I found talks about Windows Desktop, not server.

答:
As of August 2017, WSL is available on Windows Server insider builds..
Although I haven't tried it, I assume you could start a Windows Server 2016 instance and enable Windows Insider updates.
The installation guide for installing WSL on Windows Server is here.</p>


问:
org.openqa.selenium.StaleElementReferenceException: element is not attached to the page document while iterating through a List
I don't know why this error shows up . Need help to fix it . Website i am working on :"http://freevideolectures.com/Course/3680/Pentaho-BI" . In this site </p>

```<code>List<WebElement> cl = d.findElements(By.xpath("//ul[@class='lecture_menu']/li/a"));
System.out.println(cl.size());

for(int e=0 ; e<=cl.size()-1; e++) {
        cl.get(e).click();// i think the error shows up here, the loop runs for e=0 ,
        Thread.sleep(1000);
        String q = d.findElement(By.xpath(".//*[@id='cs-about']/div/div[2]/div[2]/span/a")).getAttribute("href");
        System.out.println(q);
}
</code>```

<p>The loop runs once for e=0 , i am getting the output for that . After this the error shows up . error: stale element reference: element is not attached to the page document.  Help Please .  </p>

答:
Just break the loop when you find the element you want to click on it.

Reason is it is finding element even though that element is clicked. Use For -If Loop so when you get that element break it

Body:
I don't know why this error shows up . Need help to fix it . Website i am working on :"http://freevideolectures.com/Course/3680/Pentaho-BI" . In this site

List<WebElement> cl = d.findElements(By.xpath("//ul[@class='lecture_menu']/li/a"));
System.out.println(cl.size());

for(int e=0 ; e<=cl.size()-1; e++) {
        cl.get(e).click();// i think the error shows up here, the loop runs for e=0 ,
        Thread.sleep(1000);
        String q = d.findElement(By.xpath(".//*[@id='cs-about']/div/div[2]/div[2]/span/a")).getAttribute("href");
        System.out.println(q);
}

The loop runs once for e=0 , i am getting the output for that . After this the error shows up . error: stale element reference: element is not attached to the page document.  Help Please .


问:
How to get access to a file from one child module into another child module in maven?
This is my maven project Structure:

```<code>Parent Module
|
|---Child Module A
       |
       |--target/xyz.jar (generated during mvn clean install)
|---Child Module B
       |
       |--target/abc.jar (generated during mvn clean install)
       |--rpm-maven-plugin (in pom.xml file)
</code>```

Reactor Build Order:
 1. Parent
 2. Child A
 3. Child B

I want to access xyz.jar in mappings sources so that the rpm contains/bundles both abc.jar and xyz.jar inside a single rpm. I tried doing

./Child A/target/xyz.jar

and

Child A/target/xyz.jar

but it says source location does not exists. I am not sure how maven can traverse from one child module to another child module.

Thanks.

答: You do not access other artifacts through relative paths, but you use the Maven coordinates. After clean install, the respective artifact is in your local repository, so you can get it through its GAV. If you need to copy it, look at the dependency:copy goal.

Body:
This is my maven project Structure:

Parent Module
|
|---Child Module A
       |
       |--target/xyz.jar (generated during mvn clean install)
|---Child Module B
       |
       |--target/abc.jar (generated during mvn clean install)
       |--rpm-maven-plugin (in pom.xml file)

Reactor Build Order:
 1. Parent
 2. Child A
 3. Child B

I want to access xyz.jar in mappings sources so that the rpm contains/bundles both abc.jar and xyz.jar inside a single rpm. I tried doing

./Child A/target/xyz.jar

and

Child A/target/xyz.jar

but it says source location does not exists. I am not sure how maven can traverse from one child module to another child module.

Thanks.


问:
How to handle uppercase and lowercase characters when using UIKeyCommand
We are in the process of receiving and processing keyboard input.

Among my source code,

```<code>UIKeyCommand *menuKey = [UIKeyCommand keyCommandWithInput:[NSString stringWithFormat:@"%c", 77]
                                                modifierFlags:0
                                                       action:@selector(menuKey:)];
</code>```

There is this part.

However, if you process it like this, it will only react when it is an uppercase 'M', and it does not respond when it is a lowercase 'm'.

Is there a way to handle UIKeyCommand with all uppercase and lowercase characters?

答: The reason is that you only look for 77 which is ASCII code for M. In order to allow m, you need to add 109 as well

Body:
We are in the process of receiving and processing keyboard input.

Among my source code,

UIKeyCommand *menuKey = [UIKeyCommand keyCommandWithInput:[NSString stringWithFormat:@"%c", 77]
                                                modifierFlags:0
                                                       action:@selector(menuKey:)];

There is this part.

However, if you process it like this, it will only react when it is an uppercase 'M', and it does not respond when it is a lowercase 'm'.

Is there a way to handle UIKeyCommand with all uppercase and lowercase characters?


问:
What is the meaning of UriComponentsBuilder?
I get an example UriComponentsBuilder while learning spring boot. I don't know the meaning of UriComponentsBuilder and the function of UriComponentsBuilder.</p>

答:
Yes, this used for constructing URI. Particularly useful when you want to invoke webservices in your class. Eg:

```<code>String baseUri = "/sample-uri"
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(uri);
builder.queryParam("id", "1");
String uri= builder.build().encode().toUriString();
</code>```

It is evident that you can pass additional params, to this. This provide a clean and efficient way of creating uris than writing those as plain text.

Body:
Yes, this used for constructing URI. Particularly useful when you want to invoke webservices in your class. Eg:

String baseUri = "/sample-uri"
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(uri);
builder.queryParam("id", "1");
String uri= builder.build().encode().toUriString();

It is evident that you can pass additional params, to this. This provide a clean and efficient way of creating uris than writing those as plain text.