问:
How to connect more than one Bluetooth audio devices with android phones, one device should record and other should play?
I am trying to develop one audio record play application with Bluetooth devices I need to satisfy below scenario.

If there are more than one audio Bluetooth device is connected, if one of the device is recording audio other device should play the audio simultaneously.

I can connect the Bluetooth devices in my MainActivity class below but the audio is not playing with the Bluetooth devices.

```<code>import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity implements Runnable
{
    protected static final String TAG = "TAG";
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    Button mScan;
    BluetoothAdapter mBluetoothAdapter;
    private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private ProgressDialog mBluetoothConnectProgressDialog;
    private BluetoothSocket mBluetoothSocket;
    BluetoothDevice mBluetoothDevice;

    @Override
    public void onCreate(Bundle mSavedInstanceState)
    {
        super.onCreate(mSavedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        mScan = (Button) findViewById(R.id.Scan);
        mScan.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View mView)
            {
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (mBluetoothAdapter == null)
                {
                    Toast.makeText(Main.this, "Message1", 2000).show();
                }
                else
                {
                    if (!mBluetoothAdapter.isEnabled())
                    {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    }
                    else
                    {
                        ListPairedDevices();
                        Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
                        startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                    }
                }
            }
        });

        mTune.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View mView)
            {
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (mBluetoothAdapter == null)
                {
                    Toast.makeText(Main.this, "Message2", 2000).show();
                }
                else
                {
                    if (!mBluetoothAdapter.isEnabled())
                    {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    }
                    else
                    {
                        ListPairedDevices();
                        Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
                        startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                    }
                }
            }
        });
    }// onCreate

    public void onActivityResult(int mRequestCode, int mResultCode, Intent mDataIntent)
    {
        super.onActivityResult(mRequestCode, mResultCode, mDataIntent);

        switch (mRequestCode)
        {
            case REQUEST_CONNECT_DEVICE:
                if (mResultCode == Activity.RESULT_OK)
                {
                    Bundle mExtra = mDataIntent.getExtras();
                    String mDeviceAddress = mExtra.getString("DeviceAddress");
                    Log.v(TAG, "Coming incoming address " + mDeviceAddress);
                    mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
                    mBluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", mBluetoothDevice.getName() + " : " + mBluetoothDevice.getAddress(), true, false);
                    Thread mBlutoothConnectThread = new Thread(this);
                    mBlutoothConnectThread.start();
                    //pairToDevice(mBluetoothDevice); This method is replaced by progress dialog with thread
                }
                break;

            case REQUEST_ENABLE_BT:
                if (mResultCode == Activity.RESULT_OK)
                {
                    ListPairedDevices();
                    Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
                    startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                }
                else
                {
                    Toast.makeText(Main.this, "Message", 2000).show();
                }
                break;
        }
    }

    private void ListPairedDevices()
    {
        Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
        if (mPairedDevices.size() > 0)
        {
            for (BluetoothDevice mDevice : mPairedDevices)
            {
                Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress());
            }
        }
    }

    public void run()
    {
        try
        {
            mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
            mBluetoothAdapter.cancelDiscovery();
            mBluetoothSocket.connect();
            mHandler.sendEmptyMessage(0);
        }
        catch (IOException eConnectException)
        {
            Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
             closeSocket(mBluetoothSocket);
             return;
        }
    }

    private void closeSocket(BluetoothSocket nOpenSocket)
    {
        try
        {
            nOpenSocket.close();
            Log.d(TAG, "SocketClosed");
        }
        catch (IOException ex)
        {
            Log.d(TAG, "CouldNotCloseSocket");
        }
    }

    private Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            mBluetoothConnectProgressDialog.dismiss();
            Toast.makeText(Main.this, "DeviceConnected", 5000).show();
        }
    };
}
</code>```

答:
Based on all the research I have done, the answer is no. Unless you have multiple bluetooth chips in your phone/tablet/mp3 player (an extremeley unlikely scenario) or some kind of hub/reciever that is otherwise connected to the speaker set up in the house, you will be limited to one bluetooth speaker. However, it is possible to create more convoluted setups than a simple bluetooth connection. There are Bluetooth audio recievers that can plug in to a speaker's audio in cable. These combined with long wires and splitters copuld do your job. If you want to make it wireless, fm transmitters are a thing. The bluetooth reciever would connect to an fm transmitter and each speaker could be paired with an fm reciever and you're good to go.

