问:
WinForms on Tabpage selected run method in UserControl
My Tabcontrol has 3 Tabpages. I am currently in Tabpage 1, when I would select Tabpage 2. I want to run a method in my UserControl assigned to that Tabpage. You could call this a "Focus" listener. How would I implement this? Or is this possible at all?

Edit:

Lets say I have a file named "UserControl1.cs" In here there is a method OnFocus() I would like to call this method when its Tabpage becomes the active tab. I am assigning the UserControl to the Tabpage like this:

```<code>        // AllOpenUserControls = List<UserControl> // With the active pages

        TabPage newPage = new TabPage();
        newPage.Text = title;
        newPage.AutoScroll = true;
        newPage.BackColor = SystemColors.Window;
        newPage.Controls.Add(userControl);
        AllOpenUserControls.Add(userControl);

        tabControl.TabPages.Add(newPage);
</code>```

答:
Add the EventHandler for SelectedIndexChanged here:

```<code>...
tabControl.TabPages.Add(newPage);
tabControl.SelectedIndexChanged += new EventHandler(userControl.OnFocus);
</code>```

Your OnFocus-method should look like this:

```<code>public void OnFocus(object sender, System.EventArgs e)
{
    TabControl tc = (TabControl)sender;
    if (tc.SelectedTab == this.Parent)
    {
        //Parent-Tab is selected, do stuff...
    }
}
</code>```

Body:
My Tabcontrol has 3 Tabpages. I am currently in Tabpage 1, when I would select Tabpage 2. I want to run a method in my UserControl assigned to that Tabpage. You could call this a "Focus" listener. How would I implement this? Or is this possible at all?

Edit:

Lets say I have a file named "UserControl1.cs" In here there is a method OnFocus() I would like to call this method when its Tabpage becomes the active tab. I am assigning the UserControl to the Tabpage like this:

        // AllOpenUserControls = List<UserControl> // With the active pages

        TabPage newPage = new TabPage();
        newPage.Text = title;
        newPage.AutoScroll = true;
        newPage.BackColor = SystemColors.Window;
        newPage.Controls.Add(userControl);
        AllOpenUserControls.Add(userControl);

        tabControl.TabPages.Add(newPage);

Body:
Add the EventHandler for SelectedIndexChanged here:

...
tabControl.TabPages.Add(newPage);
tabControl.SelectedIndexChanged += new EventHandler(userControl.OnFocus);

Your OnFocus-method should look like this:

public void OnFocus(object sender, System.EventArgs e)
{
    TabControl tc = (TabControl)sender;
    if (tc.SelectedTab == this.Parent)
    {
        //Parent-Tab is selected, do stuff...
    }
}


来源: stackexchange

问:
How do I create a project in WebStorm for Node.js?
I have created a project in WebStorm by watching a tutorial Node.js + Express - Tutorial - Insert and Get Data with MongoDB (check from 1:49 to 1:53 (I get error when I run www.js))

when i run localhost:8000, im able to insert the data,but i am not able to get the data,i get the below error

GET / 200 44.467 ms - 1968 GET /stylesheets/style.css 200 27.109 ms -
  962 GET /favicon.ico 404 6.245 ms - 199 POST /insert 302 245.066 ms -
  46 GET / 304 5.643 ms - - GET /stylesheets/style.css 304 1.362 ms - -
  C:\Users\ptech-user\WebstormProjects\aishuuu\node_modules\mongodb\lib\mongo_client.js:421
            throw err
            ^

AssertionError [ERR_ASSERTION]: null == 'MongoError: failed to connect
  to server [localhost:27017] on first connect [MongoError: connect
  ECONNREFUSED 127.0.0.1:27017]'
      at C:\Users\ptech-user\WebstormProjects\aishuuu\routes\index.js:37:12
      at connectCallback (C:\Users\ptech-user\WebstormProjects\aishuuu\node_modules\mongodb\lib\mongo_client.js:515:5)
      at C:\Users\ptech-user\WebstormProjects\aishuuu\node_modules\mongodb\lib\mongo_client.js:418:11
      at _combinedTickCallback (internal/process/next_tick.js:131:7)
      at process._tickCallback (internal/process/next_tick.js:180:9)

GitHub link for source code

How to solve this?

im not able to get the data

答:
You do not have and 'http://' module instead of this you have 'http'.
Edit the require statement in the following way

Incorrect

```<code>var http=require('http://');
</code>```

Correct

```<code>var http=require('http');
</code>```

For a better understanding of what you do take a more in-depth tutorial about Node.Js and how it works.
Resource:
https://www.guru99.com/node-js-tutorial.html

ContentLicense: CC BY-SA 3.0

Body:
You do not have and 'http://' module instead of this you have 'http'.
Edit the require statement in the following way

Incorrect

var http=require('http://');

Correct

var http=require('http');

For a better understanding of what you do take a more in-depth tutorial about Node.Js and how it works.
Resource:
https://www.guru99.com/node-js-tutorial.html


问:
Session 'app': Error Launching activity
After the Android Studio 2.0 update while the gradle build  finishes I get this :

Session 'app': Error Launching activity .

It prevents the app from starting but it's installed in my emulator.
This is what comes up in the Run tab :

Unexpected error while executing: am start -n "com.example.user.ypologismosmoriwn/com.example.user.ypologismosmoriwn.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Error while Launching activity

Here is the code:

```<code>package com.example.user.ypologismosmoriwn;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

It's just an empty Activity,nothing added

and the XML code is just a Relative Layout with 4 Texts and 3 Check Boxes

This is the logcat i am getting

Thanks anyone who is willing to help

答: Try reinstalling the app, this solved the error for me. The trick was that, I uninstalled my app, but Android didn't truly uninstall it. On my phone, there is a guest user (my sister uses it sometimes). If you uninstall the app from your main user, it will still be available on the phone, but only for the guest user. It looks like Android Studio can't handle this case. I guess it detects that the app is installed, so it will not be reinstalled again for the current user, hence the OS can't access and launch the activity. Nice bug, I'll report it.</p>

Title: Session 'app': Error Launching activity

Body:
After the Android Studio 2.0 update while the gradle build  finishes I get this :

Session 'app': Error Launching activity .

It prevents the app from starting but it's installed in my emulator.
This is what comes up in the Run tab :

Unexpected error while executing: am start -n "com.example.user.ypologismosmoriwn/com.example.user.ypologismosmoriwn.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Error while Launching activity

Here is the code:

package com.example.user.ypologismosmoriwn;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

It's just an empty Activity,nothing added

and the XML code is just a Relative Layout with 4 Texts and 3 Check Boxes

This is the logcat i am getting

Thanks anyone who is willing to help


问:
VideoView disappearing while scrolling/swiping in VerticalViewPager
I am having an issue with VideoView when using with VerticalViewPager.

When I scroll/swipe the ViewPager the VideoView becomes black. Actually here VideoView is getting disappeared the black color is the background of the ViewPager.

I don't have this issue when using horizontal ViewPager even with current custom VerticalViewpager set to horizontal.
When I scroll, VideoView disappears and when I lift my finger from screen VideoView appears back again.

I have tried many VerticalViewpager libraries and almost all of them have this same issue.

Have anyone faced this issue before? How to fix this?

These are the screenshots:

VideoView when not swiping:

VideoView when swiping vertically:

Here is my code

VerticalViewpager.java

```<code>import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class VerticalViewpager extends ViewPager {
    public VerticalViewpager(Context context) {
        super(context);
        init();
    }

    public VerticalViewpager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // The majority of the magic happens here
        setPageTransformer(true, new VerticalPageTransformer());
        // The easiest way to get rid of the overscroll drawing that happens on the left and right
        setOverScrollMode(OVER_SCROLL_NEVER);
    }

    private class VerticalPageTransformer implements ViewPager.PageTransformer {

        @Override
        public void transformPage(View view, float position) {

            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);

            } else if (position <= 1) { // [-1,1]
                view.setAlpha(1);

                // Counteract the default slide transition
                view.setTranslationX(view.getWidth() * -position);

                //set Y position to swipe in from top
                float yPosition = position * view.getHeight();
                view.setTranslationY(yPosition);

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
            }
        }
    }

    /**
     * Swaps the X and Y coordinates of your touch event.
     */
    private MotionEvent swapXY(MotionEvent ev) {
        float width = getWidth();
        float height = getHeight();

        float newX = (ev.getY() / height) * width;
        float newY = (ev.getX() / width) * height;

        ev.setLocation(newX, newY);

        return ev;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev){
        boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
        swapXY(ev); // return touch coordinates to original reference frame for any child views
        return intercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return super.onTouchEvent(swapXY(ev));
    }
}
</code>```

MainActivity.java

```<code>import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    MyPagerAdapter adapterViewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        VerticalViewpager vpPager = (VerticalViewpager) findViewById(R.id.vpPAger);
        adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
        vpPager.setAdapter(adapterViewPager);

        for (int i = 0; i < 2; i++) {
            adapterViewPager.addFragment(FragmentWithOneImage.newInstance("Frag "+ i,R.drawable.jackie));
        }

        vpPager.setAdapter(adapterViewPager);
    }

    public static class MyPagerAdapter extends FragmentStatePagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();

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

        public void addFragment(Fragment fragment) {
            mFragments.add(fragment);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public float getPageWidth(int position) {
            return super.getPageWidth(position);
        }
    }
}
</code>```

FragmentWithOneImage.java

```<code>import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.VideoView;

public class FragmentWithOneImage extends Fragment {
    private String title;
    private int image;

