问:
function used from within javascript dojo closure using "this"-notation is undefined
I have a Problem accessing an Object function using "this".
In case of the below example (which is simplified, because I cannot supply actual code due to various reasons) the function call this._getEntry() is "undefined" when calling
createList().

I would hope for some opinions on wether this is due to a misunderstanding of
javascript closures or rather a syntax error.

In the latter case I will have to find the error in the actual code myself.

If it is a misunderstanding of javascript or dojo concepts I would really appreciate
some help on how to correctly scope and access the below mentioned function (_getEntry()).

```<code>var OBJECT = {
  _getEntry : function(entry){
    var li = document.createElement('LI');
    li.appendChild(document.createTextNode(entry));
    return li;
  },
  createList : function(entryArray){
    var list = document.createElement('UL');
    dojo.forEach(entryArray,function(entry){
      list.appendChild(this._getEntry(entry));
    });
    dojo.body().appendChild(list);
  }
};
OBJECT.createList(["entry1","entry2"]);
</code>```

thanks!

答:
This is a common problem and you are right, its all about scoping and closure. What is happening here is once you get into the forEach the context changes to the global context (window). Handily, Dojo provides a way to set this context:

```<code>  createList : function(entryArray){
    var list = document.createElement('UL');
    dojo.forEach(entryArray,function(entry){
      list.appendChild(this._getEntry(entry));
    }, this);

    dojo.body().appendChild(list);
  }
</code>```

An alternate approach is to use closure to get at this

```<code>  createList : function(entryArray){
    var list = document.createElement('UL');
    var _this = this; // closure allowing the forEach callback access to this
                      // some popular variable names used for this include:
                      // $this, _this, me and that
    dojo.forEach(entryArray,function(entry){
      list.appendChild(_this._getEntry(entry));
    });

    dojo.body().appendChild(list);
  }
</code>```

Body:
I have a Problem accessing an Object function using "this".
In case of the below example (which is simplified, because I cannot supply actual code due to various reasons) the function call this._getEntry() is "undefined" when calling
createList().

I would hope for some opinions on wether this is due to a misunderstanding of
javascript closures or rather a syntax error.

In the latter case I will have to find the error in the actual code myself.

If it is a misunderstanding of javascript or dojo concepts I would really appreciate
some help on how to correctly scope and access the below mentioned function (_getEntry()).

var OBJECT = {
  _getEntry : function(entry){
    var li = document.createElement('LI');
    li.appendChild(document.createTextNode(entry));
    return li;
  },
  createList : function(entryArray){
    var list = document.createElement('UL');
    dojo.forEach(entryArray,function(entry){
      list.appendChild(this._getEntry(entry));
    });
    dojo.body().appendChild(list);
  }
};
OBJECT.createList(["entry1","entry2"]);

thanks!

Body:
This is a common problem and you are right, its all about scoping and closure. What is happening here is once you get into the forEach the context changes to the global context (window). Handily, Dojo provides a way to set this context:

  createList : function(entryArray){
    var list = document.createElement('UL');
    dojo.forEach(entryArray,function(entry){
      list.appendChild(this._getEntry(entry));
    }, this);

    dojo.body().appendChild(list);
  }

An alternate approach is to use closure to get at this

  createList : function(entryArray){
    var list = document.createElement('UL');
    var _this = this; // closure allowing the forEach callback access to this
                      // some popular variable names used for this include:
                      // $this, _this, me and that
    dojo.forEach(entryArray,function(entry){
      list.appendChild(_this._getEntry(entry));
    });

    dojo.body().appendChild(list);
  }


来源: stackexchange

问:
How to add just once always method?
I am pretty new to Android Studio, and i added on my app the possibility to choose between two map apps. But i wanted to know how to add the infamous "Always open with/just once" method.

```<code>private void launchNextActivity(String latitude, String longitude, int state) {
    for (int i = 0; i < User.getUserCourses().size(); i++) {
        if (User.getUserCourses().get(i).getIdCourse() == course.getIdCourse()) {
            //A remplacer par l'appel de l'api
            Intent intent;

            Location location = getLastKnownLocation();
            if (location == null) {
                Toast.makeText(getApplicationContext(), "Connexion avec le serveur impossible", Toast.LENGTH_SHORT).show();
                return;
            }
            String uri = "google.navigation:q=" + latitude + "+" + longitude;
            uri = uri.replace(" ", "+");
            intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(uri)).setPackage("com.google.android.apps.maps");
            if (intent == null) {
                findViewById(R.id.cancel_button).setClickable(false);
                Snackbar
                        .make(findViewById(R.id.snackbar_position), "Google Map missing", Snackbar.LENGTH_LONG)
                        .setAction("Download", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                try {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.apps.maps")));
                                } catch (android.content.ActivityNotFoundException anfe) {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.maps")));
                                }
                                findViewById(R.id.cancel_button).setClickable(true);
                            }
                        })
                        .setActionTextColor(getResources().getColor(R.color.ShGreen2))
                        .show();
            }

            //Load Waze if available
            Intent wazeIntent;
            String uriWaze = "https://waze.com/ul?ll=" + latitude + "," + longitude + "&navigate=yes";
            wazeIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uriWaze)).setPackage("com.waze");

            Intent chooserIntent = Intent.createChooser(intent, "Ouvrir l'itinéraire avec:");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { wazeIntent });
            reloadActivity(state, chooserIntent);
        }
</code>```

I have searched for almost a week and found almost no info on how this actually works. I know that because i always call a chooser it will always launch it, but how to add the "always open with/just once" without a chooser?

答:
You can use a geo URI scheme to open a location in the user's default map application (which will result in the "always open with/just once" dialog if a default app isn't set).</p>

```<code>Uri location = Uri.parse("geo:" + latitude + "," + longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, location);
if (intent.resolveActivity(getPackageManager()) != null) {
    startActivity(intent);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to add just once always method?

Body:
I am pretty new to Android Studio, and i added on my app the possibility to choose between two map apps. But i wanted to know how to add the infamous "Always open with/just once" method.

private void launchNextActivity(String latitude, String longitude, int state) {
    for (int i = 0; i < User.getUserCourses().size(); i++) {
        if (User.getUserCourses().get(i).getIdCourse() == course.getIdCourse()) {
            //A remplacer par l'appel de l'api
            Intent intent;

            Location location = getLastKnownLocation();
            if (location == null) {
                Toast.makeText(getApplicationContext(), "Connexion avec le serveur impossible", Toast.LENGTH_SHORT).show();
                return;
            }
            String uri = "google.navigation:q=" + latitude + "+" + longitude;
            uri = uri.replace(" ", "+");
            intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(uri)).setPackage("com.google.android.apps.maps");
            if (intent == null) {
                findViewById(R.id.cancel_button).setClickable(false);
                Snackbar
                        .make(findViewById(R.id.snackbar_position), "Google Map missing", Snackbar.LENGTH_LONG)
                        .setAction("Download", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                try {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.apps.maps")));
                                } catch (android.content.ActivityNotFoundException anfe) {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.maps")));
                                }
                                findViewById(R.id.cancel_button).setClickable(true);
                            }
                        })
                        .setActionTextColor(getResources().getColor(R.color.ShGreen2))
                        .show();
            }

            //Load Waze if available
            Intent wazeIntent;
            String uriWaze = "https://waze.com/ul?ll=" + latitude + "," + longitude + "&navigate=yes";
            wazeIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uriWaze)).setPackage("com.waze");

            Intent chooserIntent = Intent.createChooser(intent, "Ouvrir l'itinéraire avec:");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { wazeIntent });
            reloadActivity(state, chooserIntent);
        }

I have searched for almost a week and found almost no info on how this actually works. I know that because i always call a chooser it will always launch it, but how to add the "always open with/just once" without a chooser?

Body:
You can use a geo URI scheme to open a location in the user's default map application (which will result in the "always open with/just once" dialog if a default app isn't set).

Uri location = Uri.parse("geo:" + latitude + "," + longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, location);
if (intent.resolveActivity(getPackageManager()) != null) {
    startActivity(intent);
}


问:
Memory Leak using sqlite
I am getting a memory leak warning on Instruments for these lines:

```<code> NSString *name =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];

 year = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
</code>```

Here is the code for this section:

```<code>-(NSMutableArray *)selectUsersList:(NSString *)condition:(NSString *)sort
{
    NSMutableArray *users = [[NSMutableArray alloc] init];

    if (sqlite3_open([self.databasePath UTF8String], &database) != SQLITE_OK)
    {
      sqlite3_close(database);
      NSAssert(0, @"Failed to open database");
    }
    else
    {
      NSString *query = @"SELECT * FROM users";
      if (condition != nil)
      {
        NSString *newQuery = [NSString stringWithFormat:@"%@ %@", query, condition];
        query = newQuery;
      }
      if (sort != nil) {
        NSString *newsort = [NSString stringWithFormat:@"%@ %@", query, sort];
        query = newsort;
      }
      sqlite3_stmt *statement;

      if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
      {
        while (sqlite3_step(statement) == SQLITE_ROW) {
            NSString *name =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
            }
            NSString *year= @"";
            if (sqlite3_column_text(statement, 2) != nil)
            {
                year = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
            }

            User *user = [[User alloc] initWithName:name year:year];

            [users addObject:user];
            [user release];
        }
    }
    sqlite3_finalize(statement);
    sqlite3_close(database);
  }
  return users;
}
</code>```

I want to present an empty string and not 'nil' on the view so I am setting year to an empty string first. Is there a better way to do this? How can I solve this leak?

Thanks for your help!

答:
After the while loop, you must clear the sqlite3 statement's memory with sqlite3_finalize(). So:

```<code>if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
    while (sqlite3_step(statement) == SQLITE_ROW) {
        NSString *name =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];

        NSString *year= @"";
        if (sqlite3_column_text(statement, 1) != nil) {
            year = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
        }

        User *user = [[User alloc] initWithName:name year:year];
        [users addObject:user];
        [user release];
    }
    sqlite3_finalize(statement); // DO THIS
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Memory Leak using sqlite

Body:
I am getting a memory leak warning on Instruments for these lines:

 NSString *name =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];

 year = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];

Here is the code for this section:

-(NSMutableArray *)selectUsersList:(NSString *)condition:(NSString *)sort
{
    NSMutableArray *users = [[NSMutableArray alloc] init];

    if (sqlite3_open([self.databasePath UTF8String], &database) != SQLITE_OK)
    {
      sqlite3_close(database);
      NSAssert(0, @"Failed to open database");
    }
    else
    {
      NSString *query = @"SELECT * FROM users";
      if (condition != nil)
      {
        NSString *newQuery = [NSString stringWithFormat:@"%@ %@", query, condition];
        query = newQuery;
      }
      if (sort != nil) {
        NSString *newsort = [NSString stringWithFormat:@"%@ %@", query, sort];
        query = newsort;
      }
      sqlite3_stmt *statement;

      if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
      {
        while (sqlite3_step(statement) == SQLITE_ROW) {
            NSString *name =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
            }
            NSString *year= @"";
            if (sqlite3_column_text(statement, 2) != nil)
            {
                year = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
            }

            User *user = [[User alloc] initWithName:name year:year];

            [users addObject:user];
            [user release];
        }
    }
    sqlite3_finalize(statement);
    sqlite3_close(database);
  }
  return users;
}