If you do find a solution though, I would be very interested.

Body:
I am trying to develop one audio record play application with Bluetooth devices I need to satisfy below scenario.

If there are more than one audio Bluetooth device is connected, if one of the device is recording audio other device should play the audio simultaneously.

I can connect the Bluetooth devices in my MainActivity class below but the audio is not playing with the Bluetooth devices.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity implements Runnable
{
    protected static final String TAG = "TAG";
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    Button mScan;
    BluetoothAdapter mBluetoothAdapter;
    private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private ProgressDialog mBluetoothConnectProgressDialog;
    private BluetoothSocket mBluetoothSocket;
    BluetoothDevice mBluetoothDevice;

    @Override
    public void onCreate(Bundle mSavedInstanceState)
    {
        super.onCreate(mSavedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        mScan = (Button) findViewById(R.id.Scan);
        mScan.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View mView)
            {
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (mBluetoothAdapter == null)
                {
                    Toast.makeText(Main.this, "Message1", 2000).show();
                }
                else
                {
                    if (!mBluetoothAdapter.isEnabled())
                    {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    }
                    else
                    {
                        ListPairedDevices();
                        Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
                        startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                    }
                }
            }
        });

        mTune.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View mView)
            {
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (mBluetoothAdapter == null)
                {
                    Toast.makeText(Main.this, "Message2", 2000).show();
                }
                else
                {
                    if (!mBluetoothAdapter.isEnabled())
                    {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    }
                    else
                    {
                        ListPairedDevices();
                        Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
                        startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                    }
                }
            }
        });
    }// onCreate

    public void onActivityResult(int mRequestCode, int mResultCode, Intent mDataIntent)
    {
        super.onActivityResult(mRequestCode, mResultCode, mDataIntent);

        switch (mRequestCode)
        {
            case REQUEST_CONNECT_DEVICE:
                if (mResultCode == Activity.RESULT_OK)
                {
                    Bundle mExtra = mDataIntent.getExtras();
                    String mDeviceAddress = mExtra.getString("DeviceAddress");
                    Log.v(TAG, "Coming incoming address " + mDeviceAddress);
                    mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
                    mBluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", mBluetoothDevice.getName() + " : " + mBluetoothDevice.getAddress(), true, false);
                    Thread mBlutoothConnectThread = new Thread(this);
                    mBlutoothConnectThread.start();
                    //pairToDevice(mBluetoothDevice); This method is replaced by progress dialog with thread
                }
                break;

            case REQUEST_ENABLE_BT:
                if (mResultCode == Activity.RESULT_OK)
                {
                    ListPairedDevices();
                    Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
                    startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                }
                else
                {
                    Toast.makeText(Main.this, "Message", 2000).show();
                }
                break;
        }
    }

    private void ListPairedDevices()
    {
        Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
        if (mPairedDevices.size() > 0)
        {
            for (BluetoothDevice mDevice : mPairedDevices)
            {
                Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress());
            }
        }
    }

    public void run()
    {
        try
        {
            mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
            mBluetoothAdapter.cancelDiscovery();
            mBluetoothSocket.connect();
            mHandler.sendEmptyMessage(0);
        }
        catch (IOException eConnectException)
        {
            Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
             closeSocket(mBluetoothSocket);
             return;
        }
    }

    private void closeSocket(BluetoothSocket nOpenSocket)
    {
        try
        {
            nOpenSocket.close();
            Log.d(TAG, "SocketClosed");
        }
        catch (IOException ex)
        {
            Log.d(TAG, "CouldNotCloseSocket");
        }
    }

    private Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            mBluetoothConnectProgressDialog.dismiss();
            Toast.makeText(Main.this, "DeviceConnected", 5000).show();
        }
    };
}


来源: stackexchange

问:
Why we need nock to do http request unit test?
Below is the sample code from redux document

```<code>describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
  })

  it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', () => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { body: { todos: ['do something'] }})

    const expectedActions = [
      { type: types.FETCH_TODOS_REQUEST },
      { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something']  } }
    ]

    const store = mockStore({ todos: [] })

    return store.dispatch(actions.fetchTodos())
      .then(() => { // return of async actions
        expect(store.getActions()).toEqual(expectedActions)
      })
  })
})
</code>```

