问:
Method references to static methods or static methods which return lambdas
While developing I always have to rewrite the same lambda expression over and over again which is quite redundant and most of the cases the code formatting policy imposed by my company does not help. So I moved these common lambdas to a utility class as static methods and use them as method references. The best example I have is the Throwing merger used in conjunction with java.util.stream.Collectors.toMap(Function, Function, BinaryOperator, Supplier).
Always having to write (a,b) -> {throw new IllegalArgumentException("Some message");}; just because I want to use a custom map implementation is a lot of hassle.

//First Form

public static <E> E throwingMerger(E k1, E k2) {
    throw new IllegalArgumentException("Duplicate key " + k1 + " not allowed!");
  }

//Given a list of Car objects with proper getters
Map<String,Car> numberPlateToCar=cars.stream()//
   .collect(toMap(Car::getNumberPlate,identity(),StreamUtils::throwingMerger,LinkedHasMap::new))
```

<pre class="lang-java prettyprint-override"><code>//Second Form

  public static <E> BinaryOperator<E> throwingMerger() {
    return (k1, k2) -> {
      throw new IllegalArgumentException("Duplicate key " + k1 + " not allowed!");
    };
  }
Map<String,Car> numberPlateToCar=cars.stream()//
   .collect(toMap(Car::getNumberPlate,identity(),StreamUtils.throwingMerger(),LinkedHasMap::new))
</code>```

My questions are the following:

Which of the above is the correct approach and why?

Does either one of them offer a performance advantage or compromises performance?

答:
Neither variant is more correct than the other.

Further, there is no significant performance difference, as the relevant bytecode is even identical. In either case, there will be a method holding a throw statement in your class and an instance of a runtime generated class which will invoke that method.

Note that you can find both patterns within the JDK itself.

Function.identity() and Map.Entry.comparingByKey() are examples of factory methods containing a lambda expression

Double::sum, Objects::isNull, or Objects::nonNull are examples of method references to target methods solely existing for the purpose of being referenced that way

Generally, if there are also use cases for invoking the methods directly, it’s preferable to provide them as API methods, which may also be referenced by method references, e.g. Integer::compare, Objects::requireNonNull, or Math::max.

On the other hand, providing a factory method makes the method reference an implementation detail that you can change when there is a reason to do so. E.g., did you know that Comparator.naturalOrder() is not implemented as T::compareTo? Most of the time, you don’t need to know.

Of course, factory methods taking additional parameters can’t be replaced by method references at all; sometimes, you want the parameterless methods of a class to be symmetric to those taking parameters.

There is only a tiny difference in memory consumption. Given the current implementation, every occurrence of, e.g. Objects::isNull, will cause the creation of a runtime class and an instance, which will then be reused for the particular code location. In contrast, the implementation within Function.identity() makes only one code location, hence, one runtime class and instance. See also this answer.

But it must be emphasized that this is specific to a particular implementation, as the strategy is implemented by the JRE, further, we’re talking about a finite, rather small number of code locations and hence, objects.

By the way, these approaches are not contradicting. You could even have both:

```<code>// for calling directly
public static <E> E alwaysThrow(E k1, E k2) {
    // by the way, k1 is not the key, see https://stackoverflow.com/a/45210944/2711488
    throw new IllegalArgumentException("Duplicate key " + k1 + " not allowed!");
}
// when needing a shared BinaryOperator
public static <E> BinaryOperator<E> throwingMerger() {
    return ContainingClass::alwaysThrow;
}
</code>```

Note that there’s another point to consider; the factory method always returns a materialized instance of a particular interface, i.e. BinaryOperator. For methods that need to be bound to different interfaces, depending on the context, you need method references at these places anyway. That’s why you can write

```<code>DoubleBinaryOperator sum1 = Double::sum;
BinaryOperator<Double> sum2 = Double::sum;
BiFunction<Integer,Integer,Double> sum3 = Double::sum;
</code>```

which would not be possible if there was only a factory method returning a DoubleBinaryOperator.

Body:
While developing I always have to rewrite the same lambda expression over and over again which is quite redundant and most of the cases the code formatting policy imposed by my company does not help. So I moved these common lambdas to a utility class as static methods and use them as method references. The best example I have is the Throwing merger used in conjunction with java.util.stream.Collectors.toMap(Function, Function, BinaryOperator, Supplier).
Always having to write (a,b) -> {throw new IllegalArgumentException("Some message");}; just because I want to use a custom map implementation is a lot of hassle.

//First Form

public static <E> E throwingMerger(E k1, E k2) {
    throw new IllegalArgumentException("Duplicate key " + k1 + " not allowed!");
  }

//Given a list of Car objects with proper getters
Map<String,Car> numberPlateToCar=cars.stream()//
   .collect(toMap(Car::getNumberPlate,identity(),StreamUtils::throwingMerger,LinkedHasMap::new))

//Second Form

  public static <E> BinaryOperator<E> throwingMerger() {
    return (k1, k2) -> {
      throw new IllegalArgumentException("Duplicate key " + k1 + " not allowed!");
    };
  }
Map<String,Car> numberPlateToCar=cars.stream()//
   .collect(toMap(Car::getNumberPlate,identity(),StreamUtils.throwingMerger(),LinkedHasMap::new))

My questions are the following:

Which of the above is the correct approach and why?

Does either one of them offer a performance advantage or compromises performance?

Body:
Neither variant is more correct than the other.

Further, there is no significant performance difference, as the relevant bytecode is even identical. In either case, there will be a method holding a throw statement in your class and an instance of a runtime generated class which will invoke that method.

Note that you can find both patterns within the JDK itself.

Function.identity() and Map.Entry.comparingByKey() are examples of factory methods containing a lambda expression

Double::sum, Objects::isNull, or Objects::nonNull are examples of method references to target methods solely existing for the purpose of being referenced that way

Generally, if there are also use cases for invoking the methods directly, it’s preferable to provide them as API methods, which may also be referenced by method references, e.g. Integer::compare, Objects::requireNonNull, or Math::max.

On the other hand, providing a factory method makes the method reference an implementation detail that you can change when there is a reason to do so. E.g., did you know that Comparator.naturalOrder() is not implemented as T::compareTo? Most of the time, you don’t need to know.

Of course, factory methods taking additional parameters can’t be replaced by method references at all; sometimes, you want the parameterless methods of a class to be symmetric to those taking parameters.

There is only a tiny difference in memory consumption. Given the current implementation, every occurrence of, e.g. Objects::isNull, will cause the creation of a runtime class and an instance, which will then be reused for the particular code location. In contrast, the implementation within Function.identity() makes only one code location, hence, one runtime class and instance. See also this answer.

But it must be emphasized that this is specific to a particular implementation, as the strategy is implemented by the JRE, further, we’re talking about a finite, rather small number of code locations and hence, objects.

By the way, these approaches are not contradicting. You could even have both:

// for calling directly
public static <E> E alwaysThrow(E k1, E k2) {
    // by the way, k1 is not the key, see https://stackoverflow.com/a/45210944/2711488
    throw new IllegalArgumentException("Duplicate key " + k1 + " not allowed!");
}
// when needing a shared BinaryOperator
public static <E> BinaryOperator<E> throwingMerger() {
    return ContainingClass::alwaysThrow;
}

Note that there’s another point to consider; the factory method always returns a materialized instance of a particular interface, i.e. BinaryOperator. For methods that need to be bound to different interfaces, depending on the context, you need method references at these places anyway. That’s why you can write

DoubleBinaryOperator sum1 = Double::sum;
BinaryOperator<Double> sum2 = Double::sum;
BiFunction<Integer,Integer,Double> sum3 = Double::sum;

which would not be possible if there was only a factory method returning a DoubleBinaryOperator.


来源: stackexchange

问:
Changing CSS of a property via JQuery when toggling sidebar does not work
In my rails application, I am trying to change the margin of my div depending if sidebar is collapsed or not. I am using the .css() method of JQuery and I can't seem to make it work.

Here is my JS snippet:

```<code>document.addEventListener('turbolinks:load', function(){
  $('.openbtn').on('click', function() {
    // This toggles my sidebar
    $('.collapsed-sidebar').toggleClass('displaynone');

    // Checks if the sidebar is collapsed
    if($('.collapsed-sidebar').is(":visible")){

      // So far I have verified that it triggers this alert
      // when I collapse my sidebar
      alert("collapsed sidebar is visible");

      // Class that I am trying to change the CSS Property
      $('.signedin').css({
        'margin-right': '50px !important'
      });
    }

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

Here is my HTML structure:

```<code><body>
    <div class="ui sidebar vertical left menu visible very thin icon">
        <div class="collapsed-sidebar displaynone"> // This is the element that I toggle
             // Sidebar content here
        </div>
    </div>
    <div class="pusher">
        <div class="row content">
            <div class="signedin"> // Element that I am trying to change the property
            </div>
        </div>
    </div>