I want to present an empty string and not 'nil' on the view so I am setting year to an empty string first. Is there a better way to do this? How can I solve this leak?

Thanks for your help!

Body:
After the while loop, you must clear the sqlite3 statement's memory with sqlite3_finalize(). So:

if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
    while (sqlite3_step(statement) == SQLITE_ROW) {
        NSString *name =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];

        NSString *year= @"";
        if (sqlite3_column_text(statement, 1) != nil) {
            year = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
        }

        User *user = [[User alloc] initWithName:name year:year];
        [users addObject:user];
        [user release];
    }
    sqlite3_finalize(statement); // DO THIS
}


问:
Python wordpress xmlrpc -32700 error with wordpress4.8
I just built a wordpress site and used the latest version (4.8.3).
I want to use python-wordpress-xmlrpc module. It used to works before, but now when I use QuickStart guide to connect to my wordpress, it shows an erorr.

I googled it for two day, but didn't get any answers. I found an issue on module creator's github:
https://github.com/maxcutler/python-wordpress-xmlrpc/issues/110

Looks like some people have the same error.

This is my code:

host = 'http://sample.com'
wp = Client(host+'/xmlrpc.php', 'root', 'password')
print(wp)
r = wp.call(GetPosts())

#Error:
 MEssage xmlrpc.client.Fault: <Fault -32700: 'parse error. not well formed'>
```

I think maybe it's because wordpress 4.8 uses php7 that I get errors.
How can I fix this problem?

答:
Try this:

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods import posts

host = 'http://sample.com'
wp = Client(host+'/xmlrpc.php', 'root', 'password')
r = wp.call(posts.GetPosts())
```

ContentLicense: CC BY-SA 4.0

Body:
I just built a wordpress site and used the latest version (4.8.3).
I want to use python-wordpress-xmlrpc module. It used to works before, but now when I use QuickStart guide to connect to my wordpress, it shows an erorr.

I googled it for two day, but didn't get any answers. I found an issue on module creator's github:
https://github.com/maxcutler/python-wordpress-xmlrpc/issues/110

Looks like some people have the same error.

This is my code:

host = 'http://sample.com'
wp = Client(host+'/xmlrpc.php', 'root', 'password')
print(wp)
r = wp.call(GetPosts())

#Error:
 MEssage xmlrpc.client.Fault: <Fault -32700: 'parse error. not well formed'>

I think maybe it's because wordpress 4.8 uses php7 that I get errors.
How can I fix this problem?


问:
How do I perform the CallTarget task in a “loop” with MSBuild ItemGroups?
How do I perform the CallTarget task in a "loop" with MSBuild ItemGroups?

I have a property with semicolon separated values, and I want to call target once for each of the values.

For now I have checked and msbuild is autosplitting to multiple Items in Itemgroup:

```<code><ItemGroup>
    <Version Include="$(Versions)" />
</ItemGroup>
</code>```

What I want to achieve is to have other target called as many times, as there are values in this ItemGroup.
I know I should use

```<code>%Version.Identity
</code>```

however I don't see any attribute on CallTarget Task on which it would be possible.

Unfortunately I cannot migrate the target I want to run, to C# or powershell.

答:
A target in msbuild is only executed once per invocation. If a target was already run, additional  <CallTarget> tasks don't do anything - same as when multiple targets depend on a shared target.

While it is possible to use target batching by defining metadata-specific Inputs or Outputs, this doesn't really work with items that don't represent items on disk.

The way to perform the same logic with different inputs would be to use the <MSBuild> task to perform an "inner" build which performs multiple builds of the same target with different parameters:

```<code><ItemGroup>
  <Version Include="1;2;3" />
</ItemGroup>
<MSBuild Projects="$(MSBuildProjectFile)" Targets="DoSthWithVersion" Properties="Version=%(Version.Identity)" />
…

<Target Name="DoSthWithVersion">
  <Message Importance="high" Text="Version is: $(Version)" />
</Target>
</code>```

Note that you will also need to pass any other property that has been generated/changed during the build and is not part of the project file's static property definitions (i.e. only set inside a target).

Body:
How do I perform the CallTarget task in a "loop" with MSBuild ItemGroups?

I have a property with semicolon separated values, and I want to call target once for each of the values.

For now I have checked and msbuild is autosplitting to multiple Items in Itemgroup:

<ItemGroup>
    <Version Include="$(Versions)" />
</ItemGroup>

What I want to achieve is to have other target called as many times, as there are values in this ItemGroup.
I know I should use

%Version.Identity

however I don't see any attribute on CallTarget Task on which it would be possible.

Unfortunately I cannot migrate the target I want to run, to C# or powershell.

Body:
A target in msbuild is only executed once per invocation. If a target was already run, additional  <CallTarget> tasks don't do anything - same as when multiple targets depend on a shared target.

While it is possible to use target batching by defining metadata-specific Inputs or Outputs, this doesn't really work with items that don't represent items on disk.

The way to perform the same logic with different inputs would be to use the <MSBuild> task to perform an "inner" build which performs multiple builds of the same target with different parameters:

<ItemGroup>
  <Version Include="1;2;3" />
</ItemGroup>
<MSBuild Projects="$(MSBuildProjectFile)" Targets="DoSthWithVersion" Properties="Version=%(Version.Identity)" />
…

<Target Name="DoSthWithVersion">
  <Message Importance="high" Text="Version is: $(Version)" />
</Target>

Note that you will also need to pass any other property that has been generated/changed during the build and is not part of the project file's static property definitions (i.e. only set inside a target).


问:
How to Generate Random number without repeat in database using PHP?
I would like to generate a 5 digit number which do not repeat inside the database.
Say I have a table named numbers_mst with field named my_number.

I want to generate the number the way that it do not repeat in this my_number field.
And preceding zeros are allowed in this. So numbers like 00001 are allowed.
Another thing is it should be between 00001 to 99999. How can I do that?

One thing I can guess here is I may have to create a recursive function to check number into table and generate.

答:
I know my answer is late, but if anyone is looking for this subject in the future, who want to have a random number with leading zero, you should add the LPAD() function.

So your query it will like

```<code>SELECT LPAD(FLOOR(RAND()*99999),5,0)
</code>```

Have a nice day.

Body:
I know my answer is late, but if anyone is looking for this subject in the future, who want to have a random number with leading zero, you should add the LPAD() function.

So your query it will like

SELECT LPAD(FLOOR(RAND()*99999),5,0)

Have a nice day.


问:
LDLt factorization using SciPy's Python bindings to LAPACK
I am trying to get the LDLt factorization of a given symmetric matrix with SciPy's Python bindings to LAPACK using the dsysv routine which actually solves linear systems using this matrix factorization.

I have tried the following:

```<code>import numpy as np
from scipy.linalg.lapack import dsysv

A = np.random.randint(1, 1000, size=(5, 5))
A = (A + A.T)
b = np.random.randn(5)
lult, piv, x, _ = dsysv(A, b, lower=1)
</code>```

Where x would be the solution for the above linear system and lult and piv contain information about the factorization.

How can I reconstruct LDLt from it? Sometimes negative values are contained in piv and from the docs I was not able to understand their meaning.

LAPACK's sytrf actually computes this factorization (without solving any linear system) but it does not seem available via SciPy.

There is an example here with the output I am interested in (see eq. 3-23).

答:
dsysv is the linear system solver and it does all the magic internally including calls to dsytrf. So for the factorization it is not needed. As kazemakase mentioned this is now available in SciPy (PR 7941 and will appear officially in version 1.1) and you can just use the scipy.linalg.ldl() to get the factorization and the permutation information of the outer factors. Actually this was the reason why ?sytrf and ?hetrf was added.

You can look at its source code to see how ipiv is sanitized.

With SciPy v.1.1 built with OpenBlas on Windows 10 machine vs. matlab using mkl, the performance is given below

Adding extra JIT-compilers on top of it probably would bring it to matlab speed. Since the ipiv handling and the factorization construction is done in pure numpy/python. Or better cythonize it if performance is the utmost importance.

Body:
I am trying to get the LDLt factorization of a given symmetric matrix with SciPy's Python bindings to LAPACK using the dsysv routine which actually solves linear systems using this matrix factorization.

I have tried the following:

import numpy as np
from scipy.linalg.lapack import dsysv

A = np.random.randint(1, 1000, size=(5, 5))
A = (A + A.T)
b = np.random.randn(5)
lult, piv, x, _ = dsysv(A, b, lower=1)

Where x would be the solution for the above linear system and lult and piv contain information about the factorization.

How can I reconstruct LDLt from it? Sometimes negative values are contained in piv and from the docs I was not able to understand their meaning.

LAPACK's sytrf actually computes this factorization (without solving any linear system) but it does not seem available via SciPy.

There is an example here with the output I am interested in (see eq. 3-23).


问:
automatic include mechanism in PHP
Is there a way I can include files same folder automatically?

I see lot of code in application I am working on that has this kind of code. Specific example is swift mailer (if anyone is aware of that). But this can also be used as general example:

```<code> Folder: vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport

 |
 --- File MailInvoker.php
                 |
                 --- interface Swift_Transport_MailInvoker
 |
 --- File SimpleMailInvoker.php
                 |
                 --- class Swift_Transport_SimpleMailInvoker implements Swift_Transport_MailInvoker
</code>```

I am unable to figure out without any specific include statements or without any mention in any of autoload files, how class can use interface.

Thanks in advance for help!

答: Composer is the best tool to autoload files, all modern frameworks use composer. To autoload a folder files you should inialize autoloading system and then follow some standards in file naming. You can read this tutorial for more information about composer</p>

Title: automatic include mechanism in PHP

Body:
Is there a way I can include files same folder automatically?

I see lot of code in application I am working on that has this kind of code. Specific example is swift mailer (if anyone is aware of that). But this can also be used as general example:

 Folder: vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport

 |
 --- File MailInvoker.php
                 |
                 --- interface Swift_Transport_MailInvoker
 |
 --- File SimpleMailInvoker.php
                 |
                 --- class Swift_Transport_SimpleMailInvoker implements Swift_Transport_MailInvoker

I am unable to figure out without any specific include statements or without any mention in any of autoload files, how class can use interface.

Thanks in advance for help!


问:
Call to undefined method Image::resize()
I am having problem with changing logo image in my admin panel, it was working before but after update it outputs an error. Now I am not sure what happens and here is the error:

```<code> Call to undefined method Image::resize() …/system/controllers/settings.php
</code>```

This below is the code from that area:

```<code>case 'logo-post':
    if($_app_stage == 'Demo'){
        r2(U.'appearance/customize/','e',$_L['disabled_in_demo']);
    }
    $validextentions = array("jpeg", "jpg", "png");
    $temporary = explode(".", $_FILES["file"]["name"]);
    $file_extension = end($temporary);
    $file_name = '';
    if(($_FILES["file"]["type"] == "image/png")){
        $file_name = 'logo-tmp.png';
    }
    elseif(($_FILES["file"]["type"] == "image/jpg")){
        $file_name = 'logo-tmp.jpg';
    }
    elseif(($_FILES["file"]["type"] == "image/jpeg")){
        $file_name = 'logo-tmp.jpeg';
    }
    elseif(($_FILES["file"]["type"] == "image/gif")){
        $file_name = 'logo-tmp.gif';
    }
    else{

    }
    if ((($_FILES["file"]["type"] == "image/png")
            || ($_FILES["file"]["type"] == "image/jpg")
            || ($_FILES["file"]["type"] == "image/jpeg"))
        && ($_FILES["file"]["size"] < 1000000)//approx. 100kb files can be uploaded
        && in_array($file_extension, $validextentions)){
        move_uploaded_file($_FILES["file"]["tmp_name"], 'storage/system/'. $file_name);
        $image = new Image();
        $image->source_path = 'storage/system/'. $file_name;
        $image->target_path = 'storage/system/logo.png';
       // $image->resize('0','40',ZEBRA_IMAGE_BOXED,'-1');
        $image->resize(0,0,ZEBRA_IMAGE_BOXED,'-1');

        // now delete the tmp image

        unlink('storage/system/'. $file_name);

       // r2(U.'settings/app','s',$_L['Settings Saved Successfully']);

        r2(U.'appearance/customize/','s',$_L['Settings Saved Successfully']);
    }

    else{

        r2(U.'appearance/customize/','e',$_L['Invalid Logo File']);

    }

    break;
</code>```

Line where the error is happening:

$image->resize(0,0,ZEBRA_IMAGE_BOXED,'-1');

I'd appreciate any help, thanks!

答:
Thank you for all your helping here, Now i know that the image class has been change to Img as Img.php because of the updating and file image.php is contain other gb with imagelib.php. Now i changed the above code to:

$Img = new Img(); $Img->source_path = 'storage/system/'. $file_name; $Img->target_path = 'storage/system/logo.png'; // $image->resize('0','40',ZEBRA_IMAGE_BOXED,'-1'); $Img->resize(0,0,ZEBRA_IMAGE_BOXED,'-1');

All problem solved

Body:
I am having problem with changing logo image in my admin panel, it was working before but after update it outputs an error. Now I am not sure what happens and here is the error:

 Call to undefined method Image::resize() …/system/controllers/settings.php

This below is the code from that area:

case 'logo-post':
    if($_app_stage == 'Demo'){
        r2(U.'appearance/customize/','e',$_L['disabled_in_demo']);
    }
    $validextentions = array("jpeg", "jpg", "png");
    $temporary = explode(".", $_FILES["file"]["name"]);
    $file_extension = end($temporary);
    $file_name = '';
    if(($_FILES["file"]["type"] == "image/png")){
        $file_name = 'logo-tmp.png';
    }
    elseif(($_FILES["file"]["type"] == "image/jpg")){
        $file_name = 'logo-tmp.jpg';
    }
    elseif(($_FILES["file"]["type"] == "image/jpeg")){
        $file_name = 'logo-tmp.jpeg';
    }
    elseif(($_FILES["file"]["type"] == "image/gif")){
        $file_name = 'logo-tmp.gif';
    }
    else{

    }
    if ((($_FILES["file"]["type"] == "image/png")
            || ($_FILES["file"]["type"] == "image/jpg")
            || ($_FILES["file"]["type"] == "image/jpeg"))
        && ($_FILES["file"]["size"] < 1000000)//approx. 100kb files can be uploaded
        && in_array($file_extension, $validextentions)){
        move_uploaded_file($_FILES["file"]["tmp_name"], 'storage/system/'. $file_name);
        $image = new Image();
        $image->source_path = 'storage/system/'. $file_name;
        $image->target_path = 'storage/system/logo.png';
       // $image->resize('0','40',ZEBRA_IMAGE_BOXED,'-1');
        $image->resize(0,0,ZEBRA_IMAGE_BOXED,'-1');

        // now delete the tmp image

        unlink('storage/system/'. $file_name);

       // r2(U.'settings/app','s',$_L['Settings Saved Successfully']);

        r2(U.'appearance/customize/','s',$_L['Settings Saved Successfully']);
    }

    else{

        r2(U.'appearance/customize/','e',$_L['Invalid Logo File']);

    }

    break;

Line where the error is happening:

$image->resize(0,0,ZEBRA_IMAGE_BOXED,'-1');

I'd appreciate any help, thanks!


问:
How to download only new emails from imap?
I have an application that is used to archive emails using imap. Also in this application are many imap accounts that need to be archived.

In this moment from time to time the application connects to imap accounts and download only new emails. My issue is that every time when it connects to an imap account it verifies all emails from all folders and downloads only emails that aren't downloaded yet (I store Message-ID for all emails and download only emails that have an Message-ID that is not stored).
So I want to know if there is an alternative for this, because it takes some time to verify all emails (for 10-20K it takes 2-5 minutes).

I use JavaMail API to connect to imap accounts.

答: Filter on the SEEN flag.  This flag is intended for finding new messages.  The one Caveat is that if your user is using multiple readers, then it may have been seen using another reader.</p>


问:
Excel vba runtime error 424 Object required when assigning Range variable
I have this code that consists of a function and subroutine that uses that function. Function takes a column as an argument and alters each of that column cell's content.

```<code>Function testFunc(aCol As Range)
    Dim i As Integer
    i = 0
    For Each cell In aCol
        cell.Value = i
        i = i + 1
    Next
End Function

Sub testSub()
    Dim aRange As Range
    Set aRange = ThisWorkbook.Sheets("Sheet1").Range("A1:A16")

    testFunc (ThisWorkbook.Sheets("Sheet2").Range("A1:A16"))   '<--- this works fine
    testFunc (aRange)    '<---- error
End Sub
</code>```

The Runtime error '424' Object required"| arises on linetestFunc (aRange)`. I'm not sure what's wrong, I assign variable through 'Set' and it's supposed to work fine.

Also, I tried passing the range directly to the function, without storing it in the variable first and it workes perfectly. Why?

答:
Parentheses around an expression are causing the expression to be evaluated as a value and passed ByVal to the procedure invoked.

```<code>testFunc (ThisWorkbook.Sheets("Sheet2").Range("A1:A16"))   '<--- this works fine
</code>```

No, it doesn't work fine, not with aCol As Range in the signature of testFunc - for the exact same reason as the line underneath it. A Range object has a default member that points to its .Value. When you do this:

```<code>DoSomething (SomeRange)
</code>```

What's really happening is this:

```<code>DoSomething (SomeRange.Value)
</code>```

The parentheses are telling VBA to evaluate the expression as a value, before passing the result by value (ByVal) of that expression to the procedure being invoked, regardless of the implicit ByRef modifier in the procedure's signature.

Problem is, given a 16-cell Range, Range.Value is a 2D array - and given a single-cell Range, Range.Value is a Variant that contains that cell's value, and that can't possibly be coerced into a Range object instance, so it's impossible that the code you have here "works fine": it's an object required error, because the procedure is expecting a Range and you're giving it a Variant that contains a 2D array.

Why your "works fine" code isn't really working

The only way testFunc (ThisWorkbook.Sheets("Sheet2").Range("A1:A16")) could possibly work, is if testFunc had this signature (which, I suspect it did at one point before you ultimately asked this question):

```<code>Function testFunc(aCol)
</code>```

Or the explicit equivalent:

```<code>Public Function testFunc(ByRef aCol As Variant) As Variant
</code>```

And because a 2D array can be iterated with a For Each loop (albeit very inefficiently), and it's possible that the entire A1:A16 range contains values that can be coerced into valid Integer values, "works fine" indeed... except you're updating an in-memory copy of the data, not the cells themselves - so it wasn't quite "works fine", was more like "doesn't crash".

Here's a MCVE:

```<code>Private Function DoSomething(ByRef foo As Range)
End Function

Public Sub Test()
    DoSomething (Range("A1").Value)
End Sub
</code>```

Calling Test throws run-time error 424 "Object Required".

```<code>Public Function DoSomething(ByRef foo As Range)
End Function

Public Sub Test()
    DoSomething (Range("A1:A100").Value)
End Sub
</code>```

Calling Test throws the same run-time error 424 "Object Required".

Now remove the As Range declaration:

```<code>Public Function DoSomething(ByRef foo As Variant)
    Debug.Print TypeName(foo)
End Function

Public Sub Test()
    DoSomething (Range("A1:A100").Value)
End Sub
</code>```

Invoking Test prints Variant() to the immediate pane (Ctrl+G). Now make the range contain just one single cell:

```<code>Public Function DoSomething(ByRef foo As Variant)
    Debug.Print TypeName(foo)
End Function

Public Sub Test()
    DoSomething (Range("A1").Value)
End Sub
</code>```

