问:
How to organize spaces within Confluence (wiki)?
My company will be using Confluence to store and share our knowledge base on our IT systems, and could be used to cover topics from hardware administration to issues faced by programmers.

I am curious about the best practice for setting up the global spaces. Is it better to have one large, catch-all space for the entire IT department or should the information be broken into multiple spaces focused on a particular domain?

My concern is that breaking the information into several, smaller spaces will hinder the ability to link between related topics that might be categorized into different spaces. For example, we could have 2 spaces to cover our website and our main internal system.  However, there is plenty of overlap between the website apps and the main internal system.

Any advice that can be provided would be greatly appreciated!

答: We have a space for documenting our systems, policies, applications and frameworks in general, one for blogs (where employees write about technical interesting stuff) and one per project. The per project spaces are very small and very project specific. Often a topic of a project makes it into the blog (with the include tag) and from there in a more general way into the general space. Knowledge is moving. You just can't categorize it very strict.</p>


来源: stackexchange

问:
How i can edit sip message's header parameters (android-ngn-stack)
i'm making an android IMS client using android-ngn-stack , so i wanna to modifi some header parameters so how i can edit in this headers and remove parameter , add parameter , modifi parameter .

thanks a lot ,for example , how can i set max forwards to 100 instead of 70

答:
The max forwards value can be set using the method 'setMaxFDs' in the SipStack class:

  public boolean setMaxFDs(long max_fds) {
    return tinyWRAPJNI.SipStack_setMaxFDs(swigCPtr, this, max_fds);
  }
```

ContentLicense: CC BY-SA 3.0


问:
Exception in thread "main" java.sql.SQLException: Unable to open file
how to Solve this error and made load data query to open my file??

I get java.sql.SQLException: Unable to open file when trying to create statement from file. Code:

```<code>public class LoadData {

  public static void main(String[] args) throws Exception {

  File file=new File("C://Users//suriyan.s//Documents//suriyan//employees.csv");

  String filename = file.getAbsolutePath();

  System.out.println(filename);

  String tablename = "employee";

  Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "");

  // Load the data

  String qry = "LOAD DATA LOCAL INFILE '" + filename + "' INTO TABLE " + tablename + " FIELDS TERMINATED BY ','"
+ " LINES TERMINATED BY '\n';";

  Statement stmt = connection.createStatement();

  stmt.execute(qry);

  }
}
</code>```

答:
Documentation of DATA LOAD INFILE:

On Windows, specify backslashes in path names as forward slashes or doubled backslashes.

getAbsolutePath is returning single backslashes...

The Exception should be including the file name as it is interpreted by MySQL.

Try (remembering that "\\" is a single backslash in Java):

```<code>String filename = file.getAbsolutePath().replace("\\", "/");
System.out.println("File: \"" + filename + "\"");  // just for debugging
</code>```

Probably not the problem since accessing as root, but check:

Non-LOCAL load operations read text files located on the server. For security reasons, such operations require that you have the FILE privilege.

Body:
how to Solve this error and made load data query to open my file??

I get java.sql.SQLException: Unable to open file when trying to create statement from file. Code:

public class LoadData {

  public static void main(String[] args) throws Exception {

  File file=new File("C://Users//suriyan.s//Documents//suriyan//employees.csv");

  String filename = file.getAbsolutePath();

  System.out.println(filename);

  String tablename = "employee";

  Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "");

  // Load the data

  String qry = "LOAD DATA LOCAL INFILE '" + filename + "' INTO TABLE " + tablename + " FIELDS TERMINATED BY ','"
+ " LINES TERMINATED BY '\n';";

  Statement stmt = connection.createStatement();

  stmt.execute(qry);

  }
}

Body:
Documentation of DATA LOAD INFILE:

On Windows, specify backslashes in path names as forward slashes or doubled backslashes.

getAbsolutePath is returning single backslashes...

The Exception should be including the file name as it is interpreted by MySQL.

Try (remembering that "\\" is a single backslash in Java):

String filename = file.getAbsolutePath().replace("\\", "/");
System.out.println("File: \"" + filename + "\"");  // just for debugging

Probably not the problem since accessing as root, but check:

Non-LOCAL load operations read text files located on the server. For security reasons, such operations require that you have the FILE privilege.


问:
How do I put several functions into multiple namespaces without duplicating this code?
This is a followup to:

How do I put some code into multiple namespaces without duplicating this code?

I need to change the name of a namespace but want to keep backwards compatibility. The above solution suggests that I would have to do what is done there for each and every function:

```<code>namespace NewNamespaceName
{
        void print()
        {
                //do work...
        }
        // 50 other functions
}

namespace OldNameSpaceName
{
        using NewNamespaceName::print;
        // 50 other using declarations
}
</code>```

My question: Is there a simpler way to do this?

答:
You can simply do

```<code>namespace NewNamespaceName
{
        void print()
        {
                //do work...
        }
        // 50 other functions
}

namespace OldNameSpaceName
{
        using namespace NewNamespaceName;
}
</code>```

If NewNamespaceName has other things you would want to include, but not want them to be in OldNamespaceName, then just make another private namespace and import that into the old namespace

```<code>namespace NewNamespaceName
{
        namespace Private {
                void print() { ... }
                // 50 other functions
        }
}