Why we nee to use nock for this unit test?
I did not see any where use the data from nock in this sample code.

答:
Mainly because in this test we're interested in the actions that get produced by actions.fetchTodos(). This action will make a call to the /todos endpoint, thus returning actions with some data. Since we're just interested in the data contained in the actions, we just mock it.

Nock internally intercepts the real fetch call to /todos and returns a successful 200 code, making it possible for the redux store to continue.

The data you're looking for is

```<code>{ todos: ['do something']  }
</code>```

This is mocked and also expected later on

ContentLicense: CC BY-SA 3.0

Body:
Below is the sample code from redux document

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
  })

  it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', () => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { body: { todos: ['do something'] }})

    const expectedActions = [
      { type: types.FETCH_TODOS_REQUEST },
      { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something']  } }
    ]

    const store = mockStore({ todos: [] })

    return store.dispatch(actions.fetchTodos())
      .then(() => { // return of async actions
        expect(store.getActions()).toEqual(expectedActions)
      })
  })
})

Why we nee to use nock for this unit test?
I did not see any where use the data from nock in this sample code.

Body:
Mainly because in this test we're interested in the actions that get produced by actions.fetchTodos(). This action will make a call to the /todos endpoint, thus returning actions with some data. Since we're just interested in the data contained in the actions, we just mock it.

Nock internally intercepts the real fetch call to /todos and returns a successful 200 code, making it possible for the redux store to continue.

The data you're looking for is

{ todos: ['do something']  }

This is mocked and also expected later on


问:
Binary search of a Matrix

Write an efficient algorithm that searches for a value in an m x n
  matrix.

This matrix has the following properties:

-Integers in each row are sorted from left to right.
-The first integer
  of each row is greater than or equal to the last integer of the
  previous row.

Example:

Consider the following matrix:

[

    [1,   3,  5,  7],

[10, 11, 16, 20],
   [23, 30, 34, 50]
]
Given
  target = 3, return 1 ( 1 corresponds to true )

Return 0 / 1 ( 0 if the element is not present, 1 if the element is
  present ) for this problem

My solution works on NetBeans but fails on the website. Any help will be appreciated.
https://www.interviewbit.com/problems/matrix-search/

```<code>public class Solution {

    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();

        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r -1; // row to search column

        //binary search 1st value of rows
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(mid).get(0)) {
                return 1;
            }

            if (a.get(mid).get(0) < b && b < a.get(end).get(0)) {
                if (mid + 1 >= end) {
                    biRow = mid;
                    break;
                }
            } if (b < a.get(mid).get(0)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        //binary search column of biRow
        start = 0;
        end = c-1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}
</code>```

答:
Okay, the first thing you MUST NOT do is that, you cannot physically concat the matrix into a 1D vector, as this is O(N*M) which is linear and not what we want.

// Easy but TLE code
int Solution::searchMatrix(vector<vector<int> > &A, int B) {
    vector<int> v;
    for(auto a : A) v.insert(v.end(), a.begin(), a.end());
    return binary_search(v.begin(), v.end(), B);
}
```

<p>So the point is, you have to do binary search directly on the matrix, and that is pretty much the same (except you have to write binary search your own now). </p>

<p>As you did not really access all of the elements, this is <code>O(lg (N*M))</code></p>

<pre class="lang-cs prettyprint-override"><code>// Less Easy but AC code
int Solution::searchMatrix(vector<vector<int> > &A, int B) {
    int m = A.size(), n = A[0].size(), lo = 0, hi = m*n-1, mi, row, col;
    while(lo <= hi){
        mi = lo + ((hi-lo) >> 1);
        row = mi / n;
        col = mi % n;
        if(A[row][col] == B) return 1;
        else if(A[row][col] > B) hi = mi - 1;
        else lo = mi + 1;
    }
    return 0;
}
</code>```

Title: Binary search of a Matrix

Body:
Write an efficient algorithm that searches for a value in an m x n
  matrix.

This matrix has the following properties:

-Integers in each row are sorted from left to right.
-The first integer
  of each row is greater than or equal to the last integer of the
  previous row.

Example:

Consider the following matrix:

[

    [1,   3,  5,  7],

[10, 11, 16, 20],
   [23, 30, 34, 50]
]
Given
  target = 3, return 1 ( 1 corresponds to true )

Return 0 / 1 ( 0 if the element is not present, 1 if the element is
  present ) for this problem

My solution works on NetBeans but fails on the website. Any help will be appreciated.
https://www.interviewbit.com/problems/matrix-search/

public class Solution {

    public int searchMatrix(ArrayList<ArrayList<Integer>> a, int b) {
        int r = a.size();
        int c = a.get(0).size();

        int start = 0;
        int end = r - 1;
        // default value is last row for edge case
        int biRow = r -1; // row to search column

        //binary search 1st value of rows
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(mid).get(0)) {
                return 1;
            }

            if (a.get(mid).get(0) < b && b = end) {
                    biRow = mid;
                    break;
                }
            } if (b < a.get(mid).get(0)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        //binary search column of biRow
        start = 0;
        end = c-1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (b == a.get(biRow).get(mid)) {
                return 1;
            }
            if (b < a.get(biRow).get(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return 0;
    }
}

Body:
Okay, the first thing you MUST NOT do is that, you cannot physically concat the matrix into a 1D vector, as this is O(N*M) which is linear and not what we want.

// Easy but TLE code
int Solution::searchMatrix(vector<vector<int> > &A, int B) {
    vector<int> v;
    for(auto a : A) v.insert(v.end(), a.begin(), a.end());
    return binary_search(v.begin(), v.end(), B);
}

So the point is, you have to do binary search directly on the matrix, and that is pretty much the same (except you have to write binary search your own now).

As you did not really access all of the elements, this is O(lg (N*M))

// Less Easy but AC code
int Solution::searchMatrix(vector<vector<int> > &A, int B) {
    int m = A.size(), n = A[0].size(), lo = 0, hi = m*n-1, mi, row, col;
    while(lo <= hi){
        mi = lo + ((hi-lo) >> 1);
        row = mi / n;
        col = mi % n;
        if(A[row][col] == B) return 1;
        else if(A[row][col] > B) hi = mi - 1;
        else lo = mi + 1;
    }
    return 0;
}


问:
Angular Translate not translating sometimes with one-time binding
I am using Angular 1.x and it's Angular Translate module. Recently, I switched all my translation bindings from two-way to one-time. Everything worked fine, until one day, however, I noticed that sometimes if I started refreshing the page, the translations are not actually getting translated.

Example:

```<code>{{ ::'MyTranslationKey' | translate }}
</code>```

In 90% of the times the result is correct. In the other 10%, however, the rendered result is:

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

What's the reason for this and how can I fix it?

Edit:

This doesn't happen to elements that are inside ng-if, ng-repeat or directives - e.g. when they are inside a child scope.

答:
Try:

```<code><element translate>
    {{::'MyTranslationKey'}}
</element>
</code>```

Also, using the translate attribute instead of the filter gives you better performance (according to Pascal Precht, the creator of Angular Translate).

Body:
I am using Angular 1.x and it's Angular Translate module. Recently, I switched all my translation bindings from two-way to one-time. Everything worked fine, until one day, however, I noticed that sometimes if I started refreshing the page, the translations are not actually getting translated.

Example:

{{ ::'MyTranslationKey' | translate }}

In 90% of the times the result is correct. In the other 10%, however, the rendered result is:

MyTranslationKey

What's the reason for this and how can I fix it?

Edit:

This doesn't happen to elements that are inside ng-if, ng-repeat or directives - e.g. when they are inside a child scope.

Body:
Try:

<element translate>
    {{::'MyTranslationKey'}}
</element>

Also, using the translate attribute instead of the filter gives you better performance (according to Pascal Precht, the creator of Angular Translate).


问:
How to filter JSON data based on multiple criteria in JavaScript?
I am trying to filter out all records that don't contain values from the 5 arrays: ssn, spn, smft, ssl, svtv. The output is not correct because it only works in cases where the lists contain 1 element. The output array becomes empty when they contain multiple elements. I am trying to get records that don't contain one of the values from each list (OR). I think it doesn't work because it checks if each record doesn't contain all values in each list (AND). Any idea how to fix this?

jsonData

```<code>[{"sn": "234234234", "pn": "1014143", "mft": "hello world", "sl": "GG07", "vtv": "Yes"},{"sn": "324234234", "pn": "101423131143", "mft": "hello world 1", "sl": "GG08", "vtv": "Yes"}]
</code>```

query

```<code>ssn: ['T234834U', 'T23423423'],
spn: ['1014114', '21412342'],
smft: ['Sbasdfa', 'asdfaser'],
ssl: ['BB03', 'SFD04'],
svtv: ['Yes']
</code>```

Code

```<code>function getFiltered() {
    var query = {
        sn: ssn,
        pn: spn,
        mft: smft,
        sl: ssl,
        vtv: svtv
    }
    var filtered = find_in_object(jsonData, query)
}

function find_in_object(my_object, my_criteria) {
    return my_object.filter(function(obj) {
        return Object.keys(my_criteria).every(function(c) {
            return JSON.stringify(obj[c]).indexOf(my_criteria[c]) === -1
        })
    })
}
</code>```

答:
I would turn the json object in an array and then make a simple string comparison to each key.</p>

```<code>$(document).ready(function() {
    var data = [{"mft": "hello world", "pn": "1014143", "vtv": "Yes", "pn": "T1323F2342", "sl": "GG07"},{"mft": "hello 1", "pn": "234234", "vtv": "Yes", "pn": "T252345234", "sl": "SDF87"}];

    filterData(data[0]);
});

function filterData(data) {
    var newArray = [];
     for (var key in data) {
        var value   = data[key];
        console.log(key, value);

        if (key==="ssn" || key==="spn" || key==="smft"|| key==="ssl"|| key==="svtv") {
            var object  = {key:value};
            newArray.push(object)
        }
    }
    return newArray;
}
</code>```

Body:
I am trying to filter out all records that don't contain values from the 5 arrays: ssn, spn, smft, ssl, svtv. The output is not correct because it only works in cases where the lists contain 1 element. The output array becomes empty when they contain multiple elements. I am trying to get records that don't contain one of the values from each list (OR). I think it doesn't work because it checks if each record doesn't contain all values in each list (AND). Any idea how to fix this?

jsonData

[{"sn": "234234234", "pn": "1014143", "mft": "hello world", "sl": "GG07", "vtv": "Yes"},{"sn": "324234234", "pn": "101423131143", "mft": "hello world 1", "sl": "GG08", "vtv": "Yes"}]

query

ssn: ['T234834U', 'T23423423'],
spn: ['1014114', '21412342'],
smft: ['Sbasdfa', 'asdfaser'],
ssl: ['BB03', 'SFD04'],
svtv: ['Yes']

Code

function getFiltered() {
    var query = {
        sn: ssn,
        pn: spn,
        mft: smft,
        sl: ssl,
        vtv: svtv
    }
    var filtered = find_in_object(jsonData, query)
}

function find_in_object(my_object, my_criteria) {
    return my_object.filter(function(obj) {
        return Object.keys(my_criteria).every(function(c) {
            return JSON.stringify(obj[c]).indexOf(my_criteria[c]) === -1
        })
    })
}

Body:
I would turn the json object in an array and then make a simple string comparison to each key.

$(document).ready(function() {
    var data = [{"mft": "hello world", "pn": "1014143", "vtv": "Yes", "pn": "T1323F2342", "sl": "GG07"},{"mft": "hello 1", "pn": "234234", "vtv": "Yes", "pn": "T252345234", "sl": "SDF87"}];

    filterData(data[0]);
});

function filterData(data) {
    var newArray = [];
     for (var key in data) {
        var value   = data[key];
        console.log(key, value);

        if (key==="ssn" || key==="spn" || key==="smft"|| key==="ssl"|| key==="svtv") {
            var object  = {key:value};
            newArray.push(object)
        }
    }
    return newArray;
}


问:
Android Studio: keyboard shortcut to show the error on the current line?
The only way I have found to show the error of an underlined piece of code is to hover it with the mouse.

What is the keyboard shortcut to achieve this? (when the cursor is on the line in error)

答: On Mac that's Command-F1 (in the menu bar it's View -> Error Description). I think that's Control-F1 on Windows.</p>


