问:
groovysh is giving java.lang.reflect.InvocationTargetException
Groovy version:
Groovy Version: 3.0.0-rc-3 JVM: 1.8.0_221 Vendor: Oracle Corporation OS: Linux

on running command : groovysh
Error output:

```<code>    java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:106)
        at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:124)
Caused by: java.lang.UnsatisfiedLinkError: Could not load library. Reasons: [no jansi in java.library.path, /tmp/libjansi-64-3695606470401720252.so: /tmp/libjansi-64-3695606470401720252.so: failed to map segment from shared object: Operation not permitted]
        at org.fusesource.hawtjni.runtime.Library.doLoad(Library.java:182)
        at org.fusesource.hawtjni.runtime.Library.load(Library.java:140)
        at org.fusesource.jansi.internal.CLibrary.<clinit>(CLibrary.java:42)
        at org.fusesource.jansi.AnsiConsole.wrapOutputStream(AnsiConsole.java:48)
        at org.fusesource.jansi.AnsiConsole.<clinit>(AnsiConsole.java:38)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:348)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.lambda$createCallStaticSite$2(CallSiteArray.java:65)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallStaticSite(CallSiteArray.java:63)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:156)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:115)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:119)
        at org.apache.groovy.groovysh.Main.installAnsi(Main.groovy:249)
        at org.apache.groovy.groovysh.Main.setTerminalType(Main.groovy:235)
        at org.apache.groovy.groovysh.Main.main(Main.groovy:120)
        ... 6 more
</code>```

答:
As far as I know this kind of issue comes not from Groovy itself, but from your user not having write rights to /tmp. For example if your tmp is mounted readonly.

Background: Jansi requires native libraries, that are part of the jar. Java cannot load them form the jar and requires them to be put "somewhere", which is usually /tmp. Since it seems your tmp cannot be written you get the "Operation not permitted".

Body:
Groovy version:
Groovy Version: 3.0.0-rc-3 JVM: 1.8.0_221 Vendor: Oracle Corporation OS: Linux

on running command : groovysh
Error output:

    java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:106)
        at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:124)
Caused by: java.lang.UnsatisfiedLinkError: Could not load library. Reasons: [no jansi in java.library.path, /tmp/libjansi-64-3695606470401720252.so: /tmp/libjansi-64-3695606470401720252.so: failed to map segment from shared object: Operation not permitted]
        at org.fusesource.hawtjni.runtime.Library.doLoad(Library.java:182)
        at org.fusesource.hawtjni.runtime.Library.load(Library.java:140)
        at org.fusesource.jansi.internal.CLibrary.<clinit>(CLibrary.java:42)
        at org.fusesource.jansi.AnsiConsole.wrapOutputStream(AnsiConsole.java:48)
        at org.fusesource.jansi.AnsiConsole.<clinit>(AnsiConsole.java:38)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:348)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.lambda$createCallStaticSite$2(CallSiteArray.java:65)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallStaticSite(CallSiteArray.java:63)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:156)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:115)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:119)
        at org.apache.groovy.groovysh.Main.installAnsi(Main.groovy:249)
        at org.apache.groovy.groovysh.Main.setTerminalType(Main.groovy:235)
        at org.apache.groovy.groovysh.Main.main(Main.groovy:120)
        ... 6 more


来源: stackexchange

问:
Content flows below Navigation (menubar): responsive website
I've decide to upload my responsive website, though noticed the content (in this case the dummy text) doesn't stay below the navigation menu.