namespace OldNameSpaceName
{
        using namespace NewNamespaceName::Private;
}
</code>```

Live example here https://wandbox.org/permlink/taRPm1hAd2FHbAYo

Body:
This is a followup to:

How do I put some code into multiple namespaces without duplicating this code?

I need to change the name of a namespace but want to keep backwards compatibility. The above solution suggests that I would have to do what is done there for each and every function:

namespace NewNamespaceName
{
        void print()
        {
                //do work...
        }
        // 50 other functions
}

namespace OldNameSpaceName
{
        using NewNamespaceName::print;
        // 50 other using declarations
}

My question: Is there a simpler way to do this?

Body:
You can simply do

namespace NewNamespaceName
{
        void print()
        {
                //do work...
        }
        // 50 other functions
}

namespace OldNameSpaceName
{
        using namespace NewNamespaceName;
}

If NewNamespaceName has other things you would want to include, but not want them to be in OldNamespaceName, then just make another private namespace and import that into the old namespace

namespace NewNamespaceName
{
        namespace Private {
                void print() { ... }
                // 50 other functions
        }
}

namespace OldNameSpaceName
{
        using namespace NewNamespaceName::Private;
}

Live example here https://wandbox.org/permlink/taRPm1hAd2FHbAYo


问:
How do you set up an x64 development environment based on gcc and eclipse?
I want to create 64 bit apps for (for example) 64 bit Windows 7. I've searched the web and found some help but couldn't get it to work.

Sorry I've taken so long to respond but I have tried to get the packages suggested to work but they're not easy or else I'm doing something wrong.

Anyway I ran across an environment called pellesc. It consists of a development environment around a compiler which traces is roots back to a 32-bit version that was once (according to Wikipedia) used to develop Quake. From what I've seen so far it's very promising and generates good code too!

答:
In spite of what other people are saying, Eclipse actually has very good support for C++, even in Windows: check out the CDT project. It's very mature and well-supported -- it works for C/C++ at least as well as Eclipse JDT works for Java.

As for the compiler itself, VonC is right, MinGW-w64 (but the mingw-w64 project is moving to mingw-w64.org so i suggest to use mingw-w64.org) is the best option. Eclipse CDT has built-in support for MinGW so as long as you install MinGW first, Eclipse should automatically detect it.

ContentLicense: CC BY-SA 2.5


问:
Hitting urls using threads
I am using threads to hit the urls in an arrayList. Need to store the not working urls in another arraylist. However the list of not-working urls changes everytime. Getting a malformed url exception. This exception occurs even for working urls (When tried hitting them manually). </p>

```<code>public class ThreadTest {

static int i = 0;
static ArrayList<String> arrayOfNotWorking = new ArrayList<>();

public static void main(String[] args) {
    ArrayList<String> arrayOfUrl = new ArrayList<>();

    ThreadTest threadTest = new ThreadTest();
    arrayOfUrl.add("https://www.parkbus.ca");
    arrayOfUrl.add("https://affectingchange.com/projects/fogo-island-");
    arrayOfUrl.add("https://skoll.socialedge.org/?293@@.1ad86d9e");
    arrayOfUrl.add("https://skollsocialedge.org?293@@.1ad86");
    arrayOfUrl.add("https://www.jitabangladesh.com");
    arrayOfUrl.add("https://www.ngobiz.org/picture/File/Social Enterpeuneur-The Case of Definition.pdf");
    arrayOfUrl.add("https://www.mealshare.ca/en/home/");
    arrayOfUrl.add("https://www.oecd.org/cfe/leed/38870491.pdf");
    arrayOfUrl.add("https://doi.org/10.1787/tour-2016-en");
    arrayOfUrl.add("https://www.youtube.com/user/PlaneterraCares");

    try {
        ExecutorService threadPool = Executors.newFixedThreadPool(arrayOfUrl.size());
        for (i = 0; i < arrayOfUrl.size(); i++) {
            threadPool.submit(new Runnable() {
                public void run() {
                    threadTest.hitUrl(arrayOfUrl.get(i));
                }
            });
        }
        threadPool.shutdown();
        threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        for (String string : arrayOfNotWorking) {
            System.out.println(string);
        }
    } catch (InterruptedException ex) {
        System.out.println(ex.getMessage());
    }
}

public static void hitUrl(String actualUrl) {
    try {
        URL obj = new URL(actualUrl);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();
        if (responseCode > 199 && responseCode < 400) {
        }
    } catch (Exception ex) {
        arrayOfNotWorking.add(actualUrl);
    }
}
</code>```

<p>}</p>

答:
java.net.malformedurlexception is thrown if invalid protocol is used or the url string could not be parsed due to in valid encoding.

Try to identify common problem with such invalid url's and then you can use URLEncoder or String class methods to format such url's

Title: Hitting urls using threads

Body:
I am using threads to hit the urls in an arrayList. Need to store the not working urls in another arraylist. However the list of not-working urls changes everytime. Getting a malformed url exception. This exception occurs even for working urls (When tried hitting them manually).

public class ThreadTest {

static int i = 0;
static ArrayList<String> arrayOfNotWorking = new ArrayList<>();

public static void main(String[] args) {
    ArrayList<String> arrayOfUrl = new ArrayList<>();

    ThreadTest threadTest = new ThreadTest();
    arrayOfUrl.add("https://www.parkbus.ca");
    arrayOfUrl.add("https://affectingchange.com/projects/fogo-island-");
    arrayOfUrl.add("https://skoll.socialedge.org/?293@@.1ad86d9e");
    arrayOfUrl.add("https://skollsocialedge.org?293@@.1ad86");
    arrayOfUrl.add("https://www.jitabangladesh.com");
    arrayOfUrl.add("https://www.ngobiz.org/picture/File/Social Enterpeuneur-The Case of Definition.pdf");
    arrayOfUrl.add("https://www.mealshare.ca/en/home/");
    arrayOfUrl.add("https://www.oecd.org/cfe/leed/38870491.pdf");
    arrayOfUrl.add("https://doi.org/10.1787/tour-2016-en");
    arrayOfUrl.add("https://www.youtube.com/user/PlaneterraCares");

    try {
        ExecutorService threadPool = Executors.newFixedThreadPool(arrayOfUrl.size());
        for (i = 0; i < arrayOfUrl.size(); i++) {
            threadPool.submit(new Runnable() {
                public void run() {
                    threadTest.hitUrl(arrayOfUrl.get(i));
                }
            });
        }
        threadPool.shutdown();
        threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        for (String string : arrayOfNotWorking) {
            System.out.println(string);
        }
    } catch (InterruptedException ex) {
        System.out.println(ex.getMessage());
    }
}

public static void hitUrl(String actualUrl) {
    try {
        URL obj = new URL(actualUrl);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();
        if (responseCode > 199 && responseCode < 400) {
        }
    } catch (Exception ex) {
        arrayOfNotWorking.add(actualUrl);
    }
}

}

ContentLicense: CC BY-SA 4.0


问:
Delete a row with the highest value of a specific column
I want to delete the row with the highest value on specific column

(I know that there are answers for that but none of them work for me for some reason)

All the coding I do in visual studio c# with SQL

MyDatabase: hours

```<code>Hours_Left | Hours_Spent | Time_Written | Mode | Time_Start | Time_End | Index
==============================================================================
aa         | bb          | cc           | dd   | ee         | ff       | 3
gg         | hh          | ii           | jj   | kk         | ll       | 4
mm         | nn          | oo           | pp   | qq         | rr       | 5
ss         | tt          | uu           | vv   | ww         | xx       | 6

[Hours_Left]   VARCHAR (MAX) NULL,
[Hours_Spent]  VARCHAR (MAX) NULL,
[Time_Written] VARCHAR (MAX) NULL,
[Mode]         VARCHAR (MAX) NULL,
[Time_Start]   VARCHAR (MAX) NULL,
[Time_End]     VARCHAR (MAX) NULL,
[Index]        INT           IDENTITY (1, 1) NOT NULL
</code>```

My Code:

```<code>if (con.State != ConnectionState.Open)
        {
            con.Close();
            con.Open();
        }
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = @"DELETE FROM hours WHERE Index = select max(Index) from hours limit 1";
        cmd.ExecuteNonQuery();
        con.Close();
        Display_Data();
</code>```

Don't work either when commandText is

```<code>@"DELETE TOP(1) FROM hours
  WHERE Index in
  (SELECT TOP(1) Index FROM hours
  ORDER BY Index DESC);";
</code>```

I want to delete the whole row of the highest index - i.e delete the row with the index 6 that it is the highest index

Error at:

```<code>cmd.ExecuteNonQuery();
</code>```

The error is:

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Index'. If
  this is intended as a part of a table hint, A WITH keyword and
  parenthesis are now required. See SQL Server Books Online for proper
  syntax.

答:
Try this;</p>

```<code>delete x
from dbo.[Hours] x
where exists(select 1 from dbo.[Hours] xx having MAX(xx.[Index])=x.[Index])
</code>```

Body:
I want to delete the row with the highest value on specific column

(I know that there are answers for that but none of them work for me for some reason)

All the coding I do in visual studio c# with SQL

MyDatabase: hours

Hours_Left | Hours_Spent | Time_Written | Mode | Time_Start | Time_End | Index
==============================================================================
aa         | bb          | cc           | dd   | ee         | ff       | 3
gg         | hh          | ii           | jj   | kk         | ll       | 4
mm         | nn          | oo           | pp   | qq         | rr       | 5
ss         | tt          | uu           | vv   | ww         | xx       | 6

[Hours_Left]   VARCHAR (MAX) NULL,
[Hours_Spent]  VARCHAR (MAX) NULL,
[Time_Written] VARCHAR (MAX) NULL,
[Mode]         VARCHAR (MAX) NULL,
[Time_Start]   VARCHAR (MAX) NULL,
[Time_End]     VARCHAR (MAX) NULL,
[Index]        INT           IDENTITY (1, 1) NOT NULL

My Code:

if (con.State != ConnectionState.Open)
        {
            con.Close();
            con.Open();
        }
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = @"DELETE FROM hours WHERE Index = select max(Index) from hours limit 1";
        cmd.ExecuteNonQuery();
        con.Close();
        Display_Data();

Don't work either when commandText is

@"DELETE TOP(1) FROM hours
  WHERE Index in
  (SELECT TOP(1) Index FROM hours
  ORDER BY Index DESC);";

I want to delete the whole row of the highest index - i.e delete the row with the index 6 that it is the highest index

Error at:

cmd.ExecuteNonQuery();

The error is:

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Index'. If
  this is intended as a part of a table hint, A WITH keyword and
  parenthesis are now required. See SQL Server Books Online for proper
  syntax.

Body:
Try this;

delete x
from dbo.[Hours] x
where exists(select 1 from dbo.[Hours] xx having MAX(xx.[Index])=x.[Index])


答:
Just use a namespace alias:</p>

```<code>namespace OldNameSpaceName = NewNameSpaceName;
</code>```

Title: How do I put several functions into multiple namespaces without duplicating this code?

Body:
Just use a namespace alias:

namespace OldNameSpaceName = NewNameSpaceName;


问:
How to fix the last element of LineLayout that it does not go beyond the boundaries of the screen?
I try make layout with two TextView and one Linear Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>
</code>```

But when the first element has many characters second text is hidding.

But I want to do so:

And when first text is short (or second element may not fill all aviliable area):

How i can do it? May be i need use RelativeLayout?
Big thanks for your answers!)

答:
```<code>     To have 10dp of space at left between widgets use
     android:marginLeft="10dp"
    To have 10dp of space at Right between widgets use
     android:marginRight="10dp"

    or you can use android:margin for having 10dp space on all four co-ordinate of the widget.

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:text="NOT HIDE TEXT"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
</FrameLayout>

which ever Widget will be last in hierarchy will be visible its like stack of widgets.
</code>```

Body:
I try make layout with two TextView and one Linear Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>

But when the first element has many characters second text is hidding.

But I want to do so:

And when first text is short (or second element may not fill all aviliable area):

How i can do it? May be i need use RelativeLayout?
Big thanks for your answers!)


问:
Creating EditText with button
I must create EditText with button inside and assign functions which will run after pressing the button. Then I would like to make it reusable - somehow add it as an element to my Activity. I was wondering about extending EditTextView and adding button and creating functions inside of it.
Any suggestions/ tutorials?</p>