Invoking Test prints whatever data type the value of cell A1 holds. If it's text, it prints String. If it's a number, it prints Double. If it's a date, it prints Date. If it's a cell error (e.g. #NA, #VALUE!, etc.), it prints Error.

Note that the results are identical for all of the above, whether you specify .Value explicitly or not, because omitting .Value boils down to implicitly specifying it.

Also note that passing an array ByVal is illegal. What's being passed to the function here is a copy of a pointer to the beginning of the array - the Variant array isn't storing the array itself, just a pointer to its actual location: that's why & how you can legally pass a variant array by value.

Why the variable is blowing up too

The 2nd line is throwing the same error, for the same reason:

```<code>testFunc (aRange)    '<---- error
</code>```

You're implicitly doing this:

```<code>DoSomething (SomeRange)
</code>```0

Because that's what the parentheses do: they tell VBA to evaluate the expression as a value, and pass it as such.

So you're passing a 2D variant array to a procedure that's expecting a Range.

This is different, and correct:

```<code>DoSomething (SomeRange)
</code>```1

Note the lack of parentheses: now you're passing the Range object reference to a procedure that accepts a Range object reference, ByRef (although that modifier is implicit and a more semantically correct way to do it would be to pass the object reference ByVal).

So how do I tell when the arguments are being evaluated as a value?

When you invoke a Function procedure, you're normally interested in its return value:

```<code>DoSomething (SomeRange)
</code>```2

The VBA automatically positions the opening parenthesis immediately after the function's identifier - no whitespace.

When you invoke a Function procedure without capturing its return value, you must omit the parentheses:

```<code>MsgBox "Confirm?", vbYesNo
</code>```

Note that this would be a compile error:

```<code>MsgBox ("Confirm?", vbYesNo)
</code>```

Because the expression ("Confirm?", vbYesNo) cannot be evaluated as a value and passed as such to the first parameter of the procedure.

That's easy though - MsgBox has multiple parameters. People get confused when there's only one parameter - because then this looks legal:

```<code>testFunc (aRange)
</code>```

Notice the whitespace: it shouldn't be there. That's the VBE telling you "these parentheses are NOT part of the function call, they're part of the argument you're going pass to that function, and if whatever is in these parentheses can't be evaluated as a value at run-time, expect trouble".

If your testFunc procedure isn't returning a value, then it shouldn't be a Function in the first place - it should be a Sub procedure. Functions take input and return a value, Subs do something, which usually entails side-effects, e.g. actual cell values being modified.

Body:
I have this code that consists of a function and subroutine that uses that function. Function takes a column as an argument and alters each of that column cell's content.

Function testFunc(aCol As Range)
    Dim i As Integer
    i = 0
    For Each cell In aCol
        cell.Value = i
        i = i + 1
    Next
End Function

Sub testSub()
    Dim aRange As Range
    Set aRange = ThisWorkbook.Sheets("Sheet1").Range("A1:A16")

    testFunc (ThisWorkbook.Sheets("Sheet2").Range("A1:A16"))   '<--- this works fine
    testFunc (aRange)    '<---- error
End Sub

The Runtime error '424' Object required"| arises on linetestFunc (aRange)`. I'm not sure what's wrong, I assign variable through 'Set' and it's supposed to work fine.

Also, I tried passing the range directly to the function, without storing it in the variable first and it workes perfectly. Why?

Body:
Parentheses around an expression are causing the expression to be evaluated as a value and passed ByVal to the procedure invoked.

testFunc (ThisWorkbook.Sheets("Sheet2").Range("A1:A16"))   '<--- this works fine

No, it doesn't work fine, not with aCol As Range in the signature of testFunc - for the exact same reason as the line underneath it. A Range object has a default member that points to its .Value. When you do this:

DoSomething (SomeRange)

What's really happening is this:

DoSomething (SomeRange.Value)

The parentheses are telling VBA to evaluate the expression as a value, before passing the result by value (ByVal) of that expression to the procedure being invoked, regardless of the implicit ByRef modifier in the procedure's signature.

Problem is, given a 16-cell Range, Range.Value is a 2D array - and given a single-cell Range, Range.Value is a Variant that contains that cell's value, and that can't possibly be coerced into a Range object instance, so it's impossible that the code you have here "works fine": it's an object required error, because the procedure is expecting a Range and you're giving it a Variant that contains a 2D array.

Why your "works fine" code isn't really working

The only way testFunc (ThisWorkbook.Sheets("Sheet2").Range("A1:A16")) could possibly work, is if testFunc had this signature (which, I suspect it did at one point before you ultimately asked this question):

Function testFunc(aCol)

Or the explicit equivalent:

Public Function testFunc(ByRef aCol As Variant) As Variant

And because a 2D array can be iterated with a For Each loop (albeit very inefficiently), and it's possible that the entire A1:A16 range contains values that can be coerced into valid Integer values, "works fine" indeed... except you're updating an in-memory copy of the data, not the cells themselves - so it wasn't quite "works fine", was more like "doesn't crash".

Here's a MCVE:

Private Function DoSomething(ByRef foo As Range)
End Function

Public Sub Test()
    DoSomething (Range("A1").Value)
End Sub

Calling Test throws run-time error 424 "Object Required".

Public Function DoSomething(ByRef foo As Range)
End Function

Public Sub Test()
    DoSomething (Range("A1:A100").Value)
End Sub

Calling Test throws the same run-time error 424 "Object Required".

Now remove the As Range declaration:

Public Function DoSomething(ByRef foo As Variant)
    Debug.Print TypeName(foo)
End Function

Public Sub Test()
    DoSomething (Range("A1:A100").Value)
End Sub

Invoking Test prints Variant() to the immediate pane (Ctrl+G). Now make the range contain just one single cell:

Public Function DoSomething(ByRef foo As Variant)
    Debug.Print TypeName(foo)
End Function

Public Sub Test()
    DoSomething (Range("A1").Value)
End Sub

Invoking Test prints whatever data type the value of cell A1 holds. If it's text, it prints String. If it's a number, it prints Double. If it's a date, it prints Date. If it's a cell error (e.g. #NA, #VALUE!, etc.), it prints Error.

Note that the results are identical for all of the above, whether you specify .Value explicitly or not, because omitting .Value boils down to implicitly specifying it.

Also note that passing an array ByVal is illegal. What's being passed to the function here is a copy of a pointer to the beginning of the array - the Variant array isn't storing the array itself, just a pointer to its actual location: that's why & how you can legally pass a variant array by value.

Why the variable is blowing up too

The 2nd line is throwing the same error, for the same reason:

testFunc (aRange)    '<---- error

You're implicitly doing this:

testFunc aRange.Value

Because that's what the parentheses do: they tell VBA to evaluate the expression as a value, and pass it as such.

So you're passing a 2D variant array to a procedure that's expecting a Range.

This is different, and correct:

testFunc aRange

Note the lack of parentheses: now you're passing the Range object reference to a procedure that accepts a Range object reference, ByRef (although that modifier is implicit and a more semantically correct way to do it would be to pass the object reference ByVal).

So how do I tell when the arguments are being evaluated as a value?

When you invoke a Function procedure, you're normally interested in its return value:

result = MsgBox("Confirm?", vbYesNo)

The VBA automatically positions the opening parenthesis immediately after the function's identifier - no whitespace.

When you invoke a Function procedure without capturing its return value, you must omit the parentheses:

MsgBox "Confirm?", vbYesNo

Note that this would be a compile error:

MsgBox ("Confirm?", vbYesNo)

Because the expression ("Confirm?", vbYesNo) cannot be evaluated as a value and passed as such to the first parameter of the procedure.

That's easy though - MsgBox has multiple parameters. People get confused when there's only one parameter - because then this looks legal:

testFunc (aRange)

Notice the whitespace: it shouldn't be there. That's the VBE telling you "these parentheses are NOT part of the function call, they're part of the argument you're going pass to that function, and if whatever is in these parentheses can't be evaluated as a value at run-time, expect trouble".

If your testFunc procedure isn't returning a value, then it shouldn't be a Function in the first place - it should be a Sub procedure. Functions take input and return a value, Subs do something, which usually entails side-effects, e.g. actual cell values being modified.


问:
PHP Class Constants - Public, Private or Protected?
Am I correct in assuming that const properties are automatically public? Is there a way to make them private or protected?

Thanks in advance.

答:
As of php7.1, you can define your class constants with access modifiers (public, private or protected). Have a look at the following example:

```<code><?php
class superheroes{
    public const kal_el = 'Superman';
    protected const bruce_wayne = 'Batman'; # works php7.1 onwards
    private const anthony_stark = 'Iron Man'; # works php7.1 onwards

    public static function show_remaining(){
        echo self::bruce_wayne, '<br />';
        echo self::anthony_stark, '<br />';
    }
}
echo superheroes::kal_el, '<br />';
superheroes::show_remaining();
</code>```

Credits: http://dwellupper.io/post/48/defining-class-constants-in-php

Body:
As of php7.1, you can define your class constants with access modifiers (public, private or protected). Have a look at the following example:

<?php
class superheroes{
    public const kal_el = 'Superman';
    protected const bruce_wayne = 'Batman'; # works php7.1 onwards
    private const anthony_stark = 'Iron Man'; # works php7.1 onwards

    public static function show_remaining(){
        echo self::bruce_wayne, '<br />';
        echo self::anthony_stark, '<br />';
    }
}
echo superheroes::kal_el, '<br />';
superheroes::show_remaining();

Credits: http://dwellupper.io/post/48/defining-class-constants-in-php


问:
search suggestions problem android
Well i've been looking at Android's Documentation and i don't seem to understand how they can query a database to show suggestions while the user is typing. Can you guys tell me what listener to implement? I tried onContentChanged() but it didn't work.

Thanks in advance.

答: Everything is there : http://developer.android.com/guide/topics/search/index.html</p>

Title: search suggestions problem android


问:
Java Swing adding component issues
I'm approaching the study of Swing java library.
The following simple code, "in most of cases", is not working (see pic 1 below) (label1 somehow disappear or is not added to the contentPane at all)
Very rarely it works (I had to run and stop it many times to catch the right result).  (pic 2)
Sometimes nothing displayed. (pic3)

I know it should be handled with a layout manager but i'm interested in understanding why it happens rather than workaround this.

I'm experiencing this issue within Eclipse on both Windows 7 and 8.1

Thx

```<code>public static void main(String[] args){
    // TODO Auto-generated method stub
    JFrame finestra=new JFrame("frame title");
    finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    finestra.setBounds(0, 0, 300, 700);
    finestra.setVisible(true);

    JLabel label1=new JLabel("label 1");
    finestra.add(label1);

    JLabel label2=new JLabel("label 2");
    finestra.add(label2);
}
</code>```

pic1:
]

pic2:
]

pic3:
]

答:
JFrame.add(Component) adds given component to "center" of JFrame's content pane. So, when you add label1, it is added to "center". And when you add label2, it replaces label1 in "center". That's why you end up with label2 only. Try below code and see:</p>

```<code>public class Test
{
  public static void main(String[] args)
  {
    JFrame finestra=new JFrame("frame title");
    finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    finestra.setBounds(0, 0, 300, 700);

    JLabel label1=new JLabel("label 1");
    finestra.add(label1, BorderLayout.NORTH);

    JLabel label2=new JLabel("label 2");
    finestra.add(label2, BorderLayout.CENTER);

    // Call setVisible(true) after labels are layed out.
    finestra.setVisible(true);
  }
}
</code>```

Title: Java Swing adding component issues

Body:
I'm approaching the study of Swing java library.
The following simple code, "in most of cases", is not working (see pic 1 below) (label1 somehow disappear or is not added to the contentPane at all)
Very rarely it works (I had to run and stop it many times to catch the right result).  (pic 2)
Sometimes nothing displayed. (pic3)

I know it should be handled with a layout manager but i'm interested in understanding why it happens rather than workaround this.

I'm experiencing this issue within Eclipse on both Windows 7 and 8.1

Thx

public static void main(String[] args){
    // TODO Auto-generated method stub
    JFrame finestra=new JFrame("frame title");
    finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    finestra.setBounds(0, 0, 300, 700);
    finestra.setVisible(true);

    JLabel label1=new JLabel("label 1");
    finestra.add(label1);

    JLabel label2=new JLabel("label 2");
    finestra.add(label2);
}

pic1:
]

pic2:
]

pic3:
]

Body:
JFrame.add(Component) adds given component to "center" of JFrame's content pane. So, when you add label1, it is added to "center". And when you add label2, it replaces label1 in "center". That's why you end up with label2 only. Try below code and see:

public class Test
{
  public static void main(String[] args)
  {
    JFrame finestra=new JFrame("frame title");
    finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    finestra.setBounds(0, 0, 300, 700);

    JLabel label1=new JLabel("label 1");
    finestra.add(label1, BorderLayout.NORTH);

    JLabel label2=new JLabel("label 2");
    finestra.add(label2, BorderLayout.CENTER);

    // Call setVisible(true) after labels are layed out.
    finestra.setVisible(true);
  }
}


问:
How to set quota for openstack project/tenant using python-openstacksdk
I have creatd a new project using openstacksdk. I want to set certain amount of CPU, RAM and floatingIPs available for that project to manage usage. How can I set Quota for the new project created?</p>