( http://www.azhir.co.uk/web_zip/default.html )

As you'll see it's a basic css style and I use css style to create the hamburger menu bar.

```<code>html, body {
          margin: 0;
          padding: 0;
          width: 100%;
    }

    body {
          font-family: "Helvetica Neue",sans-serif;
          font-weight: lighter;
    }

    header {
          width: 100%;
          height: 0.01vh;
          background-color: red;
    }

    .content {
          width: 94%;
          margin: 4em auto;
          font-size: 20px;
          line-height: 30px;
          text-align: justify;
    }

    .logo {
          line-height: 60px;
          position: fixed;
          float: left;
          margin: 16px 46px;
          color: black;
          font-weight: bold;
          font-size: 20px;
          letter-spacing: 2px;
    }

    nav {
          position: fixed;
          width: 100%;
          line-height: 60px;
    }

    nav ul {
          line-height: 60px;
          list-style: none;
          background: rgba(0, 0, 0, 0);   /*transparency rgba(0,0,0,0)*/
          overflow: hidden;
          color: #fff;
          padding: 0;
          text-align: right;
          margin: 0;
          padding-right: 40px;
          transition: 1s;
    }

    nav.black ul {
          background: white;  /*changes color of bar*/
    }

    nav ul li {
          display: inline-block;
          padding: 16px 40px;;
    }

    nav ul li a {
          text-decoration: none;
          color: black;
          font-weight: bold;
          font-size: 16px;
    }

    .menu-icon {
          line-height: 60px;
          width: 100%;
          background: white; /*changes hamburger color*/
          text-align: right;
          box-sizing: border-box;
          padding: 15px 24px;
          cursor: pointer;
          color: black;
          display: none;
    }

    @media(max-width: 786px) {

          .logo {
                position: fixed;
                top: 0;
                margin-top: 16px;
          }

          nav ul {
                max-height: 0px;
                background: white; /*mobile color*/
          }

          nav.black ul {
                background: white;
          }

          .showing {
                max-height: 34em;
          }

          nav ul li {
                box-sizing: border-box;
                width: 100%;
                padding: 24px;
                text-align: center;
          }

          .menu-icon {
                display: block;
          }

    }
</code>```

This is the css for my menu.css

```<code>body{
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
  background-color: white;
}

a{
  color: black;
}

.header{
  background-color: white;
  box-shadow:1px 1px 4px 0 rgba(0,0,0,.1);
  position:fixed;
  width:100%;
  z-index:3;
}

.header ul{
  margin:0;
  padding:0;
  list-style:none;
  overflow:hidden;
  background-color:white;
}

.header ul a{
  display:block;
  padding:20px;
  boder-right:1px solid grey;
  text-decoration: none;
}

.header ul a:hover{
  background-color: #e6e6e6;
}

.header .logo{
  float:left;
  display:block;
  font-size: 2em;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
}

.header .menu{
  clear:both;
  max-height:0;
  transition:max-height .2s ease-out;
}

/*hamburger*/

.header .menu-icon{
  padding: 28px 20px;
  position: relative;
  float:right;
  cursor:pointer;
}

.header .menu-icon .nav-icon{
  background:black;
  display: block;
  height:2px;
  width:18px;
  position:relative;
  transition: background .2s ease-out;
}

.header .menu-icon .nav-icon:before{
  background:black;
  content:"";
  display:block;
  height:100%;
  width:100%;
  position:absolute;
  transition: all .2s ease-out;
  top:5px;
}

.header .menu-icon .nav-icon:after{
  background:black;
  content:"";
  display:block;
  height:100%;
  width:100%;
  position:absolute;
  transition: all .2s ease-out;
  top:-5px;
}

.header .menu-btn{
  display: none;
}

.header .menu-btn:checked ~ .menu{
  max-height:240px;
}

.header .menu-btn:checked ~ .menu-icon .nav-icon{
  background: transparent;
}

.header .menu-btn:checked ~ .menu-icon .nav-icon:before{
  transform: rotate(-45deg);
  top:0;
}

.header .menu-btn:checked ~ .menu-icon .nav-icon:after{
  transform: rotate(45deg);
  top:0;
}

@media (min-width:48em){
  .header li{
    float:left;
  }
  .header li a{
    padding:20px 30px;
  }

  .header .menu{
    clear:none;
    float:right;
    max-height: none;
  }

  .header .menu-icon{
    display:none;
  }

  .header .logo{
    float:left;
    display:block;
    font-size: 2em;
    padding: 10px 8%;
    text-align: center;
    text-decoration: none;
  }

}

/*content*/
.content {
  width: 85%;
  font-size: 20px;
  line-height: 30px;
  text-align: inherit;
  margin-left:  auto;
  margin-right: auto;
}
</code>```

and the html code is pretty basic and just;

```<code><html>
  <head>
    <link rel="stylesheet" href="css/menu.css">
  </head>

  <body>
    <header class="header">
      <a href="/" class="logo">Azhir Mahmood</a>
      <input class="menu-btn" type="checkbox" id="menu-btn"/>
      <label class="menu-icon" for="menu-btn"><span class="nav-icon"></span></label>
      <ul class="menu">
        <li><a href="#ALPHA">ALPHA</a></li>
        <li><a href="#BETA">BETA</a></li>
        <li><a href="#GAMMA">GAMMA</a></li>
      </ul>
    </header>

    <div class="content">
          <p>
                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
          </p>
          <p>

  </body>
</html>
</code>```

答:
Welcome to SO!

Set padding-top: 58px on .content CLass

WHY

Because you header which have height 58px is fixed so it leave its space.. to cover it you need padding to equal to height of header. This fix is Done where we use header fixed,absolute, sticky(No DOM space)

ContentLicense: CC BY-SA 4.0

Body:
I've decide to upload my responsive website, though noticed the content (in this case the dummy text) doesn't stay below the navigation menu.

( http://www.azhir.co.uk/web_zip/default.html )

As you'll see it's a basic css style and I use css style to create the hamburger menu bar.

html, body {
          margin: 0;
          padding: 0;
          width: 100%;
    }

    body {
          font-family: "Helvetica Neue",sans-serif;
          font-weight: lighter;
    }

    header {
          width: 100%;
          height: 0.01vh;
          background-color: red;
    }

    .content {
          width: 94%;
          margin: 4em auto;
          font-size: 20px;
          line-height: 30px;
          text-align: justify;
    }

    .logo {
          line-height: 60px;
          position: fixed;
          float: left;
          margin: 16px 46px;
          color: black;
          font-weight: bold;
          font-size: 20px;
          letter-spacing: 2px;
    }

    nav {
          position: fixed;
          width: 100%;
          line-height: 60px;
    }

    nav ul {
          line-height: 60px;
          list-style: none;
          background: rgba(0, 0, 0, 0);   /*transparency rgba(0,0,0,0)*/
          overflow: hidden;
          color: #fff;
          padding: 0;
          text-align: right;
          margin: 0;
          padding-right: 40px;
          transition: 1s;
    }

    nav.black ul {
          background: white;  /*changes color of bar*/
    }

    nav ul li {
          display: inline-block;
          padding: 16px 40px;;
    }

    nav ul li a {
          text-decoration: none;
          color: black;
          font-weight: bold;
          font-size: 16px;
    }

    .menu-icon {
          line-height: 60px;
          width: 100%;
          background: white; /*changes hamburger color*/
          text-align: right;
          box-sizing: border-box;
          padding: 15px 24px;
          cursor: pointer;
          color: black;
          display: none;
    }

    @media(max-width: 786px) {

          .logo {
                position: fixed;
                top: 0;
                margin-top: 16px;
          }

          nav ul {
                max-height: 0px;
                background: white; /*mobile color*/
          }

          nav.black ul {
                background: white;
          }

          .showing {
                max-height: 34em;
          }

          nav ul li {
                box-sizing: border-box;
                width: 100%;
                padding: 24px;
                text-align: center;
          }

          .menu-icon {
                display: block;
          }

    }

This is the css for my menu.css

body{
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
  background-color: white;
}

a{
  color: black;
}

.header{
  background-color: white;
  box-shadow:1px 1px 4px 0 rgba(0,0,0,.1);
  position:fixed;
  width:100%;
  z-index:3;
}

.header ul{
  margin:0;
  padding:0;
  list-style:none;
  overflow:hidden;
  background-color:white;
}

.header ul a{
  display:block;
  padding:20px;
  boder-right:1px solid grey;
  text-decoration: none;
}

.header ul a:hover{
  background-color: #e6e6e6;
}

.header .logo{
  float:left;
  display:block;
  font-size: 2em;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
}

.header .menu{
  clear:both;
  max-height:0;
  transition:max-height .2s ease-out;
}

/*hamburger*/

.header .menu-icon{
  padding: 28px 20px;
  position: relative;
  float:right;
  cursor:pointer;
}

.header .menu-icon .nav-icon{
  background:black;
  display: block;
  height:2px;
  width:18px;
  position:relative;
  transition: background .2s ease-out;
}

.header .menu-icon .nav-icon:before{
  background:black;
  content:"";
  display:block;
  height:100%;
  width:100%;
  position:absolute;
  transition: all .2s ease-out;
  top:5px;
}

.header .menu-icon .nav-icon:after{
  background:black;
  content:"";
  display:block;
  height:100%;
  width:100%;
  position:absolute;
  transition: all .2s ease-out;
  top:-5px;
}

.header .menu-btn{
  display: none;
}

.header .menu-btn:checked ~ .menu{
  max-height:240px;
}

.header .menu-btn:checked ~ .menu-icon .nav-icon{
  background: transparent;
}

.header .menu-btn:checked ~ .menu-icon .nav-icon:before{
  transform: rotate(-45deg);
  top:0;
}

.header .menu-btn:checked ~ .menu-icon .nav-icon:after{
  transform: rotate(45deg);
  top:0;
}

@media (min-width:48em){
  .header li{
    float:left;
  }
  .header li a{
    padding:20px 30px;
  }

  .header .menu{
    clear:none;
    float:right;
    max-height: none;
  }

  .header .menu-icon{
    display:none;
  }

  .header .logo{
    float:left;
    display:block;
    font-size: 2em;
    padding: 10px 8%;
    text-align: center;
    text-decoration: none;
  }

}

/*content*/
.content {
  width: 85%;
  font-size: 20px;
  line-height: 30px;
  text-align: inherit;
  margin-left:  auto;
  margin-right: auto;
}

and the html code is pretty basic and just;

    <link rel="stylesheet" href="css/menu.css">

      Azhir Mahmood
      <input class="menu-btn" type="checkbox" id="menu-btn"/>

ALPHA

BETA

GAMMA

                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


问:
Fetch Specific field and cell value next to it based on a condition using R
I have a dataframe and I want to fetch the value of the column and the cell value next to it in separate new columns. The condition is that I want only those shelves where item A and B are present and their respective selling price. For anything else it should fetch NA. I have given an example of the input and expected output. I tried various options like concatenating and using regular expression but couldnot achieve the desired result.</p>

```<code>df_input <- data.frame (shelf_1  = c('A','A','B','C','C','D'),
                  selling_price_s1 = c(20000, 23000, 26000,25000,24000,20000),
                  shelf_2  = c('D','C','C','A','A','D'),
                  selling_price_s2 = c(23000, 25000, 25000,21000,22000,25000),
                  shelf_3  = c('C','D','D','C','NA','C'),
                  selling_price_s3 = c(20000, 23000, 26000,25000,NA,20000),
                  )

df_expected <- data.frame (shelf  = c('A','A','B','A','A','NA'),
                  selling_price = c(20000, 23000, 26000,21000,22000,NA),
                  )
</code>```

答:
Using data.table:

```<code>library(data.table)
setDT(df_input)

df_input[, melt(.SD, measure = patterns("^shelf", "^selling_price_s"))
         ][value1 %chin% c("A", "B", "NA")]

   variable value1 value2
1:        1      A  20000
2:        1      A  23000
3:        1      B  26000
4:        2      A  21000
5:        2      A  22000
6:        3     NA     NA
</code>```

PS. if you format your NA properly you need to add in |is.na(value1) in the last step.

Base R alternative:

```<code>df_out <- data.frame(
  shelf = as.character(unlist(df_input[grep("shelf", names(df_input))])),
  selling_price = unlist(df_input[grep("selling_price", names(df_input))], use.names = FALSE)
)
df_out
df_out[df_out$shelf %in% c("A", "B", "NA"), ]
</code>```

Reproducible data:

```<code>df_input <- data.frame(
  shelf_1  = c('A', 'A', 'B', 'C', 'C', 'D'),
  selling_price_s1 = c(20000, 23000, 26000, 25000, 24000, 20000),
  shelf_2  = c('D', 'C', 'C', 'A', 'A', 'D'),
  selling_price_s2 = c(23000, 25000, 25000, 21000, 22000, 25000),
  shelf_3  = c('C', 'D', 'D', 'C', 'NA', 'C'),
  selling_price_s3 = c(20000, 23000, 26000, 25000, NA, 20000)
)
</code>```

Body:
I have a dataframe and I want to fetch the value of the column and the cell value next to it in separate new columns. The condition is that I want only those shelves where item A and B are present and their respective selling price. For anything else it should fetch NA. I have given an example of the input and expected output. I tried various options like concatenating and using regular expression but couldnot achieve the desired result.

df_input <- data.frame (shelf_1  = c('A','A','B','C','C','D'),
                  selling_price_s1 = c(20000, 23000, 26000,25000,24000,20000),
                  shelf_2  = c('D','C','C','A','A','D'),
                  selling_price_s2 = c(23000, 25000, 25000,21000,22000,25000),
                  shelf_3  = c('C','D','D','C','NA','C'),
                  selling_price_s3 = c(20000, 23000, 26000,25000,NA,20000),
                  )

df_expected <- data.frame (shelf  = c('A','A','B','A','A','NA'),
                  selling_price = c(20000, 23000, 26000,21000,22000,NA),
                  )

Body:
Using data.table:

library(data.table)
setDT(df_input)

df_input[, melt(.SD, measure = patterns("^shelf", "^selling_price_s"))
         ][value1 %chin% c("A", "B", "NA")]

   variable value1 value2
1:        1      A  20000
2:        1      A  23000
3:        1      B  26000
4:        2      A  21000
5:        2      A  22000
6:        3     NA     NA

PS. if you format your NA properly you need to add in |is.na(value1) in the last step.

Base R alternative:

df_out <- data.frame(
  shelf = as.character(unlist(df_input[grep("shelf", names(df_input))])),
  selling_price = unlist(df_input[grep("selling_price", names(df_input))], use.names = FALSE)
)
df_out
df_out[df_out$shelf %in% c("A", "B", "NA"), ]

Reproducible data:

df_input <- data.frame(
  shelf_1  = c('A', 'A', 'B', 'C', 'C', 'D'),
  selling_price_s1 = c(20000, 23000, 26000, 25000, 24000, 20000),
  shelf_2  = c('D', 'C', 'C', 'A', 'A', 'D'),
  selling_price_s2 = c(23000, 25000, 25000, 21000, 22000, 25000),
  shelf_3  = c('C', 'D', 'D', 'C', 'NA', 'C'),
  selling_price_s3 = c(20000, 23000, 26000, 25000, NA, 20000)
)


问:
Binding objects defined in code-behind
I have some object that is instantiated in code behind, for instance, the XAML is called window.xaml and within the window.xaml.cs

```<code>protected Dictionary<string, myClass> myDictionary;
</code>```

How can I bind this object to, for example, a list view, using only XAML markups?

Update:

(This is exactly I have in my test code):

```<code><Window x:Class="QuizBee.Host.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="{Binding windowname}" Height="300" Width="300"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
    </Grid>
</Window>
</code>```

And in codebehind

```<code>public partial class Window1 : Window
{
    public const string windowname = "ABCDEFG";

    public Window1()
    {
        InitializeComponent();
    }
}
</code>```

Suppose the title should become "ABCDEFG" right? but it ends up showing nothing.

答:
There's a much easier way of doing this. You can assign a Name to your Window or UserControl, and then binding by ElementName.

Window1.xaml

```<code><Window x:Class="QuizBee.Host.Window1"
        x:Name="Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ListView ItemsSource="{Binding ElementName=Window1, Path=myDictionary}" />
</Window>
</code>```

Window1.xaml.cs

```<code>public partial class Window1:Window
{
    // the property must be public, and it must have a getter & setter
    public Dictionary<string, myClass> myDictionary { get; set; }

    public Window1()
    {
        // define the dictionary items in the constructor
        // do the defining BEFORE the InitializeComponent();

        myDictionary = new Dictionary<string, myClass>()
        {
            {"item 1", new myClass(1)},
            {"item 2", new myClass(2)},
            {"item 3", new myClass(3)},
            {"item 4", new myClass(4)},
            {"item 5", new myClass(5)},
        };

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

ContentLicense: CC BY-SA 3.0

Title: Binding objects defined in code-behind

Body:
I have some object that is instantiated in code behind, for instance, the XAML is called window.xaml and within the window.xaml.cs

protected Dictionary<string, myClass> myDictionary;

How can I bind this object to, for example, a list view, using only XAML markups?

Update:

(This is exactly I have in my test code):

<Window x:Class="QuizBee.Host.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="{Binding windowname}" Height="300" Width="300"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
    </Grid>
</Window>

And in codebehind

public partial class Window1 : Window
{
    public const string windowname = "ABCDEFG";

    public Window1()
    {
        InitializeComponent();
    }
}

Suppose the title should become "ABCDEFG" right? but it ends up showing nothing.

Body:
There's a much easier way of doing this. You can assign a Name to your Window or UserControl, and then binding by ElementName.

Window1.xaml

<Window x:Class="QuizBee.Host.Window1"
        x:Name="Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ListView ItemsSource="{Binding ElementName=Window1, Path=myDictionary}" />
</Window>

Window1.xaml.cs

public partial class Window1:Window
{
    // the property must be public, and it must have a getter & setter
    public Dictionary<string, myClass> myDictionary { get; set; }

    public Window1()
    {
        // define the dictionary items in the constructor
        // do the defining BEFORE the InitializeComponent();

        myDictionary = new Dictionary<string, myClass>()
        {
            {"item 1", new myClass(1)},
            {"item 2", new myClass(2)},
            {"item 3", new myClass(3)},
            {"item 4", new myClass(4)},
            {"item 5", new myClass(5)},
        };

        InitializeComponent();
    }
}


问:
Putting zeros before a number in pandas
I have a similiar question to this, but it is not about the visualization. I have a pandas dataframe with an int column.

```<code>A
5
43
1200
555
</code>```

And I need to have always 4 digits, as this stands original for a timestamp:

```<code>00:05
00:43
12:00
05:55
</code>```

How can i work on that column that i have the outcome:

```<code>0005
0043
1200
0555
</code>```

答:
Use Series.str.zfill, but first convert to strings:

```<code>df['A'] = df['A'].astype(str).str.zfill(4)
print (df)
      A
0  0005
1  0043
2  1200
3  0555
</code>```

If need ::

```<code>s = df['A'].astype(str).str.zfill(4)
df['A'] = s.str[:2] + ':' + s.str[2:]
</code>```

Or:

```<code>df['A'] = df['A'].astype(str).str.zfill(4).map(lambda x: f'{x[:2]}:{x[2:]}')
</code>```

```<code>print (df)
       A
0  00:05
1  00:43
2  12:00
3  05:55
</code>```

Title: Putting zeros before a number in pandas

Body:
I have a similiar question to this, but it is not about the visualization. I have a pandas dataframe with an int column.

A
5
43
1200
555

And I need to have always 4 digits, as this stands original for a timestamp:

00:05
00:43
12:00
05:55

How can i work on that column that i have the outcome:

0005
0043
1200
0555

Body:
Use Series.str.zfill, but first convert to strings:

df['A'] = df['A'].astype(str).str.zfill(4)
print (df)
      A
0  0005
1  0043
2  1200
3  0555

If need ::

s = df['A'].astype(str).str.zfill(4)
df['A'] = s.str[:2] + ':' + s.str[2:]

Or:

df['A'] = df['A'].astype(str).str.zfill(4).map(lambda x: f'{x[:2]}:{x[2:]}')

print (df)
       A
0  00:05
1  00:43
2  12:00
3  05:55


问:
laravel xmlwriter not found
I installed XmlWriter with the following commands:

```<code>sudo apt-get install php-xml
sudo service apache2 restart
</code>```

In Laravel 5.4 under App\Helpers I have XMLGenerator.php and the following command:

```<code>$writer = new XmlWriter();
$writer->openMemory();
....
</code>```

I get the error:

FatalErrorException in XMLGenerator.php line 90: Class 'App\Helpers\XmlWriter' not found

I don't understand how can i include the XmlWriter.

Thank you

答:
try installing xmlwriter php extension.

```<code>sudo apt-get install php-xmlwriter
</code>```

or

```<code>sudo apt-get install php7-xmlwriter
</code>```

Title: laravel xmlwriter not found

Body:
I installed XmlWriter with the following commands:

sudo apt-get install php-xml
sudo service apache2 restart

In Laravel 5.4 under App\Helpers I have XMLGenerator.php and the following command:

$writer = new XmlWriter();
$writer->openMemory();
....

I get the error:

FatalErrorException in XMLGenerator.php line 90: Class 'App\Helpers\XmlWriter' not found

I don't understand how can i include the XmlWriter.

Thank you

Body:
try installing xmlwriter php extension.

sudo apt-get install php-xmlwriter

or

sudo apt-get install php7-xmlwriter


问:
flutter : i can't keep user login
i want to keep user login after his first login but in every time i'm closing the application from the phone's background the user logged out and must login from start again

this is my api method to login

```<code>Future<dynamic> login(String email, String password ) async {
    final Map<String, dynamic> body = {'email': email, 'password': password  };

    _isLoading = true;
    notifyListeners();

    http.Response response = await http.post(Environment.userLogin,
        body: json.encode(body), headers: Environment.requestHeader);

        SharedPreferences prefs = await SharedPreferences.getInstance();

    Map<String, dynamic> res = json.decode(response.body);
    var results;
    if (res['code'] == 200) {

      _user = User.fromJson(res['message']);

      prefs.setString('email', _user.email);
      results = true;
    } else {

      results =
          FailedRequest(code: 400, message: res['error'], status: false);
    }

    _isLoading = false;
    notifyListeners();
    return results;
  }
</code>```

and this is the main function

```<code>Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var email = prefs.getString('email');
  print(email);
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]).then((_) => runApp(new MyApp()));

}
</code>```

can any one help me to solve this problem ?

答:
Example on DartPad</p>

```<code>class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FutureBuilder(
        future: SharedPreferences.getInstance(),
        builder: (BuildContext context, AsyncSnapshot<SharedPreferences> snapshot) {
          if (!snapshot.hasData) return Container();

          final isLoggedIn = snapshot.data.getString("email") != null;
          return isLoggedIn ? Home() : Login();
        },
      ),
    );
  }
}
</code>```

Title: flutter : i can't keep user login

Body:
i want to keep user login after his first login but in every time i'm closing the application from the phone's background the user logged out and must login from start again

this is my api method to login

Future<dynamic> login(String email, String password ) async {
    final Map<String, dynamic> body = {'email': email, 'password': password  };

    _isLoading = true;
    notifyListeners();

    http.Response response = await http.post(Environment.userLogin,
        body: json.encode(body), headers: Environment.requestHeader);

        SharedPreferences prefs = await SharedPreferences.getInstance();

    Map<String, dynamic> res = json.decode(response.body);
    var results;
    if (res['code'] == 200) {

      _user = User.fromJson(res['message']);

      prefs.setString('email', _user.email);
      results = true;
    } else {

      results =
          FailedRequest(code: 400, message: res['error'], status: false);
    }

    _isLoading = false;
    notifyListeners();
    return results;
  }

and this is the main function

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var email = prefs.getString('email');
  print(email);
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]).then((_) => runApp(new MyApp()));

}

can any one help me to solve this problem ?

Body:
Example on DartPad

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FutureBuilder(
        future: SharedPreferences.getInstance(),
        builder: (BuildContext context, AsyncSnapshot<SharedPreferences> snapshot) {
          if (!snapshot.hasData) return Container();

          final isLoggedIn = snapshot.data.getString("email") != null;
          return isLoggedIn ? Home() : Login();
        },
      ),
    );
  }
}


问:
<meta http-equiv="X-UA-Compatible" content="IE=8" /> not working in test environment?
We are currently experiencing an issue in IE9 with our Sitefinity CMS and I was able to fix it in my development environment by adding:

to the head tag (before the title). In our test environment this is not working, any thoughts what might cause this?

答:
The tag should be before any other element in the head not just only before title.
Test the result in the browser using the "view source" command to ensure it is the first.</p>


问:
Rails: Unknown attribute during model create
I have an error message - "unknown attribute :news_id" but I can't understand where the problem is. I have news controller and I want to create comments for every news. I hope that someone could help me. Thanks in advance.

schema.rb

```<code>create_table "comments", :primary_key => "ID", :force => true do |t|
  t.integer "Author_ID"
  t.integer "News_ID", :null => false
  t.string "Content", :limit => 500, :null => false
  t.datetime "Date", :null => false
