问:
Intent with multiple startactivity paramaters
I want a value to be passed from the first to the last activity when a button is clicked.

At the same time I want this button to bring me to the second activity. Somehow this doesn't work.

```<code>private void imagebutton1 () {
          ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
            btn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  //startActivity (new Intent(Akt1.this,Akt2.class));

                  String data1 = "data1";

                  Intent intent = new Intent (Akt1.this,Akt2.class);
                  Intent passdata_intent = new Intent(Akt1.this, Akt6.class);
                  passdata_intent.putExtra("data1",data1);

                 startActivity(passdata_intent);

              }
          });
</code>```

答:
```<code>   btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //startActivity (new Intent(Akt1.this,Akt2.class));

                String data1 = "data1";

                Intent intent = new Intent (Akt1.this,Akt2.class);
                intent.putExtra("data1",data1);
                startActivity(intent);
            }
        });
</code>```

In your Akt2.class add this code

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);

    String data1 = getIntent().getExtras().getString("data1");

    // your code

}
</code>```

Body:
I want a value to be passed from the first to the last activity when a button is clicked.

At the same time I want this button to bring me to the second activity. Somehow this doesn't work.

private void imagebutton1 () {
          ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
            btn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  //startActivity (new Intent(Akt1.this,Akt2.class));

                  String data1 = "data1";

                  Intent intent = new Intent (Akt1.this,Akt2.class);
                  Intent passdata_intent = new Intent(Akt1.this, Akt6.class);
                  passdata_intent.putExtra("data1",data1);

                 startActivity(passdata_intent);

              }
          });

Body:
   btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //startActivity (new Intent(Akt1.this,Akt2.class));

                String data1 = "data1";

                Intent intent = new Intent (Akt1.this,Akt2.class);
                intent.putExtra("data1",data1);
                startActivity(intent);
            }
        });

In your Akt2.class add this code

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

    String data1 = getIntent().getExtras().getString("data1");

    // your code

}


来源: stackexchange

问:
How would i make a custom error message in python
In a python program I am making, I want it to only take integers, and if it gets a string say "There has been an error in the system." instead of murmering sensless information the user will not understand</p>

答:
You can try this..    </p>

```<code>import ctypes
ctypes.windll.user32.MessageBoxW(None, u"CUSTOM MESSAGE", u"TITLE BAR", 0)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can try this..

import ctypes
ctypes.windll.user32.MessageBoxW(None, u"CUSTOM MESSAGE", u"TITLE BAR", 0)

ContentLicense: CC BY-SA 4.0


问:
android.content.Context.getSystemService(java.lang.String)' on a null object reference
when click  button on 'listview', I want to use Push Notification.
But there is Error..

'ListViewAdapter'

```<code> public class ListViewAdapter extends BaseAdapter{
private Context con;
public ListViewAdapter(Context con) {
        this.con = con;
        getData("http://117.17.158.240/test/GpsSender.php");
    }
....
...
 @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final int pos = position;
        final Context context = parent.getContext();

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(com.satt.mjbus.R.layout.listview_item, parent, false);

        }
 final ImageButton btn = (ImageButton)convertView.findViewById(com.satt.mjbus.R.id.button);
        btn.setTag(position);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int poss = (Integer) v.getTag();
                int check_num = 0;

                btn.setSelected(true);
                if (check_num == 0) {
                    btn.setSelected(true);
                    check_num = 1;
                } else if (check_num == 1) {
                    btn.setSelected(false);
                    check_num = 0;
                }
                NotificationManager notificationManager = (NotificationManager) con.getSystemService(con.NOTIFICATION_SERVICE);
                Intent intent1 = new Intent(con.getApplicationContext(), ListViewAdapter.class);

                Notification.Builder builder = new Notification.Builder(con.getApplicationContext());
                intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                PendingIntent pendingNotificationIntent = PendingIntent.getActivity(con, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

                builder.setSmallIcon(R.drawable.bus)
                        .setTicker("HETT")
                        .setWhen(System.currentTimeMillis())
                        .setNumber(1)
                        .setContentTitle("푸쉬 제목")
                        .setContentText("푸쉬내용")
                        .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                        .setContentIntent(pendingNotificationIntent)
                        .setAutoCancel(true)
                        .setOngoing(true);

                notificationManager.notify(1, builder.build());

            }

        });
        btn.setFocusable(false);

....
}
</code>```

And I got error is
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

plz help..

答:
Replace this line of code </p>

```<code>LayoutInflater inflater =
    (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
</code>```

<p>with </p>

```<code>LayoutInflater inflater =
    (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
</code>```

Body:
when click  button on 'listview', I want to use Push Notification.
But there is Error..

'ListViewAdapter'

 public class ListViewAdapter extends BaseAdapter{
private Context con;
public ListViewAdapter(Context con) {
        this.con = con;
        getData("http://117.17.158.240/test/GpsSender.php");
    }
....
...
 @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final int pos = position;
        final Context context = parent.getContext();

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(com.satt.mjbus.R.layout.listview_item, parent, false);

        }
 final ImageButton btn = (ImageButton)convertView.findViewById(com.satt.mjbus.R.id.button);
        btn.setTag(position);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int poss = (Integer) v.getTag();
                int check_num = 0;

                btn.setSelected(true);
                if (check_num == 0) {
                    btn.setSelected(true);
                    check_num = 1;
                } else if (check_num == 1) {
                    btn.setSelected(false);
                    check_num = 0;
                }
                NotificationManager notificationManager = (NotificationManager) con.getSystemService(con.NOTIFICATION_SERVICE);
                Intent intent1 = new Intent(con.getApplicationContext(), ListViewAdapter.class);

                Notification.Builder builder = new Notification.Builder(con.getApplicationContext());
                intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                PendingIntent pendingNotificationIntent = PendingIntent.getActivity(con, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

                builder.setSmallIcon(R.drawable.bus)
                        .setTicker("HETT")
                        .setWhen(System.currentTimeMillis())
                        .setNumber(1)
                        .setContentTitle("푸쉬 제목")
                        .setContentText("푸쉬내용")
                        .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                        .setContentIntent(pendingNotificationIntent)
                        .setAutoCancel(true)
                        .setOngoing(true);

                notificationManager.notify(1, builder.build());

            }

        });
        btn.setFocusable(false);

....
}

And I got error is
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

plz help..

Body:
Replace this line of code

