问:
Increasing and decreasing value of the clicks of the button
Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.

I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:

var clicks = 0;

function clickME() {
  clicks += 1;
  if (clicks == 2) {
    clicks = 0;
  }
  document.getElementById("clicks").innerHTML = clicks;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="Button" id="bt" /></code>```

答:
Since you have this tagged as jQuery here is a solution using jQuery. The solution involves using the data- attribute to hold the click count for each button (input). Not sure why you use inputs instead of buttons, but I kept that the same

It also has a getTotal() function that goes through each element and tallies the click to see how many slots were selected and displays that number for you.

$(document).ready(function() {
  $(".btn").on("click", clickME);
});

function clickME() {
  var clicks = $(this).data("clicks");
  var newClicks = parseInt(clicks) + 1;
  if(newClicks > 1){
    newClicks = 0;
  }
  // set the new click count on the element
  $(this).data("clicks", newClicks);
  setTotal();
}

function setTotal(){
  var total = 0;
  $(".btn").each(function(imdex, btn) {
    var currClicks = parseInt($(btn).data("clicks"));
    total += currClicks;
  });
  $("#clicks").text(total);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="Button" class="btn" data-clicks=0 value="0" />
<input type="Button" class="btn" data-clicks=0 value="1" />
<input type="Button" class="btn" data-clicks=0 value="2" />
<input type="Button" class="btn" data-clicks=0 value="3" />
<input type="Button" class="btn" data-clicks=0 value="4" />
<input type="Button" class="btn" data-clicks=0 value="5" />
<input type="Button" class="btn" data-clicks=0 value="6" />

<div>
  <p>You've choose 0 slot/s.</p>
</div></code>```

Body:
Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.

I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:

var clicks = 0;

function clickME() {
  clicks += 1;
  if (clicks == 2) {
    clicks = 0;
  }
  document.getElementById("clicks").innerHTML = clicks;
}

<input type="Button" id="bt" />

Body:
Since you have this tagged as jQuery here is a solution using jQuery. The solution involves using the data- attribute to hold the click count for each button (input). Not sure why you use inputs instead of buttons, but I kept that the same

It also has a getTotal() function that goes through each element and tallies the click to see how many slots were selected and displays that number for you.

$(document).ready(function() {
  $(".btn").on("click", clickME);
});

function clickME() {
  var clicks = $(this).data("clicks");
  var newClicks = parseInt(clicks) + 1;
  if(newClicks > 1){
    newClicks = 0;
  }
  // set the new click count on the element
  $(this).data("clicks", newClicks);
  setTotal();
}

function setTotal(){
  var total = 0;
  $(".btn").each(function(imdex, btn) {
    var currClicks = parseInt($(btn).data("clicks"));
    total += currClicks;
  });
  $("#clicks").text(total);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="Button" class="btn" data-clicks=0 value="0" />
<input type="Button" class="btn" data-clicks=0 value="1" />
<input type="Button" class="btn" data-clicks=0 value="2" />
<input type="Button" class="btn" data-clicks=0 value="3" />
<input type="Button" class="btn" data-clicks=0 value="4" />
<input type="Button" class="btn" data-clicks=0 value="5" />
<input type="Button" class="btn" data-clicks=0 value="6" />

<div>
  <p>You've choose <a id="clicks">0</a> slot/s.</p>
</div>


来源: stackexchange

问:
React-infinite-calendar range selection
I am facing issues with onSelect event for range selection in react-infinite-calendar. Can any one suggest me with answers ? I want to select start date and end date and get those values to pass to the state.

答:
JSX

```<code><InfiniteCalendar
    Component={withRange(Calendar)}
    height={350}
    min={new Date(2017,8,1)}
    selected={this.state.selectedDates}
    layout={'portrait'}
    width={'100%'}
    onSelect={this.onCalendarSelect}
/>
</code>```

onCalendarSelectCode

```<code>onCalendarSelect = (e) => {
        if (e.eventType === 3) {
            this.setState({ selectedDates: {
                start: e.start,
                end: e.end,
            } });
        }
    }
</code>```

on select with range functionality will return an object with start, end, and eventType. Event type of 3 will indicate user has selected a start and end. You can then set this to state.

ContentLicense: CC BY-SA 3.0

Title: React-infinite-calendar range selection

Body:
JSX

<InfiniteCalendar
    Component={withRange(Calendar)}
    height={350}
    min={new Date(2017,8,1)}
    selected={this.state.selectedDates}
    layout={'portrait'}
    width={'100%'}
    onSelect={this.onCalendarSelect}
/>

onCalendarSelectCode

onCalendarSelect = (e) => {
        if (e.eventType === 3) {
            this.setState({ selectedDates: {
                start: e.start,
                end: e.end,
            } });
        }
    }

on select with range functionality will return an object with start, end, and eventType. Event type of 3 will indicate user has selected a start and end. You can then set this to state.


问:
Is there anyway to disable the styling of select elements in the JQuerymobile libraries
I'd like to have a native select-menu within my application, so it would be great if I could just set a flag like 'data-theming="none"' to mark this control as not to be styled by jquery mobile. is this possible?

I've had a look at http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.js and can see that it applies the selectmenu() function to all select elements bar ui-slider ones.

I'm pretty new to JQuery, my question is, is it possible to override the selectmenu() function in the JQuery mobile library with my own one that does nothing and if so how do I do this? My other option is to move away from the CDN hosted JQueryMobile and download and edit the existing one.

Thanks in advance!

答:
data-role="nojs" should do the trick.

This attribute makes jquery mobile skip the element and its contents.

As a workaround I suggest:

wrap the select in a div you can locate easily and add something like this to the page:

```<code>$(function(){
$d=$('#thedivthere');
$s=$d.find('select').attr('class','').clone();
$d.empty().append($s);
});
</code>```

This will not be covered by jquery mobile, because adding this happens later. And it removes any classes that jqm added.

ContentLicense: CC BY-SA 2.5

Body:
data-role="nojs" should do the trick.

This attribute makes jquery mobile skip the element and its contents.

As a workaround I suggest:

wrap the select in a div you can locate easily and add something like this to the page:

$(function(){
$d=$('#thedivthere');
$s=$d.find('select').attr('class','').clone();
$d.empty().append($s);
});

This will not be covered by jquery mobile, because adding this happens later. And it removes any classes that jqm added.


问:
Constraint error with private part, arrays and pointers
I am trying to do a typical Get procedure with this features:

Header:

```<code>procedure Get (M:Map; Key: in Key_Type; Value: out Value_Type; Success: out Boolean) is
</code>```

private part:

```<code>type Cell is record
    Key: Key_Type;
    Value: Value_Type;
    Full:Boolean:= False;
end record

type Cell_Array is array (1..50) of Cell;
type Cell_Array_A is access Cell_Array;

type Map is record
    P_Array: Cell_Array_A;
    Length:Natural=0;
    Indice:Natural;
end record
</code>```

My first condition on my Get procedure has the following aspect:

```<code>for k in 1..NumClien loop
    if M.P_Array(k).Key = Key then
...
</code>```

But when I try to execute it, it always gives me the following error:
Lower_Layer.Inet(Receiver_Task): Unexpected exception raised CONSTRAINT_ERROR

How can I solve it?
PS: Header of the Get procedure and private part are mandatory...

Thank you!

答:
if you eliminate the unnecessary use of access types, your problem will go away:

```<code>type Map is record
   List : Cell_Array;
   ...
end record;
</code>```

Access types are needed so rarely in well designed Ada that I'm tempted to say "never".

Body:
I am trying to do a typical Get procedure with this features:

Header:

procedure Get (M:Map; Key: in Key_Type; Value: out Value_Type; Success: out Boolean) is

private part:

type Cell is record
    Key: Key_Type;
    Value: Value_Type;
    Full:Boolean:= False;
end record

type Cell_Array is array (1..50) of Cell;
type Cell_Array_A is access Cell_Array;

type Map is record
    P_Array: Cell_Array_A;
    Length:Natural=0;
    Indice:Natural;
end record

My first condition on my Get procedure has the following aspect:

for k in 1..NumClien loop
    if M.P_Array(k).Key = Key then
...

But when I try to execute it, it always gives me the following error:
Lower_Layer.Inet(Receiver_Task): Unexpected exception raised CONSTRAINT_ERROR

How can I solve it?
PS: Header of the Get procedure and private part are mandatory...

Thank you!

Body:
if you eliminate the unnecessary use of access types, your problem will go away:

type Map is record
   List : Cell_Array;
   ...
end record;

Access types are needed so rarely in well designed Ada that I'm tempted to say "never".


问:
PagerAdapter() cannot be applied to android.app FragmentManager
I tried to create a ViewPager in Android Studio.
I get the error:

```<code>PagerAdapter() cannot be applied to android.app FragmentManager
</code>```

at the line super(fm);

Here is my code for the adapter. Do I need to change anything?

```<code>package com.example.admin.usthweather;

import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.view.View;

/**
 * Created by Admin on 11/15/2017.
 */

public class HomeFragmentAdapter extends PagerAdapter {
  private final int PAGE_COUNT = 3;
  private String titles[] = new String[] {"Hanoi","Paris", "Saigon"};

  public HomeFragmentAdapter(FragmentManager fm){
    super(fm);
  }

  @Override
  public int getCount() {
    return PAGE_COUNT;
  }

  // Override
  public Fragment getItem(int page) {
// returns an instance of Fragment corresponding to the specified page
    Fragment frag=null;
    switch (page){
      case 0:
        frag=new Hanoi();
        break;
      case 1:
        frag=new Paris();
        break;
      case 2:
        frag=new Saigon();
        break;
    }
    return frag;
  }

  @Override
  public boolean isViewFromObject(View view, Object object) {
    return false;
  }
}
</code>```

答:
There is no constructor in PagerAdapter with FragmentManager as parameter. You're code is similar for FragmentPagerAdapter or FragmentStatePagerAdapter so you can use one of them. It will be something like this:

```<code>public class HomeFragmentAdapter extends FragmentStatePagerAdapter {

  private final int PAGE_COUNT = 3;
  private String titles[] = new String[] {"Hanoi","Paris", "Saigon"};

  public HomeFragmentAdapter(FragmentManager fm){
    super(fm);
  }

  @Override
  public int getCount() {
    return PAGE_COUNT;
  }

  @Override
  public Fragment getItem(int page) {
    Fragment frag=null;
    switch (page){
      case 0:
        frag=new Hanoi();
        break;
      case 1:
        frag=new Paris();
        break;
      case 2:
        frag=new Saigon();
        break;
    }
    return frag;
  }
}
</code>```

Please remember to use the correct import file for Fragment and FragmentManager from Support library:

```<code>import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
</code>```

Body:
I tried to create a ViewPager in Android Studio.
I get the error:

PagerAdapter() cannot be applied to android.app FragmentManager

at the line super(fm);

Here is my code for the adapter. Do I need to change anything?

package com.example.admin.usthweather;

import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.view.View;

/**
 * Created by Admin on 11/15/2017.
 */

public class HomeFragmentAdapter extends PagerAdapter {
  private final int PAGE_COUNT = 3;
  private String titles[] = new String[] {"Hanoi","Paris", "Saigon"};

  public HomeFragmentAdapter(FragmentManager fm){
    super(fm);
  }

  @Override
  public int getCount() {
    return PAGE_COUNT;
  }

  // Override
  public Fragment getItem(int page) {
// returns an instance of Fragment corresponding to the specified page
    Fragment frag=null;
    switch (page){
      case 0:
        frag=new Hanoi();
        break;
      case 1:
        frag=new Paris();
        break;
      case 2:
        frag=new Saigon();
        break;
    }
    return frag;
  }

  @Override
  public boolean isViewFromObject(View view, Object object) {
    return false;
  }
}

Body:
There is no constructor in PagerAdapter with FragmentManager as parameter. You're code is similar for FragmentPagerAdapter or FragmentStatePagerAdapter so you can use one of them. It will be something like this:

public class HomeFragmentAdapter extends FragmentStatePagerAdapter {

  private final int PAGE_COUNT = 3;
  private String titles[] = new String[] {"Hanoi","Paris", "Saigon"};

  public HomeFragmentAdapter(FragmentManager fm){
    super(fm);
  }

  @Override
  public int getCount() {
    return PAGE_COUNT;
  }

  @Override
  public Fragment getItem(int page) {
    Fragment frag=null;
    switch (page){
      case 0:
        frag=new Hanoi();
        break;
      case 1:
        frag=new Paris();
        break;
      case 2:
        frag=new Saigon();
        break;
    }
    return frag;
  }
}

Please remember to use the correct import file for Fragment and FragmentManager from Support library:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;


问:
Can't change Bootstrap Datepicker format
I want to have a datepicker with this format: dd/mm/yyyy. When I set the default date in Javascript I have my date with the good format. But when I click it to choose an another date the format is reset at: mm/dd/yyyy

HTML code:

  <input type="text" class="form-control" data-bind="value: startDate, event: {change: savePerishableDate}" id="date"/>

```

<p>Javascript datepicker:</p>

<pre class="lang-html prettyprint-override"><code><script type="text/javascript">
    $(document).ready(function() {
        $("#date").datepicker({
            format: "dd/mm/yyyy",
            language: "fr",
            changeMonth: true,
            changeYear: true
        });
    });
</script>
</code>```

Javascript:

self.startDate(new Date)
tmpDate = new Date
self.startDate(tmpDate.toLocaleDateString("fr-FR"))
$('#date').datepicker 'setDate', self.startDate()
```

答:
I think you are using old version of bootstrap datepicker,Using this latest you can set dateformat as you want

$(document).ready(function() {
            $("#date").datepicker({
                format: "dd/mm/yyyy",
                language: "fr",
                changeMonth: true,
                changeYear: true
            });
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link type="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker3.min.css"/>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<div class="input-group" id="datepicker">
  <input type="text" class="form-control" data-bind="value: startDate, event: {change: savePerishableDate}" id="date"/>
</div></code>```

Body:
I want to have a datepicker with this format: dd/mm/yyyy. When I set the default date in Javascript I have my date with the good format. But when I click it to choose an another date the format is reset at: mm/dd/yyyy

HTML code:

  <input type="text" class="form-control" data-bind="value: startDate, event: {change: savePerishableDate}" id="date"/>

Javascript datepicker:

Javascript:

self.startDate(new Date)
tmpDate = new Date
self.startDate(tmpDate.toLocaleDateString("fr-FR"))
$('#date').datepicker 'setDate', self.startDate()

Body:
I think you are using old version of bootstrap datepicker,Using this latest you can set dateformat as you want

$(document).ready(function() {
            $("#date").datepicker({
                format: "dd/mm/yyyy",
                language: "fr",
                changeMonth: true,
                changeYear: true
            });
        });

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link type="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker3.min.css"/>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<div class="input-group" id="datepicker">
  <input type="text" class="form-control" data-bind="value: startDate, event: {change: savePerishableDate}" id="date"/>
</div>


问:
Kafka offset management on Kafka topic as well as local database
I want to manage offset in Kafka topic as well as the database so that if I want to reprocess in the queue after a certain point I can. How can I proceed on this? Thanks in advance.</p>

答:
Given a PartitionInfo you should be able to tell your consumer to seekToBeginning or seek to an offset in that partition.

A ConsumerRecord knows it's topic, partition and offset. You could record these facts in a database.

But the catch here is if your topics are partitioned. Your data then will be chronological for that category. So if you have two partitions and partition essentially by last name, the name changes for the first half of the alphabet will be sequential, and the second half will be sequential, but it's non obvious how to get a single chronological view of the name changes across the system.

However, if you recorded partition and offset for a particular change in the database, you could seek to that partition and offset and reprocess the stream from that point.

(This becomes irrelevant if you only have one partition, but it's something to think about when/if your topic or streaming architecture needs multiple partitions)

Stepping back from the actual question into theory, I'm not really sure why you would want to do this, as consumer groups will record your committed offset to Kafka itself, thus if your stream processing app crashes you'll be able to pick up from where you left off without worry. This message committing either happens automatically, if you set the enable.auto.commit property, or you can control this manually if you call commitSync() on the consumer. Or you're trying to use an immutable data store (Kafka) as one would a mutable store, but that's just a bit of pure speculation based on the fact that you're not really descriptive with why you want to do the thing you want to do.


问:
Testing MobX Component
I am facing an issue of how to test a component in Mobx that we are passing props to.
I am using Jest and I just want to make a simple snapshot test.

Next to default export I am also using named export of just the component so @inject and @observer don't influence it. I should just  pass my own 'expenses' and 'filters' as a prop but it is not working.

So this is my component. I am passing RootStore as a prop to that component.

ExpenseList Component

```<code> @inject('RootStore')
    @observer
    export class ExpenseList extends Component {
      render() {
        const {expenses} = this.props.RootStore.ExpensesStore
        const {filters} = this.props.RootStore.FiltersStore
        const expensesFilter = selectExpense(expenses, filters)
        return (
          <div>
          {
            expenses.length === 0 ? (
              <p>No expenses</p>
            ) : (
              expensesFilter.map((expense) => {
                return <ExpenseListItem key={expense.id} {...expense} />
              })
            )
          }
          </div>
        )
      }
    }
</code>```

ExpenseList.test.js

```<code>import React from 'react'
import { shallow } from 'enzyme'
import { ExpenseList } from '../../components/ExpenseList'
import expenses from '../fixtures/expenses'

test('should render ExpenseList with expenses', () => {
  // const wrapper = shallow(<ExpenseList RootStore={{'ExpensesStore':{'expenses':expenses}}}/>)
  const wrapper = shallow(<ExpenseList
  RootStore={
    {
      'ExpensesStore':{
        'expenses':expenses
      },
      'FiltersStore': {
        'filters': {
          text: 'e',
          sortBy: 'date',
          startDate: '11.2017.',
          endDate: '12.2017.'
        }

      }
    }
  }
  />)
  expect(wrapper).toMatchSnapshot();
})
</code>```

This is my RootStore

```<code>import ExpensesStore from './ExpensesStore'
import FiltersStore from './FiltersStore'

class RootStore {
    ExpensesStore = new ExpensesStore(this)
    FiltersStore = new FiltersStore(this)
}

const rootStore = new RootStore()

export default rootStore
</code>```

ExpensesStore

```<code>class ExpensesStore {

  constructor(rootStore) {
    this.rootStore = rootStore
  }

  @observable expenses = [];

  findExpense(paramsId) {
    return computed(() => {
      return this.expenses.find((expense) => expense.id === paramsId)
    }).get()
  }

}

export default ExpensesStore
</code>```

FiltersStore

```<code>class FiltersStore {

  constructor(rootStore) {
    this.rootStore = rootStore
  }

  @observable filters = {
    text: '',
    sortBy: 'date',
    startDate: moment().startOf('month'),
    endDate: moment().endOf('month')
  }

}

export default FiltersStore
</code>```

答:
Ok. The problem were decorators at the top of the component.

Using shallow rendering won't provide any useful results when testing injected components; only the injector will be rendered. To test with shallow rendering, instantiate the wrappedComponent

```<code>test('should render ExpenseList with expenses', () => {
  const wrapper = shallow(<ExpenseList.wrappedComponent
  RootStore = {
    {
      ExpensesStore: {
        expenses
      },
      FiltersStore: {
        filters: {
          text: 'e',
          sortBy: 'date',
          startDate: '',
          endDate: ''
        }
      }
    }
  }
  />)
  expect(wrapper).toMatchSnapshot();
})
</code>```

Title: Testing MobX Component

Body:
I am facing an issue of how to test a component in Mobx that we are passing props to.
I am using Jest and I just want to make a simple snapshot test.

Next to default export I am also using named export of just the component so @inject and @observer don't influence it. I should just  pass my own 'expenses' and 'filters' as a prop but it is not working.

So this is my component. I am passing RootStore as a prop to that component.

ExpenseList Component

 @inject('RootStore')
    @observer
    export class ExpenseList extends Component {
      render() {
        const {expenses} = this.props.RootStore.ExpensesStore
        const {filters} = this.props.RootStore.FiltersStore
        const expensesFilter = selectExpense(expenses, filters)
        return (

          {
            expenses.length === 0 ? (

No expenses

            ) : (
              expensesFilter.map((expense) => {
                return <ExpenseListItem key={expense.id} {...expense} />
              })
            )
          }

        )
      }
    }

ExpenseList.test.js

import React from 'react'
import { shallow } from 'enzyme'
import { ExpenseList } from '../../components/ExpenseList'
import expenses from '../fixtures/expenses'

test('should render ExpenseList with expenses', () => {
  // const wrapper = shallow(<ExpenseList RootStore={{'ExpensesStore':{'expenses':expenses}}}/>)
  const wrapper = shallow(<ExpenseList
  RootStore={
    {
      'ExpensesStore':{
        'expenses':expenses
      },
      'FiltersStore': {
        'filters': {
          text: 'e',
          sortBy: 'date',
          startDate: '11.2017.',
          endDate: '12.2017.'
        }

      }
    }
  }
  />)
  expect(wrapper).toMatchSnapshot();
})

This is my RootStore

import ExpensesStore from './ExpensesStore'
import FiltersStore from './FiltersStore'

class RootStore {
    ExpensesStore = new ExpensesStore(this)
    FiltersStore = new FiltersStore(this)
}

const rootStore = new RootStore()

export default rootStore

ExpensesStore

class ExpensesStore {

  constructor(rootStore) {
    this.rootStore = rootStore
  }

  @observable expenses = [];

  findExpense(paramsId) {
    return computed(() => {
      return this.expenses.find((expense) => expense.id === paramsId)
    }).get()
  }

}

export default ExpensesStore

FiltersStore

class FiltersStore {

  constructor(rootStore) {
    this.rootStore = rootStore
  }

  @observable filters = {
    text: '',
    sortBy: 'date',
    startDate: moment().startOf('month'),
    endDate: moment().endOf('month')
  }

}

export default FiltersStore

Body:
Ok. The problem were decorators at the top of the component.

Using shallow rendering won't provide any useful results when testing injected components; only the injector will be rendered. To test with shallow rendering, instantiate the wrappedComponent

test('should render ExpenseList with expenses', () => {
  const wrapper = shallow(<ExpenseList.wrappedComponent
  RootStore = {
    {
      ExpensesStore: {
        expenses
      },
      FiltersStore: {
        filters: {
          text: 'e',
          sortBy: 'date',
          startDate: '',
          endDate: ''
        }
      }
    }
  }
  />)
  expect(wrapper).toMatchSnapshot();
})


问:
Why do I have to wrap an Async<T> into another async workflow and let! it?
I'm trying to understand async workflows in F# but I found one part that I really don't understand.

The following code works fine:

```<code>let asynWorkflow = async{
    let! result = Stream.TryOpenAsync(partition) |> Async.AwaitTask
    return result
    }

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)
</code>```

I define a async workflow where TryOpenAsync returns a Task<StreamOpenResult> type. I convert it to Async<StreamOpenResult> with Async.AwaitTask. (Side quest: "Await"Task? It doesn't await it just convert it, does it? I think it has nothing to do with Task.Wait or the await keyword). I "await" it with let! and return it.
To start the workflow I use RunSynchronously which should start the workflow and return the result (bind it). On the result I check if the Stream is Found or not.

But now to my first question. Why do I have to wrap the TryOpenAsync call in another async computation and let! ("await") it?
E.g. the following code does not work:

```<code>let asynWorkflow =  Stream.TryOpenAsync(partition) |> Async.AwaitTask

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)
</code>```

I thought the AwaitTask makes it an Async<T> and RunSynchronously should start it. Then use the result. What do I miss?

My second question is why is there any "Async.Let!" function available? Maybe because it does not work or better why doesn't it work with the following code?

```<code>let ``let!`` task = async{
    let! result = task |> Async.AwaitTask
   return result
   }

let stream = Async.RunSynchronously ( ``let!`` (Stream.TryOpenAsync(partition))  )
         |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)
</code>```

I just insert the TryOpenAsync as a parameter but it does not work. By saying does not work I mean the whole FSI will hang. So it has something to do with my async/"await".

--- Update:

Result of working code in FSI:

```<code>>

Real: 00:00:00.051, CPU: 00:00:00.031, GC gen0: 0, gen1: 0, gen2: 0
val asynWorkflow : Async<StreamOpenResult>
val stream : Stream
</code>```

Result of not working code in FSI:

```<code>>
</code>```

And you cannot execute anything in the FSI anymore

--- Update 2

I'm using Streamstone. Here the C# example: https://github.com/yevhen/Streamstone/blob/master/Source/Example/Scenarios/S04_Write_to_stream.cs

and here the Stream.TryOpenAsync: https://github.com/yevhen/Streamstone/blob/master/Source/Streamstone/Stream.Api.cs#L192

答:
Not that I want to answer your question with another question, but: why are you doing code like this anyway? That might help to understand it. Why not just:

```<code>let asyncWorkflow = async {
    let! result = Stream.TryOpenAsync(partition) |> Async.AwaitTask
    if result.Found then return openResult.Stream else return Stream(partition) }
</code>```

There's little point in creating an async workflow only to immediately call RunSynchronously on it - it's similar to calling .Result on a Task - it just blocks the current thread until the workflow returns.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to understand async workflows in F# but I found one part that I really don't understand.

The following code works fine:

let asynWorkflow = async{
    let! result = Stream.TryOpenAsync(partition) |> Async.AwaitTask
    return result
    }

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)

I define a async workflow where TryOpenAsync returns a Task<StreamOpenResult> type. I convert it to Async<StreamOpenResult> with Async.AwaitTask. (Side quest: "Await"Task? It doesn't await it just convert it, does it? I think it has nothing to do with Task.Wait or the await keyword). I "await" it with let! and return it.
To start the workflow I use RunSynchronously which should start the workflow and return the result (bind it). On the result I check if the Stream is Found or not.

But now to my first question. Why do I have to wrap the TryOpenAsync call in another async computation and let! ("await") it?
E.g. the following code does not work:

let asynWorkflow =  Stream.TryOpenAsync(partition) |> Async.AwaitTask

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)

I thought the AwaitTask makes it an Async<T> and RunSynchronously should start it. Then use the result. What do I miss?

My second question is why is there any "Async.Let!" function available? Maybe because it does not work or better why doesn't it work with the following code?

let ``let!`` task = async{
    let! result = task |> Async.AwaitTask
   return result
   }

let stream = Async.RunSynchronously ( ``let!`` (Stream.TryOpenAsync(partition))  )
         |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)

I just insert the TryOpenAsync as a parameter but it does not work. By saying does not work I mean the whole FSI will hang. So it has something to do with my async/"await".

--- Update:

Result of working code in FSI:

>

Real: 00:00:00.051, CPU: 00:00:00.031, GC gen0: 0, gen1: 0, gen2: 0
val asynWorkflow : Async<StreamOpenResult>
val stream : Stream

Result of not working code in FSI:

>

And you cannot execute anything in the FSI anymore

--- Update 2

I'm using Streamstone. Here the C# example: https://github.com/yevhen/Streamstone/blob/master/Source/Example/Scenarios/S04_Write_to_stream.cs

and here the Stream.TryOpenAsync: https://github.com/yevhen/Streamstone/blob/master/Source/Streamstone/Stream.Api.cs#L192

Body:
Not that I want to answer your question with another question, but: why are you doing code like this anyway? That might help to understand it. Why not just:

let asyncWorkflow = async {
    let! result = Stream.TryOpenAsync(partition) |> Async.AwaitTask
    if result.Found then return openResult.Stream else return Stream(partition) }

There's little point in creating an async workflow only to immediately call RunSynchronously on it - it's similar to calling .Result on a Task - it just blocks the current thread until the workflow returns.


问:
Code-Golf: Friendly Number Abbreviator
Based on this question: Is there a way to round numbers into a friendly format?

THE CHALLENGE - UPDATED! (removed hundreds abbreviation from spec)

The shortest code by character count that will abbreviate an integer (no decimals).

Code should include the full program.

Relevant range is from 0 - 9,223,372,036,854,775,807 (the upper limit for signed 64 bit integer).

The number of decimal places for abbreviation will be positive. You will not need to calculate the following: 920535 abbreviated -1 place (which would be something like 0.920535M).

Numbers in the tens and hundreds place (0-999) should never be abbreviated (the abbreviation for the number 57 to 1+ decimal places is 5.7dk - it is unneccessary and not friendly).

Remember to round half away from zero (23.5 gets rounded to 24). Banker's rounding is verboten.

Here are the relevant number abbreviations:

h = hundred     (102)

k = thousand    (103)

M = million     (106)

G = billion     (109)

T = trillion    (1012)

P = quadrillion (1015)

E = quintillion (1018)

SAMPLE INPUTS/OUTPUTS (inputs can be passed as separate arguments):

First argument will be the integer to abbreviate. The second is the number of decimal places.

```<code>12 1                  => 12 // tens and hundreds places are never rounded
1500 2                => 1.5k
1500 0                => 2k // look, ma! I round UP at .5
0 2                   => 0
1234 0                => 1k
34567 2               => 34.57k
918395 1              => 918.4k
2134124 2             => 2.13M
47475782130 2         => 47.48G
9223372036854775807 3 => 9.223E
// ect...
</code>```

Original answer from related question (JavaScript, does not follow spec):

```<code>function abbrNum(number, decPlaces) {
    // 2 decimal places => 100, 3 => 1000, etc
    decPlaces = Math.pow(10,decPlaces);

    // Enumerate number abbreviations
    var abbrev = [ "k", "m", "b", "t" ];

    // Go through the array backwards, so we do the largest first
    for (var i=abbrev.length-1; i>=0; i--) {

        // Convert array index to "1000", "1000000", etc
        var size = Math.pow(10,(i+1)*3);

        // If the number is bigger or equal do the abbreviation
        if(size <= number) {
             // Here, we multiply by decPlaces, round, and then divide by decPlaces.
             // This gives us nice rounding to a particular decimal place.
             number = Math.round(number*decPlaces/size)/decPlaces;

             // Add the letter for the abbreviation
             number += abbrev[i];

             // We are done... stop
             break;
        }
    }

    return number;
}
</code>```

Title: Code-Golf: Friendly Number Abbreviator

Body:
Based on this question: Is there a way to round numbers into a friendly format?

THE CHALLENGE - UPDATED! (removed hundreds abbreviation from spec)

The shortest code by character count that will abbreviate an integer (no decimals).

Code should include the full program.

Relevant range is from 0 - 9,223,372,036,854,775,807 (the upper limit for signed 64 bit integer).

The number of decimal places for abbreviation will be positive. You will not need to calculate the following: 920535 abbreviated -1 place (which would be something like 0.920535M).

Numbers in the tens and hundreds place (0-999) should never be abbreviated (the abbreviation for the number 57 to 1+ decimal places is 5.7dk - it is unneccessary and not friendly).

Remember to round half away from zero (23.5 gets rounded to 24). Banker's rounding is verboten.

Here are the relevant number abbreviations:

h = hundred     (102)

k = thousand    (103)

M = million     (106)

G = billion     (109)

T = trillion    (1012)

P = quadrillion (1015)

E = quintillion (1018)

SAMPLE INPUTS/OUTPUTS (inputs can be passed as separate arguments):

First argument will be the integer to abbreviate. The second is the number of decimal places.

12 1                  => 12 // tens and hundreds places are never rounded
1500 2                => 1.5k
1500 0                => 2k // look, ma! I round UP at .5
0 2                   => 0
1234 0                => 1k
34567 2               => 34.57k
918395 1              => 918.4k
2134124 2             => 2.13M
47475782130 2         => 47.48G
9223372036854775807 3 => 9.223E
// ect...

Original answer from related question (JavaScript, does not follow spec):

function abbrNum(number, decPlaces) {
    // 2 decimal places => 100, 3 => 1000, etc
    decPlaces = Math.pow(10,decPlaces);

    // Enumerate number abbreviations
    var abbrev = [ "k", "m", "b", "t" ];

    // Go through the array backwards, so we do the largest first
    for (var i=abbrev.length-1; i>=0; i--) {

        // Convert array index to "1000", "1000000", etc
        var size = Math.pow(10,(i+1)*3);

        // If the number is bigger or equal do the abbreviation
        if(size <= number) {
             // Here, we multiply by decPlaces, round, and then divide by decPlaces.
             // This gives us nice rounding to a particular decimal place.
             number = Math.round(number*decPlaces/size)/decPlaces;

             // Add the letter for the abbreviation
             number += abbrev[i];

             // We are done... stop
             break;
        }
    }

    return number;
}

Body:
PHP 57 chars

for($a=num+1;$a>=1;$a=$a/26)$c=chr(--$a%26+65).$c;echo$c;


问:
Reflection and runtime class to get method
Actually in all my class, i alway have attribute name

Class clazz, Object obj

When we know the object type, we can do something like (if id is a attribute....)

```<code>Integer id = ((BaseObj) field.get(obj)).getId();
</code>```

Actually

field.get(obj))

return me a object, i search to get value of name attribute of this object.

I search to do something like

```<code>String name = ((clazz.getClass()) field.get(obj)).getName();
</code>```

答:
You cannot cast to a class that's only known at runtime. Either make all these classes implement an interface with a getName() method or you'll have to resort to reflection:

```<code>String name = (String) clazz.getMethod("getName").invoke(obj);
</code>```

Body:
Actually in all my class, i alway have attribute name

Class clazz, Object obj

When we know the object type, we can do something like (if id is a attribute....)

Integer id = ((BaseObj) field.get(obj)).getId();

Actually

field.get(obj))