问:
Ip address DNS and Domains
I'm a little confused about IP addresses.

I know that every web domain has an ip address.
Does the IP address represent the physical machine / host the website files are stored on?

Therefore when DNS lookup is performed, the domain's IP address is returned to the client. The client then uses this ip to contact the server that the web files reside on.

Is my understanding correct?

Many thanks

答: You're talking about HTTP protocol. Yes, FQDN (web domain) is resolved to IP address by DNS server. Client will connect to server IP address. Since you're probably using HTTP 1.1, HTTP request will contain also FQDN. This information is used by web server to perform several checks, like SSL certificate validation or Virtualhost management (several domains on a single IP address).</p>

Title: Ip address DNS and Domains


问:
Unexpected results with try, with open
Can't figure this one out and there doesn't seem to be any info on the web either. Tried it with both Python 2 and 3.

```<code>def load_settings():
    try:
        with open('settings.txt', 'r') as f:
            return f.read()
    except FileNotFoundError:
        with open('settings.txt', 'w') as f:
            f.write('default_settings')
        load_settings()
</code>```

I would expect the above function to return 'default_settings' given that settings.txt doesn't already exist. Instead it returns None.

答:
Change your code to this,</p>

```<code>def load_settings():
    try:
        with open('settings.txt', 'r') as f:
            return f.read()
    except FileNotFoundError:
        with open('settings.txt', 'w') as f:
            f.write('default_settings')
        return load_settings()
</code>```