答:
Current openstackSDK (0.9.19) does not have function to allocate quota.
This can be done using openstack API.</p>

```<code>conn = connection.Connection(auth_url='URL', project_name='PROJECT', username='USERNAME', password='ADMIN_PASSWORD', verify=False)

token = conn.authorize()

header = {'X-AUTH-TOKEN': token,'Content-Type': 'application/json'}
request_body = {"quota_set": {"instances": "3" ,"ram": "40960", "cores": "20"}}
data_json = json.dumps(request_body, sort_keys=True, indent=4, separators=(',', ': '))
r = requests.put(nova_url,headers=header,data=data_json,verify=False)
</code>```

Body:
Current openstackSDK (0.9.19) does not have function to allocate quota.
This can be done using openstack API.

conn = connection.Connection(auth_url='URL', project_name='PROJECT', username='USERNAME', password='ADMIN_PASSWORD', verify=False)

token = conn.authorize()

header = {'X-AUTH-TOKEN': token,'Content-Type': 'application/json'}
request_body = {"quota_set": {"instances": "3" ,"ram": "40960", "cores": "20"}}
data_json = json.dumps(request_body, sort_keys=True, indent=4, separators=(',', ': '))
r = requests.put(nova_url,headers=header,data=data_json,verify=False)


问:
OAuth token refresh with React Native and Redux
I am new to React Native and one of the first obstacles I am running into is refreshing my access token when it expires. The basic implementation is such that there is an access token and a refresh token. The access token expires and the refresh token is sent within the Authorization header to refresh the access token. Based on this SO post I implemented a Middleware that checks during each API call to see if our access token is expiring soon. If so, it kicks off an action creator which makes API calls to refresh and confirm the new access token. I've only shown the refresh call here, as to not overcomplicate things.

The PROBLEM is that the same middleware that detects the need to refresh is also hit by the refresh call itself, and this leads to an infinite loop and eventually exceeding the call stack size. I was wondering if anybody is able to help me figure out a way around this, or tell me I'm being dumb and offer a better overall solution. Any guidance is much appreciated. Thank you!

```<code>function auth({ dispatch, getState }) {
      return next => action => {
        if (typeof action === 'function') {
          // Check expiration of our token
          if (tokenIsExpired(getState)) {
            console.log('Our access token will expire in less than 30s, refreshing');
            // Make sure we are not already refreshing the access token
            if (!getState().core.refreshTokenIsLoading) {
              return next(dispatch(refreshAccessTokenFlow())).then(() => next(action));
            } else {
              // Take promise from state and act after it
              return getState().core.refreshAccessTokenFlow.then(() => next(action));
            }
          }
        }
        return next(action);
      }
    }

export function refreshAccessTokenFlow() {
  return (dispatch) => {
    return dispatch(refreshAccessToken())
      .then((didRefresh) => {
        console.log('refresh access token returned');
        return Promise.resolve();
      })
      .catch(error => {
        console.log('refresh access token failed: ' + error);
        return Promise.reject(error);
      });
  }
}
</code>```

答:
You could for example pass in metadata in the actions that require the access token and afterwards in the middleware check or you need to validate the token based on that metadata.

Action file

```<code>// My Team
export function fetchStuffWithOAuthStart(userId) {
  return {
    type: USER_FETCH_STUFF_WITHOUT_OAUTH_START,
    payload: { userId },
    meta: {
      oauth: true,
    }
};
</code>```

Middleware

```<code>function auth({ dispatch, getState }) {
      return next => action => {
        if (typeof action === 'function') {
          // Check here or you need to validate the token
          if (!action.meta || !action.meta.oauth) {
            return next(action);
          }

          // Check expiration of our token
          if (tokenIsExpired(getState)) {
            console.log('Our access token will expire in less than 30s, refreshing');
            // Make sure we are not already refreshing the access token
            if (!getState().core.refreshTokenIsLoading) {
              return next(dispatch(refreshAccessTokenFlow())).then(() => next(action));
            } else {
              // Take promise from state and act after it
              return getState().core.refreshAccessTokenFlow.then(() => next(action));
            }
          }
        }
        return next(action);
      }
    }

export function refreshAccessTokenFlow() {
  return (dispatch) => {
    return dispatch(refreshAccessToken())
      .then((didRefresh) => {
        console.log('refresh access token returned');
        return Promise.resolve();
      })
      .catch(error => {
        console.log('refresh access token failed: ' + error);
        return Promise.reject(error);
      });
  }
}
</code>```

Body:
I am new to React Native and one of the first obstacles I am running into is refreshing my access token when it expires. The basic implementation is such that there is an access token and a refresh token. The access token expires and the refresh token is sent within the Authorization header to refresh the access token. Based on this SO post I implemented a Middleware that checks during each API call to see if our access token is expiring soon. If so, it kicks off an action creator which makes API calls to refresh and confirm the new access token. I've only shown the refresh call here, as to not overcomplicate things.

The PROBLEM is that the same middleware that detects the need to refresh is also hit by the refresh call itself, and this leads to an infinite loop and eventually exceeding the call stack size. I was wondering if anybody is able to help me figure out a way around this, or tell me I'm being dumb and offer a better overall solution. Any guidance is much appreciated. Thank you!

function auth({ dispatch, getState }) {
      return next => action => {
        if (typeof action === 'function') {
          // Check expiration of our token
          if (tokenIsExpired(getState)) {
            console.log('Our access token will expire in less than 30s, refreshing');
            // Make sure we are not already refreshing the access token
            if (!getState().core.refreshTokenIsLoading) {
              return next(dispatch(refreshAccessTokenFlow())).then(() => next(action));
            } else {
              // Take promise from state and act after it
              return getState().core.refreshAccessTokenFlow.then(() => next(action));
            }
          }
        }
        return next(action);
      }
    }

export function refreshAccessTokenFlow() {
  return (dispatch) => {
    return dispatch(refreshAccessToken())
      .then((didRefresh) => {
        console.log('refresh access token returned');
        return Promise.resolve();
      })
      .catch(error => {
        console.log('refresh access token failed: ' + error);
        return Promise.reject(error);
      });
  }
}

Body:
You could for example pass in metadata in the actions that require the access token and afterwards in the middleware check or you need to validate the token based on that metadata.

Action file