return me a object, i search to get value of name attribute of this object.

I search to do something like

String name = ((clazz.getClass()) field.get(obj)).getName();

Body:
You cannot cast to a class that's only known at runtime. Either make all these classes implement an interface with a getName() method or you'll have to resort to reflection:

String name = (String) clazz.getMethod("getName").invoke(obj);


问:
Rails Association about a "helper" table
I'm rewriting an old PHP application and have to migrate the database.
It has a join
table harddisks_imagecapturing:

```<code>id  manuscripts_id   harddisk_id
-------------------------------
1   206              18
2   206              17
3   206              16
</code>```

Table imagecapturing:

```<code>id harddisk_id library signature
-------------------------------
1   16         "foo"    "MS352"
2   17         "bar"    "AB67"
3   18         "baz"    "WQ62"
</code>```

Table harddisks:

```<code>id   harddisk_name capacity
-------------------------------
16   "Seagate"    2000
17   "Seagate"    2000
18   "Seagate"    4000
</code>```

The problem is, that I don't have an manuscript_id in the table imagecapturing instead a signature that is unique and could be used as a "helper table" to reference from manuscript table.

Table manuscripts:

```<code>id   signature
---------------
206   "MS352"
</code>```

How can I make the Rails associations right to retrieve the data into a table with the columns:

signature, library, harddisk_name, capacity

? I suppose one had to use the manuscript_id from harddisks_imagecapturing table to get the signature from the manuscript table.

```<code>class Imagecapturing < ApplicationRecord
  self.table_name = 'imagecapturing'

  belongs_to :harddisk

end

class HarddisksImagecapturing < ApplicationRecord
  self.table_name = 'harddisks_imagecapturing'

  belongs_to :harddisk
  belongs_to :imagecapturing
end

class Harddisk < ApplicationRecord
  has_many :manuscripts_harddisks
  has_many :manuscripts, through: :manuscripts_harddisks

  default_scope { order(kaufdatum: :desc) }

  # Harddisk.order('id ASC').reorder('kaufdatum DESC')
end

class Manuscript < ApplicationRecord

end
</code>```

答:
You can specify which column(s) to use as the primary_key and foreign_key for associations. http://guides.rubyonrails.org/association_basics.html#options-for-belongs-to

```<code>class Manuscript < ApplicationRecord
  belongs_to :imagecapturing, foreign_key: "signature", primary_key: "signature"
end
</code>```

Alternatively, like you mentioned, you could navigate through your harddisks_imagecapturing table as well.

Body:
I'm rewriting an old PHP application and have to migrate the database.
It has a join
table harddisks_imagecapturing:

id  manuscripts_id   harddisk_id
-------------------------------
1   206              18
2   206              17
3   206              16

Table imagecapturing:

id harddisk_id library signature
-------------------------------
1   16         "foo"    "MS352"
2   17         "bar"    "AB67"
3   18         "baz"    "WQ62"

Table harddisks:

id   harddisk_name capacity
-------------------------------
16   "Seagate"    2000
17   "Seagate"    2000
18   "Seagate"    4000

The problem is, that I don't have an manuscript_id in the table imagecapturing instead a signature that is unique and could be used as a "helper table" to reference from manuscript table.

Table manuscripts:

id   signature
---------------
206   "MS352"

How can I make the Rails associations right to retrieve the data into a table with the columns:

signature, library, harddisk_name, capacity

? I suppose one had to use the manuscript_id from harddisks_imagecapturing table to get the signature from the manuscript table.

class Imagecapturing < ApplicationRecord
  self.table_name = 'imagecapturing'

  belongs_to :harddisk

end

class HarddisksImagecapturing < ApplicationRecord
  self.table_name = 'harddisks_imagecapturing'

  belongs_to :harddisk
  belongs_to :imagecapturing
end

class Harddisk < ApplicationRecord
  has_many :manuscripts_harddisks
  has_many :manuscripts, through: :manuscripts_harddisks

  default_scope { order(kaufdatum: :desc) }

  # Harddisk.order('id ASC').reorder('kaufdatum DESC')
