问:
TabLayout Not Binding to Viewpager
I have a fragment which hosts a TabLayout and a ViewPager. The host fragment is part of a container that switches based on the item selection of a bottom navigation bar.

For some reason, the ViewPager isn't inflating the fragments, and the TabLayout is unresponsive. When sliding left or right, the indicator stops as soon as you stop sliding, and doesn't snap like it should. And, of course, the fragments don't show.

Here is my code...I'm wondering what I am doing wrong.

PopularHolderFragment.java

```<code>import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import ai.gab.android.R;
import ai.gab.android.ui.adapters.fragment.PopularFragmentsAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Andrew Quebe on 10/20/2017.
 */

@SuppressWarnings("ConstantConditions")
public class PopularHolderFragment extends Fragment {

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;

    @BindView(R.id.viewPager)
    ViewPager viewPager;

    public static PopularHolderFragment newInstance() {
        return new PopularHolderFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_popular_holder, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewPager.setAdapter(new PopularFragmentsAdapter(getActivity().getSupportFragmentManager()));

        tabLayout.addTab(tabLayout.newTab().setText("Posts"));
        tabLayout.addTab(tabLayout.newTab().setText("Users"));
        tabLayout.setupWithViewPager(viewPager);
    }
}
</code>```

PopularFragmentsAdapter.java

```<code>import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import ai.gab.android.ui.fragments.popular.PopularPostsFragment;
import ai.gab.android.ui.fragments.popular.PopularUsersFragment;

/**
 * Created by Andrew Quebe on 8/7/2017.
 */

public class PopularFragmentsAdapter extends FragmentStatePagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return PopularPostsFragment.newInstance();
            case 1:
                return PopularUsersFragment.newInstance();
        }
        return null;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Posts";
            case 1:
                return "Users";
        }
        return super.getPageTitle(position);
    }

    @Override
    public int getCount() {
        return 2;
    }
}
</code>```

fragment_popular_holder.xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activities.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Light">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:elevation="2dp"
            tools:targetApi="lollipop" />

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

    <include layout="@layout/util_popular_main_content" />

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

util_popular_main_content.xml

```<code><android.support.constraint.ConstraintLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/fragment_popular_holder">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Screenshots

Also wondering why the text isn't its normal size.

Note that I do not want a toolbar in this layout, and perhaps that is my issue, but I don't see why it would be as the widgets should be able to work independently of each other.

答:
Using the comment from Mike and AndroidSmoker74's answer, I was able to fix the TabLayout bug.

PopularWrapperFragment.java

```<code>public class PopularWrapperFragment extends Fragment {

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;

    @BindView(R.id.viewPager)
    ViewPager viewPager;

    public static PopularWrapperFragment newInstance() {
        return new PopularWrapperFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_popular_holder, container, false);
        ButterKnife.bind(this, view);
        ((MainActivity) getActivity()).setPagingEnabled(false);
        viewPager.setAdapter(new PopularFragmentsAdapter(getChildFragmentManager()));
        tabLayout.setupWithViewPager(viewPager);
        return view;
    }
}
</code>```

PopularFragmentsAdapter.java

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

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return PopularPostsFragment.newInstance();
            case 1:
                return PopularUsersFragment.newInstance();
        }
        return null;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Posts";
            case 1:
                return "Users";
        }
        return super.getPageTitle(position);
    }

    @Override
    public int getCount() {
        return 2;
    }
}
</code>```

Hope someone finds this useful!

Title: TabLayout Not Binding to Viewpager

Body:
I have a fragment which hosts a TabLayout and a ViewPager. The host fragment is part of a container that switches based on the item selection of a bottom navigation bar.

For some reason, the ViewPager isn't inflating the fragments, and the TabLayout is unresponsive. When sliding left or right, the indicator stops as soon as you stop sliding, and doesn't snap like it should. And, of course, the fragments don't show.

Here is my code...I'm wondering what I am doing wrong.

PopularHolderFragment.java

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import ai.gab.android.R;
import ai.gab.android.ui.adapters.fragment.PopularFragmentsAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Andrew Quebe on 10/20/2017.
 */

@SuppressWarnings("ConstantConditions")
public class PopularHolderFragment extends Fragment {

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;

    @BindView(R.id.viewPager)
    ViewPager viewPager;

    public static PopularHolderFragment newInstance() {
        return new PopularHolderFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_popular_holder, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewPager.setAdapter(new PopularFragmentsAdapter(getActivity().getSupportFragmentManager()));

        tabLayout.addTab(tabLayout.newTab().setText("Posts"));
        tabLayout.addTab(tabLayout.newTab().setText("Users"));
        tabLayout.setupWithViewPager(viewPager);
    }
}

PopularFragmentsAdapter.java

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import ai.gab.android.ui.fragments.popular.PopularPostsFragment;
import ai.gab.android.ui.fragments.popular.PopularUsersFragment;

/**
 * Created by Andrew Quebe on 8/7/2017.
 */

public class PopularFragmentsAdapter extends FragmentStatePagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return PopularPostsFragment.newInstance();
            case 1:
                return PopularUsersFragment.newInstance();
        }
        return null;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Posts";
            case 1:
                return "Users";
        }
        return super.getPageTitle(position);
    }

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

fragment_popular_holder.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activities.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Light">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:elevation="2dp"
            tools:targetApi="lollipop" />

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

    <include layout="@layout/util_popular_main_content" />

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

util_popular_main_content.xml

<android.support.constraint.ConstraintLayout 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/fragment_popular_holder">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>

Screenshots

Also wondering why the text isn't its normal size.

Note that I do not want a toolbar in this layout, and perhaps that is my issue, but I don't see why it would be as the widgets should be able to work independently of each other.

Body:
Using the comment from Mike and AndroidSmoker74's answer, I was able to fix the TabLayout bug.

PopularWrapperFragment.java

public class PopularWrapperFragment extends Fragment {

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;

    @BindView(R.id.viewPager)
    ViewPager viewPager;

    public static PopularWrapperFragment newInstance() {
        return new PopularWrapperFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_popular_holder, container, false);
        ButterKnife.bind(this, view);
        ((MainActivity) getActivity()).setPagingEnabled(false);
        viewPager.setAdapter(new PopularFragmentsAdapter(getChildFragmentManager()));
        tabLayout.setupWithViewPager(viewPager);
        return view;
    }
}

PopularFragmentsAdapter.java

public class PopularFragmentsAdapter extends FragmentStatePagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return PopularPostsFragment.newInstance();
            case 1:
                return PopularUsersFragment.newInstance();
        }
        return null;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Posts";
            case 1:
                return "Users";
        }
        return super.getPageTitle(position);
    }

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

Hope someone finds this useful!


来源: stackexchange

问:
When I compile .c file it always creates .exe file with name 'a'
I use GCC compiler to compile and run C program on CMD.
When I compile C program using command gcc hello.c it creates an executable file file with name a.exe but when I use IDE it uses the name same as .c file as hello.exe.
Is it possible to create .exe file name same as .c file on CMD?

答:
You need to understand the syntax of output. Following is the description of the command:

```<code>$ gcc [options] [source files] [object files] -o output file
</code>```

In your case you should execute the commands as following:

```<code>$ gcc myfile.c -o myfile
$ ./myfile
</code>```

For more descriptions and more optimized ways refer to the following url:
http://www.rapidtables.com/code/linux/gcc/gcc-o.htm

ContentLicense: CC BY-SA 3.0

Body:
You need to understand the syntax of output. Following is the description of the command:

$ gcc [options] [source files] [object files] -o output file

In your case you should execute the commands as following:

$ gcc myfile.c -o myfile
$ ./myfile

For more descriptions and more optimized ways refer to the following url:
http://www.rapidtables.com/code/linux/gcc/gcc-o.htm


问:
tvOS - TVML background-color
Just started with TVML for Apple tvOS the other day. And I'm stuck..

Trying to set the background-color to a rgba for a reviewCard in TVML, but there are no changes..

background-color: rgba(255,255,255,100);

Any clue?

答:
The attribute background-color for rgba is red,blue,green,alpha.

Red,blue,green can be set in a range from 0 to 255.
Alpha however, can only be set in a range from 0.0 to 1.0

If you just want to make it full color, only set rgb without the alpha attribute, it will set 1.0 automatically.

Title: tvOS - TVML background-color


问:
Return checked value from Child to Parent and to Grandparent component using React
I am making a list of names of students and their ID's. The Parent class calls upon Child class whenever a list element is to be rendered.

```<code>export default class Parent extends Component {
  render() {
    return (
      <div>
        <div>
          <ul>{this.props.studentData.map(item => {
            return(
            <div><Child key={item.id} {...item} /></div>);
          })}
          </ul>
          <button>Submit</button>
        </div>
      </div>
    );
  }
}

export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (
      <li><input type="checkbox"/>{name}</li>
    );
  }
}
</code>```

I am trying to place a submit button under the list which returns the result of checked student name, one or many. What I don't understand is that how to return the value of student name from the Child component to Parent and all the way to the top of the hierarchy and store in some kind of variable. Is there a way to return values to the parent components i.e the components that make a call?

答:
You can send a callback function to Child which notifies whenever it has been checked or unchecked.

const Child = ({ id, name, onChange }) =>

    <input
      type="checkbox"
      onChange={(event) => onChange(id, event.target.checked) }
    />
    {name}