LayoutInflater inflater =
    (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

with

LayoutInflater inflater =
    (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


问:
score string created with label not erasing previous score while score changes dynamically-LibGdx
In my game UI, I have a label on a box image to write score.

```<code>private void drawNoOfCoins() {
    Label.LabelStyle style = new Label.LabelStyle();
    style.font = game.font2;
    Label totalCoinLabel = new Label(coinScoreController.getTotalCoinString(), style);

    totalCoinLabel.setPosition(showcoinImage.getWidth() / 2,Constants.WORLD_HEIGHT - 2 * totalCoinLabel.getHeight());
    stage.addActor(totalCoinLabel);

    totalCoinLabel.setBounds( showcoinImage.getX(), showcoinImage.getY(),showcoinImage.getWidth(), showcoinImage.getHeight());
    totalCoinLabel.setAlignment( Align.center );
}

private void ShowCoinScoreBox() {
    showcoinImage = new Image(showScoreTexture);
    showcoinImage.setPosition(Constants.WORLD_WIDTH / 42,Constants.WORLD_HEIGHT - (showcoinImage.getHeight() * 1.5f));
    stage.addActor(showcoinImage);
}
</code>```

I am calling this method drawNoOfCoins() in render() and score is getting updated dynamically.

But every time the score changes dynamically,updated score is showing on top of the previous score.
Is this problem comes because of label or any other things?
How can I solve it?

答:
Call ShowCoinScoreBox() & drawNoOfCoins() at once from ApplicationListener's create() or from show() method of Screen Interface for initialization. You're creating new Actor on render call and adding them to the stage.

Keep reference of totalCoinLabel globally instead of local.

```<code>private Label totalCoinLabel;

private void drawNoOfCoins() {
    Label.LabelStyle style = new Label.LabelStyle();
    style.font = game.font2;
    totalCoinLabel = new Label(coinScoreController.getTotalCoinString(), style);

   ...
}
</code>```

Inside render() method update label text

```<code>totalCoinLabel.setText(coinScoreController.getTotalCoinString());
</code>```

Body:
In my game UI, I have a label on a box image to write score.

private void drawNoOfCoins() {
    Label.LabelStyle style = new Label.LabelStyle();
    style.font = game.font2;
    Label totalCoinLabel = new Label(coinScoreController.getTotalCoinString(), style);

    totalCoinLabel.setPosition(showcoinImage.getWidth() / 2,Constants.WORLD_HEIGHT - 2 * totalCoinLabel.getHeight());
    stage.addActor(totalCoinLabel);

    totalCoinLabel.setBounds( showcoinImage.getX(), showcoinImage.getY(),showcoinImage.getWidth(), showcoinImage.getHeight());
    totalCoinLabel.setAlignment( Align.center );
}

private void ShowCoinScoreBox() {
    showcoinImage = new Image(showScoreTexture);
    showcoinImage.setPosition(Constants.WORLD_WIDTH / 42,Constants.WORLD_HEIGHT - (showcoinImage.getHeight() * 1.5f));
    stage.addActor(showcoinImage);
}

I am calling this method drawNoOfCoins() in render() and score is getting updated dynamically.

But every time the score changes dynamically,updated score is showing on top of the previous score.
Is this problem comes because of label or any other things?
How can I solve it?

Body:
Call ShowCoinScoreBox() & drawNoOfCoins() at once from ApplicationListener's create() or from show() method of Screen Interface for initialization. You're creating new Actor on render call and adding them to the stage.

Keep reference of totalCoinLabel globally instead of local.

private Label totalCoinLabel;

private void drawNoOfCoins() {
    Label.LabelStyle style = new Label.LabelStyle();
    style.font = game.font2;
    totalCoinLabel = new Label(coinScoreController.getTotalCoinString(), style);

   ...
}

Inside render() method update label text

totalCoinLabel.setText(coinScoreController.getTotalCoinString());


问:
scheme for object-oriented programmers
I'm thoroughly intrigued by Scheme, and have started with some toy programming examples, and am reading through Paul Graham's On Lisp.

One thing I haven't been able to find is a book or website intended to teach Scheme to "OO people", i.e. people like myself who've done 99 % of their coding in c++/Java/Python.

I see that closures are sort of object-y, in the sense that they have local state, and offer one or more functions that have access to that state. But I don't want to learn Scheme only to port my existing habits on to it. This is why I'm learning Scheme rather than Common Lisp at the moment; I fear that CLOS might just serve as a crutch to my existing OO habits.

What would be ideal is a book or website that offers case studies of problems solved in both an OO language, and also in Scheme in a Schemey way. I suppose I would most appreciate scientific computing and/or computer graphics problems, but anything would do.

Any pedagogical leads would be much appreciated.

答: If you are starting off with Scheme, have a look at How to Design Programs. This book presents the "Schemey" approach to problem solving. I don't think there is a book that compares OO and functional solutions to the same programming problems. But there is a nice presentation that shows how dynamic languages like Scheme could provide simple solutions to problems that demand complex design patterns in statically typed OOP languages.</p>

ContentLicense: CC BY-SA 2.5

Title: scheme for object-oriented programmers


问:
angularjs expand & collapse issue
I am new in angularjs and currently i'm facing this issue.

Problem

when i clicked on any of the node, all the nodes will be expanded or collapsed.
For example : (Before clicking on the node)

After clicking on the node

Code

```<code> <div class="item">Data Visualization</div>
      <div class= "item">
           <i class="icon ion-arrow-right-b" ng-model="collapsed" ng-click="collapsed=!collapsed"><strong>  AGV Mileage Vs Timestamp</strong></i>
           <div ng-show="collapsed">

              <div id ="agvmileage">
                <div class = "horizon">
                    <canvas width="960" height="120">
                    <script src="/static/js/frontend/cubi-agv.js"></script>
                </div>
              </div>

           </div>
      </div>

      <div class= "item">
           <i class="icon ion-arrow-right-b" ng-model="collapsed" ng-click="collapsed=!collapsed"><strong>  Board Temperature Vs Timestamp</strong></i>
           <div ng-show="collapsed">

              <div id ="agvmileage">
                <div class = "horizon">
                    <canvas width="960" height="120">
                    <script src="/static/js/frontend/cubi-agv.js"></script>
                </div>
              </div>

           </div>
      </div>

      <div class= "item">
           <i class="icon ion-arrow-right-b" ng-model="collapsed" ng-click="collapsed=!collapsed"><strong>  Laser Sensor Output Vs Timestamp</strong></i>
           <div ng-show="collapsed">

              <div id ="agvmileage">
                <div class = "horizon">
                    <canvas width="960" height="120">
                    <script src="/static/js/frontend/cubi-agv.js"></script>
                </div>
              </div>

           </div>
      </div>

      <div class= "item">
           <i class="icon ion-arrow-right-b" ng-model="collapsed" ng-click="collapsed=!collapsed"><strong>  Battery Current Vs Timestamp</strong></i>
           <div ng-show="collapsed">

              <div id ="agvmileage">
                <div class = "horizon">
                    <canvas width="960" height="120">
                    <script src="/static/js/frontend/cubi-agv.js"></script>
                </div>
              </div>

           </div>
      </div>
</code>```

And if possible, how can i declare the "data visualization" as parent node and
  others as child node then perform expand and collapse.

Please enlighten me on this, thanks in advance.

答:
Each item needs to have its own separate collapsed state. For example:

Item 1

```<code><i ng-model="collapsedMileage" ng-click="collapsedMileage = !collapsedMileage">
    <strong>AGV Mileage Vs Timestamp</strong>
</i>
<div ng-show="collapsedMileage">
    <!-- the rest of your template -->
</div>
</code>```

Item 2

```<code><i ng-model="collapsedLaser" ng-click="collapsedLaser = !collapsedLaser">
    <strong>Laser Sensor Output Vs Timestamp</strong>
</i>
<div ng-show="collapsedLaser ">
    <!-- the rest of your template -->
</div>
</code>```

Item 3

```<code><i ng-model="collapsedBattery" ng-click="collapsedBattery = !collapsedBattery">
    <strong>Battery Current Vs Timestamp</strong>
</i>
<div ng-show="collapsedBattery">
    <!-- the rest of your template -->
</div>
</code>```

Title: angularjs expand & collapse issue

Body:
I am new in angularjs and currently i'm facing this issue.

Problem

when i clicked on any of the node, all the nodes will be expanded or collapsed.
For example : (Before clicking on the node)

After clicking on the node

Code

Data Visualization

             AGV Mileage Vs Timestamp

                    <canvas width="960" height="120">

             Board Temperature Vs Timestamp

                    <canvas width="960" height="120">

             Laser Sensor Output Vs Timestamp

                    <canvas width="960" height="120">

             Battery Current Vs Timestamp

                    <canvas width="960" height="120">

And if possible, how can i declare the "data visualization" as parent node and
  others as child node then perform expand and collapse.

Please enlighten me on this, thanks in advance.

Body:
Each item needs to have its own separate collapsed state. For example:

Item 1

<i ng-model="collapsedMileage" ng-click="collapsedMileage = !collapsedMileage">
    <strong>AGV Mileage Vs Timestamp</strong>
</i>
<div ng-show="collapsedMileage">
    <!-- the rest of your template -->
</div>

Item 2

<i ng-model="collapsedLaser" ng-click="collapsedLaser = !collapsedLaser">
    <strong>Laser Sensor Output Vs Timestamp</strong>
</i>
<div ng-show="collapsedLaser ">
    <!-- the rest of your template -->
</div>

Item 3

<i ng-model="collapsedBattery" ng-click="collapsedBattery = !collapsedBattery">
    <strong>Battery Current Vs Timestamp</strong>
</i>
<div ng-show="collapsedBattery">
    <!-- the rest of your template -->
</div>


问:
trying to /how to work with dashboard template SB-Admin-BS4-Angular-4
download template from
https://github.com/jyinterfly/SB-Admin-BS4-Angular-4-master

sample demo
http://rawgit.com/start-angular/SB-Admin-BS4-Angular-4/master/dist/dashboard

I found the SB-Admin-BS4-Angular-4-master template and downloaded to my local c:\drive. I want to edit the index.html page however the page is blank. and in the online demo dashboard the other webpage htmls don’t exist in the download project.

I like the look and would like to use the dashboard webpage SB-Admin-BS4-Angular-4-master

For example I downloaded the dashboard template sb-admin-bs-4. Located the index.html. The page loads with objects I can edit.
I can locate all the html pages displayed in the demo dashboard.

Have I missed something. What do I need to do to get started.
Im a developer however new to javascript and dashboards

TIA

--dd

答: The project is developed on angular 4. The pages(components) your looking for can be found on the following path project_folder/src/app and the styles can be found on the following path project_folder/src/styles/. If your not familiar with angular 4, Please go and look at angular.io site. </p>


问:
How to access session variable in asp.net mvc using a javascript variable as a key?
I want to access a Session variable in ASP.NET MVC, but using a JavaScript variable as a key.

Here is an example in the success bloc of an ajax call :

```<code>success: function (data) {
    $.each(data, function (idx, user) {

        var sessionUserId = '@Session[" ' + user.Id + ' "]'; //this doesn't seem to work

    }
</code>```

Any help would be appreciated.

Thanks.

答:
Very Simple  , try this.

```<code>var CompanyIdVal = '@Session["CompanyId"]';
</code>```

here companyIdVal is javascript variable ^ where as companyId is the key of session variable.
I hope this will help

Body:
I want to access a Session variable in ASP.NET MVC, but using a JavaScript variable as a key.

Here is an example in the success bloc of an ajax call :

success: function (data) {
    $.each(data, function (idx, user) {

        var sessionUserId = '@Session[" ' + user.Id + ' "]'; //this doesn't seem to work

    }

Any help would be appreciated.

Thanks.

Body:
Very Simple  , try this.

var CompanyIdVal = '@Session["CompanyId"]';

here companyIdVal is javascript variable ^ where as companyId is the key of session variable.
I hope this will help


问:
Mocking extension function in Kotlin
How to mock Kotlin extension function using Mockito or PowerMock in tests? Since they are resolved statically should they be tested as static method calls or as non static?</p>

答:
First of all, Mockito knows nothing Kotlin specific language constructs. In the end, Mockito will have a look into the byte code. Mockito is only able to understand what it finds there and what looks like a Java language construct.

Meaning: to be really sure, you might want to use javap to deassemble the compiled classfiles to identify the exact names/signatures of the methods you want to mock.

And obviously: when that method is static, you have to user PowerMock, or JMockit; if not, you should prefer to with Mockito.

From a java point of view, you simply avoid mocking static stuff; but of course, things get really interesting, now that different languages with different ideas/concepts come together.

Title: Mocking extension function in Kotlin


问:
Set select option 'selected', by value
I have a select field with some options in it. Now I need to select one of those options with jQuery. But how can I do that when I only know the value of the option that must be selected?

I have the following HTML:

  <select>
    <option value="val1">Val 1</option>
    <option value="val2">Val 2</option>
    <option value="val3">Val 3</option>
  </select>

```

I need to select the option with value val2. How can this be done?

Here's a demo page:
http://jsfiddle.net/9Stxb/

答:
It's better to use change() after setting select value.

```<code>$("div.id_100 select").val("val2").change();
</code>```

By doing this, the code will close to changing select by user, the explanation is included in JS Fiddle:

JS Fiddle

Title: Set select option 'selected', by value

Body:
I have a select field with some options in it. Now I need to select one of those options with jQuery. But how can I do that when I only know the value of the option that must be selected?

I have the following HTML:

  <select>
    <option value="val1">Val 1</option>
    <option value="val2">Val 2</option>
    <option value="val3">Val 3</option>
  </select>

I need to select the option with value val2. How can this be done?

Here's a demo page:
http://jsfiddle.net/9Stxb/

Body:
It's better to use change() after setting select value.

$("div.id_100 select").val("val2").change();

By doing this, the code will close to changing select by user, the explanation is included in JS Fiddle:

JS Fiddle


问:
What is the best unit testing tool for a mix of managed and unmanaged C++?
I am going to start implementing some unit tests for a codebase that is a mix of managed and unmanaged C++. Can NUnit hack it with unmanaged code? Is there a better alternative?</p>

答: NUnit will work fine with unmanaged code as long as you write the unit tests in managed C++.  The outside wrapper will be NUnit friendly and can access the unmanaged parts.</p>

OwnerDisplayName: brian

OwnerDisplayName: plinth


问:
How to quickly check if folder is empty (.NET)?
I have to check, if directory on disk is empty. It means, that it does not contain any folders/files. I know, that there is a simple method. We get array of FileSystemInfo's and check if count of elements equals to zero. Something like that:

```<code>public static bool CheckFolderEmpty(string path)
{
    if (string.IsNullOrEmpty(path))
    {
        throw new ArgumentNullException("path");
    }

    var folder = new DirectoryInfo(path);
    if (folder.Exists)
    {
        return folder.GetFileSystemInfos().Length == 0;
    }

    throw new DirectoryNotFoundException();
}
</code>```

This approach seems OK. BUT!! It is very, very bad from a perspective of performance. GetFileSystemInfos() is a very hard method. Actually, it enumerates all filesystem objects of folder, gets all their properties, creates objects, fills typed array etc. And all this just to simply check Length. That's stupid, isn't it?

I just profiled such code and determined, that ~250 calls of such method are executed in ~500ms. This is very slow and I believe, that it is possible to do it much quicker.

Any suggestions?

答:
Here is something that might help you doing it. I managed to do it in two iterations. </p>

```<code> private static IEnumerable<string> GetAllNonEmptyDirectories(string path)
   {
     var directories =
        Directory.EnumerateDirectories(path, "*.*", SearchOption.AllDirectories)
        .ToList();

     var directoryList =
     (from directory in directories
     let isEmpty = Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).Length == 0
     where !isEmpty select directory)
     .ToList();

     return directoryList.ToList();
   }
</code>```

Body:
I have to check, if directory on disk is empty. It means, that it does not contain any folders/files. I know, that there is a simple method. We get array of FileSystemInfo's and check if count of elements equals to zero. Something like that:

public static bool CheckFolderEmpty(string path)
{
    if (string.IsNullOrEmpty(path))
    {
        throw new ArgumentNullException("path");
    }

    var folder = new DirectoryInfo(path);
    if (folder.Exists)
    {
        return folder.GetFileSystemInfos().Length == 0;
    }

    throw new DirectoryNotFoundException();
}

This approach seems OK. BUT!! It is very, very bad from a perspective of performance. GetFileSystemInfos() is a very hard method. Actually, it enumerates all filesystem objects of folder, gets all their properties, creates objects, fills typed array etc. And all this just to simply check Length. That's stupid, isn't it?

I just profiled such code and determined, that ~250 calls of such method are executed in ~500ms. This is very slow and I believe, that it is possible to do it much quicker.

Any suggestions?

Body:
Here is something that might help you doing it. I managed to do it in two iterations.

 private static IEnumerable<string> GetAllNonEmptyDirectories(string path)
   {
     var directories =
        Directory.EnumerateDirectories(path, "*.*", SearchOption.AllDirectories)
        .ToList();

     var directoryList =
     (from directory in directories
     let isEmpty = Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).Length == 0
     where !isEmpty select directory)
     .ToList();

     return directoryList.ToList();
   }


问:
Javascript -> file-download Edge -> set "from" to actual site
I can download files from my server. After a lot research I found this method in javascript:

```<code>fetch("requestUrlToFile",
    {
        method: "GET",
        headers: {
            "authorization": "jwt"
        }
    })
        .then(checkStatus)
        .then(function(res){
            return res.blob();
        })
        .then(function(blob){
            var filename =  "PdfName-" + new Date().getTime() + ".pdf";
            if (typeof window.navigator.msSaveBlob !== 'undefined') { // IE
                var blob = new Blob([blob], { type: 'application/pdf' });
                window.navigator.msSaveBlob(blob, filename);
            } else {//if (typeof window.chrome !== 'undefined') { // Chrome
                var link = document.createElement('a');
                link.id = "download_" + billingId;
                link.className = "hidden";
                link.href = window.URL.createObjectURL(blob);
                link.download = filename;
                $downloads.appendChild(link);
                link.click();
                $downloads.innerHTML = "";
            }
        });
</code>```

This works in all modern browsers (IE 10+, Edge, FF, Chrome, Opera). But Safari and mobile browsers don't work.

Can you help me with it?

答:
I found a solution that works in every common browser i found here: W3Counter: Global Web Stats.

I used the Blob implementation of eligrey on github: Eligrey Blob.js as a polyfill.

Tested:

IE > 10 (Windows)

Edge (Windows)

Chrome (Windows, Android, iOS)

FireFox (Windows, Android)

Safari (Mac, iOS, Windows)

Opera (Windows)

fetch("requestUrlToFile",
{
    method: "GET",
    headers: {
        "authorization": "jwt"
    }
})
    .then(checkStatus)
    .then(function(res){
        return res.blob();
    })
    .then(function(data){
        var filename =  "PdfName-" + new Date().getTime() + ".pdf";
        var blob = new Blob([data], { type: 'application/pdf' });
        download(blob, filename);
    });

function download(blob, filename) {
  //first we need to prepend BOM for the UTF-8 text types
  if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
    blob = new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
  }
  //than we need to declare all variable to check which download we need to use
  var donwload_url = window.URL || window.webkitURL || window
      ,blob_url = download_url.createObjectURL(blob)
      ,download_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
      ,use_download_link = "download" in download_link
      ,click = function(node){ var event = new MouseEvent("click"); node.dispatchEvent(event); }
      ,is_opera = (!!view.opr && !!opr.addons) || !!view.opera || navigator.userAgent.indexOf(' OPR/') >= 0
      ,is_chrome = !!view.chrome && !!view.chrome.webstore
      ,is_safari = Object.prototype.toString.call(view.HTMLElement).indexOf('Constructor') > 0 || !is_chrome && !is_opera && view.webkitAudioContext !== undefined
      ,is_chrome_ios =/CriOS\/[\d]+/.test(navigator.userAgent)
      ,forceable_type = "application/octet-stream"
      ,type = blob.type
      ,forced_download = type === forceable_type;
  //now we can start checking which download we use
  if (typeof window === "undefined" || typeof window.navigator !== "undefined" && /MSIE [1-9]\./.test(window.navigator.userAgent)) {
      return; //IE <10 is not supported
  } else if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, filename);
  } else if(use_download_link) {
      download_link.href = blob_url;
      download_link.download = filename;
      click(save_link);
  } else if((is_chrome_ios || (forced_download && is_safari)) && window.FileReader){
      var reader = new FileReader();
      reader.onloadend = function(){
          var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
          var openWindow = window.open(url, "_blank");
          if(!openWindow) window.location.href = url;
      }
  } else {
      if(force){
          window.location.href = blob_url;
      } else {
          var openWindow = window.open(blob_url, "_blank");
          if(!openWindow) window.location.href = url;
      }
  }
}```

Body:
I can download files from my server. After a lot research I found this method in javascript:

fetch("requestUrlToFile",
    {
        method: "GET",
        headers: {
            "authorization": "jwt"
        }
    })
        .then(checkStatus)
        .then(function(res){
            return res.blob();
        })
        .then(function(blob){
            var filename =  "PdfName-" + new Date().getTime() + ".pdf";
            if (typeof window.navigator.msSaveBlob !== 'undefined') { // IE
                var blob = new Blob([blob], { type: 'application/pdf' });
                window.navigator.msSaveBlob(blob, filename);
            } else {//if (typeof window.chrome !== 'undefined') { // Chrome
                var link = document.createElement('a');
                link.id = "download_" + billingId;
                link.className = "hidden";
                link.href = window.URL.createObjectURL(blob);
                link.download = filename;
                $downloads.appendChild(link);
                link.click();
                $downloads.innerHTML = "";
            }
        });

This works in all modern browsers (IE 10+, Edge, FF, Chrome, Opera). But Safari and mobile browsers don't work.

Can you help me with it?


问:
Multiple queries with Entity Framework in C#
I am using C# and EF to work with a SQL Server database.

I need to do several queries at a time. For now I'm doing all the operations together and in the end I'm calling the DbContext.SaveChanges function to apply all the changes at once.

My problem is that if one of the queries has an error, all the queries are cancelled.

Do I need to call the DbContext.SaveChanges for every query for this?

Thanks

答:
Yes you can call the DBcontext.SaveChanges after every query to run the query successfully. If your one of the query having error so the remain work will be saved and please try to put your error query at
 the end of your execution if there are no dependency.</p>


问:
What's the difference between L1 and L2 caches in web-applications with Hibernate as ORM mechanism?
I just want some general info about standard purpose of using L1 cache and L2 cache.

I'm curious because I'm investigating the system with terracotta as 2nd level cache and I've found that it also has 1st-level cache.

答:
In JPA/Hibernate (and other similar ORM tools), the L1 cache is the transactional cache i.e. the entities stored from when you open a transaction to when you close it. This is almost never a shared cache (other threads can't make use of it). In JPA, this would usually be held by the EntityManager.

The L2 cache is a full (typically) shared cache. If you have multiple threads/queries pulling in data, then they can make use of entities that have already been retrieved by other threads that are still live in the cache. In JPA, this would usually be held by the EntityManagerFactory.


问:
Even with Nuget.exe 4.1.0 - Serilog already has a dependency defined for 'Microsoft.CSharp'
I know there's an answer for this question from 2016 but it's not working today. I have VS2013 with the latest CU installed.

My Nuget package source settings:

I want to install the nu-get package "Serilog.Sinks.MSSqlServer". First, I ensure nuget is up to date by navigating to the ".nuget" folder of the solution's folder and running "nuget update -self":

Unfortunately, I still get the error when trying to add the package:

If I try to update nuget from the "Extensions and Updates" page of VS then I get a 403 error as shown below:

The 403 does suggest a proxy issue but other packages can be installed to the same dev box ok. I just installed "Apache log4net" from the Manage NuGet Packages window - no problem

Any ideas of a work-around for this please?

答:
This might be related to the fact that you now (with the new NuGet CLI tool version) need to use the new NuGet API.

from nuget.org

NuGet feed v3 (VS 2015 and later / NuGet v3.x and above): https://api.nuget.org/v3/index.json
  NuGet feed v2 (VS 2013 and earlier / NuGet 2.x): https://www.nuget.org/api/v2

You can check (and edit) your NuGet Package Sources under Tools, Options, NuGet Package Manager, Package Sources.

@Rob Bowman, in response to your comment and looking at the screenshot of your Available package sources, try edit your default nuget.org to https://api.nuget.org/v3/index.json or add a new source and make sure they're both enabled. Maybe that'll do the trick.

Update: maybe manually updating the NuGet Package Manager (since updating it through Extensions and Updates is not working) solves the problem. NuGet Package Manager for Visual Studio 2013.
Going to Visual Studio menu Help, About should display the currently installed version of this extension (and others).


问:
How To Get Hidden TD Value when i click on a TR
im trying to make a task manger based on web system that can monitor tasks at work , im using html and php .
im trying to show all the tasks in table and when i click on a task (row) i want to get a hidden td value (id of task) and send it as arg to another page for more information about the task .
i searched the web how can i do that , but i didnt realy understand how to do it with my table .
here is my table code

```<code>                   <table id="thickets_show">
                    <tr id="show_ticket_table_header">
                        <td>Work Week</td>
                        <td>Task Submited Date</td>
                        <td>Task Submited Time</td>
                        <td>Task</td>
                        <td>Project</td>
                        <td>Task Owner</td>
                        <td>Task Assigend to</td>
                        <td>Priority</td>
                        <td>Status</td>
                        <td>Task Total Work Time</td>
                        <td>Task Due Date</td>
                        <td>Task Finish Date</td>
                        <td>Team</td>
                    </tr>';
                    foreach ($tasks as $key => $value) {
                        if ($value['ticket_status']=="done")
                            echo '<tr id="done_ticket" >';
                        elseif ($value['ticket_priority']=="high")
                             echo '<tr id="high_ticket" class="ticket_raw">';
                        else
                            echo '<tr class="ticket_raw">';
                        echo '
                                <td>
                                    '.$value['work_week'].'
                                </td>
                                <td>
                                    '.$value['ticket_date'].'
                                </td>
                                <td>
                                    '.$value['ticket_time_submit'].'
                                </td>
                                <td>
                                    '.$value['ticket_request'].'
                                </td>
                                <td>
                                    '.$value['ticket_project'].'
                                </td>
                                <td>
                                    '.$value['ticket_onwer'].'
                                </td>
                                <td>
                                    '.$value['ticket_assigned_user'].'
                                </td>
                                <td>
                                    '.$value['ticket_priority'].'
                                </td>
                                <td>
                                    '.$value['ticket_status'].'
                                </td>
                                <td>
                                    '.$value['ticket_worktime'].'
                                </td>
                                <td>
                                    '.$value['ticket_due_date'].'
                                </td>
                                <td>
                                    '.$value['ticket_finish_date'].'
                                </td>
                                <td>
                                    '.$value['team'].'
                                </td>
                                <td style="display:none;" id="ticket_id class="divOne">
                                    '.$value['id'].'
                                </td>
                              </tr>
</code>```

this is the function that im using

```<code>$(function(){
            $(".ticket_raw" ).on(\'click\',function(e){
                e.preventDefault();
                var id = $(this).attr("#ticket_id");
                alert(id);
            });
        });
</code>```

答:
$('tr').on('click',function(){
 var hidden_items = $(this).find('.td_hidden');
 $.each(hidden_items,function(k,v){
  console.log($(v).text());
 })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,body{
 height: 100%;
 margin: 0 auto;
 padding: 0px;
}
td{
 border:1px solid black;
}</code>```

   COLUMN1
   COLUMN2
   COLUMN3
   COLUMN4

   VALUE01
   VALUE02
   VALUE03
   VALUE04
   VALUE_HIDDEN_01
   VALUE_HIDDEN_02

   VALUE11
   VALUE12
   VALUE13
   VALUE14
   VALUE_HIDDEN_11
   VALUE_HIDDEN_12

```

Body:
im trying to make a task manger based on web system that can monitor tasks at work , im using html and php .
im trying to show all the tasks in table and when i click on a task (row) i want to get a hidden td value (id of task) and send it as arg to another page for more information about the task .
i searched the web how can i do that , but i didnt realy understand how to do it with my table .
here is my table code

                        Work Week
                        Task Submited Date
                        Task Submited Time
                        Task
                        Project
                        Task Owner
                        Task Assigend to
                        Priority
                        Status
                        Task Total Work Time
                        Task Due Date
                        Task Finish Date
                        Team

';
                    foreach ($tasks as $key => $value) {
                        if ($value['ticket_status']=="done")
                            echo '
';
                        elseif ($value['ticket_priority']=="high")
                             echo '
';
                        else
                            echo '
';
                        echo '

                                    '.$value['work_week'].'

                                    '.$value['ticket_date'].'

                                    '.$value['ticket_time_submit'].'

                                    '.$value['ticket_request'].'

                                    '.$value['ticket_project'].'

                                    '.$value['ticket_onwer'].'

                                    '.$value['ticket_assigned_user'].'

                                    '.$value['ticket_priority'].'

                                    '.$value['ticket_status'].'

                                    '.$value['ticket_worktime'].'

                                    '.$value['ticket_due_date'].'

                                    '.$value['ticket_finish_date'].'

                                    '.$value['team'].'

                                    '.$value['id'].'

this is the function that im using

$(function(){
            $(".ticket_raw" ).on(\'click\',function(e){
                e.preventDefault();
                var id = $(this).attr("#ticket_id");
                alert(id);
            });
        });

Body:
$('tr').on('click',function(){
 var hidden_items = $(this).find('.td_hidden');
 $.each(hidden_items,function(k,v){
  console.log($(v).text());
 })
})

html,body{
 height: 100%;
 margin: 0 auto;
 padding: 0px;
}
td{
 border:1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<body>
 <table>
  <tr>
   <td>COLUMN1</td>
   <td>COLUMN2</td>
   <td>COLUMN3</td>
   <td>COLUMN4</td>
  </tr>
  <tr>
   <td>VALUE01</td>
   <td>VALUE02</td>
   <td>VALUE03</td>
   <td>VALUE04</td>
   <td style="display:none;" class="td_hidden">VALUE_HIDDEN_01</td>
   <td style="display:none;" class="td_hidden">VALUE_HIDDEN_02</td>
  </tr>
  <tr>
   <td>VALUE11</td>
   <td>VALUE12</td>
   <td>VALUE13</td>
   <td>VALUE14</td>
   <td style="display:none;" class="td_hidden">VALUE_HIDDEN_11</td>
   <td style="display:none;" class="td_hidden">VALUE_HIDDEN_12</td>
  </tr>
 </table>
</body>


问:
PHP classes is this right
still getting used to PHP classes so a bit of "help /guidance" please

I have a class like this:

```<code>class ansa_accounturl_query {

    function __construct() {

     global $DBH;
     global $limit;
     $STH = $DBH->query("SELECT frm_url.frm_urlID,frm_url.frm_url FROM frm_url WHERE frm_url.accountID='SOMETHING' ".$limit." ");
     $STH->setFetchMode(PDO::FETCH_OBJ);
     $this->noforms = $STH->rowCount();
     while($row  = $STH->fetch()):
         $this->frm_urlID[]  = $row->frm_urlID;
         $this->frm_url[] = $row->frm_url;
     endwhile;
    }

}
</code>```

The limit comes from a PHP function - and works.

What I would really like to do is create extend classes for  the above example which gives say $this-frm_url as a function. so that on the "page" I call the class $classcall = new class(); but rather than have to go echo $classcall->frm_url[$key]; I can just call a function like this echo frm_url(); So in the example above there would be 2 extend classes one for frm_urlID and one for frm_url.

Also, in the "master class" am I right in in setting as array? i.e. $this->frm_url[] as without that I cannot seem to run a loop but the loop does seem "over" complex if you do it this way as you (well I) have to get a count of the array items then run the loop so you (again I) have a for() statement then a foreach().  Seems longwinded to me.

Thanks in adavance.

答:
First:
Please do not use globals.
If you have to use "global" there is a 90% percent chance that your design is bad.
Either pass $DBH and $limit as parameters to __construct($dbh,$limit) or define them as static propertys of ansa_accounturl_query.
If you define them as static propertys the values will still be identical for all instance of your class.

Second:
If you want to call a method without creating a instance first you can declare the methods static, too. Then you can call them like this:

```<code>classname::myMethod(parameter);
</code>```

if you allways use the same db and the same setting I would suggest you create a class with static propertys and 3 static methods.

Title: PHP classes is this right

Body:
still getting used to PHP classes so a bit of "help /guidance" please

I have a class like this:

class ansa_accounturl_query {

    function __construct() {

     global $DBH;
     global $limit;
     $STH = $DBH->query("SELECT frm_url.frm_urlID,frm_url.frm_url FROM frm_url WHERE frm_url.accountID='SOMETHING' ".$limit." ");
     $STH->setFetchMode(PDO::FETCH_OBJ);
     $this->noforms = $STH->rowCount();
     while($row  = $STH->fetch()):
         $this->frm_urlID[]  = $row->frm_urlID;
         $this->frm_url[] = $row->frm_url;
     endwhile;
    }

}

The limit comes from a PHP function - and works.

What I would really like to do is create extend classes for  the above example which gives say $this-frm_url as a function. so that on the "page" I call the class $classcall = new class(); but rather than have to go echo $classcall->frm_url[$key]; I can just call a function like this echo frm_url(); So in the example above there would be 2 extend classes one for frm_urlID and one for frm_url.

Also, in the "master class" am I right in in setting as array? i.e. $this->frm_url[] as without that I cannot seem to run a loop but the loop does seem "over" complex if you do it this way as you (well I) have to get a count of the array items then run the loop so you (again I) have a for() statement then a foreach().  Seems longwinded to me.

Thanks in adavance.

Body:
First:
Please do not use globals.
If you have to use "global" there is a 90% percent chance that your design is bad.
Either pass $DBH and $limit as parameters to __construct($dbh,$limit) or define them as static propertys of ansa_accounturl_query.
If you define them as static propertys the values will still be identical for all instance of your class.

Second:
If you want to call a method without creating a instance first you can declare the methods static, too. Then you can call them like this:

classname::myMethod(parameter);

if you allways use the same db and the same setting I would suggest you create a class with static propertys and 3 static methods.


问:
opencv error "Error: org.opencv.objdetect.CascadeClassifier.CascadeClassifier_1(Ljava/lang/String;)J"
I am using the opencv-249.jar for the image processing but when i run my program in hadoop enviroment it shows me an error.I also use System.loadlibrary(Core.NATIVE_LIBRARY_NAME) but still getting an error

```<code>Error: org.opencv.objdetect.CascadeClassifier.CascadeClassifier_1(Ljava/lang/String;)J
</code>```

Mapper class is as below

```<code>public static class DumpHibMapper
    extends Mapper<ImageHeader, FloatImage, IntWritable, Text> {

    private static Configuration conf;

    public DumpHibMapper() {}

    public void setup(Mapper<ImageHeader, FloatImage, IntWritable, Text>.Context paramMapper)
      throws IOException {
       conf = paramMapper.getConfiguration();
       System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    public void map(ImageHeader paramImageHeader, FloatImage paramFloatImage, Mapper<ImageHeader, FloatImage, IntWritable, Text>.Context paramMapper)
      throws IOException, InterruptedException {
      if (paramFloatImage != null) {
        String str1 = conf.get("local.file.path");
        CascadeClassifier localCascadeClassifier = new CascadeClassifier(str1 + "haarcascade_frontalface_default.xml");
        String str2 = UUID.randomUUID().toString();
        File localFile = new File(str1.toString() + "imwf/" + str2 + ".jpg");
        FileOutputStream localFileOutputStream = new FileOutputStream(localFile);
        JPEGImageUtil.getInstance().encodeImage(paramFloatImage, paramImageHeader, localFileOutputStream);
        Mat localMat = Highgui.imread(localFile.getAbsolutePath());
        MatOfRect localMatOfRect = new MatOfRect();
        localCascadeClassifier.detectMultiScale(localMat, localMatOfRect);
        int i = localMatOfRect.toArray().length;
        if (i == 0) {
          localFile.renameTo(new File(str1.toString() + "imwof/" + localFile.getName()));
        }
        int j = paramFloatImage.getWidth();
        int k = paramFloatImage.getHeight();
        String str3 = ByteUtils.asHex(ByteUtils.FloatArraytoByteArray(paramFloatImage.getData()));
        String str4;
        if (i > 0) {
          str4 = j + "x" + k + "\t(" + str3 + ")\t\t" + str2 + ".jpg";
          paramMapper.write(new IntWritable(1), new Text(str4));
        } else {
          str4 = j + "x" + k + "\t(" + str3 + ")\t\t" + "No face detected found " + str2 + ".jpg";
          paramMapper.write(new IntWritable(1), new Text(str4));
        }
      }
    }
  }
</code>```

答:
Add System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
in  Main Method

Body:
I am using the opencv-249.jar for the image processing but when i run my program in hadoop enviroment it shows me an error.I also use System.loadlibrary(Core.NATIVE_LIBRARY_NAME) but still getting an error

Error: org.opencv.objdetect.CascadeClassifier.CascadeClassifier_1(Ljava/lang/String;)J

Mapper class is as below

public static class DumpHibMapper
    extends Mapper<ImageHeader, FloatImage, IntWritable, Text> {

    private static Configuration conf;

    public DumpHibMapper() {}

    public void setup(Mapper<ImageHeader, FloatImage, IntWritable, Text>.Context paramMapper)
      throws IOException {
       conf = paramMapper.getConfiguration();
       System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    public void map(ImageHeader paramImageHeader, FloatImage paramFloatImage, Mapper<ImageHeader, FloatImage, IntWritable, Text>.Context paramMapper)
      throws IOException, InterruptedException {
      if (paramFloatImage != null) {
        String str1 = conf.get("local.file.path");
        CascadeClassifier localCascadeClassifier = new CascadeClassifier(str1 + "haarcascade_frontalface_default.xml");
        String str2 = UUID.randomUUID().toString();
        File localFile = new File(str1.toString() + "imwf/" + str2 + ".jpg");
        FileOutputStream localFileOutputStream = new FileOutputStream(localFile);
        JPEGImageUtil.getInstance().encodeImage(paramFloatImage, paramImageHeader, localFileOutputStream);
        Mat localMat = Highgui.imread(localFile.getAbsolutePath());
        MatOfRect localMatOfRect = new MatOfRect();
        localCascadeClassifier.detectMultiScale(localMat, localMatOfRect);
        int i = localMatOfRect.toArray().length;
        if (i == 0) {
          localFile.renameTo(new File(str1.toString() + "imwof/" + localFile.getName()));
        }
        int j = paramFloatImage.getWidth();
        int k = paramFloatImage.getHeight();
        String str3 = ByteUtils.asHex(ByteUtils.FloatArraytoByteArray(paramFloatImage.getData()));
        String str4;
        if (i > 0) {
          str4 = j + "x" + k + "\t(" + str3 + ")\t\t" + str2 + ".jpg";
          paramMapper.write(new IntWritable(1), new Text(str4));
        } else {
          str4 = j + "x" + k + "\t(" + str3 + ")\t\t" + "No face detected found " + str2 + ".jpg";
          paramMapper.write(new IntWritable(1), new Text(str4));
        }
      }
    }
  }


问:
MediaWiki extension: get sections or structured article text from WikiPage/ParserOutput
I am using the following to get a WikiPage and ParserOutput:

$parserOutput = WikiPage::factory(Title::newFromText('sometitle'))
->getParserOutput(new ParserOptions());

Then, I can see the sections in the article:

print_r($parserOutput->getSections());

But, this just gives me a section title and information about the order/TOC level.

How can I go from here to getting the text content of the section?

Alternative question: how can I get structured data from an article? That is, I want to go from an article title to an object with a map of sections to text.

答: Not sure if there is a nice way. For a hacky one, you can look at how MobileFrontend does it.</p>


问:
Lambda expression in Python doesn't work correctly
I tried to make some lambda expressions. There is no any error. But it doesn't work correctly. Following is my code.

```<code>from nltk.tokenize import word_tokenize

list1 = 'gain, archive, win, success'.split(',')
list2 = 'miss, loss, gone, give up'.split(',')

def classify(s, rls):
for (f, emotion) in rls:
  if f(s):
     return emotion
return "another"

rules = [(lambda x: (i for i, j in zip(word_tokenize(x),list2) if i == j) != [], "sad"),
         (lambda x: (a for a, b in zip(word_tokenize(x),list1) if a == b) != [], "happy"),]

print classify("I win the game", rules)
print classify("I miss you", rules)
</code>```

The output is

```<code>sad
sad
</code>```

I have no idea what is the wrong with my code. Can someone help me !

答:
Zip iterates through the lists "in parallel", so it returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. (source)

So you were trying to check if the i-th word of the sentence matches the i-th sentiment word in the least, which I guess is not what you want. Plus, as noted by @juanpa.arrivillaga, you were checking if a generator was equal to the empty list, which is always True, for the simple reason that a generator is not a list, independently from its content.

What you want is checking if any word in the sentence is in the sentiment list.

Try changing:

```<code>lambda x: (i for i, j in zip(word_tokenize(x),list2) if i == j) != []
</code>```

to:

```<code>lambda x: any(word in list2 for word in word_tokenize(x))
</code>```

So overall you define rules like this:

```<code>rules = [(lambda x: any(word in list2 for word in word_tokenize(x)), "sad"),
         (lambda x: any(word in list1 for word in word_tokenize(x)), "happy")]
</code>```

Also, there are white spaces in the words in sentiment lists that can make the comparison fail.
Redefine them as follows:

```<code>list1 = 'gain,archive,win,success'.split(',')
list2 = 'miss,loss,gone,give up'.split(',')
</code>```

Or even better use strip to remove empty spaces from beginning and end of words as general good practice when working with strings.

Body:
I tried to make some lambda expressions. There is no any error. But it doesn't work correctly. Following is my code.

from nltk.tokenize import word_tokenize

list1 = 'gain, archive, win, success'.split(',')
list2 = 'miss, loss, gone, give up'.split(',')

def classify(s, rls):
for (f, emotion) in rls:
  if f(s):
     return emotion
return "another"

rules = [(lambda x: (i for i, j in zip(word_tokenize(x),list2) if i == j) != [], "sad"),
         (lambda x: (a for a, b in zip(word_tokenize(x),list1) if a == b) != [], "happy"),]

print classify("I win the game", rules)
print classify("I miss you", rules)

The output is

sad
sad

I have no idea what is the wrong with my code. Can someone help me !

Body:
Zip iterates through the lists "in parallel", so it returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. (source)

So you were trying to check if the i-th word of the sentence matches the i-th sentiment word in the least, which I guess is not what you want. Plus, as noted by @juanpa.arrivillaga, you were checking if a generator was equal to the empty list, which is always True, for the simple reason that a generator is not a list, independently from its content.

What you want is checking if any word in the sentence is in the sentiment list.

Try changing:

lambda x: (i for i, j in zip(word_tokenize(x),list2) if i == j) != []

to:

lambda x: any(word in list2 for word in word_tokenize(x))

So overall you define rules like this:

rules = [(lambda x: any(word in list2 for word in word_tokenize(x)), "sad"),
         (lambda x: any(word in list1 for word in word_tokenize(x)), "happy")]

Also, there are white spaces in the words in sentiment lists that can make the comparison fail.
Redefine them as follows:

list1 = 'gain,archive,win,success'.split(',')
list2 = 'miss,loss,gone,give up'.split(',')

Or even better use strip to remove empty spaces from beginning and end of words as general good practice when working with strings.


问:
How to define a function inside a loop
Why is this not working ?

```<code>u = {}
for me in ['foo', 'bar']:
   def callback():
       return 'I am %s' % me
   u[me] = callback
</code>```

The output I get is:

```<code>>>> u['foo']()
'I am bar'
</code>```

It seems the callback is defined once at the latest iteration.

EDIT

As proposed by kawadhiya21, a class approach would work:

```<code>class CallbackFactory():
    def __init__(self, me):
       self.me = me

    def __call__(self):
       return 'I am %s' % self.me

u = {}
for me in ['foo', 'bar']:

   u[me] = CallbackFactory(me)
</code>```

But it is far more complicated than the former approach.

答:
All your functions are referencing the same variable me. When you try and call the function, me has the value 'bar', because that's what it was when the loop ended.

If you want me to take a different value for each definition of the function, then each function needs its own copy of the variable.

```<code>u = {}
for me in ['foo', 'bar']:
   def callback(me_copy=me):
       return 'I am %s' % me_copy
   u[me] = callback
</code>```

If you wanted, you could shorten that to:

```<code>u = {}
for me in ['foo', 'bar']:
   u[me] = lambda me_copy=me: 'I am %s'%me_copy
</code>```

or even

```<code>u = { me: (lambda me_copy=me: 'I am %s'%me_copy) for me in ('foo', 'bar') }
</code>```

Title: How to define a function inside a loop

Body:
Why is this not working ?

u = {}
for me in ['foo', 'bar']:
   def callback():
       return 'I am %s' % me
   u[me] = callback

The output I get is:

>>> u['foo']()
'I am bar'

It seems the callback is defined once at the latest iteration.

EDIT

As proposed by kawadhiya21, a class approach would work:

class CallbackFactory():
    def __init__(self, me):
       self.me = me

    def __call__(self):
       return 'I am %s' % self.me

u = {}
for me in ['foo', 'bar']:

   u[me] = CallbackFactory(me)

But it is far more complicated than the former approach.

Body:
All your functions are referencing the same variable me. When you try and call the function, me has the value 'bar', because that's what it was when the loop ended.

If you want me to take a different value for each definition of the function, then each function needs its own copy of the variable.

u = {}
for me in ['foo', 'bar']:
   def callback(me_copy=me):
       return 'I am %s' % me_copy
   u[me] = callback

If you wanted, you could shorten that to:

u = {}
for me in ['foo', 'bar']:
   u[me] = lambda me_copy=me: 'I am %s'%me_copy

or even

u = { me: (lambda me_copy=me: 'I am %s'%me_copy) for me in ('foo', 'bar') }


问:
How to set Data Model value on Custom TableView UILabel in Objective C
I am new in iOS and I am facing problem regarding to set Data Model on UIlabel

I used like this code to change

In ConnectiondidFinishLoading

```<code> AuditTextBoxarray=[[NSMutableArray alloc] init];
            for(int i=0;i<idarray.count;i++)
            {
                DataModel *model = [DataModel new];
                model.AuditTextBoxString = @"";
                [AuditTextBoxarray addObject:model];
            }
</code>```

In cellforrowatindexpath

```<code> cell.lblAuditTextBox.text=[NSString stringWithFormat:@"%@",[AuditTextBoxarray objectAtIndex:indexPath.row ]];
</code>```

On Button Click

```<code>   NSString *String=textView1.text;
   DataModel *model = [AuditTextBoxarray objectAtIndex:index];
   model.AuditTextBoxString = String;
</code>```

But I am not able to set value of data model in tableview:

How can I set Data Model value to uilabel? I am doing something wrong, but what I am not getting.

DataModel.h

```<code>@interface DataModel : NSObject
@property(nonatomic, strong)NSString *strSelected;
@property(nonatomic,strong)NSString *TextViewvalue;
@property(nonatomic,strong)NSString *RateViewValue;
@property(nonatomic,strong)NSString *Popupvalue;
@property(nonatomic,strong)NSString *SurveySelected;
@property(nonatomic,strong)NSString *AuditTextBoxString;
</code>```

DataModule.m

```<code>#import "DataModel.h"

@implementation DataModel

@end
</code>```

I used DataModule to change Button colour and set it on the table view like this

In ConnectionDidFinishLoading

```<code>    for (int i =0; i<idarray.count; i++)
    {
        DataModel *model = [DataModel new];
        model.strSelected = @"";
        [arrData addObject:model];

    }
</code>```

Button Click

```<code>sender.backgroundColor = [UIColor redColor];
DataModel *model = [arrData objectAtIndex:sender.tag];
model.strSelected = @"P";
</code>```

cellforrowatindexoath

```<code> //background color change on button
    DataModel *model = [arrData objectAtIndex:indexPath.row];
    if([model.strSelected isEqualToString:@"P"])
    {
        cell.passbtn.backgroundColor = [UIColor redColor];
    }
</code>```

Now I am trying to add text on uilabel frok data model.

答:
After you update the dataModel in ConnectiondidFinishLoading or On Button Click, Reload the tableview on main thread(if you are in a separate thread) to refresh the data on the View.
something like </p>

```<code>dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableview reloadData];
});
</code>```

Body:
I am new in iOS and I am facing problem regarding to set Data Model on UIlabel

I used like this code to change

In ConnectiondidFinishLoading

 AuditTextBoxarray=[[NSMutableArray alloc] init];
            for(int i=0;i<idarray.count;i++)
            {
                DataModel *model = [DataModel new];
                model.AuditTextBoxString = @"";
                [AuditTextBoxarray addObject:model];
            }

In cellforrowatindexpath

 cell.lblAuditTextBox.text=[NSString stringWithFormat:@"%@",[AuditTextBoxarray objectAtIndex:indexPath.row ]];

On Button Click

   NSString *String=textView1.text;
   DataModel *model = [AuditTextBoxarray objectAtIndex:index];
   model.AuditTextBoxString = String;

But I am not able to set value of data model in tableview:

How can I set Data Model value to uilabel? I am doing something wrong, but what I am not getting.

DataModel.h

@interface DataModel : NSObject
@property(nonatomic, strong)NSString *strSelected;
@property(nonatomic,strong)NSString *TextViewvalue;
@property(nonatomic,strong)NSString *RateViewValue;
@property(nonatomic,strong)NSString *Popupvalue;
@property(nonatomic,strong)NSString *SurveySelected;
@property(nonatomic,strong)NSString *AuditTextBoxString;

DataModule.m

#import "DataModel.h"

@implementation DataModel

@end

I used DataModule to change Button colour and set it on the table view like this

In ConnectionDidFinishLoading

    for (int i =0; i<idarray.count; i++)
    {
        DataModel *model = [DataModel new];
        model.strSelected = @"";
        [arrData addObject:model];

    }

Button Click

sender.backgroundColor = [UIColor redColor];
DataModel *model = [arrData objectAtIndex:sender.tag];
model.strSelected = @"P";

cellforrowatindexoath

 //background color change on button
    DataModel *model = [arrData objectAtIndex:indexPath.row];
    if([model.strSelected isEqualToString:@"P"])
    {
        cell.passbtn.backgroundColor = [UIColor redColor];
    }

Now I am trying to add text on uilabel frok data model.

Body:
After you update the dataModel in ConnectiondidFinishLoading or On Button Click, Reload the tableview on main thread(if you are in a separate thread) to refresh the data on the View.
something like

dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableview reloadData];
});


问:
How can I shrink an image in HTML whilst maintaining its sharpness?
I have an image that I use many times. In several cases I want to shrink its size, but obviously it loses sharpness when I do this in HTML.

Is there a way to fix this? The image is located elsewhere and I can’t save it locally.

Thanks

答: You cannot control the way the browser renders images when they are resized. Images will look better when being passed through Photoshop's filters (or those in another tool) upon resize.</p>


问:
Kendo UI for Angular authenticationModel
I am new in programming and I am trying to connect a Progress database using Progress Developer Studio authentication model (/WEB-INF/oeablSecurity-form-local.xml) with KENDO UI for Angular project. When I am using anonymous authentication everything is working fine, but I couldn't manage to make Form authentication with username and password. This is the code:</p>

```<code>/// <reference path="progress/progress.d.ts" />

import { Component, ViewChild, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable, BehaviorSubject } from 'rxjs/Rx';
import {
    GridComponent,
    GridDataResult,
    DataStateChangeEvent,
    // State
 } from '@progress/kendo-angular-grid';
 import {
     State,
     process
 } from '@progress/kendo-data-query';
import * as Progress from "./progress/progress";

let progress = Progress.progress;

/* Example service */
@Injectable()
export class CategoriesService extends BehaviorSubject<GridDataResult> {
    private tableName: string = 'Client';
    private jsdoPromise: Promise<Progress.progress.data.JSDO>;

    constructor(private http: Http) {
        super(null);

        const serviceURI = 'serviceURI';
        const catalogURI = 'catalogURI';

        let opts: Progress.progress.data.JSDOSessionOptions = {
            serviceURI: serviceURI,
        };
        let session = new progress.data.JSDOSession(opts);
        this.jsdoPromise = new Promise( (resolve, reject) => {
            session.login("", "").done(function (session: Progress.progress.data.JSDOSession, result: any, info: any) {
                console.log("session.login");
                session.addCatalog(catalogURI).then(() => {
                    resolve(new progress.data.JSDO('AdvClients'));
                });
            })
        })
    }
    public query(state: any): void {
        this.fetch(this.tableName, state)
            .subscribe(x => super.next(x));
    }
    private fetch(tableName: string, state: State): Observable<GridDataResult> {
        let that = this;
        let query = {
            skip: state.skip,
            top: state.take
        };
        let promise = new Promise((resolve, reject) => {
            this.jsdoPromise.then((jsdo) => {
                console.log("jsdoPromise.resolve");
                let afterFill = (jsdo: any, success: any, request: any) => {
                        jsdo.unsubscribe('AfterFill', afterFill, this);
                        if (success) {
                            let data = jsdo.getData();
                            if (query.top) {
                                let afterInvoke = (jsdo1: any, success1: any, request1: any): void => {
                                    jsdo.unsubscribe('AfterInvoke', 'count', afterInvoke, this);
                                    console.log("promise.resolve 1");
                                    resolve(<GridDataResult>{
                                        data: data,
                                        total: request1.response.numRecs
                                    });
                                };
                                jsdo.subscribe('AfterInvoke', 'count', afterInvoke, this);
                                jsdo.count(query);
                            } else {
                                console.log("promise.resolve 2");

                                resolve(<GridDataResult>{
                                    data: data,
                                    total: data.length
                                });
                            }
                        } else {
                            reject(new Error('Error while executing query'));
                        }
                    };
                jsdo.subscribe('AfterFill', afterFill, this);
                jsdo.fill(query);
            })
        });

        let result = Observable.fromPromise(promise)
            .map((ret: GridDataResult) => (<GridDataResult>{
                data: ret.data,
                total: ret.total
            }));

        return result;
    }
}
</code>```

答:
I made it.

```<code>const serviceURI = 'http://ctc-server:8810/CtcIdea';
    const catalogURI = serviceURI + '/static/CtcIdeaService1.json';
</code>```

const authenticationModel = progress.data.Session.AUTH_TYPE_FORM;

```<code>    let opts: Progress.progress.data.JSDOSessionOptions = {
        serviceURI: serviceURI,
</code>```

authenticationModel: authenticationModel

```<code>    };
</code>```

Body:
I am new in programming and I am trying to connect a Progress database using Progress Developer Studio authentication model (/WEB-INF/oeablSecurity-form-local.xml) with KENDO UI for Angular project. When I am using anonymous authentication everything is working fine, but I couldn't manage to make Form authentication with username and password. This is the code:

/// <reference path="progress/progress.d.ts" />

import { Component, ViewChild, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable, BehaviorSubject } from 'rxjs/Rx';
import {
    GridComponent,
    GridDataResult,
    DataStateChangeEvent,
    // State
 } from '@progress/kendo-angular-grid';
 import {
     State,
     process
 } from '@progress/kendo-data-query';
import * as Progress from "./progress/progress";

let progress = Progress.progress;

/* Example service */
@Injectable()
export class CategoriesService extends BehaviorSubject<GridDataResult> {
    private tableName: string = 'Client';
    private jsdoPromise: Promise<Progress.progress.data.JSDO>;

    constructor(private http: Http) {
        super(null);

        const serviceURI = 'serviceURI';
        const catalogURI = 'catalogURI';

        let opts: Progress.progress.data.JSDOSessionOptions = {
            serviceURI: serviceURI,
        };
        let session = new progress.data.JSDOSession(opts);
        this.jsdoPromise = new Promise( (resolve, reject) => {
            session.login("", "").done(function (session: Progress.progress.data.JSDOSession, result: any, info: any) {
                console.log("session.login");
                session.addCatalog(catalogURI).then(() => {
                    resolve(new progress.data.JSDO('AdvClients'));
                });
            })
        })
    }
    public query(state: any): void {
        this.fetch(this.tableName, state)
            .subscribe(x => super.next(x));
    }
    private fetch(tableName: string, state: State): Observable<GridDataResult> {
        let that = this;
        let query = {
            skip: state.skip,
            top: state.take
        };
        let promise = new Promise((resolve, reject) => {
            this.jsdoPromise.then((jsdo) => {
                console.log("jsdoPromise.resolve");
                let afterFill = (jsdo: any, success: any, request: any) => {
                        jsdo.unsubscribe('AfterFill', afterFill, this);
                        if (success) {
                            let data = jsdo.getData();
                            if (query.top) {
                                let afterInvoke = (jsdo1: any, success1: any, request1: any): void => {
                                    jsdo.unsubscribe('AfterInvoke', 'count', afterInvoke, this);
                                    console.log("promise.resolve 1");
                                    resolve(<GridDataResult>{
                                        data: data,
                                        total: request1.response.numRecs
                                    });
                                };
                                jsdo.subscribe('AfterInvoke', 'count', afterInvoke, this);
                                jsdo.count(query);
                            } else {
                                console.log("promise.resolve 2");

                                resolve(<GridDataResult>{
                                    data: data,
                                    total: data.length
                                });
                            }
                        } else {
                            reject(new Error('Error while executing query'));
                        }
                    };
                jsdo.subscribe('AfterFill', afterFill, this);
                jsdo.fill(query);
            })
        });

        let result = Observable.fromPromise(promise)
            .map((ret: GridDataResult) => (<GridDataResult>{
                data: ret.data,
                total: ret.total
            }));

        return result;
    }
}

Body:
I made it.

const serviceURI = 'http://ctc-server:8810/CtcIdea';
    const catalogURI = serviceURI + '/static/CtcIdeaService1.json';

const authenticationModel = progress.data.Session.AUTH_TYPE_FORM;

    let opts: Progress.progress.data.JSDOSessionOptions = {
        serviceURI: serviceURI,

authenticationModel: authenticationModel

    };


问:
Espresso how to test if Activity is finished?
I want to assert that my Acitivty that I am currently testing is finished when certain actions are performed. Unfortunately so far I am only to assert it by adding some sleep at the end of the test. Is there a better way ?</p>

```<code>import android.content.Context;
import android.os.Build;
import android.support.test.rule.ActivityTestRule;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import static org.junit.Assert.assertTrue;

@SuppressWarnings("unchecked")
@RunWith(JUnit4.class)
@LargeTest
public class MyActivityTest {

    Context context;

    @Rule
    public ActivityTestRule<MyActivity> activityRule
            = new ActivityTestRule(MyActivity.class, true, false);

    @Before
    public void setup() {
        super.setup();
        // ...
    }

    @Test
    public void finishAfterSomethingIsPerformed() throws Exception {

        activityRule.launchActivity(MyActivity.createIntent(context));

        doSomeTesting();

        activityRule.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                fireEventThatResultsInTheActivityToFinishItself();
            }
        });

        Thread.sleep(2000); // this is needed :(

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            assertTrue(activityRule.getActivity().isDestroyed());
        }

    }

}
</code>```

答:
Not sure if its a good practice but this worked for me:</p>

```<code>assertTrue(mTestRule.getActivity() == null);
</code>```

Body:
I want to assert that my Acitivty that I am currently testing is finished when certain actions are performed. Unfortunately so far I am only to assert it by adding some sleep at the end of the test. Is there a better way ?

import android.content.Context;
import android.os.Build;
import android.support.test.rule.ActivityTestRule;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import static org.junit.Assert.assertTrue;

@SuppressWarnings("unchecked")
@RunWith(JUnit4.class)
@LargeTest
public class MyActivityTest {

    Context context;

    @Rule
    public ActivityTestRule<MyActivity> activityRule
            = new ActivityTestRule(MyActivity.class, true, false);

    @Before
    public void setup() {
        super.setup();
        // ...
    }

    @Test
    public void finishAfterSomethingIsPerformed() throws Exception {

        activityRule.launchActivity(MyActivity.createIntent(context));

        doSomeTesting();

        activityRule.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                fireEventThatResultsInTheActivityToFinishItself();
            }
        });

        Thread.sleep(2000); // this is needed :(

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            assertTrue(activityRule.getActivity().isDestroyed());
        }

    }

}

Body:
Not sure if its a good practice but this worked for me:

assertTrue(mTestRule.getActivity() == null);


问:
Check if value in object is null or empty javascript
That's my problem: I could have this array of objects:

```<code>[{
    "name": "Alex",
    "code": "05422180283",
    "pIva": "05422180283",
    "subCode": null
}, {
    "name": "John",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}, {
    "name": "Billy",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}, {
    "name": "Tom",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}]
</code>```

This json is used in a form by an ng-repeat and the null field should be  filled. When the submit button is pressed the system should be check if there are still empty field. So the situation could be this one now:

```<code>[{
    "name": "Alex",
    "code": "05422180283",
    "pIva": "05422180283",
    "subCode": null
}, {
    "name": "John",
    "code": "88985556",
    "pIva": "1919ASVVV",
    "subCode": "9991VVVV"
}, {
    "name": "Billy",
    "code": "89952366555",
    "pIva": "BB588918989",
    "subCode": "ASA234434"
}, {
    "name": "Tom",
    "code": null,
    "pIva": "541198198",
    "subCode": "ACEVV9999"
}]
</code>```

As you can see there are 2 null fields. In this situation the system should be advise the user that there are 2 empty fields. (with an alert or something like that). Otherwise the user can submit the form without any problem. This is what i've done so far:

```<code>angular.forEach($scope.myArray, function(items){
                if(_.chain(items).find(_.isNull).isNull().value()) {
                    //console.log('Found one');
                    formHasEmptyFields = true;
                } else {
                    //console.log('Did not find one');
                    formHasEmptyFields = false;
                }
                if(_(items).find(_.isNull) === null) {
                    //console.log('Found one');
                    formHasEmptyFields = true;
                } else {
                    //console.log('Did not find one');
                    formHasEmptyFields = false;
                }
            });
            if(formHasEmptyFields == true) {
                alert('There are empty fields');
            } else {
                submitFunction($scope.myArray);
            }
</code>```

But it doesn't work because seems that it check only the last object. In fact, if I fill the last object in the form it doesn't show me the alert. Any idea? $scope.myArray is my array of objects of course

答:
See the MDN docs for some

```<code>const hasItemWhithFalsyCode = items.some(x => !x.code);
</code>```

You can do all sorts of stuff, like filter out the items without a code

```<code>const itemsWithTruthyCode = items.filter(x => x.code);
</code>```

To explictly check for null

```<code>const hasItemWhithNullCode = items.some(x => x.code === null);
</code>```

Body:
That's my problem: I could have this array of objects:

[{
    "name": "Alex",
    "code": "05422180283",
    "pIva": "05422180283",
    "subCode": null
}, {
    "name": "John",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}, {
    "name": "Billy",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}, {
    "name": "Tom",
    "code": null,
    "pIva": null,
    "subCode": "IT"
}]

This json is used in a form by an ng-repeat and the null field should be  filled. When the submit button is pressed the system should be check if there are still empty field. So the situation could be this one now:

[{
    "name": "Alex",
    "code": "05422180283",
    "pIva": "05422180283",
    "subCode": null
}, {
    "name": "John",
    "code": "88985556",
    "pIva": "1919ASVVV",
    "subCode": "9991VVVV"
}, {
    "name": "Billy",
    "code": "89952366555",
    "pIva": "BB588918989",
    "subCode": "ASA234434"
}, {
    "name": "Tom",
    "code": null,
    "pIva": "541198198",
    "subCode": "ACEVV9999"
}]

As you can see there are 2 null fields. In this situation the system should be advise the user that there are 2 empty fields. (with an alert or something like that). Otherwise the user can submit the form without any problem. This is what i've done so far:

angular.forEach($scope.myArray, function(items){
                if(_.chain(items).find(_.isNull).isNull().value()) {
                    //console.log('Found one');
                    formHasEmptyFields = true;
                } else {
                    //console.log('Did not find one');
                    formHasEmptyFields = false;
                }
                if(_(items).find(_.isNull) === null) {
                    //console.log('Found one');
                    formHasEmptyFields = true;
                } else {
                    //console.log('Did not find one');
                    formHasEmptyFields = false;
                }
            });
            if(formHasEmptyFields == true) {
                alert('There are empty fields');
            } else {
                submitFunction($scope.myArray);
            }

But it doesn't work because seems that it check only the last object. In fact, if I fill the last object in the form it doesn't show me the alert. Any idea? $scope.myArray is my array of objects of course

Body:
See the MDN docs for some

const hasItemWhithFalsyCode = items.some(x => !x.code);

You can do all sorts of stuff, like filter out the items without a code

const itemsWithTruthyCode = items.filter(x => x.code);

To explictly check for null

const hasItemWhithNullCode = items.some(x => x.code === null);


问:
Why does my function need parentheses?
In my framework, the functions are called without parentheses.... (See showErrors)

```<code>(function () {
  'use strict';

  angular
    .module('core')
    .directive('showErrors', showErrors);

  showErrors.$inject = ['$timeout', '$interpolate'];

  function showErrors($timeout, $interpolate) {
    var directive = {
      restrict: 'A',
      require: '^form',
      compile: compile
    };

    return directive;
</code>```

I get how it works... but when I try this, my component won't work. It only works if I change it to  .component('hotkeys', HotkeysComponent()); // adding parenthesis to HotkeysComponent

```<code>  angular
    .module('contacts.components')
    .component('hotkeys', HotkeysComponent);

  function HotkeysComponent() {
    var component = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      controller: 'AddManagerController',
      controllerAs: 'vm'
    };

    return component;
</code>```

To clarify, it won't work unless I do HotkeysComponent()

```<code>angular
  .module('contacts.components')
  .component('hotkeys', HotkeysComponent()); // why don't the other functions need ()?
</code>```

答:
There is a big difference between the two. HotkeysComponent as a parameter gives the function pointer, while HotkeysComponent() is the value HotkeysComponent returns.

An example:

```<code>testFunction(variable) {
    variable();
}

testFunction(alert);
</code>```

Here we pass alert as a function (not the return value). Now we can execute this function inside testFunction.

```<code>testFunction(variable) {
    console.log(variable);
}

sum(x, y) {
    return x + y;
}

testFunction(sum(10,20));
</code>```

Here we pass the outcome of the sum function to the function, which we can use inside our testFunction.

Title: Why does my function need parentheses?

Body:
In my framework, the functions are called without parentheses.... (See showErrors)

(function () {
  'use strict';

  angular
    .module('core')
    .directive('showErrors', showErrors);

  showErrors.$inject = ['$timeout', '$interpolate'];

  function showErrors($timeout, $interpolate) {
    var directive = {
      restrict: 'A',
      require: '^form',
      compile: compile
    };

    return directive;

I get how it works... but when I try this, my component won't work. It only works if I change it to  .component('hotkeys', HotkeysComponent()); // adding parenthesis to HotkeysComponent

  angular
    .module('contacts.components')
    .component('hotkeys', HotkeysComponent);

  function HotkeysComponent() {
    var component = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      controller: 'AddManagerController',
      controllerAs: 'vm'
    };

    return component;

To clarify, it won't work unless I do HotkeysComponent()

angular
  .module('contacts.components')
  .component('hotkeys', HotkeysComponent()); // why don't the other functions need ()?

Body:
There is a big difference between the two. HotkeysComponent as a parameter gives the function pointer, while HotkeysComponent() is the value HotkeysComponent returns.

An example:

testFunction(variable) {
    variable();
}

testFunction(alert);

Here we pass alert as a function (not the return value). Now we can execute this function inside testFunction.

testFunction(variable) {
    console.log(variable);
}

sum(x, y) {
    return x + y;
}

testFunction(sum(10,20));

Here we pass the outcome of the sum function to the function, which we can use inside our testFunction.


问:
Why does the content overflow when mu content is set to 100% height
My layout has a header and footer and in between those a content div.

When I set my content height to 100% it overflows instead of expanding the div.

* {
  margin: 0;
  padding: 0;
}

body,
html {
  height: 100%;
}

.header,
.footer {
  height: 100px;
  width: 100%;
  background-color: red;
  color: white;
}

.content {
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <h1>Heading</h1>
</div>
<div class="content">
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
  <p>Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy</p>

  <span>
                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy
            </span>
</div>
<div class="footer">
  <h1>Footer
    <h1>
</div></code>```

I already know the solution is to get rid of the 100% height.
But what I want to know is why does this happen. Shouldn't 100% height expand it's height to fit the parent?

Here is the fiddle for my code.

答:
Shouldn't 100% height expand it's height to fit the parent?

Yes, but the overflow comes because you have set a fixed height for the parent, so it can't grow.

I recommend you to not use height: 100% for the main containers like html and body, because you will want it to be flexible. You also will want for these containers to be at least the initial screen height, so use this:

```<code>html,
body {
  min-height: 100vh;
}
</code>```

With this you will have an at least 100% height containers that will grow if there is more content inside. But you can't use height: 100% for the child containers, but since usually the use case will be to have a container with a height equal to a screen percentage, you can use vh (viewport height units) to achieve this without worries about the height of the parent containers. You can create a class like this:

```<code>.full-height{
    height: 100vh;
}
</code>```

Body:
My layout has a header and footer and in between those a content div.

When I set my content height to 100% it overflows instead of expanding the div.

* {
  margin: 0;
  padding: 0;
}

body,
html {
  height: 100%;
}

.header,
.footer {
  height: 100px;
  width: 100%;
  background-color: red;
  color: white;
}

.content {
  width: 100%;
  height: 100%;
}

Heading

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque
    montesque rhoncus quis eros. Vestnunc nonummy

                Sapibulumnibh phasellus nulla egestibulum enim pretium elit tincidunt estiquam ultrisque donectetur. Sedcondimentumsan odio hendrerit proin vitae dignis nibh ac justo id congue. Amesintesque vel curabitae volutpat donec alique nasceleifendimentesque montesque rhoncus quis eros. Vestnunc nonummy

Footer

I already know the solution is to get rid of the 100% height.
But what I want to know is why does this happen. Shouldn't 100% height expand it's height to fit the parent?

Here is the fiddle for my code.

Body:
Shouldn't 100% height expand it's height to fit the parent?

Yes, but the overflow comes because you have set a fixed height for the parent, so it can't grow.

I recommend you to not use height: 100% for the main containers like html and body, because you will want it to be flexible. You also will want for these containers to be at least the initial screen height, so use this:

html,
body {
  min-height: 100vh;
}

With this you will have an at least 100% height containers that will grow if there is more content inside. But you can't use height: 100% for the child containers, but since usually the use case will be to have a container with a height equal to a screen percentage, you can use vh (viewport height units) to achieve this without worries about the height of the parent containers. You can create a class like this:

.full-height{
    height: 100vh;
}