end
</code>```

Comment model:

```<code>belongs_to :news
</code>```

News model:

```<code>has_many :comments
</code>```

答:
I faced this same issue when working on a Ruby on Rails application with a PostgreSQL database in production.

Here's how I solved it:

The issue was that I added some new columns to the table(s) in my development environment using new migration files that I generated, but when I made a push to the production environment, I didn't create those new columns via migration too.

All I had to do was to simply run a database migration in the production environment to create those new columns using the migration files that were generated in the development environment.

```<code>rails db:migrate
</code>```

That's all.

I hope this helps

Body:
I have an error message - "unknown attribute :news_id" but I can't understand where the problem is. I have news controller and I want to create comments for every news. I hope that someone could help me. Thanks in advance.

schema.rb

create_table "comments", :primary_key => "ID", :force => true do |t|
  t.integer "Author_ID"
  t.integer "News_ID", :null => false
  t.string "Content", :limit => 500, :null => false
  t.datetime "Date", :null => false
end

Comment model:

belongs_to :news

News model:

has_many :comments

Body:
I faced this same issue when working on a Ruby on Rails application with a PostgreSQL database in production.

Here's how I solved it:

The issue was that I added some new columns to the table(s) in my development environment using new migration files that I generated, but when I made a push to the production environment, I didn't create those new columns via migration too.

All I had to do was to simply run a database migration in the production environment to create those new columns using the migration files that were generated in the development environment.

rails db:migrate

That's all.

I hope this helps


问:
SAS proc sql - is this the correct usage?
This works but wanted a health check as to if i have done this correct with proc sql connect to i.e do i need to have separate "select * from connection to's"?

```<code>proc sql;
connect to database (database=test user="&srvuser" password="&srvpass") ;
create table bob as
select t1._ as bob1
      ,t2._ as bob2
      ,t3._ as bob3
      ,t1._-t2._ as bob4