    public static FragmentWithOneImage newInstance(String title, int resImage) {
        FragmentWithOneImage fragment = new FragmentWithOneImage();
        Bundle args = new Bundle();
        args.putInt("image", resImage);
        args.putString("title", title);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        image = getArguments().getInt("image", 0);
        title = getArguments().getString("title");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one_img, container, false);

        ImageView imageView = (ImageView) view.findViewById(R.id.imgMain);
        imageView.setImageResource(image);

        Uri uri = Uri.parse("http://abhiandroid-8fb4.kxcdn.com/ui/wp-content/uploads/2016/04/videoviewtestingvideo.mp4");
        VideoView simpleVideoView = (VideoView) view.findViewById(R.id.simpleVideoView); // initiate a video view
        simpleVideoView.setVideoURI(uri);
        simpleVideoView.start();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }
}
</code>```

activiy_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.example.sudheeshm.verticalviewpager.VerticalViewpager
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/vpPAger"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:swipe_orientation="vertical"
        android:background="@android:color/black"/>

</LinearLayout>
</code>```

fragment_one_img.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    >

    <VideoView
        android:id="@+id/simpleVideoView"
        android:layout_width="match_parent"
        android:layout_height="300dp" />
    <ImageView
        android:layout_below="@+id/simpleVideoView"
        android:id="@+id/imgMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
</code>```

attrs.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="VerticalViewpager" >
        <attr name="swipe_orientation" format="enum" >
            <enum name="horizontal" value="0" />
            <enum name="vertical" value="1" />
        </attr>
    </declare-styleable>
</resources>
</code>```

答:
It has to do with VideoView being based on SurfaceView and this view is not optimized for tranlations (scrolling in a ViewPager). Check out these answers related to VideoViews in a ViewPager at these following links: post 1, 2.

Maybe you can find a solution to your issue.

Body:
I am having an issue with VideoView when using with VerticalViewPager.

When I scroll/swipe the ViewPager the VideoView becomes black. Actually here VideoView is getting disappeared the black color is the background of the ViewPager.

I don't have this issue when using horizontal ViewPager even with current custom VerticalViewpager set to horizontal.
When I scroll, VideoView disappears and when I lift my finger from screen VideoView appears back again.

I have tried many VerticalViewpager libraries and almost all of them have this same issue.

Have anyone faced this issue before? How to fix this?

These are the screenshots:

VideoView when not swiping:

VideoView when swiping vertically:

Here is my code

VerticalViewpager.java

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class VerticalViewpager extends ViewPager {
    public VerticalViewpager(Context context) {
        super(context);
        init();
    }

    public VerticalViewpager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // The majority of the magic happens here
        setPageTransformer(true, new VerticalPageTransformer());
        // The easiest way to get rid of the overscroll drawing that happens on the left and right
        setOverScrollMode(OVER_SCROLL_NEVER);
    }

    private class VerticalPageTransformer implements ViewPager.PageTransformer {

        @Override
        public void transformPage(View view, float position) {

            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);

            } else if (position <= 1) { // [-1,1]
                view.setAlpha(1);

                // Counteract the default slide transition
                view.setTranslationX(view.getWidth() * -position);

                //set Y position to swipe in from top
                float yPosition = position * view.getHeight();
                view.setTranslationY(yPosition);

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
            }
        }
    }

    /**
     * Swaps the X and Y coordinates of your touch event.
     */
    private MotionEvent swapXY(MotionEvent ev) {
        float width = getWidth();
        float height = getHeight();

        float newX = (ev.getY() / height) * width;
        float newY = (ev.getX() / width) * height;

        ev.setLocation(newX, newY);

        return ev;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev){
        boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
        swapXY(ev); // return touch coordinates to original reference frame for any child views
        return intercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return super.onTouchEvent(swapXY(ev));
    }
}

MainActivity.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    MyPagerAdapter adapterViewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        VerticalViewpager vpPager = (VerticalViewpager) findViewById(R.id.vpPAger);
        adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
        vpPager.setAdapter(adapterViewPager);

        for (int i = 0; i < 2; i++) {
            adapterViewPager.addFragment(FragmentWithOneImage.newInstance("Frag "+ i,R.drawable.jackie));
        }

        vpPager.setAdapter(adapterViewPager);
    }

    public static class MyPagerAdapter extends FragmentStatePagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();

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

        public void addFragment(Fragment fragment) {
            mFragments.add(fragment);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public float getPageWidth(int position) {
            return super.getPageWidth(position);
        }
    }
}

FragmentWithOneImage.java

import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.VideoView;

public class FragmentWithOneImage extends Fragment {
    private String title;
    private int image;

    public static FragmentWithOneImage newInstance(String title, int resImage) {
        FragmentWithOneImage fragment = new FragmentWithOneImage();
        Bundle args = new Bundle();
        args.putInt("image", resImage);
        args.putString("title", title);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        image = getArguments().getInt("image", 0);
        title = getArguments().getString("title");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one_img, container, false);

        ImageView imageView = (ImageView) view.findViewById(R.id.imgMain);
        imageView.setImageResource(image);

        Uri uri = Uri.parse("http://abhiandroid-8fb4.kxcdn.com/ui/wp-content/uploads/2016/04/videoviewtestingvideo.mp4");
        VideoView simpleVideoView = (VideoView) view.findViewById(R.id.simpleVideoView); // initiate a video view
        simpleVideoView.setVideoURI(uri);
        simpleVideoView.start();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }
}

activiy_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.example.sudheeshm.verticalviewpager.VerticalViewpager
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/vpPAger"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:swipe_orientation="vertical"
        android:background="@android:color/black"/>

</LinearLayout>

fragment_one_img.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    >

    <VideoView
        android:id="@+id/simpleVideoView"
        android:layout_width="match_parent"
        android:layout_height="300dp" />
    <ImageView
        android:layout_below="@+id/simpleVideoView"
        android:id="@+id/imgMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="VerticalViewpager" >
        <attr name="swipe_orientation" format="enum" >
            <enum name="horizontal" value="0" />
            <enum name="vertical" value="1" />
        </attr>
    </declare-styleable>
</resources>


问:
AWS s3 mv command deletes the source directory
The objective is to move all the files from s3 "dir2" directory to EMR directory "mydir".

I am using the command:

aws s3 mv s3:///dir1/dir2/ /mnt/mydir/ --recursive

This command gets executed but the dir2 directory from s3 gets deleted.
The files within dir2 although moves to mydir of EMR.

How can I only move the files from source dir of s3 without removing the source directory?

答:
When dealing with multiple objects, you want to use sync not cp or mv:

```<code>aws s3 sync s3:///dir1/dir2/ /mnt/mydir/
</code>```

There are ways to load data into EMR directly from S3, so you may want to look into those.

Update: I have confirmed that:

```<code>aws s3 mv s3://bucket/f1/f2 . --recursive
</code>```

Will move all of the files inside f2/ while leaving f2 in the bucket.

Body:
When dealing with multiple objects, you want to use sync not cp or mv:

aws s3 sync s3:///dir1/dir2/ /mnt/mydir/

There are ways to load data into EMR directly from S3, so you may want to look into those.

Update: I have confirmed that:

aws s3 mv s3://bucket/f1/f2 . --recursive

Will move all of the files inside f2/ while leaving f2 in the bucket.


问:
Bind an array to placeholder in Oralce SQL developer
In SQL Developer when I want to provide a list of values to a single placeholder SQL developer reads them as one value.
e.g

```<code>select *  from some_table where some_value in (:list_of_values);
</code>```

When I enter 1,2,3 into the Value text box it oracle reads all 1,2,3 as one
 value

答:
Note: this is an answer to the original version of the question which has been significantly changed by edits.

What do I need to put in the text box below ?

There is nothing that you can put into the text box to generate multiple columns when you are using a bind variable since a bind variable represents a single value.

If you change your query to use a substitution variable:

```<code>select &ary from dual;
</code>```

Then you can enter 1,2,3 in the dialog box and you will get the output:

```<code>1 2 3
- - -
1 2 3
</code>```

Body:
In SQL Developer when I want to provide a list of values to a single placeholder SQL developer reads them as one value.
e.g

select *  from some_table where some_value in (:list_of_values);

When I enter 1,2,3 into the Value text box it oracle reads all 1,2,3 as one
 value

Body:
Note: this is an answer to the original version of the question which has been significantly changed by edits.

What do I need to put in the text box below ?

There is nothing that you can put into the text box to generate multiple columns when you are using a bind variable since a bind variable represents a single value.

If you change your query to use a substitution variable:

select &ary from dual;

Then you can enter 1,2,3 in the dialog box and you will get the output:

1 2 3
- - -
1 2 3


问:
How do I get the name of a test being run from within a setup or teardown callback?
I'd like to add performance warnings to our tests, like so:

```<code># in test_helper.rb
class ActiveSupport::TestCase
  def record_test_start_time
    @test_start_time = Time.now
  end
  setup :record_test_start_time

  def warn_long_running_test
    running_time = Time.now - @test_start_time
    if running_time > 10.seconds
      puts "WARNING: Test #{test_name} ran for #{running_time}"
    end
  end
  setup :record_test_start_time
end
</code>```

How do I get the test name into the test_name variable?  I've had poor results using Kernel#caller from setup/teardown callbacks in the past.

答: The name method gives you a string "method name(class name)" and I think @method_name gives you the name of the current test.

ContentLicense: CC BY-SA 2.5

Body:
I'd like to add performance warnings to our tests, like so:

# in test_helper.rb
class ActiveSupport::TestCase
  def record_test_start_time
    @test_start_time = Time.now
  end
  setup :record_test_start_time

  def warn_long_running_test
    running_time = Time.now - @test_start_time
    if running_time > 10.seconds
      puts "WARNING: Test #{test_name} ran for #{running_time}"
    end
  end
  setup :record_test_start_time
end

How do I get the test name into the test_name variable?  I've had poor results using Kernel#caller from setup/teardown callbacks in the past.


问:
Can I delete /var/log/btmp and /var/log/auth.log files?
I am using a CentOS server with password protected SSH connection.

Recently my server ran out of memory, I looked at the largest files and saw this

```<code>du -a /var/log | sort -n -r | head -n 10
16511636        /var/log
11348496        /var/log/upstart
11348372        /var/log/upstart/docker.log
3370656 /var/log/btmp
1739268 /var/log/auth.log
41688   /var/log/mail.log
10256   /var/log/syslog
512     /var/log/wtmp
244     /var/log/dpkg.log
172     /var/log/apt
</code>```

Look at /var/log/btmp (over 3GB) and /var/log/auth.log (over 1.7GB).

I have a thousands of users daily on that website/server.

Can I delete those files? is it safe?

答:
You are better off just slicking them with something like</p>

```<code>cat /dev/null > /var/log/btmp
cat /dev/null > /var/log/auth.log
</code>```

Body:
I am using a CentOS server with password protected SSH connection.

Recently my server ran out of memory, I looked at the largest files and saw this

du -a /var/log | sort -n -r | head -n 10
16511636        /var/log
11348496        /var/log/upstart
11348372        /var/log/upstart/docker.log
3370656 /var/log/btmp
1739268 /var/log/auth.log
41688   /var/log/mail.log
10256   /var/log/syslog
512     /var/log/wtmp
244     /var/log/dpkg.log
172     /var/log/apt

Look at /var/log/btmp (over 3GB) and /var/log/auth.log (over 1.7GB).

I have a thousands of users daily on that website/server.

Can I delete those files? is it safe?

Body:
You are better off just slicking them with something like

cat /dev/null > /var/log/btmp
cat /dev/null > /var/log/auth.log


问:
Most performant way to filter a huge List in C#?
We have an ASP.NET MVC web application that is hooked up to a SQL Server DB via Entity Framework. One of the main tasks of this application is to allow users to quickly search and filter a huge database table that holds archive values.

The table structure is quite simple: Timestamp (DateTime), StationId (int), DatapointId (int), Value (double). This table holds somewhat between 10 to 100 million rows. I optimized the DB table with a covering index etc., but the user experience was still quite laggy when filtering by DatapointId, StationId, Time and Skipping and Taking only the portion I want to show on the page.

So I tried a different approach: as our server has a lot of RAM, I thought that we could simply load the whole archive table into a List<ArchiveRow> when the web app starts up, then simply get the data directly from this List instead of doing a round-trip to the database. This works quite well, it takes about 9 seconds to load the whole archive table (with currently about 10 million entries) into the List. The ArchiveRow is a simple object that looks like this:

```<code>public class ArchiveResponse {
    public  int Length { get; set; }
    public int numShown { get; set; }
    public  int numFound { get; set; }
    public  int numTotal { get; set; }
    public  List<ArchiveRow> Rows { get; set; }
}
</code>```

and accordingly:

```<code>public class ArchiveRow {
    public  int s { get; set; }
    public  int d { get; set; }
    public  DateTime t { get; set; }
    public  double v { get; set; }
}
</code>```

When I now try to get the desired data from the List with a Linq query, it is already faster the querying the DB, but it is still quite slow when filtering by multiple criteria. For example, when I filter by one StationId and 12 DatapointIds, it takes about 5 seconds to retrieve a window of 25 rows. I already switched from filtering with Where to using joins, but I think there is still room for improvement. Are there maybe better ways to implement such a caching mechanism while keeping memory consumption as low as possible? Are there other collection types that are better suited for this purpose?

So here is the code that filters and fetches the relevant data from the ArchiveCache list:

```<code>// Total number of entries in archive cache
var numTotal = ArchiveCache.Count();

// Initial Linq query
ParallelQuery<ArchiveCacheValue> query = ArchiveCache.AsParallel();

// The request may contain StationIds that the user is interested in,
// so here's the filtering by StationIds with a join:
if (request.StationIds.Count > 0)
{
    query = from a in ArchiveCache.AsParallel()
             join b in request.StationIds.AsParallel()
             on a.StationId equals b
             select a;
}

// The request may contain DatapointIds that the user is interested in,
// so here's the filtering by DatapointIds with a join:
if (request.DatapointIds.Count > 0)
{
    query = from a in query.AsParallel()
             join b in request.DatapointIds.AsParallel()
             on a.DataPointId equals b
             select a;
}

// Number of matching entries after filtering and before windowing
int numFound = query.Count();

// Pagination: Select only the current window that needs to be shown on the page
var result = query.Skip(request.Start == 0 ? 0 : request.Start - 1).Take(request.Length);

// Number of entries on the current page that will be shown
int numShown = result.Count();

// Build a response object, serialize it to Json and return to client
// Note: The projection with the Rows is not a bottleneck, it is only done to
// shorten 'StationId' to 's' etc. At this point there are only 25 to 50 rows,
// so that is no problem and happens in way less than 1 ms
ArchiveResponse myResponse = new ArchiveResponse();
myResponse.Length = request.Length;
myResponse.numShown = numShown;
myResponse.numFound = numFound;
myResponse.numTotal = numTotal;
myResponse.Rows = result.Select(x => new archRow() { s = x.StationId, d = x.DataPointId, t = x.DateValue, v = x.Value }).ToList();

return JsonSerializer.ToJsonString(myResponse);
</code>```

Some more details: the number of stations is usually something between 5 to 50, rarely more than 50. The number of datapoints is <7000. The web application is set to 64 bit with <gcAllowVeryLargeObjects enabled="true" /> set in the web.config.

I'm really looking forward for further improvements and recommendations. Maybe there's a completely different approach based on arrays or similar, that performs way better without linq?