答:
This is what you need to do:

```<code> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/relativeLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/edittext"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:completionHint="yourhint"
                android:dropDownHeight="match_parent"
                android:hint="From"
                android:padding="20dp"
                android:visibility="visible"
                />
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@id/image"
                android:layout_alignParentRight="true"
                />
        </RelativeLayout>

      </LinearLayout>
</code>```

And set OnClicklistener to the button in your OnCreate method like this:

```<code>Button image = (Button) findViewById(R.id.image);
image.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
//handle your on click event here
}
});
</code>```

Title: Creating EditText with button

Body:
This is what you need to do:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/relativeLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/edittext"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:completionHint="yourhint"
                android:dropDownHeight="match_parent"
                android:hint="From"
                android:padding="20dp"
                android:visibility="visible"
                />
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@id/image"
                android:layout_alignParentRight="true"
                />
        </RelativeLayout>

      </LinearLayout>

And set OnClicklistener to the button in your OnCreate method like this:

Button image = (Button) findViewById(R.id.image);
image.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
//handle your on click event here
}
});


问:
Fullscreen button of Video inside WebView not working
I'm trying to implement a subclass of WebChromeClient in order to have a working fullscreen button on youtube embed video links (ex: https://www.youtube.com/embed/dQw4w9WgXcQ) inside a WebView.

I basically simplified this repo, here are some snippets:

VideoWebChromeClient:

```<code>public class VideoWebChromeClient extends WebChromeClient {
    private boolean isVideoFullscreen = false;
    private View activityNonVideoView;
    private ViewGroup activityVideoView;
    private View videoViewContainer;
    private CustomViewCallback videoCallback;
    private Window videoWindow;

    public VideoWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, Window window) {
        this.activityNonVideoView = activityNonVideoView;
        this.activityVideoView =  activityVideoView;
        this.videoWindow = window;
    }

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
        Log.w("ENTER FULLSCREEN");
        videoCallback = callback;
        videoViewContainer = view;
        videoWindow.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        activityNonVideoView.setVisibility(View.GONE);
        activityVideoView.addView(videoViewContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        activityVideoView.setVisibility(View.VISIBLE);
        isVideoFullscreen = true;
    }

    @Override
    public void onHideCustomView() {
        if (!isVideoFullscreen) {
            return;
        }
        Log.w("EXIT FULLSCREEN");
        activityVideoView.setVisibility(View.GONE);
        activityVideoView.removeView(videoViewContainer);
        activityNonVideoView.setVisibility(View.VISIBLE);
        videoWindow.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        videoViewContainer = null;
        videoCallback.onCustomViewHidden();
        isVideoFullscreen = false;
    }

    public boolean onBackPressed() {
        onHideCustomView();
        return isVideoFullscreen;
    }
  }
</code>```

WebViewActivity

```<code>public class WebViewActivity extends BaseActivity {

    public static final String WEB_VIEW_URL_EXTRA = "URL";
    private boolean loadedFirstURL = true;
    private VideoWebChromeClient mWebChromeClient;

    @Bind(webview)
    WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(provideLayoutId());
        String url = (String) getIntent().getSerializableExtra(WEB_VIEW_URL_EXTRA);

        // Check if URL is YouTube / Vimeo
        if (RegexHelper.isVideoURL(url)){
            // Allow Fullscreen
            final View defaultLayout = findViewById(R.id.defaultLayout);
            final View fullscreenLayout = findViewById(R.id.fullscreenLayout);
            mWebChromeClient = new VideoWebChromeClient(defaultLayout, (ViewGroup) fullscreenLayout, getWindow());
            mWebView.setWebChromeClient(mWebChromeClient);

            // Block external links
            mWebView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (loadedFirstURL) {
                        loadedFirstURL = false;
                        return false;
                    }
                    return true;
                }
            });
        }
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl(url);
    }

        @Override
        public void onBackPressed() {
            if (!mWebChromeClient.onBackPressed())
            {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                }
                else {
                    super.onBackPressed();
                }
            }
        }
    }
</code>```

It works correctly on KitKat but not on Nougat (I have only those two devices to test on): when I tap the fullscreen button it sometimes goes into fullscreen, but most times it "flashes" and stays not-fullscreen.

And then, when it's actually in fullscreen mode, the button to exit fullscreen doesn't work (onHideCustomView is not called at all)

You can see that I put logs and noticed that when the "flash" happens, onHideCustomView is actually called right after onShowCustomView ("ENTER FULLSCREEN" then immediately "EXIT FULLSCREEN"), I don't understand why.

Thanks a lot if anyone can point me towards a solution

答:
I was also facing the same issue but I fixed it after spending hours on it.

All you have to do is set the UserAgent String of a KitKat device. And that is it!

```<code>private String userAgent = "Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/_BuildID_) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36";
mWebView.getSettings().setUserAgentString(userAgent);
</code>```

This will fix all the weird functioning of onShowCustomView() and onHideCustomView() on newer devices.
Hope it helps.

Body:
I'm trying to implement a subclass of WebChromeClient in order to have a working fullscreen button on youtube embed video links (ex: https://www.youtube.com/embed/dQw4w9WgXcQ) inside a WebView.

I basically simplified this repo, here are some snippets:

VideoWebChromeClient:

public class VideoWebChromeClient extends WebChromeClient {
    private boolean isVideoFullscreen = false;
    private View activityNonVideoView;
    private ViewGroup activityVideoView;
    private View videoViewContainer;
    private CustomViewCallback videoCallback;
    private Window videoWindow;

    public VideoWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, Window window) {
        this.activityNonVideoView = activityNonVideoView;
        this.activityVideoView =  activityVideoView;
        this.videoWindow = window;
    }

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
        Log.w("ENTER FULLSCREEN");
        videoCallback = callback;
        videoViewContainer = view;
        videoWindow.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        activityNonVideoView.setVisibility(View.GONE);
        activityVideoView.addView(videoViewContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        activityVideoView.setVisibility(View.VISIBLE);
        isVideoFullscreen = true;
    }

    @Override
    public void onHideCustomView() {
        if (!isVideoFullscreen) {
            return;
        }
        Log.w("EXIT FULLSCREEN");
        activityVideoView.setVisibility(View.GONE);
        activityVideoView.removeView(videoViewContainer);
        activityNonVideoView.setVisibility(View.VISIBLE);
        videoWindow.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        videoViewContainer = null;
        videoCallback.onCustomViewHidden();
        isVideoFullscreen = false;
    }

    public boolean onBackPressed() {
        onHideCustomView();
        return isVideoFullscreen;
    }
  }

WebViewActivity

public class WebViewActivity extends BaseActivity {

    public static final String WEB_VIEW_URL_EXTRA = "URL";
    private boolean loadedFirstURL = true;
    private VideoWebChromeClient mWebChromeClient;

    @Bind(webview)
    WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(provideLayoutId());
        String url = (String) getIntent().getSerializableExtra(WEB_VIEW_URL_EXTRA);

        // Check if URL is YouTube / Vimeo
        if (RegexHelper.isVideoURL(url)){
            // Allow Fullscreen
            final View defaultLayout = findViewById(R.id.defaultLayout);
            final View fullscreenLayout = findViewById(R.id.fullscreenLayout);
            mWebChromeClient = new VideoWebChromeClient(defaultLayout, (ViewGroup) fullscreenLayout, getWindow());
            mWebView.setWebChromeClient(mWebChromeClient);

            // Block external links
            mWebView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (loadedFirstURL) {
                        loadedFirstURL = false;
                        return false;
                    }
                    return true;
                }
            });
        }
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl(url);
    }

        @Override
        public void onBackPressed() {
            if (!mWebChromeClient.onBackPressed())
            {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                }
                else {
                    super.onBackPressed();
                }
            }
        }
    }

It works correctly on KitKat but not on Nougat (I have only those two devices to test on): when I tap the fullscreen button it sometimes goes into fullscreen, but most times it "flashes" and stays not-fullscreen.

And then, when it's actually in fullscreen mode, the button to exit fullscreen doesn't work (onHideCustomView is not called at all)

You can see that I put logs and noticed that when the "flash" happens, onHideCustomView is actually called right after onShowCustomView ("ENTER FULLSCREEN" then immediately "EXIT FULLSCREEN"), I don't understand why.

Thanks a lot if anyone can point me towards a solution

Body:
I was also facing the same issue but I fixed it after spending hours on it.

All you have to do is set the UserAgent String of a KitKat device. And that is it!

private String userAgent = "Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/_BuildID_) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36";
mWebView.getSettings().setUserAgentString(userAgent);

This will fix all the weird functioning of onShowCustomView() and onHideCustomView() on newer devices.
Hope it helps.