from (select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1)) t1
,(select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'R')) t2
,(select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL)) t3;
disconnect from database;
quit;
run;
</code>```

Thanks

答:
The query could work that way, but a cleaner approach might be to do everything server side in one query over a single  connection to

```<code>create table want as
select bob1, bob2, bob3, bob1-bob2 as bob4 from connection to database
(
 select
  (select count(*) from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1) as bob1,
  (select count(*) from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'R') as bob2,
  (select count(*) from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL) as bob3
)
</code>```

A slightly different approach would return one row per count.  The result set could be transposed in SAS.  There where clause could be left off, but the remote system would have to traverse every record in IMAGE_MSG_LOG and lose ability to utilize any indices that the where might leverage.

```<code>create table want as
select * from connection to database
(
  select
    case
      when RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1 then 'D1'
      when RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL then 'RNULL'
      when RR_MSG_CODE  = 'R' then 'RNOTNULL'
      else 'NOCAT'
    end
    as category,
    count(*) as category_count
  from DAVE.IMAGE_MSG_LOG
  where
      (RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1)
   or (RR_MSG_CODE  = 'R')
  group by category
)
</code>```

After transpose

bob1 is D1

bob2 is RNULL + RNOTNULL

bob3 is RNULL

bob4 is bob1-bob2

Body:
This works but wanted a health check as to if i have done this correct with proc sql connect to i.e do i need to have separate "select * from connection to's"?

proc sql;
connect to database (database=test user="&srvuser" password="&srvpass") ;
create table bob as
select t1._ as bob1
      ,t2._ as bob2
      ,t3._ as bob3
      ,t1._-t2._ as bob4
from (select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1)) t1
,(select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'R')) t2
,(select * from connection to database
(Select count(*)
        from DAVE.IMAGE_MSG_LOG
        where RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL)) t3;
disconnect from database;
quit;
run;

Thanks

Body:
The query could work that way, but a cleaner approach might be to do everything server side in one query over a single  connection to

create table want as
select bob1, bob2, bob3, bob1-bob2 as bob4 from connection to database
(
 select
  (select count(*) from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1) as bob1,
  (select count(*) from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'R') as bob2,
  (select count(*) from DAVE.IMAGE_MSG_LOG
   where RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL) as bob3
)

A slightly different approach would return one row per count.  The result set could be transposed in SAS.  There where clause could be left off, but the remote system would have to traverse every record in IMAGE_MSG_LOG and lose ability to utilize any indices that the where might leverage.

create table want as
select * from connection to database
(
  select
    case
      when RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1 then 'D1'
      when RR_MSG_CODE  = 'R' and RR_MSG_TIME_STAMP IS NULL then 'RNULL'
      when RR_MSG_CODE  = 'R' then 'RNOTNULL'
      else 'NOCAT'
    end
    as category,
    count(*) as category_count
  from DAVE.IMAGE_MSG_LOG
  where
      (RR_MSG_CODE  = 'D' and RR_MSG_SEQ_NO = 1)
   or (RR_MSG_CODE  = 'R')
  group by category
)

After transpose

bob1 is D1

bob2 is RNULL + RNOTNULL

bob3 is RNULL

bob4 is bob1-bob2


问:
Can we connect MongoDB from logic Apps without using cosmosDB
I need to connect MongoDB from my logic App without using CosmosDB. is it possible by any other way?</p>

答:
Right now there is no connector available with Logic Apps to connect to MongoDB directly.

As mentioned in the comment, you need to use the Azure Function with Cosmosdb API or with data factory as mentioned in the comment.


问:
using ramda type definition, pipe function throws type error
I installed type definition file for Ramda (@types/ramda), when I write the following code, no complains:

```<code>const gt5 = (x: number): boolean => x > 5
const inc = (x: number): number => x + 1
const f = pipe(map(inc), filter(gt5))
console.log(f([1,6,8]))
</code>```

but if I change the order of filter and map:

```<code>const gt5 = (x: number): boolean => x > 5
const inc = (x: number): number => x + 1
const f = pipe(filter(gt5), map(inc))
console.log(f([1,6,8]))
</code>```

I got the following error:

(alias) filter(fn: (value: number) => boolean): R.FilterOnceApplied (+4 overloads)
import filter
No overload matches this call.
  The last overload gave the following error.
    Argument of type 'FilterOnceApplied' is not assignable to parameter of type '(x0: unknown, x1: unknown, x2: unknown) => readonly number[]'.
      Types of parameters 'source' and 'x0' are incompatible.
        Type 'unknown' is not assignable to type 'number[] | Dictionary'.
          Type 'unknown' is not assignable to type 'Dictionary'.ts(2769)
index.d.ts(2172, 9): The last overload is declared here.

Of cause the code still runs correctly.

How do I fix this error?

I'm using VSCode.

答:
filter is supposed to work with both arrays and objects, but typescript gets confused as a result - from here

So one way to fix this error is:

```<code>const f = pipe(
  filter<number, "array">(gt5),
  map(inc)
);
</code>```

Hope it helps!

Body:
I installed type definition file for Ramda (@types/ramda), when I write the following code, no complains:

const gt5 = (x: number): boolean => x > 5
const inc = (x: number): number => x + 1
const f = pipe(map(inc), filter(gt5))
console.log(f([1,6,8]))

but if I change the order of filter and map:

const gt5 = (x: number): boolean => x > 5
const inc = (x: number): number => x + 1
const f = pipe(filter(gt5), map(inc))
console.log(f([1,6,8]))

I got the following error:

(alias) filter(fn: (value: number) => boolean): R.FilterOnceApplied (+4 overloads)
import filter
No overload matches this call.
  The last overload gave the following error.
    Argument of type 'FilterOnceApplied' is not assignable to parameter of type '(x0: unknown, x1: unknown, x2: unknown) => readonly number[]'.
      Types of parameters 'source' and 'x0' are incompatible.
        Type 'unknown' is not assignable to type 'number[] | Dictionary'.
          Type 'unknown' is not assignable to type 'Dictionary'.ts(2769)
index.d.ts(2172, 9): The last overload is declared here.

Of cause the code still runs correctly.

How do I fix this error?

I'm using VSCode.

Body:
filter is supposed to work with both arrays and objects, but typescript gets confused as a result - from here

So one way to fix this error is:

const f = pipe(
  filter<number, "array">(gt5),
  map(inc)
);

Hope it helps!


问:
Capture canvas screen as video using Silverlight
I have Silverlight application which have Bing Maps Silverlight control for map visualization. User can fly from location to location on map, add pins and every other map related stuff. My question is is it possible to capture video of canvas in my silverlight app where map is? So that user can specify draw me a route from A to B, and then my SL app will programmatically capture map screen and produce it like a video.

I was able to do that with WPF and Expression encoder SDK, but I'm afraid that this is not possible with SL (expression encoder + SL). Any suggestions?

Thank you in advance

答:
If you could capture the users actions (they clicked X and Y elements and typed Z into the textbox), then you could use those same actions to generate a video on the server.

A lame basic way to accomplish this is to open the site in a browser on the server, use video capture software to capture the browser window, and then inject the users actions programmatically. Of course this would be a terribly heavy application, but it's all I could come up with. Perhaps it'll spark a better idea.

As a side note, I highly doubt Silverlight can capture the browsers screen as this would be a major security flaw. Imagine hidden Silverlight controls capturing a user's actions without their knowledge.


问:
Processing large CSV uploads in Node.js
Per a prior thread here:

Node async loop - how to make this code run in sequential order?

...I'm looking for broader advice on processing large data upload files.

Scenario:

User uploads a very large CSV file with hundreds-of-thousands to millions of rows. It's streaming into an endpoint using multer:

```<code>const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

router.post("/", upload.single("upload"), (req, res) => {
    //...
});
</code>```

Each row is transformed into a JSON object. That object is then mapped into several smaller ones, which need to be inserted into several different tables, spread out across, and accessed by, various microservice containers.

```<code>async.forEachOfSeries(data, (line, key, callback) => {
    let model = splitData(line);
    //save model.record1, model.record2, etc. sequentially
});
</code>```

It's obvious I'm going to run into memory limitations with this approach. What is the most efficient manner for doing this?

答:
Large .csv Data Parse and Import

I used the above model to import a 1.7mm x 200 matrix of csv data into mongo with the following code.  Admittedly It's slow and I could use a little help on learning how to chunk the data better to make it more efficient, i.e. instead of inserting after each read, accumulate rows into an array of 5,10,25k rows and then insertMany or better yet become fluent in the through2-map or through2-filter methods.  If anyone is willing to share an example, thank you in advance.

```<code>require('dotenv').config();
const parse = require('csv-parser');
const fs = require("fs");
const through2 = require('through2')
const db = require('../models');

const file = "myFile.csv"
const rows = [];

//========Constructor Function for Mongo Import after each read======//
function Hotspot(variable1, variable2,...) {
this.variable1 = variable1;
this.variable2 = variable2;
...}

//========Counter so I can monitor progress in console============//
let counter = 0;
const rows = [];

//This function is imported & run in server.js from './scripts' after mongoose connection established//

exports.importCsvData = () => {
    fs.createReadStream(myFile)
        .pipe(parse())
        .pipe(through2({ objectMode: true }, (row, enc, cb) => {
            let hotspot = new Hotspot(
                `${row["ROW_VARIABLE_COLUMN_1"]}`,
                `${row["ROW_VARIABLE_COLUMN_2"]}`,...)

     db.MongoModel.create(hotspot)
                .then(result => console.log('created', counter++))
                .then(() => { cb(null, true) })
                .catch(err => {
                    cb(err, null)
                })
        }))
        .on('data', (row) => {
            rows.push(row);
        })
        .on('end', () => {
            console.log('read complete')
        })
}
</code>```

I used the following posts and links:

https://github.com/rvagg/through2#readme

https://nodesource.com/blog/understanding-object-streams

https://dev.to/isalevine/parsing-csv-files-in-node-js-with-fs-createreadstream-and-csv-parser-koi

https://dev.to/maheshkay/read-csv-file-using-node-js-29oc

as basis and reference for writing this script.  Appears to be working 'fine' except that I started this at 10pm last night and it is less than halfway finished as of 7:45am this morning.  This is better than the
"event": "Allocation failed - JavaScript heap out of memory"
error I received after I tried to accumulate all of my 'hotspot' objects into an array of hotspots for the purpose of bulk insert into mongoDB.  I am fairly new to readStream/through2/csv-parser in Node and learning, but wanted to share something that works, and is currently working.

Title: Processing large CSV uploads in Node.js

Body:
Per a prior thread here:

Node async loop - how to make this code run in sequential order?

...I'm looking for broader advice on processing large data upload files.

Scenario:

User uploads a very large CSV file with hundreds-of-thousands to millions of rows. It's streaming into an endpoint using multer:

const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

router.post("/", upload.single("upload"), (req, res) => {
    //...
});

Each row is transformed into a JSON object. That object is then mapped into several smaller ones, which need to be inserted into several different tables, spread out across, and accessed by, various microservice containers.

async.forEachOfSeries(data, (line, key, callback) => {
    let model = splitData(line);
    //save model.record1, model.record2, etc. sequentially
});

It's obvious I'm going to run into memory limitations with this approach. What is the most efficient manner for doing this?

Body:
Large .csv Data Parse and Import

I used the above model to import a 1.7mm x 200 matrix of csv data into mongo with the following code.  Admittedly It's slow and I could use a little help on learning how to chunk the data better to make it more efficient, i.e. instead of inserting after each read, accumulate rows into an array of 5,10,25k rows and then insertMany or better yet become fluent in the through2-map or through2-filter methods.  If anyone is willing to share an example, thank you in advance.

require('dotenv').config();
const parse = require('csv-parser');
const fs = require("fs");
const through2 = require('through2')
const db = require('../models');

const file = "myFile.csv"
const rows = [];

//========Constructor Function for Mongo Import after each read======//
function Hotspot(variable1, variable2,...) {
this.variable1 = variable1;
this.variable2 = variable2;
...}

//========Counter so I can monitor progress in console============//
let counter = 0;
const rows = [];

//This function is imported & run in server.js from './scripts' after mongoose connection established//

exports.importCsvData = () => {
    fs.createReadStream(myFile)
        .pipe(parse())
        .pipe(through2({ objectMode: true }, (row, enc, cb) => {
            let hotspot = new Hotspot(
                `${row["ROW_VARIABLE_COLUMN_1"]}`,
                `${row["ROW_VARIABLE_COLUMN_2"]}`,...)

     db.MongoModel.create(hotspot)
                .then(result => console.log('created', counter++))
                .then(() => { cb(null, true) })
                .catch(err => {
                    cb(err, null)
                })
        }))
        .on('data', (row) => {
            rows.push(row);
        })
        .on('end', () => {
            console.log('read complete')
        })
}

I used the following posts and links:

https://github.com/rvagg/through2#readme

https://nodesource.com/blog/understanding-object-streams

https://dev.to/isalevine/parsing-csv-files-in-node-js-with-fs-createreadstream-and-csv-parser-koi

https://dev.to/maheshkay/read-csv-file-using-node-js-29oc

as basis and reference for writing this script.  Appears to be working 'fine' except that I started this at 10pm last night and it is less than halfway finished as of 7:45am this morning.  This is better than the
"event": "Allocation failed - JavaScript heap out of memory"
error I received after I tried to accumulate all of my 'hotspot' objects into an array of hotspots for the purpose of bulk insert into mongoDB.  I am fairly new to readStream/through2/csv-parser in Node and learning, but wanted to share something that works, and is currently working.


问:
Angular Material Style Class not working
I'm using Angular Material to add Date Picker to my app. For some reason the angular material is not applying the original angular material styles.

How it displays in my app:

How it SHOULD display:

What I have done:

```<code>npm install --save @angular/material @angular/cdk

