问:
System design: whether to normalize the departments or not
I'm working with two consultants in one project. The thing is we reached a point where both of them cannot get into an agreement and each offer a different approach.

The thing is we have a store with four departments and we want to find the best approach for working with all of them in the same database.

Each department sell different products: Cars, Boats, Jetskies and Motorbikes.

When the data is inserted or updated in each department there are some triggers to be fires so different workflows will begin, when adding a new car there are certain requirements that needs to be checked as well as the details of the car that are completely different than a boat. Also, regarding the data there are not many fields there are in common, I would say so far only the brand, color, model and year, everything else is specific for each deparment due to the different products and how they work with them..

Consultant one says:

Create one table for all the departments and use a column to identify what department the row belongs to, this way you will have only one trigger and inside the trigger you will then call the function/mehod you need for each record type.

Reason: you only have one table (with over 200 fields) and one trigger, is easier to maintain. Also if you need to report you just need to query one table and filter based on the record type. If you need to report for all the items you don't need to have multiple joins.

Consultant two says:

Create one table for each deparment and a trigger for each table.

Reason: you will have smaller tables (aprox 50 fields each) and is more flexible and you have it all separated. If you want to report you need to join the tables as you want to include data from different places.

I see the advantages of having everything in one place but if I want to expand or change anything I have the feeling I will bre creating a beast table as the data grows.

On the other side keep it separated look more appealing but will need to setup everything for each different table.

What would you say is the best approach?

答:
I will go with one.

I assume you have a large number of products and this list will grow in future. All these are Products at the end. They will have some common fields and common logic.

If you use Process Builder with Invocable classes instead of Triggers, you may be able to get away with just configuration changes while adding a new object, if its fields and functionality are same/similar to a existing object.

There may also be limitation on the number of different objects a profile has access to based on your license types.

Salesforce has a standard object called Product. Its a single object to be classifies based on record type.

I would have gone with approach two if this was not salesforce. Based on how salesforce works and the limitations it imposes one seems like a better and cleaner solution.


来源: stackexchange

问:
App crashes on login, crash when starting dashboard activity
I'm creating a simple login to dashboard app and I'm having trouble with my app launching as I try to launch the dashboard home activity once login is tapped with correct credentials.

```<code>error code: Unable to find explicit activity class {com.example.david.myview3/com.example.david.myview3.DashBoardAppActivity}; have you declared this activity in your AndroidManifest.xml?
</code>```

It is the DashBoardAppActivity.java I wish to launch which happens in the the signIn() method of this class.

```<code>public void signIn(View V)
{
    final Dialog dialog = new Dialog(HomeActivity.this);
    dialog.setContentView(R.layout.login);
    dialog.setTitle("Login");

    // get the Refferences of views
    final  EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
    final  EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);

    Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);

    // Set On ClickListener
    btnSignIn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // get The User name and Password
            String userName=editTextUserName.getText().toString();
            String password=editTextPassword.getText().toString();

            // fetch the Password form database for respective user name
            String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);

            // check if the Stored password matches with  Password entered by user
            if(password.equals(storedPassword))
            {
                Toast.makeText(HomeActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();

                dialog.dismiss();
                startActivity (new Intent(getApplicationContext(), DashBoardAppActivity.class));
            }
            else
            {
                Toast.makeText(HomeActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
            }
        }
    });
</code>```

DashBoardAppActivity.java

```<code>    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
import android.view.View;

public abstract class DashboardAppActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    //Lifecycle Methods

    protected void onDestroy()
    {
        super.onDestroy();
    }

    protected void onStop()
    {
        super.onStop();
    }

    protected void onStart()
    {
        super.onStart();
    }

    protected void onPause()
    {
        super.onPause();
    }

    protected void onResume()
    {
        super.onResume();
    }

    //App Click Methods

    public void onSearch(View v)
    {
        startActivity (new Intent(getApplicationContext(), SearchActivity.class));
    }

    public void onAbout(View v)
    {
        startActivity (new Intent(getApplicationContext(), AboutActivity.class));
    }

    public void return2Home(Context context)
    {
        final Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity (intent);
    }

    public void onPhotoAlbum(View v)
    {
        startActivity (new Intent(getApplicationContext(), PhotoAlbumActivity.class));
    }

    public void onMessage(View v)
    {
        startActivity (new Intent(getApplicationContext(), MessagesActivity.class));
    }

    public void onHome (View v)
    {
        return2Home(this);
    }

}
</code>```

And this is my manifest

```<code>   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.david.myview3"
    android:versionCode="1"
    android:versionName="1.0">

    <application
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:theme="@style/AppTheme">

        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity android:name=".DashHomeActivity"
            android:theme="@style/Theme.D1"
            android:label="@string/app_name"
            />

        <activity
        android:name="SignUPActivity"/>

        <activity android:name=".SearchActivity"
            android:theme="@style/Theme.D1"
            android:label="@string/title_search"/>

        <activity android:name=".AboutActivity"
            android:theme="@style/Theme.D1"
            android:label="@string/title_about"
            />
        <activity android:name=".PhotoAlbumActivity"
            android:theme="@style/Theme.D1"
            android:label="@string/title_photoalbum"
            />
        <activity android:name=".MessagesActivity"
            android:theme="@style/Theme.D1"
            android:label="@string/title_message"
            />

</application>

    <uses-sdk android:minSdkVersion="9" />

</manifest>
</code>```

This activity launches fine if I launch one of it's features before it then use said features home feature to return to the dashbaord, it just does not seem to like to go from login to that dashboard first.

答:
Add this  DashBoardAppActivity activity to manifest </p>