问:
Division and remainder of large numbers in JavaScript
I'm trying to get the remainder of a large number, for example:

1551690021432628813 % 64

But I find that the it's a couple of digits too long for JavaScript. i.e. it's getting rounded to zero.

Is there a way around this other than using a 26kb library like BigInteger.js?

答: There are some workarounds, but generally it is easiest to use a library Read more</p>


问:
how to make material2 tabs to use full page size
I want to create tab group having two tabs. Tab group should use the full page size and the individual tab should get equal width. Following is code that I am using

```<code><md-tab-group fxFlexFill>
    <md-tab>
        <ng-template md-tab-label>
            <md-icon>description</md-icon> Content Privileges
        </ng-template>
        Content Privileges
    </md-tab>
    <md-tab>
        <ng-template md-tab-label>
            <md-icon>flash_on</md-icon> Application Privileges
        </ng-template>
        Application Privileges
    </md-tab>
</md-tab-group>
</code>```

And here is the output of above

Tabs are not using the full width. And label icon and text is not aligned.

How can I do that?

答:
You can use following css to spread them evenly.

```<code>/deep/ .mat-tab-label {
    width: 50%;
}
</code>```

demo

Body:
I want to create tab group having two tabs. Tab group should use the full page size and the individual tab should get equal width. Following is code that I am using

<md-tab-group fxFlexFill>
    <md-tab>
        <ng-template md-tab-label>
            <md-icon>description</md-icon> Content Privileges
        </ng-template>
        Content Privileges
    </md-tab>
    <md-tab>
        <ng-template md-tab-label>
            <md-icon>flash_on</md-icon> Application Privileges
        </ng-template>
        Application Privileges
    </md-tab>
</md-tab-group>

And here is the output of above

Tabs are not using the full width. And label icon and text is not aligned.

How can I do that?

Body:
You can use following css to spread them evenly.

/deep/ .mat-tab-label {
    width: 50%;
}

demo


问:
How to get custom UserDetailService Object in Resource Server in spring-security-oauth2?
I have separate authorization server and resource server.
Authorization server is pointing to a separate database. I haves used CustomUserDetailService for user related information.
I have used CustomTokenEnhancer to have additional information apart from the token in the response.

```<code>@Configuration
public class OAuth2Configuration {

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {

        private static final String ENV_OAUTH = "authentication.oauth.";
        private static final String PROP_CLIENTID = "clientid";
        private static final String PROP_SECRET = "secret";
        private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";

        private RelaxedPropertyResolver propertyResolver;

        @Autowired
        private DataSource dataSource;

        @Autowired
        private CustomUserDetailService userDetailsService;

        @Bean
        public TokenStore tokenStore() {
            return new CustomTokenStore(dataSource);
        }

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints)
                throws Exception {
            endpoints
                    .tokenStore(tokenStore())
                    .userDetailsService(userDetailsService)

                    .tokenEnhancer(tokenEnhancer())
                    .accessTokenConverter(accessTokenConverter())

                    .authenticationManager(authenticationManager);
        }

        @Bean
        public TokenEnhancer tokenEnhancer() {
           return new CustomTokenEnhancer();
        }

        @Bean
        public DefaultAccessTokenConverter accessTokenConverter() {
            return new DefaultAccessTokenConverter();
        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer)
                throws Exception {
            oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
        }
    }

}
</code>```

CustomUserDetailService  Class:

```<code>@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private AccountRepository accountRepository;

    @Override
    public UserDetails loadUserByUsername(String username) {

        Account account = accountRepository.getByEmail(username);

        if(account == null) {
            throw new UsernameNotFoundException(username);
        }

        return new MyUserPrincipal(account);

    }
}
</code>```

CustomTokenEnhancer  Class:

```<code>public class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        MyUserPrincipal user = (MyUserPrincipal) authentication.getPrincipal();
        final Map<String, Object> additionalInfo = new HashMap<>();

        additionalInfo.put("user_information", user.getAccount());

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

        return accessToken;
    }

}
</code>```

Request/Response

```<code>http://localhost:9191/authserver/oauth/token

{
    "access_token": "fddb571e-224e-4cd7-974e-65104dd24b41",
    "token_type": "bearer",
    "refresh_token": "eb412b00-9e4e-4d6c-86d8-324d999b5f08",
    "expires_in": 100,
    "scope": "read write",
    "account_information": {
        "id": 14,
        "firstname": "name",
        "lastname": "lastname",

    }
}
</code>```

At resource server side, I have used RemoteTokenSerice to verify the the token presented by user is valid or not.

```<code>@Configuration
@EnableResourceServer
public class OAuthResourceConfig extends ResourceServerConfigurerAdapter {

    private TokenExtractor tokenExtractor = new BearerTokenExtractor();

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request,
                    HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
                if (tokenExtractor.extract(request) == null) {
                    SecurityContextHolder.clearContext();
                }
                filterChain.doFilter(request, response);
            }
        }, AbstractPreAuthenticatedProcessingFilter.class);
        http.csrf().disable();
        http.authorizeRequests().anyRequest().authenticated();
    }

    @Bean
    public AccessTokenConverter accessTokenConverter() {
        return new DefaultAccessTokenConverter();
    }

    @Bean
    @Primary
    public RemoteTokenServices remoteTokenServices(final @Value("${auth.server.url}") String checkTokenUrl,
            final @Value("${auth.server.clientId}") String clientId,
            final @Value("${auth.server.clientsecret}") String clientSecret) {

        final RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        remoteTokenServices.setCheckTokenEndpointUrl(checkTokenUrl+"?name=value");
        remoteTokenServices.setClientId(clientId);
        remoteTokenServices.setClientSecret(clientSecret);
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
        return remoteTokenServices;
    }

    }
</code>```

So It is working properly and when I make a request to resource server with token, it processes the request if the token is valid.  My question is I want to get Account object in resource server. I tried with below:

```<code> Account account = (Account)SecurityContextHolder.getContext().getAuthentication().getPrincipal()
</code>```

But it gives string and not the complete user define object and hence it throws the exception.How to get Account object in any controller in Resource server?

```<code>{
    "timestamp": 1499334657703,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "java.lang.ClassCastException",
    "message": "java.lang.String cannot be cast to Account",
    "path": "/secure"
    }
</code>```

I tried with link but is it possible to inject two token services, RemoteTokenService and CustomUserInfoTokenServices both?

Also I think here spring makes  internal call from Resource Server to Authorization Server (http://localhost:9191/authserver/oauth/check_token?token=d8dae984-7bd8-4aab-9990-a2c916dfe667) to validate the token.

Is there any way I can get those information in controller without calling this endpoint again.

Response:

```<code>{
    "exp": 1499333294,
    "account_information": {
        "accountid": 14,
        "firstname": "fname",
        "lastname": "lname",

    },
    "user_name": "abc@abc.com",
    "client_id": "clientId",
    "scope": [
        "read",
        "write"
    ]
}
</code>```

答:
I have overridden below method and added some logic.

```<code>public class CustomAccessTokenConverter extends DefaultAccessTokenConverter{

    private UserAuthenticationConverter userTokenConverter = new DefaultUserAuthenticationConverter();

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
        Map<String, String> parameters = new HashMap<String, String>();
        @SuppressWarnings("unchecked")
        Set<String> scope = new LinkedHashSet<String>(map.containsKey(SCOPE) ? (Collection<String>) map.get(SCOPE)
                : Collections.<String>emptySet());
        Authentication user = userTokenConverter.extractAuthentication(map);
        String clientId = (String) map.get(CLIENT_ID);
        parameters.put(CLIENT_ID, clientId);
        parameters.put("account_information", String.valueOf((((Map) map.get("account_information")).get("accountid"))));
        @SuppressWarnings("unchecked")
        Set<String> resourceIds = new LinkedHashSet<String>(map.containsKey(AUD) ? (Collection<String>) map.get(AUD)
                : Collections.<String>emptySet());

        Map<String, Serializable> extensions = new HashMap<String, Serializable>();
        extensions.put("account_information", (HashMap) map.get("account_information"));

        OAuth2Request request = new OAuth2Request(parameters, clientId, null, true, scope, resourceIds, null, null,
                extensions);
        return new OAuth2Authentication(request, user);
    }

}
</code>```

Resource Server Class

```<code>@Bean
    public AccessTokenConverter accessTokenConverter() {
        //return new DefaultAccessTokenConverter();
        return new CustomAccessTokenConverter();
    }

    @Bean
    @Primary
    public RemoteTokenServices remoteTokenServices(final @Value("${auth.server.url}") String checkTokenUrl,
            final @Value("${auth.server.clientId}") String clientId,
            final @Value("${auth.server.clientsecret}") String clientSecret) {

        final RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        remoteTokenServices.setCheckTokenEndpointUrl(checkTokenUrl+"?name=value");
        remoteTokenServices.setClientId(clientId);
        remoteTokenServices.setClientSecret(clientSecret);
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
        return remoteTokenServices;
    }
</code>```

Now I can get additional information in controller.

```<code>OAuth2Authentication authentication = (OAuth2Authentication)SecurityContextHolder.getContext().getAuthentication();

        Map<String, Serializable> map = authentication.getOAuth2Request().getExtensions();
</code>```

Body:
I have separate authorization server and resource server.
Authorization server is pointing to a separate database. I haves used CustomUserDetailService for user related information.
I have used CustomTokenEnhancer to have additional information apart from the token in the response.

@Configuration
public class OAuth2Configuration {

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {

        private static final String ENV_OAUTH = "authentication.oauth.";
        private static final String PROP_CLIENTID = "clientid";
        private static final String PROP_SECRET = "secret";
        private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";

        private RelaxedPropertyResolver propertyResolver;

        @Autowired
        private DataSource dataSource;

        @Autowired
        private CustomUserDetailService userDetailsService;

        @Bean
        public TokenStore tokenStore() {
            return new CustomTokenStore(dataSource);
        }

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints)
                throws Exception {
            endpoints
                    .tokenStore(tokenStore())
                    .userDetailsService(userDetailsService)

                    .tokenEnhancer(tokenEnhancer())
                    .accessTokenConverter(accessTokenConverter())

                    .authenticationManager(authenticationManager);
        }

        @Bean
        public TokenEnhancer tokenEnhancer() {
           return new CustomTokenEnhancer();
        }

        @Bean
        public DefaultAccessTokenConverter accessTokenConverter() {
            return new DefaultAccessTokenConverter();
        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer)
                throws Exception {
            oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
        }
    }

}

