问:
element.loader.split is not a function
I get this error </p>

```<code>/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:58
    if(element.loader) return element.loader.split("!");                                    ^TypeError: element.loader.split is not a function
at getLoadersFromObject (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:58:43)
at LoadersList.<anonymous> (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:78:12)
at Array.map (native)
</code>```

<p>this is my webpack </p>

```<code>var webpack = require("webpack");
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {

entry: {app: './src/app.js' },
  output: {filename: 'public/build/bundle.js',
        sourceMapFilename: 'public/build/bundle.map' },
  module: {
    loaders: [
      { test: /\.(js|jsx)$/, loader: 'babel-loader',query: {
        presets: ['stage-0','react','es2015'],
        plugins: ["transform-decorators-legacy","transform-class-properties"]
    } },
      { test: /\.css$/, loaders: [ 'style-loader', 'css-loader' ] },
      { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=public/fonts/[name].[ext]'  },
      {test: /\.(jpe?g|png|gif|svg)$/i,    loaders: [
      'file?hash=sha512&digest=hex&name=[hash].[ext]',
      'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
    ]}
    ]
  }
}
</code>```

答:
The problem is in your last loader.

```<code>{test: /\.(jpe?g|png|gif|svg)$/i,    loader: [
  'file?hash=sha512&digest=hex&name=[hash].[ext]',
  'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]}
</code>```

That has an array, not a string. loader expects a string, loaders expects an array. Change the key to loaders, plural:

```<code>{test: /\.(jpe?g|png|gif|svg)$/i,    loaders: [
  'file?hash=sha512&digest=hex&name=[hash].[ext]',
  'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]}
</code>```

Title: element.loader.split is not a function

Body:
I get this error

/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:58
    if(element.loader) return element.loader.split("!");                                    ^TypeError: element.loader.split is not a function
at getLoadersFromObject (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:58:43)
at LoadersList.<anonymous> (/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:78:12)
at Array.map (native)

this is my webpack