```<code>        <activity android:name=".DashBoardAppActivity"
        android:theme="@style/Theme.D1"
       />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a simple login to dashboard app and I'm having trouble with my app launching as I try to launch the dashboard home activity once login is tapped with correct credentials.

error code: Unable to find explicit activity class {com.example.david.myview3/com.example.david.myview3.DashBoardAppActivity}; have you declared this activity in your AndroidManifest.xml?

It is the DashBoardAppActivity.java I wish to launch which happens in the the signIn() method of this class.

public void signIn(View V)
{
    final Dialog dialog = new Dialog(HomeActivity.this);
    dialog.setContentView(R.layout.login);
    dialog.setTitle("Login");

    // get the Refferences of views
    final  EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
    final  EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);

    Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);

    // Set On ClickListener
    btnSignIn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // get The User name and Password
            String userName=editTextUserName.getText().toString();
            String password=editTextPassword.getText().toString();

            // fetch the Password form database for respective user name
            String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);

            // check if the Stored password matches with  Password entered by user
            if(password.equals(storedPassword))
            {
                Toast.makeText(HomeActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();

                dialog.dismiss();
                startActivity (new Intent(getApplicationContext(), DashBoardAppActivity.class));
            }
            else
            {
                Toast.makeText(HomeActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
            }
        }
    });

DashBoardAppActivity.java

    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
import android.view.View;

public abstract class DashboardAppActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    //Lifecycle Methods

    protected void onDestroy()
    {
        super.onDestroy();
    }

    protected void onStop()
    {
        super.onStop();
    }

    protected void onStart()
    {
        super.onStart();
    }

    protected void onPause()
    {
        super.onPause();
    }

    protected void onResume()
    {
        super.onResume();
    }

    //App Click Methods

    public void onSearch(View v)
    {
        startActivity (new Intent(getApplicationContext(), SearchActivity.class));
    }

    public void onAbout(View v)
    {
        startActivity (new Intent(getApplicationContext(), AboutActivity.class));
    }

    public void return2Home(Context context)
    {
        final Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity (intent);
    }

    public void onPhotoAlbum(View v)
    {
        startActivity (new Intent(getApplicationContext(), PhotoAlbumActivity.class));
    }

    public void onMessage(View v)
    {
        startActivity (new Intent(getApplicationContext(), MessagesActivity.class));
    }

    public void onHome (View v)
    {
        return2Home(this);
    }

}

And this is my manifest

   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.david.myview3"
    android:versionCode="1"
    android:versionName="1.0">

    <application
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:theme="@style/AppTheme">

        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity android:name=".DashHomeActivity"
            android:theme="@style/Theme.D1"
            android:label="@string/app_name"
            />

        <activity
        android:name="SignUPActivity"/>

        <activity android:name=".SearchActivity"
            android:theme="@style/Theme.D1"
            android:label="@string/title_search"/>

        <activity android:name=".AboutActivity"
            android:theme="@style/Theme.D1"
            android:label="@string/title_about"
            />
        <activity android:name=".PhotoAlbumActivity"
            android:theme="@style/Theme.D1"
            android:label="@string/title_photoalbum"
            />
        <activity android:name=".MessagesActivity"
            android:theme="@style/Theme.D1"
            android:label="@string/title_message"
            />

</application>

    <uses-sdk android:minSdkVersion="9" />

</manifest>

This activity launches fine if I launch one of it's features before it then use said features home feature to return to the dashbaord, it just does not seem to like to go from login to that dashboard first.

Body:
Add this  DashBoardAppActivity activity to manifest

        <activity android:name=".DashBoardAppActivity"
        android:theme="@style/Theme.D1"
       />


问:
How to minify JavaScript like Google Analytics?
Most of you are probably familiar with this little tracking code offered by Google Analytics.

```<code><script>
(
    function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    }
)(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-00000000-0', 'auto');
ga('send', 'pageview');
</script>
</code>```

The interesting part is that this little excerpt contains arguments that form the word isogram. This script also uses arguments to declare variables to shave off some bits from the final file size. Arguably, you would not use this pattern when writing the code (?), so my question is, how does Google minify its code and are these techniques available to mere mortals, too?

I found online this example by Stephen Morley that includes a code that looks like something you'd write before minifying it. I took that code and run it through Google's very own Closure Compiler on advanced optimisation. As expected, the resulting code is nothing like the actual script used by Google Analytics.

```<code>(function(){window.b="ga";"ga"in window||(window.a=function(){window.a.q.push(arguments)},window.a.q=[]);window.a.c=(new Date).getTime();var c=document.createElement("script");c.src="//www.google-analytics.com/analytics.js";c.async=!0;var d=document.getElementsByTagName("script")[0];d.parentNode.insertBefore(c,d)})();
</code>```

This time, the code is less DRY and bigger, even without the two extra commands.

So to clarify, I am curious how the Google engineers arrived to the above result (I do not think their code actually looks like the one in Stephen's example), and could this process be replicated even if you are not a part of Google? Thank you in advance!

答:
It's actually fairly simple and a fun task to write such scripts.

Here is a long example how to turn a regular function into something like this:

I'd start with an imaginary script. I've included a scriptLoader which loads a javascript file asynchronously:

```<code>window.loadScript  = function(src){
    const scriptTag = document.createElement('script');
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = document.getElementsByTagName('script')[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}
</code>```

When called like this: loadScript("/url.js") it will insert a new script tag (before the first script tag) in the DOM and the browser will download the script.

So far so good. Let's say I want to pass this script arguments before it has loaded. Inside the script that will be loaded I access a unique global object. Let's call it window.myScriptArgs. So ideally, once the script has loaded it reads window.myScriptArgs and executes accordingly.

Now I could do window.myScriptArgs = [] and call it a day but since my hypothetical example will only load a single script file, I add the logic to the loadScript function as well.

```<code>window.loadScript  = function(src){
    window.myScriptArgs = window.myScriptArgs || [];
    const scriptTag = document.createElement('script');
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = document.getElementsByTagName('script')[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}
loadScript("/my-script.js");
</code>```

Okay, so I check if myScriptArgs is already present and if not I set it to an empty array.
Now I also know that my-script.js exposes a global myScript() method. So I write a stub for it. This stub will put every argument received to it into the myScriptArgs array:

```<code>window.myScript = () => {
     window.myScriptArgs = window.myScriptArgs || [];
     window.myScriptArgs.push(arguments);
}
</code>```

Now I can call loadScript and immediately call myScript() with given arguments. No need to worry about loading issues or whatnot. Once "my-script.js" is loaded it reads window.myScriptArgs and acts as excepted. The code looks like this:

```<code>window.myScript = () => {
    window.myScriptArgs = window.myScriptArgs || [];
    window.myScriptArgs.push(arguments);
}

window.loadScript  = function(src){
    window.myScriptArgs = window.myScriptArgs || [];
    const scriptTag = document.createElement('script');
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = document.getElementsByTagName('script')[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}
loadScript("/my-script.js");
myScript('command', 'args', 'args1');
myScript('command2', 'args3', 'args4');
</code>```

Okay, that works as expected. Let's optimize it. First I combine the loadScript and myScript stub to a single function called initMyScript():

```<code>window.initMyScript = function(src){
    window.myScriptArgs = window.myScriptArgs || [];
    window.myScript = window.myScript || function(){
        window.myScriptArgs.push(arguments);
    }

    const scriptTag = document.createElement('script');
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = document.getElementsByTagName('script')[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}
initMyScript("/my-script.js");
myScript('command', 'args', 'args1');
myScript('command2', 'args3', 'args4');
</code>```

It's nothing too fancy atm. Now I'm going to get rid of the multiple window. calls by passing window as an argument to initMyScript. I'll also do this with document.

The script looks like this:

```<code>window.initMyScript = function(p, a, src){
    p.myScriptArgs = p.myScriptArgs || [];
    p.myScript = p.myScript || function(){
        p.myScriptArgs.push(arguments);
    }

    const scriptTag = a.createElement('script');
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = a.getElementsByTagName('script')[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}
initMyScript(window, document, "/my-script.js");
</code>```

Now let's see where I repeat myself to save some more bits. I use the string script twice, same for myScript:

```<code>window.initMyScript = function(p, a, s, c, src){
    p.myScriptArgs = p.myScriptArgs || [];
    p[c] = p[c] || function(){
        p.myScriptArgs.push(arguments);
    }

    const scriptTag = a.createElement(s);
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = a.getElementsByTagName(s)[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}
initMyScript(window, document, 'script', 'myScript', "/my-script.js");
</code>```

Next step in my journey is to make the variables short. And I also turn this function into a self-executing function to save the window.initMyScript definition:

```<code>(function(p, a, s, c, src){
    p.myScriptArgs = p.myScriptArgs || [];
    p[c] = p[c] || function(){
        p.myScriptArgs.push(arguments);
    }

    const q = a.createElement(s);
    q.async = true;
    q.src = src;

    const d = a.getElementsByTagName(s)[0];
    d.parentNode.insertBefore(q, d);
})(window, document, 'script', 'myScript', "/my-script.js");
</code>```

And to my last mystery: I edit the function parameters to confuse people and also minify the code even more. You can actually chain functions in javascript using commas ;).

```<code>(function(p, a, s, c, A, l, i){
    p["myScriptArgs"]=p["myScriptArgs"]||[],p[c] = p[c]||function(){
        p["myScriptArgs"].push(arguments)},
    l = a.createElement(s);l.async = true;l[A] = A;
    i = a.getElementsByTagName(s)[0];
    i.parentNode.insertBefore(l, i);
})(window, document, 'script', 'myScript', "/my-script.js");
myScript("arg1", "arg2");
myScript("arg2", "arg3");
</code>```

Do note that I add two extra parameters in the function, that's because I need to save the element returned by createElement and don't want to use a var statement ;).

You can take this even further, but you get the point. For small functions, you can do it yourself without a problem.

Furthermore, you can use a minifier like UglifyJS and then rename the variables yourself afterward if you are really into that whole isogram thing...

Note: I didn't test any of this code. Here be dragons.
The imaginary code is my bad attempt at de-obfuscating googles example. The google-analytics snippet works almost the same as my custom snippet. GA optimizes a bit more (e.g. turning true into 1) but you get the point.

Read more about the things used in my example:
Immediately Invoked Function Expression
Property accessors (especially Bracket notation)

And javascript specific things like passing three arguments to a function which takes 5.

Body:
Most of you are probably familiar with this little tracking code offered by Google Analytics.

The interesting part is that this little excerpt contains arguments that form the word isogram. This script also uses arguments to declare variables to shave off some bits from the final file size. Arguably, you would not use this pattern when writing the code (?), so my question is, how does Google minify its code and are these techniques available to mere mortals, too?

I found online this example by Stephen Morley that includes a code that looks like something you'd write before minifying it. I took that code and run it through Google's very own Closure Compiler on advanced optimisation. As expected, the resulting code is nothing like the actual script used by Google Analytics.

(function(){window.b="ga";"ga"in window||(window.a=function(){window.a.q.push(arguments)},window.a.q=[]);window.a.c=(new Date).getTime();var c=document.createElement("script");c.src="//www.google-analytics.com/analytics.js";c.async=!0;var d=document.getElementsByTagName("script")[0];d.parentNode.insertBefore(c,d)})();

This time, the code is less DRY and bigger, even without the two extra commands.

So to clarify, I am curious how the Google engineers arrived to the above result (I do not think their code actually looks like the one in Stephen's example), and could this process be replicated even if you are not a part of Google? Thank you in advance!

Body:
It's actually fairly simple and a fun task to write such scripts.

Here is a long example how to turn a regular function into something like this:

I'd start with an imaginary script. I've included a scriptLoader which loads a javascript file asynchronously:

window.loadScript  = function(src){
    const scriptTag = document.createElement('script');
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = document.getElementsByTagName('script')[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}

When called like this: loadScript("/url.js") it will insert a new script tag (before the first script tag) in the DOM and the browser will download the script.

So far so good. Let's say I want to pass this script arguments before it has loaded. Inside the script that will be loaded I access a unique global object. Let's call it window.myScriptArgs. So ideally, once the script has loaded it reads window.myScriptArgs and executes accordingly.

Now I could do window.myScriptArgs = [] and call it a day but since my hypothetical example will only load a single script file, I add the logic to the loadScript function as well.

window.loadScript  = function(src){
    window.myScriptArgs = window.myScriptArgs || [];
    const scriptTag = document.createElement('script');
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = document.getElementsByTagName('script')[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}
loadScript("/my-script.js");

Okay, so I check if myScriptArgs is already present and if not I set it to an empty array.
Now I also know that my-script.js exposes a global myScript() method. So I write a stub for it. This stub will put every argument received to it into the myScriptArgs array:

window.myScript = () => {
     window.myScriptArgs = window.myScriptArgs || [];
     window.myScriptArgs.push(arguments);
}

Now I can call loadScript and immediately call myScript() with given arguments. No need to worry about loading issues or whatnot. Once "my-script.js" is loaded it reads window.myScriptArgs and acts as excepted. The code looks like this:

window.myScript = () => {
    window.myScriptArgs = window.myScriptArgs || [];
    window.myScriptArgs.push(arguments);
}

window.loadScript  = function(src){
    window.myScriptArgs = window.myScriptArgs || [];
    const scriptTag = document.createElement('script');
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = document.getElementsByTagName('script')[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}
loadScript("/my-script.js");
myScript('command', 'args', 'args1');
myScript('command2', 'args3', 'args4');

Okay, that works as expected. Let's optimize it. First I combine the loadScript and myScript stub to a single function called initMyScript():

window.initMyScript = function(src){
    window.myScriptArgs = window.myScriptArgs || [];
    window.myScript = window.myScript || function(){
        window.myScriptArgs.push(arguments);
    }

    const scriptTag = document.createElement('script');
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = document.getElementsByTagName('script')[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}
initMyScript("/my-script.js");
myScript('command', 'args', 'args1');
myScript('command2', 'args3', 'args4');

It's nothing too fancy atm. Now I'm going to get rid of the multiple window. calls by passing window as an argument to initMyScript. I'll also do this with document.

The script looks like this:

window.initMyScript = function(p, a, src){
    p.myScriptArgs = p.myScriptArgs || [];
    p.myScript = p.myScript || function(){
        p.myScriptArgs.push(arguments);
    }

    const scriptTag = a.createElement('script');
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = a.getElementsByTagName('script')[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}
initMyScript(window, document, "/my-script.js");

Now let's see where I repeat myself to save some more bits. I use the string script twice, same for myScript:

window.initMyScript = function(p, a, s, c, src){
    p.myScriptArgs = p.myScriptArgs || [];
    p[c] = p[c] || function(){
        p.myScriptArgs.push(arguments);
    }

    const scriptTag = a.createElement(s);
    scriptTag.async = true;
    scriptTag.src = src;

    const anyOtherScriptTag = a.getElementsByTagName(s)[0];
    anyOtherScriptTag.parentNode.insertBefore(scriptTag, anyOtherScriptTag);
}
initMyScript(window, document, 'script', 'myScript', "/my-script.js");

Next step in my journey is to make the variables short. And I also turn this function into a self-executing function to save the window.initMyScript definition:

(function(p, a, s, c, src){
    p.myScriptArgs = p.myScriptArgs || [];
    p[c] = p[c] || function(){
        p.myScriptArgs.push(arguments);
    }

    const q = a.createElement(s);
    q.async = true;
    q.src = src;

    const d = a.getElementsByTagName(s)[0];
    d.parentNode.insertBefore(q, d);
})(window, document, 'script', 'myScript', "/my-script.js");

And to my last mystery: I edit the function parameters to confuse people and also minify the code even more. You can actually chain functions in javascript using commas ;).

(function(p, a, s, c, A, l, i){
    p["myScriptArgs"]=p["myScriptArgs"]||[],p[c] = p[c]||function(){
        p["myScriptArgs"].push(arguments)},
    l = a.createElement(s);l.async = true;l[A] = A;
    i = a.getElementsByTagName(s)[0];
    i.parentNode.insertBefore(l, i);
})(window, document, 'script', 'myScript', "/my-script.js");
myScript("arg1", "arg2");
myScript("arg2", "arg3");

Do note that I add two extra parameters in the function, that's because I need to save the element returned by createElement and don't want to use a var statement ;).

You can take this even further, but you get the point. For small functions, you can do it yourself without a problem.

Furthermore, you can use a minifier like UglifyJS and then rename the variables yourself afterward if you are really into that whole isogram thing...

Note: I didn't test any of this code. Here be dragons.
The imaginary code is my bad attempt at de-obfuscating googles example. The google-analytics snippet works almost the same as my custom snippet. GA optimizes a bit more (e.g. turning true into 1) but you get the point.

Read more about the things used in my example:
Immediately Invoked Function Expression
Property accessors (especially Bracket notation)

And javascript specific things like passing three arguments to a function which takes 5.


问:
datatable plugin not display elements after clicking again on link to show
I am using data table plugin for table pagination, it work for the first time, but when I click again on link to show the table all elements of data table plugin disappears, do you know how to solve this problem. thanks.

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title></title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid text-center">
      <div class="row content">
       <div class="col-lg-2 sidenav">
      <a href="#" id="link3" class="list-group-item">Vertical link #3</a>
        </div>
        <div class="col-lg-10 text-left">
          <div class="row">
            <div class="col-lg-12" id="content"></div>
          </div>
        </div>
      </div>
    </div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<!-- link3 -->
<script src="link3.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
</html>
</code>```

link3.js

```<code>$(document).ready(function(){
var table = $('<table><thead><tr><th>Name</th><th>Age</th><th>Position</th><th>Note</th></tr></thead><tbody></tbody></table>').addClass('table table-bordered table-hover search-table');
    $("#link3").on("click", function () {
      $('#content').html(table);
    $.ajax({
        url:'test.json',
        dataType:'json',
        type:'GET',
        Accept:"aplication/json",
        cache:false,
        success:function(data){
            $.each(data, function(index, item){
                var id = item.name;
                var id2= item.age;
                var id3=item.position;
                var id4=item.note;
                $(".table").append("<tr><td>"+id+"</td><td>"+id2+"</td><td>"+id3+"</td><td>"+id4+"</td></tr>");
            });
            $('.search-table').DataTable();
        },
        error:function(e){
            alert("there is some thing wrong!")
        }
    });
});

});
</code>```

test.json

```<code>[

  {
    "name": "Olivia Doe",
    "age": "18",
    "position": "SW developer",
    "note": ""
  },
  {
    "name": "Sophia Doe",
    "age": "19",
    "position": "Graphic",
    "note": ""
  },
  {
    "name": "Ava Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Joshua Doe",
    "age": "21",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Viktor Doe",
    "age": "22",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Ahmed Doe",
    "age": "23",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Emma Doe",
    "age": "24",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Evelyn Doe",
    "age": "25",
    "position": "Analyst",
    "note": "Evelyn's work is always amazing!"
  },
  {
    "name": "Noah Doe",
    "age": "26",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Liam Doe",
    "age": "27",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Mason Doe",
    "age": "28",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Jacob Doe",
    "age": "29",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "William Doe",
    "age": "30",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Ethan Doe",
    "age": "18",
    "position": "Project manager",
    "note": "Great job Ethan\nas always!"
  },
  {
    "name": "James Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Alexander Doe",
    "age": "21",
    "position": "Project manager",
    "note": ""
  }
]
</code>```

答:
You can try doing this

```<code>$('#mytable').DataTable({"sAjaxSource" : "Your_url"});
</code>```

Provide the url that returns your jsondata.

Body:
I am using data table plugin for table pagination, it work for the first time, but when I click again on link to show the table all elements of data table plugin disappears, do you know how to solve this problem. thanks.

index.html

<!DOCTYPE html>

  <title></title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" rel="stylesheet">

      Vertical link #3

link3.js

$(document).ready(function(){
var table = $('

Name	Age	Position	Note

').addClass('table table-bordered table-hover search-table');
    $("#link3").on("click", function () {
      $('#content').html(table);
    $.ajax({
        url:'test.json',
        dataType:'json',
        type:'GET',
        Accept:"aplication/json",
        cache:false,
        success:function(data){
            $.each(data, function(index, item){
                var id = item.name;
                var id2= item.age;
                var id3=item.position;
                var id4=item.note;
                $(".table").append("
"+id+"	"+id2+"	"+id3+"	"+id4+"
");
            });
            $('.search-table').DataTable();
        },
        error:function(e){
            alert("there is some thing wrong!")
        }
    });
});

});

test.json

[

  {
    "name": "Olivia Doe",
    "age": "18",
    "position": "SW developer",
    "note": ""
  },
  {
    "name": "Sophia Doe",
    "age": "19",
    "position": "Graphic",
    "note": ""
  },
  {
    "name": "Ava Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Joshua Doe",
    "age": "21",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Viktor Doe",
    "age": "22",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Ahmed Doe",
    "age": "23",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Emma Doe",
    "age": "24",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Evelyn Doe",
    "age": "25",
    "position": "Analyst",
    "note": "Evelyn's work is always amazing!"
  },
  {
    "name": "Noah Doe",
    "age": "26",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Liam Doe",
    "age": "27",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Mason Doe",
    "age": "28",
    "position": "Analyst",
    "note": ""
  },
  {
    "name": "Jacob Doe",
    "age": "29",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "William Doe",
    "age": "30",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Ethan Doe",
    "age": "18",
    "position": "Project manager",
    "note": "Great job Ethan\nas always!"
  },
  {
    "name": "James Doe",
    "age": "20",
    "position": "Project manager",
    "note": ""
  },
  {
    "name": "Alexander Doe",
    "age": "21",
    "position": "Project manager",
    "note": ""
  }
]

Body:
You can try doing this

$('#mytable').DataTable({"sAjaxSource" : "Your_url"});

Provide the url that returns your jsondata.

ContentLicense: CC BY-SA 4.0


问:
Does cobalt support YouTube 360 Video(Spherical Video)
Dose cobalt support youtube 360 video(Spherical Video)? If yes, how it's been implemented, is there any document for it? Does it need the platform to do extra things to support it?</p>

答:
Almost. There is still some small remaining work that prevents this from being a simple yes, but the vast bulk of the work is done and has been shown to function.

A document will soon be appearing in the source tree explaining all this, but here is a preview...

In order to support spherical video, a platform will have to support decode-to-texture, introduced in Starboard API version 4. Cobalt will choose between punch-out and decode-to-texture when creating an SbPlayer, based on whether a mesh transform has been applied to the video tag. In decode-to-texture mode, every frame, the video texture will then be queried from the player, and rendered into the UI graphics plane with the current transform applied.


问:
How to enable SMTP port 25 in Google Cloud Redhat 7 instance?
I am using webmail to configure the mail service. the webmail to any external mail providers(gmail,yahoo) is not working. the serviceis working fine within webmail to webmail accounts. from research i found that google cloud is not allowing SMTP to connect on PORT 25.

How to solve this?

答: You can use port 2525 to send email from google cloud. Almost all major email service providers support port 2525. But all other smtp ports are blocked for outbound mail.</p>


问:
Laravel comments and user relationship returns null
I'm trying to implement commenting system on my website but i'm having hard time with the relationships. for some reason when i try to access the user relation from the comment class it returns null.. my code:
Post.php

```<code>    class Post extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['title','created_at','username','image'];
    public function user()
    {
      return $this->belongsTo(User::class,'username');
    }
    public function votes()
    {
      //Quick note: Id refers to the post id.
      return $this->hasMany(PostVotes::class,'post_id');
    }
    public function comments()
    {
      return $this->hasMany(Comment::class,'post_id');
    }
}
</code>```

User.php

```<code>class User extends Model implements Authenticatable
{
  use AuthenticableTrait;
  protected $primaryKey = 'username';
  public $incrementing = false;
  public $timestamps = false;
  protected $fillable = ['username','email','password','created_at','avatar','about'];
  // Gets avatar to display on navbar.
  public function posts()
  {
    return $this->hasMany(Post::class,'username');
  }
  public function comments()
  {
    return $this->hasMany(Comment::class,'username');
  }
  public static function getAvatar()
  {
     return self::Where('username', '=', Session::get('username'))->value('avatar');
  }

}
</code>```

Comment.php

```<code>    class Comment extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['comment','created_at','post_id','username'];
    public function user()
    {
        $this->belongsTo(User::class,'username') ;
    }
    public function post()
    {
        $this->belongsTo(Post::class,'post_id');
    }
}
public function view($post_id)
   {
      $post = Post::with('comments')->findOrFail($post_id);
      return view('posts.view',compact('post'));
   }
  @foreach($post->comments as $comment)
 // null
 {{dd($comment->user())}}
@endforeach
</code>```

答:
```<code>    public function displaycomment($id) {
        $data['comment'] = comment::select('comments.id', 'comments.description', 'users.name', 'comments.created_at', 'comments.post_id')->where('post_id',$id)->leftjoin('users', 'users.id', '=', 'comments.user_id')->get();
//        dd($data);
        return view('displayblog',  compact('data'));
    }
</code>```

Body:
I'm trying to implement commenting system on my website but i'm having hard time with the relationships. for some reason when i try to access the user relation from the comment class it returns null.. my code:
Post.php

    class Post extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['title','created_at','username','image'];
    public function user()
    {
      return $this->belongsTo(User::class,'username');
    }
    public function votes()
    {
      //Quick note: Id refers to the post id.
      return $this->hasMany(PostVotes::class,'post_id');
    }
    public function comments()
    {
      return $this->hasMany(Comment::class,'post_id');
    }
}

User.php

class User extends Model implements Authenticatable
{
  use AuthenticableTrait;
  protected $primaryKey = 'username';
  public $incrementing = false;
  public $timestamps = false;
  protected $fillable = ['username','email','password','created_at','avatar','about'];
  // Gets avatar to display on navbar.
  public function posts()
  {
    return $this->hasMany(Post::class,'username');
  }
  public function comments()
  {
    return $this->hasMany(Comment::class,'username');
  }
  public static function getAvatar()
  {
     return self::Where('username', '=', Session::get('username'))->value('avatar');
  }

}

Comment.php

    class Comment extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['comment','created_at','post_id','username'];
    public function user()
    {
        $this->belongsTo(User::class,'username') ;
    }
    public function post()
    {
        $this->belongsTo(Post::class,'post_id');
    }
}
public function view($post_id)
   {
      $post = Post::with('comments')->findOrFail($post_id);
      return view('posts.view',compact('post'));
   }
  @foreach($post->comments as $comment)
 // null
 {{dd($comment->user())}}
@endforeach


问:
How to keep API key of restful webservices safe in android app?
I have been doing an Android project involving restful web services. What is the best way to keep API key safe. I have read a lot online. Many say it is safe to keep key in the server and use it and that it will be safe. I don't understand what that means. By my understanding saving key in the server means that the app needs to fetch it during operation by using volley or any other httpclient by providing an url. The attacker can decompile the apk file and see the url from which the key is obtained, get the key and do his nasty work. Am I getting things wrong? How can storing API key in the server be safe? Please help me understand.</p>

答: you should write something like a SecureStorage using the Android Keystore and SharedPreferences and put the string inside it. We are currently developing such a library --> have a look at it here</p>


问:
Recursive queries in a batch with Apollo (graphql)
Facebook flaunted ability to commit recursive queries when opening graphql, I'm struggling to find documentation that permits you to do it efficiently (networking wise) and easily.

To be precise I'd like query child (name) > name child (curName) [ name child ...] potentially until I exhaust the whole tree without entering arbitrary number of branches within query itself if its possible.

答:
The field resolver actually solve it. There are basically two kinds of queries in graphql server, one is root query resolver, and the other is the field resolver. See the following example in apollo, but the idea behind is the same:

```<code>type Person {
   name: String
   friends: [Person]
}

type Query {
    allPeople($name: String):[Person]
}

schema {
    query: Query
}
</code>```

Based on the above typedef, you can write a root query resolver like below:

```<code>{
    Query: {
        allPeople: (root, args) => PersonModel.find({where: {name: args.name}})
    }
}
</code>```

And you also need to write a resolver for the friends field like below:

```<code>{
    Person: {
        friends: (root, args) => PersonModel.find({where: {friendId: root.id}})
    }
}
</code>```

Because of the field resolver, it can go infinite nesting.

By the way, in order to avoid too many sql statements hitting db, we can introduce dataloader package which is from facebook it can combine all queries in one async chain into one batch query we provide when initialising dataloader.

The code above is kind of pseudocode, hope it explained well.

Cheers,
Ron

Body:
The field resolver actually solve it. There are basically two kinds of queries in graphql server, one is root query resolver, and the other is the field resolver. See the following example in apollo, but the idea behind is the same:

type Person {
   name: String
   friends: [Person]
}

type Query {
    allPeople($name: String):[Person]
}

schema {
    query: Query
}

Based on the above typedef, you can write a root query resolver like below:

{
    Query: {
        allPeople: (root, args) => PersonModel.find({where: {name: args.name}})
    }
}

And you also need to write a resolver for the friends field like below:

{
    Person: {
        friends: (root, args) => PersonModel.find({where: {friendId: root.id}})
    }
}

Because of the field resolver, it can go infinite nesting.

By the way, in order to avoid too many sql statements hitting db, we can introduce dataloader package which is from facebook it can combine all queries in one async chain into one batch query we provide when initialising dataloader.

The code above is kind of pseudocode, hope it explained well.

Cheers,
Ron


问:
Reference binding and the copy constructor/move constructor
If I have a function like so:

```<code>int foo(std::vector<int>* integer1ArrayIn, * integer2ArrayIn) {
    std::vector<int>& integer1Array = *integer1ArrayIn;
    std::vector<int>& integer2Array = *integer2ArrayIn;
}
</code>```

Will the reference integer1Array be calling a copy constructor/move constructor to copy over the elements of the passed in parameter?

Does binding a reference to a dereferenced pointer call the copy constructor?

In what circumstances does reference binding invoke a copy constructor?

Can someone explain what happens as this code executes in memory?

Thank you

答:
No.

No, but it would crash badly if it was nullptr. Consider passing by reference whenever a parameter HAS to be there, and pass by pointer when a parameter MIGHT be there (but always verify for nullptr too!).

Whenever the l-value (in this case integer1Array and integer2Array) are pointers or references, it will never call copy/move constructor.

if you had std::vector integer1Array = *integer1ArrayIn it would effectively make a copy.

You can use Jonas's answer to play around with and see for yourself :)

Body:
If I have a function like so:

int foo(std::vector<int>* integer1ArrayIn, * integer2ArrayIn) {
    std::vector<int>& integer1Array = *integer1ArrayIn;
    std::vector<int>& integer2Array = *integer2ArrayIn;
}

Will the reference integer1Array be calling a copy constructor/move constructor to copy over the elements of the passed in parameter?

Does binding a reference to a dereferenced pointer call the copy constructor?

In what circumstances does reference binding invoke a copy constructor?

Can someone explain what happens as this code executes in memory?

Thank you


问:
How to resize QPlainTextEdit widget when displayed
I have a QT GUI application, it has a vertical layout all the controls expand to fill the layout. If I add a QTextBox to the layout it has a fixed size (too big), I can change this in the designer or in code (in the MainWindow constructor)

```<code>    m_textEdit->setMaximumHeight(3 * RowHeight);
</code>```

but then it seems it is fixed permanently. I want to make it bigger when it has focus.

I have tried css

```<code>  m_textEdit->setStyleSheet("QPlainTextEdit:focus{max-height: 400px}");
</code>```

I have tried the resize function which is called in an action

```<code>  m_textEdit->resize(m_textEdit->width(), 3 * RowHeight);
</code>```

also doesn't resize once displayed.

I also thought that maybe I could put it in a splitter layout which would then be resizeable, but then the controls didn't expand with the window size.

Any ideas anyone?

答:
You can change the widget size dynamically depending on the focus. When it's enterred, make the size bigger. When it's left, make the size smaller.

There are multiple ways to do this. In my opinion, the cleaner and easier way is by installing an event filter to your widget.
In this event filter, you will handle the QEvent::FocusIn and QEvent::FocusOut to change the size of your widget.

The CSS change is not the way to go in your case, neither is the resize.

The more convenient way is by changing the width/height using minimum, fixed, maximum).

It's up to you to decide which strategy, if you want to set the size using QWidget::setFixedXXX, or some QWidget::setMaximumXXX, QWidget::setMinimumXXX method. I like the Fixed one, but it really depends on your application style, and your layout context.

Official doc on event filter : (http://doc.qt.io/qt-5/qobject.html#installEventFilter).

Body:
I have a QT GUI application, it has a vertical layout all the controls expand to fill the layout. If I add a QTextBox to the layout it has a fixed size (too big), I can change this in the designer or in code (in the MainWindow constructor)

    m_textEdit->setMaximumHeight(3 * RowHeight);

but then it seems it is fixed permanently. I want to make it bigger when it has focus.

I have tried css

  m_textEdit->setStyleSheet("QPlainTextEdit:focus{max-height: 400px}");

I have tried the resize function which is called in an action

  m_textEdit->resize(m_textEdit->width(), 3 * RowHeight);

also doesn't resize once displayed.

I also thought that maybe I could put it in a splitter layout which would then be resizeable, but then the controls didn't expand with the window size.

Any ideas anyone?


问:
Replacing words in text file using a dictionary
I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

The code doesn't produce any errors, but also doesn't do any replacing.

```<code>import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)

             print line
</code>```

答:
This is how I would do it:</p>

```<code>fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

with open('yourfile.txt', 'w+') as f:
    s = f.read()
    for key in fields:
        s = s.replace(key, fields[key])
    f.write(s)
</code>```

Body:
I'm trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.

Based on answers to How do I edit a text file in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

The code doesn't produce any errors, but also doesn't do any replacing.

import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)

             print line

Body:
This is how I would do it:

fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

with open('yourfile.txt', 'w+') as f:
    s = f.read()
    for key in fields:
        s = s.replace(key, fields[key])
    f.write(s)


问:
Will providing APIs help deter screen scraping?
I have been thinking quite a bit here lately about screen scraping and what a task it can be. So I pose the following question.

Would you as a site developer expose simple APIs to prevent users from screen scraping, such as JSON results?

These results could then implement caching, and they are much smaller for traffic than the huge amounts of markup that could potentially be downloaded.

I am not looking at prevention, but deterring scraping.

Scraping Bandwidth Sample

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

users: 200,000

% of users using utility: 5

filesize: 1kb

freq: 1 minute

Formula:

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

10,000 * 1440 * 1

14400000kb or 13.73291015625gb

Assuming your JSON result is 200 bytes that's now (10,000 * 1440 * 0.2) or 2.74658203125gb a day.

That's a change of about 11gb of traffic a day.

My Stack Overflow profile is 96k for reference.

The reason for this question prompted asking for a JSON result from users profiles:

http://stackoverflow.uservoice.com/pages/general/suggestions/101342-add-json-for-user-information

I wanted to find out if other developers would expose this type of API, and if it is worth your time to provide these APIs to reduce bandwidth.

答:
If it's easier for technical users to use an API than it is for them to screen-scrape, they will do so.  Even better so, if you can encourage people to use your APIs instead of screen-scraping, you should have a much easier time monitoring traffic, because the automated user-agents are clearly distinguished from the browser user-agents.

A RESTful JSON interface is a good choice, because it can be scripted from any other language fairly easy (show me a language that doesn't have a JSON parser and I'll show you a language nobody cares about).

OwnerDisplayName: Tom Anderson

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Tom Anderson

OwnerDisplayName: Tom


问:
Ajax.Actionlink opens in a new page
I have a partial view that needs to get loaded between two div but when the ajax.actionlink is invoked it open the content in the partial view in a new browser window. I use UpdateTargetId = "ajaxReplace"

Regards

答:
Did you include/reference all the necessary javascript files?

You say you use MVC 3.

If you have UnobtrusiveJavaScriptEnabled then you'll need:

jQuery

jquery.unobtrusive-ajax.js

if you also use client side validation, you'll need;

jquery.validate.js

jquery.validate.unobtrusive.js

These files can all be found when you create a new MVC3 project.

Title: Ajax.Actionlink opens in a new page


问:
How to find the date n days ago in Python?
I would like to write a script where I give Python a number of days (let's call it d) and it gives me the date we were d days ago.

I am struggling with the module datetime:

```<code>import datetime

tod = datetime.datetime.now()
d = timedelta(days = 50)
a = tod - h
Type Error : unsupported operand type for - : "datetime.timedelta" and
"datetime.datetime"
</code>```

答:
If your arguments are something like, yesterday,2 days ago, 3 months ago, 2 years ago. The function below could be of help in getting the exact date for the arguments.
You first need to import the following date utils

```<code>import datetime
from dateutil.relativedelta import relativedelta
</code>```

Then implement the function below

```<code>def get_past_date(str_days_ago):
    TODAY = datetime.date.today()
    splitted = str_days_ago.split()
    if len(splitted) == 1 and splitted[0].lower() == 'today':
        return str(TODAY.isoformat())
    elif len(splitted) == 1 and splitted[0].lower() == 'yesterday':
        date = TODAY - relativedelta(days=1)
        return str(date.isoformat())
    elif splitted[1].lower() in ['hour', 'hours', 'hr', 'hrs', 'h']:
        date = datetime.datetime.now() - relativedelta(hours=int(splitted[0]))
        return str(date.date().isoformat())
    elif splitted[1].lower() in ['day', 'days', 'd']:
        date = TODAY - relativedelta(days=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['wk', 'wks', 'week', 'weeks', 'w']:
        date = TODAY - relativedelta(weeks=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['mon', 'mons', 'month', 'months', 'm']:
        date = TODAY - relativedelta(months=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['yrs', 'yr', 'years', 'year', 'y']:
        date = TODAY - relativedelta(years=int(splitted[0]))
        return str(date.isoformat())
    else:
        return "Wrong Argument format"
</code>```

You can then call the function like this:

```<code>print get_past_date('5 hours ago')
print get_past_date('yesterday')
print get_past_date('3 days ago')
print get_past_date('4 months ago')
print get_past_date('2 years ago')
print get_past_date('today')
</code>```

Body:
I would like to write a script where I give Python a number of days (let's call it d) and it gives me the date we were d days ago.

I am struggling with the module datetime:

import datetime

tod = datetime.datetime.now()
d = timedelta(days = 50)
a = tod - h
Type Error : unsupported operand type for - : "datetime.timedelta" and
"datetime.datetime"

Body:
If your arguments are something like, yesterday,2 days ago, 3 months ago, 2 years ago. The function below could be of help in getting the exact date for the arguments.
You first need to import the following date utils

import datetime
from dateutil.relativedelta import relativedelta

Then implement the function below

def get_past_date(str_days_ago):
    TODAY = datetime.date.today()
    splitted = str_days_ago.split()
    if len(splitted) == 1 and splitted[0].lower() == 'today':
        return str(TODAY.isoformat())
    elif len(splitted) == 1 and splitted[0].lower() == 'yesterday':
        date = TODAY - relativedelta(days=1)
        return str(date.isoformat())
    elif splitted[1].lower() in ['hour', 'hours', 'hr', 'hrs', 'h']:
        date = datetime.datetime.now() - relativedelta(hours=int(splitted[0]))
        return str(date.date().isoformat())
    elif splitted[1].lower() in ['day', 'days', 'd']:
        date = TODAY - relativedelta(days=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['wk', 'wks', 'week', 'weeks', 'w']:
        date = TODAY - relativedelta(weeks=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['mon', 'mons', 'month', 'months', 'm']:
        date = TODAY - relativedelta(months=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['yrs', 'yr', 'years', 'year', 'y']:
        date = TODAY - relativedelta(years=int(splitted[0]))
        return str(date.isoformat())
    else:
        return "Wrong Argument format"

You can then call the function like this:

print get_past_date('5 hours ago')
print get_past_date('yesterday')
print get_past_date('3 days ago')
print get_past_date('4 months ago')
print get_past_date('2 years ago')
print get_past_date('today')


问:
How to Split DataSet in 2 to Display in Different GridViews
How can I split a DataSet in half so that each half can be bound to a seperate GridView?

Currently I am doing:

```<code>gridviewQc1.DataSource = SelectedQCItems;
gridviewQc1.DataBind();
</code>```

Where SelectedQCItems is my DataSet.

What I would like to do:

```<code>gridviewQc1.DataSource = SelectedQCItemsFirstHalf;
gridviewQc1.DataBind();

gridviewQc2.DataSource = SelectedQCItemsSecondHalf;
gridviewQc2.DataBind();
</code>```

I tried calling

```<code>var table = SelectedQCItems.Tables[0];
var halfData = table.Select().Take(table.Rows.Count/2);
gridviewQc1.DataSource = halfData;
gridviewQc1.DataBind();
</code>```

But on the last line I get a HttpException

A field or property with the name 'Criteria' was not found on the selected data source.

I guess the header names are not stored in each individual Table object in the DataSet.

Am I doing something wrong or should I appraoch this differently?

The code for the GridView:

```<code><asp:GridView ID="gridviewQc1" runat="server" AutoGenerateColumns="false"
    AutoGenerateSelectButton="true" OnRowDataBound="gridviewQc1_RowDataBound"
    OnSelectedIndexChanged="gridviewQc1_SelectedIndexChanged" >
    <Columns>
        <asp:BoundField HeaderText="Criteria" DataField="Criteria" />
        <asp:BoundField HeaderText="Major" DataField="Major" />
        <asp:BoundField HeaderText="Mass" DataField="Mass"/>
    </Columns>
</asp:GridView>
</code>```

答:
I was able to do this with the below code, which creates 2 copies the DataSet and then deletes half of the entries from each copy before binding them to the 2 GridViews:

```<code>var ds1 = SelectedQCItems.Copy();
var ds2 = SelectedQCItems.Copy();

var lastRowIndex = SelectedQCItems.Tables[0].Rows.Count - 1;
var halfwayIndex = SelectedQCItems.Tables[0].Rows.Count / 2 - 1;

for (int i = lastRowIndex; i > halfwayIndex; i--)
{
    ds1.Tables[0].Rows.RemoveAt(i);
}
ds1.AcceptChanges();

for (int i = halfwayIndex; i > -1; i--)
{
    ds2.Tables[0].Rows.RemoveAt(i);
}
ds2.AcceptChanges();

var one = ds1.Tables[0].Rows.Count;
var two = ds2.Tables[0].Rows.Count;

gridviewQc1.DataSource = ds1;
gridviewQc1.DataBind();

gridviewQc2.DataSource = ds2;
gridviewQc2.DataBind();
</code>```

Body:
How can I split a DataSet in half so that each half can be bound to a seperate GridView?

Currently I am doing:

gridviewQc1.DataSource = SelectedQCItems;
gridviewQc1.DataBind();

Where SelectedQCItems is my DataSet.

What I would like to do:

gridviewQc1.DataSource = SelectedQCItemsFirstHalf;
gridviewQc1.DataBind();

gridviewQc2.DataSource = SelectedQCItemsSecondHalf;
gridviewQc2.DataBind();

I tried calling

var table = SelectedQCItems.Tables[0];
var halfData = table.Select().Take(table.Rows.Count/2);
gridviewQc1.DataSource = halfData;
gridviewQc1.DataBind();

But on the last line I get a HttpException

A field or property with the name 'Criteria' was not found on the selected data source.

I guess the header names are not stored in each individual Table object in the DataSet.

Am I doing something wrong or should I appraoch this differently?

The code for the GridView:

<asp:GridView ID="gridviewQc1" runat="server" AutoGenerateColumns="false"
    AutoGenerateSelectButton="true" OnRowDataBound="gridviewQc1_RowDataBound"
    OnSelectedIndexChanged="gridviewQc1_SelectedIndexChanged" >
    <Columns>
        <asp:BoundField HeaderText="Criteria" DataField="Criteria" />
        <asp:BoundField HeaderText="Major" DataField="Major" />
        <asp:BoundField HeaderText="Mass" DataField="Mass"/>
    </Columns>
</asp:GridView>

Body:
I was able to do this with the below code, which creates 2 copies the DataSet and then deletes half of the entries from each copy before binding them to the 2 GridViews:

var ds1 = SelectedQCItems.Copy();
var ds2 = SelectedQCItems.Copy();

var lastRowIndex = SelectedQCItems.Tables[0].Rows.Count - 1;
var halfwayIndex = SelectedQCItems.Tables[0].Rows.Count / 2 - 1;

for (int i = lastRowIndex; i > halfwayIndex; i--)
{
    ds1.Tables[0].Rows.RemoveAt(i);
}
ds1.AcceptChanges();

for (int i = halfwayIndex; i > -1; i--)
{
    ds2.Tables[0].Rows.RemoveAt(i);
}
ds2.AcceptChanges();

var one = ds1.Tables[0].Rows.Count;
var two = ds2.Tables[0].Rows.Count;

gridviewQc1.DataSource = ds1;
gridviewQc1.DataBind();

gridviewQc2.DataSource = ds2;
gridviewQc2.DataBind();


问:
rspec create() method not working
I am working on an online learning portal like bento. For a user to unlock the next lesson, they must have to review at least one submission from the other user on the assignment of any previous lessons(complete by the current user). Considering this logic, I have a rspec test where I have tested if the page is being redirected to the other user's submission or not? In order to pass the test, I have to create dummy submission. For that, I am using create() method but the redirection to submission page is failing on the test but it works fine on the website. The code responsible for redirection in submission_controller is

```<code>def review_submission
 @submission = Submission.where('lesson_id < ?', current_user.submissions.last.assignment.lesson_id.to_i)
                        .shuffle[1]
 if @submission.nil?
  redirect_to @assignment
 else
  redirect_to assignment_submission_path(assignment_id: @assignment.id, id: @submission.id)
 end
end
</code>```

The code of the test is

```<code>it "redirects to submission path" do
    admin_user = create(:admin_user)
    sign_in admin_user
    user = create(:user)
    sign_in user
    assignment = create(:assignment, admin_user_id: admin_user.id)
    #I was creating dummy submissions data using rspec create method.
    submission = create(:submission, lesson_id: 1)
    post :create, params: { submission: attributes_for(:submission, user_id: user.id), assignment_id: assignment.id}

    expect(response).to redirect_to assignment_submission_path( assignment_id: assignment.id, id: Submission.last.id)
  end
</code>```

Dummy data is coming from FactoryGirl

```<code>factory :submission do
  user_id 1
  assignment_id 1
  lesson_id 2
  content "this is the submission of my assignment"
  factory :invalid_submission do
    content ""
  end
end
</code>```

Any suggestions are highly appreciated. Thank you in advance.

答:
It looks like @submission is nil, so it's redirecting you to the Attachments#show page instead of the Submissions#show page. You're setting it like:

```<code>@submission = Submission.where('lesson_id < ?', current_user.submissions.last.assignment.lesson_id.to_i).shuffle[1]
</code>```

It's trying to find the Submission based on current_user.submissions. Your Factory is just making the submission like:

```<code>submission = create(:submission, lesson_id: 1)
</code>```

That defaults the user_id to be 1, which probably isn't the ID of your signed in user (since you create the admin user above it). Try passing in the user_id to your FactoryGirl's creation of the Submission. May also want to pass in the assignment_id too actually, so the Submission will correctly belong to the Assignment.

```<code>submission = create(:submission, lesson_id: 1, user_id: user.id, assignment_id: assignment.id)
</code>```

Then the Submission should be assigned to your User, and hopefully the Controller will find it and your test will pass.

Title: rspec create() method not working

Body:
I am working on an online learning portal like bento. For a user to unlock the next lesson, they must have to review at least one submission from the other user on the assignment of any previous lessons(complete by the current user). Considering this logic, I have a rspec test where I have tested if the page is being redirected to the other user's submission or not? In order to pass the test, I have to create dummy submission. For that, I am using create() method but the redirection to submission page is failing on the test but it works fine on the website. The code responsible for redirection in submission_controller is

def review_submission
 @submission = Submission.where('lesson_id < ?', current_user.submissions.last.assignment.lesson_id.to_i)
                        .shuffle[1]
 if @submission.nil?
  redirect_to @assignment
 else
  redirect_to assignment_submission_path(assignment_id: @assignment.id, id: @submission.id)
 end
end

The code of the test is

it "redirects to submission path" do
    admin_user = create(:admin_user)
    sign_in admin_user
    user = create(:user)
    sign_in user
    assignment = create(:assignment, admin_user_id: admin_user.id)
    #I was creating dummy submissions data using rspec create method.
    submission = create(:submission, lesson_id: 1)
    post :create, params: { submission: attributes_for(:submission, user_id: user.id), assignment_id: assignment.id}

    expect(response).to redirect_to assignment_submission_path( assignment_id: assignment.id, id: Submission.last.id)
  end

Dummy data is coming from FactoryGirl

factory :submission do
  user_id 1
  assignment_id 1
  lesson_id 2
  content "this is the submission of my assignment"
  factory :invalid_submission do
    content ""
  end
end

Any suggestions are highly appreciated. Thank you in advance.

Body:
It looks like @submission is nil, so it's redirecting you to the Attachments#show page instead of the Submissions#show page. You're setting it like:

@submission = Submission.where('lesson_id < ?', current_user.submissions.last.assignment.lesson_id.to_i).shuffle[1]

It's trying to find the Submission based on current_user.submissions. Your Factory is just making the submission like:

submission = create(:submission, lesson_id: 1)

That defaults the user_id to be 1, which probably isn't the ID of your signed in user (since you create the admin user above it). Try passing in the user_id to your FactoryGirl's creation of the Submission. May also want to pass in the assignment_id too actually, so the Submission will correctly belong to the Assignment.

submission = create(:submission, lesson_id: 1, user_id: user.id, assignment_id: assignment.id)

Then the Submission should be assigned to your User, and hopefully the Controller will find it and your test will pass.


问:
is openjdk complete opensource implementation of java along with jvm and compiler?
does OpenJdk provide complete opensource implementation for java along with JVM and compiler sources, so that it can be modified by others and implement to distribute</p>

答:
Yes, OpenJDK is the Reference Implementation of Java SE.

It includes JVM, Class Library, tools etc.

The modification and distribution is subject to GNU General Public License, version 2 with the Classpath Exception.


问:
Want to pass ArrayList contain class objects in javascript
I have a ArrayList which contain objects of a Java Class.I want to pass that list to javascript and want to populate the data within the object in to jsp.
The ArrayList is present in the jsp.Each class object only contain 2 parameter values.Class name is 'Certificate' and it contain 'certId' and 'certName'

jsp:

```<code><%
 ArrayList getAllCertificateNamewithId=new ArrayList();
 getAllCertificateNamewithId=(ArrayList)mainMap.get("getAllCertificateNamewithIdMap");%>
<input type="button"  width="16" height="16"  onclick="fetchAndShow('<%=getAllCertificateNamewithId %>')" />
</code>```

Javascript

```<code>function fetchAndShow(certObj){
//How to fetch the list's each object  and cast to java class 'Certificate'
}
</code>```

List contain

```<code>[com.dto.Certificate@9b44a1, com.dto.Certificate@1b6b3ac]
</code>```

答: I don't know whether it would be right or not but it's worth a try. Try to use GSON or JACKSON libraries to convert your java object to JSON string. Then I think that you would be able to use that JSON String data in your Javascript code and get the certID and certName wherever you want.</p>

Body:
I have a ArrayList which contain objects of a Java Class.I want to pass that list to javascript and want to populate the data within the object in to jsp.
The ArrayList is present in the jsp.Each class object only contain 2 parameter values.Class name is 'Certificate' and it contain 'certId' and 'certName'

jsp:

<%
 ArrayList getAllCertificateNamewithId=new ArrayList();
 getAllCertificateNamewithId=(ArrayList)mainMap.get("getAllCertificateNamewithIdMap");%>
<input type="button"  width="16" height="16"  onclick="fetchAndShow('<%=getAllCertificateNamewithId %>')" />

Javascript

function fetchAndShow(certObj){
//How to fetch the list's each object  and cast to java class 'Certificate'
}

List contain

[com.dto.Certificate@9b44a1, com.dto.Certificate@1b6b3ac]


问:
AVPlayer not full screen in landscape mode using iOS swift
I have a video view set to full screen. However while playing in the simulator, it is not running full screen.

This issue is only for iPads and not iPhones.

Here is my code:

```<code>override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(true)

    let bundle: Bundle = Bundle.main
    let videoPlayer: String = bundle.path(forResource: "normalnewer", ofType: "mp4")!
    let movieUrl : NSURL = NSURL.fileURL(withPath: videoPlayer) as NSURL
    //        var fileURL = NSURL(fileURLWithPath: "/Users/Mantas/Desktop/123/123/video-1453562323.mp4.mp4")
    playerView = AVPlayer(url: movieUrl as URL)

    NotificationCenter.default.addObserver(self,selector: #selector(playerItemDidReachEnd),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: self.playerView.currentItem) // Add observer

            var playerLayer=AVPlayerLayer(player: playerView)
//        self.avPlayerLayer.playerLayer = AVLayerVideoGravityResizeAspectFill

    playerLayer.frame = viewVideo.bounds
//        self.playerLayer.frame = self.videoPreviewLayer.bounds

    viewVideo.layer.addSublayer(playerLayer)

    playerView.play()

    UserDefaults.standard.set("normalnewer", forKey: "video")

}
</code>```

I have tried checking landscape mode in target's general.
Gone through the threads below:
how to play a video in fullscreen mode using swift ios?

Play video fullscreen in landscape mode, when my entire application is in lock in portrait mode

Setting device orientation in Swift iOS

But these did not resolve my issue.
Here is a screenshot.

Can somebody help me resolve this?

答: After spending some time taking a good look at the Storyboard, I tried changing the fill to Aspect fill & fit and that resolved the problem :)</p>

Body:
I have a video view set to full screen. However while playing in the simulator, it is not running full screen.

This issue is only for iPads and not iPhones.

Here is my code:

override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(true)

    let bundle: Bundle = Bundle.main
    let videoPlayer: String = bundle.path(forResource: "normalnewer", ofType: "mp4")!
    let movieUrl : NSURL = NSURL.fileURL(withPath: videoPlayer) as NSURL
    //        var fileURL = NSURL(fileURLWithPath: "/Users/Mantas/Desktop/123/123/video-1453562323.mp4.mp4")
    playerView = AVPlayer(url: movieUrl as URL)

    NotificationCenter.default.addObserver(self,selector: #selector(playerItemDidReachEnd),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: self.playerView.currentItem) // Add observer

            var playerLayer=AVPlayerLayer(player: playerView)
//        self.avPlayerLayer.playerLayer = AVLayerVideoGravityResizeAspectFill

    playerLayer.frame = viewVideo.bounds
//        self.playerLayer.frame = self.videoPreviewLayer.bounds

    viewVideo.layer.addSublayer(playerLayer)

    playerView.play()

    UserDefaults.standard.set("normalnewer", forKey: "video")

}

I have tried checking landscape mode in target's general.
Gone through the threads below:
how to play a video in fullscreen mode using swift ios?

Play video fullscreen in landscape mode, when my entire application is in lock in portrait mode

Setting device orientation in Swift iOS

But these did not resolve my issue.
Here is a screenshot.

Can somebody help me resolve this?


问:
WINWORD.EXE remains running when filling word template
I created microsoft word template and I need  to pass data to word template.

I used following code, but after this code, word application task is not deleted from task manager, how to solve this?

WINWORD.EXE remains running when Word is closed

```<code>private void button1_Click(object sender, EventArgs e)
    {
        Object oMissing = System.Reflection.Missing.Value;
        Object oTemplatePath = "D:\\template.dotx";
        Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
        Document wordDoc = new Document();
        wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
        foreach (Field myMergeField in wordDoc.Fields)
        {
            Range rngFieldCode = myMergeField.Code;
            String fieldText = rngFieldCode.Text;

            if (fieldText.StartsWith(" MERGEFIELD"))
            {
                Int32 endMerge = fieldText.IndexOf("\\");
                Int32 fieldNameLength = fieldText.Length - endMerge;
                String fieldName = fieldText.Substring(11, endMerge - 11);
                fieldName = fieldName.Trim();
                if (fieldName == "lbl_name")
                {
                    myMergeField.Select();
                    wordApp.Selection.TypeText("my data");
                }
            }
        }
        wordDoc.SaveAs("D:\\myfile.doc");
        wordDoc.SaveAs2("D:\\myfile.pdf", WdSaveFormat.wdFormatPDF);
        wordDoc.Close();
        wordApp.Application.Quit();
    }
</code>```

答:
Add reference to Microsoft Word 12.0 Object Library.

Create a Word Template.

Select insert tab in word.

Select Quick Parts. Then Field.

Select field category as MergeField. Give the MergeField name as ‘lbl_name’.

And use following code for example :

```<code>   private void button1_Click(object sender, EventArgs e)
    {
        Object oMissing = System.Reflection.Missing.Value;
        Object oTemplatePath = "D:\\template.dotx";
        Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
        Document wordDoc = new Document();
        wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
        foreach (Field myMergeField in wordDoc.Fields)
        {
            Range rngFieldCode = myMergeField.Code;
            String fieldText = rngFieldCode.Text;

            if (fieldText.StartsWith(" MERGEFIELD"))
            {
                Int32 endMerge = fieldText.IndexOf("\\");
                Int32 fieldNameLength = fieldText.Length - endMerge;
                String fieldName = fieldText.Substring(11, endMerge - 11);
                fieldName = fieldName.Trim();
                if (fieldName == "lbl_name")
                {
                    myMergeField.Select();
                    wordApp.Selection.TypeText("my data");
                }
            }
        }
        wordDoc.SaveAs("D:\\myfile.doc");
        wordDoc.SaveAs2("D:\\myfile.pdf", WdSaveFormat.wdFormatPDF);
        wordDoc.Close();
        wordApp.Application.Quit();
    }
</code>```

Body:
I created microsoft word template and I need  to pass data to word template.

I used following code, but after this code, word application task is not deleted from task manager, how to solve this?

WINWORD.EXE remains running when Word is closed

private void button1_Click(object sender, EventArgs e)
    {
        Object oMissing = System.Reflection.Missing.Value;
        Object oTemplatePath = "D:\\template.dotx";
        Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
        Document wordDoc = new Document();
        wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
        foreach (Field myMergeField in wordDoc.Fields)
        {
            Range rngFieldCode = myMergeField.Code;
            String fieldText = rngFieldCode.Text;

            if (fieldText.StartsWith(" MERGEFIELD"))
            {
                Int32 endMerge = fieldText.IndexOf("\\");
                Int32 fieldNameLength = fieldText.Length - endMerge;
                String fieldName = fieldText.Substring(11, endMerge - 11);
                fieldName = fieldName.Trim();
                if (fieldName == "lbl_name")
                {
                    myMergeField.Select();
                    wordApp.Selection.TypeText("my data");
                }
            }
        }
        wordDoc.SaveAs("D:\\myfile.doc");
        wordDoc.SaveAs2("D:\\myfile.pdf", WdSaveFormat.wdFormatPDF);
        wordDoc.Close();
        wordApp.Application.Quit();
    }

Body:
Add reference to Microsoft Word 12.0 Object Library.

Create a Word Template.

Select insert tab in word.

Select Quick Parts. Then Field.

Select field category as MergeField. Give the MergeField name as ‘lbl_name’.

And use following code for example :

   private void button1_Click(object sender, EventArgs e)
    {
        Object oMissing = System.Reflection.Missing.Value;
        Object oTemplatePath = "D:\\template.dotx";
        Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
        Document wordDoc = new Document();
        wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
        foreach (Field myMergeField in wordDoc.Fields)
        {
            Range rngFieldCode = myMergeField.Code;
            String fieldText = rngFieldCode.Text;

            if (fieldText.StartsWith(" MERGEFIELD"))
            {
                Int32 endMerge = fieldText.IndexOf("\\");
                Int32 fieldNameLength = fieldText.Length - endMerge;
                String fieldName = fieldText.Substring(11, endMerge - 11);
                fieldName = fieldName.Trim();
                if (fieldName == "lbl_name")
                {
                    myMergeField.Select();
                    wordApp.Selection.TypeText("my data");
                }
            }
        }
        wordDoc.SaveAs("D:\\myfile.doc");
        wordDoc.SaveAs2("D:\\myfile.pdf", WdSaveFormat.wdFormatPDF);
        wordDoc.Close();
        wordApp.Application.Quit();
    }


问:
Email using C# The server responded Server Has exceeded SSP rate limit
When I am trying to sending mail from local PC . The error

```<code>Server Has exceeded SSP rate limit.
</code>```

Keeps coming. When I upload the same to my cloud server and sending mail from there , it works perfectly . why I am getting this issue.
This is the code I'm using to send the mail.

```<code>        MailMessage objMailMsg;
    Mail objMail = new Mail();
    ClsCommonFunctions objMessage = new ClsCommonFunctions();

    objMailMsg = new MailMessage();

    objMailMsg.To.Add(to.Trim());
    objMailMsg.From = new MailAddress("xxx@xx.com", "xxxxx");
    objMailMsg.Subject = subject;
    objMailMsg.Body = body;

    objMailMsg.IsBodyHtml = true;
    objMailMsg.BodyEncoding = System.Text.Encoding.GetEncoding("windows-1256");

    objMailMsg.Headers.Add("Disposition-Notification-To", "xxx@xxx.com");

    SmtpClient smtp = new SmtpClient("yyyy.com");

    smtp.Port = 25;
    smtp.Credentials = new System.Net.NetworkCredential("xxx@xxx.com", "password");

    try
    {
        smtp.Send(objMailMsg);

    }
    catch (Exception ex)
    {
        objMessage.show_message(this, ex.Message);
    }

    Thread.Sleep(1000);

    objMailMsg.To.Clear();
    objMailMsg.Dispose();
</code>```

答: Check with your SMTP provider if you can send emails from elsewhere than his network. External access is often blocked. </p>

Body:
When I am trying to sending mail from local PC . The error

Server Has exceeded SSP rate limit.

Keeps coming. When I upload the same to my cloud server and sending mail from there , it works perfectly . why I am getting this issue.
This is the code I'm using to send the mail.

        MailMessage objMailMsg;
    Mail objMail = new Mail();
    ClsCommonFunctions objMessage = new ClsCommonFunctions();

    objMailMsg = new MailMessage();

    objMailMsg.To.Add(to.Trim());
    objMailMsg.From = new MailAddress("xxx@xx.com", "xxxxx");
    objMailMsg.Subject = subject;
    objMailMsg.Body = body;

    objMailMsg.IsBodyHtml = true;
    objMailMsg.BodyEncoding = System.Text.Encoding.GetEncoding("windows-1256");

    objMailMsg.Headers.Add("Disposition-Notification-To", "xxx@xxx.com");

    SmtpClient smtp = new SmtpClient("yyyy.com");

    smtp.Port = 25;
    smtp.Credentials = new System.Net.NetworkCredential("xxx@xxx.com", "password");

    try
    {
        smtp.Send(objMailMsg);

    }
    catch (Exception ex)
    {
        objMessage.show_message(this, ex.Message);
    }

    Thread.Sleep(1000);

    objMailMsg.To.Clear();
    objMailMsg.Dispose();


问:
Get Reports from SAP BO server to Shared drive via SSIS
I have a requirement to get copies of reports in SAP BO server and drop them in a Shared drive via SSIS.
I have no idea on the BO server side ,Is this possible? If yes, kindly guide me on this.

TIA :)

Aiswarya

答: Sure - that's basic scheduling functionality.  You just have to schedule it to save to the designated UNC path.</p>


问:
Equivalent of RxJS switchMap in ReactiveX/Rx.NET
In RxJS, there is a switchMap function. Is there an equivalent in ReactiveX/Rx.NET? I don't see one in the transforming documentation.

答:
Edit

switch is the equivalent.  http://reactivex.io/documentation/operators/switch.html

In short, switchMap and switch will cancel any previous streams whereas flatMap will not.


问:
VAT changes - how to change VAT and then round price up
With the UK VAT rate due to change in the New Year, several clients will need to update their sites to the new VAT rate. As prices are all stored in a MySQL table (excluding VAT), changing the actual VAT rate is a simple flag in the backend of most sites, but this leaves 'ugly' prices £10.87, rather than £10.99.

I'd like to run a query against the prices to alter the prices so that all of the new prices (when the new VAT rate is added) are 'nice' prices rather than ugly ones.

For instance:

Current Price (ex VAT): £8.50

Current Price (VAT @ 17.5%): £9.99

New Price (VAT @ 20%): £10.20

Desired Price (VAT @ 20%): £10.99

答: Though it's dishonest to your customers to try and disguise a price rise as a VAT increase, you could use something like CEIL (which rounds a decimal up to the nearest integer), then - 0.01. </p>


问:
How to show the selected item of a WPF binding
C#:

```<code>public void SetCompetition(Window wT1)
{
    //Add all the Copetition
    wT1._competition = new List<Competition>();
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test1", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test2", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test3", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test4", IsSelected = false });

        wT1.cboSetupCompetition.ItemsSource = wT1._competition;
        wT1.cboSetupCompetition.Items.Refresh();
    }
</code>```

Data Template:

```<code><UserControl.Resources>
    <System:Double x:Key="Double1">11</System:Double>
    <DataTemplate x:Key="cmbCompetition">
        <WrapPanel  Height="30" >

            <Label Content="{Binding Name}" ></Label>

        </WrapPanel>
    </DataTemplate>

</UserControl.Resources>

<ComboBox x:Name="cboSetupCompetition" ItemTemplate="{DynamicResource     cmbCompetition}" HorizontalAlignment="Left" Margin="29,28,0,0" VerticalAlignment="Top" Width="173" RenderTransformOrigin="0.5,0.591" FontSize="12" Height="22" IsEditable="True"  Background="#FFD8D8D8" SelectionChanged="UpdateCompetitionSelection"/>
</code>```

I have a Combobox with a label and an image and when I select an item I would like to see the same format in the Combobox when it is closed. I am not getting any errors I am seeing the name of the application.Competition(this is my object Model) instead of the values of the image and label.

The SetCopetition is invoked when the application loads.

答:
the specific problem as Mn8 spotted is that IsEditable=true forces the combo to display a textbox as the selected item

However you are still thinking winforms not WPF, using code behind to link data into the view causes many problems and instability as quite often this breaks the binding connections which is what is suspected was your problem initially, using a proper MVVM approach will eliminate all these problems

the best overveiw of MVVM i know of is

https://msdn.microsoft.com/en-gb/library/hh848246.aspx

Model

this is your data layer, it handle storage and access to data, your model will handle access to files, databases, services, etc

a simple model would be

```<code>public class Model
{
    public string Text { get; set; }
    public Uri Uri { get; set; }
}
</code>```

ViewModel

on top of your Model you have your View Model
this manages the interaction of your View with the model
for example here because it uses Prism's BindableBase the SetProperty method notifies the View of any changes to the data, the ObservableCollection automatically notifies of changes to the collection, it also uses Prism's DelegateCommand to allow method binding in the view

```<code>public class ViewModel:BindableBase
{
    public ViewModel()
    {
        AddItem = new DelegateCommand(() => Collection.Add(new Model()
        {
            Text = NewText,
            Uri = new Uri(NewUri)
        }));
    }
    private string _NewText;

    public string NewText
    {
        get { return _NewText; }
        set { SetProperty(ref _NewText, value); }
    }
    private string _NewUri;

    public string NewUri
    {
        get { return _NewUri; }
        set { SetProperty(ref _NewUri, value); }
    }

    private Model _SelectedItem;

    public Model SelectedItem
    {
        get { return _SelectedItem; }
        set
        {
            if (SetProperty(ref _SelectedItem, value))
            {
                NewText = value?.Text;
                NewUri = value?.Uri.ToString();
            }
        }
    }

    public ObservableCollection<Model> Collection { get; } = new ObservableCollection<Model>();

    public DelegateCommand AddItem { get; set; }
}
</code>```

View

the View ideally does nothing but displays and collects data, all formatting / Styling should be done here

firstly you need to define the data source, the usual way is via the data context as this auto inherits down the visual tree, in the example because i set the window's datacontext, i have also set it for everything in the window the only exception is the dataTempplate as this is set to the current item in the collection

i then bind properties to the datasource

Note the code behind file is only the default constructor no other code at all

```<code><Window
    x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    <StackPanel>
        <GroupBox Header="Text">
            <TextBox Text="{Binding NewText}"/>
        </GroupBox>
        <GroupBox Header="URI">
            <TextBox Text="{Binding NewUri}"/>
        </GroupBox>
        <Button Content="Add" Command="{Binding AddItem}"/>
        <ComboBox ItemsSource="{Binding Collection}" SelectedItem="{Binding SelectedItem}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="{Binding Uri}" />
                        <TextBlock Text="{Binding Text}"/>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

    </StackPanel>
</Window>
</code>```

Body:
C#:

public void SetCompetition(Window wT1)
{
    //Add all the Copetition
    wT1._competition = new List<Competition>();
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test1", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test2", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test3", IsSelected = false });
    wT1._competition.Add(new Competition { Logo = "3.png", Name = "test4", IsSelected = false });

        wT1.cboSetupCompetition.ItemsSource = wT1._competition;
        wT1.cboSetupCompetition.Items.Refresh();
    }

Data Template:

<UserControl.Resources>
    <System:Double x:Key="Double1">11</System:Double>
    <DataTemplate x:Key="cmbCompetition">
        <WrapPanel  Height="30" >

        </WrapPanel>
    </DataTemplate>

</UserControl.Resources>

<ComboBox x:Name="cboSetupCompetition" ItemTemplate="{DynamicResource     cmbCompetition}" HorizontalAlignment="Left" Margin="29,28,0,0" VerticalAlignment="Top" Width="173" RenderTransformOrigin="0.5,0.591" FontSize="12" Height="22" IsEditable="True"  Background="#FFD8D8D8" SelectionChanged="UpdateCompetitionSelection"/>

I have a Combobox with a label and an image and when I select an item I would like to see the same format in the Combobox when it is closed. I am not getting any errors I am seeing the name of the application.Competition(this is my object Model) instead of the values of the image and label.

The SetCopetition is invoked when the application loads.

Body:
the specific problem as Mn8 spotted is that IsEditable=true forces the combo to display a textbox as the selected item

However you are still thinking winforms not WPF, using code behind to link data into the view causes many problems and instability as quite often this breaks the binding connections which is what is suspected was your problem initially, using a proper MVVM approach will eliminate all these problems

the best overveiw of MVVM i know of is

https://msdn.microsoft.com/en-gb/library/hh848246.aspx

Model

this is your data layer, it handle storage and access to data, your model will handle access to files, databases, services, etc

a simple model would be

public class Model
{
    public string Text { get; set; }
    public Uri Uri { get; set; }
}

ViewModel

on top of your Model you have your View Model
this manages the interaction of your View with the model
for example here because it uses Prism's BindableBase the SetProperty method notifies the View of any changes to the data, the ObservableCollection automatically notifies of changes to the collection, it also uses Prism's DelegateCommand to allow method binding in the view

public class ViewModel:BindableBase
{
    public ViewModel()
    {
        AddItem = new DelegateCommand(() => Collection.Add(new Model()
        {
            Text = NewText,
            Uri = new Uri(NewUri)
        }));
    }
    private string _NewText;

    public string NewText
    {
        get { return _NewText; }
        set { SetProperty(ref _NewText, value); }
    }
    private string _NewUri;

    public string NewUri
    {
        get { return _NewUri; }
        set { SetProperty(ref _NewUri, value); }
    }

    private Model _SelectedItem;

    public Model SelectedItem
    {
        get { return _SelectedItem; }
        set
        {
            if (SetProperty(ref _SelectedItem, value))
            {
                NewText = value?.Text;
                NewUri = value?.Uri.ToString();
            }
        }
    }

    public ObservableCollection<Model> Collection { get; } = new ObservableCollection<Model>();

    public DelegateCommand AddItem { get; set; }
}

View

the View ideally does nothing but displays and collects data, all formatting / Styling should be done here

firstly you need to define the data source, the usual way is via the data context as this auto inherits down the visual tree, in the example because i set the window's datacontext, i have also set it for everything in the window the only exception is the dataTempplate as this is set to the current item in the collection

i then bind properties to the datasource

Note the code behind file is only the default constructor no other code at all

<Window
    x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    <StackPanel>
        <GroupBox Header="Text">
            <TextBox Text="{Binding NewText}"/>
        </GroupBox>
        <GroupBox Header="URI">
            <TextBox Text="{Binding NewUri}"/>
        </GroupBox>
        <Button Content="Add" Command="{Binding AddItem}"/>
        <ComboBox ItemsSource="{Binding Collection}" SelectedItem="{Binding SelectedItem}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="{Binding Uri}" />
                        <TextBlock Text="{Binding Text}"/>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

    </StackPanel>
</Window>