</body
</code>```

Here is the CSS of my sidebar:

```<code>.displaynone {
  display: none !important;
}

.ui.sidebar.vertical.menu {
  -webkit-transition-duration: 0.1s;
  transition-duration: 0.1s;
}
</code>```

答:
you can try this long method :D

Make a style on specific class and you can add the attribute on that div if another element is visible.

For example,

```<code>.add-margin-50px{
    margin-right: 50px;
}
</code>```

if($('.collapsed-sidebar').is(":visible")){

  $(".signedin").addClass("add-margin-50px")
  }

Hope this can help :)

ContentLicense: CC BY-SA 4.0

Body:
In my rails application, I am trying to change the margin of my div depending if sidebar is collapsed or not. I am using the .css() method of JQuery and I can't seem to make it work.

Here is my JS snippet:

document.addEventListener('turbolinks:load', function(){
  $('.openbtn').on('click', function() {
    // This toggles my sidebar
    $('.collapsed-sidebar').toggleClass('displaynone');

    // Checks if the sidebar is collapsed
    if($('.collapsed-sidebar').is(":visible")){

      // So far I have verified that it triggers this alert
      // when I collapse my sidebar
      alert("collapsed sidebar is visible");

      // Class that I am trying to change the CSS Property
      $('.signedin').css({
        'margin-right': '50px !important'
      });
    }

  });
});

Here is my HTML structure:

 // This is the element that I toggle
             // Sidebar content here

 // Element that I am trying to change the property

</body

Here is the CSS of my sidebar:

.displaynone {
  display: none !important;
}

.ui.sidebar.vertical.menu {
  -webkit-transition-duration: 0.1s;
  transition-duration: 0.1s;
}

Body:
you can try this long method :D

Make a style on specific class and you can add the attribute on that div if another element is visible.

For example,

.add-margin-50px{
    margin-right: 50px;
}

if($('.collapsed-sidebar').is(":visible")){

  $(".signedin").addClass("add-margin-50px")
  }

Hope this can help :)


问:
How to set 'wait_timeout' value in postgresql as in MySQL?
I am using Postgresql(9.6.3) and I need to set value for Wait_timeout variable. But I don't find any answers related to that or any equivalent variables that can be used in Postgresql instead of wait_timeout variable in MySQL.

```<code>     long wait_time = 0;
     ResultSet rs = null;
     try {
        Statement st = con.createStatement();
        rs = st.executeQuery("show variables like 'wait_timeout'");
        if(rs.next())
            wait_time = rs.getLong("Value");
        rs.close();
    } catch (SQLException e) {
        logger.error(e);
    }
// wait time in SQl is maintained in seconds whereas here we need
milliseconds
     return (wait_time*1000)/2;
</code>```

I am getting null value in resultSet variable after executing the query. I have found a variable called Statement_timeout but I don't know whether, it is equivalent for it or not, as it may affect all other sessions where as wait_timeout in MySQL does not. Please suggest me a better solution. Thanks in advance.

答:
MySQL implements a lot of timeouts (https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html).

MySQL has:

wait_timeout - The number of seconds the server waits for activity on a noninteractive connection before closing it. Default value 28800s = 8 hours.

Similar is "interactive_timeout" - The number of seconds the server waits for activity on an interactive connection before closing it.

PostgreSQL currently has:

"statement_timeout" - Abort any statement that takes more than the specified number of milliseconds, starting from the time the command arrives at the server from the client.

"idle_in_transaction_session_timeout" - Terminate any session with an open transaction that has been idle for longer than the specified duration in milliseconds.

(https://www.postgresql.org/docs/11/runtime-config-client.html)

See for example here - https://dba.stackexchange.com/questions/164419/is-it-possible-to-limit-timeout-on-postgres-server

To be honest I so far did not need to fiddle with these timeouts in MySQL except for "connect_timeout". So I cannot give you direct advice about it. But maybe "idle_in_transaction_session_timeout" is what you need.

Body:
I am using Postgresql(9.6.3) and I need to set value for Wait_timeout variable. But I don't find any answers related to that or any equivalent variables that can be used in Postgresql instead of wait_timeout variable in MySQL.

     long wait_time = 0;
     ResultSet rs = null;
     try {
        Statement st = con.createStatement();
        rs = st.executeQuery("show variables like 'wait_timeout'");
        if(rs.next())
            wait_time = rs.getLong("Value");
        rs.close();
    } catch (SQLException e) {
        logger.error(e);
    }
// wait time in SQl is maintained in seconds whereas here we need
milliseconds
     return (wait_time*1000)/2;

I am getting null value in resultSet variable after executing the query. I have found a variable called Statement_timeout but I don't know whether, it is equivalent for it or not, as it may affect all other sessions where as wait_timeout in MySQL does not. Please suggest me a better solution. Thanks in advance.


问:
Set An Alert on Sharepoint 2013 for multiple list and library
I have some sites with many list and library. I want to know about their changes. set alert for any list and library is very difficult and It takes a long time.
Is there any soloution ?</p>

答:
We can use create alert for all the custom list and document library using C# code or PowerShell script.

The following C# code for your reference.

```<code>SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite("http://sp2013"))
    {
        using (SPWeb web = site.OpenWeb())
        {
            foreach(SPList list in web.Lists)
            {
                if (list.BaseType == SPBaseType.GenericList || list.BaseType == SPBaseType.DocumentLibrary)
                {
                    SPUser user = web.EnsureUser(@"domain\admin");
                    SPAlert newAlert = user.Alerts.Add();
                    newAlert.Title = "My Custom Alert";
                    newAlert.AlertType = SPAlertType.List;
                    newAlert.List = list;
                    newAlert.DeliveryChannels = SPAlertDeliveryChannels.Email;
                    newAlert.EventType = SPEventType.Add;
                    newAlert.AlertFrequency = SPAlertFrequency.Immediate;
                    newAlert.Update();
                }
            }

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

Reference:

Programmatically Creating Alerts in SharePoint

Create - Edit - Find - Delete SharePoint Alerts using PowerShell

Body:
We can use create alert for all the custom list and document library using C# code or PowerShell script.

The following C# code for your reference.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite("http://sp2013"))
    {
        using (SPWeb web = site.OpenWeb())
        {
            foreach(SPList list in web.Lists)
            {
                if (list.BaseType == SPBaseType.GenericList || list.BaseType == SPBaseType.DocumentLibrary)
                {
                    SPUser user = web.EnsureUser(@"domain\admin");
                    SPAlert newAlert = user.Alerts.Add();
                    newAlert.Title = "My Custom Alert";
                    newAlert.AlertType = SPAlertType.List;
                    newAlert.List = list;
                    newAlert.DeliveryChannels = SPAlertDeliveryChannels.Email;
                    newAlert.EventType = SPEventType.Add;
                    newAlert.AlertFrequency = SPAlertFrequency.Immediate;
                    newAlert.Update();
                }
            }

        }
    }
});

Reference:

Programmatically Creating Alerts in SharePoint

Create - Edit - Find - Delete SharePoint Alerts using PowerShell


问:
In my Case Statement it always return the else value
In my query i use a case statement which always return the else value , here the query: </p>

```<code>CASE WHEN CC.IBUS_CODE = null then to_char(vDQ.COA_CAT_ID)  ELSE (vDQ.COA_CAT_ID ||' | '||CC.IBUS_CODE) end AS COA_CAT_ID

here is the output
COA_CAT_ID
4800 |
4700 | 31113
4600 | 31112
4500 | 31111
4900 |

Expected output
  COA_CAT_ID
    4800
    4700 | 31113
    4600 | 31112
    4500 | 31111
    4900
</code>```

答:
The issue with your case expression is that you are checking for a column equaling null - that isn't right. = null is something that would return null instead of true or false, meaning your case statement would always drop into the else section.

Instead, you need to use is null, e.g.:

```<code>CASE WHEN CC.IBUS_CODE is null
          then to_char(vDQ.COA_CAT_ID)
     ELSE (vDQ.COA_CAT_ID ||' | '||CC.IBUS_CODE)
END AS COA_CAT_ID
</code>```

Here's a db<>fiddle that demonstrates the issue and fix.

Body:
In my query i use a case statement which always return the else value , here the query:

CASE WHEN CC.IBUS_CODE = null then to_char(vDQ.COA_CAT_ID)  ELSE (vDQ.COA_CAT_ID ||' | '||CC.IBUS_CODE) end AS COA_CAT_ID

here is the output
COA_CAT_ID
4800 |
4700 | 31113
4600 | 31112
4500 | 31111
4900 |

Expected output
  COA_CAT_ID
    4800
    4700 | 31113
    4600 | 31112
    4500 | 31111
    4900

Body:
The issue with your case expression is that you are checking for a column equaling null - that isn't right. = null is something that would return null instead of true or false, meaning your case statement would always drop into the else section.

Instead, you need to use is null, e.g.:

CASE WHEN CC.IBUS_CODE is null
          then to_char(vDQ.COA_CAT_ID)
     ELSE (vDQ.COA_CAT_ID ||' | '||CC.IBUS_CODE)
END AS COA_CAT_ID

Here's a db<>fiddle that demonstrates the issue and fix.


问:
Multiple path.exists callbacks, how to know which file the return status is for?
The node.js built in library function for checking if a file exists asynchronously only supplies a boolean "exists" to the callback. I need to check if multiple files exists which seems problematic. How do I know for which file the response is?

Is the execution order of the callbacks guaranteed or something? Or can I supply the index to the callback somehow that I haven't thought of? Obviously my attempt here with "var k" failed. :/

```<code>var path = require('path');
var sys = require('sys');

var paths = new Array();
paths.push('file_0');
paths.push('file_1');
paths.push('file_2');

for (var i = 0; i < paths.length; i++)
{
    var k = i;
    path.exists(paths[i], function(exists) {
        var j = i;
        sys.puts("One of the files has this status: " + exists + " but which one?");
        sys.puts("j is: "+j);
        sys.puts("k is: "+k);
    });
}
</code>```

The output from a run is:

```<code>$ node test.js
One of the files has this status: false but which one?
j is: 3
k is: 2
One of the files has this status: false but which one?
j is: 3
k is: 2
One of the files has this status: false but which one?
j is: 3
k is: 2
</code>```

答: Unfortunately, Javascript hoists all variable declarations to the top of the function, which is stupid and unintuitive.  Some workarounds: JavaScript variable binding and loop</p>

ContentLicense: CC BY-SA 3.0

Body:
The node.js built in library function for checking if a file exists asynchronously only supplies a boolean "exists" to the callback. I need to check if multiple files exists which seems problematic. How do I know for which file the response is?

Is the execution order of the callbacks guaranteed or something? Or can I supply the index to the callback somehow that I haven't thought of? Obviously my attempt here with "var k" failed. :/

var path = require('path');
var sys = require('sys');

var paths = new Array();
paths.push('file_0');
paths.push('file_1');
paths.push('file_2');

for (var i = 0; i < paths.length; i++)
{
    var k = i;
    path.exists(paths[i], function(exists) {
        var j = i;
        sys.puts("One of the files has this status: " + exists + " but which one?");
        sys.puts("j is: "+j);
        sys.puts("k is: "+k);
    });
}

The output from a run is:

$ node test.js
One of the files has this status: false but which one?
j is: 3
k is: 2
One of the files has this status: false but which one?
j is: 3
k is: 2
One of the files has this status: false but which one?
j is: 3
k is: 2


问:
Warning whenever I run sourceCpp
I am having trouble running Rcpp on my PC in RStudio. Whenever I sourceCpp() a cpp file, even the Hello World file that comes with Rcpp::Rcpp.package.skeleton(), I get the warning

```<code>In normalizePath(path.expand(path), winslash, mustWork) :
  path[1]=".../anRpackage/src/../inst/include": The system cannot find the path specified
</code>```

I searched Stackoverflow and it looks like some people get this warning if they don't have Depends: Rcpp in the DESCRIPTION of their package, but I am just running sourceCpp() so the DESCRIPTION file shouldn't matter (I also changed my DESCRIPTION file).
It is just a warning so the class and functions I wrote do appear in R, but RStudio frequently crashes after I use the functions in R a few times, which may or may not be related.

My session info:

```<code>R version 3.1.3 (2015-03-09)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8 x64 (build 9200)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] Rcpp_0.12.1         RevoUtilsMath_7.4.1 RevoUtils_7.4.1     RevoMods_7.4.1      RevoScaleR_7.4.1    lattice_0.20-30     rpart_4.1-9

loaded via a namespace (and not attached):
[1] codetools_0.2-10 foreach_1.4.2    grid_3.1.3       iterators_1.0.7  tools_3.1.3
</code>```

I suppose it is possible that Revolution R is the culprit here, but I have no way of knowing. I would appreciate help, because I don't want to ignore this warning, and it's obviously not ideal for RStudio to crash repeatedly.

Kind Regards

答:
This is still relevant today, so here's my discoveries.

Rcpp can generate interfaces to and from C++ and R.
These are generated with the help of attributes specified in source-files.

From these attributes, the call to Rcpp::compileAttributes() produces the headers. Whilst at it, this also create the folder <package directory>/inst/include. If you have specified no attributes, anywhere, then compileAttributes() does not create these directories.

In order to get rid of this warning, create the <package directory>/inst/include.

For more on attributes, see Rcpp attributes vignette.

Title: Warning whenever I run sourceCpp

Body:
I am having trouble running Rcpp on my PC in RStudio. Whenever I sourceCpp() a cpp file, even the Hello World file that comes with Rcpp::Rcpp.package.skeleton(), I get the warning

In normalizePath(path.expand(path), winslash, mustWork) :
  path[1]=".../anRpackage/src/../inst/include": The system cannot find the path specified

I searched Stackoverflow and it looks like some people get this warning if they don't have Depends: Rcpp in the DESCRIPTION of their package, but I am just running sourceCpp() so the DESCRIPTION file shouldn't matter (I also changed my DESCRIPTION file).
It is just a warning so the class and functions I wrote do appear in R, but RStudio frequently crashes after I use the functions in R a few times, which may or may not be related.

My session info:

R version 3.1.3 (2015-03-09)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8 x64 (build 9200)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] Rcpp_0.12.1         RevoUtilsMath_7.4.1 RevoUtils_7.4.1     RevoMods_7.4.1      RevoScaleR_7.4.1    lattice_0.20-30     rpart_4.1-9

loaded via a namespace (and not attached):
[1] codetools_0.2-10 foreach_1.4.2    grid_3.1.3       iterators_1.0.7  tools_3.1.3

I suppose it is possible that Revolution R is the culprit here, but I have no way of knowing. I would appreciate help, because I don't want to ignore this warning, and it's obviously not ideal for RStudio to crash repeatedly.

Kind Regards


问:
'react-scripts' is not recognized as an internal or external command
I've got a maven project, within which is JavaScript project cloned as a git sub-module. So the directory structure looks like mavenapp/src/main/javascript/[npm project files]

Inside my package.json, the test looks like this:

```<code>"test": "react-scripts test --env=jsdom",
</code>```

but when I try to run npm test, it says

'react-scripts' is not recognized as an internal or external command,

Interestingly, when I clone the javascript project independently I don't get this error. I've tried re-running npm install.

NPM version: 5.5.1

Node.js version: 9.3.0

答: I have tried many of the solutions to this problem found on line, but in my case nothing worked except for reinstalling NVM for Windows (which I am using to manage multiple Node versions). In the installer, it detects installed Node versions and asks the user if they wish for NVM to control them. I said yes and NVM fixed all PATH issues. As a result, things worked as before. This issue may have multiple causes, but corrupted PATH is definitely one of them and (re)installing NVM fixes PATH.</p>

Body:
I've got a maven project, within which is JavaScript project cloned as a git sub-module. So the directory structure looks like mavenapp/src/main/javascript/[npm project files]

Inside my package.json, the test looks like this:

"test": "react-scripts test --env=jsdom",

but when I try to run npm test, it says

'react-scripts' is not recognized as an internal or external command,

Interestingly, when I clone the javascript project independently I don't get this error. I've tried re-running npm install.

NPM version: 5.5.1

Node.js version: 9.3.0


问:
how can i pass value from javascript to my php function codeigniter
Thank for help and attention.I'm apprentice

I tried this already

if i did it wrong way your can tell me anything.i learning. thanks.

checkfb() is a php function and outside script i want to call checkfb() in script function with pass javascript value.if in php looklike simply pass by value checkfb($fbFName,$fbLName,$Email); ?> but cant do cuz in script scope.i am sorry if i made your misunderstanding.

```<code>function checkLoginState() {
              FB.getLoginStatus(function(response) {
                  statusChangeCallback(response);
                    <?php $this->checkfb($fbFName,$fbLName,$Email); ?>
              });

public function checkfb($FName,$LName,$Email){

    print_r('checkfb') ; exit();
  }
  //code work for log in facebook already but i wanna add data into my database

function getCurrentUserInfo() {
<script>
              FB.api('/me?fields=first_name,last_name,email,link,gender,picture', function(userInfo) {

                  fbFName = userInfo.first_name;
                  fbLName = userInfo.last_name;
                  fbEmail = userInfo.email;
                  fbLink = userInfo.link;
                  fbGender = userInfo.gender;
                  fbpicture = userInfo.picture;
                  alert(fbID);
                  console.log(fbID);
                  console.log(fbFName);
                  console.log(fbLName);
                  console.log(fbEmail);

              });
          }
          function checkLoginState() {
              FB.getLoginStatus(function(response){
                  statusChangeCallback(response);
              });
          }
      </script>
</code>```