npm install --save @angular/animations

// Added this to the Angular Module whose components require the date picker
import {MatNativeDateModule, MatDatepickerModule} from "@angular/material";

//Added this in the root style.css file for the entire app
@import "~@angular/material/prebuilt-themes/indigo-pink.css";
</code>```

I'm not sure what I'm doing wrong.

Update:

Module Code:

```<code>import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule} from "@angular/router";
import {ProposalListComponent} from './components/proposal-list.component';
import {ProposalDetailComponent} from './components/proposal-detail.component';
import {ProposalEditComponent} from './components/proposal-edit.component';
import {ReactiveFormsModule} from "@angular/forms";
import {ProposalEditResolverService} from "./services/proposal-edit-resolver.service";
import {SectorResolverService} from "../root/services/sector-resolver.service";
import {ProposalAddComponent} from './components/proposal-add.component';
import {AuthGuard} from "../authentication/guards/auth.guard";
import {MatNativeDateModule, MatDatepickerModule, MatFormFieldModule, MatInputModule} from "@angular/material";
import {FileDropModule} from "ngx-file-drop";
import {ProposalListResolverService} from "./services/proposal-list-resolver.service";

@NgModule({
    imports: [
       CommonModule,
       RouterModule.forChild([
        {
          path: 'proposals',
          component: ProposalListComponent,
          canActivate: [AuthGuard],
          resolve: {proposals: ProposalListResolverService}
        },
        {
          path: 'proposals/:id',
          component: ProposalEditComponent,
          canActivate: [AuthGuard],
          resolve: {proposal: ProposalEditResolverService, sector: SectorResolverService}
        },
        {
         path: 'proposals/0/new',
         component: ProposalAddComponent,
         canActivate: [AuthGuard],
         resolve: {sector: SectorResolverService}
         }
        ]),
         ReactiveFormsModule,
         MatFormFieldModule,
         MatInputModule,
         MatDatepickerModule,
         MatNativeDateModule,
         FileDropModule
        ],
         declarations: [ProposalListComponent, ProposalDetailComponent,    ProposalEditComponent, ProposalAddComponent],
         providers: [ProposalEditResolverService,     ProposalListResolverService]
         })
    export class ProposalModule {
    }
</code>```

HTML:

This code is within the "ProposalEditComponent" which is part of the above module.

```<code><input matInput [matDatepicker]="picker" placeholder="Choose a date">
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
</code>```

答:
You need to wrap the input element with a <mat-form-field> and then the Material style is applied.

<input matInput .... /> on its own is not sufficient.

You need:

```<code><mat-form-field>
    <input matInput .... />
</mat-form-field>
</code>```

Body:
I'm using Angular Material to add Date Picker to my app. For some reason the angular material is not applying the original angular material styles.

How it displays in my app:

How it SHOULD display:

What I have done:

npm install --save @angular/material @angular/cdk

npm install --save @angular/animations

// Added this to the Angular Module whose components require the date picker
import {MatNativeDateModule, MatDatepickerModule} from "@angular/material";

//Added this in the root style.css file for the entire app
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

I'm not sure what I'm doing wrong.

Update:

Module Code:

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule} from "@angular/router";
import {ProposalListComponent} from './components/proposal-list.component';
import {ProposalDetailComponent} from './components/proposal-detail.component';
import {ProposalEditComponent} from './components/proposal-edit.component';
import {ReactiveFormsModule} from "@angular/forms";
import {ProposalEditResolverService} from "./services/proposal-edit-resolver.service";
import {SectorResolverService} from "../root/services/sector-resolver.service";
import {ProposalAddComponent} from './components/proposal-add.component';
import {AuthGuard} from "../authentication/guards/auth.guard";
import {MatNativeDateModule, MatDatepickerModule, MatFormFieldModule, MatInputModule} from "@angular/material";
import {FileDropModule} from "ngx-file-drop";
import {ProposalListResolverService} from "./services/proposal-list-resolver.service";

@NgModule({
    imports: [
       CommonModule,
       RouterModule.forChild([
        {
          path: 'proposals',
          component: ProposalListComponent,
          canActivate: [AuthGuard],
          resolve: {proposals: ProposalListResolverService}
        },
        {
          path: 'proposals/:id',
          component: ProposalEditComponent,
          canActivate: [AuthGuard],
          resolve: {proposal: ProposalEditResolverService, sector: SectorResolverService}
        },
        {
         path: 'proposals/0/new',
         component: ProposalAddComponent,
         canActivate: [AuthGuard],
         resolve: {sector: SectorResolverService}
         }
        ]),
         ReactiveFormsModule,
         MatFormFieldModule,
         MatInputModule,
         MatDatepickerModule,
         MatNativeDateModule,
         FileDropModule
        ],
         declarations: [ProposalListComponent, ProposalDetailComponent,    ProposalEditComponent, ProposalAddComponent],
         providers: [ProposalEditResolverService,     ProposalListResolverService]
         })
    export class ProposalModule {
    }

HTML:

This code is within the "ProposalEditComponent" which is part of the above module.

<input matInput [matDatepicker]="picker" placeholder="Choose a date">
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>

Body:
You need to wrap the input element with a <mat-form-field> and then the Material style is applied.

<input matInput .... /> on its own is not sufficient.

You need:

<mat-form-field>
    <input matInput .... />
</mat-form-field>


问:
ValueError: Error when checking input: expected dense_1_input to have shape (180,) but got array with shape (1,)
My learning model is as follows (using Keras).

```<code>model = Sequential()
model.add(Dense(100, activation='relu', input_shape = (X_train.shape[0],)))
model.add(Dense(500, activation='relu'))
model.add(Dense(2, activation='softmax'))
</code>```

My input data X_train is an array of shape (180,) and the corresponding y_train containing labels is also an array of shape (180,). I tried to compile and fit the model as follows.

```<code>model.compile(loss="sparse_categorical_crossentropy",
             optimizer="adam",
             metrics=['accuracy'])

model.fit(X_train, y_train, epochs = 200)
</code>```

When I run the model.fit(), I encountered the following error:

```<code>ValueError: Error when checking input: expected dense_1_input to have
shape (180,) but got array with shape (1,)
</code>```

I'm not sure what I'm doing wrong since I'm pretty new to deep learning. Any help is appreciated. Thanks.

答:
As @Thomas Schillaci wrote, the problem is that if you write X_train.shape[0] you are taking into account the number of samples of your dataset. But in that line the code want to know how many features you have, so you have to change in X_train.shape[1] in order to have the n° of input.
How many labels do you have?

Body:
My learning model is as follows (using Keras).

model = Sequential()
model.add(Dense(100, activation='relu', input_shape = (X_train.shape[0],)))
model.add(Dense(500, activation='relu'))
model.add(Dense(2, activation='softmax'))

My input data X_train is an array of shape (180,) and the corresponding y_train containing labels is also an array of shape (180,). I tried to compile and fit the model as follows.

model.compile(loss="sparse_categorical_crossentropy",
             optimizer="adam",
             metrics=['accuracy'])

model.fit(X_train, y_train, epochs = 200)

When I run the model.fit(), I encountered the following error:

ValueError: Error when checking input: expected dense_1_input to have
shape (180,) but got array with shape (1,)

I'm not sure what I'm doing wrong since I'm pretty new to deep learning. Any help is appreciated. Thanks.


问:
select row from orc snappy table in hive
I have created a table employee_orc which is orc format with snappy compression.

```<code>    create table employee_orc(emp_id string, name string)
 row format delimited fields terminated by '\t' stored as orc tblproperties("orc.compress"="SNAPPY");
</code>```

I have uploaded data into the table using the insert statement.

```<code>employee_orc table has 1000 records.
</code>```

When I run the below query, it shows all the records

```<code>select * from employee_orc;
</code>```

But when run the below query, it shows zero results even though the records exist.

```<code>select * from employee_orc where emp_id = "EMP456";
</code>```

Why I am unable to retrieve a single record from the employee_orc table?

答:
On my part, I don't understand why you want to specify a delimiter in ORC. Are you confusing CSV and ORC or external vs managed ?
I advice you to create your table differently

create table employee_orc(emp_id string, name string)
stored as ORC
TBLPROPERTIES (
"orc.compress"="ZLIB");

Body:
I have created a table employee_orc which is orc format with snappy compression.

    create table employee_orc(emp_id string, name string)
 row format delimited fields terminated by '\t' stored as orc tblproperties("orc.compress"="SNAPPY");

I have uploaded data into the table using the insert statement.

employee_orc table has 1000 records.

When I run the below query, it shows all the records

select * from employee_orc;

But when run the below query, it shows zero results even though the records exist.

select * from employee_orc where emp_id = "EMP456";

Why I am unable to retrieve a single record from the employee_orc table?


答:
In base R:

cols <- c("shelf", "value")
subset(rbind(setNames(df_input[1:2], cols),
             setNames(df_input[3:4], cols),
             setNames(df_input[5:6], cols)),
       shelf == "A" | shelf == "B" | shelf == "NA"))

#>    shelf value
#> 1      A 20000
#> 2      A 23000
#> 3      B 26000
#> 10     A 21000
#> 11     A 22000
#> 17    NA    NA
```

Title: Fetch Specific field and cell value next to it based on a condition using R

Body:
I have a dataframe and I want to fetch the value of the column and the cell value next to it in separate new columns. The condition is that I want only those shelves where item A and B are present and their respective selling price. For anything else it should fetch NA. I have given an example of the input and expected output. I tried various options like concatenating and using regular expression but couldnot achieve the desired result.

