问:
Start activity crashes app else the app is minimazin
My app receives data from the database for authorization and registration.When startActivity(new Intent(this, Main.class));
line is commented out the app just minimize, and when uncommented it crashes.

Manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.littledev.test_v2">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Login">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Main">

        </activity>
    </application>

</manifest>
</code>```

Login.java

```<code>package com.example.littledev.test_v2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class Login extends AppCompatActivity {

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

    public void onLoginSuccess() {
        startActivity(new Intent(this, Main.class));
    }

    public void onLogin(View view){
        EditText eLogin = (EditText) findViewById(R.id.username);
        EditText ePass = (EditText) findViewById(R.id.password);
        String login = eLogin.getText().toString();
        String pass = ePass.getText().toString();
        Sql_bridge bridge = new Sql_bridge(this);
        bridge.execute("login",login,pass);
        finish();
    }

    public void onRegister(View view) {
        //startActivity(new Intent(this, Register.class));
    }
}
</code>```

Sql_bridge.java

```<code>package com.example.littledev.test_v2;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by LittleDev on 3/30/2017.
 */

public class Sql_bridge extends AsyncTask<String,Void,String> {
    private Context ctx;
    Sql_bridge (Context ctx)
    {
        this.ctx =ctx;
    }
    @Override
    protected void onPreExecute() {
        AlertDialog alertDialog;
        alertDialog = new AlertDialog.Builder(ctx).create();
        alertDialog.setTitle("Main Information....");
    }