Title: Unexpected results with try, with open

Body:
Can't figure this one out and there doesn't seem to be any info on the web either. Tried it with both Python 2 and 3.

def load_settings():
    try:
        with open('settings.txt', 'r') as f:
            return f.read()
    except FileNotFoundError:
        with open('settings.txt', 'w') as f:
            f.write('default_settings')
        load_settings()

I would expect the above function to return 'default_settings' given that settings.txt doesn't already exist. Instead it returns None.

Body:
Change your code to this,

def load_settings():
    try:
        with open('settings.txt', 'r') as f:
            return f.read()
    except FileNotFoundError:
        with open('settings.txt', 'w') as f:
            f.write('default_settings')
        return load_settings()


问:
Is it ok to change public storage folder name from 'public/storage' to 'public/public'?
Laravel recommends here to create symlink from public/storage to storage/app/public.  I'm looking for some inputs on whether renaming public/storage to public/public would cause any issues in other configurations or packages.

I am doing this because all my filenames in db are relative to storage/app folder.  I store it that way since I can then uniformly retrieve any file using storage_path() helper.  For example:

Protected file: storage/app/internal/secret.doc => filename in db = internal/secret.doc

Public file: storage/app/public/common.doc => filename in db = public/common.doc

Then to retrieve them:

```<code>// get filename 'internal/secret.doc' or 'public/common.doc'
$filename = DB::table('files')->find(1)->value('name'); // find file where id=1 and get only the name field
$file = storage_path('app/'.$filename);
</code>```

This way I don't have to wonder whether I need to add public/ folder while retrieving a specific file.  Also when I use asset() helper to generate urls to public files, again I can simply say:

```<code>$url = asset($filename)`;
</code>```

Whereas, if I continue to use public/storage as the symlinked folder then I would have to do:

```<code>$temp_filename = str_replace('public/', '', $filename);
$url = asset('storage/'.$temp_filename);
</code>```

Let me know if you have a different take or spot some issues with the renaming.

答: Once public/storage is sym linked to storage/app/public, you don't want your filepath in asset() to reference public.  Public folder is already the root of your webserver, and asset() assumes public directory base.  So your asset would be in asset("storage/$filename"). That actually pulls from storage/app/public/$filename.

Body:
Laravel recommends here to create symlink from public/storage to storage/app/public.  I'm looking for some inputs on whether renaming public/storage to public/public would cause any issues in other configurations or packages.

I am doing this because all my filenames in db are relative to storage/app folder.  I store it that way since I can then uniformly retrieve any file using storage_path() helper.  For example:

Protected file: storage/app/internal/secret.doc => filename in db = internal/secret.doc

Public file: storage/app/public/common.doc => filename in db = public/common.doc

Then to retrieve them:

// get filename 'internal/secret.doc' or 'public/common.doc'
$filename = DB::table('files')->find(1)->value('name'); // find file where id=1 and get only the name field
$file = storage_path('app/'.$filename);

This way I don't have to wonder whether I need to add public/ folder while retrieving a specific file.  Also when I use asset() helper to generate urls to public files, again I can simply say:

$url = asset($filename)`;