答: Thanks everyone.I Solved my problem.I write this script in controller that why i got a problem i just move to view and use ajax to send value to controller. :)</p>

Body:
Thank for help and attention.I'm apprentice

I tried this already

if i did it wrong way your can tell me anything.i learning. thanks.

checkfb() is a php function and outside script i want to call checkfb() in script function with pass javascript value.if in php looklike simply pass by value checkfb($fbFName,$fbLName,$Email); ?> but cant do cuz in script scope.i am sorry if i made your misunderstanding.

function checkLoginState() {
              FB.getLoginStatus(function(response) {
                  statusChangeCallback(response);
                    <?php $this->checkfb($fbFName,$fbLName,$Email); ?>
              });

public function checkfb($FName,$LName,$Email){

    print_r('checkfb') ; exit();
  }
  //code work for log in facebook already but i wanna add data into my database

function getCurrentUserInfo() {


问:
React-Native Picker TypeError: Cannot read property 'map' of undefined
I am trying to display data in picker (react-native) but the above error is displaying if I try to map the this.state.dataSource
I don't understand what seems to be the problem

I have tried almost all the same type questions on Stackoverflow but none of them seems to work

```<code> constructor() {
        super()
        this.state = {
            dataSource: [],
            PickerValueHolder: '',

        }

    }

</code>```

```<code>componentDidMount() {

  var path = RNFS.DocumentDirectoryPath + '/defects/' + 'defects'+ '.json';
  console.log(path);
  // write the file
  return RNFS.readFile(path, 'utf8')
    .then((success) => {
      newData = JSON.parse(success);
      dataSource = newData[0].results.recordset;
      dataSource = JSON.stringify(dataSource)
      console.log("datasource "+dataSource);
      this.setState({
        isLoading: false,
        dataSource
      });
    })
    .catch((err) => {
      console.log(err.message);
    });
}
</code>```

console.log("datasource "+dataSource); output

```<code>[{"success":true,"results":{"recordsets":[[{"DefectID":2,"Defect":"Damage","Description":"Crack in walls"}]],"recordset":[{"DefectID":2,"Defect":"Damage","Description":"Crack in walls"}],"output":{},"rowsAffected":[1],"returnValue":0}}]
</code>```

Picker code

```<code><Picker
  selectedValue={this.state.PickerValueHolder}
  style={{ height: 50, width: 100 }}
  onValueChange={
    (itemValue, itemIndex) => this.setState({ PickerValueHolder: itemValue })}
>
  {console.log("Picker " + this.state.dataSource)}
  {this.state.dataSource.map((item, key) => {
    <Picker.Item label={item.defect} value={item.defect} key={key} />
    }
  )}
</Picker>
</code>```

{console.log("Picker " + this.state.dataSource)} output

[{"DefectID":2,"Defect":"Damage","Description":"Crack in walls"}]

error TypeError: Cannot read property 'map' of undefined

Expected output:  the data should get inflated in picker

答:
Because RNFS.readFile(path, 'utf8') is async, the render method will most likely be called before this.state.dataSource has been populated. this.state.dataSource will be null initially, so you need to set that within your constructor.

```<code>// ...
constructor() {
  this.state = {
    dataSource: []
  }
}
</code>```

Update

Within your question, you are stringifying dataSource and assinging that within state. Strings don't have the map function within JavaScript, so remove that offending code, as per below.

```<code>  return RNFS.readFile(path, 'utf8')
    .then((success) => {
      newData = JSON.parse(success);
      dataSource = newData[0].results.recordset;
      console.log("datasource "+JSON.stringify(dataSource));
      this.setState({
        isLoading: false,
        dataSource
      });
    })
    .catch((err) => {
      console.log(err.message);
    });
</code>```

Body:
I am trying to display data in picker (react-native) but the above error is displaying if I try to map the this.state.dataSource
I don't understand what seems to be the problem

I have tried almost all the same type questions on Stackoverflow but none of them seems to work

 constructor() {
        super()
        this.state = {
            dataSource: [],
            PickerValueHolder: '',

        }

    }

componentDidMount() {

  var path = RNFS.DocumentDirectoryPath + '/defects/' + 'defects'+ '.json';
  console.log(path);
  // write the file
  return RNFS.readFile(path, 'utf8')
    .then((success) => {
      newData = JSON.parse(success);
      dataSource = newData[0].results.recordset;
      dataSource = JSON.stringify(dataSource)
      console.log("datasource "+dataSource);
      this.setState({
        isLoading: false,
        dataSource
      });
    })
    .catch((err) => {
      console.log(err.message);
    });
}

console.log("datasource "+dataSource); output

[{"success":true,"results":{"recordsets":[[{"DefectID":2,"Defect":"Damage","Description":"Crack in walls"}]],"recordset":[{"DefectID":2,"Defect":"Damage","Description":"Crack in walls"}],"output":{},"rowsAffected":[1],"returnValue":0}}]

Picker code

<Picker
  selectedValue={this.state.PickerValueHolder}
  style={{ height: 50, width: 100 }}
  onValueChange={
    (itemValue, itemIndex) => this.setState({ PickerValueHolder: itemValue })}
>
  {console.log("Picker " + this.state.dataSource)}
  {this.state.dataSource.map((item, key) => {
    <Picker.Item label={item.defect} value={item.defect} key={key} />
    }
  )}
</Picker>

{console.log("Picker " + this.state.dataSource)} output

[{"DefectID":2,"Defect":"Damage","Description":"Crack in walls"}]

error TypeError: Cannot read property 'map' of undefined

Expected output:  the data should get inflated in picker

Body:
Because RNFS.readFile(path, 'utf8') is async, the render method will most likely be called before this.state.dataSource has been populated. this.state.dataSource will be null initially, so you need to set that within your constructor.

// ...
constructor() {
  this.state = {
    dataSource: []
  }
}

Update

Within your question, you are stringifying dataSource and assinging that within state. Strings don't have the map function within JavaScript, so remove that offending code, as per below.

  return RNFS.readFile(path, 'utf8')
    .then((success) => {
      newData = JSON.parse(success);
      dataSource = newData[0].results.recordset;
      console.log("datasource "+JSON.stringify(dataSource));
      this.setState({
        isLoading: false,
        dataSource
      });
    })
    .catch((err) => {
      console.log(err.message);
    });


问:
how to resolve unusual time delay problem in webview content loading
i'm facing a unusual problem while loading a webview with new content.

Imagine a ebook reader app that im going to implement...

app that allows the user to swap(fling) the screen backward and forward to see the chapter content(nothing but reading the book).

Book that contains several chapters and i'm keeping each chapter in separate webpage

when activity begins i load the first chapter in to the webview.

i'm loading a new chapter as soon as one chapter ends (user is unaware of loading new page to web view he is just turning pages forward and backward)

after first chapter 2,3,4 ..n chapters..

As going next chapter i need to allow the user to come to previous chapter.

in some condtion imagine if user finishes chapter 1 and come to chapter 2 . but user may want refer back to previous page. Then i should load the chapter 1.

i can do that by loading previous chapter. but the content that is visible to user should not be the beginning of the chapter it should be end of the chapter. So im scrolling up to end of chapter see the end of below code. But logic not working ..

```<code> public void fling(...){
 //swap forward
    if (end_of_page==false)
       scrollBy(480);
    else if (end_of_page==true)
       webview.Load(); //load next chapter
//swap backward
       if beginning_of_chapter==true && previous_chapter_exists==true
    webview.Load();  //load previous chapter
    scrollBy(10000); //Scroll up to 10000 px so that i can get end of chapter
</code>```

But Problem here is the webview will not scrolls upto 10000px. bcoz the statement scrollBy(10000); executes before the previous chapter is loaded into webview (i.e bcoz of delay in webview loading).

How can i solve this problem?

答: Use onPageFinished to do processing after the page is loaded.</p>

Body:
i'm facing a unusual problem while loading a webview with new content.

Imagine a ebook reader app that im going to implement...

app that allows the user to swap(fling) the screen backward and forward to see the chapter content(nothing but reading the book).

Book that contains several chapters and i'm keeping each chapter in separate webpage

when activity begins i load the first chapter in to the webview.

i'm loading a new chapter as soon as one chapter ends (user is unaware of loading new page to web view he is just turning pages forward and backward)

after first chapter 2,3,4 ..n chapters..

As going next chapter i need to allow the user to come to previous chapter.

in some condtion imagine if user finishes chapter 1 and come to chapter 2 . but user may want refer back to previous page. Then i should load the chapter 1.

i can do that by loading previous chapter. but the content that is visible to user should not be the beginning of the chapter it should be end of the chapter. So im scrolling up to end of chapter see the end of below code. But logic not working ..

 public void fling(...){
 //swap forward
    if (end_of_page==false)
       scrollBy(480);
    else if (end_of_page==true)
       webview.Load(); //load next chapter
//swap backward
       if beginning_of_chapter==true && previous_chapter_exists==true
    webview.Load();  //load previous chapter
    scrollBy(10000); //Scroll up to 10000 px so that i can get end of chapter

But Problem here is the webview will not scrolls upto 10000px. bcoz the statement scrollBy(10000); executes before the previous chapter is loaded into webview (i.e bcoz of delay in webview loading).

How can i solve this problem?


问:
Use multiple QR codes simultaneously on a screen for AR with Unity3D
I am extremely new to Unity3D and AR generally.
I am trying to build an app that will contain multiple QR codes 3-7 on a screen simultaneously and show a different animation/ image on each of them.

Is that possible?

I guess I cannot use Vuforia for this purpose, because I read on its page that “A maximum of 2 Object Targets can be tracked simultaneously.”

What about AR core? I read that "ARCore tracks up to 20 images simultaneously in the user's environment off-camera and on-camera, but does not track multiple instances of the same image."

Any other suggestions?

Thank you in advance!

答:
Vuforia Documentation says it can track up to 5 Image-Targets at a time:

This is why the Vuforia SDK limits the maximum number of
  simultaneously tracked image-based targets to 5, and provides an API
  method that enables you to define a lower maximum for your app.

here

If you configure Vuforia to work with ARCore or ARKit under the hood (which it can and I would recommend, since the tracking is way more stable) you may be able to get even more, but that I don't know. Device performance will be the limiting factor for the number of Targets at that point. You can change the number of maximum targets in your vuforia settings on your ARCamera. If that doesn't work switching to ARCore without Vuforia sounds like an option, yes.

Hope that helps.


问:
how can I read xls and xlsx file in spark with java?
I want to read xls and xlsx (MS Excel) files row by row in spark like we do it for text files OR any how?

I want to use spark to increase performance for reading a large xls file say 1 GB, that's why I need spark to read the file in parts like we do for text files.

How can I read data from excel files in spark whether it is line by line or not?

I just want to read entries in the xls file anyhow using spark.

Please suggest.

Thanks!!!

答:
Here is how I done.

In maven add dependencies

```<code><dependencies>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.4.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.11</artifactId>
        <version>2.4.2</version>
    </dependency>
    <dependency>
        <groupId>com.crealytics</groupId>
        <artifactId>spark-excel_2.11</artifactId>
        <version>0.11.1</version>
    </dependency>
</dependencies>
</code>```

My main class

```<code>import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

public class ReadExcelSheets {

    public static void main(String[] args) {
        //skip logging extras
        Logger.getLogger("org").setLevel(Level.ERROR);

       //build session
        SparkSession spark = SparkSession
                .builder()
                .appName("Java Spark SQL Example")
                .config("spark.master", "local")
                .getOrCreate();

        //read excel - change file name
        Dataset<Row> df = spark.read()
                .format("com.crealytics.spark.excel")
                .option("useHeader", "true")
                //.option("dataAddress", "'Sheet1'!A1:M1470") // optional when you want to read sheets where A1 first top cell and M1470 us very bottom left of sheet.
                .load("datasets/test1.xlsx");
        //show your data
        df.show();
    }
}
</code>```

Body:
Here is how I done.

In maven add dependencies

<dependencies>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.4.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.11</artifactId>
        <version>2.4.2</version>
    </dependency>
    <dependency>
        <groupId>com.crealytics</groupId>
        <artifactId>spark-excel_2.11</artifactId>
        <version>0.11.1</version>
    </dependency>
</dependencies>

My main class

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

public class ReadExcelSheets {

    public static void main(String[] args) {
        //skip logging extras
        Logger.getLogger("org").setLevel(Level.ERROR);

       //build session
        SparkSession spark = SparkSession
                .builder()
                .appName("Java Spark SQL Example")
                .config("spark.master", "local")
                .getOrCreate();

        //read excel - change file name
        Dataset<Row> df = spark.read()
                .format("com.crealytics.spark.excel")
                .option("useHeader", "true")
                //.option("dataAddress", "'Sheet1'!A1:M1470") // optional when you want to read sheets where A1 first top cell and M1470 us very bottom left of sheet.
                .load("datasets/test1.xlsx");
        //show your data
        df.show();
    }
}


答:
This technique should work for any version</p>

```<code>SELECT (
    CASE WHEN (
             SELECT count(b.f1)
                FROM tbl b
                WHERE b.f1 = a.f1 AND a.id > b.id) > 0
             THEN '' ELSE a.f1 END) f1, a.f2
       FROM tbl a
ORDER BY a.f1, a.id asc;
</code>```

Title: Group or eliminate duplicates fields in columns

Body:
I want to group the data of the field 1 that has more data in the field 2

+-----+----------+---------------+
| id  |  field1  |    field2     |
+-----+----------+---------------+
|  1  |   ONE    |   Medicine    |
|  2  |   TWO    |   Food        |
|  3  |   TWO    |   Medicine    |
+-----+----------+---------------+

I want something like this

+-----+----------+---------------+
| id  |  field1  |    field2     |
+-----+----------+---------------+
|  1  |   ONE    |   Medicine    |
|  2  |   TWO    |   Food        |
|  3  |          |   Medicine    |
+-----+----------+---------------+

I dont know if is possible im new in mysql

thanks for your time

Body:
This technique should work for any version

SELECT (
    CASE WHEN (
             SELECT count(b.f1)
                FROM tbl b
                WHERE b.f1 = a.f1 AND a.id > b.id) > 0
             THEN '' ELSE a.f1 END) f1, a.f2
       FROM tbl a
ORDER BY a.f1, a.id asc;


问:
'react-scripts' is not recognized as an internal or external command, operable program or batch file
I am learning to react. The version I installed is 16. I installed prop-types via npm after I got an error that 'react-scripts' is not recognized as an internal or external command, operable program or batch file."

答: One of the causes of this issue is corrupted PATH and the only fix I found for that issue was to (re)install NVM and let the installer take control over the installed Node version when it asks to do so and it will fix the PATH for you. In my case that was the fix.</p>


问:
Adding a legend to a ggplot2
I try to add a legend to my ggplot2 plots but it is not working out. Also the command show.legend does not change anything

Following the answer of this question (Adding manual legend in ggplot) I tried scal_colour_manueal but it did not work out

```<code>library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

ggp <- ggplot( data = data, aes( x = Week, y = value, group = kpi) ) +
  geom_line(color=color1, show.legend = T)

ggp <- ggp +
geom_line( mapping = aes( x = Week, y = value2, group = kpi), colour = color2 , show.legend = T)

ggp <- ggp +
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))

plot(ggp)
</code>```

How can I add a legend to this plot?

答:
You shouldn't set colours outside of aes if you want them to depent on some variable of the data frame.

```<code>library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

ggp <- ggplot( data = data, aes( x = Week, y = value, col= kpi) ) +
  geom_line(show.legend = T)

ggp <- ggp +
geom_line( mapping = aes( x = Week, y = value2, col= kpi), show.legend = T)

ggp <- ggp +
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))

plot(ggp)
</code>```

Title: Adding a legend to a ggplot2

Body:
I try to add a legend to my ggplot2 plots but it is not working out. Also the command show.legend does not change anything

Following the answer of this question (Adding manual legend in ggplot) I tried scal_colour_manueal but it did not work out

library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

ggp <- ggplot( data = data, aes( x = Week, y = value, group = kpi) ) +
  geom_line(color=color1, show.legend = T)

ggp <- ggp +
geom_line( mapping = aes( x = Week, y = value2, group = kpi), colour = color2 , show.legend = T)

ggp <- ggp +
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))

plot(ggp)

How can I add a legend to this plot?

Body:
You shouldn't set colours outside of aes if you want them to depent on some variable of the data frame.

library(ggplot2)
library(data.table)

color1 = "#D30F4B"
color2 = "#66B512"

data= data.frame(Week = rep(1:5,2), kpi = rep(c("Var1", "Var2"), each=5), value = runif(10), value2 = c(runif(5), rep(NA,5))  )

ggp <- ggplot( data = data, aes( x = Week, y = value, col= kpi) ) +
  geom_line(show.legend = T)

ggp <- ggp +
geom_line( mapping = aes( x = Week, y = value2, col= kpi), show.legend = T)

ggp <- ggp +
  facet_wrap( kpi ~ . , ncol = 1) +
  scale_colour_manual(name="Legend", values=c(color1, color2))

plot(ggp)


问:
detecting a valid CSS document with PHP?
Is there a way to have PHP detect if a file is a valid CSS document?</p>

答:
I suppose you could use CURL to submit the .css file to the W3 CSS validator.  Scraping the results to determine whether the validator thinks the css in question is valid would be a bit of a challenge though, especially if you want to extract the list of errors if it's not valid.  </p>

<p>If you hammer their validator with a lot of requests, however, they could possibly block you.  Be aware of that if you do go the curl route. </p>

Body:
I suppose you could use CURL to submit the .css file to the W3 CSS validator.  Scraping the results to determine whether the validator thinks the css in question is valid would be a bit of a challenge though, especially if you want to extract the list of errors if it's not valid.

If you hammer their validator with a lot of requests, however, they could possibly block you.  Be aware of that if you do go the curl route.


答:
You can try with merge and indicator=True and query() out the both:

```<code>matching_cols=df1.columns.intersection(df2.columns).tolist() #find matching columns to merge
df1.merge(df2,on=matching_cols,how='outer',indicator=True).query("_merge!='both'")
</code>```

This will show you the uncommon data between the dataframes

```<code>             Hypervisor             IP                 Operating System  \
0  lglac125.lss.emc.com  10.247.52.125  VMware ESXi 5.5.0 build-9919047
5  lglac125.lss.emc.com                 VMware ESXi 5.5.0 build-9919047
6              DummyRow  10.247.52.129  VMware ESXi 5.5.0 build-9919047

        Domain        Memory  No. CPU  Availability (%)  Last Collection Time  \
0  lss.emc.com  524278.03125      4.0             100.0          1.558599e+09
5  lss.emc.com  524278.03125      4.0             100.0          1.558599e+09
6  lss.emc.com  524278.03125      4.0             100.0          1.558600e+09

   Arrays DummyColumn      _merge
0     NaN         NaN   left_only
5     NaN           A  right_only
6     NaN           F  right_only
</code>```

Title: How to compare all entries in columns of 2 csv files (csv1 and csv2) in python/pandas?

Body:
I have 2 CSV files:

CSV1:

"Hypervisor","IP","ABCD","Operating System","Domain","Memory","No. CPU","Availability (%)","Last Collection Time","lol"
"lglac125.lss.com","10.247.52.125","VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599031E9"
"lglac126.lss.com","10.247.52.126","VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9"
"lglac127.lss.com","10.247.52.127","VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","0.0","1.558599031E9"
"lglac128.lss.com","10.247.52.128","VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9"
"lglac129.lss.com","10.247.52.129","VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9"

CSV2:

"Hypervisor","IP","Arrays","Operating System","Domain","Memory","No. CPU","Availability (%)","Last Collection Time","DummyColumn"
"lglac125.lss.com","10.247.52.125",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599031E9","A"
"lglac126.lss.com","10.247.52.126",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9","B"
"lglac127.lss.com","10.247.52.127",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","0.0","1.558599031E9","C"
"lglac128.lss.com","10.247.52.128",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9","D"
"lglac129.lss.com","10.247.52.129",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9","E"
"DummyRow","10.247.52.129",,"VMware ESXi 5.5.0 build-9919047","lss.com","524278.03125","4.0","100.0","1.558599931E9","F"

I am trying to compare all the entries of each column (if available in csv2), with corresponding rows. If there is any entry missing or changed, i need to raise a flag. There could be possibility of add or removal of any column in both the files. So i need to first check if the column x is there in csv2 and then match the entry for the same column from csv1.

I've been struggling with this for three days now and couldn't come to a solution. I highly appreciate any help.

Body:
You can try with merge and indicator=True and query() out the both:

matching_cols=df1.columns.intersection(df2.columns).tolist() #find matching columns to merge
df1.merge(df2,on=matching_cols,how='outer',indicator=True).query("_merge!='both'")

This will show you the uncommon data between the dataframes

             Hypervisor             IP                 Operating System  \
0  lglac125.lss.emc.com  10.247.52.125  VMware ESXi 5.5.0 build-9919047
5  lglac125.lss.emc.com                 VMware ESXi 5.5.0 build-9919047
6              DummyRow  10.247.52.129  VMware ESXi 5.5.0 build-9919047

        Domain        Memory  No. CPU  Availability (%)  Last Collection Time  \
0  lss.emc.com  524278.03125      4.0             100.0          1.558599e+09
5  lss.emc.com  524278.03125      4.0             100.0          1.558599e+09
6  lss.emc.com  524278.03125      4.0             100.0          1.558600e+09

   Arrays DummyColumn      _merge
0     NaN         NaN   left_only
5     NaN           A  right_only
6     NaN           F  right_only


问:
How to create a list corresponding to each number from 2 to 100 that will contain numbers from an array that are its multiples?
Recently i came across this question and could not figure out an optimal solution for it.

Suppose we have an array of numbers of any range like 9,-3,0,4,11,2,-8,.....
We need to print numbers from 2 to 100 and corresponding to each of them we need to print a list of numbers from the array such that the number in the array is divisible by it.
Example:
Using the existing array in example,
2 -> 4,2,-8,...
3 -> -3,9,...
4 -> 4,-8,...
and like this upto 100.

I tried working out the solution by dividing each number of the array by numbers from 2 to 100 and subsequently creating the list corresponding to each of them. But that didn't seem to me an optimal solution.

I even tried grouping numbers like a number which is divisible by 8 will be divisible by 2 and 4 so we don't need to divide it again. This would reduce some operations and complexity but would in turn, require creating such groups.

Please can anyone help finding an optimal solution for this problem by reducing the need to divide each number by 2 to 100.

答:
To solve the given problem I would choose one of the two following approaches:

Version 1

Two simple nested loops in combination with the method map.computeIfAbsent

```<code>int[] myArray = {3,5,1,-7,6,34,88,2,-8,9,10,4,33};
Map<Integer,List<Integer>> version1 = new HashMap<>();
for(int i = 2; i< 100; i++){
    for(int x : myArray){
        if(x%i==0)
           version1.computeIfAbsent(i, k -> new ArrayList<>()).add(x);
    }
}
System.out.println(version1);
</code>```

Version 2

A solution only with stream operations

```<code>    Map<Integer,List<Integer>> version2 = Arrays.stream(myArray).distinct().boxed()
            .flatMap(p -> IntStream.range(2, 100).filter(i -> p%i ==0).boxed()
                    .map(l->new AbstractMap.SimpleEntry<>(l,p)))
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

    System.out.println(version2);
</code>```

There are certainly more elegant solutions or solutions that are optimal in terms of complexity. But I think the approaches here are short and easy to read.

Body:
To solve the given problem I would choose one of the two following approaches:

Version 1

Two simple nested loops in combination with the method map.computeIfAbsent

int[] myArray = {3,5,1,-7,6,34,88,2,-8,9,10,4,33};
Map<Integer,List<Integer>> version1 = new HashMap<>();
for(int i = 2; i< 100; i++){
    for(int x : myArray){
        if(x%i==0)
           version1.computeIfAbsent(i, k -> new ArrayList<>()).add(x);
    }
}
System.out.println(version1);

Version 2

A solution only with stream operations

    Map<Integer,List<Integer>> version2 = Arrays.stream(myArray).distinct().boxed()
            .flatMap(p -> IntStream.range(2, 100).filter(i -> p%i ==0).boxed()
                    .map(l->new AbstractMap.SimpleEntry<>(l,p)))
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

    System.out.println(version2);

There are certainly more elegant solutions or solutions that are optimal in terms of complexity. But I think the approaches here are short and easy to read.


问:
Reflecting Return Date & Extension Date in Excel
I am setting up a Excel for Rental of Vehicle to Keep track of Vehicle Return Date & Extension Date. I can get the table to show vehicle return but couldnt get it to show the extension date.

Tried to use Multiple If And statement.

```<code>=IF(AND($B10<>"",$C10<>""),1-SUMPRODUCT(('[Rental Current Fleet.xlsm]Rental Vehicle'!$G$7:$G$1000<=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$H$7:$H$1000>=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$C$7:$C$1000=$B10)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$D$7:$D$1000=$C10)),"")
</code>```

**Above code is working

```<code>=IF(AND($B10<>"",$C10<>""),1-SUMPRODUCT(('[Rental Current Fleet.xlsm]Rental Vehicle'!$H$7:$H$1000<=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$J$7:$J$1000>=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$C$7:$C$1000=$B10)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$D$7:$D$1000=$C10)),"")
</code>```

Cell Shows #Value!

答:
You could use a more simpler approach:

Formula C2:

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

Formula E2:

```<code>=D2-C2
</code>```

Tips for total amount due:

Formula F2:

=B2*VLOOKUP("Normal",$I$2:$J$3,2,FALSE)+E2*VLOOKUP("Extension",$I$2:$J$3,2,FALSE)

Body:
I am setting up a Excel for Rental of Vehicle to Keep track of Vehicle Return Date & Extension Date. I can get the table to show vehicle return but couldnt get it to show the extension date.

Tried to use Multiple If And statement.

=IF(AND($B10<>"",$C10<>""),1-SUMPRODUCT(('[Rental Current Fleet.xlsm]Rental Vehicle'!$G$7:$G$1000<=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$H$7:$H$1000>=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$C$7:$C$1000=$B10)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$D$7:$D$1000=$C10)),"")