// My Team
export function fetchStuffWithOAuthStart(userId) {
  return {
    type: USER_FETCH_STUFF_WITHOUT_OAUTH_START,
    payload: { userId },
    meta: {
      oauth: true,
    }
};

Middleware

function auth({ dispatch, getState }) {
      return next => action => {
        if (typeof action === 'function') {
          // Check here or you need to validate the token
          if (!action.meta || !action.meta.oauth) {
            return next(action);
          }

          // Check expiration of our token
          if (tokenIsExpired(getState)) {
            console.log('Our access token will expire in less than 30s, refreshing');
            // Make sure we are not already refreshing the access token
            if (!getState().core.refreshTokenIsLoading) {
              return next(dispatch(refreshAccessTokenFlow())).then(() => next(action));
            } else {
              // Take promise from state and act after it
              return getState().core.refreshAccessTokenFlow.then(() => next(action));
            }
          }
        }
        return next(action);
      }
    }

export function refreshAccessTokenFlow() {
  return (dispatch) => {
    return dispatch(refreshAccessToken())
      .then((didRefresh) => {
        console.log('refresh access token returned');
        return Promise.resolve();
      })
      .catch(error => {
        console.log('refresh access token failed: ' + error);
        return Promise.reject(error);
      });
  }
}


问:
Sub-Form in Swift Eureka
I'm using Eureka Form-Framework in Swift 3 project.

I need to use MultivaluedSection, but instead of fetching a String out of a String options array (like in code below), I want to open a subform (e.g. with TextRow, NumberRow, ...) in a presented controller.

I know, that I can implement a custom presenter row, but I don't find a solution to show a "sub-form" for a custom presenter row.

Is this even possible with Eureka framework?

```<code>let multivaluedSection = MultivaluedSection(multivaluedOptions: [.Insert, .Delete],
                                                    header: rawField["name"].stringValue,
                                                    footer: "")
multivaluedSection.multivaluedRowToInsertAt = { index in
            return PushRow<String>{
                $0.title = "Tap to select ;)..at \(index)"
                $0.options = ["Option 1", "Option 2", "Option 3"]
            } }
self.form.append(multivaluedSection)
</code>```

答:
This can be done using a custom selector row.

You just need to follow the instructions here, make a custom push row,

```<code>public final class CustomPushRow: SelectorRow<PushSelectorCell<SomeType>, YourSubFormVC>, RowType {

    public required init(tag: String?) {
        super.init(tag: tag)
        presentationMode = .show(controllerProvider: ControllerProvider.callback {
            return YourSubFormVC(){ _ in }
            }, onDismiss: { vc in
                _ = vc.navigationController?.popViewController(animated: true)
        })
    }
}
</code>```

YourSubFormVC is the VC that is going to be presented when a suer taps on the row. It should conform to TypedRowControllerType. Since you want this VC to be a form as well, make it inherit from FormViewController and start building the form in viewDidLoad!

Title: Sub-Form in Swift Eureka

Body:
I'm using Eureka Form-Framework in Swift 3 project.

I need to use MultivaluedSection, but instead of fetching a String out of a String options array (like in code below), I want to open a subform (e.g. with TextRow, NumberRow, ...) in a presented controller.

I know, that I can implement a custom presenter row, but I don't find a solution to show a "sub-form" for a custom presenter row.

Is this even possible with Eureka framework?

let multivaluedSection = MultivaluedSection(multivaluedOptions: [.Insert, .Delete],
                                                    header: rawField["name"].stringValue,
                                                    footer: "")
multivaluedSection.multivaluedRowToInsertAt = { index in
            return PushRow<String>{
                $0.title = "Tap to select ;)..at \(index)"
                $0.options = ["Option 1", "Option 2", "Option 3"]
            } }
self.form.append(multivaluedSection)

Body:
This can be done using a custom selector row.

You just need to follow the instructions here, make a custom push row,

public final class CustomPushRow: SelectorRow<PushSelectorCell<SomeType>, YourSubFormVC>, RowType {

    public required init(tag: String?) {
        super.init(tag: tag)
        presentationMode = .show(controllerProvider: ControllerProvider.callback {
            return YourSubFormVC(){ _ in }
            }, onDismiss: { vc in
                _ = vc.navigationController?.popViewController(animated: true)
        })
    }
}

YourSubFormVC is the VC that is going to be presented when a suer taps on the row. It should conform to TypedRowControllerType. Since you want this VC to be a form as well, make it inherit from FormViewController and start building the form in viewDidLoad!


问:
How to apply SMTP Authentication to my mail
The code below is my mail code that send passsword to mail but it does not go to yahoo and gmail i want to add STMP authentication to it how can i do that.

```<code> <?php
     if(isset($_POST['submit'])){
 If(empty($_POST['email'])) {
 echo 'Please fill in the required fields!';

     }else{

        $email_to = $_POST['email'];
         $sql = "SELECT statue FROM statue WHERE mail='$email_to'";
         $result = mysql_query($sql);

             $count=mysql_num_rows($result);
             if($count==1){
             $rows = mysql_fetch_array($result);
             $your_password = $rows['statue'];

         $to = $email_to;
        $subject = "Your password here";
         $headers  = 'MIME-Version: 1.0' . "\r\n";
         $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
         $headers .="from: Alinke <support@mydomain.com>";

            $messages ="Here is your password : $your_password";
             $sentmail = mail($to,$subject,$messages,$headers);
             }else{
             echo 'your email can not be found in our database';
         }

             if($sentmail){
                 echo 'Your password has been sent to your email address.';
             }else{
                 echo 'Cannot send password to your e-mail address';
             }
     }
 }
</code>```

?>

答:
Swiftmailer is an advanced mailer class that can deal with authentication.

Here is an example for sending E-Mail through Google Mail with Swiftmailer.

Body:
The code below is my mail code that send passsword to mail but it does not go to yahoo and gmail i want to add STMP authentication to it how can i do that.

 <?php
     if(isset($_POST['submit'])){
 If(empty($_POST['email'])) {
 echo 'Please fill in the required fields!';

     }else{

        $email_to = $_POST['email'];
         $sql = "SELECT statue FROM statue WHERE mail='$email_to'";
         $result = mysql_query($sql);

             $count=mysql_num_rows($result);
             if($count==1){
             $rows = mysql_fetch_array($result);
             $your_password = $rows['statue'];

         $to = $email_to;
        $subject = "Your password here";
         $headers  = 'MIME-Version: 1.0' . "\r\n";
         $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
         $headers .="from: Alinke <support@mydomain.com>";

            $messages ="Here is your password : $your_password";
             $sentmail = mail($to,$subject,$messages,$headers);
             }else{
             echo 'your email can not be found in our database';
         }

             if($sentmail){
                 echo 'Your password has been sent to your email address.';
             }else{
                 echo 'Cannot send password to your e-mail address';
             }
     }
 }

?>


问:
How can I force a file to be opened in a new instance of the application?
I have the following code:

```<code>var p = Process.Start("file.xlsx");
p.WaitForExit();
</code>```

If Excel is already running, the file will be opened in that instance and p will be null and therefore I can't wait for exit. How can I force the file to be opened in a new instance of the application?

答:
Try this:

"c:\Program Files (x86)\Microsoft Office\Office\Office12\excel.exe" /x "path_to_your_file.xlsx"

C#

```<code>var psi = new ProcessStartInfo();
psi.FileName = @"C:\Program Files (x86)\Microsoft Office\Office12\Excel.exe";
psi.Arguments = @"/x ""C:\Users\Michael\Desktop\abc.xlsx";
var p = new Process();
p.StartInfo = psi;
p.Start();
p.WaitForExit();
</code>```

The subfolder /Office12 depends on the office version you're using.

Body:
I have the following code:

var p = Process.Start("file.xlsx");
p.WaitForExit();

If Excel is already running, the file will be opened in that instance and p will be null and therefore I can't wait for exit. How can I force the file to be opened in a new instance of the application?

Body:
Try this:

"c:\Program Files (x86)\Microsoft Office\Office\Office12\excel.exe" /x "path_to_your_file.xlsx"

C#

var psi = new ProcessStartInfo();
psi.FileName = @"C:\Program Files (x86)\Microsoft Office\Office12\Excel.exe";
psi.Arguments = @"/x ""C:\Users\Michael\Desktop\abc.xlsx";
var p = new Process();
p.StartInfo = psi;
p.Start();
p.WaitForExit();

The subfolder /Office12 depends on the office version you're using.


问:
JS split regex by two different character
I have 2 strings:

```<code>"test:header_footer"
"test_3142"
</code>```

I want to get array:

```<code>array = "test:header_footer".split(":") // ['test', 'header_footer']
array2 = "test_3142".split("_") // ['test', '3142']
</code>```

Can I combine this with a regex expression to get the same result?

```<code>function(s) {
 retutn s.split(/:|_/) // return bad value
}
</code>```

So if string contain ':' - not separate by second '_'

答:
You can use the includes method on your String to determine if there's a : present. If there is split the String by the colon, otherwise split the String by the underscore.

```<code>split_string = s => s.includes(":") ? s.split(":") : s.split("_");
</code>```

//test strings
let str = "my:string_demo",
  str2 = "my_string_demo",
  str3 = "myString:demo_thing",
  //string function
  split_string = s => s.includes(":") ? s.split(":") : s.split("_");

console.log(
  str, split_string(str)
);
console.log(
  str2, split_string(str2)
);
console.log(
  str3, split_string(str3)
);```

Body:
I have 2 strings:

"test:header_footer"
"test_3142"

I want to get array:

array = "test:header_footer".split(":") // ['test', 'header_footer']
array2 = "test_3142".split("_") // ['test', '3142']

Can I combine this with a regex expression to get the same result?

function(s) {
 retutn s.split(/:|_/) // return bad value
}

So if string contain ':' - not separate by second '_'

Body:
You can use the includes method on your String to determine if there's a : present. If there is split the String by the colon, otherwise split the String by the underscore.

split_string = s => s.includes(":") ? s.split(":") : s.split("_");

//test strings
let str = "my:string_demo",
  str2 = "my_string_demo",
  str3 = "myString:demo_thing",
  //string function
  split_string = s => s.includes(":") ? s.split(":") : s.split("_");

console.log(
  str, split_string(str)
);
console.log(
  str2, split_string(str2)
);
console.log(
  str3, split_string(str3)
);


问:
System.Net.SecurityProtocolType.Tls12 definition not found
I'm trying to add the following line of code to the Global.asax file in a website project.

```<code>System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
</code>```

The vs2012 IntelliSense is showing that Tls12 definition exist.  But the build is saying that the definition does not exist (See screen shot).

I've tried adding System.Net.dll to the bin folder of the project, but the build still failed.  Any idea how I might be able to resolve this?

答:
Are you on .net 4.0? You should be at least 4.5 to use it. You can try to update your web target framework version:
TLS 1.2 in .NET Framework 4.0</p>

Body:
I'm trying to add the following line of code to the Global.asax file in a website project.

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

The vs2012 IntelliSense is showing that Tls12 definition exist.  But the build is saying that the definition does not exist (See screen shot).

I've tried adding System.Net.dll to the bin folder of the project, but the build still failed.  Any idea how I might be able to resolve this?


问:
Excel time difference
I have two time:

9:29:00 AM (B2)

6:16:00 PM (C2)

I want to get the hh:mm (hours and minutes) between those two times. I tried the following function:

```<code>=TEXT(B2-C2,"h:mm")
</code>```

But I get a #VALUE! error.

I formatted the two time cells as TIME format (*h:mm:ss am:pm) and result cell also as TIME format (hh:mm)

答:
As barry houdini mentioned back in 2013, I also ran into the error of subtracting giving a negative number, and excel just throws an error. No other response on the internet gave me good results. Although my method is longer, it always works with times in hh:mm:ss AM/PM. Just change the text format part of the formula for whatever you have. My data was:

11:15:45 PM 1:41:20 AM

I converted it to military time for ease with

```<code>=TEXT(A2, "hh:mm:ss")
</code>```

Data was now:

23:15:45    01:41:20

I made another column, let's call it C, that just subtracts the second time from the first time,

```<code>=B2-A2
</code>```

I next used an IF statement on this column, so that if the absolute value of the difference was the same as the number (a positive), I'd use

```<code>TEXT(B2-A2,"hh:mm:ss")
</code>```

which just subtracts the later time from the earlier time. But...

If the absolute value of the difference was not the same, e.g. error-ville with a lot of hashes ##########, I use:

```<code>TEXT(24-(A10-B10),"hh:mm:ss")
</code>```

Altogether, we have one more column, which finally spits out the correct hour difference. This column is predicated on columns A, B, and our error-prone difference column C:

```<code>=IF(C2=ABS(C2),TEXT(B2-A2,"hh:mm:ss"),TEXT(24-(A2-B2),"hh:mm:ss"))
</code>```

this is the most ridiculous thing I have ever done. It's been years and such a simple case, never solved by Excel.

Title: Excel time difference

Body:
I have two time:

9:29:00 AM (B2)

6:16:00 PM (C2)

I want to get the hh:mm (hours and minutes) between those two times. I tried the following function:

=TEXT(B2-C2,"h:mm")

But I get a #VALUE! error.

I formatted the two time cells as TIME format (*h:mm:ss am:pm) and result cell also as TIME format (hh:mm)

Body:
As barry houdini mentioned back in 2013, I also ran into the error of subtracting giving a negative number, and excel just throws an error. No other response on the internet gave me good results. Although my method is longer, it always works with times in hh:mm:ss AM/PM. Just change the text format part of the formula for whatever you have. My data was:

11:15:45 PM 1:41:20 AM

I converted it to military time for ease with

=TEXT(A2, "hh:mm:ss")

Data was now:

23:15:45    01:41:20

I made another column, let's call it C, that just subtracts the second time from the first time,

=B2-A2

I next used an IF statement on this column, so that if the absolute value of the difference was the same as the number (a positive), I'd use

TEXT(B2-A2,"hh:mm:ss")

which just subtracts the later time from the earlier time. But...

If the absolute value of the difference was not the same, e.g. error-ville with a lot of hashes ##########, I use:

TEXT(24-(A10-B10),"hh:mm:ss")

Altogether, we have one more column, which finally spits out the correct hour difference. This column is predicated on columns A, B, and our error-prone difference column C:

=IF(C2=ABS(C2),TEXT(B2-A2,"hh:mm:ss"),TEXT(24-(A2-B2),"hh:mm:ss"))

this is the most ridiculous thing I have ever done. It's been years and such a simple case, never solved by Excel.


问:
Drupal 8 customizing view title in module
I am using the following code to change a view title to a custom title:

```<code>function MYMODULE_preprocess_page_title(&$variables) {
  if (some logic to check if this is the correct view)
    $variables['title] = 'Something Different!';
}
</code>```

This works to change the title in the content area within the
 tag, but the title of the browser tab is not changed (in <title>...</title>).

What is the correct way to change the view title to reflect both in the page body and the browser title?

答:
It will depends on how you build or what theme you are using, for example for change the HTML title using the default system theme it use something like this
https://github.com/drupal/drupal/blob/8.4.x/core/modules/system/templates/html.html.twig#L32

```<code> <title>{{ head_title|safe_join(' | ') }}</title>
</code>```

In this case you need to look what the values are for it, I would recommend to look for the value into the page preprocessor.

Body:
I am using the following code to change a view title to a custom title:

function MYMODULE_preprocess_page_title(&$variables) {
  if (some logic to check if this is the correct view)
    $variables['title] = 'Something Different!';
}

This works to change the title in the content area within the
 tag, but the title of the browser tab is not changed (in <title>...</title>).

What is the correct way to change the view title to reflect both in the page body and the browser title?

Body:
It will depends on how you build or what theme you are using, for example for change the HTML title using the default system theme it use something like this
https://github.com/drupal/drupal/blob/8.4.x/core/modules/system/templates/html.html.twig#L32

 <title>{{ head_title|safe_join(' | ') }}</title>

In this case you need to look what the values are for it, I would recommend to look for the value into the page preprocessor.


问:
How to find Outlook contact Unique ID?
I want to see all fields of the contacts in outlook. Here the contacts are synchronized from D365. All fields that are coming from D365 will also be shown in outlook contacts (fields such as PrimaryId, CreatedBy, Owner, CreatedDate, modified By, modifiedDate etc.. )

When I open the contacts, not all fields are showing. How can I see all fields of the records?

Suggestions are appreciated.

答:
You can open Advanced Find for Contacts and in there you can select additional columns.

Thanks Naveen. Except for ContactId, all the fields that you list should be available in a Contact Advanced Find view.

To get the ContactId for an individual record, you can get it from the URL of the record, or use the Chrome Level Up add-in, or bookmarklets.

To get a list of Contact ID's you can export a view to Excel with reimport to get the ID's in the hidden column A, or create a FetchXML query and run it in FetchXML Tester, among other ways.

Title: How to find Outlook contact Unique ID?


问:
How to center text in a row using Bootstrap 4
The problem is that
 and
 are appearing on same line and no matter what I do they can't be centered.

HTML

```<code><div class="container">
  <div class="row" id="appSummary">
    <h1>Why This App Is Awesome</h1>
    <p class="lead">Summary, once again, of your app's awesomeness</p>
  </div>
</div>
</code>```

CSS

```<code>#appSummary{
  text-align:center;
}
</code>```

答:
The best way to do this is to wrap the text in a column that has the class text-center.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

Why This App Is Awesome

Summary, once again, of your app's awesomeness

```

An other way to do this is to use the class justify-content-center on the row, but without the column things may break.

Body:
The problem is that
 and
 are appearing on same line and no matter what I do they can't be centered.

HTML

Why This App Is Awesome

Summary, once again, of your app's awesomeness

CSS

#appSummary{
  text-align:center;
}