end

class Manuscript < ApplicationRecord

end

Body:
You can specify which column(s) to use as the primary_key and foreign_key for associations. http://guides.rubyonrails.org/association_basics.html#options-for-belongs-to

class Manuscript < ApplicationRecord
  belongs_to :imagecapturing, foreign_key: "signature", primary_key: "signature"
end

Alternatively, like you mentioned, you could navigate through your harddisks_imagecapturing table as well.


问:
Convert Soap XML response to Object
i'm new to working with SOAP API's

I have a soap response from an API

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<LoginResponse xmlns="http://test.org/ADMail_Service">
<LoginResult>
<ErrorMessage>Successful login</ErrorMessage>
<Status>true</Status>
</LoginResult>
</LoginResponse>
</soapenv:Body>
</soapenv:Envelope>
</code>```

I'm trying to transform this into an object.

From reading articles online I'm trying to use JAXB to do this, but my object is empty.

Here's the code for reading the response. I wrote the response to an xml file for test purposes:

```<code>try {
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
    xsr.nextTag(); // Advance to Envelope tag

    xsr.nextTag(); // Advance to Body tag
    xsr.nextTag();
    xsr.nextTag();

    JAXBContext jc = JAXBContext.newInstance(LoginResult.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    JAXBElement<LoginResult> je = unmarshaller.unmarshal(xsr, LoginResult.class);

    System.out.println(je.getName());
    System.out.println(je.getValue());
} catch (XMLStreamException e) {
    e.printStackTrace();
} catch (JAXBException e) {
    e.printStackTrace();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
</code>```

The LoginResult class:

```<code>public class LoginResult {
    private String errorMessage;
    private String status;

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}
</code>```

Thanks in advance!

答:
IMO, you should consider using tools to handle SOAP messages instead of doing it on your own.

Examples :

Java EE 5 Tutorial : Creating a Simple Web Service and Client with JAX-WS

Spring Boot : Consuming a SOAP message

EDIT

There's a few things to say about your comment so I'll put my answer here.

First,

I have nothing to do with the API, all I do is make a POST request...

You have nothing to do with the API but you make a POST request to the API.
I think this is a figure of speech, right ?...

and there's no wsdl....

You can almost always get the WSDL of a SOAP webservice with this little trick. Just add ?wsdl at the end of the SOAP webservice URL.

Example :

Here's the URL of a SOAP webservice on the web (a real one) : http://www.webservicex.com/stockquote.asmx

You can get its WSDL like this : http://www.webservicex.com/stockquote.asmx?wsdl

So the only option is to parse the response

IMO, there's almost always more than one solution to a problem in software development.

Title: Convert Soap XML response to Object

Body:
i'm new to working with SOAP API's

I have a soap response from an API

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<LoginResponse xmlns="http://test.org/ADMail_Service">
<LoginResult>
<ErrorMessage>Successful login</ErrorMessage>
<Status>true</Status>
</LoginResult>
</LoginResponse>
</soapenv:Body>
</soapenv:Envelope>

I'm trying to transform this into an object.

From reading articles online I'm trying to use JAXB to do this, but my object is empty.

Here's the code for reading the response. I wrote the response to an xml file for test purposes:

try {
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
    xsr.nextTag(); // Advance to Envelope tag

    xsr.nextTag(); // Advance to Body tag
    xsr.nextTag();
    xsr.nextTag();

    JAXBContext jc = JAXBContext.newInstance(LoginResult.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    JAXBElement<LoginResult> je = unmarshaller.unmarshal(xsr, LoginResult.class);

    System.out.println(je.getName());
    System.out.println(je.getValue());
} catch (XMLStreamException e) {
    e.printStackTrace();
} catch (JAXBException e) {
    e.printStackTrace();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

The LoginResult class:

public class LoginResult {
    private String errorMessage;
    private String status;

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

Thanks in advance!


问:
How to browse a .zip file in IntelliJ (or .jar, etc.)
I'd like to be able to "open up" (without unzipping) .zip files or .jar files in IntelliJ much like you can do in Eclipse by clicking the twisty. How do I do this with IntelliJ?</p>

答:
There is now a Intellij Plugin that solves that:

https://plugins.jetbrains.com/plugin/9491-archive-browser

Update: it works now also for nested archives. (tested 2019.1)


问:
Java Android - HttpURLConnection - Response Code 400 on Android 4.x.x
I am using the following code:

```<code>        System.setProperty("http.keepAlive","false");
        String content;
        mainURL += "&fingerprint=" + Build.FINGERPRINT + "&devicename=" + "" + "&devicemodel=" + Build.MANUFACTURER + " - " + Build.MODEL;
        try {
            URL url = new URL(mainURL);
            HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
            urlconn.setConnectTimeout(HTTP_REQUEST_TIMEOUT);
            urlconn.setReadTimeout(HTTP_REQUEST_TIMEOUT);
            urlconn.setRequestMethod("GET");
            urlconn.connect();

            int responseCode = urlconn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK){
                content = readStream(urlconn.getInputStream());
            }else{
                content = "error";
            }

            urlconn.disconnect();
        } catch (Exception e) {
            return "error";
        }

        return content;
</code>```

This works fine on Android 6.x.x and Android 7.x.x but on Android 4.4.2 it's returning http response code 400. Is this problem maybe being caused because of this:

mainURL += "&fingerprint=" + Build.FINGERPRINT + "&devicename=" + "" + "&devicemodel=" + Build.MANUFACTURER + " - " + Build.MODEL;

Thanks in advance.

答:
I fixed the problem.

Build is not working on Android 4.x.x that's why HttpURLConnection didn't work either.

Body:
I am using the following code:

        System.setProperty("http.keepAlive","false");
        String content;
        mainURL += "&fingerprint=" + Build.FINGERPRINT + "&devicename=" + "" + "&devicemodel=" + Build.MANUFACTURER + " - " + Build.MODEL;
        try {
            URL url = new URL(mainURL);
            HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
            urlconn.setConnectTimeout(HTTP_REQUEST_TIMEOUT);
            urlconn.setReadTimeout(HTTP_REQUEST_TIMEOUT);
            urlconn.setRequestMethod("GET");
            urlconn.connect();

            int responseCode = urlconn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK){
                content = readStream(urlconn.getInputStream());
            }else{
                content = "error";
            }

            urlconn.disconnect();
        } catch (Exception e) {
            return "error";
        }

        return content;

This works fine on Android 6.x.x and Android 7.x.x but on Android 4.4.2 it's returning http response code 400. Is this problem maybe being caused because of this:

mainURL += "&fingerprint=" + Build.FINGERPRINT + "&devicename=" + "" + "&devicemodel=" + Build.MANUFACTURER + " - " + Build.MODEL;

Thanks in advance.


问:
How do I integrate a Polymer + Node.JS JavaScript app with React + TypeScript
I have recently been tasked with integrating React + TypeScript with an existing starter app that contains many great Polymer Components (Predix UI Starter). I understand that this may seem non-sensical to some (after all, you could simply provide app state and logic using Polymer as a framework). However, the React library and the object oriented nature of TypeScript have a lot to offer, so what are some tips for getting started here?

答:
I will be integrating the Predix UI Starter with the create-react-app starter. Specifically, I will enable a React Component to render() a px-dropdown polymer component. This concept and method can apply to any polymer starter app. This DOES NOT completely integrate these two starters, it is ONLY a POC for rendering a polymer component in a React render() method, using TypeScript.

Clone both of these repos. Work out of the Predix UI Starter - this will contain all of the components once you run npm install and bower install.

Ensure that the package.json in the Predix UI Starter contains all of the dependencies and devDependencies that the react app contains. In the package.json file, in the scripts object, change "start" : ..., to "start" : "react-scripts-ts start". This will serve the app to localhost using TypeScript (this is where the tsconfig.json and the tslint.json files come into play).

Copy the tsconfig.json, tslint.json, and the tsconfig.test.json files into the root directory of the Predix UI Starter.

As per the naming convention for React apps, rename the server folder to src. In the .bowerrc file, append public/ before bower_components, this will enable the public/index.html file to import polymer components generated by bower. Unless configured to do so, public/index.html will be unable to load polymer components in parent folders to the public folder. (The user may need to configure the Predix Starter to initially serve the public/index.html file).

From the react starter to the Predix starter, copy the App.tsx and the index.tsx files to the src folder, and copy the index.html file to the public folder (this file will be what the app initially serves).

Add the px-dropdown component to the JSX namespace so that you can render it within a react component by adding a global.d.ts file to the root directory with the following content:

declare namespace JSX {
    interface IntrinsicElements {
       'px-dropdown': any
    }
}

You are now ready to render() the px-dropdown component. In the public/index.html file, import the component using the following two lines (within the  tag):

```<code><link rel="import" href="bower_components/polymer/polymer.html" />
<link rel="import" href="bower_components/px-dropdown/px-dropdown.html" />
</code>```

Let's pass some items to the props of the App Component. In the index.tsx file, edit the line that renders the component to look like <App items={'[{"key":"1", "val": "One"},{"key" : "2", "val": "Two"}]'}/>

The following code in App.tsx will render the px-dropdown component successfully:

```<code>    class App extends React.Component<any, any> {
        constructor (props: any) {
          super(props);
        }
        render() {
          ...
          return (
            <div className="App">
              ...
              <px-dropdown
                items={this.props.items}
                sort-mode="key"
                button-style="default"
                display-value="Select"
                disable-clear>
              </px-dropdown>
            </div>
      );
    }
 }
</code>```

You are now ready to begin rendering Polymer components using React + TypeScript.

Body:
I will be integrating the Predix UI Starter with the create-react-app starter. Specifically, I will enable a React Component to render() a px-dropdown polymer component. This concept and method can apply to any polymer starter app. This DOES NOT completely integrate these two starters, it is ONLY a POC for rendering a polymer component in a React render() method, using TypeScript.

Clone both of these repos. Work out of the Predix UI Starter - this will contain all of the components once you run npm install and bower install.

Ensure that the package.json in the Predix UI Starter contains all of the dependencies and devDependencies that the react app contains. In the package.json file, in the scripts object, change "start" : ..., to "start" : "react-scripts-ts start". This will serve the app to localhost using TypeScript (this is where the tsconfig.json and the tslint.json files come into play).

Copy the tsconfig.json, tslint.json, and the tsconfig.test.json files into the root directory of the Predix UI Starter.

As per the naming convention for React apps, rename the server folder to src. In the .bowerrc file, append public/ before bower_components, this will enable the public/index.html file to import polymer components generated by bower. Unless configured to do so, public/index.html will be unable to load polymer components in parent folders to the public folder. (The user may need to configure the Predix Starter to initially serve the public/index.html file).

From the react starter to the Predix starter, copy the App.tsx and the index.tsx files to the src folder, and copy the index.html file to the public folder (this file will be what the app initially serves).

Add the px-dropdown component to the JSX namespace so that you can render it within a react component by adding a global.d.ts file to the root directory with the following content:

declare namespace JSX {
    interface IntrinsicElements {
       'px-dropdown': any
    }
}

You are now ready to render() the px-dropdown component. In the public/index.html file, import the component using the following two lines (within the <head> tag):

<link rel="import" href="bower_components/polymer/polymer.html" />
<link rel="import" href="bower_components/px-dropdown/px-dropdown.html" />

Let's pass some items to the props of the App Component. In the index.tsx file, edit the line that renders the component to look like <App items={'[{"key":"1", "val": "One"},{"key" : "2", "val": "Two"}]'}/>

The following code in App.tsx will render the px-dropdown component successfully:

    class App extends React.Component<any, any> {
        constructor (props: any) {
          super(props);
        }
        render() {
          ...
          return (
            <div className="App">
              ...
              <px-dropdown
                items={this.props.items}
                sort-mode="key"
                button-style="default"
                display-value="Select"
                disable-clear>
              </px-dropdown>
            </div>
      );
    }
 }

You are now ready to begin rendering Polymer components using React + TypeScript.


问:
Item Control Modified Not Displayed Properly in WPF
I have item control which is bind with List. When I tried to add an item in that list it is not reflected in the item control (UI). But when replaced the Observable Collection instead of list It is perfectly worked what is the reason on that Could you please help me?

Is it any way sort the observable collection directly?

答:
The difference is that the ObservableCollection<T> class implements the INotifyCollectionChanged interface and raises the CollectionChanged event whenever an item is added and removed. This is required for the UI to be updated automatically. A List<T> does not implement this interface.

Is it any way sort the observable collection directly?

The easiest way to sort the source collection itself is to do pass a sorted IEnumerable to it when you create it:

```<code>this.Collection = new ObservableCollection<Type>(list.OrderBy(x => x.Property));
</code>```

It has no built-in Sort method that sorts the items internally.

Body:
The difference is that the ObservableCollection<T> class implements the INotifyCollectionChanged interface and raises the CollectionChanged event whenever an item is added and removed. This is required for the UI to be updated automatically. A List<T> does not implement this interface.

Is it any way sort the observable collection directly?

The easiest way to sort the source collection itself is to do pass a sorted IEnumerable to it when you create it:

this.Collection = new ObservableCollection<Type>(list.OrderBy(x => x.Property));

It has no built-in Sort method that sorts the items internally.


问:
FrameLayout not set under AppBarLayout
I have this layout from standart android examples. I need caontent layout for fragments.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="megar.ru.nfpclient.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/holo_orange_light"></FrameLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
</code>```

I need FrameLayout top under AppBarLayout botton. How can I do it?

答:
Add

```<code>app:layout_behavior="@string/appbar_scrolling_view_behavior"
</code>```

to the FrameLayout like this

```<code><FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="@android:color/holo_orange_light"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    />
</code>```

Title: FrameLayout not set under AppBarLayout

Body:
I have this layout from standart android examples. I need caontent layout for fragments.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="megar.ru.nfpclient.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/holo_orange_light"></FrameLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

I need FrameLayout top under AppBarLayout botton. How can I do it?

Body:
Add

app:layout_behavior="@string/appbar_scrolling_view_behavior"

to the FrameLayout like this

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="@android:color/holo_orange_light"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    />


问:
Wrong accelerator underline on controls on high DPI
I am having a problem, that accelerator key underlines on all controls do not get correctly rendered (too far down from the text) in a Firemonkey Application on Windows systems with higher DPI settings.I have attached a screenshot to demonstrate the problem.
Does anyone know how to fix this?
I am using Delphi 10.2 with Update 1.

答:
Found a fix myself.

In FMX.Objects.pas replace (line 4472)

```<code>LBaseline := TFontGlyphManager.Current.GetBaseline(ALayout.Font, ACanvas.Scale);
</code>```

with

```<code> LBaseline := TFontGlyphManager.Current.GetBaseline(ALayout.Font, 1);
</code>```

and (lines 4483, 4484)

```<code>FUnderlineBeginPoint.Y := Ceil(FUnderlineBeginPoint.Y) + 1.5;
FUnderlineEndPoint.Y := Ceil(FUnderlineEndPoint.Y) + 1.5;
</code>```

with

```<code>FUnderlineBeginPoint.Y := Ceil(FUnderlineBeginPoint.Y) + 1.5 * ACanvas.Scale;
FUnderlineEndPoint.Y := Ceil(FUnderlineEndPoint.Y) + 1.5 * ACanvas.Scale;
</code>```

Body:
Found a fix myself.

In FMX.Objects.pas replace (line 4472)

LBaseline := TFontGlyphManager.Current.GetBaseline(ALayout.Font, ACanvas.Scale);

with

 LBaseline := TFontGlyphManager.Current.GetBaseline(ALayout.Font, 1);

and (lines 4483, 4484)

FUnderlineBeginPoint.Y := Ceil(FUnderlineBeginPoint.Y) + 1.5;
FUnderlineEndPoint.Y := Ceil(FUnderlineEndPoint.Y) + 1.5;

with

FUnderlineBeginPoint.Y := Ceil(FUnderlineBeginPoint.Y) + 1.5 * ACanvas.Scale;
FUnderlineEndPoint.Y := Ceil(FUnderlineEndPoint.Y) + 1.5 * ACanvas.Scale;


问:
parsing xml - off by a node
I am trying to parse the value from a Yahoo finance page. I used Chrome to inspect the element of interest (the current price of a stock) and used the xpath in this simple script:

```<code>from lxml import html
import requests

page = requests.get('https://finance.yahoo.com/quote/VNQ?p=VNQ')
tree = html.fromstring(page.content)

print tree.xpath('//*[@id="quote-header-info"]/div[3]/div[1]/div/span[1]/text()')
</code>```

However, what I get is the text value from the next span tag. I've tried to alter the xpath that Chrome gives me to get the previous text value with no success. Can someone tell me where I went wrong?

答:
If this is the price you want you could take it from an easier place in the page. For instance the title html tag contains it. With a bit of string parsing, you'll get the right value. The value is always after the first space.</p>

```<code>from lxml import html
import requests

page = requests.get('https://finance.yahoo.com/quote/VNQ?p=VNQ')
tree = html.fromstring(page.content)

title = tree.xpath('//title/text()')[0]
value = title.split()[1]

print(value)
</code>```

Title: parsing xml - off by a node

Body:
I am trying to parse the value from a Yahoo finance page. I used Chrome to inspect the element of interest (the current price of a stock) and used the xpath in this simple script:

from lxml import html
import requests

page = requests.get('https://finance.yahoo.com/quote/VNQ?p=VNQ')
tree = html.fromstring(page.content)

print tree.xpath('//*[@id="quote-header-info"]/div[3]/div[1]/div/span[1]/text()')

However, what I get is the text value from the next span tag. I've tried to alter the xpath that Chrome gives me to get the previous text value with no success. Can someone tell me where I went wrong?

Body:
If this is the price you want you could take it from an easier place in the page. For instance the title html tag contains it. With a bit of string parsing, you'll get the right value. The value is always after the first space.

from lxml import html
import requests

page = requests.get('https://finance.yahoo.com/quote/VNQ?p=VNQ')
tree = html.fromstring(page.content)

title = tree.xpath('//title/text()')[0]
value = title.split()[1]

print(value)


问:
ASP.NET web application project: how to copy a referenced DLL's dependencies to the 'Temporary ASP.NET Files' folder?
I have a web application project WAP that references class library CL. CL needs some xml configuration files in order to work properly.

In WAP's csproj, I add a PostBuildEvent to copy the necessary XML files to the TargetDir. When I build, the folder structure is good; the bin folder contains CL and the xml files.

When I run the webservice, CL throws an error because it can't find the xml files:

```<code>System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\accountreplication\284ca636\19f84c15\assembly\dl3\bf68503c\34888845_bd69cb01\XmlTemplates\Clusters.xml'.
</code>```

From what I've read, ASP.NET will compile on the fly my files and put them in that 'Temporary ASP.NET' folder. So it seems like my problem is that the xml files from the /bin/ folder are not copied in that temp folder.

Any idea on what I should do to get around this? Either to copy the xml files in the temp folder, or to actually serve the files from the /bin/ directory directly (not sure if this is possible). Ideally, I don't want to add an environment variable to the /bin/ directory.

Thanks!

答:
We had a similar problem and ended up adding an appSettings key/value to web.config that our DLL use to find the required files.  Files were copied there manually.

```<code><configuration>
  ...
  <appSettings>
    <add key="sExeFolder" value="C:\Project\Support_Files"/>
  </appSettings>
  ...
</configuration>
</code>```

Body:
I have a web application project WAP that references class library CL. CL needs some xml configuration files in order to work properly.

In WAP's csproj, I add a PostBuildEvent to copy the necessary XML files to the TargetDir. When I build, the folder structure is good; the bin folder contains CL and the xml files.

When I run the webservice, CL throws an error because it can't find the xml files:

System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\accountreplication\284ca636\19f84c15\assembly\dl3\bf68503c\34888845_bd69cb01\XmlTemplates\Clusters.xml'.

From what I've read, ASP.NET will compile on the fly my files and put them in that 'Temporary ASP.NET' folder. So it seems like my problem is that the xml files from the /bin/ folder are not copied in that temp folder.

Any idea on what I should do to get around this? Either to copy the xml files in the temp folder, or to actually serve the files from the /bin/ directory directly (not sure if this is possible). Ideally, I don't want to add an environment variable to the /bin/ directory.

Thanks!

Body:
We had a similar problem and ended up adding an appSettings key/value to web.config that our DLL use to find the required files.  Files were copied there manually.

<configuration>
  ...
  <appSettings>
    <add key="sExeFolder" value="C:\Project\Support_Files"/>
  </appSettings>
  ...
</configuration>


问:
php - finding keys in an array that match a pattern
I have an array that looks like:

```<code> Array ( [2.5] => ABDE [4.8] => Some other value )
</code>```

How would I find any key/value pair where the key matches a pattern?  I will know the value of the first digit in the key,but not the second. so for example, using a prefix of "2.", I want to somehow be able to find the key "2.5" and return both the key and the value "ABDE".

I was thinking about using a regular expression with a pattern like:

```<code>$prefix = 2;
$pattern = '/'.$prefix.'\.\d/i';
</code>```

and then looping through the array and checking each key.  (by the way, just for demo purposes, $prefix has been hardcoded to 2, but in the real system, this is a value provided by the user's input).

I'm wondering if there's a simpler way to do this?

Thanks.

答:
That are my ways  </p>

```<code>$data = ["path"=>"folder","filename"=>"folder/file.txt","required"=>false];

// FIRST WAY

$keys = array_keys($data);
if (!in_array("path", $keys) && !in_array("filename",$keys) && !in_array("required",$keys)) {
    return myReturn(false, "Dados pendentes");
}

// SECOND WAY

$keys = implode("," array_keys($data));
if (!preg_match('/(path)|(filename)|(required)/'), $keys) {
    return myReturn(false, "Dados pendentes");
}
</code>```

Body:
I have an array that looks like:

 Array ( [2.5] => ABDE [4.8] => Some other value )

How would I find any key/value pair where the key matches a pattern?  I will know the value of the first digit in the key,but not the second. so for example, using a prefix of "2.", I want to somehow be able to find the key "2.5" and return both the key and the value "ABDE".

I was thinking about using a regular expression with a pattern like:

$prefix = 2;
$pattern = '/'.$prefix.'\.\d/i';

and then looping through the array and checking each key.  (by the way, just for demo purposes, $prefix has been hardcoded to 2, but in the real system, this is a value provided by the user's input).

I'm wondering if there's a simpler way to do this?

Thanks.

Body:
That are my ways

$data = ["path"=>"folder","filename"=>"folder/file.txt","required"=>false];

// FIRST WAY

$keys = array_keys($data);
if (!in_array("path", $keys) && !in_array("filename",$keys) && !in_array("required",$keys)) {
    return myReturn(false, "Dados pendentes");
}

// SECOND WAY

$keys = implode("," array_keys($data));
if (!preg_match('/(path)|(filename)|(required)/'), $keys) {
    return myReturn(false, "Dados pendentes");
}


问:
Python + Flask: How to replace the value of a xml tag
I am trying to rewrite an XML file at a specific point.

I have a tag ['db']['usa']['user']['id']['number'] - for example...

I need to replace the value of the tag number.
I opened the file

```<code>with open('myFile.xml', 'a') as file:
    myFile = xmltodict.parse(file.read())
</code>```

and then I just say that

```<code>myFile['db']['usa']['user']['id']['number'] = 1
</code>```

But it doesn't really change the value to 1

How could I open an xml file and rewrite a specific value to a tag?

Thanks

答:
I assigned the node to a variable:

```<code>node = ['db']['usa']['user']['id']['number']
</code>```

and when returning the file I wrote the variable where it should be:

```<code>def returnFile(node, encoded):

     return '''<ID='''+node+'''>
     <CONTENTTYPE>image/jpeg</CONTENTTYPE>
     <CONTENTS>'''+str(encoded)+'''</CONTENTS>
     </BINARY-INFO-AZRLICHTBILD>'''
</code>```

That solved my problem

Body:
I am trying to rewrite an XML file at a specific point.

I have a tag ['db']['usa']['user']['id']['number'] - for example...

I need to replace the value of the tag number.
I opened the file

with open('myFile.xml', 'a') as file:
    myFile = xmltodict.parse(file.read())

and then I just say that

myFile['db']['usa']['user']['id']['number'] = 1

But it doesn't really change the value to 1

How could I open an xml file and rewrite a specific value to a tag?

Thanks

Body:
I assigned the node to a variable:

node = ['db']['usa']['user']['id']['number']

and when returning the file I wrote the variable where it should be:

def returnFile(node, encoded):

     return '''<ID='''+node+'''>
     <CONTENTTYPE>image/jpeg</CONTENTTYPE>
     <CONTENTS>'''+str(encoded)+'''</CONTENTS>
     </BINARY-INFO-AZRLICHTBILD>'''

That solved my problem