CustomUserDetailService  Class:

@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private AccountRepository accountRepository;

    @Override
    public UserDetails loadUserByUsername(String username) {

        Account account = accountRepository.getByEmail(username);

        if(account == null) {
            throw new UsernameNotFoundException(username);
        }

        return new MyUserPrincipal(account);

    }
}

CustomTokenEnhancer  Class:

public class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        MyUserPrincipal user = (MyUserPrincipal) authentication.getPrincipal();
        final Map<String, Object> additionalInfo = new HashMap<>();

        additionalInfo.put("user_information", user.getAccount());

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

        return accessToken;
    }

}

Request/Response

http://localhost:9191/authserver/oauth/token

{
    "access_token": "fddb571e-224e-4cd7-974e-65104dd24b41",
    "token_type": "bearer",
    "refresh_token": "eb412b00-9e4e-4d6c-86d8-324d999b5f08",
    "expires_in": 100,
    "scope": "read write",
    "account_information": {
        "id": 14,
        "firstname": "name",
        "lastname": "lastname",

    }
}

At resource server side, I have used RemoteTokenSerice to verify the the token presented by user is valid or not.

@Configuration
@EnableResourceServer
public class OAuthResourceConfig extends ResourceServerConfigurerAdapter {

    private TokenExtractor tokenExtractor = new BearerTokenExtractor();

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request,
                    HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
                if (tokenExtractor.extract(request) == null) {
                    SecurityContextHolder.clearContext();
                }
                filterChain.doFilter(request, response);
            }
        }, AbstractPreAuthenticatedProcessingFilter.class);
        http.csrf().disable();
        http.authorizeRequests().anyRequest().authenticated();
    }

    @Bean
    public AccessTokenConverter accessTokenConverter() {
        return new DefaultAccessTokenConverter();
    }

    @Bean
    @Primary
    public RemoteTokenServices remoteTokenServices(final @Value("${auth.server.url}") String checkTokenUrl,
            final @Value("${auth.server.clientId}") String clientId,
            final @Value("${auth.server.clientsecret}") String clientSecret) {

        final RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        remoteTokenServices.setCheckTokenEndpointUrl(checkTokenUrl+"?name=value");
        remoteTokenServices.setClientId(clientId);
        remoteTokenServices.setClientSecret(clientSecret);
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
        return remoteTokenServices;
    }

    }

So It is working properly and when I make a request to resource server with token, it processes the request if the token is valid.  My question is I want to get Account object in resource server. I tried with below:

 Account account = (Account)SecurityContextHolder.getContext().getAuthentication().getPrincipal()

But it gives string and not the complete user define object and hence it throws the exception.How to get Account object in any controller in Resource server?

{
    "timestamp": 1499334657703,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "java.lang.ClassCastException",
    "message": "java.lang.String cannot be cast to Account",
    "path": "/secure"
    }

I tried with link but is it possible to inject two token services, RemoteTokenService and CustomUserInfoTokenServices both?

Also I think here spring makes  internal call from Resource Server to Authorization Server (http://localhost:9191/authserver/oauth/check_token?token=d8dae984-7bd8-4aab-9990-a2c916dfe667) to validate the token.

Is there any way I can get those information in controller without calling this endpoint again.

Response:

{
    "exp": 1499333294,
    "account_information": {
        "accountid": 14,
        "firstname": "fname",
        "lastname": "lname",

    },
    "user_name": "abc@abc.com",
    "client_id": "clientId",
    "scope": [
        "read",
        "write"
    ]
}

Body:
I have overridden below method and added some logic.

public class CustomAccessTokenConverter extends DefaultAccessTokenConverter{

    private UserAuthenticationConverter userTokenConverter = new DefaultUserAuthenticationConverter();

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
        Map<String, String> parameters = new HashMap<String, String>();
        @SuppressWarnings("unchecked")
        Set<String> scope = new LinkedHashSet<String>(map.containsKey(SCOPE) ? (Collection<String>) map.get(SCOPE)
                : Collections.<String>emptySet());
        Authentication user = userTokenConverter.extractAuthentication(map);
        String clientId = (String) map.get(CLIENT_ID);
        parameters.put(CLIENT_ID, clientId);
        parameters.put("account_information", String.valueOf((((Map) map.get("account_information")).get("accountid"))));
        @SuppressWarnings("unchecked")
        Set<String> resourceIds = new LinkedHashSet<String>(map.containsKey(AUD) ? (Collection<String>) map.get(AUD)
                : Collections.<String>emptySet());

        Map<String, Serializable> extensions = new HashMap<String, Serializable>();
        extensions.put("account_information", (HashMap) map.get("account_information"));

        OAuth2Request request = new OAuth2Request(parameters, clientId, null, true, scope, resourceIds, null, null,
                extensions);
        return new OAuth2Authentication(request, user);
    }

}

Resource Server Class

@Bean
    public AccessTokenConverter accessTokenConverter() {
        //return new DefaultAccessTokenConverter();
        return new CustomAccessTokenConverter();
    }

    @Bean
    @Primary
    public RemoteTokenServices remoteTokenServices(final @Value("${auth.server.url}") String checkTokenUrl,
            final @Value("${auth.server.clientId}") String clientId,
            final @Value("${auth.server.clientsecret}") String clientSecret) {

        final RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        remoteTokenServices.setCheckTokenEndpointUrl(checkTokenUrl+"?name=value");
        remoteTokenServices.setClientId(clientId);
        remoteTokenServices.setClientSecret(clientSecret);
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter());
        return remoteTokenServices;
    }

Now I can get additional information in controller.

OAuth2Authentication authentication = (OAuth2Authentication)SecurityContextHolder.getContext().getAuthentication();

        Map<String, Serializable> map = authentication.getOAuth2Request().getExtensions();


问:
split a large file into small file based on pattern that can occur randomly Python
I have this large file with following content:

```<code>Column1 column2 column3
 345     367    Ramesh
 456     469    Ramesh
 300     301    Ramesh
 298     390    Naresh
 123     125    Suresh
 394     305    Suresh
 ......
 .....
</code>```

Now, I want to split this file into small files based on the name in column3. Like this:

File1: Ramesh.txt

```<code>column1 column2 column3
345     367      Ramesh
456     469      Ramesh
300     301      Ramesh
</code>```

File2: Naresh.txt

```<code>column1 column2 column3
298     390     Naresh
</code>```

File3: Suresh.txt

```<code>Column1 column2 column3
123     125      suresh
394     305      suresh
</code>```

and likewise.
I wrote the following python codes and it worked:

```<code>def split_file(file1):
source=open(file1)
l=[]
header=0
header_line=""
file_count=0
for line in source:
    line=line.rstrip()
    a=line.split()
    if header==0:
        header_line=line
        header+=1
    else:
        if a[-1] not in l:
            l.append(a[-1])
            file_count+=1
            if file_count>1:
                dest.close()
            else:
                pass
            dest=open(a[-1],'a')
            dest.write(header_line+"\n"+line+"\n")
        else:
            dest.write(line+"\n")
source.close()
dest.close()
</code>```