class Parent extends React.Component {
  constructor() {
    super()

    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(id, checked) {
    console.log(`student ${id} is ${checked ? 'checked' : 'unchecked'}`)
  }

  render() {
    return (

          {this.props.studentData.map(item =>
            <Child key={item.id} {...item} onChange={this.handleChange} />
          )}

    )
  }
}

const studentData = [
  { id: 1, name: 'Student 1' },
  { id: 2, name: 'Student 2' },
  { id: 3, name: 'Student 3' },
]

ReactDOM.render(
  <Parent studentData={studentData} />,
  document.getElementById('root')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Body:
I am making a list of names of students and their ID's. The Parent class calls upon Child class whenever a list element is to be rendered.

export default class Parent extends Component {
  render() {
    return (

{this.props.studentData.map(item => {
            return(

<Child key={item.id} {...item} />
);
          })}

          <button>Submit</button>

    );
  }
}

export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (

<input type="checkbox"/>{name}

    );
  }
}

I am trying to place a submit button under the list which returns the result of checked student name, one or many. What I don't understand is that how to return the value of student name from the Child component to Parent and all the way to the top of the hierarchy and store in some kind of variable. Is there a way to return values to the parent components i.e the components that make a call?

Body:
You can send a callback function to Child which notifies whenever it has been checked or unchecked.

const Child = ({ id, name, onChange }) =>
  <li>
    <input
      type="checkbox"
      onChange={(event) => onChange(id, event.target.checked) }
    />
    {name}
  </li>