df_input <- data.frame (shelf_1  = c('A','A','B','C','C','D'),
                  selling_price_s1 = c(20000, 23000, 26000,25000,24000,20000),
                  shelf_2  = c('D','C','C','A','A','D'),
                  selling_price_s2 = c(23000, 25000, 25000,21000,22000,25000),
                  shelf_3  = c('C','D','D','C','NA','C'),
                  selling_price_s3 = c(20000, 23000, 26000,25000,NA,20000),
                  )

df_expected <- data.frame (shelf  = c('A','A','B','A','A','NA'),
                  selling_price = c(20000, 23000, 26000,21000,22000,NA),
                  )


问:
Get parent name
With what method or variable can I find out the name of the parent object in this example? That is, during the event of hovering the mouse over the first button, get the name $GetParentName = "Button01", second $GetParentName = "Button02", third $GetParentName = "Button03". $GetParentName is [string].

If instead of the variable $GetParentName to apply $This, then the variable $This allows you to get the values of the object, but does not get the name of the object. But how to get the name of the object? Thanks

Edited: without using $This.Name.

```<code>$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    Button01 = [System.Windows.Forms.Button] @{ Top = 0 }
    Button02 = [System.Windows.Forms.Button] @{ Top = 30 }
    Button03 = [System.Windows.Forms.Button] @{ Top = 60 }
}

$Script = { Write-host $GetParentName }

1..3 | % {

    $A["Button0$_"].Add_MouseEnter($Script)

    $A.Main.Controls.Add($A["Button0$_"])
}

[void]$A.Main.ShowDialog()
</code>```

答:
You need to set the .Name property for the button controls if you want to get their names inside the MouseEnter script:

```<code>Add-Type -AssemblyName System.Windows.Forms

$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    Button01 = [System.Windows.Forms.Button] @{ Top = 0  ; Name = 'Button01'}
    Button02 = [System.Windows.Forms.Button] @{ Top = 30 ; Name = 'Button02'}
    Button03 = [System.Windows.Forms.Button] @{ Top = 60 ; Name = 'Button03'}
}

$Script = { Write-host $this.Name }

1..3 | ForEach-Object {

    $A["Button0$_"].Add_MouseEnter($Script)

    $A.Main.Controls.Add($A["Button0$_"])
}

[void]$A.Main.ShowDialog()

$A.Main.Dispose()
</code>```

Edit

Creating and naming the buttons inside the ForEach-Object loop could save you typing the name for each button:

```<code>Add-Type -AssemblyName System.Windows.Forms

$A = @{
    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }
}

$Script = { Write-host $this.Name }

1..3 | ForEach-Object {
    $A["Button0$_"] = [System.Windows.Forms.Button] @{ Top = ($_ -1) * 30 ; Name = "Button0$_"}
    $A["Button0$_"].Add_MouseEnter($Script)

    $A.Main.Controls.Add($A["Button0$_"])
}

[void]$A.Main.ShowDialog()

$A.Main.Dispose()
</code>```

Title: Get parent name

Body:
With what method or variable can I find out the name of the parent object in this example? That is, during the event of hovering the mouse over the first button, get the name $GetParentName = "Button01", second $GetParentName = "Button02", third $GetParentName = "Button03". $GetParentName is [string].

If instead of the variable $GetParentName to apply $This, then the variable $This allows you to get the values of the object, but does not get the name of the object. But how to get the name of the object? Thanks

Edited: without using $This.Name.

$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    Button01 = [System.Windows.Forms.Button] @{ Top = 0 }
    Button02 = [System.Windows.Forms.Button] @{ Top = 30 }
    Button03 = [System.Windows.Forms.Button] @{ Top = 60 }
}

$Script = { Write-host $GetParentName }

1..3 | % {

    $A["Button0$_"].Add_MouseEnter($Script)

    $A.Main.Controls.Add($A["Button0$_"])
}

[void]$A.Main.ShowDialog()

Body:
You need to set the .Name property for the button controls if you want to get their names inside the MouseEnter script:

Add-Type -AssemblyName System.Windows.Forms

$A = @{

    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }

    Button01 = [System.Windows.Forms.Button] @{ Top = 0  ; Name = 'Button01'}
    Button02 = [System.Windows.Forms.Button] @{ Top = 30 ; Name = 'Button02'}
    Button03 = [System.Windows.Forms.Button] @{ Top = 60 ; Name = 'Button03'}
}

$Script = { Write-host $this.Name }

1..3 | ForEach-Object {

    $A["Button0$_"].Add_MouseEnter($Script)

    $A.Main.Controls.Add($A["Button0$_"])
}

[void]$A.Main.ShowDialog()

$A.Main.Dispose()

Edit

Creating and naming the buttons inside the ForEach-Object loop could save you typing the name for each button:

Add-Type -AssemblyName System.Windows.Forms

$A = @{
    Main = [System.Windows.Forms.Form] @{ StartPosition = 'CenterParent' }
}

$Script = { Write-host $this.Name }

1..3 | ForEach-Object {
    $A["Button0$_"] = [System.Windows.Forms.Button] @{ Top = ($_ -1) * 30 ; Name = "Button0$_"}
    $A["Button0$_"].Add_MouseEnter($Script)

    $A.Main.Controls.Add($A["Button0$_"])
}

[void]$A.Main.ShowDialog()

$A.Main.Dispose()


问:
Replace() with Split()
I need to enter a "0" in case there's only one digit after the comma, how does replace() work in this situation?

var a = "2x 250,5";

console.log(a.replace(a.split(",")[1], a.split(",")[1] + 0));

//expected result
// 2x 250,50

//Output
//2x 2500,5```

Title: Replace() with Split()

Body:
let a = "2x 250,0";

console.log([a.split(','), a.split(',').pop().length===1 ? '0':null].join(''));


问:
admin.site.register(Question) doesn't work
i am new to Django and python, and i want to start django admin with official exercises

i'm okay with running server. but questions doesn't show up.

my code is :

admin.py

```<code>from django.contrib import admin
from .models import Question

admin.site.register(Question)
</code>```

thank you for reading my question

答:
1) You should have a model named Question in your app's models.py file

2)You should run makemigrations and migrate commands

Body:
i am new to Django and python, and i want to start django admin with official exercises

i'm okay with running server. but questions doesn't show up.

my code is :

admin.py

from django.contrib import admin
from .models import Question

admin.site.register(Question)

thank you for reading my question


问:
How to make a table in matlab?
I want to make a simple table in Matlab, so I used this code:

```<code>T := table(a = 13, c = 42)
</code>```

But it gives an error:

xrd
  Undefined function 'T' for input arguments of type
  'char'.
  Error in xrd (line 1)
  T := table(a = 13, c = 42)

How can I fix this?

答:
As the MATLAB way to initialize a table with predefined column names seems particularly obscure to me, I am documenting it here.

Be aware that I use the cell2table function once to initialize the table.
From then on, jobTable.FOO = ...; will enable you to create further columns FOO.

```<code>jobTable = cell2table([{'running'}, {'queued'}, {'finished'}]', 'VariableNames', {'state'});
jobTable.rank = [0, 1, -1]';
jobTable.workflowId = [0, 29039, 28000]';
</code>```

You can transform the table into a struct, which is e.g. more useful for communication with java, by using: table2struct(jobTable).

Title: How to make a table in matlab?

Body:
I want to make a simple table in Matlab, so I used this code:

T := table(a = 13, c = 42)

But it gives an error:

xrd
  Undefined function 'T' for input arguments of type
  'char'.
  Error in xrd (line 1)
  T := table(a = 13, c = 42)

How can I fix this?

Body:
As the MATLAB way to initialize a table with predefined column names seems particularly obscure to me, I am documenting it here.

Be aware that I use the cell2table function once to initialize the table.
From then on, jobTable.FOO = ...; will enable you to create further columns FOO.