答:
I would at least store those values in an array or vector of struct ArchiveRow to make sure all data is in contiguous memory. This way you will greatly benefit from locality of reference (i.e. use the L1 cache efficiently). And you also avoid the overhead of a list (pointers/references). (Update: I did a quick lookup of C# List. Looks like List is the same as C++ vector (i.e. an array), and C# LinkedList is the same as C++ list.. a bit confusing - iow, no pointer overhead here for the C# List<>)

Try to make the struct as small as possible. Use uint32 or even uint16 where possible, maybe 32 bit for the datetime and maybe even float instead of double (depending on your values). Also put the widest values first in your struct (for better alignment).

Even the brute force approach (scanning the whole array, a few 100MB of contiguous memory) should finish in well under 1 second.

To optimize further you can sort the data (or better, retrieve it sorted from the database) which will allow you to do a binary search, and also keep the values for the resultset close together. For example: sort on StationId, DataPointId.

If the data gets bigger, you could store the same structure on disk (in a binary file) and access it via memory mapping.

Also, you only have to scan for the first 25 items. You could then store the last checked position (for that session / query), and when the next page is asked, start from there for the next 25 items. This will also save on memory which would be needed to store the full resultset.

If the number of stations is small, and the data is sorted on StationId, you could also keep a small list or jump table (while importing) with the starting position of each StationId and directly jump to there to scan for datapoints of that station.

it takes about 9 seconds to load the whole archive table (with
  currently about 10 million entries) into the List.

Just in case you didn't do this already, make sure to set an initial Capacity on the list to avoid multiple reallocations.

Body:
We have an ASP.NET MVC web application that is hooked up to a SQL Server DB via Entity Framework. One of the main tasks of this application is to allow users to quickly search and filter a huge database table that holds archive values.

The table structure is quite simple: Timestamp (DateTime), StationId (int), DatapointId (int), Value (double). This table holds somewhat between 10 to 100 million rows. I optimized the DB table with a covering index etc., but the user experience was still quite laggy when filtering by DatapointId, StationId, Time and Skipping and Taking only the portion I want to show on the page.

So I tried a different approach: as our server has a lot of RAM, I thought that we could simply load the whole archive table into a List<ArchiveRow> when the web app starts up, then simply get the data directly from this List instead of doing a round-trip to the database. This works quite well, it takes about 9 seconds to load the whole archive table (with currently about 10 million entries) into the List. The ArchiveRow is a simple object that looks like this:

public class ArchiveResponse {
    public  int Length { get; set; }
    public int numShown { get; set; }
    public  int numFound { get; set; }
    public  int numTotal { get; set; }
    public  List<ArchiveRow> Rows { get; set; }
}

and accordingly:

public class ArchiveRow {
    public  int s { get; set; }
    public  int d { get; set; }
    public  DateTime t { get; set; }
    public  double v { get; set; }
}

When I now try to get the desired data from the List with a Linq query, it is already faster the querying the DB, but it is still quite slow when filtering by multiple criteria. For example, when I filter by one StationId and 12 DatapointIds, it takes about 5 seconds to retrieve a window of 25 rows. I already switched from filtering with Where to using joins, but I think there is still room for improvement. Are there maybe better ways to implement such a caching mechanism while keeping memory consumption as low as possible? Are there other collection types that are better suited for this purpose?

So here is the code that filters and fetches the relevant data from the ArchiveCache list:

// Total number of entries in archive cache
var numTotal = ArchiveCache.Count();

// Initial Linq query
ParallelQuery<ArchiveCacheValue> query = ArchiveCache.AsParallel();

// The request may contain StationIds that the user is interested in,
// so here's the filtering by StationIds with a join:
if (request.StationIds.Count > 0)
{
    query = from a in ArchiveCache.AsParallel()
             join b in request.StationIds.AsParallel()
             on a.StationId equals b
             select a;
}

// The request may contain DatapointIds that the user is interested in,
// so here's the filtering by DatapointIds with a join:
if (request.DatapointIds.Count > 0)
{
    query = from a in query.AsParallel()
             join b in request.DatapointIds.AsParallel()
             on a.DataPointId equals b
             select a;
}

// Number of matching entries after filtering and before windowing
int numFound = query.Count();

// Pagination: Select only the current window that needs to be shown on the page
var result = query.Skip(request.Start == 0 ? 0 : request.Start - 1).Take(request.Length);

// Number of entries on the current page that will be shown
int numShown = result.Count();

// Build a response object, serialize it to Json and return to client
// Note: The projection with the Rows is not a bottleneck, it is only done to
// shorten 'StationId' to 's' etc. At this point there are only 25 to 50 rows,
// so that is no problem and happens in way less than 1 ms
ArchiveResponse myResponse = new ArchiveResponse();
myResponse.Length = request.Length;
myResponse.numShown = numShown;
myResponse.numFound = numFound;
myResponse.numTotal = numTotal;
myResponse.Rows = result.Select(x => new archRow() { s = x.StationId, d = x.DataPointId, t = x.DateValue, v = x.Value }).ToList();

return JsonSerializer.ToJsonString(myResponse);

Some more details: the number of stations is usually something between 5 to 50, rarely more than 50. The number of datapoints is <7000. The web application is set to 64 bit with <gcAllowVeryLargeObjects enabled="true" /> set in the web.config.

I'm really looking forward for further improvements and recommendations. Maybe there's a completely different approach based on arrays or similar, that performs way better without linq?


问:
Ionic3/Angular4: Two-way databinding stops working after click event on Google-Maps
I am using Ionic 3 and I am using the Google Maps plugin for it. I have two pages, a list and a map. I display the same objects on both views and when you click a list entry or a marker (info window), the object's detail page will be opened where you can rate the selected object.

Anyway, when I open the detail page via the list, everything works fine but when I open the detail page via the map-marker, the two-way data binding stops working. In the code below you can find the <rating-input> component in the rating dialog. That's the code that's not working.

I've tried using a simple input text to find out if it's really the two way data binding or if it's my component. The data binding did not work either using the simple textbox.

Here is the code:

```<code> //adding the markers to the map and adding the clicklisteners
 putMarkersForMarkets(markets: Christmasmarket[]) {

markets.forEach(market => {
  let isOpen = this.openinghoursService.isOpenAt(market, new Date());
  this.map.addMarker({
    title: market.name,
    icon: isOpen ? 'green' : 'red',
    animation: 'DROP',
    position: {
      lat: market.position.latitude,
      lng: market.position.longitude
    }
  }).then(marker => {
    marker.on(GoogleMapsEvent.INFO_CLICK)
      .subscribe(() => {
        this.onClickMarket(market);
      });
  });;

});

}

onClickMarket(market: Christmasmarket) {
       this.map.setVisible(false);
       this.map.setClickable(false);
     this.app.getRootNav().push(MarketDetailPage, { data: market });
   }
</code>```

Rating-Popup html:

```<code><ion-header>
  <ion-navbar color="primary">
    <ion-title>{{'RATINGDIALOG.TITLE' | translate}}</ion-title>
    <ion-buttons end>
      <button ion-button icon-only (click)="dismiss()">
      <ion-icon name="close"></ion-icon>
    </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <form #form="ngForm">
    <b>{{'RATINGDIALOG.HEADERMARKET' | translate}}</b><br>
    <rating-input [(rating)]="rating" [texts]="ratingTexts" name="rating"></rating-input>
    <b>{{'RATINGDIALOG.HEADERPRICE' | translate}}</b><br>
    <rating-input [(rating)]="ratingPrice" symbol="logo-euro" [texts]="ratingPriceTexts"></rating-input>

    <input type="text" [(value)]="meinval">

    {{meinval}}
  </form>
</ion-content>
<ion-footer>
  <ion-row>
    <ion-col>
      <button [disabled]="rating == 0 || ratingPrice == 0" ion-button full color="secondary" (click)="saveRating()">
        {{'RATINGDIALOG.SAVE' | translate}}
    </button>
    </ion-col>
    <ion-col>
      <button ion-button full color="secondary" (click)="dismiss()">{{'RATINGDIALOG.CANCEL' | translate}}
      </button>
    </ion-col>
  </ion-row>
</ion-footer>
</code>```

Rating popup typescript:

```<code>import { Component, OnInit } from '@angular/core';
import { ViewController, NavParams } from 'ionic-angular';
import { Christmasmarket } from "../../../model/christmasmarket";
import { ChristmasMarketService } from "../../../services/christmasmarketservice";
import { TranslateService } from "@ngx-translate/core";

@Component({
  selector: 'rating-dialog',
  templateUrl: 'ratingdialog.component.html'
})
export class RatingDialogComponent implements OnInit {

  rating: number;
  ratingPrice: number;

  ratingTexts: Array<string>;
  ratingPriceTexts: Array<string>;

  market: Christmasmarket;

  meinval: String;
  constructor(
    private viewCtrl: ViewController,
    private navParams: NavParams,
    private christmasMarketService: ChristmasMarketService,
    private translate: TranslateService
  ) {

  }

  ngOnInit(): void {

    this.translate.get('RATINGTEXTS').subscribe(res => {
      this.ratingTexts = [];
      this.ratingTexts.push(res['VALUE1']);
      this.ratingTexts.push(res['VALUE2']);
      this.ratingTexts.push(res['VALUE3']);
      this.ratingTexts.push(res['VALUE4']);
      this.ratingTexts.push(res['VALUE5']);
    });

    this.translate.get('RATINGPRICETEXTS').subscribe(res => {
      this.ratingPriceTexts = [];
      this.ratingPriceTexts.push(res['VALUE1']);
      this.ratingPriceTexts.push(res['VALUE2']);
      this.ratingPriceTexts.push(res['VALUE3']);
      this.ratingPriceTexts.push(res['VALUE4']);
      this.ratingPriceTexts.push(res['VALUE5']);
    });

    this.market = this.navParams.get('data');
    this.rating = 0;
    this.ratingPrice = 0;

    this.christmasMarketService.findRatingOfMarket(this.market.id).then(rating => {

      if (rating) {
        this.rating = rating.rating;
        this.ratingPrice = rating.ratingPrice;
      }
    }).catch(e => {

        console.log(e);
    });
  }

  dismiss() {
    this.viewCtrl.dismiss(this.market);
  }

  saveRating() {
    this.christmasMarketService.rateMarket(this.market.id, this.rating, this.ratingPrice).then(market => {
      this.market = market;
      this.dismiss();
      console.log(market);
  }).catch(e => {
      console.log(e);
  });

  }

}
</code>```

Rating-input component html

```<code><button ion-button icon-only clear="true" (click)="onClickRating(num)" *ngFor="let num of possibleRatings">
<ion-icon [name]="symbol"  [color]="rating >= num ? 'black' : 'grey'"></ion-icon>
</button>
<p *ngIf="texts">
    {{texts[rating-1]}}
</p>
<p *ngIf="!rating || rating == 0">
    -
</p>
</code>```

rating-input component typescript

import { Component, Input, Output, EventEmitter } from "@angular/core";

```<code>@Component({
  selector: 'rating-input',
  templateUrl: 'ratinginput.component.html'
})
export class RatingInputComponent{

  @Input() @Output() rating: number;
  @Input() symbol: string = 'star';
  @Input() texts : Array<string>;

  @Output() ratingChange = new EventEmitter();

  possibleRatings: Array<number> = [1, 2, 3, 4, 5];

  onClickRating(rating: number) {
    this.rating = rating;
    this.ratingChange.emit(this.rating);
  }
}
</code>```

答:
The problem lies here:

```<code>.then(marker => {
    marker.on(GoogleMapsEvent.INFO_CLICK)
      .subscribe(() => {
        this.onClickMarket(market);
      });
});
</code>```

A click event coming from the google maps api uses its own event listeners, and you have to listen to them using  addListener. The problem is, that this is running outside the ngZone. To re-enter the zone, after an event like that has occured, you need to inject ngZone into your component, and execute ngZone.run():

```<code>constructor(private readonly ngZone: NgZone) {}

// ...
putMarkersForMarkets(): void {

    // ...
    .then(marker => {
        marker.on(GoogleMapsEvent.INFO_CLICK).subscribe(() => {
            this.ngZone.run(() => this.onClickMarket(market));
        });
    });
}
</code>```

This will make sure that any code running inside the run() method will be running inside the zone, and therefore will trigger the change detection

Body:
I am using Ionic 3 and I am using the Google Maps plugin for it. I have two pages, a list and a map. I display the same objects on both views and when you click a list entry or a marker (info window), the object's detail page will be opened where you can rate the selected object.

Anyway, when I open the detail page via the list, everything works fine but when I open the detail page via the map-marker, the two-way data binding stops working. In the code below you can find the <rating-input> component in the rating dialog. That's the code that's not working.

I've tried using a simple input text to find out if it's really the two way data binding or if it's my component. The data binding did not work either using the simple textbox.

Here is the code:

 //adding the markers to the map and adding the clicklisteners
 putMarkersForMarkets(markets: Christmasmarket[]) {

markets.forEach(market => {
  let isOpen = this.openinghoursService.isOpenAt(market, new Date());
  this.map.addMarker({
    title: market.name,
    icon: isOpen ? 'green' : 'red',
    animation: 'DROP',
    position: {
      lat: market.position.latitude,
      lng: market.position.longitude
    }
  }).then(marker => {
    marker.on(GoogleMapsEvent.INFO_CLICK)
      .subscribe(() => {
        this.onClickMarket(market);
      });
  });;

});

}

onClickMarket(market: Christmasmarket) {
       this.map.setVisible(false);
       this.map.setClickable(false);
     this.app.getRootNav().push(MarketDetailPage, { data: market });
   }

Rating-Popup html:

<ion-header>
  <ion-navbar color="primary">
    <ion-title>{{'RATINGDIALOG.TITLE' | translate}}</ion-title>
    <ion-buttons end>
      <button ion-button icon-only (click)="dismiss()">
      <ion-icon name="close"></ion-icon>
    </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <form #form="ngForm">
    {{'RATINGDIALOG.HEADERMARKET' | translate}}

    <rating-input [(rating)]="rating" [texts]="ratingTexts" name="rating"></rating-input>
    {{'RATINGDIALOG.HEADERPRICE' | translate}}

    <rating-input [(rating)]="ratingPrice" symbol="logo-euro" [texts]="ratingPriceTexts"></rating-input>

    <input type="text" [(value)]="meinval">

    {{meinval}}
  </form>
</ion-content>
<ion-footer>
  <ion-row>
    <ion-col>
      <button [disabled]="rating == 0 || ratingPrice == 0" ion-button full color="secondary" (click)="saveRating()">
        {{'RATINGDIALOG.SAVE' | translate}}
    </button>
    </ion-col>
    <ion-col>
      <button ion-button full color="secondary" (click)="dismiss()">{{'RATINGDIALOG.CANCEL' | translate}}
      </button>
    </ion-col>
  </ion-row>
</ion-footer>

Rating popup typescript:

import { Component, OnInit } from '@angular/core';
import { ViewController, NavParams } from 'ionic-angular';
import { Christmasmarket } from "../../../model/christmasmarket";
import { ChristmasMarketService } from "../../../services/christmasmarketservice";
import { TranslateService } from "@ngx-translate/core";

@Component({
  selector: 'rating-dialog',
  templateUrl: 'ratingdialog.component.html'
})
export class RatingDialogComponent implements OnInit {

  rating: number;
  ratingPrice: number;

  ratingTexts: Array<string>;
  ratingPriceTexts: Array<string>;

  market: Christmasmarket;

  meinval: String;
  constructor(
    private viewCtrl: ViewController,
    private navParams: NavParams,
    private christmasMarketService: ChristmasMarketService,
    private translate: TranslateService
  ) {

  }

  ngOnInit(): void {

    this.translate.get('RATINGTEXTS').subscribe(res => {
      this.ratingTexts = [];
      this.ratingTexts.push(res['VALUE1']);
      this.ratingTexts.push(res['VALUE2']);
      this.ratingTexts.push(res['VALUE3']);
      this.ratingTexts.push(res['VALUE4']);
      this.ratingTexts.push(res['VALUE5']);
    });

    this.translate.get('RATINGPRICETEXTS').subscribe(res => {
      this.ratingPriceTexts = [];
      this.ratingPriceTexts.push(res['VALUE1']);
      this.ratingPriceTexts.push(res['VALUE2']);
      this.ratingPriceTexts.push(res['VALUE3']);
      this.ratingPriceTexts.push(res['VALUE4']);
      this.ratingPriceTexts.push(res['VALUE5']);
    });

    this.market = this.navParams.get('data');
    this.rating = 0;
    this.ratingPrice = 0;

    this.christmasMarketService.findRatingOfMarket(this.market.id).then(rating => {

      if (rating) {
        this.rating = rating.rating;
        this.ratingPrice = rating.ratingPrice;
      }
    }).catch(e => {

        console.log(e);
    });
  }

  dismiss() {
    this.viewCtrl.dismiss(this.market);
  }

  saveRating() {
    this.christmasMarketService.rateMarket(this.market.id, this.rating, this.ratingPrice).then(market => {
      this.market = market;
      this.dismiss();
      console.log(market);
  }).catch(e => {
      console.log(e);
  });

  }

}

Rating-input component html

<button ion-button icon-only clear="true" (click)="onClickRating(num)" *ngFor="let num of possibleRatings">
<ion-icon [name]="symbol"  [color]="rating >= num ? 'black' : 'grey'"></ion-icon>
</button>

    {{texts[rating-1]}}

    -

rating-input component typescript

import { Component, Input, Output, EventEmitter } from "@angular/core";

@Component({
  selector: 'rating-input',
  templateUrl: 'ratinginput.component.html'
})
export class RatingInputComponent{

  @Input() @Output() rating: number;
  @Input() symbol: string = 'star';
  @Input() texts : Array<string>;

  @Output() ratingChange = new EventEmitter();

  possibleRatings: Array<number> = [1, 2, 3, 4, 5];

  onClickRating(rating: number) {
    this.rating = rating;
    this.ratingChange.emit(this.rating);
  }
}

Body:
The problem lies here:

.then(marker => {
    marker.on(GoogleMapsEvent.INFO_CLICK)
      .subscribe(() => {
        this.onClickMarket(market);
      });
});

A click event coming from the google maps api uses its own event listeners, and you have to listen to them using  addListener. The problem is, that this is running outside the ngZone. To re-enter the zone, after an event like that has occured, you need to inject ngZone into your component, and execute ngZone.run():

constructor(private readonly ngZone: NgZone) {}

// ...
putMarkersForMarkets(): void {

    // ...
    .then(marker => {
        marker.on(GoogleMapsEvent.INFO_CLICK).subscribe(() => {
            this.ngZone.run(() => this.onClickMarket(market));
        });
    });
}

This will make sure that any code running inside the run() method will be running inside the zone, and therefore will trigger the change detection


问:
How to detect touch on UIWebView
On UIWebview, how can I detect a touch?

But not when user clicks some URL or touching a control.

Is it possible to handle it?

答:
Do you mean you want to override the options that popup when they hold down on a link? I managed to get one to work with this tutorial/guide but the one posted here is still slightly buggy and needs you to do some fine tuning:
http://www.icab.de/blog/2010/07/11/customize-the-contextual-menu-of-uiwebview/</p>

Title: How to detect touch on UIWebView


问:
How to delete data from array and then interpolate over that gap in python?
So I am looking at a day's worth of data. I am trying to remove the hour 12:00 to 13:00 from the data set, and then interpolate over that hour given the rest of the data.

I am running into two problems:

The way I am removing the data is incorrect and I am not sure how to fix it. It deletes the data, but then shifts the data over again so there in not a gap. This is evident when I graph the data, and there is no gap.

I don't know if I need to use interpolate.interp1d or interpolate.splev.

This is not the exact data I am using, but it is a good example to show what I need to do and what I have tried.

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
from matplotlib import pylab

day_sec=np.arange(0,86400,1) #24 hours in seconds
ydata=np.exp(-day_sec/30) #random ydata for example

remove_seconds=np.arange(43200,46800,1) #12-13:00 in seconds

last=len(remove_seconds)-1

for i in range(len(day_sec)): #what I have tried to remove the data, but failed
  if (day_sec[i] >= remove_seconds[0]) and (day_sec[i] <= remove_seconds[last]):
    new_day_sec=np.delete(day_sec,[i],None)
    new_ydata=np.delete(ydata,[i],None)

f=interpolate.interp1d(new_day_sec,new_ydata) #not sure this is correct
</code>```

Any help is appreciated. Thanks!

答:
You can accomplish this without using a loop.  Here's an example with some more "meaningful" y data.  (The mean of your current ydata is 0, and the expectation is zero also.)

```<code>import numpy as np
from scipy import interpolate

# Step one - build your data and combine it into one 2d array
day_sec = np.arange(0, 86400)
ydata = np.random.randn(day_sec.shape[0]) + np.log(day_sec + 1)
data = np.column_stack((day_sec, ydata))

# Step two - get rid of the slice from 12:13 with a mask
# Remember your array is 0-indexed
remove_seconds = np.arange(43200, 46800)
mask = np.ones(data.shape[0], dtype=bool)
# Mask is now False within `remove_seconds` and True everywhere else.
# This allows us to filter (boolean mask) `data`.
mask[remove_seconds] = False
newdata = data[mask, :]

# Step three - interpolate
# `f` here is just a function, not an array.  You need to input
#     your "dropped" range of seconds to produce predicted values.
f = interpolate.interp1d(newdata[:, 0], newdata[:, 1])
predicted = f(remove_seconds)

# If you want to insert the interpolated data
data[~mask, 1] = predicted

plt.plot(data[:, 0], data[:, 1])
</code>```

Body:
So I am looking at a day's worth of data. I am trying to remove the hour 12:00 to 13:00 from the data set, and then interpolate over that hour given the rest of the data.

I am running into two problems:

The way I am removing the data is incorrect and I am not sure how to fix it. It deletes the data, but then shifts the data over again so there in not a gap. This is evident when I graph the data, and there is no gap.

I don't know if I need to use interpolate.interp1d or interpolate.splev.

This is not the exact data I am using, but it is a good example to show what I need to do and what I have tried.

import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
from matplotlib import pylab

day_sec=np.arange(0,86400,1) #24 hours in seconds
ydata=np.exp(-day_sec/30) #random ydata for example

remove_seconds=np.arange(43200,46800,1) #12-13:00 in seconds

last=len(remove_seconds)-1

for i in range(len(day_sec)): #what I have tried to remove the data, but failed
  if (day_sec[i] >= remove_seconds[0]) and (day_sec[i] <= remove_seconds[last]):
    new_day_sec=np.delete(day_sec,[i],None)
    new_ydata=np.delete(ydata,[i],None)

f=interpolate.interp1d(new_day_sec,new_ydata) #not sure this is correct

Any help is appreciated. Thanks!

Body:
You can accomplish this without using a loop.  Here's an example with some more "meaningful" y data.  (The mean of your current ydata is 0, and the expectation is zero also.)

import numpy as np
from scipy import interpolate

# Step one - build your data and combine it into one 2d array
day_sec = np.arange(0, 86400)
ydata = np.random.randn(day_sec.shape[0]) + np.log(day_sec + 1)
data = np.column_stack((day_sec, ydata))

# Step two - get rid of the slice from 12:13 with a mask
# Remember your array is 0-indexed
remove_seconds = np.arange(43200, 46800)
mask = np.ones(data.shape[0], dtype=bool)
# Mask is now False within `remove_seconds` and True everywhere else.
# This allows us to filter (boolean mask) `data`.
mask[remove_seconds] = False
newdata = data[mask, :]

# Step three - interpolate
# `f` here is just a function, not an array.  You need to input
#     your "dropped" range of seconds to produce predicted values.
f = interpolate.interp1d(newdata[:, 0], newdata[:, 1])
predicted = f(remove_seconds)

# If you want to insert the interpolated data
data[~mask, 1] = predicted

plt.plot(data[:, 0], data[:, 1])


问:
How to get mountable engine path in Rails 5?
I am writing a middleware inside a mountable engine, and I need to know the mount point of the engine. How would i do this in Rails 5? I've tried MyEng::Engine.routes._generate_prefix({}) but that does not work in Rails 5.

答:
Update after E L Rayle comment

If you want to get the path on which the engine is mounted you can use the following method:

```<code>MyEng::Engine.routes.find_script_name({})
</code>```

See comments for more details.

[previous wrong answer]

I think you are looking for this one: MyEngine::Engine.root. See this question

Body:
Update after E L Rayle comment

If you want to get the path on which the engine is mounted you can use the following method:

MyEng::Engine.routes.find_script_name({})

See comments for more details.

[previous wrong answer]

I think you are looking for this one: MyEngine::Engine.root. See this question

ContentLicense: CC BY-SA 4.0


问:
Does Git handle transactions when pulling?
I have a git repository (let's call it "CGR") cloned from a github fork (GK), that one forks an original github repo (GR). I do changes in CGR, and commit them on a branch B. Then, I pull the master branch from GR to CGR, and merge that master branch into B branch.

And after that operation, some files still remain unchanged. I can pull again, and git says "okay, your local branch is up to date with the GR branch".

I check a file in my local repository CGR (let's say, "pom.xml"), and there, I see that some modifications are missing.

So, there's the real question I have: does Git handle transactions when pulling and how does Git handle transactions? Because I suspect a network failure at the wrong time, leading to a corrupted local repository, which makes sense if Git has holes in its transaction mechanism or if it has no transaction at all.

答:
There are reasonably good online resources that cover git's protocols and data structures.  It's a lot of information.  With that knowledge, understanding the mechanisms for ensuring consistency after a fetch or pull are pretty straightforward; without that knowledge, it would seem pretty incomprehensible in my opinion.

So if you really want to know, then you have some research to do; it would make no sense to try to reiterate it all here (and if I interpreted your question as a request for a documentation reference, then I suppose I would've down-voted it as off-topic instead of answering).

Failing that, all I can tell you is: no, your hypothesis does not make sense.  You can choose whether to trust me on that - you wouldn't be the first to be dead sure that their incorrect observations are conclusive.  But consider whether a gaping hole like you describe wouldn't be well-known by experience, and whether anyone would actually use git if that were the case.

Keeping in mind that git is a distributed source control system by design.


问:
Symfony2 Best way to implement database translations
I'm refactoring a multilanguage website to symfony.

The site has plenty of language stuff stored in databases (product descriptions, product name...) and a language table. It looks pretty much like these:
Table product:
-id
-price
-stock
-...

Table product_language:
-id_product
-id_language
-name
-description

Table language:
-id
-name
-code

So I'm thinking in the best way to migrate this to symfony and doctrine, I've been looking into the translatable extension but I don't know if it would fit here (I'm not sure about if its possible to ad the language table into it)

Thanks!

答:
You could use VM5's Entity Translations bundle.
It's pretty simple and lightweight. And it also uses native Doctrine ORM associations for translations.</p>


问:
Vaadin OSGi Portlet on Liferay 7
I'm trying to create a Vaadin protlet and deploy it on a liferay portal with OSGI.
I'm new to this so sorry if its very simple but I don't understand what I'm missing.

OSGi Portlets on Liferay 7
is the tutorial that I found in Vaadin's site.

Tutorial says :

Publishing an OSGi portlet on Liferay 7+ can be done in two ways:
  using annotations or using properties. Annotating a UI class with
  @VaadinLiferayPortletConfiguration (available in
  vaadin-liferay-integration) and making it an OSGi service of type UI
  is the easiest way to automatically publish the UI as a portlet and
  configure it to use the correct static resources.

```<code>@Theme(MyTheme.THEME_NAME)
@VaadinLiferayPortletConfiguration(name = "Vaadin.Tutorial.1", displayName =
"Vaadin Tutorial App")
@Component(service = UI.class, scope = ServiceScope.PROTOTYPE)
public class MyUI extends UI {
...
}
</code>```

I created a maven project with vaadin-liferay-integration but Eclipse does not recognize annotations in this tutorial (@VaadinLiferayPortletConfiguration AND @Component )
Does any one have any idea what the problem is?

答:
Better place to start is official Vaadin archetype:

https://repo1.maven.org/maven2/com/vaadin/vaadin-archetype-liferay-portlet/8.1.6/

Moreover, this a sample portlet I wrote for Liferay 7, very basic but with some tricks:

https://github.com/ctliv/vaadin-portlet-sample/

Title: Vaadin OSGi Portlet on Liferay 7

Body:
I'm trying to create a Vaadin protlet and deploy it on a liferay portal with OSGI.
I'm new to this so sorry if its very simple but I don't understand what I'm missing.

OSGi Portlets on Liferay 7
is the tutorial that I found in Vaadin's site.

Tutorial says :

Publishing an OSGi portlet on Liferay 7+ can be done in two ways:
  using annotations or using properties. Annotating a UI class with
  @VaadinLiferayPortletConfiguration (available in
  vaadin-liferay-integration) and making it an OSGi service of type UI
  is the easiest way to automatically publish the UI as a portlet and
  configure it to use the correct static resources.

@Theme(MyTheme.THEME_NAME)
@VaadinLiferayPortletConfiguration(name = "Vaadin.Tutorial.1", displayName =
"Vaadin Tutorial App")
@Component(service = UI.class, scope = ServiceScope.PROTOTYPE)
public class MyUI extends UI {
...
}

I created a maven project with vaadin-liferay-integration but Eclipse does not recognize annotations in this tutorial (@VaadinLiferayPortletConfiguration AND @Component )
Does any one have any idea what the problem is?


问:
Add a website to IIS on localhost
I was trying to add my ASP.NET website in IIS 7.5 on my local computer. I followed these steps in IIS Manager.

Right-click sites>Add website and specify the physical path. (I chose the app pool as Default app pool)

Right-click on the WebSite just added>Manage>Browse.

On trying to browse the website, I am getting this error

The requested page cannot be accessed because the related configuration data for the page is invalid

Here's the screenshot:

答:
It sounds like the process your IIS App Pool is running under does not have read access to the directory you specified.

The IIS App Pool is probably running under Network Service or ASP .NET 4.0 account depending on the version of .NET you're using.

Try navigating to the physical directory and changing the security properties to give Network Service and ASP .NET 4.0 (if it exists on your computer) Read access.

Title: Add a website to IIS on localhost


问:
How resume file while uploading to server
in my project user want to upload 3GB video file.
in case while uploading time it stopped because of some internet failure or any other disturbance.

while next uploading time it should start from where it got stopped.
it should not start from stating point again.

any suggestions please....

it's a .net project (MVC,Jquery,EF and Sql server)

i am storing all files into AWS s3.

答:
Here is a starting point ,,,

Source; How to upload to S3 with Pause/Resume support?

I implemented the following app.

Github Link: https://github.com/interpegasus/condo_example
It is based on the sample app and gem from: http://cotag.github.com/Condominios/

All credit to https://github.com/cotag/ for a great gem and work.

FEATURES:

Pause / Resume support ~ 5MB chunks

Large File Upload

Progress Bar

No Java Applet / No Flash

Registration system via devise


问:
display: flex in ancessor and one of its child bring errors.
Good day.

Second time in my large CSS project I found that if ancessor and it's child have a display: flex property. This leads to error. I cannot formulate what conditions for this bug. And this time I think I found one more of it's appearance:

1) On Desktop Chrome works fine: https://youtu.be/e6jIKx7KM7s
2) On Iphone dose not works: https://youtu.be/0Nw_dHPhYZQ

Usually this error happens on iPhone, but some times even desktop chrome fails in rendering. https://gist.github.com/lbvf50mobile/5dc976a3a451ac491159ea6b5d971482

First/second "display: flex": I have when set generate sticky footer with scrolling and holy grail layouts.

Third "display: flex" inside swiper-slider and this leads to error on Safary/Chrome of the iPhone 6s.

What do you think it is?

thank you

答:
Error was fixed by simplifying code:

Code with BUGS:

```<code>main.pose .center{
  & a.center{flex: 1 100;}
  & .text{flex: 100 1;}
}
</code>```

Simplified BUG-FREE code:

```<code>main.pose .center{
  & a.center{}
  & .text{flex: 1;}
}
</code>```

Body:
Error was fixed by simplifying code:

Code with BUGS:

main.pose .center{
  & a.center{flex: 1 100;}
  & .text{flex: 100 1;}
}

Simplified BUG-FREE code:

main.pose .center{
  & a.center{}
  & .text{flex: 1;}
}


问:
Spring-batch to spring task in Spring cloud data flow
I'm new to spring-batch and spring cloud data flow.
I modified the sample quickstart project for the spring-batch and it now writes on a local MSSQL database: it works fine when I run it using java -jar.
I now tried to deploy it to a local instance of Spring Cloud Data Flow, imported it as a Task from the dashboard and tried to run: it gives me this error:

```<code>2017-11-15 17:54:46.109  INFO 17164 --- [           main] hello.Application                        : Starting Application v0.0.1-SNAPSHOT on localmachine with PID 17164 (C:\Users\massimo.sporchia\eclipse-workspace\batch-example\target\batch-example-0.0.1-SNAPSHOT.jar started by massimo.sporchia in C:\Users\MASSIM~1.SPO\AppData\Local\Temp\spring-cloud-dataflow-5975572085987003620\exampleTask-1510764882259\exampleTask-4fd22d5a-a5f0-49d5-8634-a4bbb21d2675)
2017-11-15 17:54:46.129  INFO 17164 --- [           main] hello.Application                        : No active profile set, falling back to default profiles: default
2017-11-15 17:54:46.402  INFO 17164 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1698c449: startup date [Wed Nov 15 17:54:46 CET 2017]; root of context hierarchy
2017-11-15 17:54:49.020  WARN 17164 --- [           main] o.s.c.a.ConfigurationClassEnhancer       : @Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.
2017-11-15 17:54:49.066  WARN 17164 --- [           main] o.s.c.a.ConfigurationClassEnhancer       : @Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.
2017-11-15 17:54:49.288  INFO 17164 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.task.batch.configuration.TaskBatchAutoConfiguration' of type [org.springframework.cloud.task.batch.configuration.TaskBatchAutoConfiguration$$EnhancerBySpringCGLIB$$da33614e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-11-15 17:54:49.306  INFO 17164 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$54c3b5c2] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-11-15 17:54:49.441  INFO 17164 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.task.batch.listener.BatchEventAutoConfiguration' of type [org.springframework.cloud.task.batch.listener.BatchEventAutoConfiguration$$EnhancerBySpringCGLIB$$22896b51] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-11-15 17:54:49.631  WARN 17164 --- [           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'batchConfiguration': Unsatisfied dependency expressed through field 'jobBuilderFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration': Unsatisfied dependency expressed through field 'dataSources'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: org.h2.Driver
2017-11-15 17:54:49.653  INFO 17164 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-15 17:54:49.686 ERROR 17164 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'batchConfiguration': Unsatisfied dependency expressed through field 'jobBuilderFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration': Unsatisfied dependency expressed through field 'dataSources'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: org.h2.Driver
</code>```

The same spring-batch uber-jar works when deployed as a Stream: what am I missing?

答:
Thanks for the repo.

To run a Spring Batch job in SCDF, you will have to adapt the application to Spring Cloud Task programming model. Please use the Spring Cloud Task and Spring Cloud Data Flow batch-job samples as a reference.

Unless the application adapts to this model, it will not run in SCDF.

One other thing. A batch-job can only run as a Task in SCDF and it cannot be used in a Stream.

Body:
I'm new to spring-batch and spring cloud data flow.
I modified the sample quickstart project for the spring-batch and it now writes on a local MSSQL database: it works fine when I run it using java -jar.
I now tried to deploy it to a local instance of Spring Cloud Data Flow, imported it as a Task from the dashboard and tried to run: it gives me this error:

2017-11-15 17:54:46.109  INFO 17164 --- [           main] hello.Application                        : Starting Application v0.0.1-SNAPSHOT on localmachine with PID 17164 (C:\Users\massimo.sporchia\eclipse-workspace\batch-example\target\batch-example-0.0.1-SNAPSHOT.jar started by massimo.sporchia in C:\Users\MASSIM~1.SPO\AppData\Local\Temp\spring-cloud-dataflow-5975572085987003620\exampleTask-1510764882259\exampleTask-4fd22d5a-a5f0-49d5-8634-a4bbb21d2675)
2017-11-15 17:54:46.129  INFO 17164 --- [           main] hello.Application                        : No active profile set, falling back to default profiles: default
2017-11-15 17:54:46.402  INFO 17164 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1698c449: startup date [Wed Nov 15 17:54:46 CET 2017]; root of context hierarchy
2017-11-15 17:54:49.020  WARN 17164 --- [           main] o.s.c.a.ConfigurationClassEnhancer       : @Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.
2017-11-15 17:54:49.066  WARN 17164 --- [           main] o.s.c.a.ConfigurationClassEnhancer       : @Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.
2017-11-15 17:54:49.288  INFO 17164 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.task.batch.configuration.TaskBatchAutoConfiguration' of type [org.springframework.cloud.task.batch.configuration.TaskBatchAutoConfiguration$$EnhancerBySpringCGLIB$$da33614e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-11-15 17:54:49.306  INFO 17164 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$54c3b5c2] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-11-15 17:54:49.441  INFO 17164 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.task.batch.listener.BatchEventAutoConfiguration' of type [org.springframework.cloud.task.batch.listener.BatchEventAutoConfiguration$$EnhancerBySpringCGLIB$$22896b51] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-11-15 17:54:49.631  WARN 17164 --- [           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'batchConfiguration': Unsatisfied dependency expressed through field 'jobBuilderFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration': Unsatisfied dependency expressed through field 'dataSources'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: org.h2.Driver
2017-11-15 17:54:49.653  INFO 17164 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-15 17:54:49.686 ERROR 17164 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'batchConfiguration': Unsatisfied dependency expressed through field 'jobBuilderFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration': Unsatisfied dependency expressed through field 'dataSources'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: org.h2.Driver

The same spring-batch uber-jar works when deployed as a Stream: what am I missing?


问:
Opencl - Transfer Global memory Work-Group + border to Local memory
Here a draft of code I produced :

```<code>void __kernel myKernel(__global const short* input,
                       __global short* output,
                       const int width,
                       const int height){

    // Always square. (and 16x16 in our example)
    const uint local_size = get_local_size(0);

    // Get the work-item col/row index
    const uint wi_c = get_local_id(0);
    const uint wi_r = get_local_id(1);

    // Get the global col/row index
    const uint g_c = get_global_id(0);
    const uint g_r = get_global_id(1);

    // Declare a local array NxN
    const uint arr_size = local_size *local_size ;
    __local short local_in[arr_size];

    // Transfer the global memory for into a local one.
    local_in[wi_c  + wi_r*local_size ] = input[g_c + g_r*width];

    // Wait that all the work-item are sync
    barrier(CLK_LOCAL_MEM_FENCE);

    // Now add code to process on the local array (local_in).
</code>```

As far as I understand OpenCL work-group/work-item, this is what I need to do to copy a global 16x16 ROI of from global to local memory. (Please correct me if I'm wrong, since I'm beginning at this).

So after the barrier, each element in local_in can be access via wi_c + wi_r*local_size.

But now let's do something tricky. If I want for each work-item in my work group to work on a 3x3 neighborhood, I will need a 18x18 local_in array.

But how to create this ? Since I have only 16x16=256 work-item (threads), but I need 18x18=324 (missing 68 threads to do it).

My basic idea should be to do:

```<code>if(wi_c == 0 && wi_r == 0){
    // Code that copy the border into the new array that should be
    // local_in[(local_size+2)*(local_size+2)];
}
</code>```

But this is terrible, since the first work-item (1st thread) will have to handle all the border and the rest of the work-items in this group will just be waiting this 1st work-item to finish. (Again, this is my understanding of OpenCL, might be wrong).

So here are my real question:

Is there another easier solution for this kind of problem ? Like changing the NDRange Local size to be overlapping or something ?

I start to read about coalesced memory access, is my first draft of code look like it ? I don't think so, since I'm using a "stride" approach to load the global memory. But I don't understand how I could change the first part of that code to be efficient also.

Once the barrier is reached, the processing continue of each work-item to get a final value that need to be stored back into the global output array. Should I put again a barrier before this "write" or all good to leave all the work-item finish their self ?

答:
I tried different approaches and I came with the final version, which is less "if" and use thread as much as possible (On second phase, might not be fully efficient since few thread are idle, but it's the best I was able to get).

The principle is to set an origin (start pos) at the top-left corner and create Read/Write index from this position using loop index. The loop start at the local id position in 2D. So all 256 work-items write their first element, and on phase two only 68 work-items on 256 will complete the 2 bottom rows + 2 right columns.

I'm not a OpenCL pro yet, so this could still have more improvement (maybe loop unroll, I don't know).

```<code>    __local float wrkSrc[324];
    const int lpitch = 18;

    // Add halfROI to handle the corner
    const int lcol = get_local_id(0);
    const int lrow = get_local_id(1);

    const int2 gid = { col, row };
    const int2 lid = { lcol, lrow };

    // Always get the most Top-left corner of that ROI to extract.
    const int2 startPos = gid - lid - halfROI;

    // Loop on each thread to get their right ID.
    // Thread with id < 2 * halfROI will process more then others, but not that much an issue.
    for ( int x = lid.x; x < lpitch; x += 16 ) {
        for ( int y = lid.y; y < lpitch; y += 16 ) {

            // Get the position to write into the local array.
            const int lidx = x + y * lpitch;

            // Get the position to read into the global memory (src)
            const int2 readPos = startPos + (int2)( x, y );

            // Is inside ?
            if ( readPos.x >= 0 && readPos.x < width && readPos.y >= 0 && readPos.y < height )
                wrkSrc[lidx] = src[readPos.x + readPos.y * lab_new_pitch];
            else
                wrkSrc[lidx] = 0.0f;
        }
    }
</code>```

Body:
Here a draft of code I produced :

void __kernel myKernel(__global const short* input,
                       __global short* output,
                       const int width,
                       const int height){

    // Always square. (and 16x16 in our example)
    const uint local_size = get_local_size(0);

    // Get the work-item col/row index
    const uint wi_c = get_local_id(0);
    const uint wi_r = get_local_id(1);

    // Get the global col/row index
    const uint g_c = get_global_id(0);
    const uint g_r = get_global_id(1);

    // Declare a local array NxN
    const uint arr_size = local_size *local_size ;
    __local short local_in[arr_size];

    // Transfer the global memory for into a local one.
    local_in[wi_c  + wi_r*local_size ] = input[g_c + g_r*width];

    // Wait that all the work-item are sync
    barrier(CLK_LOCAL_MEM_FENCE);

    // Now add code to process on the local array (local_in).

As far as I understand OpenCL work-group/work-item, this is what I need to do to copy a global 16x16 ROI of from global to local memory. (Please correct me if I'm wrong, since I'm beginning at this).

So after the barrier, each element in local_in can be access via wi_c + wi_r*local_size.

But now let's do something tricky. If I want for each work-item in my work group to work on a 3x3 neighborhood, I will need a 18x18 local_in array.

But how to create this ? Since I have only 16x16=256 work-item (threads), but I need 18x18=324 (missing 68 threads to do it).

My basic idea should be to do:

if(wi_c == 0 && wi_r == 0){
    // Code that copy the border into the new array that should be
    // local_in[(local_size+2)*(local_size+2)];
}

But this is terrible, since the first work-item (1st thread) will have to handle all the border and the rest of the work-items in this group will just be waiting this 1st work-item to finish. (Again, this is my understanding of OpenCL, might be wrong).

So here are my real question:

Is there another easier solution for this kind of problem ? Like changing the NDRange Local size to be overlapping or something ?

I start to read about coalesced memory access, is my first draft of code look like it ? I don't think so, since I'm using a "stride" approach to load the global memory. But I don't understand how I could change the first part of that code to be efficient also.

Once the barrier is reached, the processing continue of each work-item to get a final value that need to be stored back into the global output array. Should I put again a barrier before this "write" or all good to leave all the work-item finish their self ?

Body:
I tried different approaches and I came with the final version, which is less "if" and use thread as much as possible (On second phase, might not be fully efficient since few thread are idle, but it's the best I was able to get).

The principle is to set an origin (start pos) at the top-left corner and create Read/Write index from this position using loop index. The loop start at the local id position in 2D. So all 256 work-items write their first element, and on phase two only 68 work-items on 256 will complete the 2 bottom rows + 2 right columns.

I'm not a OpenCL pro yet, so this could still have more improvement (maybe loop unroll, I don't know).

    __local float wrkSrc[324];
    const int lpitch = 18;

    // Add halfROI to handle the corner
    const int lcol = get_local_id(0);
    const int lrow = get_local_id(1);

    const int2 gid = { col, row };
    const int2 lid = { lcol, lrow };

    // Always get the most Top-left corner of that ROI to extract.
    const int2 startPos = gid - lid - halfROI;

    // Loop on each thread to get their right ID.
    // Thread with id < 2 * halfROI will process more then others, but not that much an issue.
    for ( int x = lid.x; x < lpitch; x += 16 ) {
        for ( int y = lid.y; y < lpitch; y += 16 ) {

            // Get the position to write into the local array.
            const int lidx = x + y * lpitch;

            // Get the position to read into the global memory (src)
            const int2 readPos = startPos + (int2)( x, y );

            // Is inside ?
            if ( readPos.x >= 0 && readPos.x < width && readPos.y >= 0 && readPos.y < height )
                wrkSrc[lidx] = src[readPos.x + readPos.y * lab_new_pitch];
            else
                wrkSrc[lidx] = 0.0f;
        }
    }


问:
Boxing Native C++ Pointer
I have a pointer to a native class and want to temporarily wrap it in a Object. I assume the System::Reflection::Pointer::Box() function would be the way to go. However I'm having trouble formatting the second parameter to it.

```<code>class A {}
A * a;
Object ^ o = Box(a, A::typeid);
</code>```

I get a runtime error that says 'Type must be a pointer', as I suppose it should be. But I cannot figure out the syntax.

答:
I couldn't get System.Reflection.Pointer.Box to work either, but found the capability to do what you are trying with humble IntPtr.

```<code>A * a = new A;
Object ^o = gcnew IntPtr(a); // a is boxed in o
IntPtr i = safe_cast<IntPtr>(o); // Unbox the IntPtr
A * aIsBack = static_cast<A*>(i.ToPointer()); // Retrieve a
</code>```

Title: Boxing Native C++ Pointer

Body:
I have a pointer to a native class and want to temporarily wrap it in a Object. I assume the System::Reflection::Pointer::Box() function would be the way to go. However I'm having trouble formatting the second parameter to it.

class A {}
A * a;
Object ^ o = Box(a, A::typeid);

I get a runtime error that says 'Type must be a pointer', as I suppose it should be. But I cannot figure out the syntax.

Body:
I couldn't get System.Reflection.Pointer.Box to work either, but found the capability to do what you are trying with humble IntPtr.

A * a = new A;
Object ^o = gcnew IntPtr(a); // a is boxed in o
IntPtr i = safe_cast<IntPtr>(o); // Unbox the IntPtr
A * aIsBack = static_cast<A*>(i.ToPointer()); // Retrieve a


问:
Swift: Take a screenshot of the viewController and share it on Facebook
I created the following function to share a post on Facebook:

```<code>@IBAction func socialShare(_ sender: Any){
    //Alert
    let alert = UIAlertController(title: "Share", message: "First share!", preferredStyle: .actionSheet)

    //First action
    let actionOne = UIAlertAction(title: "Share on Facebook", style: .default) { (action) in

        //Checking if user is connected to Facebook
        if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook)
        {
            let post = SLComposeViewController(forServiceType: SLServiceTypeFacebook)!
            post.setInitialText("First")
            post.add(UIImage(named: "Mylogo.png"))
            self.present(post, animated: true, completion: nil)
        } else {self.showAlert(service: "Facebook")}
    }

    let actionThree = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    //Add action to action sheet
    alert.addAction(actionOne)
    alert.addAction(actionThree)

    //Present alert
    self.present(alert, animated: true, completion: nil)
}

func showAlert(service:String){
    let alert = UIAlertController(title: "Error", message: "You are not connected to \(service)", preferredStyle: .alert)
    let action = UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)

    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}
</code>```

But what I really want to do is to share an image and this image must be a screenshot of the viewController in which the user taps the share button. Is this possible? If so, how?

Update:

For the screenshot I have found a function like this:

```<code>func screenShotMethod() {
    //Create the UIImage
    UIGraphicsBeginImageContext(view.frame.size)
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
</code>```

But I don't know how to implement it in my code.

答:
to do that you can do something like this

```<code>func screenShotMethod() -> UIImage? {
    //Create the UIImage
    UIGraphicsBeginImageContext(view.frame.size)
    view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}
</code>```

And add it to:

```<code>    let post = SLComposeViewController(forServiceType: SLServiceTypeFacebook)!
    post.setInitialText("First")
    post.add(screenShotMethod())
    self.present(post, animated: true, completion: nil)
</code>```

Body:
I created the following function to share a post on Facebook:

@IBAction func socialShare(_ sender: Any){
    //Alert
    let alert = UIAlertController(title: "Share", message: "First share!", preferredStyle: .actionSheet)

    //First action
    let actionOne = UIAlertAction(title: "Share on Facebook", style: .default) { (action) in

        //Checking if user is connected to Facebook
        if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook)
        {
            let post = SLComposeViewController(forServiceType: SLServiceTypeFacebook)!
            post.setInitialText("First")
            post.add(UIImage(named: "Mylogo.png"))
            self.present(post, animated: true, completion: nil)
        } else {self.showAlert(service: "Facebook")}
    }

    let actionThree = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    //Add action to action sheet
    alert.addAction(actionOne)
    alert.addAction(actionThree)

    //Present alert
    self.present(alert, animated: true, completion: nil)
}

func showAlert(service:String){
    let alert = UIAlertController(title: "Error", message: "You are not connected to \(service)", preferredStyle: .alert)
    let action = UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)

    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

But what I really want to do is to share an image and this image must be a screenshot of the viewController in which the user taps the share button. Is this possible? If so, how?

Update:

For the screenshot I have found a function like this:

func screenShotMethod() {
    //Create the UIImage
    UIGraphicsBeginImageContext(view.frame.size)
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

But I don't know how to implement it in my code.

Body:
to do that you can do something like this

func screenShotMethod() -> UIImage? {
    //Create the UIImage
    UIGraphicsBeginImageContext(view.frame.size)
    view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

And add it to:

    let post = SLComposeViewController(forServiceType: SLServiceTypeFacebook)!
    post.setInitialText("First")
    post.add(screenShotMethod())
    self.present(post, animated: true, completion: nil)