Body:
The best way to do this is to wrap the text in a column that has the class text-center.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<div class="container">
  <div class="row" id="appSummary">
    <div class="col text-center">
      <h1>Why This App Is Awesome</h1>
      <p class="lead">Summary, once again, of your app's awesomeness</p>
    </div>
  </div>
</div>

An other way to do this is to use the class justify-content-center on the row, but without the column things may break.


问:
Calling a Java application from CLIPS
I have a runnable jar: help.jar, and I need to call it from a rule in CLIPS, as

```<code>(defrule ask-shape
    (not (shape ?))
    =>
    (bind ?answer (ask-question "What is the shape?"))
    (while (eq ?answer help) do
       (help) ;; calling the java function
       (bind ?answer (ask-question "What is the shape?")))
    (assert (shape ?answer)))
</code>```

How can I do it?

答:
Read the CLIPS Advanced Programming Guide for instructions on creating user-defined functions which will allow you to call C code from a CLIPS program (such as calling "(help)" in your ask-shape rule). Use a search engine and search for "how to call Java from C". You'll get hits like this: https://www.codeproject.com/Articles/22881/How-to-Call-Java-Functions-from-C-Using-JNI.

Alternately if you don't need any interaction between CLIPS and the Java code you code use the system command from your rule: (system "java -jar help.jar").

Title: Calling a Java application from CLIPS

Body:
I have a runnable jar: help.jar, and I need to call it from a rule in CLIPS, as

(defrule ask-shape
    (not (shape ?))
    =>
    (bind ?answer (ask-question "What is the shape?"))
    (while (eq ?answer help) do
       (help) ;; calling the java function
       (bind ?answer (ask-question "What is the shape?")))
    (assert (shape ?answer)))

How can I do it?


问:
How to create tree based query from same table in mysql?
Hey guys i want to create one tree based data in my html view from mysql.
I have one table salary_slip there 2 columns pay_month and pay_year.

data is like this:

```<code>pay_month      pay_year

February         2014
march            2014
January          2015
February         2015
April            2015
may              2015
June             2015
January          2016
march            2016
December         2016
</code>```

So now i want to create tree view for the same.so, if user will click on 2016(pay_year) onclick this all data in pay_month in front of 2016 should be display in tree format and same for the all.

My current query is:

```<code>select
    PAY_MONTH,
    PAY_YEAR
from
    india_salary_slip_details
where
    EMPLOYEE_ID = 34
group by
    pay_year
</code>```

By this i got my data:
but i can only see each year's first month only.
please provide me with better query so i can get my result.

image for the same:current data from my query

答:
A major part of your problem comes from the use of GROUP BY, which is used for, well, grouping.

MySQL has different handling of GROUP BY than other DBMS' that require all non-aggregate fields to be listed in the GROUP BY clause. MySQL give you enough rope with which to hang yourself (so to speak), which is why you didn't get an error for what is clearly not an intended use of GROUP BY.

Depending on how your front end is handling the data, you have a few options.

Option 1) Have it load (ordered) and use the output loop to determine the change in year.

SQL Query:

```<code>SELECT
    PAY_MONTH,
    PAY_YEAR
FROM
    india_salary_slip_details
WHERE
    EMPLOYEE_ID = 34
ORDER BY
    pay_year,
    pay_month -- we want it ordered by year, then month, though this will be alphabetical due to the data type
</code>```

PHP Code:

```<code><?php
$year = NULL;
foreach ($result as $row) { // Assuming your result is stored as $result
   if ($row['PAY_YEAR'] !== $year) {
       // Print the year in the left column so to speak, perhaps create a sublist, etc
       // Set the year
       $year = $row['PAY_YEAR'];
   }
   // Add month
   // Do something with $row['PAY_MONTH'], perhaps add it to a sublist, again, depends on front end handling.
}
</code>```

Option 2) Have it load the years, then the next level asynchronously.

SQL Query to get years:

```<code>SELECT DISTINCT
    PAY_YEAR
FROM
    india_salary_slip_details
WHERE
    EMPLOYEE_ID = 34
ORDER BY
    PAY_YEAR
</code>```

SQL Query to get months given a year:

```<code>SELECT
    PAY_MONTH
FROM
    india_salary_slip_details
WHERE
    EMPLOYEE_ID = 34
    AND PAY_YEAR = (Whatever the year is)
ORDER BY
    PAY_MONTH
</code>```

Body:
Hey guys i want to create one tree based data in my html view from mysql.
I have one table salary_slip there 2 columns pay_month and pay_year.

data is like this:

pay_month      pay_year

February         2014
march            2014
January          2015
February         2015
April            2015
may              2015
June             2015
January          2016
march            2016
December         2016

So now i want to create tree view for the same.so, if user will click on 2016(pay_year) onclick this all data in pay_month in front of 2016 should be display in tree format and same for the all.

My current query is:

select
    PAY_MONTH,
    PAY_YEAR
from
    india_salary_slip_details
where
    EMPLOYEE_ID = 34
group by
    pay_year

By this i got my data:
but i can only see each year's first month only.
please provide me with better query so i can get my result.

image for the same:current data from my query

Body:
A major part of your problem comes from the use of GROUP BY, which is used for, well, grouping.

MySQL has different handling of GROUP BY than other DBMS' that require all non-aggregate fields to be listed in the GROUP BY clause. MySQL give you enough rope with which to hang yourself (so to speak), which is why you didn't get an error for what is clearly not an intended use of GROUP BY.

Depending on how your front end is handling the data, you have a few options.

Option 1) Have it load (ordered) and use the output loop to determine the change in year.

SQL Query:

SELECT
    PAY_MONTH,
    PAY_YEAR
FROM
    india_salary_slip_details
WHERE
    EMPLOYEE_ID = 34
ORDER BY
    pay_year,
    pay_month -- we want it ordered by year, then month, though this will be alphabetical due to the data type

PHP Code:

<?php
$year = NULL;
foreach ($result as $row) { // Assuming your result is stored as $result
   if ($row['PAY_YEAR'] !== $year) {
       // Print the year in the left column so to speak, perhaps create a sublist, etc
       // Set the year
       $year = $row['PAY_YEAR'];
   }
   // Add month
   // Do something with $row['PAY_MONTH'], perhaps add it to a sublist, again, depends on front end handling.
}

Option 2) Have it load the years, then the next level asynchronously.

SQL Query to get years:

SELECT DISTINCT
    PAY_YEAR
FROM
    india_salary_slip_details
WHERE
    EMPLOYEE_ID = 34
ORDER BY
    PAY_YEAR

SQL Query to get months given a year:

SELECT
    PAY_MONTH
FROM
    india_salary_slip_details
WHERE
    EMPLOYEE_ID = 34
    AND PAY_YEAR = (Whatever the year is)
ORDER BY
    PAY_MONTH


问:
Ruby/Rails ternary and range
I want to filter a parameter if it falls within a range of 1 to 100.

Controller:

```<code>@range = search_range(params[:range])
</code>```

Helper:

```<code>def search_range(range)
  range = range.to_i
  range == 1..100 ? range : 30
end
</code>```

But it's always returns 30... tried many things and normal "if/else" but want ternary operator.
Thanks

答:
Just want to check if params[:range] is between 1..100. If not return 30

This should work:

```<code>def search_range(range)
  range = range.to_i
  range.between?(1, 100) ? range : 30
end
</code>```

The problem with your code is that == compares objects, i.e.:

```<code>20 == 1..100
#=> false
</code>```

checks whether the integer 20 is (numerically) equal to the range 1..100. Of course it's not, 1..100 isn't even a number.

Title: Ruby/Rails ternary and range

Body:
I want to filter a parameter if it falls within a range of 1 to 100.

Controller:

@range = search_range(params[:range])

Helper:

def search_range(range)
  range = range.to_i
  range == 1..100 ? range : 30
end

But it's always returns 30... tried many things and normal "if/else" but want ternary operator.
Thanks

Body:
Just want to check if params[:range] is between 1..100. If not return 30

This should work:

def search_range(range)
  range = range.to_i
  range.between?(1, 100) ? range : 30
end

The problem with your code is that == compares objects, i.e.:

20 == 1..100
#=> false

checks whether the integer 20 is (numerically) equal to the range 1..100. Of course it's not, 1..100 isn't even a number.


问:
How do I replace a char with another char in a database field
So this finds the bullet. I want to replace it with '*'

```<code>SELECT * FROM tblTrkRecordAction WHERE CHARINDEX(CHAR(0x0095), Comment) > 0
</code>```

答:
Assuming you want to make this replacement in the comments field you could try this:</p>

```<code>SELECT
    REPLACE(Comment, CHAR(0x0095), '*') AS new_comment
FROM tblTrkRecordAction
WHERE
    CHARINDEX(CHAR(0x0095), Comment) > 0;
</code>```

Body:
So this finds the bullet. I want to replace it with '*'

SELECT * FROM tblTrkRecordAction WHERE CHARINDEX(CHAR(0x0095), Comment) > 0

Body:
Assuming you want to make this replacement in the comments field you could try this:

SELECT
    REPLACE(Comment, CHAR(0x0095), '*') AS new_comment