Now, my query is how can I modify these codes to work even if column3 is not sorted. For example:

```<code>Column1 column2 column3
345     367    Ramesh
123     125    Suresh
456     469    Ramesh
298     390    Naresh
300     301    Ramesh
394     305    Suresh
</code>```

Shall I generate random variable as values (to handle the output file) with the name in column3 as keys. And then use this dictionary to open the file everytime script encounters the key? Any suggestion will be appreciated.

答:
You can create a new file handle for each value of column3 and then just write it all to that file, e.g.:

```<code>import os

def split_file(path):
    file_handles = {}  # a map of file handles based on the last param
    target_path = os.path.dirname(path)  # get the location of the passed file path
    with open(path, "r") as f:  # open our input file for reading
        header = next(f)  # reads the first line to use as a header in all files
        for line in f:
            index = line.rfind(" ")  # replace with \t if you use tab-delimited files
            value = line[index+1:].rstrip()  # get the last value
            if not value:  # invalid entry, skip
                continue
            if value not in file_handles:  # we haven't started writing to this file
                # create a new file with the value of the last column
                handle = open(os.path.join(target_path, value + ".txt"), "a")
                handle.write(header)  # write the header to our new file
                file_handles[value] = handle  # store it to our file handles list
            else:
                handle = file_handles[value]
            handle.write(line)  # write the current line to the designated handle
    for handle in file_handles.values():  # close our output file handles
        handle.close()
</code>```

Then you can run it with a simple:

```<code>split_file("your_file.dat")
</code>```

And it will even respect file paths if you pass them.

Body:
I have this large file with following content:

Column1 column2 column3
 345     367    Ramesh
 456     469    Ramesh
 300     301    Ramesh
 298     390    Naresh
 123     125    Suresh
 394     305    Suresh
 ......
 .....

Now, I want to split this file into small files based on the name in column3. Like this:

File1: Ramesh.txt

column1 column2 column3
345     367      Ramesh
456     469      Ramesh
300     301      Ramesh

File2: Naresh.txt

column1 column2 column3
298     390     Naresh

File3: Suresh.txt

Column1 column2 column3
123     125      suresh
394     305      suresh

and likewise.
I wrote the following python codes and it worked:

def split_file(file1):
source=open(file1)
l=[]
header=0
header_line=""
file_count=0
for line in source:
    line=line.rstrip()
    a=line.split()
    if header==0:
        header_line=line
        header+=1
    else:
        if a[-1] not in l:
            l.append(a[-1])
            file_count+=1
            if file_count>1:
                dest.close()
            else:
                pass
            dest=open(a[-1],'a')
            dest.write(header_line+"\n"+line+"\n")
        else:
            dest.write(line+"\n")
source.close()
dest.close()

Now, my query is how can I modify these codes to work even if column3 is not sorted. For example:

Column1 column2 column3
345     367    Ramesh
123     125    Suresh
456     469    Ramesh
298     390    Naresh
300     301    Ramesh
394     305    Suresh

Shall I generate random variable as values (to handle the output file) with the name in column3 as keys. And then use this dictionary to open the file everytime script encounters the key? Any suggestion will be appreciated.

Body:
You can create a new file handle for each value of column3 and then just write it all to that file, e.g.:

import os

def split_file(path):
    file_handles = {}  # a map of file handles based on the last param
    target_path = os.path.dirname(path)  # get the location of the passed file path
    with open(path, "r") as f:  # open our input file for reading
        header = next(f)  # reads the first line to use as a header in all files
        for line in f:
            index = line.rfind(" ")  # replace with \t if you use tab-delimited files
            value = line[index+1:].rstrip()  # get the last value
            if not value:  # invalid entry, skip
                continue
            if value not in file_handles:  # we haven't started writing to this file
                # create a new file with the value of the last column
                handle = open(os.path.join(target_path, value + ".txt"), "a")
                handle.write(header)  # write the header to our new file
                file_handles[value] = handle  # store it to our file handles list
            else:
                handle = file_handles[value]
            handle.write(line)  # write the current line to the designated handle
    for handle in file_handles.values():  # close our output file handles
        handle.close()

Then you can run it with a simple:

split_file("your_file.dat")

And it will even respect file paths if you pass them.


问:
Android Displaying Snackbar Inside Fragment
I am running into some issues with displaying a snackbar inside a fragment. I can set one up fine for an activity but when I try in a fragment it just doesnt appear and no error is given.

Snackbar inside fragment

```<code>Snackbar snackbar = Snackbar.make(rootView, "Snackbar test", Snackbar.LENGTH_SHORT);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
</code>```

rootView in fragment

```<code>    rootView = inflater.inflate(R.layout.fragment_possible_recipes, container, false);
</code>```

Fragments XML

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></ListView>

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:paddingBottom="50dp"
    android:src="@drawable/no_result"
    android:visibility="gone"
    android:id="@+id/imageview"
    android:layout_gravity="center"/>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/filterButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_gravity="bottom|right"
    android:layout_marginBottom="63dp"
    android:layout_marginRight="16dp"
    android:clickable="true"
    android:src="@drawable/ic_filter"
    app:backgroundTint="@color/floatingButton" />

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

Main Activity XML

```<code><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->

<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout2">

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

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <FrameLayout
        android:id="@+id/container_body"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

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

<fragment
    android:id="@+id/fragment_navigation_drawer"
    android:name="com.example.rory.pocketchef.Fragments.FragmentDrawer"
    android:layout_width="@dimen/nav_drawer_width"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:layout="@layout/fragment_navigation_drawer"
    tools:layout="@layout/fragment_navigation_drawer" />

</android.support.v4.widget.DrawerLayout>
</code>```

答:
You can get it done far easily just by using it like following.

```<code>Snackbar.make(getActivity().findViewById(android.R.id.content),
           "text to show", Snackbar.LENGTH_LONG).show();
</code>```

This should work in anywhere within a Fragment.

PS. I know this is old but I leave it here anyway for future reference.

Body:
I am running into some issues with displaying a snackbar inside a fragment. I can set one up fine for an activity but when I try in a fragment it just doesnt appear and no error is given.

Snackbar inside fragment

Snackbar snackbar = Snackbar.make(rootView, "Snackbar test", Snackbar.LENGTH_SHORT);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();

rootView in fragment

    rootView = inflater.inflate(R.layout.fragment_possible_recipes, container, false);

Fragments XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></ListView>

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:paddingBottom="50dp"
    android:src="@drawable/no_result"
    android:visibility="gone"
    android:id="@+id/imageview"
    android:layout_gravity="center"/>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/filterButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_gravity="bottom|right"
    android:layout_marginBottom="63dp"
    android:layout_marginRight="16dp"
    android:clickable="true"
    android:src="@drawable/ic_filter"
    app:backgroundTint="@color/floatingButton" />

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

Main Activity XML

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout2">

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

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <FrameLayout
        android:id="@+id/container_body"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

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

<fragment
    android:id="@+id/fragment_navigation_drawer"
    android:name="com.example.rory.pocketchef.Fragments.FragmentDrawer"
    android:layout_width="@dimen/nav_drawer_width"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:layout="@layout/fragment_navigation_drawer"
    tools:layout="@layout/fragment_navigation_drawer" />

</android.support.v4.widget.DrawerLayout>

Body:
You can get it done far easily just by using it like following.

Snackbar.make(getActivity().findViewById(android.R.id.content),
           "text to show", Snackbar.LENGTH_LONG).show();

This should work in anywhere within a Fragment.

PS. I know this is old but I leave it here anyway for future reference.


问:
Center buttons in middle of image
I try to make buttons that will be in the middle of the picture, but the problem is that either those buttons are in the middle of the page or under the picture. Any suggestions how to fix it and what I do wrong? https://jsfiddle.net/m5g16vt7/

* {
  box-sizing: border-box
}

body {
  font-family: Verdana, sans-serif;
  margin: 0
}

imageSlide-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: pink;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8)
}