**Above code is working

=IF(AND($B10<>"",$C10<>""),1-SUMPRODUCT(('[Rental Current Fleet.xlsm]Rental Vehicle'!$H$7:$H$1000<=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$J$7:$J$1000>=H$7)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$C$7:$C$1000=$B10)*('[Rental Current Fleet.xlsm]Rental Vehicle'!$D$7:$D$1000=$C10)),"")

Cell Shows #Value!

Body:
You could use a more simpler approach:

Formula C2:

=A2+B2

Formula E2:

=D2-C2

Tips for total amount due:

Formula F2:

=B2*VLOOKUP("Normal",$I$2:$J$3,2,FALSE)+E2*VLOOKUP("Extension",$I$2:$J$3,2,FALSE)


问:
Set slider/swiper to autoplay from 1st slide
Created a slider/swiper with idangero api. When I set the autoplay to the slider, the slider immediately jumps to slide 2, then again to slide 1, continuing to slide 3.

I tried to include setInitialSlide: 0, but it didn't make any difference.

var mySwiper = new Swiper('.swiper-container', {
    speed: 500,
    loop: true,
    setInitialSlide: 0,
    spaceBetween: 0,
});

var mySwiper = document.querySelector('.swiper-container').swiper

mySwiper.slideNext();

var mySwiper = new Swiper('.swiper-container', {
  autoplay: {
    delay: 1000,
  },
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.swiper-container {
width: 200px;
height: 200px;
position: absolute;
}

.swiper-slide {
  width: 200px;
  height: 200px;
  background: lightblue;
}</code>```

Slide 1

Slide 2

Slide 3

```

I would like the slider to autoplay from the 1st slide, and after the last slide slider should continue looping from the 1st slide.

答:
Try to used this I hope it will help you

```<code>var swiper = new Swiper('.swiper-container', {
    effect: 'coverflow',
    grabCursor: true,
    centeredSlides: true,
    slidesPerView: 'auto',
    loop: true,
    coverflowEffect: {
        rotate: 50,
        stretch: 0,
        depth: 100,
        modifier: 1,
        slideShadows: true,
    },
    autoplay: {
        delay: 2000,
    },
});
</code>```

Body:
Created a slider/swiper with idangero api. When I set the autoplay to the slider, the slider immediately jumps to slide 2, then again to slide 1, continuing to slide 3.

I tried to include setInitialSlide: 0, but it didn't make any difference.

var mySwiper = new Swiper('.swiper-container', {
    speed: 500,
    loop: true,
    setInitialSlide: 0,
    spaceBetween: 0,
});

var mySwiper = document.querySelector('.swiper-container').swiper

mySwiper.slideNext();

var mySwiper = new Swiper('.swiper-container', {
  autoplay: {
    delay: 1000,
  },
});

.swiper-container {
width: 200px;
height: 200px;
position: absolute;
}

.swiper-slide {
  width: 200px;
  height: 200px;
  background: lightblue;
}

Slide 1

Slide 2

Slide 3

I would like the slider to autoplay from the 1st slide, and after the last slide slider should continue looping from the 1st slide.

Body:
Try to used this I hope it will help you

var swiper = new Swiper('.swiper-container', {
    effect: 'coverflow',
    grabCursor: true,
    centeredSlides: true,
    slidesPerView: 'auto',
    loop: true,
    coverflowEffect: {
        rotate: 50,
        stretch: 0,
        depth: 100,
        modifier: 1,
        slideShadows: true,
    },
    autoplay: {
        delay: 2000,
    },
});


问:
Typeorm error with unique:true in entity instance
this is my error:
QueryFailedError: ER_BLOB_KEY_WITHOUT_LENGTH: BLOB/TEXT column 'username' used in key specification without a key length

if I remove unique:true anything goes fine!

import   {
      Entity,
      PrimaryGeneratedColumn,
      CreateDateColumn,
      Column,enter code here
      BeforeInsert,
    } from 'typeorm';

```<code>import * as bcrypt from 'bcryptjs';
import * as jwt from 'jsonwebtoken';
import { response } from 'express';
//utilizzo Entity da typeorm e creo la tabella User Entity('User)
@Entity('user')
export class UserEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @CreateDateColumn()
  created: Date;

  @Column({
    type: 'text',
    unique: true,
  })
  username: string;

  @Column('text')
  password: string;

  @BeforeInsert()
  async hashPassword() {
    this.password = await bcrypt.hash(this.password, 10);
  }
  toResponseObject(showToken:boolean = true) {
    const { id, created, username,token } = this;

    const responseObject =  { id, created, username,token };
    if(showToken){
      responseObject.token = token
    }
    return responseObject;
  }

  async comparePassword(attempt: string) {
    return await bcrypt.compare(attempt, this.password);
  }

  private get token() {
    const { id, username } = this;
    return jwt.sign({
      id,
      username,
    },process.env.SECRET,{expiresIn:"7d"})
  }
}
</code>```

答:
If I understand it correctly, you cannot use unique in combination with a text column.
For me, the solution was to switch the type to varchar.</p>

Body:
this is my error:
QueryFailedError: ER_BLOB_KEY_WITHOUT_LENGTH: BLOB/TEXT column 'username' used in key specification without a key length

if I remove unique:true anything goes fine!

import   {
      Entity,
      PrimaryGeneratedColumn,
      CreateDateColumn,
      Column,enter code here
      BeforeInsert,
    } from 'typeorm';

import * as bcrypt from 'bcryptjs';
import * as jwt from 'jsonwebtoken';
import { response } from 'express';
//utilizzo Entity da typeorm e creo la tabella User Entity('User)
@Entity('user')
export class UserEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @CreateDateColumn()
  created: Date;

  @Column({
    type: 'text',
    unique: true,
  })
  username: string;

  @Column('text')
  password: string;

  @BeforeInsert()
  async hashPassword() {
    this.password = await bcrypt.hash(this.password, 10);
  }
  toResponseObject(showToken:boolean = true) {
    const { id, created, username,token } = this;

    const responseObject =  { id, created, username,token };
    if(showToken){
      responseObject.token = token
    }
    return responseObject;
  }

  async comparePassword(attempt: string) {
    return await bcrypt.compare(attempt, this.password);
  }

  private get token() {
    const { id, username } = this;
    return jwt.sign({
      id,
      username,
    },process.env.SECRET,{expiresIn:"7d"})
  }
}


问:
Subscribing multiple handlers to DOM Events with jQuery
I am attempting to subscribe events by the CSS class.  I have two handlers, defined as follows:

```<code>$(document).ready(function() {
    $('.refresh-cart').click(
        function(e) {
            alert('refreshing');
        });

    $('form.ajax').submit(
        function(e) {
            e.preventDefault();
            $.post(
                this.action,
                $(this).serialize(),
                function(data, textStatus, jqXHR) { alert('post'); },
                'text');
        }
    );
});
</code>```

When these handlers overlap, I am not getting the expected functionality.

This code works correctly, by alerting 'post' and submitting an ajax request.

```<code> <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" />
 </form>
</code>```

This code works correctly, by alerting 'refreshing'

```<code>  <div class="refresh-cart">Refresh Widget</div>
</code>```

However, when these overlap (such as in the following example), only the 'refresh-cart' subscriber fires.

```<code> <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" class="refresh-cart" />
 </form>
</code>```

What am I doing wrong and how can I make both handlers fire?

答:
It works just fine for me..

You do have to close the first alert box, though, before the second can be shown..

your code live at http://jsfiddle.net/gaby/W3zC4/

Body:
I am attempting to subscribe events by the CSS class.  I have two handlers, defined as follows:

$(document).ready(function() {
    $('.refresh-cart').click(
        function(e) {
            alert('refreshing');
        });

    $('form.ajax').submit(
        function(e) {
            e.preventDefault();
            $.post(
                this.action,
                $(this).serialize(),
                function(data, textStatus, jqXHR) { alert('post'); },
                'text');
        }
    );
});

When these handlers overlap, I am not getting the expected functionality.

This code works correctly, by alerting 'post' and submitting an ajax request.

 <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" />
 </form>

This code works correctly, by alerting 'refreshing'

Refresh Widget

However, when these overlap (such as in the following example), only the 'refresh-cart' subscriber fires.

 <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" class="refresh-cart" />
 </form>

What am I doing wrong and how can I make both handlers fire?


问:
How does this javascript import of kurento-utils get recognized?
On this line:
https://github.com/Kurento/kurento-tutorial-java/blob/master/kurento-player/src/main/resources/static/index.html#L24

This javascript file is imported. However, there is no file called "kurento-utils.js" in this package. So how does this work? Is this some magic of bower?

Where does that file come from and how can I get it to be accessible in my code?

When I run this code, I get:

(index):281 Uncaught ReferenceError: kurentoUtils is not defined

Thank you!

答:
Where is no magic:

```<code> git clone https://github.com/Kurento/kurento-utils-js
 cd kurento-utils-js-master
 npm install
</code>```

To build the browser version of the library you'll only need to exec the grunt task runner and they will be generated on the dist folder. Alternatively, if you don't have it globally installed, you can run a local copy by executing:

node_modules/.bin/grunt

(for windows i run grunt.cmd)

```<code> cd kurento-utils-js-master/dist
</code>```

Here we are

copy kurento-utils.js in your resource folder

Body:
Where is no magic:

 git clone https://github.com/Kurento/kurento-utils-js
 cd kurento-utils-js-master
 npm install

To build the browser version of the library you'll only need to exec the grunt task runner and they will be generated on the dist folder. Alternatively, if you don't have it globally installed, you can run a local copy by executing:

node_modules/.bin/grunt

(for windows i run grunt.cmd)

 cd kurento-utils-js-master/dist

Here we are

copy kurento-utils.js in your resource folder


问:
Microsoft Graph REST API v1.0 - List personal contacts using application permissions
I've registered a web application in Azure Portal, granted it a Contacts.Read permission, gave it an administrator consent and now trying to list personal contacts of a particular user with Microsoft Graph REST API v1.0 using this application.

At first i'm trying to get an access token by sending POST request to
https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token with following body parameters: scope=https://graph.microsoft.com/contacts.read, grant_type=client_credentials, my client_id and my client_secret.

In response i'm getting an error 400 Bad Request. Body:
{"error":"invalid_scope","error_description":"AADSTS70011: The provided request must include a 'scope' input parameter. The provided value for the input parameter 'scope' is not valid. The scope https://graph.microsoft.com/contacts.read is not valid."}

When i'm replacing scope parameter in token request like this: scope=https://graph.microsoft.com/.default, i'm actually receiving 200 OK and my Bearer token in response.

But when i'm requesting user personal contacts by sending GET request to https://graph.microsoft.com/v1.0/users/{user_id}/contacts with this token, i'm getting 401 Unauthorized in response with following error:

"code": "NoPermissionsInAccessToken",
"message": "The token contains no permissions, or permissions can not be understood.",

I've also tried to replace the scope value in my token request with {app_id_uri}/.default and {app_id_uri}/contacts.read with no luck.

So how do i list user personal contacts using Microsoft Graph REST API v1.0? What am i doing wrong?

EDIT: Permissions screenshot:

答:
Keep the scope:

scope=https://graph.microsoft.com/.default

You will need Application permissions (Admin):

users.read.all

contacts.read

I'd opt for the readwrite versions in case you want to add/edit contacts

I also use Delegated permission with offline_access

you've set contacts in the legacy exchange add the graph contacts permission instead.


问:
extjs how to parametrize a component
I'm trying to pass two parameters oneOfAll and twoOfAll into a container. From the initComponent function I do:

```<code>initComponent: function () {
       this.callParent(arguments);
       console.log('Results', this.oneOfAll, this.twoOfAll);
}
</code>```

and the browser's console prints the correct data, but when:

```<code>items: [
          {
              xtype: 'button',
              text: 'Other click',
              id: 'buttonClick',
              handler: function(item) {
                  Ext.Msg.alert('Other Click', '!!!' + this.oneOfAll);
              }
          },
          {
              xtype: 'button',
              text: 'CLICK',
              id: 'buttonClick_2',
              handler: function(item) {
                 Ext.Msg.alert('Other Click', '!!!' + this.twoOfAll);
              }
           }
      ]
</code>```

these values are not seen by the container config, both times undefined is returned.

I have this fiddle: https://fiddle.sencha.com/#view/editor&fiddle/2sk3

How can I pass these parameters into the container and be seen by it?

答:
You can set reference to current component in initComponent method and use them in child component.

Take a look on example:
https://fiddle.sencha.com/#view/editor&fiddle/2skh

Title: extjs how to parametrize a component

Body:
I'm trying to pass two parameters oneOfAll and twoOfAll into a container. From the initComponent function I do:

initComponent: function () {
       this.callParent(arguments);
       console.log('Results', this.oneOfAll, this.twoOfAll);
}

and the browser's console prints the correct data, but when:

items: [
          {
              xtype: 'button',
              text: 'Other click',
              id: 'buttonClick',
              handler: function(item) {
                  Ext.Msg.alert('Other Click', '!!!' + this.oneOfAll);
              }
          },
          {
              xtype: 'button',
              text: 'CLICK',
              id: 'buttonClick_2',
              handler: function(item) {
                 Ext.Msg.alert('Other Click', '!!!' + this.twoOfAll);
              }
           }
      ]

these values are not seen by the container config, both times undefined is returned.

I have this fiddle: https://fiddle.sencha.com/#view/editor&fiddle/2sk3

How can I pass these parameters into the container and be seen by it?


问:
Calculation between 2 vectors where one is 4d and other is 1d
I am using Matlab 2018b. One problem has emerged when I am working with 2 vectors. One is of 4d form and other is of 1d form. I would like to subtract the value of a vector from the values of the other vector.

Idea:

I need to run a loop upon the vector A and vector B. Inside the loop I'll obtain the value of the vector A and subtract a value of the corresponding index from B

But, I would like to solve the problem in a more MATLAB way rather than procedural way. Can you please guide me for this?

Example:

```<code>A=[val(:,:,1,1)
      = 0.67
    val(:,:,2,1)
        =0.55
   val(:,:,3,1)
        =0.12
   val(:,:,1,2)
      = 0.12
    val(:,:,2,2)
        =0.50
    val(:,:,3,2)
        =0.11
]
B=[1
    0]
</code>```

The operation would be like this one

```<code>Result=[
            val(:,:,1,1) =0.67-1
            val(:,:,2,1) =0.55-1
            val(:,:,3,1) =0.12-1
            val(:,:,1,2) =0.12-0
            val(:,:,2,2) =0.5-0
            val(:,:,3,2) =0.11-0
]
</code>```

thanks,

答:
In order to avoid using permute you can use two tricks:

Implicit expansion

Singleton dimension

If you want to substract a 1D matrix to a 4D matrix the problem is that matlab doesn't know on which dimension the substraction should be applied.

But matlab allows you to create a matrix with singleton dimension for example a matrix 1x1x1x2 can be created.

Here is an example:

```<code>% Creation of the 4D matrix
A = rand(3,4,5,2);
% Creation of another 4D matrix but with 3 singleton dimension
B = [1,0];
B = reshape(B,1,1,1,2);
%                   ↑
%              4th dimension

%Now matlab know that the substraction should be applied on the 4th dimension.
X = A-B;
</code>```

Another example:

```<code>% Creation of the 4D matrix
A = rand(3,4,2,5);
% Creation of another 4D matrix but with 2 singleton dimension
B = [1,0];
B = reshape(B,1,1,2); %could also be written reshape(B,1,1,2,1)
%                 ↑
%             3th dimension

%Now matlab know that the substraction should be applied on the 3th dimension.
X = A-B;
</code>```

Body:
I am using Matlab 2018b. One problem has emerged when I am working with 2 vectors. One is of 4d form and other is of 1d form. I would like to subtract the value of a vector from the values of the other vector.

Idea:

I need to run a loop upon the vector A and vector B. Inside the loop I'll obtain the value of the vector A and subtract a value of the corresponding index from B

But, I would like to solve the problem in a more MATLAB way rather than procedural way. Can you please guide me for this?

Example:

A=[val(:,:,1,1)
      = 0.67
    val(:,:,2,1)
        =0.55
   val(:,:,3,1)
        =0.12
   val(:,:,1,2)
      = 0.12
    val(:,:,2,2)
        =0.50
    val(:,:,3,2)
        =0.11
]
B=[1
    0]

The operation would be like this one

Result=[
            val(:,:,1,1) =0.67-1
            val(:,:,2,1) =0.55-1
            val(:,:,3,1) =0.12-1
            val(:,:,1,2) =0.12-0
            val(:,:,2,2) =0.5-0
            val(:,:,3,2) =0.11-0
]

thanks,

Body:
In order to avoid using permute you can use two tricks:

Implicit expansion

Singleton dimension

If you want to substract a 1D matrix to a 4D matrix the problem is that matlab doesn't know on which dimension the substraction should be applied.

But matlab allows you to create a matrix with singleton dimension for example a matrix 1x1x1x2 can be created.

Here is an example:

% Creation of the 4D matrix
A = rand(3,4,5,2);
% Creation of another 4D matrix but with 3 singleton dimension
B = [1,0];
B = reshape(B,1,1,1,2);
%                   ↑
%              4th dimension

%Now matlab know that the substraction should be applied on the 4th dimension.
X = A-B;

Another example:

% Creation of the 4D matrix
A = rand(3,4,2,5);
% Creation of another 4D matrix but with 2 singleton dimension
B = [1,0];
B = reshape(B,1,1,2); %could also be written reshape(B,1,1,2,1)
%                 ↑
%             3th dimension

%Now matlab know that the substraction should be applied on the 3th dimension.
X = A-B;