Whereas, if I continue to use public/storage as the symlinked folder then I would have to do:

$temp_filename = str_replace('public/', '', $filename);
$url = asset('storage/'.$temp_filename);

Let me know if you have a different take or spot some issues with the renaming.


问:
finding time slots present between start time and end time in python
We have csv file containing predefined time slots.
According to start time and end time provided by the user we want time slots present between the start time and end time.

eg

```<code>start time =11:00:00
end time=19:00:00

output- slot_no 2,3,4,5
</code>```

Body:
We have csv file containing predefined time slots.
According to start time and end time provided by the user we want time slots present between the start time and end time.

eg

start time =11:00:00
end time=19:00:00

output- slot_no 2,3,4,5

Body:
I think you need boolean indexing with loc and between for selecting column Slot_no, all columns and values are converted to_timedelta, also midnight is replaced to 24:00:00:

df = pd.DataFrame(
{'Slot_no':[1,2,3,4,5,6,7],
'start_time':['0:01:00','8:01:00','10:01:01','12:01:00','14:01:00','18:01:01','20:01:00'],
'end_time':['8:00:00','10:00:00','12:00:00','14:00:00','18:00:00','20:00:00','0:00:00']})
df = df.reindex_axis(['Slot_no','start_time','end_time'], axis=1)
df['start_time'] = pd.to_timedelta(df['start_time'])
df['end_time'] = pd.to_timedelta(df['end_time'].replace('0:00:00', '24:00:00'))
print (df)
   Slot_no  start_time        end_time
0        1    00:01:00 0 days 08:00:00
1        2    08:01:00 0 days 10:00:00
2        3    10:01:01 0 days 12:00:00
3        4    12:01:00 0 days 14:00:00
4        5    14:01:00 0 days 18:00:00
5        6    18:01:01 0 days 20:00:00
6        7    20:01:00 1 days 00:00:00

start = pd.to_timedelta('11:00:00')
end = pd.to_timedelta('19:00:00')

mask = df['start_time'].between(start, end) | df['end_time'].between(start, end)

s = df.loc[mask, 'Slot_no']
print (s)
2    3
3    4
4    5
5    6
Name: Slot_no, dtype: int64

L = df.loc[mask, 'Slot_no'].tolist()
print (L)
[3, 4, 5, 6]


问:
URL masking in asp.Net
I have two about pages in my website, "About.aspx" and "OtherAbout.aspx".
Which of these is navigate to is based on the user logged in.
I want to always display About.aspx as the URL even if we are on OtherAbout.aspx, is this possible?</p>

答: You can try to use the Server.Transfer method for this purpose</p>

ContentLicense: CC BY-SA 2.5

Title: URL masking in asp.Net


问:
Spring Data JPA: Invalid object name if use more than one Config Class in jUnit test
I receive SQLServerException when run test:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {OlmeFtpConfig.class, OlmeCapConfig.class}, loader = AnnotationConfigContextLoader.class)
public class FirmsRepositoryTest {

    @Autowired
    FirmsRepository firmsRepository;
    @Autowired
    ExtraDAO extraDAO;

    @Test
    public void save() throws Exception {

        int extraID = extraDAO.getMaxExtraID();

        FirmsEntity firmsEntity = new FirmsEntity();
            firmsEntity.setBoCode(DataGenerator.getNumberText(5));
            firmsEntity.setextraID(extraID);
            firmsEntity.setFirmShortName(DataGenerator.getNumberText(10));
            firmsEntity.setId(DataGenerator.getNumberBetween(9999,99999));

        FirmsEntity save = firmsRepository.save(firmsEntity);
        assertNotNull(save);

    }
</code>```

The full stack trace is:

```<code>org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy68.save(Unknown Source)
    at com.pivotal.olme.jpa.dao.FirmsRepositoryTest.save(FirmsRepositoryTest.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2123)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1911)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1887)
    at org.hibernate.loader.Loader.doQuery(Loader.java:932)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:319)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2205)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:61)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:51)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4071)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
    at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1230)
    at org.hibernate.internal.SessionImpl.access$1900(SessionImpl.java:203)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2787)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2761)
    at org.hibernate.internal.SessionImpl.get(SessionImpl.java:1071)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:290)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:170)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:69)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:874)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:860)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy45.merge(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:511)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 38 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'stg.FIRMS'.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1635)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:426)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:372)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:6276)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1793)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:184)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:159)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:284)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:83)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:83)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
    ... 86 more