    @Override
    protected String doInBackground(String... params) {
        String reg_url = "http://e-shops.hol.es/app_register";
        String log_url = "http://e-shops.hol.es/app_login";
        String method = params[0];
        if (method.equals("register")) {
            String name = params[1];
            String surname = params[2];
            String email = params[3];
            String password = params[4];
            try {
                URL url = new URL(reg_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream OS = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                        URLEncoder.encode("surname", "UTF-8") + "=" + URLEncoder.encode(surname, "UTF-8") + "&" +
                        URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
                        URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if (method.equals("login")){
            String login_name = params[1];
            String login_pass = params[2];
            try {
                URL url = new URL(log_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                String data = URLEncoder.encode("login","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
                        URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        Login login = new Login();
        switch (result) {
            case "Registered":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                break;
            case "Login":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                login.onLoginSuccess();

                break;
            default:
                Toast.makeText(ctx, "Failed", Toast.LENGTH_LONG).show();
                break;
        }

    }
}
</code>```

Logcat

```<code>03-30 15:11:48.323 9997-9997/com.example.littledev.test_v2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.littledev.test_v2, PID: 9997
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4298)
                                                                                at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4245)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                                                at android.app.Activity.startActivity(Activity.java:4582)
                                                                                at android.app.Activity.startActivity(Activity.java:4550)
                                                                                at com.example.littledev.test_v2.Login.onLoginSuccess(Login.java:19)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:131)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:23)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                at android.os.AsyncTask.access$500(AsyncTask.java:180)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7329)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
</code>```

I realy don`t have a clue why it crashes.

答:
as @sasilKumar and @Jaydeep Patel said:
in onLogin() method in your Login.java you called finish() immediately after starting Sql_bridge Async task instance and that was early before invoking of onLoginSuccess() after obtaing resultin onPostExecute(String result) on the MainThread and that what throws that exception.

Body:
My app receives data from the database for authorization and registration.When startActivity(new Intent(this, Main.class));
line is commented out the app just minimize, and when uncommented it crashes.

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.littledev.test_v2">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Login">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Main">

        </activity>
    </application>

</manifest>

Login.java

package com.example.littledev.test_v2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class Login extends AppCompatActivity {

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

    public void onLoginSuccess() {
        startActivity(new Intent(this, Main.class));
    }

    public void onLogin(View view){
        EditText eLogin = (EditText) findViewById(R.id.username);
        EditText ePass = (EditText) findViewById(R.id.password);
        String login = eLogin.getText().toString();
        String pass = ePass.getText().toString();
        Sql_bridge bridge = new Sql_bridge(this);
        bridge.execute("login",login,pass);
        finish();
    }

    public void onRegister(View view) {
        //startActivity(new Intent(this, Register.class));
    }
}

Sql_bridge.java

package com.example.littledev.test_v2;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by LittleDev on 3/30/2017.
 */

public class Sql_bridge extends AsyncTask<String,Void,String> {
    private Context ctx;
    Sql_bridge (Context ctx)
    {
        this.ctx =ctx;
    }
    @Override
    protected void onPreExecute() {
        AlertDialog alertDialog;
        alertDialog = new AlertDialog.Builder(ctx).create();
        alertDialog.setTitle("Main Information....");
    }

    @Override
    protected String doInBackground(String... params) {
        String reg_url = "http://e-shops.hol.es/app_register";
        String log_url = "http://e-shops.hol.es/app_login";
        String method = params[0];
        if (method.equals("register")) {
            String name = params[1];
            String surname = params[2];
            String email = params[3];
            String password = params[4];
            try {
                URL url = new URL(reg_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream OS = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                        URLEncoder.encode("surname", "UTF-8") + "=" + URLEncoder.encode(surname, "UTF-8") + "&" +
                        URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
                        URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if (method.equals("login")){
            String login_name = params[1];
            String login_pass = params[2];
            try {
                URL url = new URL(log_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                String data = URLEncoder.encode("login","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
                        URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String response = "";
                String line;
                while ((line = bufferedReader.readLine())!=null)
                {
                    response+= line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response;

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        Login login = new Login();
        switch (result) {
            case "Registered":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                break;
            case "Login":
                Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
                login.onLoginSuccess();

                break;
            default:
                Toast.makeText(ctx, "Failed", Toast.LENGTH_LONG).show();
                break;
        }

    }
}

Logcat

03-30 15:11:48.323 9997-9997/com.example.littledev.test_v2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.littledev.test_v2, PID: 9997
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4298)
                                                                                at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:4245)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                                                at android.app.Activity.startActivity(Activity.java:4582)
                                                                                at android.app.Activity.startActivity(Activity.java:4550)
                                                                                at com.example.littledev.test_v2.Login.onLoginSuccess(Login.java:19)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:131)
                                                                                at com.example.littledev.test_v2.Sql_bridge.onPostExecute(Sql_bridge.java:23)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                at android.os.AsyncTask.access$500(AsyncTask.java:180)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7329)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

I realy don`t have a clue why it crashes.


来源: stackexchange

问:
Non Exhaustive List When Handling Errors Inside a Class Function in Swift
Running the following snippet in a playground / project:

```<code>class Piece {
    enum ParseError: Error {
        case unknown(string: String)
    }

    class func parse(string: String) throws {
        throw ParseError.unknown(string: string)
    }
}

class Board {
    class func parse(string: String) {
        do {
            try Piece.parse(string: string)
        } catch Piece.ParseError.unknown(let string) {
            print(string)
        }
    }
}
</code>```

Gives a Swift Compiler Error:

Errors thrown from here are not handled because the enclosing catch is not exhaustive

The following works fine:

```<code>enum ParseError: Error {
    case unknown(string: String)
}

func parse(string: String) throws {
    throw ParseError.unknown(string: string)
}

do {
    try parse(string: "rook")
} catch ParseError.unknown(let string) {
    print(string)
}
</code>```

Running Xcode 8.3 / Swift 3.1

What's the reason for the error?

答:
As said by the language guide (emphasis mine):

The catch clauses don’t have to handle every possible error that the code in its do clause can throw. If none of the catch clauses handle the error, the error propagates to the surrounding scope. However, the error must be handled by some surrounding scope [...]

Therefore, your example

```<code>class Board {
    class func parse(string: String) {
        do {
            try Piece.parse(string: string)
        } catch Piece.ParseError.unknown(let string) {
            print(string)
        }
    }
}
</code>```

is illegal – because combined, the do-catch block and the enclosing scope (the actual method itself) don't exhaustively handle every possible error that Piece.parse(string: string) can throw (remember that a throwing function can throw any error type that conforms to the Error protocol).

You would either want to add a "catch all" block to your do-catch in order to handle any other thrown error:

```<code>do {
    try Piece.parse(string: string)
} catch Piece.ParseError.unknown(let string) {
    print(string)
} catch {
    // do error handling for any miscellaneous errors here.
    print(error)
}
</code>```

Or make parse(string:) a throwing method in order to propagate any uncaught errors back to the caller.

```<code>class func parse(string: String) throws {
    // ...
}
</code>```

The only reason why

```<code>enum ParseError: Error {
    case unknown(string: String)
}

func parse(string: String) throws {
    throw ParseError.unknown(string: string)
}

do {
    try parse(string: "rook")
} catch ParseError.unknown(let string) {
    print(string)
}
</code>```

compiles at the top-level of a main.swift file is simply because that scope is special. It can catch any uncaught error, and upon doing so will invoke fatalError() with a description of that error.

I cannot find any official documentation for this, but if you look in the Standard Library's ErrorType.swift file, you'll see the following function:

```<code>/// Invoked by the compiler when code at top level throws an uncaught error.
@_silgen_name("swift_errorInMain")
public func _errorInMain(_ error: Error) {
  fatalError("Error raised at top level: \(String(reflecting: error))")
}
</code>```

And if we examine the IR emitted for a simplified version of the above code, sure enough we can see that the compiler inserts a call to swift_errorInMain upon an uncaught error being thrown.

With a playground, you get a similar behaviour in that the compiler allows uncaught errors at the top-level – although in the case of an error being thrown, the playground just seems to silently terminate without displaying a fatal error message.

It's difficult to investigate further due to the fact that Swift playgrounds run code in their own special environment, therefore meaning that the runtime behaviour can wildly differ from code compiled with swiftc. Really, you should never use a playground to test the actual behaviour of Swift code.

ContentLicense: CC BY-SA 3.0

Body:
Running the following snippet in a playground / project:

class Piece {
    enum ParseError: Error {
        case unknown(string: String)
    }

    class func parse(string: String) throws {
        throw ParseError.unknown(string: string)
    }
}

class Board {
    class func parse(string: String) {
        do {
            try Piece.parse(string: string)
        } catch Piece.ParseError.unknown(let string) {
            print(string)
        }
    }
}

Gives a Swift Compiler Error:

Errors thrown from here are not handled because the enclosing catch is not exhaustive

The following works fine:

enum ParseError: Error {
    case unknown(string: String)
}

func parse(string: String) throws {
    throw ParseError.unknown(string: string)
}

do {
    try parse(string: "rook")
} catch ParseError.unknown(let string) {
    print(string)
}

Running Xcode 8.3 / Swift 3.1

What's the reason for the error?

Body:
As said by the language guide (emphasis mine):

The catch clauses don’t have to handle every possible error that the code in its do clause can throw. If none of the catch clauses handle the error, the error propagates to the surrounding scope. However, the error must be handled by some surrounding scope [...]

Therefore, your example

class Board {
    class func parse(string: String) {
        do {
            try Piece.parse(string: string)
        } catch Piece.ParseError.unknown(let string) {
            print(string)
        }
    }
}

is illegal – because combined, the do-catch block and the enclosing scope (the actual method itself) don't exhaustively handle every possible error that Piece.parse(string: string) can throw (remember that a throwing function can throw any error type that conforms to the Error protocol).

You would either want to add a "catch all" block to your do-catch in order to handle any other thrown error:

do {
    try Piece.parse(string: string)
} catch Piece.ParseError.unknown(let string) {
    print(string)
} catch {
    // do error handling for any miscellaneous errors here.
    print(error)
}

Or make parse(string:) a throwing method in order to propagate any uncaught errors back to the caller.

class func parse(string: String) throws {
    // ...
}

The only reason why

enum ParseError: Error {
    case unknown(string: String)
}

func parse(string: String) throws {
    throw ParseError.unknown(string: string)
}

do {
    try parse(string: "rook")
} catch ParseError.unknown(let string) {
    print(string)
}

compiles at the top-level of a main.swift file is simply because that scope is special. It can catch any uncaught error, and upon doing so will invoke fatalError() with a description of that error.

I cannot find any official documentation for this, but if you look in the Standard Library's ErrorType.swift file, you'll see the following function:

/// Invoked by the compiler when code at top level throws an uncaught error.
@_silgen_name("swift_errorInMain")
public func _errorInMain(_ error: Error) {
  fatalError("Error raised at top level: \(String(reflecting: error))")
}

And if we examine the IR emitted for a simplified version of the above code, sure enough we can see that the compiler inserts a call to swift_errorInMain upon an uncaught error being thrown.

With a playground, you get a similar behaviour in that the compiler allows uncaught errors at the top-level – although in the case of an error being thrown, the playground just seems to silently terminate without displaying a fatal error message.

It's difficult to investigate further due to the fact that Swift playgrounds run code in their own special environment, therefore meaning that the runtime behaviour can wildly differ from code compiled with swiftc. Really, you should never use a playground to test the actual behaviour of Swift code.


问:
Windows cmd - Interact with user input prompt [npm] using oneliner
I am trying to pass in an input as one line to an user-input prompt, but am having difficulty working out how to do it correctly.

Specifically I am trying to login to npm using npm adduser (npm login is its alias)

When it's a singular value it works but this only gets me so far: echo exampleuser| npm adduser

Username: exampleuser
Password:
Password: npm ERR! cb() never called!

But unfortunately when I try to add multiple commands together it goes awry. Eg:

echo 'exampleuser examplepassword ex@email.com'| npm adduser or

echo 'exampleuser\r\nexamplepassword\r\nex@email.com'| npm adduser or

echo 'exampleuser&& echo examplepassword&& echo ex@email.com'| npm adduser, etc...

Gets back errors along the lines of

Username: 'exampleuser examplepassword'
npm WARN Name must be lowercase
Username:
Username: npm ERR! cb() never called!

Any suggestions would be greatly appreciated.

答:
to pass several values, you have to pass several lines. echo isn't able to echo a line break, so you have to use several echo's

```<code>(
echo exampleUser
echo hisPassword
echo ex@email.com
)|npm adduser
</code>```

As a single line:

```<code>(echo exampleUser&echo hisPassword&echo ex@email.com)|npm adduser
</code>```

(note: NO space before &!)

(Note: this is how to pass several parameters; Can't test, if npm will actually accept them)

Body:
to pass several values, you have to pass several lines. echo isn't able to echo a line break, so you have to use several echo's

(
echo exampleUser
echo hisPassword
echo ex@email.com
)|npm adduser

As a single line:

(echo exampleUser&echo hisPassword&echo ex@email.com)|npm adduser

(note: NO space before &!)

(Note: this is how to pass several parameters; Can't test, if npm will actually accept them)


问:
Detecting colour of a specific x and y coordinate of an image in MATLAB
I'm trying to obtain the colour of a specific coordinate on an image. For example: X is an image with size width:300 and height:300. I would like to know the colour at x:10 and y:10 coordinate. I couldn't write any code because I don't know if this is even possible in matlab?

Thank you.

答:
Of course you can do such operations on MATLAB:

```<code>A = imread('yourimage.png');

X = 10;
Y = 10;

color = A(Y, X, :);
color = squeeze(color);
</code>```

color will then be a row vector containing the RGB values of that pixel (from 0 to 255). Of course the Y image axis is oriented towards the opposite verse than the Cartesian one.

Body:
Of course you can do such operations on MATLAB:

A = imread('yourimage.png');

X = 10;
Y = 10;

color = A(Y, X, :);
color = squeeze(color);

color will then be a row vector containing the RGB values of that pixel (from 0 to 255). Of course the Y image axis is oriented towards the opposite verse than the Cartesian one.


问:
How to override models __str__ method so you would have different presentation in admin panel
What is the clean way to override __str__ method of a model so that admin and super admin see it differently in admin panel.

In my model class I want to check if user is is_superuser or not so I could show different things in __str__ method.

Point of this is the situation that my super admin can see all objects belonging to everyone but normal admin can only see his objects so if I write:

def __str__(self):

```<code>   return "Object: %s , created by: %s"%(self.title,self.created_by)
</code>```

My super admin will be able to see who is the creator of object in panel, and that is fine.
But my normal admin will see only his objects and not needed message saying that he is the creator.
That is why I would need a different return in __str__ method for normal admins.

答:
Instead of doing it in __str__ method, you can specify which fields to display in the list in admin.

```<code>class MyModelAdmin(admin.ModelAdmin):
    def get_list_display(self, request):
        if request.user.is_superuser:
            return ('title' , 'created_by')
        else:
            return ('title',)
admin.site.register(MyModel, MyModelAdmin)
</code>```

and then update your __str__ method to return just the title.

Body:
What is the clean way to override __str__ method of a model so that admin and super admin see it differently in admin panel.

In my model class I want to check if user is is_superuser or not so I could show different things in __str__ method.

Point of this is the situation that my super admin can see all objects belonging to everyone but normal admin can only see his objects so if I write:

def __str__(self):

   return "Object: %s , created by: %s"%(self.title,self.created_by)

My super admin will be able to see who is the creator of object in panel, and that is fine.
But my normal admin will see only his objects and not needed message saying that he is the creator.
That is why I would need a different return in __str__ method for normal admins.

Body:
Instead of doing it in __str__ method, you can specify which fields to display in the list in admin.

class MyModelAdmin(admin.ModelAdmin):
    def get_list_display(self, request):
        if request.user.is_superuser:
            return ('title' , 'created_by')
        else:
            return ('title',)
admin.site.register(MyModel, MyModelAdmin)

and then update your __str__ method to return just the title.


问:
Azure Blob Storage Generates Invalid Shared Access Signature
I am using below code sample to create shared access signatures for private files stored inside Azure Blob storage. The generated Url is sometimes valid but most of the time is invalid due to authentication error.

```<code>public async Task<string> GetFileUrl(string containerName, string fileName)
{
     ICloudBlob blob = await GetBlob(containerName, fileName);

     string signature = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
     {
           SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
           SharedAccessExpiryTime = DateTime.UtcNow.AddDays(7),
           Permissions = SharedAccessBlobPermissions.Read
     });

     return blob.Uri.AbsoluteUri + signature;
}
</code>```

I receive following response when the formed SAS is not valid,

```<code><Error>
    <Code>AuthenticationFailed</Code>
    <Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.RequestId:</Message>
    <AuthenticationErrorDetail>Signature fields not well formed.</AuthenticationErrorDetail>
</Error>
</code>```

Following are the parameters for a URL that is failing to authenticate

```<code>sv=2016-05-31
sig=SbVzxo+dv28FvJP+Z9b1w6uvWUT72Pw1BSe3MIRooM0=
st=2017-03-30T11:52:35Z
se=2017-04-06T11:57:35Z
sr=b
sp=r
</code>```

答:
I found the problem.
I did not mention in question but the code for generation SAS is called via HTTTP client and the URL for accessing the Blob with SAS is located in Location header of the response.

I was trying to retrieve the URL with

```<code>response.Headers.Location.ToString();
</code>```

but, I should have used

```<code>response.Headers.Location.OriginalString.ToString();
</code>```

According to Microsoft the Location.ToString() returns the canonically unescaped form of the URI. That is why my signature was invalid and there were characters like + inside it.

Body:
I am using below code sample to create shared access signatures for private files stored inside Azure Blob storage. The generated Url is sometimes valid but most of the time is invalid due to authentication error.

public async Task<string> GetFileUrl(string containerName, string fileName)
{
     ICloudBlob blob = await GetBlob(containerName, fileName);

     string signature = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
     {
           SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
           SharedAccessExpiryTime = DateTime.UtcNow.AddDays(7),
           Permissions = SharedAccessBlobPermissions.Read
     });

     return blob.Uri.AbsoluteUri + signature;
}

I receive following response when the formed SAS is not valid,

<Error>
    AuthenticationFailed
    <Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.RequestId:</Message>
    <AuthenticationErrorDetail>Signature fields not well formed.</AuthenticationErrorDetail>
</Error>

Following are the parameters for a URL that is failing to authenticate

sv=2016-05-31
sig=SbVzxo+dv28FvJP+Z9b1w6uvWUT72Pw1BSe3MIRooM0=
st=2017-03-30T11:52:35Z
se=2017-04-06T11:57:35Z
sr=b
sp=r

Body:
I found the problem.
I did not mention in question but the code for generation SAS is called via HTTTP client and the URL for accessing the Blob with SAS is located in Location header of the response.

I was trying to retrieve the URL with

response.Headers.Location.ToString();

but, I should have used

response.Headers.Location.OriginalString.ToString();

According to Microsoft the Location.ToString() returns the canonically unescaped form of the URI. That is why my signature was invalid and there were characters like + inside it.


问:
Changing occurrences of one pattern to another
grep -R \"\/web *
gives me some occurrences which i want to change to
\"\$\/web

How can I do this?

答:
Command-line: sed -i 's/"\/web/"$\/web/g' FILENAME, or omit -i and FILENAME if piping input.

Take care when doing it though - it might be a good idea to run without -i first, and then with it if you are sure that the results are exactly what you want.

For multiple files: find . -type f -exec sed -i 's/"\/web/"$\/web/g' {} \;

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Convert a string to std filesystem path
A file path is passed as a string. How do I convert this string to a std::filesystem::path? Example:</p>

```<code>#include <filesystem>

std::string inputPath = "a/custom/path.ext";
const std::filesystem::path path = inputPath; // Is this assignment safe?
</code>```

答:
Yes, this construction is safe:

```<code>const std::filesystem::path path = inputPath; // Is this assignment safe?
</code>```

That is not assignment, that is copy initialization. You are invoking this constructor:

```<code>template< class Source >
path( const Source& source );
</code>```

which takes:

Constructs the path from a character sequence provided by source (4), which is a pointer or an input iterator to a null-terminated character/wide character sequence, an std::basic_string or an std::basic_string_view,

So you're fine. Plus, it would be really weird if you couldn't construct a filesystem::path from a std::string.

Title: Convert a string to std filesystem path

Body:
A file path is passed as a string. How do I convert this string to a std::filesystem::path? Example:

#include <filesystem>

std::string inputPath = "a/custom/path.ext";
const std::filesystem::path path = inputPath; // Is this assignment safe?

Body:
Yes, this construction is safe:

const std::filesystem::path path = inputPath; // Is this assignment safe?

That is not assignment, that is copy initialization. You are invoking this constructor:

template< class Source >
path( const Source& source );

which takes:

Constructs the path from a character sequence provided by source (4), which is a pointer or an input iterator to a null-terminated character/wide character sequence, an std::basic_string or an std::basic_string_view,

So you're fine. Plus, it would be really weird if you couldn't construct a filesystem::path from a std::string.


问:
How to include files from other project in visual studio
We have two projects in visual studio, first one is workflows which generated sql files by a DSL tool (this is something like Linq2Sql designer which gestates files automatically by every change)
Second one is a Database project,
I want to include the generated sql files in database project, so that when the content regenerated, I wouldn't need to copy paste it in database project.

For this reason, I add existing sql files as Link (Add as link) to database project, the problem is they don't copy in build process, then I get an error about files are not exists.

I found an article about it in http://mattperdeck.com/post/Copying-linked-content-files-at-each-build-using-MSBuild.aspx but that one is not working for me too.

Then I was thinking about including files automatically in my solution by adding something like , but they will be added to the root of the project not in the desired path.

```<code><ItemGroup>
  <None Include="..\..\Workflows\*.sql" />
</ItemGroup>
</code>```

答:
I solved my issue, but I keep it open to get better solutions

I added below code to project file

```<code><Content Include="..\..\Workflows\*.sql">
  <Link>Deployment\Post-Deployment\WorkflowDataSync\%(Filename)%(Extension)</Link>
</Content>
</code>```

And I added this to pre-build event command line in project properties page

```<code>xcopy "$(ProjectDir)..\..\Workflows\*.sql" "$(ProjectDir)Deployment\Post-Deployment\WorkflowDataSync" /Y /I
</code>```

Body:
We have two projects in visual studio, first one is workflows which generated sql files by a DSL tool (this is something like Linq2Sql designer which gestates files automatically by every change)
Second one is a Database project,
I want to include the generated sql files in database project, so that when the content regenerated, I wouldn't need to copy paste it in database project.

For this reason, I add existing sql files as Link (Add as link) to database project, the problem is they don't copy in build process, then I get an error about files are not exists.

I found an article about it in http://mattperdeck.com/post/Copying-linked-content-files-at-each-build-using-MSBuild.aspx but that one is not working for me too.

Then I was thinking about including files automatically in my solution by adding something like , but they will be added to the root of the project not in the desired path.

<ItemGroup>
  <None Include="..\..\Workflows\*.sql" />
</ItemGroup>

Body:
I solved my issue, but I keep it open to get better solutions

I added below code to project file

<Content Include="..\..\Workflows\*.sql">
  <Link>Deployment\Post-Deployment\WorkflowDataSync\%(Filename)%(Extension)</Link>
</Content>

And I added this to pre-build event command line in project properties page

xcopy "$(ProjectDir)..\..\Workflows\*.sql" "$(ProjectDir)Deployment\Post-Deployment\WorkflowDataSync" /Y /I


问:
JavaScript: Regex for numbers that include decimal and fractional parts with optional leading minus sign?
I have tried to run the following regex:

```<code>(-?\d+\.?(\d*)?)
</code>```

which works very well when I try it on https://regex101.com/r/lD2qB4/5

But when I apply it to my JavaScript code, it doesn't accept leading minus sign!

What could be the reason for something like that?

Inputs that 'should' match:

123.456

123456.

-123.456

Inputs that 'should not' match:

123.456.

123456..

--123.456

EDIT:

Code snippet:

```<code>private validateNumber() {
        let newValue: string = $(this.getNativeElement()).val();
        if (/(-?\d+\.?(\d*)?)/.test(newValue)) {
            let min = (this.options.min) ? this.options.min : this.numberTypesRenges.get(this.options.numberType).min;
            let max = (this.options.max) ? this.options.max : this.numberTypesRenges.get(this.options.numberType).max;
            if (+newValue >= min && +newValue <= max) {
                this.prevValue = newValue;
            } else {
                this.ngModel.reset(this.prevValue);
            }
        } else {
            this.ngModel.reset(this.prevValue);
        }
    }
</code>```

答:
There is only one issue

```<code>/^(-?\d+(\.\d+)?$/
^^^           ^^
</code>```

The start and end. Otherwise it will do partial match.

Also, you can group the optional .\d together

AS   (\.\d+) instead of `.?\d*?

Note that * means 0 or more so, it will match 1..

Instead use + for 1 or more

Body:
I have tried to run the following regex:

(-?\d+\.?(\d*)?)

which works very well when I try it on https://regex101.com/r/lD2qB4/5

But when I apply it to my JavaScript code, it doesn't accept leading minus sign!

What could be the reason for something like that?

Inputs that 'should' match:

123.456

123456.

-123.456

Inputs that 'should not' match:

123.456.

123456..

--123.456

EDIT:

Code snippet:

private validateNumber() {
        let newValue: string = $(this.getNativeElement()).val();
        if (/(-?\d+\.?(\d*)?)/.test(newValue)) {
            let min = (this.options.min) ? this.options.min : this.numberTypesRenges.get(this.options.numberType).min;
            let max = (this.options.max) ? this.options.max : this.numberTypesRenges.get(this.options.numberType).max;
            if (+newValue >= min && +newValue <= max) {
                this.prevValue = newValue;
            } else {
                this.ngModel.reset(this.prevValue);
            }
        } else {
            this.ngModel.reset(this.prevValue);
        }
    }

Body:
There is only one issue

/^(-?\d+(\.\d+)?$/
^^^           ^^

The start and end. Otherwise it will do partial match.

Also, you can group the optional .\d together

AS   (\.\d+) instead of `.?\d*?

Note that * means 0 or more so, it will match 1..

Instead use + for 1 or more


问:
Global secondary index: Number of projected attributes in all indexes exceeds limit of 20
I'm trying to create a GSI on a table with 30 columns (using ruby SDK). I use the projection_type: 'ALL' - but I still get the following exception:

```<code>Aws::DynamoDB::Errors::ValidationException: One or more parameter values were invalid: Number of projected attributes in all indexes exceeds limit of 20, number of projected attributes:30
</code>```

As far as I read, this should only happen when using the INCLUDE projection_type:

This limit does not apply for secondary indexes with a ProjectionType of KEYS_ONLY or ALL.
  http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-secondary-indexes

The create statement looks something like:

```<code>connection.update_table({
    table_name: "my-table", # required
    attribute_definitions: [
      {
        attribute_name: "indexDate",
        attribute_type: "S",
      },
      {
        attribute_name: "createdAt",
        attribute_type: "S",
      },
    ],
    global_secondary_index_updates: [
      {
        create: {
          index_name: "my-new-index", # required
          key_schema: [
            {
              attribute_name: "indexDate",
              key_type: "HASH",
            },
            {
              attribute_name: "createdAt",
              key_type: "RANGE",
            },
          ],
          projection: { # required
            projection_type: "ALL"
          },
          provisioned_throughput: { # required
            read_capacity_units: 10, # required
            write_capacity_units: 300, # required
          }
        }
      }
    ]
  })
</code>```

答: Turned out that the attribute limit restriction goes across all GSI's on the table. I had another one that caused this one to fail. Deleted that one, and then it worked.</p>

Body:
I'm trying to create a GSI on a table with 30 columns (using ruby SDK). I use the projection_type: 'ALL' - but I still get the following exception:

Aws::DynamoDB::Errors::ValidationException: One or more parameter values were invalid: Number of projected attributes in all indexes exceeds limit of 20, number of projected attributes:30

As far as I read, this should only happen when using the INCLUDE projection_type:

This limit does not apply for secondary indexes with a ProjectionType of KEYS_ONLY or ALL.
  http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-secondary-indexes

The create statement looks something like:

connection.update_table({
    table_name: "my-table", # required
    attribute_definitions: [
      {
        attribute_name: "indexDate",
        attribute_type: "S",
      },
      {
        attribute_name: "createdAt",
        attribute_type: "S",
      },
    ],
    global_secondary_index_updates: [
      {
        create: {
          index_name: "my-new-index", # required
          key_schema: [
            {
              attribute_name: "indexDate",
              key_type: "HASH",
            },
            {
              attribute_name: "createdAt",
              key_type: "RANGE",
            },
          ],
          projection: { # required
            projection_type: "ALL"
          },
          provisioned_throughput: { # required
            read_capacity_units: 10, # required
            write_capacity_units: 300, # required
          }
        }
      }
    ]
  })


问:
add additional-include-directory and reference => point to a static library in ONE setting
I have an application project (MyGame) that want to access everything inside a static library (MyLib) in the same solution:-

```<code>MyVisualSolution
- MyLib (static library)  : 200  .h & .cpp
- MyGame (win32 app)      : 100  .h & .cpp
</code>```

The steps to achieve the above requirement are :-

set project property of MyGame > add additional include directory = .h folder in MyLib

In Solution Explorer, click References of MyGame, then click the check-box MyLib.

I have to do both steps, and the settings are   in very different places.

I think it is tedious, dirty, not intuitive, and error prone.

Is there any way to do it in a single place inside Visual Studio?

I expect to do just one thing that is similar to the second step.

(I feel that property sheet may be the closest answer, but it still can't solve.)

As far as I searched, there is none.  (visual c++: #include files from other projects in the same solution)

答:
This is maybe not a full answer but too long for a comment: we have multiple projects which each have with multiple static and dynamic library projects and multiple applications. To minimize configuration we settled for a having a clear project structure, a couple of conventions, and common property sheets for all projects which enforce said structure and conventions. It took a while to set this up but in the end it's worth it.

Project structure (simplified) is:

```<code>maindir \
        _bin \
        _lib \
        build \
               paths.props
               linker.props
               compiler.props
               default.props
               maindir.user.props
               autolink_template.h
        projectA \
                  projectA.h
                  autolink.h
        projectB \
                  tests \
                  projectB \
                           projectB.h
                           autolink.h
</code>```

_bin is where all dlls/exes go. We might either use subdirectories per platform/configuration combo or else use postfixes on output names like projectA_x86d.exe for Debug|Win32 builds. This is all setup in property sheets (our projects basically never have any modifications to settings, they just contain the source/include files and import property sheets from the build directory)

_lib is where the import and static libraries go. Again, either with subdirectories or with postfixes on the names.

build has all common property sheets. A normal project just includes default.props which automatically figures out whether an exe/lib/dll is built based on $(ConfigurationType) and includes other property sheets according to that. There are property sheets for setting output paths to _lib and _bin, search paths so the _lib directory is found by linker, adding maindir to include search path, even things like setting file versions based on git hash etc, ... If a .user.props is found it is also imported, this allows custom settings related to maindir.

For the include files we always use #include  instead of just . Imo this is clearer and reduces chances of name clashes. If a project has seperate tests/source directories like projectB, maindir.user.props is adjusted to add maindir/projectB to the include path so we can still just use #include

For setting up linking there's an autolink.h in each lib project which has a #pragma comment(lib, "projectA.lib") (created from a template in the build dir) so to link to that lib another project just has to #include .

Now this may be overkill for you but you might get some ideas which work well for your particular situation.

Body:
I have an application project (MyGame) that want to access everything inside a static library (MyLib) in the same solution:-

MyVisualSolution
- MyLib (static library)  : 200  .h & .cpp
- MyGame (win32 app)      : 100  .h & .cpp

The steps to achieve the above requirement are :-

set project property of MyGame > add additional include directory = .h folder in MyLib

In Solution Explorer, click References of MyGame, then click the check-box MyLib.

I have to do both steps, and the settings are   in very different places.

I think it is tedious, dirty, not intuitive, and error prone.

Is there any way to do it in a single place inside Visual Studio?

I expect to do just one thing that is similar to the second step.

(I feel that property sheet may be the closest answer, but it still can't solve.)

As far as I searched, there is none.  (visual c++: #include files from other projects in the same solution)

Body:
This is maybe not a full answer but too long for a comment: we have multiple projects which each have with multiple static and dynamic library projects and multiple applications. To minimize configuration we settled for a having a clear project structure, a couple of conventions, and common property sheets for all projects which enforce said structure and conventions. It took a while to set this up but in the end it's worth it.

Project structure (simplified) is:

maindir \
        _bin \
        _lib \
        build \
               paths.props
               linker.props
               compiler.props
               default.props
               maindir.user.props
               autolink_template.h
        projectA \
                  projectA.h
                  autolink.h
        projectB \
                  tests \
                  projectB \
                           projectB.h
                           autolink.h

_bin is where all dlls/exes go. We might either use subdirectories per platform/configuration combo or else use postfixes on output names like projectA_x86d.exe for Debug|Win32 builds. This is all setup in property sheets (our projects basically never have any modifications to settings, they just contain the source/include files and import property sheets from the build directory)

_lib is where the import and static libraries go. Again, either with subdirectories or with postfixes on the names.

build has all common property sheets. A normal project just includes default.props which automatically figures out whether an exe/lib/dll is built based on $(ConfigurationType) and includes other property sheets according to that. There are property sheets for setting output paths to _lib and _bin, search paths so the _lib directory is found by linker, adding maindir to include search path, even things like setting file versions based on git hash etc, ... If a .user.props is found it is also imported, this allows custom settings related to maindir.

For the include files we always use #include  instead of just . Imo this is clearer and reduces chances of name clashes. If a project has seperate tests/source directories like projectB, maindir.user.props is adjusted to add maindir/projectB to the include path so we can still just use #include

For setting up linking there's an autolink.h in each lib project which has a #pragma comment(lib, "projectA.lib") (created from a template in the build dir) so to link to that lib another project just has to #include .

Now this may be overkill for you but you might get some ideas which work well for your particular situation.


问:
Importing a big xlsx file into R?
I'm wondering if anyone knows of a way to import data from a "big" xlsx file (~20Mb). I tried to use xlsx and XLConnect libraries. Unfortunately, both use rJava and I always obtain the same error:

```<code>> library(XLConnect)
> wb <- loadWorkbook("MyBigFile.xlsx")
Error: OutOfMemoryError (Java): Java heap space
</code>```

or

```<code>> library(xlsx)
> mydata <- read.xlsx2(file="MyBigFile.xlsx")
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  :
   java.lang.OutOfMemoryError: Java heap space
</code>```

I also tried to modify the java.parameters before loading rJava:

```<code>> options( java.parameters = "-Xmx2500m")
> library(xlsx) # load rJava
> mydata <- read.xlsx2(file="MyBigFile.xlsx")
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  :
   java.lang.OutOfMemoryError: Java heap space
</code>```

or after loading rJava (this is a bit stupid, I think):

```<code>> library(xlsx) # load rJava
> options( java.parameters = "-Xmx2500m")
> mydata <- read.xlsx2(file="MyBigFile.xlsx")
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  :
   java.lang.OutOfMemoryError: Java heap space
</code>```

But nothing works. Does anyone have an idea?

答:
I do agree with @orville jackson response & it really helped me too.

Inline to the answer provided by @orville jackson. here is the detailed description of how you can use openxlsx for reading and writing big files.

When data size is small, R has many packages and functions which can be utilized as per your requirement.

write.xlsx, write.xlsx2, XLconnect also do the work but these are sometimes slow as compare to openxlsx.

So, if you are dealing with the large data sets and came across java errors. I would suggest to have a look of "openxlsx" which is really awesome and reduce the time by 1/12th.

I've tested all and finally i was really impressed with the performance of openxlsx capabilities.

Here are the steps for writing multiple datasets into multiple sheets.

```<code>install.packages("openxlsx")
library("openxlsx")

start.time <- Sys.time()

# Creating large data frame
x <- as.data.frame(matrix(1:4000000,200000,20))
y <- as.data.frame(matrix(1:4000000,200000,20))
z <- as.data.frame(matrix(1:4000000,200000,20))

# Creating a workbook
wb <- createWorkbook("Example.xlsx")
Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") ## path to zip.exe
</code>```

Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") has to be static as it takes reference of some utility from Rtools.

Note: Incase Rtools is not installed on your system, please install it first for smooth experience. here is the link for your reference: (choose appropriate version)
https://cran.r-project.org/bin/windows/Rtools/

check the options as per link below (need to select all the check box while installation)
https://cloud.githubusercontent.com/assets/7400673/12230758/99fb2202-b8a6-11e5-82e6-836159440831.png

```<code># Adding a worksheets : parameters for addWorksheet are 1. Workbook Name 2. Sheet Name

addWorksheet(wb, "Sheet 1")
addWorksheet(wb, "Sheet 2")
addWorksheet(wb, "Sheet 3")

# Writing data in to respetive sheets: parameters for writeData are 1. Workbook Name 2. Sheet index/ sheet name 3. dataframe name

writeData(wb, 1, x)

# incase you would like to write sheet with filter available for ease of access you can pass the parameter withFilter = TRUE in writeData function.
writeData(wb, 2, x = y, withFilter = TRUE)

## Similarly writeDataTable is another way for representing your data with table formatting:

writeDataTable(wb, 3, z)

saveWorkbook(wb, file = "Example.xlsx", overwrite = TRUE)

end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken
</code>```

openxlsx package is really good for reading and writing huge data from/ in excel files and has lots of options for custom formatting within excel.

The interesting fact is that we don’t have to bother about java heap memory here.

Title: Importing a big xlsx file into R?

Body:
I'm wondering if anyone knows of a way to import data from a "big" xlsx file (~20Mb). I tried to use xlsx and XLConnect libraries. Unfortunately, both use rJava and I always obtain the same error:

> library(XLConnect)
> wb <- loadWorkbook("MyBigFile.xlsx")
Error: OutOfMemoryError (Java): Java heap space

or

> library(xlsx)
> mydata <- read.xlsx2(file="MyBigFile.xlsx")
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  :
   java.lang.OutOfMemoryError: Java heap space

I also tried to modify the java.parameters before loading rJava:

> options( java.parameters = "-Xmx2500m")
> library(xlsx) # load rJava
> mydata <- read.xlsx2(file="MyBigFile.xlsx")
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  :
   java.lang.OutOfMemoryError: Java heap space

or after loading rJava (this is a bit stupid, I think):

> library(xlsx) # load rJava
> options( java.parameters = "-Xmx2500m")
> mydata <- read.xlsx2(file="MyBigFile.xlsx")
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  :
   java.lang.OutOfMemoryError: Java heap space

But nothing works. Does anyone have an idea?

Body:
I do agree with @orville jackson response & it really helped me too.

Inline to the answer provided by @orville jackson. here is the detailed description of how you can use openxlsx for reading and writing big files.

When data size is small, R has many packages and functions which can be utilized as per your requirement.

write.xlsx, write.xlsx2, XLconnect also do the work but these are sometimes slow as compare to openxlsx.

So, if you are dealing with the large data sets and came across java errors. I would suggest to have a look of "openxlsx" which is really awesome and reduce the time by 1/12th.

I've tested all and finally i was really impressed with the performance of openxlsx capabilities.

Here are the steps for writing multiple datasets into multiple sheets.

install.packages("openxlsx")
library("openxlsx")

start.time <- Sys.time()

# Creating large data frame
x <- as.data.frame(matrix(1:4000000,200000,20))
y <- as.data.frame(matrix(1:4000000,200000,20))
z <- as.data.frame(matrix(1:4000000,200000,20))

# Creating a workbook
wb <- createWorkbook("Example.xlsx")
Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") ## path to zip.exe

Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") has to be static as it takes reference of some utility from Rtools.

Note: Incase Rtools is not installed on your system, please install it first for smooth experience. here is the link for your reference: (choose appropriate version)
https://cran.r-project.org/bin/windows/Rtools/

check the options as per link below (need to select all the check box while installation)
https://cloud.githubusercontent.com/assets/7400673/12230758/99fb2202-b8a6-11e5-82e6-836159440831.png

# Adding a worksheets : parameters for addWorksheet are 1. Workbook Name 2. Sheet Name

addWorksheet(wb, "Sheet 1")
addWorksheet(wb, "Sheet 2")
addWorksheet(wb, "Sheet 3")

# Writing data in to respetive sheets: parameters for writeData are 1. Workbook Name 2. Sheet index/ sheet name 3. dataframe name

writeData(wb, 1, x)

# incase you would like to write sheet with filter available for ease of access you can pass the parameter withFilter = TRUE in writeData function.
writeData(wb, 2, x = y, withFilter = TRUE)

## Similarly writeDataTable is another way for representing your data with table formatting:

writeDataTable(wb, 3, z)

saveWorkbook(wb, file = "Example.xlsx", overwrite = TRUE)

end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

openxlsx package is really good for reading and writing huge data from/ in excel files and has lots of options for custom formatting within excel.

The interesting fact is that we don’t have to bother about java heap memory here.


问:
Update buffer and reset the locking-mode back to original one
Lets say we have a procedure which takes in a buffer-parameter:

myprocedure.p:

```<code>DEF PARAM BUFFER bufferParameter FOR DatabaseTable.

/* Get the same buffer in EXCLUSIVE-LOCK for updating */
FIND CURRENT bufferParameter EXCLUSIVE-LOCK.

/* Update the value */
ASSIGN bufferParameter.MyField = "new value".

/* Reset the locking mode back to the original one? */
FIND CURRENT bufferParameter NO-LOCK.
</code>```

The problem with this approach is that it is possibly changing the original locking-mode of the passed buffer parameter. It is possible that the buffer was in EXCLUSIVE-LOCK or f.ex in NO-LOCK. By changing the locking-mode, this procedure could invoke updating errors in some other programs using this same buffer.

Another solution would be to create a new temporary buffer for the same table, and then update the database thru that buffer (without touching the passed parameter buffer). The con of this approach is that the original passed buffer parameter will become 'out-of-date'. It would require a new database query to update it's 'MyField' value to match the one in the database.

How I could reset the buffer's locking-mode back to the original one after updating it's fields?

答:
It's bizarre that lock type is not an attribute of the buffer handle. It would seem to be an obvious necessity.

You can find the _lock records for the recid, but you need to find the table ID as well, which would mean looking it up in _file from the handle:table.

So, assuming you've only one database connected, you'd have something like:

```<code>FIND _file NO-LOCK WHERE _file-name = bufHandle:TABLE.
FIND _lock NO-LOCK WHERE _lock-name = USERID()
    AND _lock-table = _file-number
    AND _lock-recid = bufHandle:RECID.
</code>```

If the record exists, you know you have a lock. The _lock_flags will tell you what kind of locks you have. I think S is share and E is exclusive and think if there is a Q then you are waiting for that lock, which I wouldn't expect if you already have a lock on the record.

You could then re-lock the record in the appropriate state if it wasn't already exclusively locked when your function began.

Body:
Lets say we have a procedure which takes in a buffer-parameter:

myprocedure.p:

DEF PARAM BUFFER bufferParameter FOR DatabaseTable.

/* Get the same buffer in EXCLUSIVE-LOCK for updating */
FIND CURRENT bufferParameter EXCLUSIVE-LOCK.

/* Update the value */
ASSIGN bufferParameter.MyField = "new value".

/* Reset the locking mode back to the original one? */
FIND CURRENT bufferParameter NO-LOCK.

The problem with this approach is that it is possibly changing the original locking-mode of the passed buffer parameter. It is possible that the buffer was in EXCLUSIVE-LOCK or f.ex in NO-LOCK. By changing the locking-mode, this procedure could invoke updating errors in some other programs using this same buffer.

Another solution would be to create a new temporary buffer for the same table, and then update the database thru that buffer (without touching the passed parameter buffer). The con of this approach is that the original passed buffer parameter will become 'out-of-date'. It would require a new database query to update it's 'MyField' value to match the one in the database.

How I could reset the buffer's locking-mode back to the original one after updating it's fields?

Body:
It's bizarre that lock type is not an attribute of the buffer handle. It would seem to be an obvious necessity.

You can find the _lock records for the recid, but you need to find the table ID as well, which would mean looking it up in _file from the handle:table.

So, assuming you've only one database connected, you'd have something like:

FIND _file NO-LOCK WHERE _file-name = bufHandle:TABLE.
FIND _lock NO-LOCK WHERE _lock-name = USERID()
    AND _lock-table = _file-number
    AND _lock-recid = bufHandle:RECID.

If the record exists, you know you have a lock. The _lock_flags will tell you what kind of locks you have. I think S is share and E is exclusive and think if there is a Q then you are waiting for that lock, which I wouldn't expect if you already have a lock on the record.

You could then re-lock the record in the appropriate state if it wasn't already exclusively locked when your function began.


问:
Deserialize JSON to string in raw format using Jackson
I have a use case where I want the JSON to be converted to string as it is, but it is failing and giving me null, here is my POJO:

```<code>@Data
@JsonSnakeCase
@JsonIgnoreProperties(ignoreUnknown = true)
public class DocumentTemplateRequest {

@Enumerated(EnumType.STRING)
private TemplateState state;

@JsonDeserialize(using = JsonAsStringDeserializer.class)
private String inputSchema;

}
</code>```

the Json I am using as payload:

```<code>{
"state": "staging",
"input_schema": {
    "title": "Person",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        }
    },
    "required": ["firstName", "lastName"]
}

}
</code>```

I am using object mapper for mappings:

```<code>    ObjectMapper objectMapper = new ObjectMapper();
    DocumentTemplateRequest documentTemplateRequest = null;
    try {
        documentTemplateRequest = objectMapper.readValue(str, DocumentTemplateRequest.class);
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

and here is my deserializer:

```<code>public class JsonAsStringDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    TreeNode tree = jsonParser.getCodec().readTree(jsonParser);
    return tree.toString();

}
}
</code>```

and the results of deserialization is :

```<code>state : staging
inputSchema: null
</code>```

why inputSchema is coming as null, what am I missing?

答:
it is with the property?
you are missing underscroe. input_schema is different from inputSchema.

either use the same property name everywhere you use it or use jsonproperty annotation to be sepecific.

Body:
I have a use case where I want the JSON to be converted to string as it is, but it is failing and giving me null, here is my POJO:

@Data
@JsonSnakeCase
@JsonIgnoreProperties(ignoreUnknown = true)
public class DocumentTemplateRequest {

@Enumerated(EnumType.STRING)
private TemplateState state;

@JsonDeserialize(using = JsonAsStringDeserializer.class)
private String inputSchema;

}

the Json I am using as payload:

{
"state": "staging",
"input_schema": {
    "title": "Person",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        }
    },
    "required": ["firstName", "lastName"]
}

}

I am using object mapper for mappings:

    ObjectMapper objectMapper = new ObjectMapper();
    DocumentTemplateRequest documentTemplateRequest = null;
    try {
        documentTemplateRequest = objectMapper.readValue(str, DocumentTemplateRequest.class);
    } catch (IOException e) {
        e.printStackTrace();
    }

and here is my deserializer:

public class JsonAsStringDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    TreeNode tree = jsonParser.getCodec().readTree(jsonParser);
    return tree.toString();

}
}

and the results of deserialization is :

state : staging
inputSchema: null

why inputSchema is coming as null, what am I missing?


问:
Controller in its own dependency injection
I am not aware of latest release of angularjs. I saw a piece of code like below

```<code>angular.module('app')
    .controller('myApp', [myApp]);

function myApp() {
      var vm = this;
      vm.title = 'Customers';
      vm.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
    };
</code>```

instead of code i used to write earlier like

```<code>angular.module('app')
    .controller('myApp', function($scope){
      $scope.title = 'Customers';
      $scope.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
});
</code>```

So why are we injecting the functionality required for the controller? what advantage does it provide. Correct me if my understanding is wrong.

答:
That controller is not being used in its own dependency injection.

This is simply a syntax for defining a controller:

```<code>.controller('controllerName', [
    'dependency1',
    'dependency2',
    function (dependency1, dependency2) {
    }
]);
</code>```

This approach allows specifying the names for the dependencies explicitly and prevents your dependencies from getting messed up if you minify the code.

In the case of your example, there are no dependencies, and the function is being referenced as a variable instead of being included inline.

It's also using the "controller as" syntax (where the controller refers to itself as this) instead of using the $scope service, but that is a completely separate matter.

You could also modify your second example to work the same way:

```<code>angular.module('app')
    .controller('myApp', ['$scope', myApp]);

function myApp($scope){
      $scope.title = 'Customers';
      $scope.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
}
</code>```

Body:
I am not aware of latest release of angularjs. I saw a piece of code like below

angular.module('app')
    .controller('myApp', [myApp]);

function myApp() {
      var vm = this;
      vm.title = 'Customers';
      vm.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
    };

instead of code i used to write earlier like

angular.module('app')
    .controller('myApp', function($scope){
      $scope.title = 'Customers';
      $scope.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
});

So why are we injecting the functionality required for the controller? what advantage does it provide. Correct me if my understanding is wrong.

Body:
That controller is not being used in its own dependency injection.

This is simply a syntax for defining a controller:

.controller('controllerName', [
    'dependency1',
    'dependency2',
    function (dependency1, dependency2) {
    }
]);

This approach allows specifying the names for the dependencies explicitly and prevents your dependencies from getting messed up if you minify the code.

In the case of your example, there are no dependencies, and the function is being referenced as a variable instead of being included inline.

It's also using the "controller as" syntax (where the controller refers to itself as this) instead of using the $scope service, but that is a completely separate matter.

You could also modify your second example to work the same way:

angular.module('app')
    .controller('myApp', ['$scope', myApp]);

function myApp($scope){
      $scope.title = 'Customers';
      $scope.customers = [
        {name: 'Haley'}, {name: 'Ella'}, {name: 'Landon'}, {name: 'John'}
        ];
}


问:
AWS subdomain connect to specific folder
I want to create a subdomain for specific folder in my server eg: sub.xxxx.com and will open what is in /var/html/sub/ folder

I tried to create subdomain but always gives me this when opening in browser

server DNS address could not be found

I tried to create from Route 53 and configure the vhost but no success

答:
Go to the amazon Route53 hosted zone you already created for your domain and create record set following below instruction

Put the sub domain name into the name field like test.XXXXX.com

Select CNAME-canonical name from the type drop down menu

Alias (no)

TTL- default (300)

Value- Just the domain name (XXXXX.com)

Routing policy- default (simple)


问:
.NET's GUID structure
http://msdn.microsoft.com/en-us/library/system.guid.aspx

How does it work? How does it guarantee unique ID? Does it only rely on probability or is there another trick? Can I always trust it to give unique id or what are cases where I should avoid guid?

答:
First of all, the Guid structure does not guarantee anything by itself you can create many guids yourself by an explicit constructor: var myGuid = new Guid(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }); That way you can create how many identical Guids you like.

But I suppose you mean Guids created with the static method Guid.NewGuid(). In the remarks section it is noted that the probability that the Guid is all zeros or equal to another Guid is low.

You can also read the RFC that describes how the randomness in a Guid is created.

Title: .NET's GUID structure


问:
How to compare if any of the elements in a row is same
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

```<code>DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA
</code>```

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

```<code> > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)
</code>```

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

答:
I would do a sapply along the indices (minus the last) of the table:

```<code>compare <- function(i) {
    row1 <- as.character(DT[i,])
    row2 <- as.character(DT[i+1,])
    return(length(intersect(row1[!is.na(row1)], row2[!is.na(row2)])) > 0)
}

result <- sapply(1:(nrow(DT) - 1), compare)
</code>```

This returns a vector of logicals, so if you prefer to get integers, wrap the output of compare in a as.numeric()

Body:
Is there a way to compare whether "any value of" a row is identical to "any value" of the row above -- regardless of the order? Below is a very random input data table.

DT <- data.table(A=c("a","a","b","d","e","f","h","i","j"),
                 B=c("a","b","c","c","f","g",NA,"j",NA),
                 C=c("a","b","c","b","g","h",NA,NA,NA))

> DT
   A  B  C
1: a  a  a
2: a  b  b
3: b  c  c
4: d  c  b
5: e  f  g
6: f  g  h
7: h NA NA
8: i  j NA
9: j NA NA

I would like to add a column D that compares a row with the row above, and compare whether any values of the two rows are identical (regardless of the order). So the desired output would be:

 > DT
   A  B  C  D
1: a  a  a  0 #No row above to compare; could be either NA or 0
2: a  b  b  1 #row 2 has "a", which is in row 1; returns 1
3: b  c  c  1 #row 3 has "b", which is in row 2; returns 1
4: d  c  b  1 #row 4 has "b" and "c", which are in row 3; returns 1
5: e  f  g  0 #row 5 has nothing that is in row 4; returns 0
6: f  g  h  1 #row 6 has "f" and "g", which are in row 5; returns 1
7: h NA NA  1 #row 7 has "h", which is in row 6; returns 1
8: i  j NA  0 #row 8 has nothing that is in row 7 (NA doesn't count)
9: j NA NA  1 #row 9 has "j", which is in row 8; returns 1 (NA doesn't count)

The main idea is that I would like to compare a row (or a vector) with another row (vector), and define two rows to be identical if any of the elements in each row (vector) are.  (without reiterating to compare each element)

Body:
I would do a sapply along the indices (minus the last) of the table:

compare <- function(i) {
    row1 <- as.character(DT[i,])
    row2 <- as.character(DT[i+1,])
    return(length(intersect(row1[!is.na(row1)], row2[!is.na(row2)])) > 0)
}

result <- sapply(1:(nrow(DT) - 1), compare)

This returns a vector of logicals, so if you prefer to get integers, wrap the output of compare in a as.numeric()


问:
How to get parameters properties from a stored procedure in Oracle?
I am developing an admin panel where we can determine which stored procedures and views can be called in Oracle 12c schemas, from services in our micro-services platform.

The services must know which parameters a procedure needs, and which columns a view has available, in order to call them.

I the admin panel, the creator of the procedure or view may register it, by typing in these information, like object's name, each parameter's name, length and data type.

But it would be much more elegant if the user just types the name of the object and then a SQL SELECT would retrieve a procedure's parameters properties in a table, and the same with the view's column's properties, so the panel would register those configurations automatically.

Could anybody post a query on how to achieve this? I am very new to Oracle and I don't know how to query the objects metadata.

答:
I believe your are looking for something like this.

```<code>SELECT *
  FROM SYS.DBA_PROCEDURES
  WHERE OBJECT_TYPE = 'PROCEDURE'
  AND   OBJECT_NAME = 'xxxx'
</code>```

Once you have that, you can get the parameters from something like this.

```<code>SELECT *
  FROM SYS.ALL_ARGUMENTS
  where object_name  = 'procedure_name';
</code>```

Body:
I believe your are looking for something like this.

SELECT *
  FROM SYS.DBA_PROCEDURES
  WHERE OBJECT_TYPE = 'PROCEDURE'
  AND   OBJECT_NAME = 'xxxx'

Once you have that, you can get the parameters from something like this.

SELECT *
  FROM SYS.ALL_ARGUMENTS
  where object_name  = 'procedure_name';


问:
Laravel redirect issue from blade template
I am new in laravel 5 .
I am working on larvel page security and i have to prevent open some page or Url
but when i use {{ Redirect::to('/dashboard') }} in view it is not working .

Please help me to find a way to use Redirect / Url in laravel view (Blade template)

I have already tried :-

{{ url('/dashboard') }}

{{ Redirect::to('/dashboard') }}

Code :-

```<code>@if(Auth::user()->role_id == 1)
{{ 'Page' }}
@else
{{ Redirect::to('/dashboard') }}
@endif
</code>```

答:
Use a JavaScript redirect instead:</p>

```<code>@if(Auth::user()->role_id == 1)
  {{ 'Page' }}
@else
  <script>window.location = "/dashboard";</script>
@endif
</code>```

Body:
I am new in laravel 5 .
I am working on larvel page security and i have to prevent open some page or Url
but when i use {{ Redirect::to('/dashboard') }} in view it is not working .

Please help me to find a way to use Redirect / Url in laravel view (Blade template)

I have already tried :-

{{ url('/dashboard') }}

{{ Redirect::to('/dashboard') }}

Code :-

@if(Auth::user()->role_id == 1)
{{ 'Page' }}
@else
{{ Redirect::to('/dashboard') }}
@endif

Body:
Use a JavaScript redirect instead:

@if(Auth::user()->role_id == 1)
  {{ 'Page' }}
@else
  <script>window.location = "/dashboard";</script>
@endif


问:
How to have just the time picker in a bootstrap 3 date/time picker widget with an added string in format
My question refers to the following bootstrap 3 date time picker:

https://eonasdan.github.io/bootstrap-datetimepicker/

I have a bootstrap 3 date and time picker widget on a website, but would actually like it to be just a time picker.

This is normally trivial to achieve, and can be done using the format parameter as follows:

```<code>$('#datetimepicker').datetimepicker({defaultDate:'now',ignoreReadonly: true});
$('#datetimepicker').data("DateTimePicker").format('LT');
</code>```

Note the LT for local time, or you could use:

```<code>$('#datetimepicker').data("DateTimePicker").format('HH:mm:ss');
</code>```

Both of these work as we've removed any reference to date.

However, my issue is that I use an additional string in my text field, so my code actually looks like this:

```<code>$('#datetimepicker').datetimepicker({defaultDate:'now',ignoreReadonly: true});
$('#datetimepicker').data("DateTimePicker").format('[Departing at:] LT');
</code>```

This comes from my previous question here:

Add custom text to the output text field in bootstrap datetimepicker

This works fine in that the text field shows:

But it still contains a date widget. How can I remove the date widget?

If this isn't possible, is there a way to have the time widget appear first by default, that would suffice.

I should point out that I have tried removing the

```<code>defaultDate:'now'
</code>```

code in case it was forcing the date picker to appear, but that doesn't help.

答:
It's a bug of the datetimepicker, if you look at the code you will see that it internally uses the isEnabled function to determine which component to show. The isEnabled determines if the date picker should be shown checking if the format contains a D (case insensitive). Unfortunately, it does not takes in account string escaping [].

If the format option does not contain Y, M, d and D, the component will work as expected, as shown in the following example:

$('#datetimepicker').datetimepicker({
  defaultDate:'now',
  ignoreReadonly: true,
  format: '[abc:] LT'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

<div class="form-group" style = "margin-bottom:4px;">
    <div class='input-group date' id='datetimepicker'>
        <input type='text' class="form-control" readonly='readonly'/>
        <span class="input-group-addon" style="padding: 6px 11.5px;">
        <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
</div></code>```

I found that is a already known issue and there is a open pull request that tries to fix it. If you need, you can try to change the libary code locally with the code proposed by the pull request.

Body:
My question refers to the following bootstrap 3 date time picker:

https://eonasdan.github.io/bootstrap-datetimepicker/

I have a bootstrap 3 date and time picker widget on a website, but would actually like it to be just a time picker.

This is normally trivial to achieve, and can be done using the format parameter as follows:

$('#datetimepicker').datetimepicker({defaultDate:'now',ignoreReadonly: true});
$('#datetimepicker').data("DateTimePicker").format('LT');

Note the LT for local time, or you could use:

$('#datetimepicker').data("DateTimePicker").format('HH:mm:ss');

Both of these work as we've removed any reference to date.

However, my issue is that I use an additional string in my text field, so my code actually looks like this:

$('#datetimepicker').datetimepicker({defaultDate:'now',ignoreReadonly: true});
$('#datetimepicker').data("DateTimePicker").format('[Departing at:] LT');

This comes from my previous question here:

Add custom text to the output text field in bootstrap datetimepicker

This works fine in that the text field shows:

But it still contains a date widget. How can I remove the date widget?

If this isn't possible, is there a way to have the time widget appear first by default, that would suffice.

I should point out that I have tried removing the

defaultDate:'now'

code in case it was forcing the date picker to appear, but that doesn't help.

Body:
It's a bug of the datetimepicker, if you look at the code you will see that it internally uses the isEnabled function to determine which component to show. The isEnabled determines if the date picker should be shown checking if the format contains a D (case insensitive). Unfortunately, it does not takes in account string escaping [].

If the format option does not contain Y, M, d and D, the component will work as expected, as shown in the following example:

$('#datetimepicker').datetimepicker({
  defaultDate:'now',
  ignoreReadonly: true,
  format: '[abc:] LT'
});

<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

<div class="form-group" style = "margin-bottom:4px;">
    <div class='input-group date' id='datetimepicker'>
        <input type='text' class="form-control" readonly='readonly'/>
        <span class="input-group-addon" style="padding: 6px 11.5px;">
        <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
</div>

I found that is a already known issue and there is a open pull request that tries to fix it. If you need, you can try to change the libary code locally with the code proposed by the pull request.


问:
Excel Pivot Table filters values changing on source update
In our BI infrastructure we're using Excel's pivot tables to expose the data in an Analysis Service instance (the cube), and thus far we have nothing to complain about.

Excel "reports" can be defined containing pre-selected dimensions as rows, columns and filters, for example we can set the Time dimension as a column slicer, or the Country dimension as a filter slicer. This allows the users to access this pre-defined report with the slicers already in place where they just have to select there own values to slice with if needs be.

However, even tough this is working perfectly the issue emerges when we try to actually pre-define specific values in a filter slicer. These values are getting "randomly" changed after a few days without any particular pattern from what we can observe. (Note that the cube i.e. the data source is being updated daily)

For example, we want to create a report were the users would have the data already filtered by the countries Italy and France upon opening it. So we created a report where we have the Country as a filter slicer and the countries Italy and France set as specific slicers under the Country filter.

Now the problem is that this report would maintain it's structure and selected filter values for just a few days, after which Italy may get de-selected and Germany would now be selected, or only France is maintained as a slicer. And again, we can't seem to observe any particular pattern in these changes, neither the time it's taking to "lose its format", or the filter values being selected to filter with.

Furthermore, note that even tough the underlying data source is changing daily, the pre-selected values are always there and never deleted, i.e. Italy and France in this case, would always be available in the data source. In fact you could still select them in the report, even tough they are no longer selected by default.

Anyone can help us understand why this is occurring and what can be done to go around it?

EDIT
Just realized that the slicer which values keeps changing every once in a while, is a column in another table. For example the Country Italy is in reality a column in a table City and therefore can be found in multiple records such as Rome, Milan etc., and then is exposed as a dimension in SSAS.

答: Install BIDS Helper and open Your source code in Visual Studio. Then run Dimension Health Check on the City dimension. I expect it will show some attribute relationship uniqueness issues. Fix the keys or attribute relationships and your problem should be fixed. If you need help knowing how to fix it post a screenshot of Dimension Health Check here. </p>