jobTable = cell2table([{'running'}, {'queued'}, {'finished'}]', 'VariableNames', {'state'});
jobTable.rank = [0, 1, -1]';
jobTable.workflowId = [0, 29039, 28000]';

You can transform the table into a struct, which is e.g. more useful for communication with java, by using: table2struct(jobTable).


问:
converting strings to formula objects in Julia
I have a dataframe in Julia with less than 10 column names. I want to generate a list of all possible formulas that could be fed into a linear model (eg, [Y~X1+X2+X3, Y~X1+X2, ....]). I can accomplish this easily with combinations() and string versions of the column names. However, when I try to convert the strings into Formula objects, it breaks down. Looking at DataFrames.jl documentation, it seems like one can only construct Formulas from "expressions" and I can indeed make a list of individual column names as expressions. Is there any way I can somehow join together a bunch of different expressions using the "+" operator programmatically such that the resulting composite expression can then be passed into RHS of the Formula constructor? My impulse is to search for some function that will convert an arbitrary string into the equivalent expression, but not sure if that is correct.

答:
Here is some actual working code, because I have been struggling with getting a similar problem to work. Please note this is Julia version 1.3.1 so parse is now Meta.parse and instead of combinations I used IterTools.subsets.

```<code>using RDatasets, DataFrames, IterTools, GLM
airquality = rename(dataset("datasets", "airquality"), "Solar.R" => "Solar_R")
predictors = setdiff(names(airquality), [:Temp])
for combination in subsets(predictors)
  formula = FormulaTerm(Term(:Temp), Tuple(Term.(combination)))
  if length(combination) > 0
    @show lm(formula, airquality)
  end
end
</code>```

Body:
Here is some actual working code, because I have been struggling with getting a similar problem to work. Please note this is Julia version 1.3.1 so parse is now Meta.parse and instead of combinations I used IterTools.subsets.

using RDatasets, DataFrames, IterTools, GLM
airquality = rename(dataset("datasets", "airquality"), "Solar.R" => "Solar_R")
predictors = setdiff(names(airquality), [:Temp])
for combination in subsets(predictors)
  formula = FormulaTerm(Term(:Temp), Tuple(Term.(combination)))
  if length(combination) > 0
    @show lm(formula, airquality)
  end
end


问:
Hackerrank: Climbing the Leaderboard
i have a deal with a hackerrank algorithm problem.

It works at all cases, except 6-7-8-9. It gives timeout error. I had spent so much time at this level. Someone saw where is problem?

```<code>static long[] climbingLeaderboard(long[] scores, long[] alice)
{
    //long[] ranks = new long[scores.Length];
    long[] aliceRanks = new long[alice.Length]; // same length with alice length
    long lastPoint = 0;
    long lastRank;
    for (long i = 0; i < alice.Length; i++)
    {
        lastPoint = scores[0];
        lastRank = 1;
        bool isIn = false; // if never drop in if statement
        for (long j = 0; j < scores.Length; j++)
        {
            if (lastPoint != scores[j])  //if score is not same, raise the variable
            {
                lastPoint = scores[j];
                lastRank++;
            }

            if (alice[i] >= scores[j])
            {
                aliceRanks[i] = lastRank;
                isIn = true;
                break;
            }
            aliceRanks[i] = !isIn & j + 1 == scores.Length ? ++lastRank : aliceRanks[i]; //drop in here
        }
    }
    return aliceRanks;
}
</code>```

答:
```<code>static int[] climbingLeaderboard(int[] scores, int[] alice) {

      int[] uniqueScores = IntStream.of(scores).distinct().toArray();

        int [] rank = new int [alice.length];

        int startIndex=0;

        for(int j=alice.length-1; j>=0;j--) {

        for(int i=startIndex; i<=uniqueScores.length-1;i++) {

            if (alice[j]<uniqueScores[uniqueScores.length-1]){
                    rank[j]=uniqueScores.length+1;
                    break;
                }

            else if(alice[j]>=uniqueScores[i]) {
                    rank[j]=i+1;
                    startIndex=i;
                    break;
                }

                else{continue;}

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

Title: Hackerrank: Climbing the Leaderboard

Body:
i have a deal with a hackerrank algorithm problem.

It works at all cases, except 6-7-8-9. It gives timeout error. I had spent so much time at this level. Someone saw where is problem?

static long[] climbingLeaderboard(long[] scores, long[] alice)
{
    //long[] ranks = new long[scores.Length];
    long[] aliceRanks = new long[alice.Length]; // same length with alice length
    long lastPoint = 0;
    long lastRank;
    for (long i = 0; i < alice.Length; i++)
    {
        lastPoint = scores[0];
        lastRank = 1;
        bool isIn = false; // if never drop in if statement
        for (long j = 0; j < scores.Length; j++)
        {
            if (lastPoint != scores[j])  //if score is not same, raise the variable
            {
                lastPoint = scores[j];
                lastRank++;
            }

            if (alice[i] >= scores[j])
            {
                aliceRanks[i] = lastRank;
                isIn = true;
                break;
            }
            aliceRanks[i] = !isIn & j + 1 == scores.Length ? ++lastRank : aliceRanks[i]; //drop in here
        }
    }
    return aliceRanks;
}


问:
How to access VueJS Mixin within imported JS Library
I have a 'commonLibrary.js' which I've imported into my Vue app.

A small snippet of this library (and a good example) is:

var defaultDecimalRounding=3

function formatNumber(number) {
    if (isNaN(number.value) == true) { return '-' }
    return numberWithCommas(parseFloat(number.value, 2).toFixed(defaultDecimalRounding));
}```
</div>
</div>
</p>

<p>So whenver "formatNumber" is called, it returns a number to a decimal rounding, based on the variable "defaultDecimalRounding"</p>

<p>What I'd like to do is move this defaultDecimalRounding variable out of the commonLibrary.js and into my Vue App so it can be changed within the app.</p>

<p>I've created a Mixin, as follows:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Vue.mixin({
    data: function () {
        return {
            get defaultDecimalRounding() { return 3 },
        }
    },
});</code>```

But I can't seem to get my formatNumber function to read this defaultDecimalRounding Mixin.

I don't mind doing a code-rewrite for the commonLibrary.js, there's only a dozen or so functions in there, but it would be nice to know how to get VueJS and an imported JS library talking to each other for future projects.

edit
commonLibrary.js is imported as:

```<code>import common from './scripts/common.js';
const commonLibrary = {
    install() {
        Vue.common = common
        Vue.prototype.$common = common
    }
}
Vue.use(commonLibrary)
</code>```

答:
Do as following:

in common.js

```<code>var defaultDecimalRounding = 3;

// use another name for export cause previous name  already is declared
export const defaultDecimal = defaultDecimalRounding;

function formatNumber(number) {
    if (isNaN(number.value) == true) { return '-' }
    return numberWithCommas(parseFloat(number.value, 2).toFixed(defaultDecimalRounding));
}
</code>```

in your vue app:

```<code>import { defaultDecimal } from "./common";

Vue.mixin({
  data: function() {
    return {
      defaultDecimal : defaultDecimal
    };
  }
});
</code>```

Body:
I have a 'commonLibrary.js' which I've imported into my Vue app.

A small snippet of this library (and a good example) is:

var defaultDecimalRounding=3

function formatNumber(number) {
    if (isNaN(number.value) == true) { return '-' }
    return numberWithCommas(parseFloat(number.value, 2).toFixed(defaultDecimalRounding));
}

So whenver "formatNumber" is called, it returns a number to a decimal rounding, based on the variable "defaultDecimalRounding"

What I'd like to do is move this defaultDecimalRounding variable out of the commonLibrary.js and into my Vue App so it can be changed within the app.

I've created a Mixin, as follows:

Vue.mixin({
    data: function () {
        return {
            get defaultDecimalRounding() { return 3 },
        }
    },
});

But I can't seem to get my formatNumber function to read this defaultDecimalRounding Mixin.

I don't mind doing a code-rewrite for the commonLibrary.js, there's only a dozen or so functions in there, but it would be nice to know how to get VueJS and an imported JS library talking to each other for future projects.

edit
commonLibrary.js is imported as:

import common from './scripts/common.js';
const commonLibrary = {
    install() {
        Vue.common = common
        Vue.prototype.$common = common
    }
}
Vue.use(commonLibrary)

Body:
Do as following:

in common.js

var defaultDecimalRounding = 3;

// use another name for export cause previous name  already is declared
export const defaultDecimal = defaultDecimalRounding;

function formatNumber(number) {
    if (isNaN(number.value) == true) { return '-' }
    return numberWithCommas(parseFloat(number.value, 2).toFixed(defaultDecimalRounding));
}

in your vue app:

import { defaultDecimal } from "./common";

Vue.mixin({
  data: function() {
    return {
      defaultDecimal : defaultDecimal
    };
  }
});


问:
How to pass a class instance reference as a generic type in flutter
My objective is to create a method that would take the arguments of the buildcontext and screen reference and rout it accordingly with the provided details. My partially in complete code as bellow. help would much appreciate.

My Helper class

```<code>import 'package:flutter/material.dart';

class Utils {

 static routToPage <T> (BuildContext context,  <T> page){
  Navigator.of(context).push(MaterialPageRoute(builder: (context) =>page);
 }
}
</code>```

The class I wants to access it

```<code>import './utils'
import 'package:flutter/material.dart';

class Home extends StatelessWidget {
   navigateToPage(){
    Utils.rout(BuildContext context, PageTwo())
   }
}
</code>```

For now as the syntax are wrong I'm stuck with my approach.

答:
Well, I think no need to create static class. Here is a working example.

Paste the below method in a dart file.

```<code>void navigateToScreen(BuildContext context, Widget widget) {
  Navigator.of(context).push(MaterialPageRoute(
    builder: (_) => widget,
  ));
}
</code>```

And use the class for navigating, like

```<code>navigateToScreen(buildContext, YourNavigationScreen());
</code>```

Body:
My objective is to create a method that would take the arguments of the buildcontext and screen reference and rout it accordingly with the provided details. My partially in complete code as bellow. help would much appreciate.

My Helper class

import 'package:flutter/material.dart';

class Utils {

 static routToPage <T> (BuildContext context,  <T> page){
  Navigator.of(context).push(MaterialPageRoute(builder: (context) =>page);
 }
}

The class I wants to access it

import './utils'
import 'package:flutter/material.dart';

class Home extends StatelessWidget {
   navigateToPage(){
    Utils.rout(BuildContext context, PageTwo())
   }
}

For now as the syntax are wrong I'm stuck with my approach.

Body:
Well, I think no need to create static class. Here is a working example.

Paste the below method in a dart file.

void navigateToScreen(BuildContext context, Widget widget) {
  Navigator.of(context).push(MaterialPageRoute(
    builder: (_) => widget,
  ));
}

And use the class for navigating, like

navigateToScreen(buildContext, YourNavigationScreen());


问:
C# how to map two section of appsetting and take the unique settings into single class object
I have the following sections in my appsettings. I am using asp.net core webapi application.

```<code>  "security": {
    "instance": "https://login.microsoftonline.com/",
    "domain": "domain.com",
    "tenantId": "tenantid",
    "clientId": "sameclientid"
  },
  "powerBI": {
    "resourceUri": "resourceurl",
    "authorityUri": "authorityurl",
    "extraUrl": "https://api.powerbi.com/",
    "clientId": "sameclientid",
    "clientSecret": "secret"
  }
</code>```

i need to map to single class

```<code>  class MapperClass {
    public string Instance {get;set;}
    public string Domain {get;set;}
    public string TenantId {get;set;}
    public string ClientId {get;set;}
    public string ClientSecret {get;set;}
    public string ExtraUri {get;set;}
  }
</code>```

Is there a way to merge or union the above two section and get it mapped to the final MapperClass?

Thanks

答:
Since the source document is a JSON, you can parse it to JObject and then get requested properties like this:</p>

```<code>var jsonString = "your JSON";
var jObject = JObject.Parse(jsonString);
var myClass = new MapperClass
{
    Instance = jObject["security"]["instance"].Value<string>(),
    ClientSecret = jObject["powerBI"]["clientSecret"].Value<string>()
};
</code>```

Body:
I have the following sections in my appsettings. I am using asp.net core webapi application.

  "security": {
    "instance": "https://login.microsoftonline.com/",
    "domain": "domain.com",
    "tenantId": "tenantid",
    "clientId": "sameclientid"
  },
  "powerBI": {
    "resourceUri": "resourceurl",
    "authorityUri": "authorityurl",
    "extraUrl": "https://api.powerbi.com/",
    "clientId": "sameclientid",
    "clientSecret": "secret"
  }

i need to map to single class

  class MapperClass {
    public string Instance {get;set;}
    public string Domain {get;set;}
    public string TenantId {get;set;}
    public string ClientId {get;set;}
    public string ClientSecret {get;set;}
    public string ExtraUri {get;set;}
  }

Is there a way to merge or union the above two section and get it mapped to the final MapperClass?

Thanks

Body:
Since the source document is a JSON, you can parse it to JObject and then get requested properties like this:

var jsonString = "your JSON";
var jObject = JObject.Parse(jsonString);
var myClass = new MapperClass
{
    Instance = jObject["security"]["instance"].Value<string>(),
    ClientSecret = jObject["powerBI"]["clientSecret"].Value<string>()
};


问:
Wait if code execution finished before a time limit and abort if didn't finish within limit
I have for loop and I need each iteration to take exactly 5 milliseconds.
i.e if the code finishes before the 5 milliseconds the iteration should wait until the 5 milliseconds pass, and if it takes more than 5 milliseconds the loop should ignore it and go to next iteration.

I tried this code but it is not accurate and it doesn't help to abort to next iteration if it takes more time

```<code>import time

for i in range(N):
    now = time.time_ns()
    do_something(i)
    time.sleep(0.005 - (time.time_ns() - now -3)*1e-9)
</code>```

I used time_ns() as I assumed it would be more accurate than time() but it didn't help much

答:
Save init time at the beginning

and use in your computations. Here's my example

```<code>import random
import time

N = 10
D = 0.5
T0 = time.time()

def do_something(msg):
    """Sleep 0 to 1 seconds"""
    time.sleep(random.random())
    print(msg)

for i in range(N):
    # check if we're overtime
    if T0 + (i+1)*D < time.time():
        continue