var webpack = require("webpack");
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {

entry: {app: './src/app.js' },
  output: {filename: 'public/build/bundle.js',
        sourceMapFilename: 'public/build/bundle.map' },
  module: {
    loaders: [
      { test: /\.(js|jsx)$/, loader: 'babel-loader',query: {
        presets: ['stage-0','react','es2015'],
        plugins: ["transform-decorators-legacy","transform-class-properties"]
    } },
      { test: /\.css$/, loaders: [ 'style-loader', 'css-loader' ] },
      { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=public/fonts/[name].[ext]'  },
      {test: /\.(jpe?g|png|gif|svg)$/i,    loaders: [
      'file?hash=sha512&digest=hex&name=[hash].[ext]',
      'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
    ]}
    ]
  }
}

Body:
The problem is in your last loader.

{test: /\.(jpe?g|png|gif|svg)$/i,    loader: [
  'file?hash=sha512&digest=hex&name=[hash].[ext]',
  'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]}

That has an array, not a string. loader expects a string, loaders expects an array. Change the key to loaders, plural:

{test: /\.(jpe?g|png|gif|svg)$/i,    loaders: [
  'file?hash=sha512&digest=hex&name=[hash].[ext]',
  'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]}


来源: stackexchange

问:
In python, how can I use regex to replace square bracket with parentheses
I have a list :list = [1,2,3]. And I would like to convert that into a string with parentheses: string = (1,2,3).

Currently I am using string replace string = str(list).replace('[','(').replace(']',')'). But I think there is a better way using regex.sub. But I have no idea how to do it. Thanks a lot

答:
There are a billion ways to do this, as demonstrated by all the answers. Here's another one:

```<code>my_list = [1,2,3]
my_str = "(%s)" % str(my_list).strip('[]')
</code>```

or make it recyclable:

```<code>list_in_parens = lambda l: "(%s)" % str(l).strip('[]')
my_str = list_in_parens(my_list)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There are a billion ways to do this, as demonstrated by all the answers. Here's another one:

my_list = [1,2,3]
my_str = "(%s)" % str(my_list).strip('[]')

or make it recyclable:

list_in_parens = lambda l: "(%s)" % str(l).strip('[]')
my_str = list_in_parens(my_list)


问:
How to get schemaspy to see the mysql connector?
I've just downloaded schemaspy and it is working perfectly apart from one thing. I always have to specify the path to the mysql connector with the -dp option.

If I don't specify it, I get this error:

```<code>java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Failed to load driver 'com.mysql.jdbc.Driver'
This entry doesn't point to a valid file/directory: [/mysql/mysql-connector-java-5.1.6-  bin.jar]
</code>```

The path (symlink to /usr/share/java/mysql-connector-java-5.1.28.jar or whatever version you have) is:

```<code>/usr/share/java/mysql-connector-java.jar
</code>```

And it is on the $CLASSPATH.

Also, don't expect -p prompt for a password.

答:
Create then a script with the java statement and save the path to the mysql-connector as an enviroment variable and pass it to the -dp.

I had the common issues about the mysql-connector and the dot executable file. It's not necessary to restart the machine if you pass the correct value to -gv, believe me. I've installed the Graphviz and found the mysql-connector performing a sorted search of *.jar files.

The following lines are how I executed the statement.

```<code>java
-jar schemaSpy.jar
-t mysql
-o library
-host localhost
-db dummyDB
-u user
-p user
-dp C:\Oracle\Middleware\Oracle_Home\oracle_common\modules\mysql-connector-java-commercial-5.1.22\mysql-connector-java-commercial-5.1.22-bin.jar
-gv "C:\Program Files (x86)\Graphviz2.38"
</code>```

Body:
I've just downloaded schemaspy and it is working perfectly apart from one thing. I always have to specify the path to the mysql connector with the -dp option.

If I don't specify it, I get this error:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Failed to load driver 'com.mysql.jdbc.Driver'
This entry doesn't point to a valid file/directory: [/mysql/mysql-connector-java-5.1.6-  bin.jar]

The path (symlink to /usr/share/java/mysql-connector-java-5.1.28.jar or whatever version you have) is:

/usr/share/java/mysql-connector-java.jar

And it is on the $CLASSPATH.

Also, don't expect -p prompt for a password.

Body:
Create then a script with the java statement and save the path to the mysql-connector as an enviroment variable and pass it to the -dp.

I had the common issues about the mysql-connector and the dot executable file. It's not necessary to restart the machine if you pass the correct value to -gv, believe me. I've installed the Graphviz and found the mysql-connector performing a sorted search of *.jar files.

The following lines are how I executed the statement.

java
-jar schemaSpy.jar
-t mysql
-o library
-host localhost
-db dummyDB
-u user
-p user
-dp C:\Oracle\Middleware\Oracle_Home\oracle_common\modules\mysql-connector-java-commercial-5.1.22\mysql-connector-java-commercial-5.1.22-bin.jar
-gv "C:\Program Files (x86)\Graphviz2.38"


问:
How to display submenu on dropdown using positioning and CSS?
I have this simple navigation menu for my design. But the problem is I can't display the sub menu when hovered. Is there any way to solve this? Or does my CSS has some missing styles?

nav ul {list-style-type: none; overflow: hidden; background: #000; position: relative;}
nav li {float: left;}
nav li > a {padding: 15px 15px; display: inline-block; text-decoration: none; color: white; text-align: center;}
nav li > a:hover {background: violet;}

nav ul ul { position: absolute; background: green; top: 100%;}
nav ul ul li > a:hover {color: red;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>sample UL</title>
    <style media="screen">

    </style>
  </head>
  <body>
    <nav>
      <ul>
        <li>Home</li>
        <li>Menu 1</li>
        <ul>
          <li>submenu 1</li>
          <li>submenu 2</li>
        </ul>
      </ul>
    </nav>
  </body>
</html></code>```

答:
```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>sample UL</title>
    <style media="screen">
    </style>
  </head>
  <body>
    <nav class="cf">
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Menu 1</a>
          <ul class="submenu">
            <li><a href="#">submenu 1</a></li>
            <li><a href="#">submenu 2</a></li>
          </ul></li>
      </ul>
    </nav>
  </body>
</html>
</code>```

Please refer Clearfix

Also given class name to nav as cf and inner ul as submenu

```<code>.cf:before, .cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

.cf {
    zoom:1;
}

nav {
    background: #333A31;
    height: 2.3em;
}
ul, li {
    margin: 0;
    padding: 0;
    list-style: none;
    float: left;
}
ul {
    background: #D5333C;
    height: 2em;
    width: 100%;
}
li {
    position: relative;
}
li a {
    display: block;
    line-height: 2em;
    padding: 0 1em;
    color: white;
    text-decoration: none;
}
li a:hover {
    background: #9155311;
    height: 2em;
    padding-top: .3em;
    position: relative;
    top: -.3em;
    border-radius: .3em .3em 0 0;
}
.current, a:hover.current {
    background: #AD9B7F;
    color: #eee;
    padding-top: .3em;
    border-radius: .3em .3em 0 0;
    position: relative;
    top: -.3em;
    border-bottom: .3em solid #917F63;
    cursor: default;
}
/*dropdown menu styles*/
ul.submenu {
    float: none;
    background: #916A31;
    width: auto;
    height: auto;
    position: absolute;
    top: 2em;
    left: -9000em;
}
ul.submenu li {
    float: none;
}
nav li:hover ul {
    left: 0;
}
ul.submenu li a {
    border-bottom: 1px solid white;
    padding: .2em 1em;
    white-space: nowrap;
}
ul.submenu li:last-child a {
    border-bottom: none;
}
ul.submenu li a:hover {
    background: #D5973C;
    height: 2em;
    padding-top: .2em;
    top: 0;
    border-radius: 0;
}
</code>```

Hope this helps.

Body:
I have this simple navigation menu for my design. But the problem is I can't display the sub menu when hovered. Is there any way to solve this? Or does my CSS has some missing styles?

nav ul {list-style-type: none; overflow: hidden; background: #000; position: relative;}
nav li {float: left;}
nav li > a {padding: 15px 15px; display: inline-block; text-decoration: none; color: white; text-align: center;}
nav li > a:hover {background: violet;}

nav ul ul { position: absolute; background: green; top: 100%;}
nav ul ul li > a:hover {color: red;}

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>sample UL</title>

Home

Menu 1

submenu 1

submenu 2

Body:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>sample UL</title>
    <style media="screen">
    </style>
  </head>
  <body>
    <nav class="cf">
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Menu 1</a>
          <ul class="submenu">
            <li><a href="#">submenu 1</a></li>
            <li><a href="#">submenu 2</a></li>
          </ul></li>
      </ul>
    </nav>
  </body>
</html>

Please refer Clearfix

Also given class name to nav as cf and inner ul as submenu

.cf:before, .cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

.cf {
    zoom:1;
}

nav {
    background: #333A31;
    height: 2.3em;
}
ul, li {
    margin: 0;
    padding: 0;
    list-style: none;
    float: left;
}
ul {
    background: #D5333C;
    height: 2em;
    width: 100%;
}
li {
    position: relative;
}
li a {
    display: block;
    line-height: 2em;
    padding: 0 1em;
    color: white;
    text-decoration: none;
}
li a:hover {
    background: #9155311;
    height: 2em;
    padding-top: .3em;
    position: relative;
    top: -.3em;
    border-radius: .3em .3em 0 0;
}
.current, a:hover.current {
    background: #AD9B7F;
    color: #eee;
    padding-top: .3em;
    border-radius: .3em .3em 0 0;
    position: relative;
    top: -.3em;
    border-bottom: .3em solid #917F63;
    cursor: default;
}
/*dropdown menu styles*/
ul.submenu {
    float: none;
    background: #916A31;
    width: auto;
    height: auto;
    position: absolute;
    top: 2em;
    left: -9000em;
}
ul.submenu li {
    float: none;
}
nav li:hover ul {
    left: 0;
}
ul.submenu li a {
    border-bottom: 1px solid white;
    padding: .2em 1em;
    white-space: nowrap;
}
ul.submenu li:last-child a {
    border-bottom: none;
}
ul.submenu li a:hover {
    background: #D5973C;
    height: 2em;
    padding-top: .2em;
    top: 0;
    border-radius: 0;
}

Hope this helps.


问:
Dom rendering issues ngAfterViewInit ionic 2
I am new to Ionic and angular. I notice some peculiar issues.

Whenever I need to access the DOM i have to do a time out query to get dynamic elements.

event if I use ngAfterViewInit - this doesn't work.

So for example when trying to access a dynamically generated url this wont work.

```<code> ngAfterViewInit() {

    var that  = this;
    that.img = that.el.nativeElement.querySelector('img');
    alert(that.src);

}
</code>```

However this will

```<code> ngOnInit() {

      var that  = this;
      setTimeout(function () {  // still buggy need to wait for dom to load.

      that.img = that.el.nativeElement.querySelector('img');

      alert(that.src);

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

I am using ios emulator this is in an Ionic component I have tried the following code which doesn't work without a time out. Because the url which is generated by javascript in the view doesn't get registered without the Dom loading fully.

```<code>import { Component, ElementRef, Input, OnInit, AfterContentInit } from '@angular/core';

    import ImgCache from 'imgcache.js';

    /**
     * This component will be in charge of caching images and use them when the app is offline
     */
    @Component({
      selector: 'lazy-img',
      template: `
        <div [ngClass]="{ 'placeholder': hidden }">
          <img [ngClass]="{ 'active': !hidden }" [src]="src" (load)="load()" (error)="error()" />
        </div>
      `
    })
    export class LazyImgComponent implements AfterContentInit {

      @Input() src: string;

      public img: HTMLImageElement;
      public hidden: boolean;

      constructor(public el: ElementRef) {
        this.hidden = true;
      };

      ngAfterContentInit() {

        var that  = this;

        that.img = that.el.nativeElement.querySelector('img');
        that.img.crossOrigin = 'Anonymous';

        // check if the images are already cached
        ImgCache.isCached(that.src, (path: string, success: boolean) => {

          if (success) {
            alert('cache ' + that.src);
            ImgCache.useCachedFile(that.img, function (){
                alert('now using local copy');
              }, function(){
                alert('could not load from cache');  // desnt work with live reload
              })

          } else {
            alert('no cache ' + that.src)
            ImgCache.useOnlineFile(that.img);
            ImgCache.cacheFile(that.src, () => { });

          }

        });
      }

      /**
       * This function will show the image when it has loaded
       */
      load(): void {
        this.hidden = false;
      }

      /**
       * This function will be triggered when http request fails
       */
      error(): void {
        this.img.remove();
      }

    }
</code>```

答:
Is the dynamically generated content created upon initialization? Or is it dependent on some observable pattern where the URL may not appear until after initialization fully occurs?

Another lifecycle hook you can try is ngAfterContentInit()

Respond after Angular projects external content into the component's
  view.

Called once after the first ngDoCheck().

A component-only hook.

Body:
I am new to Ionic and angular. I notice some peculiar issues.

Whenever I need to access the DOM i have to do a time out query to get dynamic elements.

event if I use ngAfterViewInit - this doesn't work.

So for example when trying to access a dynamically generated url this wont work.

 ngAfterViewInit() {

    var that  = this;
    that.img = that.el.nativeElement.querySelector('img');
    alert(that.src);

}

However this will

 ngOnInit() {

      var that  = this;
      setTimeout(function () {  // still buggy need to wait for dom to load.

      that.img = that.el.nativeElement.querySelector('img');

      alert(that.src);

      }, 300);
    }

I am using ios emulator this is in an Ionic component I have tried the following code which doesn't work without a time out. Because the url which is generated by javascript in the view doesn't get registered without the Dom loading fully.

import { Component, ElementRef, Input, OnInit, AfterContentInit } from '@angular/core';

    import ImgCache from 'imgcache.js';

    /**
     * This component will be in charge of caching images and use them when the app is offline
     */
    @Component({
      selector: 'lazy-img',
      template: `

      `
    })
    export class LazyImgComponent implements AfterContentInit {

      @Input() src: string;

      public img: HTMLImageElement;
      public hidden: boolean;

      constructor(public el: ElementRef) {
        this.hidden = true;
      };

      ngAfterContentInit() {

        var that  = this;

        that.img = that.el.nativeElement.querySelector('img');
        that.img.crossOrigin = 'Anonymous';

        // check if the images are already cached
        ImgCache.isCached(that.src, (path: string, success: boolean) => {

          if (success) {
            alert('cache ' + that.src);
            ImgCache.useCachedFile(that.img, function (){
                alert('now using local copy');
              }, function(){
                alert('could not load from cache');  // desnt work with live reload
              })

          } else {
            alert('no cache ' + that.src)
            ImgCache.useOnlineFile(that.img);
            ImgCache.cacheFile(that.src, () => { });

          }

        });
      }

      /**
       * This function will show the image when it has loaded
       */
      load(): void {
        this.hidden = false;
      }

      /**
       * This function will be triggered when http request fails
       */
      error(): void {
        this.img.remove();
      }

    }


问:
Finding the position of an item in another list from a number in a different list
Developing on my previous question I'm wondering whether there is a way to have an element in a list and find that position in another list and return what is in the position as a variable. for example:

```<code>list1 = [0,1,2,3,4]
list2 = ["0","hello","my","name","is","Daniel"]
</code>```

if the user enters the number 14 the program will return "hello Daniel" in the sense that the computer reads 14 as 1 and 4 and finds the position in list as an example.

I've tired using [list2.index(x) for x in list1] hoping that it would work but I've been unable to change the code so it does work. is there a simple way to do it

答:
You can do something like this :

```<code>input_num = 123
list1 = [0, 1, 2, 3, 4] # if list1 is not dervied from input number
list2 = ["0", "hello", "my", "name", "is", "Daniel"]
print(' '.join([list2[list1.index(int(ind))] for ind in str(input_num)]))
</code>```

This will result in :

```<code>hello my name
</code>```

Also, i would suggest you to look at the https://docs.python.org/2/tutorial/datastructures.html and trying things out to learn.

Body:
Developing on my previous question I'm wondering whether there is a way to have an element in a list and find that position in another list and return what is in the position as a variable. for example:

list1 = [0,1,2,3,4]
list2 = ["0","hello","my","name","is","Daniel"]

if the user enters the number 14 the program will return "hello Daniel" in the sense that the computer reads 14 as 1 and 4 and finds the position in list as an example.

I've tired using [list2.index(x) for x in list1] hoping that it would work but I've been unable to change the code so it does work. is there a simple way to do it

Body:
You can do something like this :

input_num = 123
list1 = [0, 1, 2, 3, 4] # if list1 is not dervied from input number
list2 = ["0", "hello", "my", "name", "is", "Daniel"]
print(' '.join([list2[list1.index(int(ind))] for ind in str(input_num)]))

This will result in :

hello my name

Also, i would suggest you to look at the https://docs.python.org/2/tutorial/datastructures.html and trying things out to learn.


问:
Is there a way to read a saved plot in to R?
Is there a way to read a saved plot in to R, and assign it an object - the equivalent of reading in a csv?

```<code>df<-read.csv('test.data.csv')
</code>```

The end goal is that I have 500 plots that were saved using ggsave() that I'd like to reposition via cowplot(), which only seems to be able to access objects in the active working environment.

Thanks for any insight.

答:
No, once the plot is saved as a .jpeg or .pdf or whatever image format you use, the back end data that is stored in the R object is lost.

You can save the R plot object using the save() function and then call that back with the load() function. However this will not be saved in a format that most other programs will recognize as an image. It is not something you could load into powerpoint.

If all you need is loading a straight up image into R, then see the answers to this question: how to read.jpeg in R 2.15

Body:
Is there a way to read a saved plot in to R, and assign it an object - the equivalent of reading in a csv?

df<-read.csv('test.data.csv')

The end goal is that I have 500 plots that were saved using ggsave() that I'd like to reposition via cowplot(), which only seems to be able to access objects in the active working environment.

Thanks for any insight.


问:
Error establishing a database connection Amazon EC2 - after moving my wordpress blog
I am getting the error: "error establishing a database connection" after moving my wordpress blog to Amazon EC2. I've checked the wp-config.php file and settings are ok (localhost, password and username).

I've read many of the questions and answers here but nothing helped me.

I have shell access so I can check everything that you need me to do. Maybe I should look at the configuration file for phpmyadmin to see what db connection settings are there, because phpmyadmin works, but I don't know where it is.

Thanks

答:
I solved this problem adding a swap to my instance:

```<code>sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo chmod 600 /var/swap.1
sudo /sbin/swapon /var/swap.1
</code>```

If you need more than 1024 then change that to something higher.

To enable it by default after reboot, add this line to /etc/fstab:

```<code>swap        /var/swap.1 swap    defaults        0   0
</code>```

To check if your instance is using swap run this command:

```<code>cat /proc/meminfo
</code>```

The result:

```<code>ubuntu@ip-172-31-24-245:/$ cat /proc/meminfo
MemTotal:         604340 kB
MemFree:            8524 kB
Buffers:            3380 kB
Cached:           398316 kB
SwapCached:            0 kB
Active:           165476 kB
Inactive:         384556 kB
Active(anon):     141344 kB
Inactive(anon):     7248 kB
Active(file):      24132 kB
Inactive(file):   377308 kB
Unevictable:           0 kB
Mlocked:               0 kB
</code>```

SwapTotal: 1048572 kB

SwapFree: 1048572 kB

```<code>Dirty:                 0 kB
Writeback:             0 kB
AnonPages:        148368 kB
Mapped:            14304 kB
Shmem:               256 kB
Slab:              26392 kB
SReclaimable:      18648 kB
SUnreclaim:         7744 kB
KernelStack:         736 kB
PageTables:         5060 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     1350740 kB
Committed_AS:     623908 kB
VmallocTotal:   34359738367 kB
VmallocUsed:        7420 kB
VmallocChunk:   34359728748 kB
HardwareCorrupted:     0 kB
AnonHugePages:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:      637952 kB
DirectMap2M:           0 kB
</code>```

Body:
I solved this problem adding a swap to my instance:

sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo chmod 600 /var/swap.1
sudo /sbin/swapon /var/swap.1

If you need more than 1024 then change that to something higher.

To enable it by default after reboot, add this line to /etc/fstab:

swap        /var/swap.1 swap    defaults        0   0

To check if your instance is using swap run this command:

cat /proc/meminfo

The result:

ubuntu@ip-172-31-24-245:/$ cat /proc/meminfo
MemTotal:         604340 kB
MemFree:            8524 kB
Buffers:            3380 kB
Cached:           398316 kB
SwapCached:            0 kB
Active:           165476 kB
Inactive:         384556 kB
Active(anon):     141344 kB
Inactive(anon):     7248 kB
Active(file):      24132 kB
Inactive(file):   377308 kB
Unevictable:           0 kB
Mlocked:               0 kB

SwapTotal: 1048572 kB

SwapFree: 1048572 kB

Dirty:                 0 kB
Writeback:             0 kB
AnonPages:        148368 kB
Mapped:            14304 kB
Shmem:               256 kB
Slab:              26392 kB
SReclaimable:      18648 kB
SUnreclaim:         7744 kB
KernelStack:         736 kB
PageTables:         5060 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     1350740 kB
Committed_AS:     623908 kB
VmallocTotal:   34359738367 kB
VmallocUsed:        7420 kB
VmallocChunk:   34359728748 kB
HardwareCorrupted:     0 kB
AnonHugePages:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:      637952 kB
DirectMap2M:           0 kB


问:
Take all items except the last ones that satisfy condition?
My specific requirement is that I have an IEnumerable<IEnumerable<string>>, and I want to "take" all items in the outer enumeration except any "empty" trailing items, where "empty" means all strings are null/empty or the inner enumeration is empty. Note that I want to keep any empty items that appear before the last non-empty one. For example:

```<code>Item 1: a, b, c
Item 2: (nothing)
Item 3: a, f, g, h
Item 4: (nothing)
Item 5: (nothing)
</code>```

I would like to keep items 1–3 but trim items 4 and 5.

In a more general sense, I have an enumeration of items, where I want to trim any trailing items that satisfy a condition, that appear behind the last item that does not satisfy the condition.

For the sake of choosing an appropriate solution, I might add that the outer enumeration will usually contain a few hundred up to a few hundred thousand items, while the inner enumerations contain only a few items each. There will probably be only a couple of empty items that I need to trim.

My current solution puts all outer items in a list (after transforming them with .Select(...)), and then in a loop keep removing the last item if it's empty, until a non-empty item is found.

答:
There is no standard efficient LINQ solution. I would go with a custom extension "LINQ like" method like this:

```<code>public static class EnumerableExtensions
{
    public static IEnumerable<T> SkipLastWhile<T>(this IEnumerable<T> source, Func<T, bool> predicate)
    {
        var skipBuffer = new List<T>();
        foreach (var item in source)
        {
            if (predicate(item))
                skipBuffer.Add(item);
            else
            {
                if (skipBuffer.Count > 0)
                {
                    foreach (var skipped in skipBuffer)
                        yield return skipped;
                    skipBuffer.Clear();
                }
                yield return item;
            }
        }
    }
}
</code>```

It requires additional space for buffering the longest item sequence satisfying the skip predicate while the LINQ Reverse method has to buffer the whole input sequence.

The usage will be:

```<code>var result = input.SkipLastWhile(e => !e.Any());
</code>```

Body:
My specific requirement is that I have an IEnumerable<IEnumerable<string>>, and I want to "take" all items in the outer enumeration except any "empty" trailing items, where "empty" means all strings are null/empty or the inner enumeration is empty. Note that I want to keep any empty items that appear before the last non-empty one. For example:

Item 1: a, b, c
Item 2: (nothing)
Item 3: a, f, g, h
Item 4: (nothing)
Item 5: (nothing)

I would like to keep items 1–3 but trim items 4 and 5.

In a more general sense, I have an enumeration of items, where I want to trim any trailing items that satisfy a condition, that appear behind the last item that does not satisfy the condition.

For the sake of choosing an appropriate solution, I might add that the outer enumeration will usually contain a few hundred up to a few hundred thousand items, while the inner enumerations contain only a few items each. There will probably be only a couple of empty items that I need to trim.

My current solution puts all outer items in a list (after transforming them with .Select(...)), and then in a loop keep removing the last item if it's empty, until a non-empty item is found.

Body:
There is no standard efficient LINQ solution. I would go with a custom extension "LINQ like" method like this:

public static class EnumerableExtensions
{
    public static IEnumerable<T> SkipLastWhile<T>(this IEnumerable<T> source, Func<T, bool> predicate)
    {
        var skipBuffer = new List<T>();
        foreach (var item in source)
        {
            if (predicate(item))
                skipBuffer.Add(item);
            else
            {
                if (skipBuffer.Count > 0)
                {
                    foreach (var skipped in skipBuffer)
                        yield return skipped;
                    skipBuffer.Clear();
                }
                yield return item;
            }
        }
    }
}

It requires additional space for buffering the longest item sequence satisfying the skip predicate while the LINQ Reverse method has to buffer the whole input sequence.

The usage will be:

var result = input.SkipLastWhile(e => !e.Any());


答:
You have to use ionViewDidLoad() event.

ionViewDidLoad()

Runs when the page has loaded. This event only happens once per page
  being created. If a page leaves but is cached, then this event will
  not fire again on a subsequent viewing. The ionViewDidLoad event is
  good place to put your setup code for the page.

Another event is ionViewDidEnter()

ionViewDidEnter()

Runs when the page has fully entered and is now the active page. This
  event will fire, whether it was the first load or a cached page.

Here is the official doc.

Title: Dom rendering issues ngAfterViewInit ionic 2


问:
Pod Resources Monitoring
In kubernetes, we can specify the the resources required with some upper limit in terms of their capacity(like memory(primary memory), CPU etc). But, is there any way to specify how much of secondary memory can be allocated to a particular pod? I understand secondary memory can be allocated externally by Volumes. But otherwise, how much secondary memory does a pod have and how can we vary it?</p>

答:
Pod resource allocation above the resource requests you define for a container (assuming you are not defining limits) is taken from whatever is available on the host the pod was deployed to by the scheduler.

This means that it will depend on:

What size instance it's deployed on

what else is running on that node

How much unallocated resources are left afterwards

Title: Pod Resources Monitoring


问:
Buttons not working with onclick and JavaScript
I am trying to make buttons that adds 10, 100, and 1000 to an input and that can clear the input field, but i can't get it to work. I have tried alle the different ways i know to add the script to my document(inline and external) but i can't seem to crack the code. The debug console tells me that The functions is not defined

EDIT:

The problem seems to be that when clicking the buttons the site redirects to the index file

var bet = document.getElementById('coincredits');
var cur = document.getElementById('coincredits').value;
var coins = document.getElementById('coins').value;

function clear() {
 bet.value = "";
}
function ten() {
 bet.value = cur + 10;
}
function hundred() {
 bet.value = cur + 100;
}
function thousand() {
 bet.value = cur + 1000;
}
function xtwo() {
 bet.value = cur * 2;
}
function max() {
 bet.value = coins;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4>Coins:</h4><p id="coins">123456789</p>

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

<div>
  <button onclick="clear()">Clear</button>
  <button onclick="ten()">+10</button>
  <button onclick="hundred()">+100</button>
  <button onclick="thousand()">+1000</button>
  <button onclick="xtwo()">x2</button>
  <button onclick="max()">Max</button>
</div></code>```

答:
You need to get the current value every time one of your functions is called.
Right now you are getting the current value of your input just once (when the script is evaluated).

i.e. add the line below to each of your functions: ten, hundred, thousand and xtwo

var cur = document.getElementById('coincredits').value;

Body:
I am trying to make buttons that adds 10, 100, and 1000 to an input and that can clear the input field, but i can't get it to work. I have tried alle the different ways i know to add the script to my document(inline and external) but i can't seem to crack the code. The debug console tells me that The functions is not defined

EDIT:

The problem seems to be that when clicking the buttons the site redirects to the index file

var bet = document.getElementById('coincredits');
var cur = document.getElementById('coincredits').value;
var coins = document.getElementById('coins').value;

function clear() {
 bet.value = "";
}
function ten() {
 bet.value = cur + 10;
}
function hundred() {
 bet.value = cur + 100;
}
function thousand() {
 bet.value = cur + 1000;
}
function xtwo() {
 bet.value = cur * 2;
}
function max() {
 bet.value = coins;
}

Coins:

123456789

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

  <button onclick="clear()">Clear</button>
  <button onclick="ten()">+10</button>
  <button onclick="hundred()">+100</button>
  <button onclick="thousand()">+1000</button>
  <button onclick="xtwo()">x2</button>
  <button onclick="max()">Max</button>


问:
Multidimensional Arrays Nested to Unlimited Depth
I have a multidimensional array nested to an unknown/unlimited depth.
I'd like to be able to loop through every element.
I don't want to use, foreach(){foreach(){foreach(){}}} as I don't know the depth.

I'm eventually looking for all nested arrays called "xyz".  Has anyone got any suggestions?

答:
Recursion.

Write a function that walks one array; for each element that is also an array, it calls itself; otherwise, when it finds the target string, it returns.

ContentLicense: CC BY-SA 2.5


问:
Cookie Rejected For Rest API call
After one year of working, the java code is suddenly rising the below error

Feb 02, 2017 6:28:39 PM org.apache.commons.httpclient.HttpMethodBase
  processCookieHeaders WARNING: Cookie rejected: "$Version=0;
  BrowserId=Mx-kTzLhTUm29MoIKmS6ag; $Path=/; $Domain=.salesforce.com".
  Domain attribute ".salesforce.com" violates RFC 2109: host minus
  domain may not contain any dots

I am not a java developer to solve this issue. I don't have any idea about this error.

My code sameple where am using httpclient

```<code>HttpClient httpclient = new HttpClient();
httpclient.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
httpclient.getParams().setParameter(HttpClientParams.COOKIE_POLICY, CookiePolicy.RFC_2965);
PostMethod post = new PostMethod(tokenUrl);
post.addParameter("grant_type", grant_type);
post.addParameter("client_id", client_id);
post.addParameter("client_secret", client_secret);
post.addParameter("username", username);
post.addParameter("password", password);

httpclient.executeMethod(post);
</code>```

What do I need to solve this issue. Any help is appreciable. Thanks!!!

Edit

Packages used in the class

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.logging.Logger;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
</code>```

答:
I had the same issue, and I have solved.

You must put this one:

```<code>httpclient.getParams().setParameter(HttpClientParams.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
</code>```

instead of:

```<code>httpclient.getParams().setParameter(HttpClientParams.COOKIE_POLICY, CookiePolicy.RFC_2965);
</code>```

BROWSER_COMPATIBILITY is compatible with the common cookie management practices, on the other hand, RFC2109 compliant is by default.

Please accept my advice :)

Title: Cookie Rejected For Rest API call

Body:
After one year of working, the java code is suddenly rising the below error

Feb 02, 2017 6:28:39 PM org.apache.commons.httpclient.HttpMethodBase
  processCookieHeaders WARNING: Cookie rejected: "$Version=0;
  BrowserId=Mx-kTzLhTUm29MoIKmS6ag; $Path=/; $Domain=.salesforce.com".
  Domain attribute ".salesforce.com" violates RFC 2109: host minus
  domain may not contain any dots

I am not a java developer to solve this issue. I don't have any idea about this error.

My code sameple where am using httpclient

HttpClient httpclient = new HttpClient();
httpclient.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
httpclient.getParams().setParameter(HttpClientParams.COOKIE_POLICY, CookiePolicy.RFC_2965);
PostMethod post = new PostMethod(tokenUrl);
post.addParameter("grant_type", grant_type);
post.addParameter("client_id", client_id);
post.addParameter("client_secret", client_secret);
post.addParameter("username", username);
post.addParameter("password", password);

httpclient.executeMethod(post);

What do I need to solve this issue. Any help is appreciable. Thanks!!!

Edit

Packages used in the class

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.logging.Logger;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

Body:
I had the same issue, and I have solved.

You must put this one:

httpclient.getParams().setParameter(HttpClientParams.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

instead of:

httpclient.getParams().setParameter(HttpClientParams.COOKIE_POLICY, CookiePolicy.RFC_2965);

BROWSER_COMPATIBILITY is compatible with the common cookie management practices, on the other hand, RFC2109 compliant is by default.

Please accept my advice :)


问:
Error:Execution failed for task ':app:transformClassesWithDexForDebug'
The error

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
  com.android.build.transform.api.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/usr/lib/jvm/java-8-oracle/bin/java'' finished with non-zero exit value 1

My app gradle file:

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId 'Hidden application ID'
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions {
        disable 'InvalidPackage'
    }
    packagingOptions {
        exclude 'META-INF/services/javax.annotation.processing.Processor'
    }
    productFlavors {
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:cardview-v7:23.1.1'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    compile 'com.google.android.gms:play-services:8.1.0'
    compile 'com.facebook.android:facebook-android-sdk:4.7.0'
    compile 'com.googlecode.libphonenumber:libphonenumber:7.2.1'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'com.android.support:preference-v7:23.1.1'
}
</code>```

While debugging, if I set minifyEnabled to true, then it compiles. However, then I cannot debug my application.

I checked this other question: Execution failed for task ':app:transformClassesWithDexForDebug' while implementing Google sign in for Android, but there is only one answer and implementing it does not resolve the issue unfortunately.

AFAIK, the error is caused due to addition of too many Gradle dependencies, but I may be wrong (I really hope to be wrong because all these packages are really important!).

Please help me to resolve this error. Much thanks!

答:
Apparently I resolved the issue by combining all the solutions
adding following to android manifest:

```<code><application
...
        android:name="android.support.multidex.MultiDexApplication" >
...
</application>
</code>```

Following to build.gradle app module

```<code>android {
...

    dexOptions {
        javaMaxHeapSize "4g"
        preDexLibraries = false
    }
...
    defaultConfig {

        multiDexEnabled true

   }

}
</code>```

Body:
The error

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
  com.android.build.transform.api.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/usr/lib/jvm/java-8-oracle/bin/java'' finished with non-zero exit value 1

My app gradle file:

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId 'Hidden application ID'
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions {
        disable 'InvalidPackage'
    }
    packagingOptions {
        exclude 'META-INF/services/javax.annotation.processing.Processor'
    }
    productFlavors {
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:cardview-v7:23.1.1'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    compile 'com.google.android.gms:play-services:8.1.0'
    compile 'com.facebook.android:facebook-android-sdk:4.7.0'
    compile 'com.googlecode.libphonenumber:libphonenumber:7.2.1'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'com.android.support:preference-v7:23.1.1'
}

While debugging, if I set minifyEnabled to true, then it compiles. However, then I cannot debug my application.

I checked this other question: Execution failed for task ':app:transformClassesWithDexForDebug' while implementing Google sign in for Android, but there is only one answer and implementing it does not resolve the issue unfortunately.

AFAIK, the error is caused due to addition of too many Gradle dependencies, but I may be wrong (I really hope to be wrong because all these packages are really important!).

Please help me to resolve this error. Much thanks!

Body:
Apparently I resolved the issue by combining all the solutions
adding following to android manifest:

<application
...
        android:name="android.support.multidex.MultiDexApplication" >
...
</application>

Following to build.gradle app module

android {
...

    dexOptions {
        javaMaxHeapSize "4g"
        preDexLibraries = false
    }
...
    defaultConfig {

        multiDexEnabled true

   }

}


问:
Avro Schema: force to interpret value (map, array) as string
I want to convert JSON to Avro via NiFi. Unfortunately the JSON has complex types as values that I want to see as a simple string!

JSON:

```<code>"FLAGS" : {"FLAG" : ["STORED","ACTIVE"]}
</code>```

How can I tell AVRO to simply store "{"FLAG" : ["STORED","ACTIVE"]}" or "[1,2,3,"X"]" as a string?

Thank you sincerely!

答:
The JSON to Avro conversion performed in NiFi's ConvertJSONToAvro processor does not really do transformation in the same step.  There is a very limited ability to transform based on the Avro schema, mostly omitting input data fields in the output.  But it won't coerce a complex structure to a string.

Instead, you should do a JSON-to-JSON transformation first, then convert your summarized JSON to Avro.  I think what you are looking for is a structure like this:

```<code>{
  "FLAGS": "{\"FLAG\":[\"STORED\",\"ACTIVE\"]}"
}
</code>```

NiFi's JoltTransformJSON, ExecuteScript processors are great for this.  If your records are simple enough, maybe even a combination of EvaluateJsonPath $.FLAGS and ReplaceText { "FLAGS": "${flags:escapeJson()}" }.

Body:
I want to convert JSON to Avro via NiFi. Unfortunately the JSON has complex types as values that I want to see as a simple string!

JSON:

"FLAGS" : {"FLAG" : ["STORED","ACTIVE"]}

How can I tell AVRO to simply store "{"FLAG" : ["STORED","ACTIVE"]}" or "[1,2,3,"X"]" as a string?

Thank you sincerely!

Body:
The JSON to Avro conversion performed in NiFi's ConvertJSONToAvro processor does not really do transformation in the same step.  There is a very limited ability to transform based on the Avro schema, mostly omitting input data fields in the output.  But it won't coerce a complex structure to a string.

Instead, you should do a JSON-to-JSON transformation first, then convert your summarized JSON to Avro.  I think what you are looking for is a structure like this:

{
  "FLAGS": "{\"FLAG\":[\"STORED\",\"ACTIVE\"]}"
}

NiFi's JoltTransformJSON, ExecuteScript processors are great for this.  If your records are simple enough, maybe even a combination of EvaluateJsonPath $.FLAGS and ReplaceText { "FLAGS": "${flags:escapeJson()}" }.


问:
startIndex cannot be larger then length of string. Parameter name: startIndex MVC4
I am running into an error only on my production while I am adding my weights that are on my receiving reports checked as received.

On my local machine this issue isn't exist. but on the production get the error below.

my controller:

```<code>public int ReceivingReportWeight
{
    get
    {
        if (_ReceivingReportWeight == null && ReceivingReportCount > 0 && ReceivingReportWeight == 0)
        {
            dynamic receivingReportDbView = Database.Open().vw_ReceivingReports;
            List<int> receivedReceivingReports = receivingReportDbView.Select(receivingReportDbView.Id).Where(receivingReportDbView.ProjectId == Id && receivingReportDbView.Received == true).ToScalarList<int>();
            dynamic vwItemsDbView = Database.Open().vw_Items;
            int receivingReportWeight = vwItemsDbView.Select(vwItemsDbView.Weight.Sum()).Where(vwItemsDbView.ModuleId == MODULE_IDS.RECEIVING_REPORT && vwItemsDbView.TransactionId == receivedReceivingReports).ToScalar<int>();
            _ReceivingReportWeight = receivingReportWeight;
        }

        return _ReceivingReportWeight.GetValueOrDefault();
    }
}
</code>```

my view

```<code>   @if (Model.ReceivingReportWeight > 0) {
        <div class="actions" style="width: 50%; text-align: right;">
            Total Received Weight: @Model.ReceivingReportWeight lbs.
        </div>
   }
</code>```

答:
That error comes from something like Substring, when the value passed into the startIndex param is greater than the total length of the string. For example, if you had a string like "Just Testing" and you did .Substring(12, 1), you'd get that exception, as the string is only 12 characters long (remember that the index is from 0, not 1, so the last index is 11).

However, there is no code that you've included in your question which does anything like that. As a result, the error is being raised from somewhere else. Track down where you're working with Substring and figure out why your index is exceeding your string length.

Body:
I am running into an error only on my production while I am adding my weights that are on my receiving reports checked as received.

On my local machine this issue isn't exist. but on the production get the error below.

my controller:

public int ReceivingReportWeight
{
    get
    {
        if (_ReceivingReportWeight == null && ReceivingReportCount > 0 && ReceivingReportWeight == 0)
        {
            dynamic receivingReportDbView = Database.Open().vw_ReceivingReports;
            List<int> receivedReceivingReports = receivingReportDbView.Select(receivingReportDbView.Id).Where(receivingReportDbView.ProjectId == Id && receivingReportDbView.Received == true).ToScalarList<int>();
            dynamic vwItemsDbView = Database.Open().vw_Items;
            int receivingReportWeight = vwItemsDbView.Select(vwItemsDbView.Weight.Sum()).Where(vwItemsDbView.ModuleId == MODULE_IDS.RECEIVING_REPORT && vwItemsDbView.TransactionId == receivedReceivingReports).ToScalar<int>();
            _ReceivingReportWeight = receivingReportWeight;
        }

        return _ReceivingReportWeight.GetValueOrDefault();
    }
}

my view

   @if (Model.ReceivingReportWeight > 0) {

            Total Received Weight: @Model.ReceivingReportWeight lbs.

   }


问:
PL SQL Patterns Matching
How to only interpret a particular word(e.g test) from a big string if it’s really “start of line + optional white space + test + space”.Also allow mixed case for the word ‘test’</p>

答:
Using REGEXP_REPLACE with all parms, you can...

Provide the value you want to affect

Provide the regular expression you want to find

Tell the function on what character to start

Tell the function which occurrence you want to replace

Provide additional modifiers, of which 'i' means use case insensitivity

This will work if you are looking to remove the second instance of test, or TeSt, or TEST.  You've not provided much in the way of examples and expected results.

```<code>-- Start test data
with test_data as
    (select 'TeSt this is how I am going to tEst going for' as test_string from dual union all
     select 'test hello everyone how are you test' from dual union all
     select 'test_find1();' from dual union all
     select 'test sample 1;' from dual union all
     select 'TEST sample 2;' from dual union all
     select 'test1 hope this is will help test2;' from dual)
-- End test data
select test_string,
       CASE WHEN REGEXP_LIKE(test_string,'^test\s+','i') THEN
                    REGEXP_REPLACE(test_string,'test','', 1, 2, 'i')
           ELSE NULL END AS result
from   test_data;
</code>```

More on REGEXP_REPLACE here

Title: PL SQL Patterns Matching

Body:
Using REGEXP_REPLACE with all parms, you can...

Provide the value you want to affect

Provide the regular expression you want to find

Tell the function on what character to start

Tell the function which occurrence you want to replace

Provide additional modifiers, of which 'i' means use case insensitivity

This will work if you are looking to remove the second instance of test, or TeSt, or TEST.  You've not provided much in the way of examples and expected results.

-- Start test data
with test_data as
    (select 'TeSt this is how I am going to tEst going for' as test_string from dual union all
     select 'test hello everyone how are you test' from dual union all
     select 'test_find1();' from dual union all
     select 'test sample 1;' from dual union all
     select 'TEST sample 2;' from dual union all
     select 'test1 hope this is will help test2;' from dual)
-- End test data
select test_string,
       CASE WHEN REGEXP_LIKE(test_string,'^test\s+','i') THEN
                    REGEXP_REPLACE(test_string,'test','', 1, 2, 'i')
           ELSE NULL END AS result
from   test_data;

More on REGEXP_REPLACE here


问:
SQL Basics If Column A is not empty then on Column B use
Hi All just starting out with SQL. would like to ask.
For example if given:

Result:

Explanation:

If column B is not empty the use Column B in Column E

If Column B is empty then use column D in Column E

If Column B and D is empty then leave  Column E as empty

How would you make this work in SQL?

答:
I suggest using Coalesce, as stated in Siyual's comment:</p>

```<code>select t.ColA
      ,t.ColB
      ,t.ColC
      ,t.ColD
      ,Coalesce(t.ColB, t.ColD) as ColE
from table t
</code>```

Body:
I suggest using Coalesce, as stated in Siyual's comment:

select t.ColA
      ,t.ColB
      ,t.ColC
      ,t.ColD
      ,Coalesce(t.ColB, t.ColD) as ColE
from table t


问:
Difference between a wildcard and a named route in Sinatra
I've been watching several tutorials on Sinatra and can't find the difference, between, say:

```<code>get "/hey/*/there/*"
</code>```

vs.

```<code>get "/hey/:first/there/:second"
</code>```

The only difference I see is the way in which the parameters is accessed. So in the first way you access it by:

```<code>params[:splat][0]
params[:splat[1]
</code>```

while the second way:

```<code>params[:first]
params[:second]
</code>```

Is a named parameter in Sinatra, just a wildcard to which we give a name? Is that the only difference?

答:
They're not quite the same. Splats can be useful if you want to match an indeterminate number of parameters, rather than a single (named) one. For example:</p>

```<code># Will match: "/hey/:first/there/:second"
# Will match: "/hey/*/there/*"
GET /hey/first/there/second

# Won't match: "/hey/:first/there/:second"
# Will match: "/hey/*/there/*"
GET /hey/first/second/there/third/fourth
</code>```

Body:
I've been watching several tutorials on Sinatra and can't find the difference, between, say:

get "/hey/*/there/*"

vs.

get "/hey/:first/there/:second"

The only difference I see is the way in which the parameters is accessed. So in the first way you access it by:

params[:splat][0]
params[:splat[1]

while the second way:

params[:first]
params[:second]

Is a named parameter in Sinatra, just a wildcard to which we give a name? Is that the only difference?

Body:
They're not quite the same. Splats can be useful if you want to match an indeterminate number of parameters, rather than a single (named) one. For example:

# Will match: "/hey/:first/there/:second"
# Will match: "/hey/*/there/*"
GET /hey/first/there/second

# Won't match: "/hey/:first/there/:second"
# Will match: "/hey/*/there/*"
GET /hey/first/second/there/third/fourth


问:
Uncaught TypeError: Cannot create property 'style' on string 'wtd_background_image'
My wordpress plugin works with fabric.js 1.2.0, When I change it to work with fabric.js 1.7.9 then it throws the error on all the pages other than plugin page:

Cannot create property 'style' on string 'wtd_background_image'

on the following line:

```<code>canvasObj= new fabric.Canvas('wtd_background_image');
</code>```

答:
You'll need to create an HTML Canvas Element with an id wtd_background_image, on all your pages.

let canvas = new Canvas('wtd_background_image');
let canvasObj = new fabric.Canvas('wtd_background_image');

function Canvas(id) {
    this.canvas = document.createElement('canvas');
    this.canvas.id = id;
    document.body.appendChild(this.canvas);
    return this.canvas;
}

// for demonstration
let circle = new fabric.Circle({radius: 20, fill: '#07C', left: 30, top: 30});
canvasObj.add(circle);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.9/fabric.min.js"></script></code>```

Body:
My wordpress plugin works with fabric.js 1.2.0, When I change it to work with fabric.js 1.7.9 then it throws the error on all the pages other than plugin page:

Cannot create property 'style' on string 'wtd_background_image'

on the following line:

canvasObj= new fabric.Canvas('wtd_background_image');

Body:
You'll need to create an HTML Canvas Element with an id wtd_background_image, on all your pages.

let canvas = new Canvas('wtd_background_image');
let canvasObj = new fabric.Canvas('wtd_background_image');

function Canvas(id) {
    this.canvas = document.createElement('canvas');
    this.canvas.id = id;
    document.body.appendChild(this.canvas);
    return this.canvas;
}

// for demonstration
let circle = new fabric.Circle({radius: 20, fill: '#07C', left: 30, top: 30});
canvasObj.add(circle);

<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.9/fabric.min.js"></script>


问:
OwinStartup not firing
I had the OwinStartup configuration code working perfectly and then it stopped working.  Unfortunately I'm not sure exactly what I did to get it to stop working and am having a really hard time figuring it out.

To make sure I have the basics covered, I doubled checked to make sure the I have the

```<code>[assembly:OwinStartup(typeof(WebApplication.Startup))]
</code>```

attribute assigned properly and made sure that I don't have an appSetting for owin:AutomaticAppStartup that is set to false so I made one set to true to be safe as there was nothing there before.

```<code><add key="owin:AutomaticAppStartup" value="true" />
</code>```

I also tried specifically calling out the appSetting:

```<code><add key="owin:appStartup" value="WebApplication.Startup" />
</code>```

Before it stopped working I upgraded the Microsoft.Owin.Security NuGet packages to 2.0.2, so I tried reverting them to 2.0.1 (that was a pain) but it didn't change anything.  I have WebActivator installed on the project and am using that to bootstrap other things but I've tested that on a fresh WebApplication template and it works there so I don't think that is the culprit.

I also tried removing my Startup class and using Visual Studio to add a new one using the OWIN Startup Class type in Add New Item and that isn't getting called either.  Next I tried adding a second Startup class since I know it will throw an exception if there is more than one OwinStartup attributes defined, but it isn't throwing any exception there.

Not sure what else to try.  Any thoughts?

Update

Turns out that Resharper removed the reference to Microsoft.Owin.Host.SystemWeb when I used it to remove unused references.

答:
I messed around with a lot of the suggestions on this post.

I had the following but still could not land on a break point. Throwing an exception proved the code was being entered.

```<code><appSettings>
...
  <add key="owin:AutomaticAppStartup" value="true" />
  <add key="owin:appStartup" value="SSOResource.Startup, SSOResource" />
...
</appSettings>
</code>```

Finally out of desperation I looked at project->properties, and then under the WEB section I also checked the NATIVE CODE checkbox (ASP.NET should be already checked).

That finally fixed it for me.

Note : I am using Visual Studio 2017 Professional.

Title: OwinStartup not firing

Body:
I had the OwinStartup configuration code working perfectly and then it stopped working.  Unfortunately I'm not sure exactly what I did to get it to stop working and am having a really hard time figuring it out.

To make sure I have the basics covered, I doubled checked to make sure the I have the

[assembly:OwinStartup(typeof(WebApplication.Startup))]

attribute assigned properly and made sure that I don't have an appSetting for owin:AutomaticAppStartup that is set to false so I made one set to true to be safe as there was nothing there before.

<add key="owin:AutomaticAppStartup" value="true" />

I also tried specifically calling out the appSetting:

<add key="owin:appStartup" value="WebApplication.Startup" />

Before it stopped working I upgraded the Microsoft.Owin.Security NuGet packages to 2.0.2, so I tried reverting them to 2.0.1 (that was a pain) but it didn't change anything.  I have WebActivator installed on the project and am using that to bootstrap other things but I've tested that on a fresh WebApplication template and it works there so I don't think that is the culprit.

I also tried removing my Startup class and using Visual Studio to add a new one using the OWIN Startup Class type in Add New Item and that isn't getting called either.  Next I tried adding a second Startup class since I know it will throw an exception if there is more than one OwinStartup attributes defined, but it isn't throwing any exception there.

Not sure what else to try.  Any thoughts?

Update

Turns out that Resharper removed the reference to Microsoft.Owin.Host.SystemWeb when I used it to remove unused references.

Body:
I messed around with a lot of the suggestions on this post.

I had the following but still could not land on a break point. Throwing an exception proved the code was being entered.

<appSettings>
...
  <add key="owin:AutomaticAppStartup" value="true" />
  <add key="owin:appStartup" value="SSOResource.Startup, SSOResource" />
...
</appSettings>

Finally out of desperation I looked at project->properties, and then under the WEB section I also checked the NATIVE CODE checkbox (ASP.NET should be already checked).

That finally fixed it for me.

Note : I am using Visual Studio 2017 Professional.


问:
Jekyll build removing folders even after exclusion; throwing Build Warning about posts
I'm trying to set up a folder in my output path that won't be removed when I Jekyll build or serve. As per the link here I tried adding the name of the folder into my _config.yml with both keep_files and exclude, as below:

```<code>exclude: ["LICENSE", "README.md", "CONTRIBUTING", "CONTRIBUTORS", "scripts", stuff]
keep_files: [stuff]
</code>```

I've tried putting stuff in quotes as well, but so long as I have that in my config attempting to build keeps throwing a Build Warning for each of my posts for some reason.

```<code>$ Jekyll Build
Configuration file: none
            Source: /home/egrodo/noahyamamoto.com/_posts
       Destination: /home/egrodo/noahyamamoto.com/_posts/_site
 Incremental build: disabled. Enable with --incremental
      Generating...
     Build Warning: Layout 'post' requested in 2015-06-12-timeline-tutorial.md does not exist.
     Build Warning: Layout 'post' requested in 2015-06-19-writing-posts.md does not exist.
     Build Warning: Layout 'post' requested in 2015-06-20-blog-tutorial.md does not exist.
     Build Warning: Layout 'post' requested in 2015-06-25-initial-setup.md does not exist.
     Build Warning: Layout 'post' requested in 2017-03-29-synonym.md does not exist.
                    done in 0.068 seconds.
 Auto-regeneration: enabled for '/home/egrodo/noahyamamoto.com/_posts'
Configuration file: none
    Server address: http://127.0.0.1:4000/
  Server running... press ctrl-c to stop.
</code>```

Afterwards, my specified "stuff" folder still exists, but the site isn't built.

Any help would be appreciated!

答: Well uh, not sure what happened, but I edited an unrelated partial and the error went away and I was able to build successfully whilst keeping the stuff folder. Not sure about this one. Will keep this here in case anyone has any solid info. </p>

Body:
I'm trying to set up a folder in my output path that won't be removed when I Jekyll build or serve. As per the link here I tried adding the name of the folder into my _config.yml with both keep_files and exclude, as below:

exclude: ["LICENSE", "README.md", "CONTRIBUTING", "CONTRIBUTORS", "scripts", stuff]
keep_files: [stuff]

I've tried putting stuff in quotes as well, but so long as I have that in my config attempting to build keeps throwing a Build Warning for each of my posts for some reason.

$ Jekyll Build
Configuration file: none
            Source: /home/egrodo/noahyamamoto.com/_posts
       Destination: /home/egrodo/noahyamamoto.com/_posts/_site
 Incremental build: disabled. Enable with --incremental
      Generating...
     Build Warning: Layout 'post' requested in 2015-06-12-timeline-tutorial.md does not exist.
     Build Warning: Layout 'post' requested in 2015-06-19-writing-posts.md does not exist.
     Build Warning: Layout 'post' requested in 2015-06-20-blog-tutorial.md does not exist.
     Build Warning: Layout 'post' requested in 2015-06-25-initial-setup.md does not exist.
     Build Warning: Layout 'post' requested in 2017-03-29-synonym.md does not exist.
                    done in 0.068 seconds.
 Auto-regeneration: enabled for '/home/egrodo/noahyamamoto.com/_posts'
Configuration file: none
    Server address: http://127.0.0.1:4000/
  Server running... press ctrl-c to stop.

Afterwards, my specified "stuff" folder still exists, but the site isn't built.

Any help would be appreciated!


问:
Efficient way of calculating distance
I am making a dating site with a search function to find matches. One of the criteria is the distance between you and the possible match. How should I calculate the distance? I think calculating the exact distance for all possible matches might be too resource-intensive.I want a different solution so the nearby people are shown without being resource-intensive.

I had this idea:

When someone registers, save their coordinates rounded to (for the latitude) the nearest 5 minutes (=9 km) in the database? When searching for a match, search trough the database looking for the same coordinates as the user. After the matches are found, the exact distance could still be calculated.

How would that work for the longitude?
Are there any better ways of doing this?
I am not looking for the formula for calculating the distance. How can I find nearby matches without having to calculate the distance to every single possible match (thousands)?

答:
At first you can pick the latitude longitude of two users and can convert them into distance as following functions:

```<code>function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles<br>";

?>
</code>```

Hope it helps.

Title: Efficient way of calculating distance

Body:
At first you can pick the latitude longitude of two users and can convert them into distance as following functions:

function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles<br>";

?>

Hope it helps.


问:
Java 8 array madness: empty arrays seem to have length 1
This code should count words in a file.  Each blank line contributes +1, even though a line full of whitespace should split to an empty array.

```<code>import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.Arrays;

public class WordCount {
  public static void main(String[] args) {
    Path p = Paths.get(args[0]);
    if(!Files.exists(p)) {
      System.err.println("File "+ args[0] + "does not exist.");
      return;
    }
    try {
      /*int dracula =*/ Files.lines(p)
      .filter( e -> !(e.matches("^\\s+$")))
      .map(e -> e.split("\\s+"))
      //.mapToInt(e -> e.length)
      //.sum();
      .forEach(e -> System.out::println);
      //System.out.println(dracula);
      int[] foo = new int[0];
      System.out.println(foo.length);
    } catch(IOException ex) {
      ex.printStackTrace();
    }
  }
}
</code>```

Here is the sample file I ran it on.

```<code>martine.space.cadet  mashewske.matt haack

Jack jacob
</code>```

Here is the octal dump of it.

```<code>Tue Mar 28:16:06:streams> od -bc headache.txt
0000000   155 141 162 164 151 156 145 056 163 160 141 143 145 056 143 141
           m   a   r   t   i   n   e   .   s   p   a   c   e   .   c   a
0000020   144 145 164 040 040 155 141 163 150 145 167 163 153 145 056 155
           d   e   t           m   a   s   h   e   w   s   k   e   .   m
0000040   141 164 164 040 150 141 141 143 153 012 012 112 141 143 153 040
           a   t   t       h   a   a   c   k  \n  \n   J   a   c   k
0000060   152 141 143 157 142 012 012 012
           j   a   c   o   b  \n  \n  \n
0000070
</code>```

答:
Note the added line highlighted by a comment.  </p>

```<code>import java.util.ArrayList;
import java.util.regex.Pattern;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
public class Test
{
    public static void main(String[] args)
    {
        ArrayList<String> foo = new ArrayList<String>();
        foo.add("     ");
        foo.add("");
        foo.add("   q\n\n");
        Pattern r = Pattern.compile("^\\s*$");  //spot blank lines
        Path p = Paths.get("jack.txt");
        try
        {
            int goo = Files.lines(p)
                .filter(e -> !r.matcher(e).matches())  //get rid of blank lines
                .mapToInt(s -> s.split("\\s+").length)
                .sum();
                //.forEach(e -> System.out.println("line:" + e));
            System.out.println("words:  " + goo);
        }
        catch(Exception annoyingMartine)
        {
            //quack
        }
        foo.stream()
            .filter(e -> !r.matcher(e).matches())
            .forEach(e -> System.out.println("line:" + e));
    }
}
</code>```

Body:
This code should count words in a file.  Each blank line contributes +1, even though a line full of whitespace should split to an empty array.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.Arrays;

public class WordCount {
  public static void main(String[] args) {
    Path p = Paths.get(args[0]);
    if(!Files.exists(p)) {
      System.err.println("File "+ args[0] + "does not exist.");
      return;
    }
    try {
      /*int dracula =*/ Files.lines(p)
      .filter( e -> !(e.matches("^\\s+$")))
      .map(e -> e.split("\\s+"))
      //.mapToInt(e -> e.length)
      //.sum();
      .forEach(e -> System.out::println);
      //System.out.println(dracula);
      int[] foo = new int[0];
      System.out.println(foo.length);
    } catch(IOException ex) {
      ex.printStackTrace();
    }
  }
}

Here is the sample file I ran it on.

martine.space.cadet  mashewske.matt haack

Jack jacob

Here is the octal dump of it.

Tue Mar 28:16:06:streams> od -bc headache.txt
0000000   155 141 162 164 151 156 145 056 163 160 141 143 145 056 143 141
           m   a   r   t   i   n   e   .   s   p   a   c   e   .   c   a
0000020   144 145 164 040 040 155 141 163 150 145 167 163 153 145 056 155
           d   e   t           m   a   s   h   e   w   s   k   e   .   m
0000040   141 164 164 040 150 141 141 143 153 012 012 112 141 143 153 040
           a   t   t       h   a   a   c   k  \n  \n   J   a   c   k
0000060   152 141 143 157 142 012 012 012
           j   a   c   o   b  \n  \n  \n
0000070

Body:
Note the added line highlighted by a comment.

import java.util.ArrayList;
import java.util.regex.Pattern;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
public class Test
{
    public static void main(String[] args)
    {
        ArrayList<String> foo = new ArrayList<String>();
        foo.add("     ");
        foo.add("");
        foo.add("   q\n\n");
        Pattern r = Pattern.compile("^\\s*$");  //spot blank lines
        Path p = Paths.get("jack.txt");
        try
        {
            int goo = Files.lines(p)
                .filter(e -> !r.matcher(e).matches())  //get rid of blank lines
                .mapToInt(s -> s.split("\\s+").length)
                .sum();
                //.forEach(e -> System.out.println("line:" + e));
            System.out.println("words:  " + goo);
        }
        catch(Exception annoyingMartine)
        {
            //quack
        }
        foo.stream()
            .filter(e -> !r.matcher(e).matches())
            .forEach(e -> System.out.println("line:" + e));
    }
}


问:
How should I use IoC DI with this repository pattern?
I am using the repository pattern found in the answer to this SO question:

Advantage of creating a generic repository vs. specific repository for each object?

Namely, each repository inherits from an abstract base class that contains generic methods like add, delete, etc. and also implements a specific repository interface for any methods that are unique to that repository/entity.

ie.

```<code>public class CompanyRepository : Repository<Company>, ICompanyRepository {
...
}
</code>```

In my business layer I am using Structure Map to get an instance of the repository, but I am unsure how to use it.

```<code> // Structure Map initialisation
 ObjectFactory.Initialize(
 x =>
 {
      x.For<ICompanyRepository>().Use<CompanyRepository>();
 });
</code>```

resolving an instance:

```<code>return ObjectFactory.GetInstance<ICompanyRepository>();
</code>```

However the instance I get is an interface and not the whole repository implementation. I don't have access to the methods on the base class (Repository<Company>). What is the usual way to do this?

答:
Why not

```<code>return ObjectFactory.GetInstance<Repository<Company>>;
</code>```

? You will have to modify accordingly your ObjectFactory initialization:

```<code>// Structure Map initialisation
ObjectFactory.Initialize(
    x => {
      x.For<Repository<Company>>().Use<CompanyRepository>();
    });
</code>```

EDIT

If you still want to get Repository<Company> also for ICompanyRepository, you need to declare a forwarding:

```<code>// Structure Map initialisation
ObjectFactory.Initialize(
    x => {
      x.For<Repository<Company>>().Use<CompanyRepository>();
      x.Forward<Repository<Company>, ICompanyRepository>();
    });
</code>```

Body:
I am using the repository pattern found in the answer to this SO question:

Advantage of creating a generic repository vs. specific repository for each object?

Namely, each repository inherits from an abstract base class that contains generic methods like add, delete, etc. and also implements a specific repository interface for any methods that are unique to that repository/entity.

ie.

public class CompanyRepository : Repository<Company>, ICompanyRepository {
...
}

In my business layer I am using Structure Map to get an instance of the repository, but I am unsure how to use it.

 // Structure Map initialisation
 ObjectFactory.Initialize(
 x =>
 {
      x.For<ICompanyRepository>().Use<CompanyRepository>();
 });

resolving an instance:

return ObjectFactory.GetInstance<ICompanyRepository>();

However the instance I get is an interface and not the whole repository implementation. I don't have access to the methods on the base class (Repository<Company>). What is the usual way to do this?

Body:
Why not

return ObjectFactory.GetInstance<Repository<Company>>;

? You will have to modify accordingly your ObjectFactory initialization:

// Structure Map initialisation
ObjectFactory.Initialize(
    x => {
      x.For<Repository<Company>>().Use<CompanyRepository>();
    });

EDIT

If you still want to get Repository<Company> also for ICompanyRepository, you need to declare a forwarding:

// Structure Map initialisation
ObjectFactory.Initialize(
    x => {
      x.For<Repository<Company>>().Use<CompanyRepository>();
      x.Forward<Repository<Company>, ICompanyRepository>();
    });


问:
How to indicate a return type that is nested (e.g. a list of ints)
I have a python function with nested return types, how can I indicate the return types correctly? (For example pycharm might detect the return type as Tuple[list, int, int] where every type is linked individually)

e.g.

```<code>def random_list(num):
    """Returns a list of random numbers
    :param num:
        Number of random numbers to generate
    :type num:
        int
    :return:
        A list of random floats
    :rtype:
        ????
    """
    return [random() for x in range(num)]
</code>```

答:
I would look into type hints and use the same expression, e.g:</p>

```<code>from typing import List

def random_list(num: int) -> List[float]:  # Py 3.5
    """Returns a list of random numbers
    :param num:
        Number of random numbers to generate
    :type num:
        int
    :return:
        A list of random floats
    :rtype:
        List[float]
    """
    return [random() for x in range(num)]
</code>```

Body:
I have a python function with nested return types, how can I indicate the return types correctly? (For example pycharm might detect the return type as Tuple[list, int, int] where every type is linked individually)

e.g.

def random_list(num):
    """Returns a list of random numbers
    :param num:
        Number of random numbers to generate
    :type num:
        int
    :return:
        A list of random floats
    :rtype:
        ????
    """
    return [random() for x in range(num)]

Body:
I would look into type hints and use the same expression, e.g:

from typing import List

def random_list(num: int) -> List[float]:  # Py 3.5
    """Returns a list of random numbers
    :param num:
        Number of random numbers to generate
    :type num:
        int
    :return:
        A list of random floats
    :rtype:
        List[float]
    """
    return [random() for x in range(num)]


问:
Auto paste clipboard on load page @ chrome extension
I'm creating a website that the main issue in it is pasting stuff from clipboard, and an extension for that.

I want to auto-paste clipboard content when a specific page is opened.

For some reason the execCommand("Paste") is not executed when the page is loaded.

content.js

```<code>setTimeout(function() { chrome.extension.sendMessage({greeting: "hello"},function(response){}); },200);
</code>```

background.js

```<code>chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
document.execCommand("Paste");
  sendResponse({});
  return true;
});
</code>```

manifest.json

```<code>"background": {
  "page": "src/bg/background.html",
  "persistent": true
},
"options_page": "src/options/index.html",
"permissions": [
  "clipboardRead",
  "clipboardWrite",
  "fileBrowserHandler",
  "*my website address*"
],
"content_scripts": [
{
"matches": [
        "*my website address*"
    ],
"js": ["js/content.js"],
    "run_at": "document_end"
}
]
</code>```

everything works great until the paste is needed to be done and it's just not working...

thanks :)

答:
http://caniuse.com/#search=clipboardData

There says that "paste" command is not fired by using document.execCommand('paste')

Apparently there are other ways to make copy & paste but it all depends on compatibility.
I am still browsing around looking for a nice solution.

Body:
I'm creating a website that the main issue in it is pasting stuff from clipboard, and an extension for that.

I want to auto-paste clipboard content when a specific page is opened.

For some reason the execCommand("Paste") is not executed when the page is loaded.

content.js

setTimeout(function() { chrome.extension.sendMessage({greeting: "hello"},function(response){}); },200);

background.js

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
document.execCommand("Paste");
  sendResponse({});
  return true;
});

manifest.json

"background": {
  "page": "src/bg/background.html",
  "persistent": true
},
"options_page": "src/options/index.html",
"permissions": [
  "clipboardRead",
  "clipboardWrite",
  "fileBrowserHandler",
  "*my website address*"
],
"content_scripts": [
{
"matches": [
        "*my website address*"
    ],
"js": ["js/content.js"],
    "run_at": "document_end"
}
]

everything works great until the paste is needed to be done and it's just not working...

thanks :)


问:
Excel Conditional Formatting Based on Team Name
I'm looking to create some Excel conditional formatting that shows if a team member met a goal based on the team they are on. In my Team tab, I have a table showing the Employee's name, the team they're on, and all of their stats for the year. When I change employee name, the team name can change. In my Goals tab, I have the goals each employee should hit by quarter for each different team.

What formula can I use in the conditional formatting that will look at the team name and compare it to the goals for that team? I'd like a cell to show as red if a goal is not met. And will this formula update itself when the Team name changes?

Team

Goals

Thanks in advance!

答:
Use the change in Team name to add lookup the goals and put them in the Team spreadsheet on a hidden row. Then use a conditional formula to compare them.

If you put the goals in row 8, then for F18 use Conditional Formatting->Highlight Cells Rules->Less Than... and put =F8 for the condition. Select some red formatting, and it'll show up on all less than the hidden amount.


问:
How to convert the values of a Map of List to a single List
How is the best (efficient and simple) way to convert the values of a Map<Object1, List<Object2>> to a List<Object2>. Should I simply iterate over all entries and adAll the items to a list?

答:
Here's a third way so you don't need to create an ArrayList, which is what you actually asked.  This is the proper way to use streams because you're not changing the state of any object.</p>

```<code>List<Object2> values = myMap.values()
                            .stream()
                            .flatMap(Collection::stream)
                            .collect(Collectors.toList());
</code>```

Body:
Here's a third way so you don't need to create an ArrayList, which is what you actually asked.  This is the proper way to use streams because you're not changing the state of any object.

List<Object2> values = myMap.values()
                            .stream()
                            .flatMap(Collection::stream)
                            .collect(Collectors.toList());


问:
Historical ethereum prices - Coinbase API
Using the python coinbase API-- The functions-- get_buy_price, get_sell_price, get_spot_price, get_historical_data, etc... all seem to return bitcoin prices only. Is there a way of querying Ethereum prices?

It would seem that currency_pair = 'BTC-USD' could be changed to something akin to currency_pair = 'ETH-USD' although this has no effect.

I would expect that the API simply doesn't support this, except that the official documentation explicitly states:

Get the total price to buy one bitcoin or ether

I can work around this somewhat by using the quote='true' flag in the buy/sell request. This however only works moving forward, I would like historical data.

答:
source code will always be your friend.

def get_spot_price(self, **params):
    """https://developers.coinbase.com/api/v2#get-spot-price"""
    if 'currency_pair' in params:
        currency_pair = params['currency_pair']
    else:
        currency_pair = 'BTC-USD'
    response = self._get('v2', 'prices', currency_pair, 'spot', data=params)
    return self._make_api_object(response, APIObject)

def get_historic_prices(self, **params):
    """https://developers.coinbase.com/api/v2#get-historic-prices"""
    response = self._get('v2', 'prices', 'historic', data=params)
    return self._make_api_object(response, APIObject)
```

<p>We can see that both functions call the same api endpoint. We see that <code>get_spot_price</code> supports the <code>currency_pair</code> argument and passes it as part of the api call. On the other hand <code>get_historic_prices</code> does not.</p>

<p>I wonder what would happen if it did. Let's try it:</p>

```from coinbase.wallet.client import Client
from coinbase.wallet.model import APIObject

client = Client(api_key, api_secret)
client._make_api_object(client._get('v2', 'prices', 'ETH-USD', 'historic'), APIObject)

<APIObject @ 0x10dd04938> {
    "currency": "USD",
    "prices": [
        {
          "price": "52.60",
          "time": "2017-03-30T17:03:48Z"
        },
        {
          "price": "52.60",
          "time": "2017-03-30T17:03:38Z"
        },
        {
          "price": "52.54",
          "time": "2017-03-30T17:03:28Z"
        },
        {
          "price": "52.54",
          "time": "2017-03-30T17:03:18Z"
        },
        {
          "price": "52.54",
          "time": "2017-03-30T17:03:08Z"
        },
        {
          "price": "52.53",
          "time": "2017-03-30T17:02:58Z"
        },
        {
          "price": "52.53",
          "time": "2017-03-30T17:02:48Z"
        },
        {
          "price": "52.53",
          "time": "2017-03-30T17:02:38Z"
        },
        {
          "price": "52.53",
          "time": "2017-03-30T17:02:28Z"
        },
        .....
```

Success!

I'll sent a PR their way. but for now you can use my code snippet.

PR submitted

ContentLicense: CC BY-SA 4.0

Body:
source code will always be your friend.

def get_spot_price(self, **params):
    """https://developers.coinbase.com/api/v2#get-spot-price"""
    if 'currency_pair' in params:
        currency_pair = params['currency_pair']
    else:
        currency_pair = 'BTC-USD'
    response = self._get('v2', 'prices', currency_pair, 'spot', data=params)
    return self._make_api_object(response, APIObject)

def get_historic_prices(self, **params):
    """https://developers.coinbase.com/api/v2#get-historic-prices"""
    response = self._get('v2', 'prices', 'historic', data=params)
    return self._make_api_object(response, APIObject)

We can see that both functions call the same api endpoint. We see that get_spot_price supports the currency_pair argument and passes it as part of the api call. On the other hand get_historic_prices does not.

I wonder what would happen if it did. Let's try it:

from coinbase.wallet.client import Client
from coinbase.wallet.model import APIObject

client = Client(api_key, api_secret)
client._make_api_object(client._get('v2', 'prices', 'ETH-USD', 'historic'), APIObject)

<APIObject @ 0x10dd04938> {
    "currency": "USD",
    "prices": [
        {
          "price": "52.60",
          "time": "2017-03-30T17:03:48Z"
        },
        {
          "price": "52.60",
          "time": "2017-03-30T17:03:38Z"
        },
        {
          "price": "52.54",
          "time": "2017-03-30T17:03:28Z"
        },
        {
          "price": "52.54",
          "time": "2017-03-30T17:03:18Z"
        },
        {
          "price": "52.54",
          "time": "2017-03-30T17:03:08Z"
        },
        {
          "price": "52.53",
          "time": "2017-03-30T17:02:58Z"
        },
        {
          "price": "52.53",
          "time": "2017-03-30T17:02:48Z"
        },
        {
          "price": "52.53",
          "time": "2017-03-30T17:02:38Z"
        },
        {
          "price": "52.53",
          "time": "2017-03-30T17:02:28Z"
        },
        .....

Success!

I'll sent a PR their way. but for now you can use my code snippet.

PR submitted


问:
Licensing modules on a web-application
Let's say that you have a Web Site that has a bunch of different modules to it such as:

Accouting ( Handle customers, invoices, etc )

Notes and Documents ( Create and Manage your documents )

Many more..

How would you restrict access one of the "Modules" if one customer does not have the appropriate license?

I've often seen components that comes with a .lic file, how do you generate one of those?

And if you use a method like that does it affect performance?

Edit

Another thing I was thinking about, if you ship all modules with your application and you only want to show the controls that you have licensed, do you need to check each control for validity or can you somehow extract that information?

答:
One way to do this to have have a bit array in which each flag corresponds to a particular module or feature. While generating a license, set the bit array according to the modules that the customer has purchased, then sign this bit array using an algorithm such as RSA. Then, in your software, verify the signature and retrieve the bit array to determine which modules to activate.

Take a look at CryptoLicensing which has support for this very scenario - you can specify upto 2040 features/modules in each generated license.

Title: Licensing modules on a web-application


问:
TypeScript type inference issue with string literal
In a react-native application, I have the style

```<code>const styles = StyleSheet.create({
    text: {
        textAlign: "center"
    },
})
</code>```

used in <Text style={styles.text} />, but the tsc compiler gives the following error:

```<code>Types of property 'textAlign' are incompatible.
Type 'string' is not assignable to type '"center" | "auto" | "left" | "right"'.
</code>```

The definition of TextStyle in @types/react-native includes:

```<code>export interface TextStyle extends TextStyleIOS, TextStyleAndroid,
ViewStyle {
    // ...
    textAlign?: "auto" | "left" | "right" | "center"
    // ...
}
</code>```

Why is the compiler complaining about incompatibility? It seems that it is inferring the type of textAlign to be the too general string instead of checking the actual value ("center").

I know that I can use a as TextStyle to avoid the problem, but I would like to know why it is happening and if I should file a ticket against the compiler.

答:
This ought to work:

```<code>const styles = StyleSheet.create({
    text: {
        textAlign: "center" as "center"
    },
})
</code>```

Normally TypeScript would type textAlign as string, but since it can't just be any string, you can cast it to the more specific type.

Body:
In a react-native application, I have the style

const styles = StyleSheet.create({
    text: {
        textAlign: "center"
    },
})

used in <Text style={styles.text} />, but the tsc compiler gives the following error:

Types of property 'textAlign' are incompatible.
Type 'string' is not assignable to type '"center" | "auto" | "left" | "right"'.

The definition of TextStyle in @types/react-native includes:

export interface TextStyle extends TextStyleIOS, TextStyleAndroid,
ViewStyle {
    // ...
    textAlign?: "auto" | "left" | "right" | "center"
    // ...
}

Why is the compiler complaining about incompatibility? It seems that it is inferring the type of textAlign to be the too general string instead of checking the actual value ("center").

I know that I can use a as TextStyle to avoid the problem, but I would like to know why it is happening and if I should file a ticket against the compiler.

Body:
This ought to work:

const styles = StyleSheet.create({
    text: {
        textAlign: "center" as "center"
    },
})

Normally TypeScript would type textAlign as string, but since it can't just be any string, you can cast it to the more specific type.


问:
Best way to unit test JAX-RS Controller?
I am learning the library javax.ws.rs so I wrote a toy API.

For instance, I've got this POST method working. I've seen that there are many libraries for testing, like Jersey or Rest Assured, but, how can I unit test that response code is 200 and that the content is "hello"?

```<code> @POST
     @Path("/getFoo")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     Foo getFoo(@BeanParam final Foo foo)
    {
            return new Foo("hello");
    }
</code>```

答:
For Jersey web services testing there are several testing frameworks, namely: Jersey Test Framework (https://jersey.java.net/documentation/1.17/test-framework.html) and REST-Assured (https://code.google.com/p/rest-assured) - see here a comparison/setup of both (http://www.hascode.com/2011/09/rest-assured-vs-jersey-test-framework-testing-your-restful-web-services/).</p>

```<code>package com.example.rest;

import static com.jayway.restassured.RestAssured.expect;
import groovyx.net.http.ContentType;

import org.junit.Before;
import org.junit.Test;

import com.jayway.restassured.RestAssured;

public class Products{

    @Before
    public void setUp(){
        RestAssured.basePath = "http://localhost:8080";
    }

    @Test
    public void testGetProducts(){
        expect().statusCode(200).contentType(ContentType.JSON).when()
                .get("/getProducts/companyid/companyname/12345088723");
    }

}
</code>```

Body:
I am learning the library javax.ws.rs so I wrote a toy API.

For instance, I've got this POST method working. I've seen that there are many libraries for testing, like Jersey or Rest Assured, but, how can I unit test that response code is 200 and that the content is "hello"?

 @POST
     @Path("/getFoo")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     Foo getFoo(@BeanParam final Foo foo)
    {
            return new Foo("hello");
    }

Body:
For Jersey web services testing there are several testing frameworks, namely: Jersey Test Framework (https://jersey.java.net/documentation/1.17/test-framework.html) and REST-Assured (https://code.google.com/p/rest-assured) - see here a comparison/setup of both (http://www.hascode.com/2011/09/rest-assured-vs-jersey-test-framework-testing-your-restful-web-services/).

package com.example.rest;

import static com.jayway.restassured.RestAssured.expect;
import groovyx.net.http.ContentType;

import org.junit.Before;
import org.junit.Test;

import com.jayway.restassured.RestAssured;

public class Products{

    @Before
    public void setUp(){
        RestAssured.basePath = "http://localhost:8080";
    }

    @Test
    public void testGetProducts(){
        expect().statusCode(200).contentType(ContentType.JSON).when()
                .get("/getProducts/companyid/companyname/12345088723");
    }

}