@media only screen and (max-width: 300px) {
  .prev,
  .next,
  .text {
    font-size: 11px
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="imageSlide-container">
  <img class="imageSlide" src="img_nature_wide.jpg" style="width: 100%">

  ❮
  ❯
</div></code>```

答:
Check this out. However if you want to place buttons center of the image just adjust your top margin and if left or right just change the text-align property.

      <meta name="viewport" content="width=device-width, initial-scale=1">
      * {box-sizing:border-box}
   body {font-family: Verdana,sans-serif;margin:0}

            imageSlide-container {
    max-width: 1000px;
    position: relative;
    margin: auto;
            }
       .buttons{
         text-align: center;
        margin-top: -45px;
       }
   .prev, .next {
    cursor: pointer;
        top: 50%;
    width: auto;
    padding: 16px;
    color: pink;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease;
    border-radius: 0 3px 3px 0;
   }
   .next {
    right: 0;
    border-radius: 3px 0 0 3px;
   }
   .prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8)
   }
            @media only screen and (max-width: 300px) {
     .prev, .next,.text {font-size: 11px}
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="imageSlide-container">
   <img class="imageSlide" src="https://www.w3schools.com/howto/img_nature_wide.jpg" style="width: 100%">

      <div class="buttons">
      ❮
      ❯
      </div>
</div></code>```

Title: Center buttons in middle of image

Body:
I try to make buttons that will be in the middle of the picture, but the problem is that either those buttons are in the middle of the page or under the picture. Any suggestions how to fix it and what I do wrong? https://jsfiddle.net/m5g16vt7/

* {
  box-sizing: border-box
}

body {
  font-family: Verdana, sans-serif;
  margin: 0
}

imageSlide-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: pink;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8)
}

@media only screen and (max-width: 300px) {
  .prev,
  .next,
  .text {
    font-size: 11px
  }
}

  ❮
  ❯

Body:
Check this out. However if you want to place buttons center of the image just adjust your top margin and if left or right just change the text-align property.

      <meta name="viewport" content="width=device-width, initial-scale=1">
      * {box-sizing:border-box}
   body {font-family: Verdana,sans-serif;margin:0}

            imageSlide-container {
    max-width: 1000px;
    position: relative;
    margin: auto;
            }
       .buttons{
         text-align: center;
        margin-top: -45px;
       }
   .prev, .next {
    cursor: pointer;
        top: 50%;
    width: auto;
    padding: 16px;
    color: pink;
    font-weight: bold;
    font-size: 18px;
    transition: 0.6s ease;
    border-radius: 0 3px 3px 0;
   }
   .next {
    right: 0;
    border-radius: 3px 0 0 3px;
   }
   .prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8)
   }
            @media only screen and (max-width: 300px) {
     .prev, .next,.text {font-size: 11px}
     }

<div class="imageSlide-container">
   <img class="imageSlide" src="https://www.w3schools.com/howto/img_nature_wide.jpg" style="width: 100%">

      <div class="buttons">
      <a class="prev" onclick="plusSlide-button(-1)">&#10094;</a>
      <a class="next" onclick="plusSlide-button(1)">&#10095;</a>
      </div>
</div>


问:
Cron Job PHP script execution time report
My question is simple: I want to know how long a PHP script is taking to execute. On top of this, I am executing it via cron. Now, I could do something via the PHP code itself to get the execution time start/end, however I wondered if there was something via the cron command that I could add to get that emailed to me, in milliseconds?

Currently I am using:

```<code>/usr/bin/php -q httpsdocs/folder/script.php > /dev/null 2>&1
</code>```

Which runs my script and stops all errors/output getting emailed to me. Can I change the above to get the execution time emailed to me somehow?

Thanks

答:
```<code>/usr/bin/time /usr/bin/php -q httpsdocs/folder/script.php
 | mail -s "Some Subject" you@youremailid.com
</code>```

<p>:-)</p>

Body:
My question is simple: I want to know how long a PHP script is taking to execute. On top of this, I am executing it via cron. Now, I could do something via the PHP code itself to get the execution time start/end, however I wondered if there was something via the cron command that I could add to get that emailed to me, in milliseconds?

Currently I am using:

/usr/bin/php -q httpsdocs/folder/script.php > /dev/null 2>&1

Which runs my script and stops all errors/output getting emailed to me. Can I change the above to get the execution time emailed to me somehow?

Thanks

Body:
/usr/bin/time /usr/bin/php -q httpsdocs/folder/script.php
 | mail -s "Some Subject" you@youremailid.com

:-)


问:
sql select update multiple column and check not null before update
I have two tables.

Table1 structure NOT NULL.

Table2 some value NULL.

I want update table2 to table1 ,

I want when select value if null don't update and skip next column have value to update.

My Table

```<code>table1      value(table1)      table2       value(table2)
t1ID        1234               t2ID         1234
t1Name      Bear               t2Name       null
t1Adress    87/25              t2Adress     99/77
t1Tel       01254798535        t2Tel        null
</code>```

My Code

```<code>UPDATE table1
SET t1Name = (SELECT t2Name
    FROM table2
    WHERE t2Name IS NOT NULL
    ),
    t1Adress = (SELECT t2Adress
    FROM table2
    WHERE t2Adress IS NOT NULL
    ),
    t1Tel = (SELECT t2Tel
    FROM table2
    WHERE t2Tel IS NOT NULL
    )
FROM table1,table2
WHERE t1ID = '1234' AND t2ID ='1234'
</code>```

When I execute I get error:

SQL error : Msg 512, Level 16, State 1, Line 1 Subquery returned more
  than 1 value.  This is not permitted when the subquery follows =, !=,
  <, <= , >, >= or when the subquery is used as an expression.  The
  statement has been terminated.

How can I fix it?

答:
The following query replaces the null values with table1 values and updates the rest from table2 values

```<code>UPDATE T1 SET T1.t1Name = IsNull(T2.t2Name,T1.t1Name),
              T1.t1Adress = IsNull(T2.t2Adress,T1.t1Adress),
              T1.t1Tel = IsNull(T2.t2Tel,T1.t1Tel)
        FROM table1 TI
                INNER JOIN table2 T2 ON T1.t1ID = T2.t2ID
</code>```

Try the following select query to check your result

```<code>SELECT T1.t1Name,IsNull(T2.t2Name,T1.t1Name),T1.t1Adress,IsNull(T2.t2Adress,T1.t1Adress),T1.t1Tel,IsNull(T2.t2Tel,T1.t1Tel)
        FROM table1 TI
                INNER JOIN table2 T2 ON T1.t1ID = T2.t2ID
</code>```

Body:
I have two tables.

Table1 structure NOT NULL.

Table2 some value NULL.

I want update table2 to table1 ,

I want when select value if null don't update and skip next column have value to update.

My Table

table1      value(table1)      table2       value(table2)
t1ID        1234               t2ID         1234
t1Name      Bear               t2Name       null
t1Adress    87/25              t2Adress     99/77
t1Tel       01254798535        t2Tel        null

My Code

UPDATE table1
SET t1Name = (SELECT t2Name
    FROM table2
    WHERE t2Name IS NOT NULL
    ),
    t1Adress = (SELECT t2Adress
    FROM table2
    WHERE t2Adress IS NOT NULL
    ),
    t1Tel = (SELECT t2Tel
    FROM table2
    WHERE t2Tel IS NOT NULL
    )
FROM table1,table2
WHERE t1ID = '1234' AND t2ID ='1234'

When I execute I get error:

SQL error : Msg 512, Level 16, State 1, Line 1 Subquery returned more
  than 1 value.  This is not permitted when the subquery follows =, !=,
  <, <= , >, >= or when the subquery is used as an expression.  The
  statement has been terminated.

How can I fix it?

Body:
The following query replaces the null values with table1 values and updates the rest from table2 values

UPDATE T1 SET T1.t1Name = IsNull(T2.t2Name,T1.t1Name),
              T1.t1Adress = IsNull(T2.t2Adress,T1.t1Adress),
              T1.t1Tel = IsNull(T2.t2Tel,T1.t1Tel)
        FROM table1 TI
                INNER JOIN table2 T2 ON T1.t1ID = T2.t2ID

Try the following select query to check your result

SELECT T1.t1Name,IsNull(T2.t2Name,T1.t1Name),T1.t1Adress,IsNull(T2.t2Adress,T1.t1Adress),T1.t1Tel,IsNull(T2.t2Tel,T1.t1Tel)
        FROM table1 TI
                INNER JOIN table2 T2 ON T1.t1ID = T2.t2ID


问:
Make child objects have their own type static container
Is it possible that each class object has its own static data store?

I mean, just to perform actions like:

```<code>class Program
{
    static void Main(string[] args)
    {
        var car1 = new Car();
        car1.Save(); ////saves in its own storage
        var own1 = new Owner();
        own1.Save(); //saves in its own storage as well
    }
}
</code>```

In code I tried, I get such error

'System.InvalidCastException`

at this place
var repo = (Repository<IEntity>) CurrentRepository;

Whats wrong and how could I make it?