FROM tblTrkRecordAction
WHERE
    CHARINDEX(CHAR(0x0095), Comment) > 0;


问:
How can explain the relation between mdlDerivatives output and mdlOutputs in S-function simulink
I am new in Simulink and have a model which is used the S-function. I can not understand how the output of the mdlDerivatives relates to the outputs of the mdlOutputs? In another word, If I want to write a mfile(without using Simulink) what are the states and what are the outputs? I want to write a mfile and find ddq, dq and q but do not get how states in these two parts make the output?(file attached)</p>

```<code>function [sys,x0,str,ts]=s_function(t,x,u,flag)
switch flag,
case 0,
e[sys,x0,str,ts]=mdlInitializeSizes;
case 1,
sys=mdlDerivatives(t,x,u);
case 3,
    sys=mdlOutputs(t,x,u);
case {2, 4, 9 }
    sys = [];
otherwise
    error(['Unhandled flag = ',num2str(flag)]);
end

function [sys,x0,str,ts]=mdlInitializeSizes
sizes = simsizes;
sizes.NumContStates  = 4;
sizes.NumDiscStates  = 0;
sizes.NumOutputs     = 4;
sizes.NumInputs      = 2;
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 0;
sys=simsizes(sizes);
x0=[0;0;0;0];
str=[];
ts=[];
function sys=mdlDerivatives(t,x,u)
q1=x(1);dq1=x(2);
q2=x(3);dq2=x(4);
dq=[dq1;dq2];

% The model is given by Slotine and Weiping Li(MIT 1987)
alfa=6.7;beta=3.4;
epc=3.0;eta=0;
m1=1;l1=1;
lc1=1/2;I1=1/12;
g=9.8;
e1=m1*l1*lc1-I1-m1*l1^2;
e2=g/l1;

H=[alfa+2*epc*cos(q2)+2*eta*sin(q2),beta+epc*cos(q2)+eta*sin(q2);
   beta+epc*cos(q2)+eta*sin(q2),beta];
C=[(-2*epc*sin(q2)+2*eta*cos(q2))*dq2,(-epc*sin(q2)+eta*cos(q2))*dq2;
   (epc*sin(q2)-eta*cos(q2))*dq1,0];
G=[epc*e2*cos(q1+q2)+eta*e2*sin(q1+q2)+(alfa-beta+e1)*e2*cos(q1);
   epc*e2*cos(q1+q2)+eta*e2*sin(q1+q2)];

tol(1)=u(1);
tol(2)=u(2);

ddq=inv(H)*(tol'-C*dq-G);
sys(1)=x(2);
sys(2)=ddq(1);
sys(3)=x(4);
sys(4)=ddq(2);
function sys=mdlOutputs(t,x,u)
sys(1)=x(1);
sys(2)=x(2);
sys(3)=x(3);
sys(4)=x(4);
</code>```

答:
A non-linear state-space model is comprised of 2 equations:

x_dot = f(x,u,t)

y = g(x,u,t)

If the system is linear this reduces to the (perhaps more familiar form)

x_dot = A * x + B * u

y = C * x + D * u

For a level-1 m-code S-Function (which is what you have), when Simulink wants the block's state derivative to be calculated it calls mdlDerivatives, and when it wan't the block's outputs it calls mdlOutputs.

That is mdlDerivatives implements the above equation for x_dot, and mdlOutputs implements the above equation for y.

Body:
I am new in Simulink and have a model which is used the S-function. I can not understand how the output of the mdlDerivatives relates to the outputs of the mdlOutputs? In another word, If I want to write a mfile(without using Simulink) what are the states and what are the outputs? I want to write a mfile and find ddq, dq and q but do not get how states in these two parts make the output?(file attached)

function [sys,x0,str,ts]=s_function(t,x,u,flag)
switch flag,
case 0,
e[sys,x0,str,ts]=mdlInitializeSizes;
case 1,
sys=mdlDerivatives(t,x,u);
case 3,
    sys=mdlOutputs(t,x,u);
case {2, 4, 9 }
    sys = [];
otherwise
    error(['Unhandled flag = ',num2str(flag)]);
end

function [sys,x0,str,ts]=mdlInitializeSizes
sizes = simsizes;
sizes.NumContStates  = 4;
sizes.NumDiscStates  = 0;
sizes.NumOutputs     = 4;
sizes.NumInputs      = 2;
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 0;
sys=simsizes(sizes);
x0=[0;0;0;0];
str=[];
ts=[];
function sys=mdlDerivatives(t,x,u)
q1=x(1);dq1=x(2);
q2=x(3);dq2=x(4);
dq=[dq1;dq2];

% The model is given by Slotine and Weiping Li(MIT 1987)
alfa=6.7;beta=3.4;
epc=3.0;eta=0;
m1=1;l1=1;
lc1=1/2;I1=1/12;
g=9.8;
e1=m1*l1*lc1-I1-m1*l1^2;
e2=g/l1;

H=[alfa+2*epc*cos(q2)+2*eta*sin(q2),beta+epc*cos(q2)+eta*sin(q2);
   beta+epc*cos(q2)+eta*sin(q2),beta];
C=[(-2*epc*sin(q2)+2*eta*cos(q2))*dq2,(-epc*sin(q2)+eta*cos(q2))*dq2;
   (epc*sin(q2)-eta*cos(q2))*dq1,0];
G=[epc*e2*cos(q1+q2)+eta*e2*sin(q1+q2)+(alfa-beta+e1)*e2*cos(q1);
   epc*e2*cos(q1+q2)+eta*e2*sin(q1+q2)];

tol(1)=u(1);
tol(2)=u(2);

ddq=inv(H)*(tol'-C*dq-G);
sys(1)=x(2);
sys(2)=ddq(1);
sys(3)=x(4);
sys(4)=ddq(2);
function sys=mdlOutputs(t,x,u)
sys(1)=x(1);
sys(2)=x(2);
sys(3)=x(3);
sys(4)=x(4);


问:
Kendo UI Editor, show HTML in Editor with encode html entities
I would like to see HTML in the Kendo UI Editor like

Hello World
```

How can i do these?

答:
My sample show on: https://dojo.telerik.com/ezOPAz/3

  $("#editor").kendoEditor({
    value: "
Hello World
",
    encoded: false,
            tools: [
                "viewHtml"
            ],
    deserialization: {
              custom: function(html) {
                 var encodedStr = html.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
                     return '&#'+i.charCodeAt(0)+';';
                  });
                return encodedStr;
              }
          }
  });```

Body:
I would like to see HTML in the Kendo UI Editor like

Hello World

How can i do these?

Body:
My sample show on: https://dojo.telerik.com/ezOPAz/3

  $("#editor").kendoEditor({
    value: "<h1>Hello World</h1>",
    encoded: false,
            tools: [
                "viewHtml"
            ],
    deserialization: {
              custom: function(html) {
                 var encodedStr = html.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
                     return '&#'+i.charCodeAt(0)+';';
                  });
                return encodedStr;
              }
          }
  });


问:
Unit Testing RESTapi with Moq Object of type String.String can not be converted to BaseObjectDto
I am trying to create a unit test of the RESTApi but I am getting an error when I attempt to call the .Get{id} method from the controller.

(The controller is mocked because it is abstract)

I receive the error (in title) when  I get to the last line of the test.

(I have tried Asserts and .Verify()'s but i dont reach them because I error out before I reach them)

I feel like I am missing something small, but then again this is my first time with Moq.

```<code>    protected CustomActionModelController(IModelProvider<TModel> provider, IModelMapper mapper)
    {
        _mapper = mapper;
        _provider = provider;
        _customActions = new Dictionary<string, Func<string, object, object>>();

        InitializeCustomActions();
    }

    protected abstract void InitializeCustomActions();

    [HttpGet("{id}")]
    [Produces(DefaultContentType)]
    public virtual TDto Get([FromRoute]string Id)
    {
        return ToDto(_provider.Get(Id));
    }

    [TestMethod]
    public void GetWithIdParameterReturnsSingleObject()
    {
        var provider = new Mock<IModelProvider<BaseDomainModel>>();
        var mapper = new Mock<IModelMapper>();
        var services = new Mock<IServiceCollection>();
        var builder = new AutofacBuilder();
        builder.RegisterType<IModelProvider<BaseDomainModel>, FakeDataProvider>().SingletonScope();
        var customMock = new Mock<CustomActionModelController<BaseDomainModel, BaseObjectDto>>(provider.Object, mapper.Object);
        customMock.Setup(x => x.Get(It.IsAny<string>())).Returns((BaseObjectDto s) =>  s = new BaseObjectDto("Test", "test"));
        var actual = customMock.Object.Get("1");
    }
</code>```

答:
Do not setup the method under test. Use CallBase on the Mock

```<code>var customMock = new Mock<CustomActionModelController<BaseDomainModel, BaseObjectDto>>(provider.Object, mapper.Object) {
    // Whether the base member virtual implementation
    // will be called for mocked classes if no setup is matched.
    CallBase = true
};

var actual = customMock.Object.Get("1");
</code>```

Reference Moq: Quickstart - Customizing Mock Behavior

Body:
I am trying to create a unit test of the RESTApi but I am getting an error when I attempt to call the .Get{id} method from the controller.

(The controller is mocked because it is abstract)

I receive the error (in title) when  I get to the last line of the test.

(I have tried Asserts and .Verify()'s but i dont reach them because I error out before I reach them)

I feel like I am missing something small, but then again this is my first time with Moq.

    protected CustomActionModelController(IModelProvider<TModel> provider, IModelMapper mapper)
    {
        _mapper = mapper;
        _provider = provider;
        _customActions = new Dictionary<string, Func<string, object, object>>();

        InitializeCustomActions();
    }

    protected abstract void InitializeCustomActions();

    [HttpGet("{id}")]
    [Produces(DefaultContentType)]
    public virtual TDto Get([FromRoute]string Id)
    {
        return ToDto(_provider.Get(Id));
    }

    [TestMethod]
    public void GetWithIdParameterReturnsSingleObject()
    {
        var provider = new Mock<IModelProvider<BaseDomainModel>>();
        var mapper = new Mock<IModelMapper>();
        var services = new Mock<IServiceCollection>();
        var builder = new AutofacBuilder();
        builder.RegisterType<IModelProvider<BaseDomainModel>, FakeDataProvider>().SingletonScope();
        var customMock = new Mock<CustomActionModelController<BaseDomainModel, BaseObjectDto>>(provider.Object, mapper.Object);
        customMock.Setup(x => x.Get(It.IsAny<string>())).Returns((BaseObjectDto s) =>  s = new BaseObjectDto("Test", "test"));
        var actual = customMock.Object.Get("1");
    }

Body:
Do not setup the method under test. Use CallBase on the Mock

var customMock = new Mock<CustomActionModelController<BaseDomainModel, BaseObjectDto>>(provider.Object, mapper.Object) {
    // Whether the base member virtual implementation
    // will be called for mocked classes if no setup is matched.
    CallBase = true
};

var actual = customMock.Object.Get("1");

Reference Moq: Quickstart - Customizing Mock Behavior