    do_something(i)

    # use modulo to compute sleep duration
    time.sleep(
        D - (time.time() - T0) % D
    )
</code>```

And the output. Notice some numbers are missing and that it takes 10×0.5 = 5 seconds.

```<code>$ time python3 aly.py
0
1
3
5
6
8

real    0m5.030s
user    0m0.028s
sys     0m0.004s
</code>```

About time_ns: time.sleep needs float, so using integer nanoseconds is meaningless.

Body:
I have for loop and I need each iteration to take exactly 5 milliseconds.
i.e if the code finishes before the 5 milliseconds the iteration should wait until the 5 milliseconds pass, and if it takes more than 5 milliseconds the loop should ignore it and go to next iteration.

I tried this code but it is not accurate and it doesn't help to abort to next iteration if it takes more time

import time

for i in range(N):
    now = time.time_ns()
    do_something(i)
    time.sleep(0.005 - (time.time_ns() - now -3)*1e-9)

I used time_ns() as I assumed it would be more accurate than time() but it didn't help much

Body:
Save init time at the beginning

and use in your computations. Here's my example

import random
import time

N = 10
D = 0.5
T0 = time.time()

def do_something(msg):
    """Sleep 0 to 1 seconds"""
    time.sleep(random.random())
    print(msg)

for i in range(N):
    # check if we're overtime
    if T0 + (i+1)*D < time.time():
        continue

    do_something(i)

    # use modulo to compute sleep duration
    time.sleep(
        D - (time.time() - T0) % D
    )

And the output. Notice some numbers are missing and that it takes 10×0.5 = 5 seconds.

$ time python3 aly.py
0
1
3
5
6
8

real    0m5.030s
user    0m0.028s
sys     0m0.004s

About time_ns: time.sleep needs float, so using integer nanoseconds is meaningless.


问:
Can a CSS overflow scrollbar be controlled in Javascript?
I have a div with a class overflow: auto;  Is there a way to control this scrollbar when it appears?

I have a ajax photo gallery (no page refresh) where some caption text is in a div, but the content is of varying length.  If you scroll down in this div and then advance to the next slide, the scrollbar does not go back to the top.  So, I was wondering if there was a way to control this scrollbar.  Thanks.

答:
To move the vertical bar back to the top on an overflowed element myControl , you must do

```<code>$("#myControl").scrollTop(0);
</code>```

or, in case of horizontal bar, to move it to the beginning (left)

```<code>$("#myControl").scrollLeft(0);
</code>```

If you want to hide the scroll bars, you must do this CSS

```<code>#myControl {
    overflow: hidden;
}
</code>```

You are assuming that the next slide resides on the top. If you have absolute positionated slides, you might better do the following, to ensure that you scroll to the correct nextSlide location:

```<code>var nextSlidePos = $("#slide" + nextSlide).position();
$("#myControl").scrollTop( nextSlidePos.top ).scrollLeft( nextSlidePos.left );
</code>```

Body:
To move the vertical bar back to the top on an overflowed element myControl , you must do

$("#myControl").scrollTop(0);

or, in case of horizontal bar, to move it to the beginning (left)

$("#myControl").scrollLeft(0);

If you want to hide the scroll bars, you must do this CSS

#myControl {
    overflow: hidden;
}

You are assuming that the next slide resides on the top. If you have absolute positionated slides, you might better do the following, to ensure that you scroll to the correct nextSlide location:

var nextSlidePos = $("#slide" + nextSlide).position();
$("#myControl").scrollTop( nextSlidePos.top ).scrollLeft( nextSlidePos.left );


问:
Using the OWASP dependencyCheck to generate separate reports for java modules instead of one large report
I'm trying to break the dependency check report generated by my Jenkins CI pipeline into multiple reports (one per module) because having one giant report can get rather large and hard to read.  This is the code I have so far to accomplish this:

```<code>if(fileExists('pom.xml')) {
   def pom = readMavenPom file: 'pom.xml'
   pom.modules.each {
     dependencyCheck additionalArguments: "--scan ./${it} --format CSV --out owasp-reports/${it}-dependency-check-report.csv", odcInstallation: "${env.DEPENDENCY_CHECK}"
     dependencyCheck additionalArguments: "--scan ./${it} --format JSON --out owasp-reports/${it}-dependency-check-report.json", odcInstallation: "${env.DEPENDENCY_CHECK}"
     dependencyCheck additionalArguments: "--scan ./${it} --format HTML --out owasp-reports/${it}-dependency-check-report.html", odcInstallation: "${env.DEPENDENCY_CHECK}"
   }
</code>```

I'm getting files generated with the appropriate names, but no dependencies are scanned.  However, this appropriately generates a large report containing all the child modules

```<code>dependencyCheck additionalArguments: '--scan ./ --format XML --format JSON --format HTML --format CSV --out owasp-reports', odcInstallation: "${env.DEPENDENCY_CHECK}"
</code>```

Any suggestions would be appreciated.

答:
For anyone else this may help, this is the solution I came up with:

```<code>if(fileExists('pom.xml')) {
    def pom = readMavenPom file: 'pom.xml'
    pom.modules.each {
        dir("${it}"){
            sh "mvn org.owasp:dependency-check-maven:aggregate"
            sh "mv target/dependency-check-report.html ../owasp-reports/${it}-dependency-check-report.html"
        }
    }
  }
</code>```

Apparently the problem with using the Jenkins plugin call is that the Jenkins plugin wraps the CLI commands, which don't recognize pom files.

Source: dependecy check could not analyze pom.xml for java

Body:
I'm trying to break the dependency check report generated by my Jenkins CI pipeline into multiple reports (one per module) because having one giant report can get rather large and hard to read.  This is the code I have so far to accomplish this:

if(fileExists('pom.xml')) {
   def pom = readMavenPom file: 'pom.xml'
   pom.modules.each {
     dependencyCheck additionalArguments: "--scan ./${it} --format CSV --out owasp-reports/${it}-dependency-check-report.csv", odcInstallation: "${env.DEPENDENCY_CHECK}"
     dependencyCheck additionalArguments: "--scan ./${it} --format JSON --out owasp-reports/${it}-dependency-check-report.json", odcInstallation: "${env.DEPENDENCY_CHECK}"
     dependencyCheck additionalArguments: "--scan ./${it} --format HTML --out owasp-reports/${it}-dependency-check-report.html", odcInstallation: "${env.DEPENDENCY_CHECK}"
   }

I'm getting files generated with the appropriate names, but no dependencies are scanned.  However, this appropriately generates a large report containing all the child modules

dependencyCheck additionalArguments: '--scan ./ --format XML --format JSON --format HTML --format CSV --out owasp-reports', odcInstallation: "${env.DEPENDENCY_CHECK}"

Any suggestions would be appreciated.

Body:
For anyone else this may help, this is the solution I came up with:

if(fileExists('pom.xml')) {
    def pom = readMavenPom file: 'pom.xml'
    pom.modules.each {
        dir("${it}"){
            sh "mvn org.owasp:dependency-check-maven:aggregate"
            sh "mv target/dependency-check-report.html ../owasp-reports/${it}-dependency-check-report.html"
        }
    }
  }

Apparently the problem with using the Jenkins plugin call is that the Jenkins plugin wraps the CLI commands, which don't recognize pom files.

Source: dependecy check could not analyze pom.xml for java


问:
Is it possible to do a firmware update using the Azure IoT Hub and Blob storage?
I have the azure IoT client running on an STM32H7 with Keil RTX 5 as its operating system. What I want to do is download a binary file from Azure (firmware) and update the firmware on my device (STM32H7).

What I have done:

I have uploaded a binary file to Azure blob storage.
I have got the sample "iothub_client_device_twin_and_methods_sample.c" example working and running correctly (It connects to the Azure IoT hub with no issues)

I want to go about my firmware update by downloading this binary file and then writing it to a storage area on my device, but I think I have the latter part covered.

From my current research, I believe the correct approach to this is to somehow create a cloud to device message containing the binary file.

My question is, based on the above:

What is the correct way to download a binary file from blob storage using the C sdk to my embedded device?

PS: I have seen there is an example for a firmware update using the raspberry pi but I was not able to understand it and modify it for my purpose.

Any help would be very appreciated. Thanks.

Edit: my firmware update will be firmware over the air, hence the need for a way to download it from Azure

Thanks

答:
You can take a look at the way the ESP-IDF implements FOTA:

ESP32 OTA via HTTPS

ESPRESSIG - Over The Air Updates

You can as well take a look at the following AN from NXP:
Firmware Update Using Secondary Bootloader

To download the firmware, you can use raw tcp/ip, http(s), ftp, etc...

If you type "arm bootloader" in google, you will get a lot of useful content:

Why every Cortex-M developer should consider using a bootloader

From Zero to main(): How to Write a Bootloader from Scratch


问:
Append a json object to another json object java
I have a two json objects

```<code>JSONObject org_query = new JSONObject("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");

JSONObject query_form = new JSONObject("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");
</code>```

I want to append the second object to first one inside the key must and form a new JSON object.

Required Output:

```<code>{"query":{"bool":{"must_not":[],"should":[],"must":[{"match_phrase": {"Sales Channel": "Online"}}]}}}
</code>```

I tried this,

```<code>org_query["query"]["bool"]["must"].append(query_form);
</code>```

But shows error.

```<code>array type expected found org.json.jsonarray java
</code>```

How to make it

答:
Not really sure which API you're using but a quick search on Google yielded this result:

The .append method is for adding values into an array.

Try using .put method. This is for adding values to a property by key.

Reference: https://docs.oracle.com/middleware/maf242/mobile/api-ref/oracle/adfmf/json/JSONObject.html

For more examples, see this other answer: https://stackoverflow.com/a/30006004/7119882

Body:
I have a two json objects

JSONObject org_query = new JSONObject("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");

JSONObject query_form = new JSONObject("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");

I want to append the second object to first one inside the key must and form a new JSON object.

Required Output:

{"query":{"bool":{"must_not":[],"should":[],"must":[{"match_phrase": {"Sales Channel": "Online"}}]}}}

I tried this,

org_query["query"]["bool"]["must"].append(query_form);

But shows error.

array type expected found org.json.jsonarray java

How to make it