Whole code is here:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //var car1 = new Car();
            //car1.Save(); ////saves in its own storage
            //var own1 = new Owner();
            //own1.Save(); //saves in its own storage as well    var car1 = new Car();

        }
    }

    public interface IEntity
    {
        long Id { get; }
    }

    public class Owner : Entity
    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public Car Car { get; set; }

        public Owner(string firstName, string lastName, Car car) : base(new Owner())
        {
            FirstName = firstName;
            LastName = lastName;
            Car = car;
        }

        public Owner() : base()
        {
        }

    }

    public class Car : Entity
    {
        public string Name { get; set; }
        public int Year { get; set; }

        public Car() : base()
        {

        }

        public Car(string name, int year)
        {
            Name = name;
            Year = year;
        }
    }

    public abstract class Entity : IEntity
    {
        public long Id { get; }

        public static object CurrentRepository { get; set; }

        public Entity(Entity ent)
        {
            Type entityType = ent.GetType();
            var instance = Activator.CreateInstance(typeof(Repository<>).MakeGenericType(entityType));

            CurrentRepository = instance;

        }

        public Entity()
        {
        }

        public void Save()
        {
            var repo = (Repository<IEntity>)CurrentRepository;
            repo.Save(this);
        }

        public void Delete()
        {
            var repo = (Repository<IEntity>)CurrentRepository;
            repo.Delete(this);
        }
    }

    public interface IRepository<T> where T : IEntity
    {
        void Save(T entity);
        void Delete(T entity);
        T Find(long id);
    }

    public class Repository<T> : IRepository<T> where T : class, IEntity
    {
        protected BaseStorage<T> CustomDataStorage;

        public Repository()
        {
            CustomDataStorage = new BaseStorage<T>();
        }

        public void Save(T entity)
        {
            CustomDataStorage.Add(entity);
        }

        public void Delete(T entity)
        {
            CustomDataStorage.Remove(entity);
        }

        public T Find(long id)
        {
            throw new NotImplementedException();
        }
    }
    public class BaseStorage<T> : IStorage<T>
    {
        List<T> data = new List<T>();

        public void Add(T entity)
        {
            data.Add(entity);
        }

        public void Remove(T entity)
        {
            throw new NotImplementedException();
        }
    }

    public interface IStorage<T>
    {
        void Add(T entity);
        void Remove(T entity);
    }

}
</code>```

答:
In code I tried, I get such error

'System.InvalidCastException`

at this place var repo = (Repository) CurrentRepository;

Whats wrong and how could I make it?

That's because you can't directly cast the CurrentRepository, a type of (Repository<Car> or Repository<Owner>) into a Repository<IEntity>.

See  to List<Interface>">here for more information on this...

To achieve what you wanted here, you could try it this way:

Make the Entity class generic (Entity<T>) and constraint the generic type as IEntity

Make the CurrentRepository a type of Repository<Entity<T>>

Move the static initialization of CurrentRepository from instance constructor to the static constructor.

Make the Owner and Car object subclass of Entity<T> with T refers to its own type making it a self referencing generics

Code:

```<code>public class Owner : Entity<Owner>
{
  ...
}

public class Car : Entity<Car>
{
  ...
}

public abstract class Entity<T> : IEntity
  where T: IEntity
{
  public long Id { get; }

  public static Repository<Entity<T>> CurrentRepository { get; set; }

  static Entity()
  {
    CurrentRepository = new Repository<Entity<T>>();
  }

  public Entity()
  {
  }

  public void Save()
  {
    CurrentRepository.Save(this);
  }

  public void Delete()
  {
    CurrentRepository.Delete(this);
  }
}
</code>```

Body:
Is it possible that each class object has its own static data store?

I mean, just to perform actions like:

class Program
{
    static void Main(string[] args)
    {
        var car1 = new Car();
        car1.Save(); ////saves in its own storage
        var own1 = new Owner();
        own1.Save(); //saves in its own storage as well
    }
}

In code I tried, I get such error

'System.InvalidCastException`

at this place
var repo = (Repository<IEntity>) CurrentRepository;

Whats wrong and how could I make it?

Whole code is here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //var car1 = new Car();
            //car1.Save(); ////saves in its own storage
            //var own1 = new Owner();
            //own1.Save(); //saves in its own storage as well    var car1 = new Car();

        }
    }

    public interface IEntity
    {
        long Id { get; }
    }

    public class Owner : Entity
    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public Car Car { get; set; }

        public Owner(string firstName, string lastName, Car car) : base(new Owner())
        {
            FirstName = firstName;
            LastName = lastName;
            Car = car;
        }

        public Owner() : base()
        {
        }

    }

    public class Car : Entity
    {
        public string Name { get; set; }
        public int Year { get; set; }

        public Car() : base()
        {

        }

        public Car(string name, int year)
        {
            Name = name;
            Year = year;
        }
    }

    public abstract class Entity : IEntity
    {
        public long Id { get; }

        public static object CurrentRepository { get; set; }

        public Entity(Entity ent)
        {
            Type entityType = ent.GetType();
            var instance = Activator.CreateInstance(typeof(Repository<>).MakeGenericType(entityType));

            CurrentRepository = instance;

        }

        public Entity()
        {
        }

        public void Save()
        {
            var repo = (Repository<IEntity>)CurrentRepository;
            repo.Save(this);
        }

        public void Delete()
        {
            var repo = (Repository<IEntity>)CurrentRepository;
            repo.Delete(this);
        }
    }

    public interface IRepository<T> where T : IEntity
    {
        void Save(T entity);
        void Delete(T entity);
        T Find(long id);
    }

    public class Repository<T> : IRepository<T> where T : class, IEntity
    {
        protected BaseStorage<T> CustomDataStorage;

        public Repository()
        {
            CustomDataStorage = new BaseStorage<T>();
        }

        public void Save(T entity)
        {
            CustomDataStorage.Add(entity);
        }

        public void Delete(T entity)
        {
            CustomDataStorage.Remove(entity);
        }

        public T Find(long id)
        {
            throw new NotImplementedException();
        }
    }
    public class BaseStorage<T> : IStorage<T>
    {
        List<T> data = new List<T>();

        public void Add(T entity)
        {
            data.Add(entity);
        }

        public void Remove(T entity)
        {
            throw new NotImplementedException();
        }
    }

    public interface IStorage<T>
    {
        void Add(T entity);
        void Remove(T entity);
    }

}

Body:
In code I tried, I get such error

'System.InvalidCastException`

at this place var repo = (Repository) CurrentRepository;

Whats wrong and how could I make it?

That's because you can't directly cast the CurrentRepository, a type of (Repository<Car> or Repository<Owner>) into a Repository<IEntity>.

See here for more information on this...

To achieve what you wanted here, you could try it this way:

Make the Entity class generic (Entity<T>) and constraint the generic type as IEntity

Make the CurrentRepository a type of Repository<Entity<T>>

Move the static initialization of CurrentRepository from instance constructor to the static constructor.

Make the Owner and Car object subclass of Entity<T> with T refers to its own type making it a self referencing generics

Code:

public class Owner : Entity<Owner>
{
  ...
}

public class Car : Entity<Car>
{
  ...
}

public abstract class Entity<T> : IEntity
  where T: IEntity
{
  public long Id { get; }

  public static Repository<Entity<T>> CurrentRepository { get; set; }

  static Entity()
  {
    CurrentRepository = new Repository<Entity<T>>();
  }

  public Entity()
  {
  }

  public void Save()
  {
    CurrentRepository.Save(this);
  }

  public void Delete()
  {
    CurrentRepository.Delete(this);
  }
}


问:
How to convert individual .php page to .html extension using URL rewriting
My .htaccess file code looks like </p>

```<code># -FrontPage-

<Limit GET POST>
order deny,allow
deny from all
allow from all
</Limit>
<Limit PUT DELETE>
order deny,allow
deny from all
</Limit>

ErrorDocument 404 /404.html

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+).html$ car.php?urlname=$1

RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+).html$ america-tour-packages.php?urlname=$1

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
</code>```

<p>This one is the individual page i have created in .php, and wanted to convert it's extension with .html using rewriting RULE but normal rule is not working, kindly suggest </p>

```<code>>RewriteEngine on
>RewriteRule ^([a-zA-Z0-9_-]+).html$ america-tour-packages.php?urlname=$1
</code>```

答:
try this:

```<code>RewriteEngine on
RewriteRule ^(.*)\.html$ $1.php
</code>```

when you will access test.html the system will look for: test.php

Body:
My .htaccess file code looks like

# -FrontPage-

<Limit GET POST>
order deny,allow
deny from all
allow from all
</Limit>
<Limit PUT DELETE>
order deny,allow
deny from all
</Limit>

ErrorDocument 404 /404.html

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+).html$ car.php?urlname=$1

RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+).html$ america-tour-packages.php?urlname=$1

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

This one is the individual page i have created in .php, and wanted to convert it's extension with .html using rewriting RULE but normal rule is not working, kindly suggest

>RewriteEngine on
>RewriteRule ^([a-zA-Z0-9_-]+).html$ america-tour-packages.php?urlname=$1

Body:
try this:

RewriteEngine on
RewriteRule ^(.*)\.html$ $1.php

when you will access test.html the system will look for: test.php