class Parent extends React.Component {
  constructor() {
    super()

    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(id, checked) {
    console.log(`student ${id} is ${checked ? 'checked' : 'unchecked'}`)
  }

  render() {
    return (
      <div>
        <ul>
          {this.props.studentData.map(item =>
            <Child key={item.id} {...item} onChange={this.handleChange} />
          )}
        </ul>
      </div>
    )
  }
}

const studentData = [
  { id: 1, name: 'Student 1' },
  { id: 2, name: 'Student 2' },
  { id: 3, name: 'Student 3' },
]

ReactDOM.render(
  <Parent studentData={studentData} />,
  document.getElementById('root')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


问:
How to remove dictionary[String:AnyObject] for array using filter function in swift?
```<code>var globalCountArray = [AnyObject]()
var assetDictionary = [String:AnyObject]()
globalCountArray.append(assetDictionary as AnyObject)
</code>```

How to filter dictionary  using Anyobject array? I have tried this.

```<code>  globalCountArray = globalCountArray.filter {$0     as AnyObject != dict }
</code>```

But I got error

Binary operator '!=' cannot be applied to operands of type 'AnyObject' and '[String : AnyObject]'"

答:
Try using this

```<code>    var globalCountArray = [AnyObject]()
    var assetDictionary = [String:AnyObject]()
    globalCountArray.append(assetDictionary as AnyObject)
    let dict = [String:AnyObject]()

    globalCountArray = globalCountArray.filter({ (obj) -> Bool in

        if obj is[String:AnyObject] {

            return (obj as! [String:AnyObject]) != dict

        }
        return false
    })
</code>```

--------- OR You can achieve the same via ----------

```<code>globalCountArray = globalCountArray.filter({ (obj) -> Bool in

            if obj is[String:AnyObject] {

                return (obj as! [String:AnyObject]) == dict

            }
            return true
        })
</code>```

You need to add this method to outside your class definition.

```<code>public func !=(lhs: [String: AnyObject], rhs: [String: AnyObject] ) -> Bool {
    return !NSDictionary(dictionary: lhs).isEqual(to: rhs)
}

 public func ==(lhs: [String: AnyObject], rhs: [String: AnyObject] ) -> Bool {
    return NSDictionary(dictionary: lhs).isEqual(to: rhs)
}
</code>```

Body:
var globalCountArray = [AnyObject]()
var assetDictionary = [String:AnyObject]()
globalCountArray.append(assetDictionary as AnyObject)

How to filter dictionary  using Anyobject array? I have tried this.

  globalCountArray = globalCountArray.filter {$0     as AnyObject != dict }

But I got error

Binary operator '!=' cannot be applied to operands of type 'AnyObject' and '[String : AnyObject]'"

Body:
Try using this

    var globalCountArray = [AnyObject]()
    var assetDictionary = [String:AnyObject]()
    globalCountArray.append(assetDictionary as AnyObject)
    let dict = [String:AnyObject]()

    globalCountArray = globalCountArray.filter({ (obj) -> Bool in

        if obj is[String:AnyObject] {

            return (obj as! [String:AnyObject]) != dict

        }
        return false
    })

--------- OR You can achieve the same via ----------

globalCountArray = globalCountArray.filter({ (obj) -> Bool in

            if obj is[String:AnyObject] {

                return (obj as! [String:AnyObject]) == dict

            }
            return true
        })

You need to add this method to outside your class definition.

public func !=(lhs: [String: AnyObject], rhs: [String: AnyObject] ) -> Bool {
    return !NSDictionary(dictionary: lhs).isEqual(to: rhs)
}

 public func ==(lhs: [String: AnyObject], rhs: [String: AnyObject] ) -> Bool {
    return NSDictionary(dictionary: lhs).isEqual(to: rhs)
}


问:
Gitlab: piping commands with grep not working?
The following command in a job script:

```<code>STATUS_ID=$(grep -Eo "Status Code [0-9]+: Done" somefile | grep -Eo "[0-9]+")
</code>```

Seems to be causing the following ci lint error:

script config should be a string or an array of strings

The command works fine on my bash however when trying to grep the status code via a file containing the line:

Status Code 8484: Done

What is causing the error on gitlab?

答:
The colon (:) makes the line be interpeted as yaml map.

The solution (to escape the special meaning of the colon) is to enclose the entire line in single quotes:

```<code>'STATUS_ID=$(grep -Eo "Status Code [0-9]+: Done" somefile | grep -Eo "[0-9]+")'
</code>```

Body:
The following command in a job script:

STATUS_ID=$(grep -Eo "Status Code [0-9]+: Done" somefile | grep -Eo "[0-9]+")

Seems to be causing the following ci lint error:

script config should be a string or an array of strings

The command works fine on my bash however when trying to grep the status code via a file containing the line:

Status Code 8484: Done

What is causing the error on gitlab?

Body:
The colon (:) makes the line be interpeted as yaml map.

The solution (to escape the special meaning of the colon) is to enclose the entire line in single quotes:

'STATUS_ID=$(grep -Eo "Status Code [0-9]+: Done" somefile | grep -Eo "[0-9]+")'


问:
Save result of select statement into wide table SQL Server
I have read about the possibilty to create wide tables (30,000 columns) in SQL server (1)

But how do I actually save the result of a select statement (one that has 1024+ columns) into a wide table?

Because if I do:

```<code>Select *
Into wide_table
From (
       **Select statement with 1024+ columns**
      ) b
</code>```

I get: CREATE TABLE failed because column 'c157' in table 'wide_table' exceeds the maximum of 1024 columns.

And, will I be able to query that table and all it's columns in a regular manner?

Thank you for your help!

答:
You are right you are allowed to created table with 30 000 columns, but you can SELECT or INSERT 'only' 4096 column in one clause:

So, in case of SELECT you will need to get the columns in parts or concatenate the results. All of this does not seem to be practical and easier and performance efficient.

If you are going to have so many columns, maybe it will be better to try to UNPIVOT the data and normalized it further.

Body:
I have read about the possibilty to create wide tables (30,000 columns) in SQL server (1)

But how do I actually save the result of a select statement (one that has 1024+ columns) into a wide table?

Because if I do:

Select *
Into wide_table
From (
       **Select statement with 1024+ columns**
      ) b

I get: CREATE TABLE failed because column 'c157' in table 'wide_table' exceeds the maximum of 1024 columns.

And, will I be able to query that table and all it's columns in a regular manner?

Thank you for your help!


问:
Adding child element to XML in python
I have an element in an XML file as:

```<code><condition>
  <comparison compare="and">
    <operand idref="XXX" type="boolean" />
  </comparison>
</condition>
</code>```

I need to add two other child elements (child1 and child2) such as:

```<code><condition>
  <child1 compare='and'>
    <child2 idref='False' type='int' />
    <comparison compare="and">
      <operand idref="XXX" type="boolean" />
    </comparison>
  </child1>
</condition>
</code>```

I proceeded using lxml:

```<code>from lxml import etree
tree = etree.parse(xml_file)
condition_elem = tree.find("<path for the condition block in the xml>")
etree.SubElement(condition_elem, 'child1')
tree.write( 'newXML.xml', encoding='utf-8', xml_declaration=True)
</code>```

This just adds the element child1 as a child  of the element condition as below and did not satisfy my requirement:

```<code><condition>
  <child1></child1>
  <comparison compare="and">
    <operand idref="XXX" type="boolean" />
  </comparison>
</condition>
</code>```

Any ideas? Thanks

答:
Using lxml's objectify submodule over it's etree submodule, I would cut out the comparison element from root, add the child1 element to it and the stuff comparison back in to that:

```<code>from lxml import objectify

tree = objectify.parse(xml_file)
condition = tree.getroot()
comparison = condition.comparison

M = objectify.ElementMaker(annotate=False)
child1 = M("child1", {'compare': 'and'})
child2 = M("child2", {'idref': 'False', 'type': 'int'})

condition.remove(comparison)
condition.child1 = child1
condition.child2 = child2
condition.child1.comparison = comparison
</code>```

The ElementMaker is an easy-to-use tool to create new xml elements. I first an instance of it (M) that doesn't annotate the xml (litter it with attributes), then use that instance to create the children, you ask for. The rest is fairly self explanatory, I think.

Title: Adding child element to XML in python

Body:
I have an element in an XML file as:

<condition>
  <comparison compare="and">
    <operand idref="XXX" type="boolean" />
  </comparison>
</condition>

I need to add two other child elements (child1 and child2) such as:

<condition>
  <child1 compare='and'>
    <child2 idref='False' type='int' />
    <comparison compare="and">
      <operand idref="XXX" type="boolean" />
    </comparison>
  </child1>
</condition>

I proceeded using lxml:

from lxml import etree
tree = etree.parse(xml_file)
condition_elem = tree.find("<path for the condition block in the xml>")
etree.SubElement(condition_elem, 'child1')
tree.write( 'newXML.xml', encoding='utf-8', xml_declaration=True)

This just adds the element child1 as a child  of the element condition as below and did not satisfy my requirement:

<condition>
  <child1></child1>
  <comparison compare="and">
    <operand idref="XXX" type="boolean" />
  </comparison>
</condition>

Any ideas? Thanks

Body:
Using lxml's objectify submodule over it's etree submodule, I would cut out the comparison element from root, add the child1 element to it and the stuff comparison back in to that:

from lxml import objectify

tree = objectify.parse(xml_file)
condition = tree.getroot()
comparison = condition.comparison

M = objectify.ElementMaker(annotate=False)
child1 = M("child1", {'compare': 'and'})
child2 = M("child2", {'idref': 'False', 'type': 'int'})

condition.remove(comparison)
condition.child1 = child1
condition.child2 = child2
condition.child1.comparison = comparison

The ElementMaker is an easy-to-use tool to create new xml elements. I first an instance of it (M) that doesn't annotate the xml (litter it with attributes), then use that instance to create the children, you ask for. The rest is fairly self explanatory, I think.


问:
Keras: load image in generator vs load image outside of generator
in the following script I want to train a CNN with mnist data.
The data is in the dataset_dir and all images are .png. The labels are the folders of the images.
Now I want to train the CNN with a generator, which gets the imagepaths and the labels.

```<code>from __future__ import print_function
import cv2, numpy as np
import random, os, glob, time
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D

dataset_dir = '/home/viktor/PycharmProjects/Datasets/mnist_png/training/**/*.png' #lies alle bilder ein, egal ob train oder test set, wir splitten spaeter
NUM_CLASSES = 10
BATCH_SIZE = 128
NUM_EPOCHS = 1

def paths_and_labels(dataset_dir):
    # dataset_dir = '/home/viktor/PycharmProjects/Datasets/mnist_png/training/**/*.png' # dataset_dir soll so aussehen, die zwei ** sind die klassennamen, ordner** ist also ordner_auto, ordner_person,...
    paths = glob.glob(dataset_dir)
    labels = []
    labels.append([os.path.basename(os.path.dirname(path)) for path in paths])
    labels = labels[0] #labels als string

    class_names = list(set(labels)) # welche klassen gibt es, string
    labels_classes = np.zeros([len(labels)], dtype=int)
    for i, class_name in enumerate(class_names):
        class_index = [j for j, x in enumerate(labels) if x == class_name]
        labels_classes[class_index] = i # labels als int, um die klasse als string zu bekommen, mach = class_names[labels_class[nr]]

    paths_and_labels_classes = list(zip(paths, labels_classes))
    random.shuffle(paths_and_labels_classes)
    paths, labels_classes = zip(*paths_and_labels_classes)

    train_paths = paths[0:int(0.6 * len(paths))]
    train_labels = labels_classes[0:int(0.6 * len(labels_classes))]

    test_paths = paths[int(0.8 * len(paths)):]
    test_labels = labels_classes[int(0.8 * len(labels_classes)):]

    val_paths = paths[int(0.6 * len(paths)):int(0.8 * len(paths))]
    val_labels = labels_classes[int(0.6 * len(paths)):int(0.8 * len(paths))]

    return train_paths, train_labels, test_paths, test_labels, val_paths, val_labels, class_names

def generator(image_paths, labels, batch_size):
    batch_features = np.zeros((batch_size, 28, 28, 1)) #oder 224,224,3
    batch_labels = np.zeros((batch_size, NUM_CLASSES))
    while True:
        for i in range(batch_size):
            # choose random index of one image in image_paths
            index = np.random.choice(len(image_paths), 1, replace=False)[0]
            im = cv2.resize(cv2.imread(image_paths[index],0), (28, 28)).astype(np.float32)
            im = np.expand_dims(im, axis=2) # weil es ein CHANNEL ist, spaeter muss das glaube ich weg
            batch_features[i] = im
            batch_labels[i][labels[index]] = 1
        batch_features = batch_features.astype('float32')
        batch_features /= 255
        yield (batch_features, batch_labels)

train_paths, train_labels, test_paths, test_labels, val_paths, val_labels, c_names = paths_and_labels(dataset_dir)
input_shape = (28, 28, 1)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(NUM_CLASSES, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
model.summary()
#my_callback = [keras.callbacks.TensorBoard(log_dir='/home/viktor/PycharmProjects/CNN_Object_Classification/logs2', histogram_freq=0, batch_size=32, write_graph=True, write_grads=False, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)]
start_time = time.clock()
model.fit_generator(generator=generator(train_paths, train_labels, BATCH_SIZE), steps_per_epoch=int(len(train_paths)/BATCH_SIZE), epochs=NUM_EPOCHS)#,callbacks=my_callback)
elapsed_time = time.clock() - start_time
print('elapsed time: ', elapsed_time)
</code>```

The results are not good

```<code>  1/281 [..............................] - ETA: 493s - loss: 16.0029 - acc: 0.1250
  2/281 [..............................] - ETA: 255s - loss: 15.9644 - acc: 0.0820
  3/281 [..............................] - ETA: 175s - loss: 39.3005 - acc: 0.0729
  4/281 [..............................] - ETA: 135s - loss: 49.8761 - acc: 0.0742
  5/281 [..............................] - ETA: 113s - loss: 55.0494 - acc: 0.0703

277/281 [============================>.] - ETA: 0s - loss: 25.6649 - acc: 0.0346
278/281 [============================>.] - ETA: 0s - loss: 25.6554 - acc: 0.0345
279/281 [============================>.] - ETA: 0s - loss: 25.6460 - acc: 0.0343
280/281 [============================>.] - ETA: 0s - loss: 25.6367 - acc: 0.0342
281/281 [==============================] - 22s - loss: 25.6274 - acc: 0.0341
elapsed time:  37.915506
</code>```

If I try the same thing, but loading all images before giving them to the generator (and not just giving the paths), then its much better.

```<code>from __future__ import print_function
import cv2, numpy as np
import random, os, glob, time
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D

dataset_dir = '/home/viktor/PycharmProjects/Datasets/mnist_png/training/**/*.png' #lies alle bilder ein, egal ob train oder test set, wir splitten spaeter
NUM_CLASSES = 10
BATCH_SIZE = 128
NUM_EPOCHS = 1

def paths_and_labels(dataset_dir):
    # dataset_dir = '/home/viktor/PycharmProjects/Datasets/mnist_png/training/**/*.png' # dataset_dir soll so aussehen, die zwei ** sind die klassennamen, ordner** ist also ordner_auto, ordner_person,...
    paths = glob.glob(dataset_dir)
    labels = []
    labels.append([os.path.basename(os.path.dirname(path)) for path in paths])
    labels = labels[0] #labels als string

    class_names = list(set(labels)) # welche klassen gibt es, string
    labels_classes = np.zeros([len(labels)], dtype=int)
    for i, class_name in enumerate(class_names):
        class_index = [j for j, x in enumerate(labels) if x == class_name]
        labels_classes[class_index] = i # labels als int, um die klasse als string zu bekommen, mach = class_names[labels_class[nr]]

    paths_and_labels_classes = list(zip(paths, labels_classes))
    random.shuffle(paths_and_labels_classes)
    paths, labels_classes = zip(*paths_and_labels_classes)

    train_paths = paths[0:int(0.6 * len(paths))]
    train_labels = labels_classes[0:int(0.6 * len(labels_classes))]

    test_paths = paths[int(0.8 * len(paths)):]
    test_labels = labels_classes[int(0.8 * len(labels_classes)):]

    val_paths = paths[int(0.6 * len(paths)):int(0.8 * len(paths))]
    val_labels = labels_classes[int(0.6 * len(paths)):int(0.8 * len(paths))]

    train_images = np.zeros((len(train_paths), 28, 28, 1))  # oder 224,224,3
    train_labels_bin = np.zeros((len(train_paths), NUM_CLASSES))

    for i in range(len(train_paths)):
        im = cv2.resize(cv2.imread(train_paths[i], 0), (28, 28)).astype(np.float32)
        im = np.expand_dims(im, axis=2)  # weil es ein CHANNEL ist, spaeter muss das glaube ich weg
        train_images[i] = im
        train_labels_bin[i][train_labels[i]] = 1
    train_images = train_images.astype('float32')
    train_images /= 255

    return train_images, train_labels_bin

def generator(images, labels, batch_size):
    batch_features = np.zeros((batch_size, 28, 28, 1),np.float32) #oder 224,224,3
    batch_labels = np.zeros((batch_size, NUM_CLASSES))
    while True:
        for i in range(batch_size):
            # choose random index of one image in image_paths
            index = np.random.choice(len(images), 1, replace=False)[0]
            batch_features[i] = images[index]
            batch_labels[i] = labels[index]
        yield (batch_features, batch_labels)

train_images, train_labels_bin = paths_and_labels(dataset_dir)
input_shape = (28, 28, 1)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(NUM_CLASSES, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
model.summary()
#my_callback = [keras.callbacks.TensorBoard(log_dir='/home/viktor/PycharmProjects/CNN_Object_Classification/logs2', histogram_freq=0, batch_size=32, write_graph=True, write_grads=False, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)]
start_time = time.clock()
model.fit_generator(generator=generator(train_images, train_labels_bin, BATCH_SIZE), steps_per_epoch=int(len(train_images)/BATCH_SIZE), epochs=NUM_EPOCHS)#,callbacks=my_callback)
elapsed_time = time.clock() - start_time
print('elapsed time: ', elapsed_time)
</code>```

The results:

```<code>  1/281 [..............................] - ETA: 461s - loss: 2.3143 - acc: 0.0859
  2/281 [..............................] - ETA: 238s - loss: 2.3017 - acc: 0.1133
  3/281 [..............................] - ETA: 164s - loss: 2.2830 - acc: 0.1536
  4/281 [..............................] - ETA: 128s - loss: 2.2632 - acc: 0.1953
  5/281 [..............................] - ETA: 106s - loss: 2.2439 - acc: 0.2219

277/281 [============================>.] - ETA: 0s - loss: 0.4778 - acc: 0.8619
278/281 [============================>.] - ETA: 0s - loss: 0.4766 - acc: 0.8623
279/281 [============================>.] - ETA: 0s - loss: 0.4759 - acc: 0.8626
280/281 [============================>.] - ETA: 0s - loss: 0.4747 - acc: 0.8629
281/281 [==============================] - 23s - loss: 0.4735 - acc: 0.8632
elapsed time:  37.089643
</code>```

I already checked if the output of the generator is the same. And it is.
So my question is, why is the loss so bad with the first script? Everything is the same. The only difference is, that in the first script I load the data IN the generator function.
And in the second Script I load the data outside of the generator function.

答:
I found my Mistake

the right generator fkt should be:

```<code>def generator(image_paths, labels, batch_size):

    while True:
        batch_features = np.zeros((batch_size, 28, 28, 1))  # oder 224,224,3
        batch_labels = np.zeros((batch_size, NUM_CLASSES))
        for i in range(batch_size):
            # choose random index of one image in image_paths
            index = np.random.choice(len(image_paths), 1, replace=False)[0]
            im = cv2.resize(cv2.imread(image_paths[index],0), (28, 28)).astype(np.float32)
            im = np.expand_dims(im, axis=2) # weil es ein CHANNEL ist, spaeter muss das glaube ich weg
            batch_features[i] = im
            batch_labels[i][labels[index]] = 1
        batch_features = batch_features.astype('float32')
        batch_features /= 255
        yield (batch_features, batch_labels)
</code>```

Body:
in the following script I want to train a CNN with mnist data.
The data is in the dataset_dir and all images are .png. The labels are the folders of the images.
Now I want to train the CNN with a generator, which gets the imagepaths and the labels.

from __future__ import print_function
import cv2, numpy as np
import random, os, glob, time
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D

dataset_dir = '/home/viktor/PycharmProjects/Datasets/mnist_png/training/**/*.png' #lies alle bilder ein, egal ob train oder test set, wir splitten spaeter
NUM_CLASSES = 10
BATCH_SIZE = 128
NUM_EPOCHS = 1

def paths_and_labels(dataset_dir):
    # dataset_dir = '/home/viktor/PycharmProjects/Datasets/mnist_png/training/**/*.png' # dataset_dir soll so aussehen, die zwei ** sind die klassennamen, ordner** ist also ordner_auto, ordner_person,...
    paths = glob.glob(dataset_dir)
    labels = []
    labels.append([os.path.basename(os.path.dirname(path)) for path in paths])
    labels = labels[0] #labels als string

    class_names = list(set(labels)) # welche klassen gibt es, string
    labels_classes = np.zeros([len(labels)], dtype=int)
    for i, class_name in enumerate(class_names):
        class_index = [j for j, x in enumerate(labels) if x == class_name]
        labels_classes[class_index] = i # labels als int, um die klasse als string zu bekommen, mach = class_names[labels_class[nr]]

    paths_and_labels_classes = list(zip(paths, labels_classes))
    random.shuffle(paths_and_labels_classes)
    paths, labels_classes = zip(*paths_and_labels_classes)

    train_paths = paths[0:int(0.6 * len(paths))]
    train_labels = labels_classes[0:int(0.6 * len(labels_classes))]

    test_paths = paths[int(0.8 * len(paths)):]
    test_labels = labels_classes[int(0.8 * len(labels_classes)):]

    val_paths = paths[int(0.6 * len(paths)):int(0.8 * len(paths))]
    val_labels = labels_classes[int(0.6 * len(paths)):int(0.8 * len(paths))]

    return train_paths, train_labels, test_paths, test_labels, val_paths, val_labels, class_names

def generator(image_paths, labels, batch_size):
    batch_features = np.zeros((batch_size, 28, 28, 1)) #oder 224,224,3
    batch_labels = np.zeros((batch_size, NUM_CLASSES))
    while True:
        for i in range(batch_size):
            # choose random index of one image in image_paths
            index = np.random.choice(len(image_paths), 1, replace=False)[0]
            im = cv2.resize(cv2.imread(image_paths[index],0), (28, 28)).astype(np.float32)
            im = np.expand_dims(im, axis=2) # weil es ein CHANNEL ist, spaeter muss das glaube ich weg
            batch_features[i] = im
            batch_labels[i][labels[index]] = 1
        batch_features = batch_features.astype('float32')
        batch_features /= 255
        yield (batch_features, batch_labels)

train_paths, train_labels, test_paths, test_labels, val_paths, val_labels, c_names = paths_and_labels(dataset_dir)
input_shape = (28, 28, 1)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(NUM_CLASSES, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
model.summary()
#my_callback = [keras.callbacks.TensorBoard(log_dir='/home/viktor/PycharmProjects/CNN_Object_Classification/logs2', histogram_freq=0, batch_size=32, write_graph=True, write_grads=False, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)]
start_time = time.clock()
model.fit_generator(generator=generator(train_paths, train_labels, BATCH_SIZE), steps_per_epoch=int(len(train_paths)/BATCH_SIZE), epochs=NUM_EPOCHS)#,callbacks=my_callback)
elapsed_time = time.clock() - start_time
print('elapsed time: ', elapsed_time)

The results are not good

  1/281 [..............................] - ETA: 493s - loss: 16.0029 - acc: 0.1250
  2/281 [..............................] - ETA: 255s - loss: 15.9644 - acc: 0.0820
  3/281 [..............................] - ETA: 175s - loss: 39.3005 - acc: 0.0729
  4/281 [..............................] - ETA: 135s - loss: 49.8761 - acc: 0.0742
  5/281 [..............................] - ETA: 113s - loss: 55.0494 - acc: 0.0703

277/281 [============================>.] - ETA: 0s - loss: 25.6649 - acc: 0.0346
278/281 [============================>.] - ETA: 0s - loss: 25.6554 - acc: 0.0345
279/281 [============================>.] - ETA: 0s - loss: 25.6460 - acc: 0.0343
280/281 [============================>.] - ETA: 0s - loss: 25.6367 - acc: 0.0342
281/281 [==============================] - 22s - loss: 25.6274 - acc: 0.0341
elapsed time:  37.915506

If I try the same thing, but loading all images before giving them to the generator (and not just giving the paths), then its much better.

from __future__ import print_function
import cv2, numpy as np
import random, os, glob, time
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D

dataset_dir = '/home/viktor/PycharmProjects/Datasets/mnist_png/training/**/*.png' #lies alle bilder ein, egal ob train oder test set, wir splitten spaeter
NUM_CLASSES = 10
BATCH_SIZE = 128
NUM_EPOCHS = 1

def paths_and_labels(dataset_dir):
    # dataset_dir = '/home/viktor/PycharmProjects/Datasets/mnist_png/training/**/*.png' # dataset_dir soll so aussehen, die zwei ** sind die klassennamen, ordner** ist also ordner_auto, ordner_person,...
    paths = glob.glob(dataset_dir)
    labels = []
    labels.append([os.path.basename(os.path.dirname(path)) for path in paths])
    labels = labels[0] #labels als string

    class_names = list(set(labels)) # welche klassen gibt es, string
    labels_classes = np.zeros([len(labels)], dtype=int)
    for i, class_name in enumerate(class_names):
        class_index = [j for j, x in enumerate(labels) if x == class_name]
        labels_classes[class_index] = i # labels als int, um die klasse als string zu bekommen, mach = class_names[labels_class[nr]]

    paths_and_labels_classes = list(zip(paths, labels_classes))
    random.shuffle(paths_and_labels_classes)
    paths, labels_classes = zip(*paths_and_labels_classes)

    train_paths = paths[0:int(0.6 * len(paths))]
    train_labels = labels_classes[0:int(0.6 * len(labels_classes))]

    test_paths = paths[int(0.8 * len(paths)):]
    test_labels = labels_classes[int(0.8 * len(labels_classes)):]

    val_paths = paths[int(0.6 * len(paths)):int(0.8 * len(paths))]
    val_labels = labels_classes[int(0.6 * len(paths)):int(0.8 * len(paths))]

    train_images = np.zeros((len(train_paths), 28, 28, 1))  # oder 224,224,3
    train_labels_bin = np.zeros((len(train_paths), NUM_CLASSES))

    for i in range(len(train_paths)):
        im = cv2.resize(cv2.imread(train_paths[i], 0), (28, 28)).astype(np.float32)
        im = np.expand_dims(im, axis=2)  # weil es ein CHANNEL ist, spaeter muss das glaube ich weg
        train_images[i] = im
        train_labels_bin[i][train_labels[i]] = 1
    train_images = train_images.astype('float32')
    train_images /= 255

    return train_images, train_labels_bin

def generator(images, labels, batch_size):
    batch_features = np.zeros((batch_size, 28, 28, 1),np.float32) #oder 224,224,3
    batch_labels = np.zeros((batch_size, NUM_CLASSES))
    while True:
        for i in range(batch_size):
            # choose random index of one image in image_paths
            index = np.random.choice(len(images), 1, replace=False)[0]
            batch_features[i] = images[index]
            batch_labels[i] = labels[index]
        yield (batch_features, batch_labels)

train_images, train_labels_bin = paths_and_labels(dataset_dir)
input_shape = (28, 28, 1)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(NUM_CLASSES, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
model.summary()
#my_callback = [keras.callbacks.TensorBoard(log_dir='/home/viktor/PycharmProjects/CNN_Object_Classification/logs2', histogram_freq=0, batch_size=32, write_graph=True, write_grads=False, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)]
start_time = time.clock()
model.fit_generator(generator=generator(train_images, train_labels_bin, BATCH_SIZE), steps_per_epoch=int(len(train_images)/BATCH_SIZE), epochs=NUM_EPOCHS)#,callbacks=my_callback)
elapsed_time = time.clock() - start_time
print('elapsed time: ', elapsed_time)

The results:

  1/281 [..............................] - ETA: 461s - loss: 2.3143 - acc: 0.0859
  2/281 [..............................] - ETA: 238s - loss: 2.3017 - acc: 0.1133
  3/281 [..............................] - ETA: 164s - loss: 2.2830 - acc: 0.1536
  4/281 [..............................] - ETA: 128s - loss: 2.2632 - acc: 0.1953
  5/281 [..............................] - ETA: 106s - loss: 2.2439 - acc: 0.2219

277/281 [============================>.] - ETA: 0s - loss: 0.4778 - acc: 0.8619
278/281 [============================>.] - ETA: 0s - loss: 0.4766 - acc: 0.8623
279/281 [============================>.] - ETA: 0s - loss: 0.4759 - acc: 0.8626
280/281 [============================>.] - ETA: 0s - loss: 0.4747 - acc: 0.8629
281/281 [==============================] - 23s - loss: 0.4735 - acc: 0.8632
elapsed time:  37.089643

I already checked if the output of the generator is the same. And it is.
So my question is, why is the loss so bad with the first script? Everything is the same. The only difference is, that in the first script I load the data IN the generator function.
And in the second Script I load the data outside of the generator function.

Body:
I found my Mistake

the right generator fkt should be:

def generator(image_paths, labels, batch_size):

    while True:
        batch_features = np.zeros((batch_size, 28, 28, 1))  # oder 224,224,3
        batch_labels = np.zeros((batch_size, NUM_CLASSES))
        for i in range(batch_size):
            # choose random index of one image in image_paths
            index = np.random.choice(len(image_paths), 1, replace=False)[0]
            im = cv2.resize(cv2.imread(image_paths[index],0), (28, 28)).astype(np.float32)
            im = np.expand_dims(im, axis=2) # weil es ein CHANNEL ist, spaeter muss das glaube ich weg
            batch_features[i] = im
            batch_labels[i][labels[index]] = 1
        batch_features = batch_features.astype('float32')
        batch_features /= 255
        yield (batch_features, batch_labels)


问:
How to round off timestamp in milliseconds to nearest seconds?
How to round off the current timestamp in milliseconds to seconds?

If this is the current timestamp in milliseconds I have -

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

The if I am rounding off to nearest second then will it be like this?

```<code>Time in MS rounded off to nearest Second = 1384393612000
</code>```

I might need to do this both in Java and C++.

答:
tl;dr

```<code>Instant.ofEpochMilli( 1_384_393_612_958L )
       .truncatedTo( ChronoUnit.SECONDS )
       .toEpochMilli()
</code>```

java.time

The modern approach in Java uses the java.time classes.

The Instant class represents a point on the timeline in UTC with a resolution of nanoseconds.

```<code>Instant instant = Instant.ofEpochMilli( 1_384_393_612_958L ) ;
Instant instantTrunc = instant.truncatedTo( ChronoUnit.SECONDS ) ;
long millis = instantTrunc.toEpochMilli() ;
</code>```

Body:
How to round off the current timestamp in milliseconds to seconds?

If this is the current timestamp in milliseconds I have -

1384393612958

The if I am rounding off to nearest second then will it be like this?

Time in MS rounded off to nearest Second = 1384393612000

I might need to do this both in Java and C++.

Body:
tl;dr

Instant.ofEpochMilli( 1_384_393_612_958L )
       .truncatedTo( ChronoUnit.SECONDS )
       .toEpochMilli()

java.time

The modern approach in Java uses the java.time classes.

The Instant class represents a point on the timeline in UTC with a resolution of nanoseconds.

Instant instant = Instant.ofEpochMilli( 1_384_393_612_958L ) ;
Instant instantTrunc = instant.truncatedTo( ChronoUnit.SECONDS ) ;
long millis = instantTrunc.toEpochMilli() ;


问:
How to reproduce $resample and $result of 'train' object in caret?
I'm new to the amazing caret package and try to reproduce some of the objects from the train() output from a lm model with resampling method = 'timeslice'.

Why does the $result$RMSE and $result$Rsquared in my example differ
from the output from the function defaultSummary($pred$pred, $pred$obs)?

What data is used to calculate RMSE, Rsquared, MAE in $resample?

```<code>require(caret)
require(doParallel)

no_cores <- detectCores() - 1
cls = makeCluster(no_cores)
registerDoParallel(cls)

data(economics)
#str(economics)
ec.data <- as.data.frame(economics[,-1]) #drop 'date' column
#head(ec.data)

#trainControl() with parallel processing and 1 step forecasts by TimeSlices------------------------
set.seed(123)
samplesCount = nrow(ec.data)
initialWindow  = 10
h = 1
s = 0
M = 1 # no of models that are evaluated during each resample (tuning parameters)

#seeds
resamplesCount = length(createTimeSlices(1:samplesCount, initialWindow, horizon = h, fixedWindow = TRUE, skip = s)$test)
seeds <- vector(mode = "list", length = resamplesCount + 1)   # length = B+1, B = number of resamples
for(i in 1:resamplesCount) seeds[[i]] <- sample.int(1000, M)  # The first B elements of the list should be vectors of integers of >= length M where M is the number of models being evaluated for each resample.
seeds[[(resamplesCount+1)]] <- sample.int(1000, 1) # The last element of the list only needs to be a single integer (for the final model)

trainCtrl.ec <- trainControl(
  method = "timeslice", initialWindow = initialWindow, horizon = h, skip = s,    # data splitting
  returnResamp = "all",
  savePredictions = "all",
  seeds = seeds,
  allowParallel = TRUE)

lm.fit.ec <- train( unemploy ~ ., data = ec.data,
                  method = "lm",
                  trControl = trainCtrl.ec)

lm.fit.ec
head(lm.fit.ec$resample)
</code>```

Output:

```<code>> lm.fit.ec
Linear Regression

574 samples
  4 predictor

No pre-processing
Resampling: Rolling Forecasting Origin Resampling (1 held-out with a fixed window)
Summary of sample sizes: 10, 10, 10, 10, 10, 10, ...
Resampling results:

  RMSE     Rsquared  MAE
  250.072  NaN       250.072

Tuning parameter 'intercept' was held constant at a value of TRUE
</code>```

Why isn't the output for RMSE and Rsquared the same as when calculated with defaultSummary() ?

```<code>dat <- as.data.frame(cbind(lm.fit.ec$pred$pred, lm.fit.ec$pred$obs))
colnames(dat) <- c("pred", "obs")
defaultSummary(dat)

> defaultSummary(dat)
      RMSE   Rsquared        MAE
394.440680   0.978365 250.072031
</code>```

How can I reproduce the results in $resample?

```<code>> head(lm.fit.ec$resample)
       RMSE Rsquared       MAE intercept    Resample
1  16.33273       NA  16.33273      TRUE Training010
2 232.16184       NA 232.16184      TRUE Training011
3 197.65143       NA 197.65143      TRUE Training012
4 393.29469       NA 393.29469      TRUE Training013
5 129.99157       NA 129.99157      TRUE Training014
6  60.95649       NA  60.95649      TRUE Training015
</code>```

Session Info:

```<code>> sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=Swedish_Sweden.1252  LC_CTYPE=Swedish_Sweden.1252    LC_MONETARY=Swedish_Sweden.1252
[4] LC_NUMERIC=C                    LC_TIME=Swedish_Sweden.1252

attached base packages:
[1] parallel  stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] fpp_0.5             tseries_0.10-42     lmtest_0.9-35       zoo_1.8-0
 [5] expsmooth_2.3       fma_2.3             forecast_8.2        mlbench_2.1-1
 [9] spikeslab_1.1.5     randomForest_4.6-12 lars_1.2            doParallel_1.0.11
[13] iterators_1.0.8     foreach_1.4.3       caret_6.0-77.9000   ggplot2_2.2.1
[17] lattice_0.20-35
</code>```

答:
I found the answer to my questions here: https://stats.stackexchange.com/questions/114168/how-to-get-sub-training-and-sub-test-from-cross-validation-in-caret

Q1. Why does the $result$RMSE and $result$Rsquared in my example differ from the output from the function defaultSummary($pred$pred, $pred$obs)?

A: The output from train is calculated as the average of the holdouts. In my example:

```<code>    # The output is the mean of $resample
    mean(lm.fit.ec$resample$RMSE)  # =250.072
    mean(lm.fit.ec$resample$MAE)   # =250.072
</code>```

Q2. What data is used to calculate RMSE, Rsquared, MAE in $resample?

```<code>> head(lm.fit.ec$resample)
RMSE Rsquared       MAE intercept    Resample
1  16.33273       NA  16.33273      TRUE Training010
2 232.16184       NA 232.16184      TRUE Training011
3 197.65143       NA 197.65143      TRUE Training012
4 393.29469       NA 393.29469      TRUE Training013
5 129.99157       NA 129.99157      TRUE Training014
6  60.95649       NA  60.95649      TRUE Training015

first_holdout <- subset(lm.fit.ec$pred, Resample == "Training010")
first_holdout

> first_holdout
pred        obs rowIndex intercept    Resample
1 2756.333 2740       11      TRUE Training010  # only 1 row since 1 step forecast horizon

# Calculate RMSE, Rsquared and MAE for the holdout set
postResample(first_holdout$pred, first_holdout$obs)

> postResample(first_holdout$pred, first_holdout$obs)
RMSE     Rsquared      MAE
16.33273       NA     16.33273
</code>```

My confusion here was mainly caused by the fact that Rsquared was NA. But since the forcast horizon was 1 step all the hold out samples only have one row and thus no Rsquared can be calculated.

Body:
I'm new to the amazing caret package and try to reproduce some of the objects from the train() output from a lm model with resampling method = 'timeslice'.

Why does the $result$RMSE and $result$Rsquared in my example differ
from the output from the function defaultSummary($pred$pred, $pred$obs)?

What data is used to calculate RMSE, Rsquared, MAE in $resample?

require(caret)
require(doParallel)

no_cores <- detectCores() - 1
cls = makeCluster(no_cores)
registerDoParallel(cls)

data(economics)
#str(economics)
ec.data <- as.data.frame(economics[,-1]) #drop 'date' column
#head(ec.data)

#trainControl() with parallel processing and 1 step forecasts by TimeSlices------------------------
set.seed(123)
samplesCount = nrow(ec.data)
initialWindow  = 10
h = 1
s = 0
M = 1 # no of models that are evaluated during each resample (tuning parameters)

#seeds
resamplesCount = length(createTimeSlices(1:samplesCount, initialWindow, horizon = h, fixedWindow = TRUE, skip = s)$test)
seeds <- vector(mode = "list", length = resamplesCount + 1)   # length = B+1, B = number of resamples
for(i in 1:resamplesCount) seeds[[i]] <- sample.int(1000, M)  # The first B elements of the list should be vectors of integers of >= length M where M is the number of models being evaluated for each resample.
seeds[[(resamplesCount+1)]] <- sample.int(1000, 1) # The last element of the list only needs to be a single integer (for the final model)

trainCtrl.ec <- trainControl(
  method = "timeslice", initialWindow = initialWindow, horizon = h, skip = s,    # data splitting
  returnResamp = "all",
  savePredictions = "all",
  seeds = seeds,
  allowParallel = TRUE)

lm.fit.ec <- train( unemploy ~ ., data = ec.data,
                  method = "lm",
                  trControl = trainCtrl.ec)

lm.fit.ec
head(lm.fit.ec$resample)

Output:

> lm.fit.ec
Linear Regression

574 samples
  4 predictor

No pre-processing
Resampling: Rolling Forecasting Origin Resampling (1 held-out with a fixed window)
Summary of sample sizes: 10, 10, 10, 10, 10, 10, ...
Resampling results:

  RMSE     Rsquared  MAE
  250.072  NaN       250.072

Tuning parameter 'intercept' was held constant at a value of TRUE

Why isn't the output for RMSE and Rsquared the same as when calculated with defaultSummary() ?

dat <- as.data.frame(cbind(lm.fit.ec$pred$pred, lm.fit.ec$pred$obs))
colnames(dat) <- c("pred", "obs")
defaultSummary(dat)

> defaultSummary(dat)
      RMSE   Rsquared        MAE
394.440680   0.978365 250.072031

How can I reproduce the results in $resample?

> head(lm.fit.ec$resample)
       RMSE Rsquared       MAE intercept    Resample
1  16.33273       NA  16.33273      TRUE Training010
2 232.16184       NA 232.16184      TRUE Training011
3 197.65143       NA 197.65143      TRUE Training012
4 393.29469       NA 393.29469      TRUE Training013
5 129.99157       NA 129.99157      TRUE Training014
6  60.95649       NA  60.95649      TRUE Training015

Session Info:

> sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=Swedish_Sweden.1252  LC_CTYPE=Swedish_Sweden.1252    LC_MONETARY=Swedish_Sweden.1252
[4] LC_NUMERIC=C                    LC_TIME=Swedish_Sweden.1252

attached base packages:
[1] parallel  stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] fpp_0.5             tseries_0.10-42     lmtest_0.9-35       zoo_1.8-0
 [5] expsmooth_2.3       fma_2.3             forecast_8.2        mlbench_2.1-1
 [9] spikeslab_1.1.5     randomForest_4.6-12 lars_1.2            doParallel_1.0.11
[13] iterators_1.0.8     foreach_1.4.3       caret_6.0-77.9000   ggplot2_2.2.1
[17] lattice_0.20-35

Body:
I found the answer to my questions here: https://stats.stackexchange.com/questions/114168/how-to-get-sub-training-and-sub-test-from-cross-validation-in-caret

Q1. Why does the $result$RMSE and $result$Rsquared in my example differ from the output from the function defaultSummary($pred$pred, $pred$obs)?

A: The output from train is calculated as the average of the holdouts. In my example:

    # The output is the mean of $resample
    mean(lm.fit.ec$resample$RMSE)  # =250.072
    mean(lm.fit.ec$resample$MAE)   # =250.072

Q2. What data is used to calculate RMSE, Rsquared, MAE in $resample?

> head(lm.fit.ec$resample)
RMSE Rsquared       MAE intercept    Resample
1  16.33273       NA  16.33273      TRUE Training010
2 232.16184       NA 232.16184      TRUE Training011
3 197.65143       NA 197.65143      TRUE Training012
4 393.29469       NA 393.29469      TRUE Training013
5 129.99157       NA 129.99157      TRUE Training014
6  60.95649       NA  60.95649      TRUE Training015

first_holdout <- subset(lm.fit.ec$pred, Resample == "Training010")
first_holdout

> first_holdout
pred        obs rowIndex intercept    Resample
1 2756.333 2740       11      TRUE Training010  # only 1 row since 1 step forecast horizon

# Calculate RMSE, Rsquared and MAE for the holdout set
postResample(first_holdout$pred, first_holdout$obs)

> postResample(first_holdout$pred, first_holdout$obs)
RMSE     Rsquared      MAE
16.33273       NA     16.33273

My confusion here was mainly caused by the fact that Rsquared was NA. But since the forcast horizon was 1 step all the hold out samples only have one row and thus no Rsquared can be calculated.


问:
string.Format equivalent that doesn't throw exception with extra marker
I want end user of my application to edit format string that is used in string.Format. I want to do that to give user ability to edit templates. Problem occurs when user enters too much markers.

This works fine:

```<code>var result = string.Format("test {0}, {1}, {2}", 1, 2, 3);
</code>```

this works too:

```<code>var result = string.Format("test {0}, {1}", 1, 2, 3);
</code>```

but this throws exception:

```<code>var result = string.Format("test {0}, {1}, {2}", 1, 2);
</code>```

System.FormatException: 'Index (zero based) must be greater than or
  equal to zero and less than the size of the argument list.'

I'm aware that I must add as much parameters as there are markers, but end user don't know that, or he can make mistakes - add extra marker.

My question is:

Can I use similar approach to format string in a way string.Format works but without exception.

I know I could use try\catch block and return format string, but I don't want to do that.

I've build very simple method that replace markers in string:

```<code>public static string SafeFormat(string format, params object[] args)
{
    var result = format;
    for (int i = 0; i < args.Length; i++)
    {
        result = result.Replace($"{{{i}}}", args[i].ToString());
    }
    return result;
}
</code>```

but this isn't supporting formatting of data that is used in place of markers.

Internally string.Format is using AppendFormatHelper (http://referencesource.microsoft.com/#mscorlib/system/text/stringbuilder.cs,2c3b4c2e7c43f5a4) that is more complex than my simple replace.

Ideally string.Format("test {0}, {1}, {2}", 1, 2) should return test 1, 2, {2}

答:
One solution is to check how many values are expected, and just append others to argument list (null or placeholders). Example string extension:

```<code>public static class StringExtensions
{
    public static string SafeFormat(this string value, params object[] args)
    {
        var pattern = @"{(.*?)}";
        var matches = Regex.Matches(value, pattern);
        var matchCount = matches.Count;
        if (matchCount > args.Length)
        {
            var argsExtended = args.ToList();
            for (int i = args.Length; i < matchCount; i++)
            {
                argsExtended.Add($"{{{i}}}"); //Can add null value to erase them
            }
            return string.Format(value, argsExtended.ToArray());
        }
        return string.Format(value, args);
    }
}
</code>```

You can easily change this to method if you want

Body:
I want end user of my application to edit format string that is used in string.Format. I want to do that to give user ability to edit templates. Problem occurs when user enters too much markers.

This works fine:

var result = string.Format("test {0}, {1}, {2}", 1, 2, 3);

this works too:

var result = string.Format("test {0}, {1}", 1, 2, 3);

but this throws exception:

var result = string.Format("test {0}, {1}, {2}", 1, 2);

System.FormatException: 'Index (zero based) must be greater than or
  equal to zero and less than the size of the argument list.'

I'm aware that I must add as much parameters as there are markers, but end user don't know that, or he can make mistakes - add extra marker.

My question is:

Can I use similar approach to format string in a way string.Format works but without exception.

I know I could use try\catch block and return format string, but I don't want to do that.

I've build very simple method that replace markers in string:

public static string SafeFormat(string format, params object[] args)
{
    var result = format;
    for (int i = 0; i < args.Length; i++)
    {
        result = result.Replace($"{{{i}}}", args[i].ToString());
    }
    return result;
}

but this isn't supporting formatting of data that is used in place of markers.

Internally string.Format is using AppendFormatHelper (http://referencesource.microsoft.com/#mscorlib/system/text/stringbuilder.cs,2c3b4c2e7c43f5a4) that is more complex than my simple replace.

Ideally string.Format("test {0}, {1}, {2}", 1, 2) should return test 1, 2, {2}

Body:
One solution is to check how many values are expected, and just append others to argument list (null or placeholders). Example string extension:

public static class StringExtensions
{
    public static string SafeFormat(this string value, params object[] args)
    {
        var pattern = @"{(.*?)}";
        var matches = Regex.Matches(value, pattern);
        var matchCount = matches.Count;
        if (matchCount > args.Length)
        {
            var argsExtended = args.ToList();
            for (int i = args.Length; i < matchCount; i++)
            {
                argsExtended.Add($"{{{i}}}"); //Can add null value to erase them
            }
            return string.Format(value, argsExtended.ToArray());
        }
        return string.Format(value, args);
    }
}

You can easily change this to method if you want


问:
extending the c programming language with gcc
I want to write my own programming language as an extension of the c programming language. The entire programming language that I am inventing are simply shorthands which translate to valid c code. For example:

```<code>namespace TcpConnection {
    void* connect(char *addr)
}
</code>```

would translate to:

```<code>void* TcpConnection_connect(char *addr)
</code>```

All that is done is a simple name replacement. This is only one example of an extension which I want to provide. Another simple extension would be function overloading (this would concatenate to the end of the function name the types of its arguments.

In any case, the result is perfectly valid C code. Is there any way to do this without going into gcc code?

答:
I did something similar to embed an assembly language for a custom bytecode format, using some C99 macro magic and Perl.

The macros

```<code>#define x3_pragma_(...) _Pragma(#__VA_ARGS__)
#define x3_asm(...) ((const struct x3instruction []){ \
    x3_pragma_(X3 ASM __VA_ARGS__) \
})
</code>```

transform

```<code>x3_asm(exit = find val(0))
</code>```

into

```<code>((const struct x3instruction []){
#pragma X3 ASM exit = find val(0)
})
</code>```

which gets piped through a Perl script to get

```<code>((const struct x3instruction []){
{ { { X3_OPFINDVAL, { .as_uint = (0) } }, { X3_OPEXIT, { 0 } } } },
})
</code>```

A sample invocation of gcc and perl would look like this:

```<code>gcc -E foo.c | perl x3pp.pl | gcc -o foo.o -x c -
</code>```

It's more complicated than stricly necessary, but I found it beneficial that the C preprocessor runs before my custom preprocessor, and I also liked that by using pragmas, the source stays legal C.

ContentLicense: CC BY-SA 2.5

Body:
I want to write my own programming language as an extension of the c programming language. The entire programming language that I am inventing are simply shorthands which translate to valid c code. For example:

namespace TcpConnection {
    void* connect(char *addr)
}

would translate to:

void* TcpConnection_connect(char *addr)

All that is done is a simple name replacement. This is only one example of an extension which I want to provide. Another simple extension would be function overloading (this would concatenate to the end of the function name the types of its arguments.

In any case, the result is perfectly valid C code. Is there any way to do this without going into gcc code?

Body:
I did something similar to embed an assembly language for a custom bytecode format, using some C99 macro magic and Perl.

The macros

#define x3_pragma_(...) _Pragma(#__VA_ARGS__)
#define x3_asm(...) ((const struct x3instruction []){ \
    x3_pragma_(X3 ASM __VA_ARGS__) \
})

transform

x3_asm(exit = find val(0))

into

((const struct x3instruction []){
#pragma X3 ASM exit = find val(0)
})

which gets piped through a Perl script to get

((const struct x3instruction []){
{ { { X3_OPFINDVAL, { .as_uint = (0) } }, { X3_OPEXIT, { 0 } } } },
})

A sample invocation of gcc and perl would look like this:

gcc -E foo.c | perl x3pp.pl | gcc -o foo.o -x c -

It's more complicated than stricly necessary, but I found it beneficial that the C preprocessor runs before my custom preprocessor, and I also liked that by using pragmas, the source stays legal C.


问:
Vba code for how to group together numbers which are the 31st character in a string with a row break between consecutive numbers
I'm trying to edit my code so that it groups all of the same numbers in a string together and adds a row break between it and the consecutive number so that it is easier to read. </p>

<p>The number I want is always the 31st character in a string and I want the data to display so that this 31st character is grouped together. Any help would be appreciated, my current code is: </p>

```<code>Sub CopyMatchedValuesToSheet()

Dim ws1 As Worksheet, ws2 As Worksheet
Dim LastRowSource As Long, i As Long
Dim SearchString As String
Dim cell As Range

Set ws1 = Worksheets("effect00001")
Set ws2 = Worksheets("Sheet2")

SearchString = "(9)" ' Set SearchString value or use the one below if you want to change it each time

'SearchString = Application.InputBox("Give a string", "SearchString", Type:=2)

i = 1

With ws1
    LastRowSource = .Cells.find("(9)", [A1], , , xlByRows, xlPrevious).Row

    For Each cell In .Range("A1:A" & LastRowSource) ' Change to A2 if it has header
        If InStr(cell.Value, SearchString) > 0 Then
            ws2.Cells(i + 1, 1).Value = cell.Value
            i = i + 1
        End If
    Next cell
End With

End Sub
</code>```

答:
```<code> Function ChopOutChar(s as string)

 Dim thirtyfirst as string
 thirtyFirst = mid(s,31,1)
 thirtyfirst = thirtyfirst &  vbcrlf ' "Carriage Return/LineFeed"
 ChopOUtChar = thirtyfirst
End Function
</code>```

Body:
I'm trying to edit my code so that it groups all of the same numbers in a string together and adds a row break between it and the consecutive number so that it is easier to read.

The number I want is always the 31st character in a string and I want the data to display so that this 31st character is grouped together. Any help would be appreciated, my current code is:

Sub CopyMatchedValuesToSheet()

Dim ws1 As Worksheet, ws2 As Worksheet
Dim LastRowSource As Long, i As Long
Dim SearchString As String
Dim cell As Range

Set ws1 = Worksheets("effect00001")
Set ws2 = Worksheets("Sheet2")

SearchString = "(9)" ' Set SearchString value or use the one below if you want to change it each time

'SearchString = Application.InputBox("Give a string", "SearchString", Type:=2)

i = 1

With ws1
    LastRowSource = .Cells.find("(9)", [A1], , , xlByRows, xlPrevious).Row

    For Each cell In .Range("A1:A" & LastRowSource) ' Change to A2 if it has header
        If InStr(cell.Value, SearchString) > 0 Then
            ws2.Cells(i + 1, 1).Value = cell.Value
            i = i + 1
        End If
    Next cell
End With

End Sub


问:
What does it mean to call an escaping closure after the function returns?
I was reading the apple developer documentation's definition of escaping closures. It says "a closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns"

I am not sure what the last part is supposed to mean, what does it mean by "after the function returns"? Does it mean "after the function returns a value"?

答:
Take for example a call to an API. This call is going to take time, but we are going to want to do something after the call is completed. For example, say we want to refresh a UITableView with the new data that we pull. If we were to do it immediately, the data wouldn't have been received yet:

```<code>ApiObject.getObjects(completion: { (error, objects) in })
tableView.reloadData()
</code>```

If we were to reload the data here, the table view will refresh immediately (before we actually have received the data). By doing it in the completion block, we are saying, run the code when we have completed the function, not when the function actually returns:

```<code>ApiObject.getObjects(completion: {(error, objects) in
    self.tableView.reloadData()
})
</code>```

Here we are running it once the objects have been fetched, not once the function itself has reached the end.

Edit

Maybe this will make it easier; I have the following code:

```<code>let comeInAnimation = POPBasicAnimation(propertyNamed: kPOPLayoutConstraintConstant)!
comeInAnimation.toValue = 0
comeInAnimation.completionBlock = { (anim, success) -> Void in
    self.loginButton.enabled = true
    self.signupButton.enabled = true
}
signUpContainingViewLeftConstraint.pop_add(comeInAnimation, forKey: AnimationString.EnterExit.identifier)
</code>```

This is using the POP animation framework. In this case, I have a login and signup button, but I also have an animation for them to appear. I dont want the buttons to be clicked while they are appearing so i have their enabled set to false originally. Now you can see they get set to enabled in the completionBlock. This means, when the animation is completed, the completion block gets called and I know now is the time to set them to be enabled. Had I done it like so:

```<code>let comeInAnimation = POPBasicAnimation(propertyNamed: kPOPLayoutConstraintConstant)!
comeInAnimation.toValue = 0
signUpContainingViewLeftConstraint.pop_add(comeInAnimation, forKey: AnimationString.EnterExit.identifier)
self.loginButton.enabled = true
self.signupButton.enabled = true
</code>```

Even though the enabled properties are set after the animation is called, the properties are actually being set before the animation is complete. Because the program runs line by line, the animation gets added and then immediately the properties are set (this is too early).

Note: This is an issue because these functions run asynchronously. That is, it allows the program to keep running while it is doing its thing. If this line of code blocked (stopped the program until it was compete) then putting the code in a completion block and putting it immediately after would be the same thing. In real life though, we dont want to block because it gives the appearance that the program has frozen.

Body:
Take for example a call to an API. This call is going to take time, but we are going to want to do something after the call is completed. For example, say we want to refresh a UITableView with the new data that we pull. If we were to do it immediately, the data wouldn't have been received yet:

ApiObject.getObjects(completion: { (error, objects) in })
tableView.reloadData()

If we were to reload the data here, the table view will refresh immediately (before we actually have received the data). By doing it in the completion block, we are saying, run the code when we have completed the function, not when the function actually returns:

ApiObject.getObjects(completion: {(error, objects) in
    self.tableView.reloadData()
})

Here we are running it once the objects have been fetched, not once the function itself has reached the end.

Edit

Maybe this will make it easier; I have the following code:

let comeInAnimation = POPBasicAnimation(propertyNamed: kPOPLayoutConstraintConstant)!
comeInAnimation.toValue = 0
comeInAnimation.completionBlock = { (anim, success) -> Void in
    self.loginButton.enabled = true
    self.signupButton.enabled = true
}
signUpContainingViewLeftConstraint.pop_add(comeInAnimation, forKey: AnimationString.EnterExit.identifier)

This is using the POP animation framework. In this case, I have a login and signup button, but I also have an animation for them to appear. I dont want the buttons to be clicked while they are appearing so i have their enabled set to false originally. Now you can see they get set to enabled in the completionBlock. This means, when the animation is completed, the completion block gets called and I know now is the time to set them to be enabled. Had I done it like so:

let comeInAnimation = POPBasicAnimation(propertyNamed: kPOPLayoutConstraintConstant)!
comeInAnimation.toValue = 0
signUpContainingViewLeftConstraint.pop_add(comeInAnimation, forKey: AnimationString.EnterExit.identifier)
self.loginButton.enabled = true
self.signupButton.enabled = true

Even though the enabled properties are set after the animation is called, the properties are actually being set before the animation is complete. Because the program runs line by line, the animation gets added and then immediately the properties are set (this is too early).

Note: This is an issue because these functions run asynchronously. That is, it allows the program to keep running while it is doing its thing. If this line of code blocked (stopped the program until it was compete) then putting the code in a completion block and putting it immediately after would be the same thing. In real life though, we dont want to block because it gives the appearance that the program has frozen.


问:
MSACCESS 2010 VBA; Syntax Error in date in query expression
I am creating a simple database for tracking working hours. The idea is that:

Every day you need to input only the days that employee did not work (startDate, endDate, absenceType),

Then calculate working days for the whole month or selected period.

Calculation of working days should take into account weekends (saturday, sunday) and holidays from Holiday table.

I took a function sample from MSDN (Counting the Number of Working Days in Access 2007) and put it into a module in my MS Access 2010 db but each time I run a query I have this error.

Typically the same error appears attempting to run a query in another sample database from somewhere.

The problem is in the strWhere clause:

```<code>strWhere = "[Holiday] >=#" & startDate & "# AND [Holiday] <=#" & endDate & "#"

' Count the number of holidays.
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays
</code>```

The error msg  from both databases is available in the link below

Runtime Error 3075 Syntax error in date in query expression

Any help is appreciated.

答:
You must force a format on the string expressions for your dates. Get used to use the ISO sequence yyyy-mm-dd as it works everywhere:

```<code>strHolidays = "NameOfYourTable"
strWhere = "[Holiday] >= #" & Format(startDate, "yyyy\/mm\/dd") & "# AND [Holiday] <= #" & Format(endDate, "yyyy\/mm\/dd") & "#"

' Count the number of holidays.
nHolidays = DCount("*", strHolidays, strWhere)
</code>```

Body:
I am creating a simple database for tracking working hours. The idea is that:

Every day you need to input only the days that employee did not work (startDate, endDate, absenceType),

Then calculate working days for the whole month or selected period.

Calculation of working days should take into account weekends (saturday, sunday) and holidays from Holiday table.

I took a function sample from MSDN (Counting the Number of Working Days in Access 2007) and put it into a module in my MS Access 2010 db but each time I run a query I have this error.

Typically the same error appears attempting to run a query in another sample database from somewhere.

The problem is in the strWhere clause:

strWhere = "[Holiday] >=#" & startDate & "# AND [Holiday] <=#" & endDate & "#"

' Count the number of holidays.
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays

The error msg  from both databases is available in the link below

Runtime Error 3075 Syntax error in date in query expression

Any help is appreciated.

Body:
You must force a format on the string expressions for your dates. Get used to use the ISO sequence yyyy-mm-dd as it works everywhere:

strHolidays = "NameOfYourTable"
strWhere = "[Holiday] >= #" & Format(startDate, "yyyy\/mm\/dd") & "# AND [Holiday] <= #" & Format(endDate, "yyyy\/mm\/dd") & "#"

' Count the number of holidays.
nHolidays = DCount("*", strHolidays, strWhere)


问:
Are these 2 statements the same?
Do these 2 statements mean the same thing?

```<code>if ($host eq '') {
    print "Host exists\n";
}
</code>```

And

```<code>if (defined $host) {
    print "Host exists\n";
}
</code>```

答:
No.

If $host is "localhost", they'll be different.

Title: Are these 2 statements the same?

Body:
Do these 2 statements mean the same thing?

if ($host eq '') {
    print "Host exists\n";
}

And

if (defined $host) {
    print "Host exists\n";
}


问:
How to use images data from database and display in the my home activity like olx in android?
I want to know how to display the images that has been stored in the database in the home activity in my application.</p>

答:
just store them in regular file system ,create a directory

```<code>File file=new File(getabsolutepath()+"/image/")
</code>```

this path doesn't change so just  store the image name in a database.

you can also store images in database using blob https://en.wikipedia.org/wiki/Binary_large_object

but it is not a good practice

Body:
just store them in regular file system ,create a directory

File file=new File(getabsolutepath()+"/image/")

this path doesn't change so just  store the image name in a database.

you can also store images in database using blob https://en.wikipedia.org/wiki/Binary_large_object

but it is not a good practice


问:
Django Cannot Be Accessed From Localhost
It's kinda weird I cannot access django from localhost but I able to access it from local IP.

```<code>python manage.py runserver 0.0.0.0:8000
</code>```

then when I try to access from

My host file

```<code>127.0.0.1 lmlicenses.wip4.adobe.com
127.0.0.1 lm.licenses.adobe.com
127.0.0.1 gc.kis.scr.kaspersky-labs.com ff.kis.scr.kaspersky-labs.com ie.kis.scr.kaspersky-labs.com
0.0.0.0 gc.kis.scr.kaspersky-labs.com ff.kis.scr.kaspersky-labs.com ie.kis.scr.kaspersky-labs.com
</code>```

I'm guessing something wrong with windows firewall or kaspersky,but I don't know what to do.

I've add exception to port 8000 and python.exe too

答:
In the settings.py file in your project folder,
add '0.0.0.0' to the allowed host list.
Then save the file and run the command.Guess will work.

Body:
It's kinda weird I cannot access django from localhost but I able to access it from local IP.

python manage.py runserver 0.0.0.0:8000

then when I try to access from

My host file

127.0.0.1 lmlicenses.wip4.adobe.com
127.0.0.1 lm.licenses.adobe.com
127.0.0.1 gc.kis.scr.kaspersky-labs.com ff.kis.scr.kaspersky-labs.com ie.kis.scr.kaspersky-labs.com
0.0.0.0 gc.kis.scr.kaspersky-labs.com ff.kis.scr.kaspersky-labs.com ie.kis.scr.kaspersky-labs.com

I'm guessing something wrong with windows firewall or kaspersky,but I don't know what to do.

I've add exception to port 8000 and python.exe too


问:
How to edit application configuration settings? App.config best way to go?
For my project I have settings that I added through the Settings in the project properties.

I quickly discovered that editing the app.config file directly seems to no really update the settings value.  Seems I have to view the project properties when I make a change and then recompile.

I'm wondering ... what is the best
and easiest way to handle customizable settings
for a project -- thought this would
be a no-brainer with how .Net
handles it ... shame on me.

Is it possible to use one of the
settings, AppSettings,
ApplicationSettings, or UserSettings to handle this?

Is it better to just write my settings to custom config file and handle things myself?

Right now ... I am looking for the quickest solution!

My environment is C#, .Net 3.5 and Visual Studio 2008.

Update

I am trying to do the following:

```<code>    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }
</code>```

Gives me a read-only error when I compile.

答:
Not sure if this is what you are after, but you can update and save the setting from the app:

ConsoleApplication1.Properties.Settings.Default.StringSetting = "test";
ConsoleApplication1.Properties.Settings.Default.Save();

OwnerDisplayName: MattRuma

Body:
For my project I have settings that I added through the Settings in the project properties.

I quickly discovered that editing the app.config file directly seems to no really update the settings value.  Seems I have to view the project properties when I make a change and then recompile.

I'm wondering ... what is the best
and easiest way to handle customizable settings
for a project -- thought this would
be a no-brainer with how .Net
handles it ... shame on me.

Is it possible to use one of the
settings, AppSettings,
ApplicationSettings, or UserSettings to handle this?

Is it better to just write my settings to custom config file and handle things myself?

Right now ... I am looking for the quickest solution!

My environment is C#, .Net 3.5 and Visual Studio 2008.

Update

I am trying to do the following:

    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }

Gives me a read-only error when I compile.

LastEditorDisplayName: MattRuma

OwnerDisplayName: Fredrik Jansson


问:
Add a new row with data to an existing repeater in ACF
i am trying to add a new row with data to an existing repeater in acf.There is no error but this code unable to insert data in database.
this is what i have tried

```<code>$row = array(
    'vacation_from_date'    => '20/10/2017',
    'vacation_to_date'  => '25/10/2017',
);
$field = get_field_object('vacations','user_' . $user_id);
add_row($field['key'], $row);
</code>```

here is my screenshot for wp-admin

答:
Should it not be

```<code>add_row('vacations', $row, $post_id);
</code>```

Or is there a reason you are using

```<code>get_field_object()
</code>```

Body:
i am trying to add a new row with data to an existing repeater in acf.There is no error but this code unable to insert data in database.
this is what i have tried

$row = array(
    'vacation_from_date'    => '20/10/2017',
    'vacation_to_date'  => '25/10/2017',
);
$field = get_field_object('vacations','user_' . $user_id);
add_row($field['key'], $row);

here is my screenshot for wp-admin

Body:
Should it not be

add_row('vacations', $row, $post_id);

Or is there a reason you are using

get_field_object()