</code>```

FirmsRepossitory looks like:

```<code>@Repository
public interface FirmsRepository extends CrudRepository<FirmsEntity, FirmsEntityPK> {

    @Modifying
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    FirmsEntity save(FirmsEntity firmsEntity);

}
</code>```

If I use only OlmeFtpConfig.class in @ContextConfiguration(classes = {OlmeFtpConfig.class} the test executes without any exception.

But in some test (where application works with two databases) i need to use both config classes. There are different datasources in each config class.

How to run test without exception and use two config class in @ContextConfiguration annotation? So I need springframework can find stg.FIRMS.

答:
Solved:

I moved one Spring config OlmeCapConfig.class into separate package.

In OlmeCapConfig.class specify carefully basePackages in @EnableJpaRepositories annotation:

@EnableJpaRepositories(basePackages={"com.pivotal.olme.cap_config",

```<code>"com.pivotal.olme.jpa.dao.cap",

"com.pivotal.olme.jpa.dao_impl.cap",

"com.pivotal.olme.jpa.entities.cap"},

entityManagerFactoryRef = "emFactoryCap",

transactionManagerRef = "txManagerCap")
</code>```

Body:
I receive SQLServerException when run test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {OlmeFtpConfig.class, OlmeCapConfig.class}, loader = AnnotationConfigContextLoader.class)
public class FirmsRepositoryTest {

    @Autowired
    FirmsRepository firmsRepository;
    @Autowired
    ExtraDAO extraDAO;

    @Test
    public void save() throws Exception {

        int extraID = extraDAO.getMaxExtraID();

        FirmsEntity firmsEntity = new FirmsEntity();
            firmsEntity.setBoCode(DataGenerator.getNumberText(5));
            firmsEntity.setextraID(extraID);
            firmsEntity.setFirmShortName(DataGenerator.getNumberText(10));
            firmsEntity.setId(DataGenerator.getNumberBetween(9999,99999));

        FirmsEntity save = firmsRepository.save(firmsEntity);
        assertNotNull(save);

    }

The full stack trace is:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy68.save(Unknown Source)
    at com.pivotal.olme.jpa.dao.FirmsRepositoryTest.save(FirmsRepositoryTest.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2123)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1911)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1887)
    at org.hibernate.loader.Loader.doQuery(Loader.java:932)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:319)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2205)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:61)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:51)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4071)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
    at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1230)
    at org.hibernate.internal.SessionImpl.access$1900(SessionImpl.java:203)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2787)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2761)
    at org.hibernate.internal.SessionImpl.get(SessionImpl.java:1071)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:290)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:170)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:69)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:874)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:860)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy45.merge(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:511)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 38 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'stg.FIRMS'.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1635)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:426)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:372)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:6276)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1793)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:184)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:159)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:284)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:83)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:83)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
    ... 86 more

FirmsRepossitory looks like:

@Repository
public interface FirmsRepository extends CrudRepository<FirmsEntity, FirmsEntityPK> {

    @Modifying
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    FirmsEntity save(FirmsEntity firmsEntity);

}

If I use only OlmeFtpConfig.class in @ContextConfiguration(classes = {OlmeFtpConfig.class} the test executes without any exception.

But in some test (where application works with two databases) i need to use both config classes. There are different datasources in each config class.

How to run test without exception and use two config class in @ContextConfiguration annotation? So I need springframework can find stg.FIRMS.

Body:
Solved:

I moved one Spring config OlmeCapConfig.class into separate package.

In OlmeCapConfig.class specify carefully basePackages in @EnableJpaRepositories annotation:

@EnableJpaRepositories(basePackages={"com.pivotal.olme.cap_config",

"com.pivotal.olme.jpa.dao.cap",

"com.pivotal.olme.jpa.dao_impl.cap",

"com.pivotal.olme.jpa.entities.cap"},

entityManagerFactoryRef = "emFactoryCap",

transactionManagerRef = "txManagerCap")