问:
Python Multiprocessing calling object method
I want to use Python's multiprocessing module to start a new process which creates some other object and calls that objects loops_forever method.

In my main class I have:

```<code>import OtherService
from multiprocessing import Process
my_other_service = OtherService(address=ADDRESS)
my_other_process = Process(target=my_other_service.loops_forever())
print("got here")
my_other_process.start()
print("done")
</code>```

When I run this code, "got here" never gets printed. loops_forever gets called just above the "got here" print, and control never returns back to my main class.

What am I doing wrong here?
I have used multiprocessing before in this fashion:

```<code>my_other_process = Process(target=OtherService, kwargs={"address":ADDRESS})
my_other_process.start()
</code>```

which correctly calls OtherService's init function and runs the init function as a separate process.
The only difference is this time I want to call init function AND then run the loops_forever method forever as a separate process.

答: When you do target=my_other_service.loops_forever(), you call loops_forever. To pass it as a function, rather than call it, you would drop the parentheses, like target=my_other_service.loops_forever.

Body:
I want to use Python's multiprocessing module to start a new process which creates some other object and calls that objects loops_forever method.

In my main class I have:

import OtherService
from multiprocessing import Process
my_other_service = OtherService(address=ADDRESS)
my_other_process = Process(target=my_other_service.loops_forever())
print("got here")
my_other_process.start()
print("done")

When I run this code, "got here" never gets printed. loops_forever gets called just above the "got here" print, and control never returns back to my main class.

What am I doing wrong here?
I have used multiprocessing before in this fashion:

my_other_process = Process(target=OtherService, kwargs={"address":ADDRESS})
my_other_process.start()

which correctly calls OtherService's init function and runs the init function as a separate process.
The only difference is this time I want to call init function AND then run the loops_forever method forever as a separate process.


来源: stackexchange

问:
How to customise font size of Table of Contents generated by package{tocloft} in LATEX
I am using document class "report" and package {tocloft}. I am having a problem in changing font size of sections, chapters, subsections explicitly on Table of Contents generated by "\tableofcontents". It is actually taking the size of contents as they are present in  report but I want to alter the font size of table of contents page .

```<code>\documentclass{report}

\usepackage{tocloft,lipsum,pgffor}

\setcounter{tocdepth}{3}% Include up to \subsubsection in ToC

\renewcommand{\cftpartfont}{\normalfont\sffamily\bfseries}% \part font in ToC
\renewcommand{\cftchapfont}{\normalfont\large\itshape}    % \chapter font in ToC
\renewcommand{\cftsecfont}{\normalfont\slshape}           % \section font in ToC
\renewcommand{\cftsubsecfont}{\normalfont\itshape}        % \subsection font in ToC
\renewcommand{\cftsubsubsecfont}{\normalfont\small}       % \subsubsection font in ToC

\begin{document}

\tableofcontents% ToC

% Create a dummy document with multiple (5) levels of sectional units
\foreach \curpart in {\Huge First, Second, Third, Last} {
  \part{\curpart{} part}
  \foreach \curchap in {\huge First, Second, Third, Last} {
    \chapter{\curchap{} chapter} \lipsum[1]
    \foreach \cursec in {\LARGE First, Second, Third, Last} {
      \section{\cursec{} section}\lipsum[2]
      \foreach \cursubsec in {First, Second, Third, Last} {
        \subsection{\cursubsec{} subsection}\lipsum[3]
        \foreach \cursubsubsec in {First, Second, Third, Last} {
          \subsubsection{\cursubsubsec{} subsubsection}\lipsum[4]
        }% \subsubsection
      }% \subsection
    }% \section
  }% \chapter
}% \part

\end{document}
</code>```

I have added \huge and \LARGE in section headings in dummy document.

```<code>\foreach \curchap in {\huge First, Second, Third, Last} {
    \chapter{\curchap{} chapter} \lipsum[1]
    \foreach \cursec in {\LARGE First, Second, Third, Last} {
</code>```

Doing this also reflects the change in size of that section heading in TOC page.
Before adding \huge and \LARGE inside the section heading

After

I want to make font size of sections and chapter headings in TOC page to be independent of what happens to them inside the document.

答:
You should avoid using font changes within the sectional unit title, as these make their way into the ToC by default. For the odd change in font, I'd suggest using

```<code>\section[<ToC entry>]{<document entry>}
</code>```

where you can specify whatever you want inside <document entry>, but leave <ToC entry> without any font changes. For a more global approach to setting fonts for sectional units, use a package that provides hooks to font settings for <ToC entry> and <document entry>, respectively.

<document entry> font changes is made easy using sectsty or titlesec, while <ToC entry> changes is most typically made using tocloft or titletoc. Specific to sectsty, redefine \Xfont for the sectional unit X. For example,

```<code>\renewcommand{\partfont}{\normalfont\Huge\bfseries}
</code>```

will affect only the <document content> of \part, leaving the <ToC entry> untouched (and without font changes).

For each sectional unit X within the ToC, tocloft provides \cftZfont where X denotes (from the tocloft documentation, section 2.3 Typesetting entries):

part for \part titles

chap for \chapter titles

sec for \section titles

subsec for \subsection titles

subsubsec for \subsubsection titles

para for \paragraph titles

subpara for \subparagraph titles

fig for figure \caption titles

subfig for subfigure \caption titles

tab for table \caption titles

subtab for subtable \caption titles

Here's an example of how to change the various components associated with different sectional units:

```<code>\documentclass{report}

\usepackage{tocloft,lipsum,pgffor,sectsty}

\setcounter{tocdepth}{3}% Include up to \subsubsection in ToC

% Font changes to ToC content of sectional units
\renewcommand{\cftpartfont}{\normalfont\sffamily\bfseries}% \part font in ToC
\renewcommand{\cftchapfont}{\normalfont\large\itshape}    % \chapter font in ToC
\renewcommand{\cftsecfont}{\normalfont\slshape}           % \section font in ToC
\renewcommand{\cftsubsecfont}{\normalfont\itshape}        % \subsection font in ToC
\renewcommand{\cftsubsubsecfont}{\normalfont\small}       % \subsubsection font in ToC

% Font changes to document content of sectional units
\renewcommand{\partfont}{\normalfont\Huge\bfseries}
\renewcommand{\chapterfont}{\normalfont\huge\bfseries}
\renewcommand{\sectionfont}{\normalfont\LARGE\bfseries}

\begin{document}

\tableofcontents% ToC

% Create a dummy document with multiple (5) levels of sectional units
\foreach \curpart in {First, Second, Third, Last} {
  \part{\curpart{} part}
  \foreach \curchap in {First, Second, Third, Last} {
    \chapter{\curchap{} chapter} \lipsum[1]
    \foreach \cursec in {First, Second, Third, Last} {
      \section{\cursec{} section}\lipsum[2]
      \foreach \cursubsec in {First, Second, Third, Last} {
        \subsection{\cursubsec{} subsection}\lipsum[3]
        \foreach \cursubsubsec in {First, Second, Third, Last} {
          \subsubsection{\cursubsubsec{} subsubsection}\lipsum[4]
        }% \subsubsection
      }% \subsection
    }% \section
  }% \chapter
}% \part

\end{document}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using document class "report" and package {tocloft}. I am having a problem in changing font size of sections, chapters, subsections explicitly on Table of Contents generated by "\tableofcontents". It is actually taking the size of contents as they are present in  report but I want to alter the font size of table of contents page .

\documentclass{report}

\usepackage{tocloft,lipsum,pgffor}

\setcounter{tocdepth}{3}% Include up to \subsubsection in ToC

\renewcommand{\cftpartfont}{\normalfont\sffamily\bfseries}% \part font in ToC
\renewcommand{\cftchapfont}{\normalfont\large\itshape}    % \chapter font in ToC
\renewcommand{\cftsecfont}{\normalfont\slshape}           % \section font in ToC
\renewcommand{\cftsubsecfont}{\normalfont\itshape}        % \subsection font in ToC
\renewcommand{\cftsubsubsecfont}{\normalfont\small}       % \subsubsection font in ToC

\begin{document}

\tableofcontents% ToC

% Create a dummy document with multiple (5) levels of sectional units
\foreach \curpart in {\Huge First, Second, Third, Last} {
  \part{\curpart{} part}
  \foreach \curchap in {\huge First, Second, Third, Last} {
    \chapter{\curchap{} chapter} \lipsum[1]
    \foreach \cursec in {\LARGE First, Second, Third, Last} {
      \section{\cursec{} section}\lipsum[2]
      \foreach \cursubsec in {First, Second, Third, Last} {
        \subsection{\cursubsec{} subsection}\lipsum[3]
        \foreach \cursubsubsec in {First, Second, Third, Last} {
          \subsubsection{\cursubsubsec{} subsubsection}\lipsum[4]
        }% \subsubsection
      }% \subsection
    }% \section
  }% \chapter
}% \part

\end{document}

I have added \huge and \LARGE in section headings in dummy document.

\foreach \curchap in {\huge First, Second, Third, Last} {
    \chapter{\curchap{} chapter} \lipsum[1]
    \foreach \cursec in {\LARGE First, Second, Third, Last} {

Doing this also reflects the change in size of that section heading in TOC page.
Before adding \huge and \LARGE inside the section heading

After

I want to make font size of sections and chapter headings in TOC page to be independent of what happens to them inside the document.

Body:
You should avoid using font changes within the sectional unit title, as these make their way into the ToC by default. For the odd change in font, I'd suggest using

\section[<ToC entry>]{<document entry>}

where you can specify whatever you want inside <document entry>, but leave <ToC entry> without any font changes. For a more global approach to setting fonts for sectional units, use a package that provides hooks to font settings for <ToC entry> and <document entry>, respectively.

<document entry> font changes is made easy using sectsty or titlesec, while <ToC entry> changes is most typically made using tocloft or titletoc. Specific to sectsty, redefine \Xfont for the sectional unit X. For example,

\renewcommand{\partfont}{\normalfont\Huge\bfseries}

will affect only the <document content> of \part, leaving the <ToC entry> untouched (and without font changes).

For each sectional unit X within the ToC, tocloft provides \cftZfont where X denotes (from the tocloft documentation, section 2.3 Typesetting entries):

part for \part titles

chap for \chapter titles

sec for \section titles

subsec for \subsection titles

subsubsec for \subsubsection titles

para for \paragraph titles

subpara for \subparagraph titles

fig for figure \caption titles

subfig for subfigure \caption titles

tab for table \caption titles

subtab for subtable \caption titles

Here's an example of how to change the various components associated with different sectional units:

\documentclass{report}

\usepackage{tocloft,lipsum,pgffor,sectsty}

\setcounter{tocdepth}{3}% Include up to \subsubsection in ToC

% Font changes to ToC content of sectional units
\renewcommand{\cftpartfont}{\normalfont\sffamily\bfseries}% \part font in ToC
\renewcommand{\cftchapfont}{\normalfont\large\itshape}    % \chapter font in ToC
\renewcommand{\cftsecfont}{\normalfont\slshape}           % \section font in ToC
\renewcommand{\cftsubsecfont}{\normalfont\itshape}        % \subsection font in ToC
\renewcommand{\cftsubsubsecfont}{\normalfont\small}       % \subsubsection font in ToC

% Font changes to document content of sectional units
\renewcommand{\partfont}{\normalfont\Huge\bfseries}
\renewcommand{\chapterfont}{\normalfont\huge\bfseries}
\renewcommand{\sectionfont}{\normalfont\LARGE\bfseries}

\begin{document}

\tableofcontents% ToC

% Create a dummy document with multiple (5) levels of sectional units
\foreach \curpart in {First, Second, Third, Last} {
  \part{\curpart{} part}
  \foreach \curchap in {First, Second, Third, Last} {
    \chapter{\curchap{} chapter} \lipsum[1]
    \foreach \cursec in {First, Second, Third, Last} {
      \section{\cursec{} section}\lipsum[2]
      \foreach \cursubsec in {First, Second, Third, Last} {
        \subsection{\cursubsec{} subsection}\lipsum[3]
        \foreach \cursubsubsec in {First, Second, Third, Last} {
          \subsubsection{\cursubsubsec{} subsubsection}\lipsum[4]
        }% \subsubsection
      }% \subsection
    }% \section
  }% \chapter
}% \part

\end{document}


问:
Overriding prototype.toString doesn't work
I have the following code.

```<code>function Test() {
    this.myTest = "Test";
}

Test.prototype.toString = function testToString() {
    return this.myTest;
};

var test = new Test();
console.log(test);
</code>```

I expect this to print Test, but it prints Test { myTest: 'Test' }. I thought that overriding toString should use that new function whenever it tries to convert to a string. Any ideas why this isn't working?

答:
function Test() {
    this.myTest = "Test";
}

Test.prototype.toString = function testToString() {
    return this.myTest;
};

var test = new Test();
console.log(test.toString());```

Body:
I have the following code.

function Test() {
    this.myTest = "Test";
}

Test.prototype.toString = function testToString() {
    return this.myTest;
};

var test = new Test();
console.log(test);

I expect this to print Test, but it prints Test { myTest: 'Test' }. I thought that overriding toString should use that new function whenever it tries to convert to a string. Any ideas why this isn't working?


问:
IP Address showing instead of Domain name on my Wordpress site
I am having an issue where I have a Domain name from Go Daddy, and I am hosting a WP site on Amazon Web Services EC2.   I have already changed the A record to so the site pulls up anytime i go to www.bemoremarketing.com.  Everything works fine until I hit the home bottom on the website.   At that point the IP comes up in in the address bar.   Any pages i access after that will have the IPaddress/page </p>

<p>From what I have gathered, I may need to change something in the wp-config.php, but I am unable to find where this is.    Any help is appreciated. </p>

答:
I do not know if this is still of interest but make sure you have all your pages linking to the actual www.yoursite.com

Also, make sure that your HOME link on the menu links to the www.yoursite.com instead of IP.

Changes made in the WP Settings > General are also needed.

Body:
I am having an issue where I have a Domain name from Go Daddy, and I am hosting a WP site on Amazon Web Services EC2.   I have already changed the A record to so the site pulls up anytime i go to www.bemoremarketing.com.  Everything works fine until I hit the home bottom on the website.   At that point the IP comes up in in the address bar.   Any pages i access after that will have the IPaddress/page

From what I have gathered, I may need to change something in the wp-config.php, but I am unable to find where this is.    Any help is appreciated.


问:
How to make Gradle 2.x, Gradle 3.x, Gradle 4.x to run with Java 9?
When using Gradle 2.x, 3.x, and 4.x that only supports Java 8, the gradle runtime does NOT run. I just installed JDK 9 on my MAC and now Gradle 2.x does NOT run. Any versions before 4.2.1.

```<code>$ gradle
$
</code>```

Nothing happens... How to fix that?

答:
According to https://blog.gradle.org/java-9-support-update, Java 9 support for Gradle came to Gradle 4.2.1.

After installing Java 9, you will have it by default in your system:

```<code>$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    9.0.1, x86_64:  "Java SE 9.0.1" /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
    1.8.0_131, x86_64:  "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
</code>```

At this point, you need to find the Gradle executable and change the JAVA_HOME to point to your Java 8 version because you still have it installed. Change the binary to define the JAVA_HOME to point to the Version 8 version.

```<code>~ ⌚ 22:54:20
$ which gradle
/usr/local/bin/gradle

~ ⌚ 11:19:12
$ vim /usr/local/bin/gradle

#!/usr/bin/env bash

##############################################################################
##
##  Gradle start up script for UN*X
##
##############################################################################

JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
</code>```

After this, Gradle will work again!

```<code>$ gradle --version

------------------------------------------------------------
Gradle 2.13
------------------------------------------------------------

Build time:   2016-04-25 04:10:10 UTC
Build number: none
Revision:     3b427b1481e46232107303c90be7b05079b05b1c

Groovy:       2.4.4
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_131 (Oracle Corporation 25.131-b11)
OS:           Mac OS X 10.12.6 x86_64
</code>```

Body:
When using Gradle 2.x, 3.x, and 4.x that only supports Java 8, the gradle runtime does NOT run. I just installed JDK 9 on my MAC and now Gradle 2.x does NOT run. Any versions before 4.2.1.

$ gradle
$

Nothing happens... How to fix that?

Body:
According to https://blog.gradle.org/java-9-support-update, Java 9 support for Gradle came to Gradle 4.2.1.

After installing Java 9, you will have it by default in your system:

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    9.0.1, x86_64:  "Java SE 9.0.1" /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
    1.8.0_131, x86_64:  "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home

At this point, you need to find the Gradle executable and change the JAVA_HOME to point to your Java 8 version because you still have it installed. Change the binary to define the JAVA_HOME to point to the Version 8 version.

~ ⌚ 22:54:20
$ which gradle
/usr/local/bin/gradle

~ ⌚ 11:19:12
$ vim /usr/local/bin/gradle

#!/usr/bin/env bash

##############################################################################
##
##  Gradle start up script for UN*X
##
##############################################################################

JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"

After this, Gradle will work again!

$ gradle --version

------------------------------------------------------------
Gradle 2.13
------------------------------------------------------------

Build time:   2016-04-25 04:10:10 UTC
Build number: none
Revision:     3b427b1481e46232107303c90be7b05079b05b1c

Groovy:       2.4.4
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_131 (Oracle Corporation 25.131-b11)
OS:           Mac OS X 10.12.6 x86_64


问:
How to properly declare/initialize/finalize dynamic array of structs with other dynamic arrays
So what i want to achieve is global variable which represents pointer to dynamic array of structs which has other pointers to dynamic arrays inside.

So i've declared everything in the header file like that:

```<code>/*** "GLOB.h" ***/

//Dynamic Array of fixed Arrays of 4 floats each
typedef float DArray1[][4];

//Dynamic Array of Integers
typedef int DArray2[];

//Struct
struct MyStruct
{
    //pointer to DArray1
    DArray1 * A1;
    //pointer to DArray2
    DArray2 * A2;
    //Length of A1 and A2
    int len = 1;
    //Some other simple elements of fixed size
};

//Dynamic Array of Structs
typedef MyStruct DAStructs[];

namespace GLOB
{
    //pointer to DAStructs
    extern DAStructs * SS;
    //Few other simple variables initialized in place
};
</code>```

Because i don't rly sure if i declared everything properly - first question is: how to declare such data-structure in C/C++?

And second(+third) is: how to properly initialize and finalize it with some variable length?

I guess initialization and finalization should be something like that:

```<code>#include "GLOB.h"

namespace GLOB
{
    void Init_SS(int len) {
        SS = new MyStruct*[len];
        for(int k=0; k<len; k++){
            SS[k].A1 = new float*[1][4];
            for(int j=0; j<4; j++) SS[k].A1[0][j] = 0.0;
            SS[k].A2 = new int*[1];
            SS[k].A2[0] = 0;
        }
    }
    void Fin_SS() {
        int len = length(SS);
        for(int k=0; k<len; k++){
            delete [] SS[k].A1;
            delete [] SS[k].A2;
        }
        delete [] SS;
    }
}
</code>```

But obviously it's just a mess of nonsense and not the appropriate code...

P.S. i'd rather avoid using  or any other solutions cuz i want to learn first of all and second i need as much control over how elements will be placed in memory as possible cuz later i'll need to pass pointer to such structure to other functions imported from DLLs...

答:
Well nobody answered, but actually the answer was really simple, cuz i did everything almost properly =)

My first (and main) mistake was that i forgot that arrays in C are just pointers to first elements, so instead of

```<code>typedef float DArray1[][4];
typedef int DArray2[];
typedef MyStruct DAStructs[];
</code>```

it should be

```<code>typedef float (*DArray1)[4];
typedef int * DArray2;
typedef MyStruct * DAStructs;
</code>```

And it's not needed to make pointer to array, cuz array is already pointer lol

And my second mistake was that i forgot (well it's not like i knew it =) that length of array in C not stored anywhere, so instead of length(SS) it should be another variable where length should be stored manually upon allocation.

But the whole logic which i assumed seem to be legit, and it works fine. Even tho i didn't tested my project for memory leaks, when i use finalization procedure it seem to free allocated memory without any problems...

Body:
So what i want to achieve is global variable which represents pointer to dynamic array of structs which has other pointers to dynamic arrays inside.

So i've declared everything in the header file like that:

/*** "GLOB.h" ***/

//Dynamic Array of fixed Arrays of 4 floats each
typedef float DArray1[][4];

//Dynamic Array of Integers
typedef int DArray2[];

//Struct
struct MyStruct
{
    //pointer to DArray1
    DArray1 * A1;
    //pointer to DArray2
    DArray2 * A2;
    //Length of A1 and A2
    int len = 1;
    //Some other simple elements of fixed size
};

//Dynamic Array of Structs
typedef MyStruct DAStructs[];

namespace GLOB
{
    //pointer to DAStructs
    extern DAStructs * SS;
    //Few other simple variables initialized in place
};

Because i don't rly sure if i declared everything properly - first question is: how to declare such data-structure in C/C++?

And second(+third) is: how to properly initialize and finalize it with some variable length?

I guess initialization and finalization should be something like that:

#include "GLOB.h"

namespace GLOB
{
    void Init_SS(int len) {
        SS = new MyStruct*[len];
        for(int k=0; k<len; k++){
            SS[k].A1 = new float*[1][4];
            for(int j=0; j<4; j++) SS[k].A1[0][j] = 0.0;
            SS[k].A2 = new int*[1];
            SS[k].A2[0] = 0;
        }
    }
    void Fin_SS() {
        int len = length(SS);
        for(int k=0; k<len; k++){
            delete [] SS[k].A1;
            delete [] SS[k].A2;
        }
        delete [] SS;
    }
}

But obviously it's just a mess of nonsense and not the appropriate code...

P.S. i'd rather avoid using  or any other solutions cuz i want to learn first of all and second i need as much control over how elements will be placed in memory as possible cuz later i'll need to pass pointer to such structure to other functions imported from DLLs...

Body:
Well nobody answered, but actually the answer was really simple, cuz i did everything almost properly =)

My first (and main) mistake was that i forgot that arrays in C are just pointers to first elements, so instead of

typedef float DArray1[][4];
typedef int DArray2[];
typedef MyStruct DAStructs[];

it should be

typedef float (*DArray1)[4];
typedef int * DArray2;
typedef MyStruct * DAStructs;

And it's not needed to make pointer to array, cuz array is already pointer lol

And my second mistake was that i forgot (well it's not like i knew it =) that length of array in C not stored anywhere, so instead of length(SS) it should be another variable where length should be stored manually upon allocation.

But the whole logic which i assumed seem to be legit, and it works fine. Even tho i didn't tested my project for memory leaks, when i use finalization procedure it seem to free allocated memory without any problems...


问:
Accessing specific array based on key in ngFor
```<code><button *ngFor="let item of items[category]"> </button>
</code>```

Where items: { cat1: [], cat2: [] }.
I need category to be a string variable to access the two arrays in items.
How do i tackle this?

答:
try this:

```<code>//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
         <button *ngFor="let item of items[category]" > {{item}}</button>
    </div>
  `,
})
export class App {
  items: any =  { cat1: ['cat1','cat2'], cat2: ['peter','peter2'] };
  category = 'cat1';
  constructor() {
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
</code>```

plunkr working:

https://plnkr.co/edit/w1YJeZPAMwN5WP3uVhZ7

Body:
<button *ngFor="let item of items[category]"> </button>

Where items: { cat1: [], cat2: [] }.
I need category to be a string variable to access the two arrays in items.
How do i tackle this?

Body:
try this:

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
         <button *ngFor="let item of items[category]" > {{item}}</button>
    </div>
  `,
})
export class App {
  items: any =  { cat1: ['cat1','cat2'], cat2: ['peter','peter2'] };
  category = 'cat1';
  constructor() {
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

plunkr working:

https://plnkr.co/edit/w1YJeZPAMwN5WP3uVhZ7


问:
How to Split or break a Python list into Unequal chunks, with specified chunk sizes
I have two Python lists of numbers.

```<code>list1 = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563]
list2 = [2,5,14,3] ##these numbers specify desired chunk sizes
</code>```

I would like to create subsets or sub-lists of list1 by splitting list1 according to the size numbers in list2.
As a result, I would like to have this:

```<code>a_list = [123,452] ##correspond to first element (2) in list2; get the first two numbers from list1
b_list = [342,533,222,402,124] ##correspond to second element (5) in list2; get the next 5 numbers from list1
c_list = [125,263,254,44,987,78,655,741,165,597,26,15,799,100] ##next 14 numbers from list1
d_list = [154,122,563] ##next 3 numbers from list1
</code>```

Essentially, each chunk should follow list2. This means, the first chunk should have the first 2 elements from list1,
the second chunk should have the next 5 elements, and so on.

How can I do this?

Body:
I have two Python lists of numbers.

list1 = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563]
list2 = [2,5,14,3] ##these numbers specify desired chunk sizes

I would like to create subsets or sub-lists of list1 by splitting list1 according to the size numbers in list2.
As a result, I would like to have this:

a_list = [123,452] ##correspond to first element (2) in list2; get the first two numbers from list1
b_list = [342,533,222,402,124] ##correspond to second element (5) in list2; get the next 5 numbers from list1
c_list = [125,263,254,44,987,78,655,741,165,597,26,15,799,100] ##next 14 numbers from list1
d_list = [154,122,563] ##next 3 numbers from list1

Essentially, each chunk should follow list2. This means, the first chunk should have the first 2 elements from list1,
the second chunk should have the next 5 elements, and so on.

How can I do this?

Body:
Create an iterator over the data, and then call next on it for each range you need:

>>> data = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563]
>>> sizes = [2, 5, 14, 3]
>>> it = iter(data)
>>> [[next(it) for _ in range(size)] for size in sizes]
[[123, 452],
 [342, 533, 222, 402, 124],
 [125, 263, 254, 44, 987, 78, 655, 741, 165, 597, 26, 15, 799, 100],
 [154, 122, 563]]


问:
Internet Explorer lowers text inside element with odd height
I have this element:

.container {
  font-size: 14px;
  line-height: 20px;
  font-family: "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.link {
  color: #3072c4;
  cursor: pointer;
}

.counter {
    display: inline-block;
    min-width: 9px;
    padding: 0 4px;
    text-align: center;
    line-height: 17px;
    background: #FF8000;
    color: #fff;
    font-size: 12px;
    font-weight: 700;
    border-radius: 17px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="container">
  <span class="link">
      Feedback
    </span>
      <span class="counter">166</span>
 </span></code>```

Its height must be 17px, horizontal padding should be 4px and font size should be 12px. It looks like a prototype in Chrome and Firefox:

But there is a problem in Internet Explorer:

It lowers the text inside, it is not well aligned vertically. If I set line-height and width of element to 18px (as well as every other even value), everything is OK, but I need 17px. How to avoid text lowering in IE?

答:
You can add a specific style for IE. You can try this:

.container {
      font-size: 14px;
      line-height: 20px;
      font-family: "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif;
    }

    .link {
      color: #3072c4;
      cursor: pointer;
    }

    .counter {
        display: inline-block;
        min-width: 9px;
        padding: 0 4px;
        text-align: center;
        line-height: 17px;
        background: #FF8000;
        color: #fff;
        font-size: 12px;
        font-weight: 700;
        border-radius: 17px;
    }
    @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
      /* IE Edge 12+ CSS styles go here */
      .counter {
          display: inline-block;
          min-width: 9px;
          padding: 0px 4px 1px 4px;
          text-align: center;
          line-height: 17px;
          background: #FF8000;
          color: #fff;
          font-size: 12px;
          font-weight: 700;
          border-radius: 17px;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="container">
  <span class="link">
      Feedback
    </span>
      <span class="counter">166</span>
 </span></code>```

Body:
I have this element:

.container {
  font-size: 14px;
  line-height: 20px;
  font-family: "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.link {
  color: #3072c4;
  cursor: pointer;
}

.counter {
    display: inline-block;
    min-width: 9px;
    padding: 0 4px;
    text-align: center;
    line-height: 17px;
    background: #FF8000;
    color: #fff;
    font-size: 12px;
    font-weight: 700;
    border-radius: 17px;
}

      Feedback

      166

Its height must be 17px, horizontal padding should be 4px and font size should be 12px. It looks like a prototype in Chrome and Firefox:

But there is a problem in Internet Explorer:

It lowers the text inside, it is not well aligned vertically. If I set line-height and width of element to 18px (as well as every other even value), everything is OK, but I need 17px. How to avoid text lowering in IE?

Body:
You can add a specific style for IE. You can try this:

.container {
      font-size: 14px;
      line-height: 20px;
      font-family: "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif;
    }

    .link {
      color: #3072c4;
      cursor: pointer;
    }

    .counter {
        display: inline-block;
        min-width: 9px;
        padding: 0 4px;
        text-align: center;
        line-height: 17px;
        background: #FF8000;
        color: #fff;
        font-size: 12px;
        font-weight: 700;
        border-radius: 17px;
    }
    @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
      /* IE Edge 12+ CSS styles go here */
      .counter {
          display: inline-block;
          min-width: 9px;
          padding: 0px 4px 1px 4px;
          text-align: center;
          line-height: 17px;
          background: #FF8000;
          color: #fff;
          font-size: 12px;
          font-weight: 700;
          border-radius: 17px;
        }
    }

<span class="container">
  <span class="link">
      Feedback
    </span>
      <span class="counter">166</span>
 </span>


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
I agree with Jeremy McCollum. Maybe you need to stop reading and start doing!

Ok, don't really stop reading, but at some point, the only way to become a better programmer is to actually work with the tool/language you are trying to learn.

My scenario is a lot like yours. While my day job is programmer, it's not C# or even .Net. The way I got the coin to drop was to actually start working on a real project. It's not even a big project, but it's a real project where I had to learn how to do a number of things I had never done (in C#).

Do exactly what you said you can't: sit down, open up VS2008, and start coding. Just do it!

Approach it like a real job, no easy outs! Pretend your employment depends on it. For me, it actually does, since I do want to get a C# job at some point in the future. If I can't complete projects, that will never happen.

OwnerDisplayName: GregD

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: GregD

OwnerDisplayName: Dennis


问:
Fastest way to count folder files in .NET 4.0
I need to count the number of files in a folder in .NET 4:
The count will return number of all files except the .db file in the folder.

Option 1:

```<code> IEnumerable<string> enumerables = Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);
 int iNumFiles = 0;
 foreach (string f in enumerables)
 {
    if (!f.EndsWith(".db"))
       iNumFiles++;
 }

 //iNumFiles is the count
</code>```

Option 2:

```<code>int iNumFiles = 0;
IEnumerable<string> enumerables1 = Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);
IEnumerable<string> enumerables2 = Directory.EnumerateFiles(strPath, "*.db", SearchOption.TopDirectoryOnly);

iNumFiles = enumerables1.Count() - enumerables2.Count();

//iNumFiles is the count
</code>```

Is there any other simpler but better methods (using RegEx or something else) that I should use?

EDIT:
Should I keep the .db file or how useful it is? All I know it is the database (cache) of folder contents.

This is messing up my file count.

Thanks for reading.

Body:
I need to count the number of files in a folder in .NET 4:
The count will return number of all files except the .db file in the folder.

Option 1:

 IEnumerable<string> enumerables = Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);
 int iNumFiles = 0;
 foreach (string f in enumerables)
 {
    if (!f.EndsWith(".db"))
       iNumFiles++;
 }

 //iNumFiles is the count

Option 2:

int iNumFiles = 0;
IEnumerable<string> enumerables1 = Directory.EnumerateFiles(strPath, "*.*", SearchOption.TopDirectoryOnly);
IEnumerable<string> enumerables2 = Directory.EnumerateFiles(strPath, "*.db", SearchOption.TopDirectoryOnly);

iNumFiles = enumerables1.Count() - enumerables2.Count();

//iNumFiles is the count

Is there any other simpler but better methods (using RegEx or something else) that I should use?

EDIT:
Should I keep the .db file or how useful it is? All I know it is the database (cache) of folder contents.

This is messing up my file count.

Thanks for reading.

Body: new DirectoryInfo(strPath).EnumerateFiles("*.db").Count();


问:
Why does batch file execution end unexpected on entering nothing on a user prompt?
I try to make a batch file which asks the user a question (just as a test for if and else statements) and waits for the answer input by the user.

I tried to use:

```<code>@echo off
echo hi!
pause
CLS
echo how are you?
set /p what=
if %what%==Good (
GOTO good
) else (
GOTO what )

:Good
CLS
echo cool!
pause
GOTO end

:what
CLS
echo what?
pause
GOTO end

:end
</code>```

The goal was to go to label what and continue there the batch file processing on user inputs anything other than Good.

But if nothing is entered by the user because of pressing only ENTER, the execution of the batch script just ends rather than going to code below label what. Also if some other things with spaces are typed on prompt, the batch file just ends the script as well.

Why does batch file execution end unexpected on entering nothing on a user prompt?

答:
set /P prompts the user for a string. The user has the freedom

to enter what you are asking for,

just hit RETURN or ENTER without entering anything at all,

enter bad strings like

```<code>a == a rd /s /q "%TEMP%" & rem
</code>```

The last example results with your batch code in deletion of the user's folder for temporary files. So please don't try that user input with your batch file.

When the user enters nothing at all on prompt, the specified environment variable keeps its current value. In your case with environment variable what not defined at all on first run, it is still not defined after the user prompt and therefore the next command line executed by cmd.exe after preprocessing the command line is:

```<code>if ==Good (
</code>```

So the left operand is missing and Windows command interpreter exits the execution of the batch file because of this syntax error as it can be seen on running this batch file from within a command prompt window instead of double clicking on the batch file. See also Debugging a batch file.

To make such a command prompt safe against no input or even bad input, use the following code:

```<code>@echo off
cls
echo Hi!
echo/
set "UserInput="
set /P "UserInput=How are you? "
if not defined UserInput goto WrongInput
setlocal EnableDelayedExpansion
if /I "!UserInput!" == "Good" endlocal & set "UserInput=" & goto Good
endlocal
set "UserInput="

:WrongInput
echo/
echo What?
echo/
pause
goto :EOF

:Good
echo/
echo Cool!
echo/
pause
</code>```

First the environment variable UserInput is definitely deleted before prompting the user.

After the user prompt an IF condition is used to check if the variable UserInput is still not defined which means the user has not input anything at all if that condition is true.

But if the user has entered a string, a new local environment is setup with enabled delayed environment variable expansion, and the value of UserInput is compared case-insensitive with the string "Good" using delayed environment variable expansion. This prevents on accidentally or intentionally wrong input that the batch file execution exits due to a syntax error caused by the user input or do something completely different than being designed for.

In this case the local environment with enabled delayed environment variable expansion is no longer needed after string comparison which always includes also the double quotes around the strings on both sides. Therefore the previous environment is immediately restored in any case.

Well, it is valid to omit if not defined UserInput because of using surrounding double quotes on the two compared strings because the left string can't be empty anymore. And in general it is advisable to define a local environment for a batch file in case of being ever called later from other batch files or from within a command prompt window.

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
cls
echo Hi!
echo/
set "UserInput="
set /P "UserInput=How are you? "
setlocal EnableDelayedExpansion
if /I "!UserInput!" == "Good" endlocal & goto Good
endlocal

echo/
echo What?
echo/
pause
goto EndBatch

:Good
echo/
echo Cool!
echo/
pause

:EndBatch
endlocal
</code>```

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

cls /?

echo /?

endlocal /?

goto /?

if /?

pause /?

set /?

setlocal /?

See also following questions with their answers for even more details and important facts to know on using environment variables within a batch file:

Why is no string output with 'echo %var%' after using 'set var = text' on command line?

Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files

set /p with spaces in variable value

Single line with multiple commands using Windows batch file

Where does GOTO :EOF return to?

DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/

Body:
I try to make a batch file which asks the user a question (just as a test for if and else statements) and waits for the answer input by the user.

I tried to use:

@echo off
echo hi!
pause
CLS
echo how are you?
set /p what=
if %what%==Good (
GOTO good
) else (
GOTO what )

:Good
CLS
echo cool!
pause
GOTO end

:what
CLS
echo what?
pause
GOTO end

:end

The goal was to go to label what and continue there the batch file processing on user inputs anything other than Good.

But if nothing is entered by the user because of pressing only ENTER, the execution of the batch script just ends rather than going to code below label what. Also if some other things with spaces are typed on prompt, the batch file just ends the script as well.

Why does batch file execution end unexpected on entering nothing on a user prompt?

Body:
set /P prompts the user for a string. The user has the freedom

to enter what you are asking for,

just hit RETURN or ENTER without entering anything at all,

enter bad strings like

a == a rd /s /q "%TEMP%" & rem

The last example results with your batch code in deletion of the user's folder for temporary files. So please don't try that user input with your batch file.

When the user enters nothing at all on prompt, the specified environment variable keeps its current value. In your case with environment variable what not defined at all on first run, it is still not defined after the user prompt and therefore the next command line executed by cmd.exe after preprocessing the command line is:

if ==Good (

So the left operand is missing and Windows command interpreter exits the execution of the batch file because of this syntax error as it can be seen on running this batch file from within a command prompt window instead of double clicking on the batch file. See also Debugging a batch file.

To make such a command prompt safe against no input or even bad input, use the following code:

@echo off
cls
echo Hi!
echo/
set "UserInput="
set /P "UserInput=How are you? "
if not defined UserInput goto WrongInput
setlocal EnableDelayedExpansion
if /I "!UserInput!" == "Good" endlocal & set "UserInput=" & goto Good
endlocal
set "UserInput="

:WrongInput
echo/
echo What?
echo/
pause
goto :EOF

:Good
echo/
echo Cool!
echo/
pause

First the environment variable UserInput is definitely deleted before prompting the user.

After the user prompt an IF condition is used to check if the variable UserInput is still not defined which means the user has not input anything at all if that condition is true.

But if the user has entered a string, a new local environment is setup with enabled delayed environment variable expansion, and the value of UserInput is compared case-insensitive with the string "Good" using delayed environment variable expansion. This prevents on accidentally or intentionally wrong input that the batch file execution exits due to a syntax error caused by the user input or do something completely different than being designed for.

In this case the local environment with enabled delayed environment variable expansion is no longer needed after string comparison which always includes also the double quotes around the strings on both sides. Therefore the previous environment is immediately restored in any case.

Well, it is valid to omit if not defined UserInput because of using surrounding double quotes on the two compared strings because the left string can't be empty anymore. And in general it is advisable to define a local environment for a batch file in case of being ever called later from other batch files or from within a command prompt window.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
cls
echo Hi!
echo/
set "UserInput="
set /P "UserInput=How are you? "
setlocal EnableDelayedExpansion
if /I "!UserInput!" == "Good" endlocal & goto Good
endlocal

echo/
echo What?
echo/
pause
goto EndBatch

:Good
echo/
echo Cool!
echo/
pause

:EndBatch
endlocal

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

cls /?

echo /?

endlocal /?

goto /?

if /?

pause /?

set /?

setlocal /?

See also following questions with their answers for even more details and important facts to know on using environment variables within a batch file:

Why is no string output with 'echo %var%' after using 'set var = text' on command line?

Symbol equivalent to NEQ, LSS, GTR, etc. in Windows batch files

set /p with spaces in variable value

Single line with multiple commands using Windows batch file

Where does GOTO :EOF return to?

DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/


问:
QML Repeater and QML Grid Layout with variable number of columns
I have an model that consist of objects with some properties, e.g.:

```<code>ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        color: "green"
        cost: 2.45
    }
    ListElement {
        name: "Orange"
        color: "orange"
        cost: 3.25
    }
    ListElement {
        name: "Banana"
        color: "yellow"
        cost: 1.95
    }
}
</code>```

And now I want to display this model using GridLayout. For each property I want to use one element inside GridLayout, e.g:

```<code>GridLayout {
    columns: 3

    Text { text: "Apple" }
    Rectangle { color: "green" }
    SpinBox { value: 2.45 }

    Text { text: "Orange" }
    Rectangle { color: "orange" }
    SpinBox { value: 3.25 }

    Text { text: "Banana" }
    Rectangle { color: "yellow" }
    SpinBox { value: 1.95 }
}
</code>```

The point is that I can easily change the columns property of GridLayout and make my layout narrower (e.g. to fit small screens). I can use Repeater to fill GridLayout. However such approach will fill my GridLayout in wrong order:

```<code>GridLayout {
    columns: 3

    Repeater {
        model: fruitModel
        Text { text: name }
    }

    Repeater {
        model: fruitModel
        Rectangle { color: color }
    }

    Repeater {
        model: fruitModel
        SpinBox { value: value }
    }
}
</code>```

And it is waste to use Layout.column and Layout.row attached properties since I want to easily change number of columns in GridLayout.

Is there any way to fill GridLayout with data from model row by row?

UPD1:

Behaviour that I want to get:

```<code>GridLayout {
    columns: parent.width > 235 ? 3 : 1

    Text { text: "Apple" }
    Rectangle { color: "green"; width: 40; height: 40 }
    SpinBox { value: 2 }

    Text { text: "Orange" }
    Rectangle { color: "orange"; width: 40; height: 40 }
    SpinBox { value: 3 }

    Text { text: "Banana" }
    Rectangle { color: "yellow"; width: 40; height: 40 }
    SpinBox { value: 1 }
}
</code>```

UPD2:
Modified variant from @m7913d:

```<code>GridLayout {
    id: layout
    property int maxColumns: 3
    columns: parent.width > 235 ? maxColumns : 1

    Repeater {
        model: fruitModel
        Text {
            text: name
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index)
            Layout.column: 0
        }
    }

    Repeater {
        model: fruitModel
        Rectangle {
            Layout.preferredWidth: 30
            Layout.preferredHeight: 30
            color: col
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 1)
            Layout.column: layout.columns == maxColumns ? 1 : 0
        }
    }

    Repeater {
        model: fruitModel
        SpinBox {
            value: val
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 2)
            Layout.column: layout.columns == maxColumns ? 2 : 0
        }
    }
}
</code>```

It's working but not easy-to-modify solution plus sometimes during layout resize there is messages QGridLayoutEngine::addItem: Cell (1, 0) already taken.

答:
A possible approach is to extend this method with condition column/row indexes:</p>

```<code>GridLayout {
    id:gridLayout
    columns: parent.width > 235 ? 3 : 1

    Repeater {
        model: fruitModel
        implicitHeight: 50
        Text {
            text: name
            Layout.row: gridLayout.columns == 3 ? index : 3 * index
            Layout.column: 0
        }
    }

    Repeater {
        model: fruitModel
        Rectangle {
            color: model.color
            implicitWidth: 50
            implicitHeight: 50
            Layout.row: gridLayout.columns == 3 ? index : 3 * index + 1
            Layout.column: gridLayout.columns == 3 ? 1 : 0
        }
    }

    Repeater {
        model: fruitModel
        SpinBox {
            value: value
            Layout.row: gridLayout.columns == 3 ? index : 3 * index + 2
            Layout.column: gridLayout.columns == 3 ? 2 : 0
        }
    }
}
</code>```

Body:
I have an model that consist of objects with some properties, e.g.:

ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        color: "green"
        cost: 2.45
    }
    ListElement {
        name: "Orange"
        color: "orange"
        cost: 3.25
    }
    ListElement {
        name: "Banana"
        color: "yellow"
        cost: 1.95
    }
}

And now I want to display this model using GridLayout. For each property I want to use one element inside GridLayout, e.g:

GridLayout {
    columns: 3

    Text { text: "Apple" }
    Rectangle { color: "green" }
    SpinBox { value: 2.45 }

    Text { text: "Orange" }
    Rectangle { color: "orange" }
    SpinBox { value: 3.25 }

    Text { text: "Banana" }
    Rectangle { color: "yellow" }
    SpinBox { value: 1.95 }
}

The point is that I can easily change the columns property of GridLayout and make my layout narrower (e.g. to fit small screens). I can use Repeater to fill GridLayout. However such approach will fill my GridLayout in wrong order:

GridLayout {
    columns: 3

    Repeater {
        model: fruitModel
        Text { text: name }
    }

    Repeater {
        model: fruitModel
        Rectangle { color: color }
    }

    Repeater {
        model: fruitModel
        SpinBox { value: value }
    }
}

And it is waste to use Layout.column and Layout.row attached properties since I want to easily change number of columns in GridLayout.

Is there any way to fill GridLayout with data from model row by row?

UPD1:

Behaviour that I want to get:

GridLayout {
    columns: parent.width > 235 ? 3 : 1

    Text { text: "Apple" }
    Rectangle { color: "green"; width: 40; height: 40 }
    SpinBox { value: 2 }

    Text { text: "Orange" }
    Rectangle { color: "orange"; width: 40; height: 40 }
    SpinBox { value: 3 }

    Text { text: "Banana" }
    Rectangle { color: "yellow"; width: 40; height: 40 }
    SpinBox { value: 1 }
}

UPD2:
Modified variant from @m7913d:

GridLayout {
    id: layout
    property int maxColumns: 3
    columns: parent.width > 235 ? maxColumns : 1

    Repeater {
        model: fruitModel
        Text {
            text: name
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index)
            Layout.column: 0
        }
    }

    Repeater {
        model: fruitModel
        Rectangle {
            Layout.preferredWidth: 30
            Layout.preferredHeight: 30
            color: col
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 1)
            Layout.column: layout.columns == maxColumns ? 1 : 0
        }
    }

    Repeater {
        model: fruitModel
        SpinBox {
            value: val
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 2)
            Layout.column: layout.columns == maxColumns ? 2 : 0
        }
    }
}

It's working but not easy-to-modify solution plus sometimes during layout resize there is messages QGridLayoutEngine::addItem: Cell (1, 0) already taken.

Body:
A possible approach is to extend this method with condition column/row indexes:

GridLayout {
    id:gridLayout
    columns: parent.width > 235 ? 3 : 1

    Repeater {
        model: fruitModel
        implicitHeight: 50
        Text {
            text: name
            Layout.row: gridLayout.columns == 3 ? index : 3 * index
            Layout.column: 0
        }
    }

    Repeater {
        model: fruitModel
        Rectangle {
            color: model.color
            implicitWidth: 50
            implicitHeight: 50
            Layout.row: gridLayout.columns == 3 ? index : 3 * index + 1
            Layout.column: gridLayout.columns == 3 ? 1 : 0
        }
    }

    Repeater {
        model: fruitModel
        SpinBox {
            value: value
            Layout.row: gridLayout.columns == 3 ? index : 3 * index + 2
            Layout.column: gridLayout.columns == 3 ? 2 : 0
        }
    }
}


问:
How to add Bootrsap icons to Flask-Nav navbar
I am using Flask-Bootrsap/ Flask-Nav support to generate a navbar for my webapp. I have some issues trying to style it. I would like to add bootrsap or font/awesome icons but i don't know how to do it directly from my rendered.

Nav.py

```<code>@nav.navigation()
def mynavbar():
    return Navbar(
        'mysite',
        View('View Historic', 'Link1'),
        View('New users', 'Link2'),
        View('New users', 'Link3'),
        View('Upload file', 'Link4'),
        View('Packages', 'Link5'),
    )
</code>```

Base.html

```<code>{% block navbar %}
    {{nav.mynavbar.render()}}
{% endblock %}
</code>```

答:
Currently there isn't a way through the main branch.

See:
https://github.com/mbr/flask-nav/pull/5
https://github.com/mbr/flask-bootstrap/pull/125

Someone made a branch for both Flask-Nav and Flask-Bootstrap to embed an img tag in the View link.

However, for some reason, the owner has yet to merge the pull request; his cited excuses seem asinine imo.

I'd recommend either using:
https://github.com/nypgand1/flask-nav/tree/feature-ViewImg

or making equivalent modifications for your own usage as the owner seems to not care.

Body:
I am using Flask-Bootrsap/ Flask-Nav support to generate a navbar for my webapp. I have some issues trying to style it. I would like to add bootrsap or font/awesome icons but i don't know how to do it directly from my rendered.

Nav.py

@nav.navigation()
def mynavbar():
    return Navbar(
        'mysite',
        View('View Historic', 'Link1'),
        View('New users', 'Link2'),
        View('New users', 'Link3'),
        View('Upload file', 'Link4'),
        View('Packages', 'Link5'),
    )

Base.html

{% block navbar %}
    {{nav.mynavbar.render()}}
{% endblock %}


问:
R saving Naive Bayes for training, R equivalent to Pythons pickle.
I have been practicing data analysis on Python and have been looking to do the same with R particularly sentiment analysis. With python to train a NB algorithm I could save it as a pickle and reuse to continue training it however I am unsure how I would do this with R.
This is currently what I have followed to train and test a data set using the library e1071. After cleaning the data.

```<code>convert_count <- function(x) {
  y <- ifelse(x > 0, 1,0)
  y <- factor(y, levels=c(0,1), labels=c("No", "Yes"))
  y
}

trainNB <- apply(dtm.train.nb, 2, convert_count)
testNB <- apply(dtm.test.nb, 2, convert_count)

system.time( classifier <- naiveBayes(trainNB, df.train$class, laplace = 1) )

system.time( pred <- predict(classifier, newdata=testNB) )
table("Predictions"= pred,  "Actual" = df.test$class )
</code>```

Can anyone explain to me what the Python pickle equivalent would be when using R?
Another question I have is is using tm to clean the corpus and then using the document term matrix achieve bag of words?

Thanks

答:
I've not used pickling in Python, but it seems like you're just compressing and saving an object, right?

In that case - I would use 'write.fst' from the "fst" package. It serializes data frames. You'll have to do a 'read.fst' when you want to access that object again.

Body:
I have been practicing data analysis on Python and have been looking to do the same with R particularly sentiment analysis. With python to train a NB algorithm I could save it as a pickle and reuse to continue training it however I am unsure how I would do this with R.
This is currently what I have followed to train and test a data set using the library e1071. After cleaning the data.

convert_count <- function(x) {
  y <- ifelse(x > 0, 1,0)
  y <- factor(y, levels=c(0,1), labels=c("No", "Yes"))
  y
}

trainNB <- apply(dtm.train.nb, 2, convert_count)
testNB <- apply(dtm.test.nb, 2, convert_count)

system.time( classifier <- naiveBayes(trainNB, df.train$class, laplace = 1) )

system.time( pred <- predict(classifier, newdata=testNB) )
table("Predictions"= pred,  "Actual" = df.test$class )

Can anyone explain to me what the Python pickle equivalent would be when using R?
Another question I have is is using tm to clean the corpus and then using the document term matrix achieve bag of words?

Thanks


问:
Not able to keep the div fixed while scrolling in an iframe
I have an web application which displays products and its information as a modal when clicked. Now when I run this web application on my localhost, the modal appears and when I scroll it remains fixed at the center of the screen just as I want. This web application is a part of a bigger web application. I use iframe to integrate this web app in the bigger web app.
Now when I click on a product in this case I get the modal but when I scroll down the modal remains at the top, it doesnot come down when I scroll as it did before.
How to fix this?

I am attaching the code and some pics for your reference.

HTML code for the modal

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <div class="popup-wrapper product-detail ibox-content wrapper
wrapper-content animated fadeInRight" data-spy="affix" data-offset-
top="400" ng-show="show" ng-click="closeModalOnOutside($event)">
<div class="popup row ibox-content modal-dialog" >
<button type="button" class="close"  ng-click="closeModal()">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>

    <div class="images col-md-5 col-xs-12" >
    <div class="slick-slide slick-current slick-active" >
    <div class="text-center">
        <img ng-src={{item.Results.Results[0].image}}
             alt="">
    </div>
    </div>
    </div>

    <div class="col-md-7 col-xs-12" >
        <div class="top-wrapper">
            <div class="name-wrapper">
            <h2 class="font-bold m-b-xs">
                                   {{item.Results.Results[0].name}}
                                </h2>

            </div>
            <div class="m-t-md">
                <h2 class="product-main-price">{{'$
    '+item.Results.Results[0].price}} </h2>
            </div>
            <hr>
            <h4>Details:</h4>
            <div class="small text-muted">
                        {{item.Results.Results[0] | tag }}

            </div>
            <hr>
            <div>
            <div class="btn-group">
                <button class="btn btn-primary btn-sm" ng-
             click="goToItem( item.Results.Results[0].product_url)">
                <i class="fa fa-cart-plus"></i> Purchase Item</button>
            </div>
            </div>

        </div>
    </div>
    <div class="loader-wrapper" ng-hide="!isLoading">
        <div class="loader-inner">
            <div class="loader">
                <div class="sk-spinner sk-spinner-wave">
                        <div class="sk-rect1"></div>
                        <div class="sk-rect2"></div>
                        <div class="sk-rect3"></div>
                        <div class="sk-rect4"></div>
                        <div class="sk-rect5"></div>
                    </div>
            </div>
        </div>
    </div>
</div>
</div>
</code>```

CSS code

```<code>.popup-wrapper {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(47, 64, 80, 0.3);
justify-content: center;
align-items: center;
z-index: 50;
padding: 30px;
overflow: auto;
}

.popup-wrapper .popup {
position: relative;
min-height: 200px;
background-color: #fff;
box-shadow: 5px 5px 10px 5px rgba(0, 0, 0, 0.4);
}

.popup-wrapper .popup {
width: 700px;
display: flex;
margin: auto;
}

.product-detail .ibox-content {
padding: 30px 30px 50px 30px;
}
.ibox-content {
clear: both;
}

.ibox-content {
background-color: #ffffff;
color: inherit;
padding: 15px 20px 20px 20px;
border-color: #e7eaec;
border-image: none;
border-style: solid solid none;
border-width: 1px 0;
 }

.modal-dialog {
z-index: 2200;
}
</code>```

Image 1 when it works properly
When I scroll the modal also scrolls down

Image2 when it doesnot work properly
When I integrate it using iframe the modal doesnot scroll down

答:
1st suggestion I have for you is, could you not just remove it out of the iframe and place the markup of the modal with the rest of the doc?

If not then you could make another iframe which only has the modal box then position fixed that iframe.

```<code>iframe {
  position: fixed;
  left: 50%;
  top: 50%;
  width: 80%;
  height: 70%;
  transform: translate(-50%, -50%);
}
</code>```

Codepen example

Body:
I have an web application which displays products and its information as a modal when clicked. Now when I run this web application on my localhost, the modal appears and when I scroll it remains fixed at the center of the screen just as I want. This web application is a part of a bigger web application. I use iframe to integrate this web app in the bigger web app.
Now when I click on a product in this case I get the modal but when I scroll down the modal remains at the top, it doesnot come down when I scroll as it did before.
How to fix this?

I am attaching the code and some pics for your reference.

HTML code for the modal

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<button type="button" class="close"  ng-click="closeModal()">
×
Close
</button>

                                   {{item.Results.Results[0].name}}

{{'$
    '+item.Results.Results[0].price}}

Details:

                        {{item.Results.Results[0] | tag }}

                <button class="btn btn-primary btn-sm" ng-
             click="goToItem( item.Results.Results[0].product_url)">
                 Purchase Item</button>

CSS code

.popup-wrapper {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(47, 64, 80, 0.3);
justify-content: center;
align-items: center;
z-index: 50;
padding: 30px;
overflow: auto;
}

.popup-wrapper .popup {
position: relative;
min-height: 200px;
background-color: #fff;
box-shadow: 5px 5px 10px 5px rgba(0, 0, 0, 0.4);
}

.popup-wrapper .popup {
width: 700px;
display: flex;
margin: auto;
}

.product-detail .ibox-content {
padding: 30px 30px 50px 30px;
}
.ibox-content {
clear: both;
}

.ibox-content {
background-color: #ffffff;
color: inherit;
padding: 15px 20px 20px 20px;
border-color: #e7eaec;
border-image: none;
border-style: solid solid none;
border-width: 1px 0;
 }

.modal-dialog {
z-index: 2200;
}

Image 1 when it works properly
When I scroll the modal also scrolls down

Image2 when it doesnot work properly
When I integrate it using iframe the modal doesnot scroll down

Body:
1st suggestion I have for you is, could you not just remove it out of the iframe and place the markup of the modal with the rest of the doc?

If not then you could make another iframe which only has the modal box then position fixed that iframe.

iframe {
  position: fixed;
  left: 50%;
  top: 50%;
  width: 80%;
  height: 70%;
  transform: translate(-50%, -50%);
}

Codepen example


问:
Extract time format from a string
I have input time string which indicates time in various formats, like "1PM" (format is: hha), "1300" (format is: kkmm) and I want to convert it into a single format, say "1300" (kkmm).

How can I know what the format of the input time string is (hha or kkmm, etc.)?

I know how to convert it into a desired format, but I'm struggling to know the format of input string.

```<code>    String inputTime = '1PM';
    SimpleDateFormat inputFormat = new SimpleDateFormat('hha');
    SimpleDateFormat outputFormat = new SimpleDateFormat('kkmm');

    Date date = inputFormat.parse(inputTime);

    String output = outputFormat.format(date);
</code>```

OUTPUT is: 1300.

Here, I'm passing input format as 'hha' in first line of code. I want to avoid that and extract time format from the inputTime string.

答:
java.time

Is there any particular reason why are you using the troublesome and long outdated SimpleDateFormat class? Your best first step would be to throw it out. Instead use LocalTime and DateTimeFormatter from java.time, the modern Java date and time API. That API is much nicer to work with.

There are basically two ways to go about your problem. I will present them in turn using java.time.

Option 1: look at the string and decide its format

Make a simple test to determine which format to use; for example, if the string ends in M, use ha, otherwise Hmm.

```<code>private static DateTimeFormatter formatterWithAmPm
        = DateTimeFormatter.ofPattern("ha", Locale.ENGLISH);
private static DateTimeFormatter formatterWithMinutes
        = DateTimeFormatter.ofPattern("Hmm");

public static LocalTime parseTime(String inputTime) {
    if (inputTime.endsWith("M")) {
        return LocalTime.parse(inputTime, formatterWithAmPm);
    } else {
        return LocalTime.parse(inputTime, formatterWithMinutes);
    }
}
</code>```

I was frankly surprised to see that format pattern string Hmm parses 123 as 01:23 and 1234 as 12:34, but it’s very convenient.

I think this option lends itself best to few constant formats. It wouldn’t be too easy to extends with further formats at a later time.

Option 2: try all relevant formats until one works

Try each possible format in turn, catch any exception and see which one doesn’t throw any.

```<code>private static final DateTimeFormatter[] parseFormatters
        = Arrays.asList("ha", "Hmm") // add more format pattern strings as required
            .stream()
            .map(fps -> DateTimeFormatter.ofPattern(fps, Locale.ENGLISH))
            .toArray(DateTimeFormatter[]::new);

public static LocalTime parseTime(String inputTime) {
    DateTimeParseException aCaughtException = null;
    for (DateTimeFormatter formatter : parseFormatters) {
        try {
            return LocalTime.parse(inputTime, formatter);
        } catch (DateTimeParseException dtpe) {
            aCaughtException = dtpe;
            // otherwise ignore, try next formatter
        }
    }
    throw aCaughtException;
}
</code>```

Take care to check if you have two formats that may match the same input and yield different results. This also means that you cannot distinguish all  thinkable formats in this way. It’s not too unreasonable to imagine a format where 1300 means minute 1300 of the day, that is 21:40. It could even mean second 1300 of the day, 00:21:40.

Title: Extract time format from a string

Body:
I have input time string which indicates time in various formats, like "1PM" (format is: hha), "1300" (format is: kkmm) and I want to convert it into a single format, say "1300" (kkmm).

How can I know what the format of the input time string is (hha or kkmm, etc.)?

I know how to convert it into a desired format, but I'm struggling to know the format of input string.

    String inputTime = '1PM';
    SimpleDateFormat inputFormat = new SimpleDateFormat('hha');
    SimpleDateFormat outputFormat = new SimpleDateFormat('kkmm');

    Date date = inputFormat.parse(inputTime);

    String output = outputFormat.format(date);

OUTPUT is: 1300.

Here, I'm passing input format as 'hha' in first line of code. I want to avoid that and extract time format from the inputTime string.

Body:
java.time

Is there any particular reason why are you using the troublesome and long outdated SimpleDateFormat class? Your best first step would be to throw it out. Instead use LocalTime and DateTimeFormatter from java.time, the modern Java date and time API. That API is much nicer to work with.

There are basically two ways to go about your problem. I will present them in turn using java.time.

Option 1: look at the string and decide its format

Make a simple test to determine which format to use; for example, if the string ends in M, use ha, otherwise Hmm.

private static DateTimeFormatter formatterWithAmPm
        = DateTimeFormatter.ofPattern("ha", Locale.ENGLISH);
private static DateTimeFormatter formatterWithMinutes
        = DateTimeFormatter.ofPattern("Hmm");

public static LocalTime parseTime(String inputTime) {
    if (inputTime.endsWith("M")) {
        return LocalTime.parse(inputTime, formatterWithAmPm);
    } else {
        return LocalTime.parse(inputTime, formatterWithMinutes);
    }
}

I was frankly surprised to see that format pattern string Hmm parses 123 as 01:23 and 1234 as 12:34, but it’s very convenient.

I think this option lends itself best to few constant formats. It wouldn’t be too easy to extends with further formats at a later time.

Option 2: try all relevant formats until one works

Try each possible format in turn, catch any exception and see which one doesn’t throw any.

private static final DateTimeFormatter[] parseFormatters
        = Arrays.asList("ha", "Hmm") // add more format pattern strings as required
            .stream()
            .map(fps -> DateTimeFormatter.ofPattern(fps, Locale.ENGLISH))
            .toArray(DateTimeFormatter[]::new);

public static LocalTime parseTime(String inputTime) {
    DateTimeParseException aCaughtException = null;
    for (DateTimeFormatter formatter : parseFormatters) {
        try {
            return LocalTime.parse(inputTime, formatter);
        } catch (DateTimeParseException dtpe) {
            aCaughtException = dtpe;
            // otherwise ignore, try next formatter
        }
    }
    throw aCaughtException;
}

Take care to check if you have two formats that may match the same input and yield different results. This also means that you cannot distinguish all  thinkable formats in this way. It’s not too unreasonable to imagine a format where 1300 means minute 1300 of the day, that is 21:40. It could even mean second 1300 of the day, 00:21:40.


问:
How can I convert a list into string format in python list?
I was wondering how I could change a list written as a string, such as ‘[1,[2,[]],[3,[]]]’ into an actual python list like [1,[2,[]],[3,[]]]. Is there any algorithm for this?</p>

答:
Assign your value to a variable then call the variable.split() it defaults to comma delimited which in your instance would result in list['[1,[2,[]],[3,[]]]']

another example of this could be this:

```<code>a = "test, 1, testing2, alpha, beta, Zulu, 23"
a.split()
Result: ['test,', '1,', 'testing2,', 'alpha,', 'beta,', 'Zulu,', '23']
</code>```

Body:
Assign your value to a variable then call the variable.split() it defaults to comma delimited which in your instance would result in list['[1,[2,[]],[3,[]]]']

another example of this could be this:

a = "test, 1, testing2, alpha, beta, Zulu, 23"
a.split()
Result: ['test,', '1,', 'testing2,', 'alpha,', 'beta,', 'Zulu,', '23']


问:
R Studio doesn't load sjp.setThem function
After re-installing sjPlot package I am not able to set a theme with sjp.setTheme. This is the message I get:

```<code>sjp.setTheme(theme = "scatter",
             geom.label.size = 3.5,
             geom.label.color = "white",
             axis.textsize = .8,
             axis.title.size = .9)
</code>```

Error in sjp.setTheme(theme = "scatter", geom.label.size = 3.5, geom.label.color = "white",  :
  could not find function "sjp.setTheme"

答: For the latest sjPlot-update, sjp.setTheme() has been renamed to set_theme().

Body:
After re-installing sjPlot package I am not able to set a theme with sjp.setTheme. This is the message I get:

sjp.setTheme(theme = "scatter",
             geom.label.size = 3.5,
             geom.label.color = "white",
             axis.textsize = .8,
             axis.title.size = .9)

Error in sjp.setTheme(theme = "scatter", geom.label.size = 3.5, geom.label.color = "white",  :
  could not find function "sjp.setTheme"


问:
NoSuchFieldError when executed from Java but not from command line
Is it possible to have java use the command line's environment instead of its own?

I have a java program calling a bash script with

```<code>final ProcessBuilder pb = new ProcessBuilder("bash", "-x", exportScriptLoc, platformId, oldWorkFlowId,
            newWorkFlowId).inheritIO();
    pb.directory(new File("/opt/nis/ddziak-dev/nis-hadoop"));
    final Process p = pb.start();
    p.waitFor();
    final int exitValue = p.exitValue();
    p.destroy();
    if (exitValue == 0) {
</code>```

When I execute the script on the command line it behaves as expected.  When my java program executes the script it produces the following exception:

```<code>Exception in thread "main" java.lang.RuntimeException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.metastore.HiveMetaStoreClient
    at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:347)
    at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:681)
    at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:625)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:212)
Caused by: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.metastore.HiveMetaStoreClient
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1422)
    at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.<init>(RetryingMetaStoreClient.java:62)
    at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:72)
    at org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient(Hive.java:2457)
    at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:2469)
    at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:341)
    ... 7 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1420)
    ... 12 more
Caused by: java.lang.NoSuchFieldError: SASL_PROPS
    at org.apache.hadoop.hive.thrift.HadoopThriftAuthBridge20S.getHadoopSaslProperties(HadoopThriftAuthBridge20S.java:127)
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.getMetaStoreSaslProperties(MetaStoreUtils.java:1485)
    at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.open(HiveMetaStoreClient.java:322)
    at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:214)
    ... 17 more
</code>```

The script is as follows

```<code>#!/bin/bash

. ~/.bash_profile
export HIVE_HOME=/usr/lib/hive
#export PATH=$PATH:$HIVE_HOME/bin

env
echo "hive -S -e \"show partitions nis.subscribers
partition(destinationPlatformId='$1', build='$2');\"|awk '{if(NR>1)print}'" >> subscribers.out
PARTITIONS=`/usr/bin/hive -S -e "show partitions nis.subscribers
partition(destinationPlatformId='$1', build='$2');"|awk '{if(NR>1)print}'`
echo "${PARTITIONS}"
if [ -z "$PARTITIONS" ]
then
  exit 2
fi

echo "${PARTITIONS}"

hqlOut=`/usr/bin/hive -S -hiveconf destPlatId=$1 -hiveconf newWorkFlowId=$3 -hiveconf oldWorkFlowId=$2 -f /opt/nis/ddziak-dev/nis-
hadoop/dapLib/updateSubscriberHiveTable.hql`

newPARTITIONS=`/usr/bin/hive -S -e "show partitions nis.subscribers partition(destinationPlatformId='$1');"|awk '{if(NR>1)print}'`
if [ -z "$newPARTITIONS" ]
then
  exit 3
fi
</code>```

答:
Is it possible to have java use the command line's environment instead of its own?

It depends on what you mean by "the command line's environment".  If you mean that in the narrow sense of a mapping from variable names to values, then

The java command by which your VM is launched gets its environment from the command that launches it.  That more likely than not works out to "the command line's environment".

Unless you take action to produce a different effect (and the code presented does not) processes you launch with the help of a ProcessBuilder will inherit a copy of the VM's environment.

But I think you're barking up the wrong tree.  Although it is conceivable that an environment issue might contribute indirectly to a java.lang.NoSuchFieldError, such an Error is

Thrown if an application tries to access or modify a specified field
  of an object, and that object no longer has that field.

Normally, this error is caught by the compiler; this error can only
  occur at run time if the definition of a class has incompatibly
  changed.

(API docs)

This suggests that the proximal cause of the error is that you have mismatched classes in your runtime classpath.  Field in this context means a member variable of a class, so that's what Java is looking for SASL_PROPS to be (though it's unclear to me which class is expected to have that field).

Body:
Is it possible to have java use the command line's environment instead of its own?

I have a java program calling a bash script with

final ProcessBuilder pb = new ProcessBuilder("bash", "-x", exportScriptLoc, platformId, oldWorkFlowId,
            newWorkFlowId).inheritIO();
    pb.directory(new File("/opt/nis/ddziak-dev/nis-hadoop"));
    final Process p = pb.start();
    p.waitFor();
    final int exitValue = p.exitValue();
    p.destroy();
    if (exitValue == 0) {

When I execute the script on the command line it behaves as expected.  When my java program executes the script it produces the following exception:

Exception in thread "main" java.lang.RuntimeException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.metastore.HiveMetaStoreClient
    at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:347)
    at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:681)
    at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:625)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:212)
Caused by: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.metastore.HiveMetaStoreClient
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1422)
    at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.<init>(RetryingMetaStoreClient.java:62)
    at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:72)
    at org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient(Hive.java:2457)
    at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:2469)
    at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:341)
    ... 7 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1420)
    ... 12 more
Caused by: java.lang.NoSuchFieldError: SASL_PROPS
    at org.apache.hadoop.hive.thrift.HadoopThriftAuthBridge20S.getHadoopSaslProperties(HadoopThriftAuthBridge20S.java:127)
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.getMetaStoreSaslProperties(MetaStoreUtils.java:1485)
    at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.open(HiveMetaStoreClient.java:322)
    at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:214)
    ... 17 more

The script is as follows

#!/bin/bash

. ~/.bash_profile
export HIVE_HOME=/usr/lib/hive
#export PATH=$PATH:$HIVE_HOME/bin

env
echo "hive -S -e \"show partitions nis.subscribers
partition(destinationPlatformId='$1', build='$2');\"|awk '{if(NR>1)print}'" >> subscribers.out
PARTITIONS=`/usr/bin/hive -S -e "show partitions nis.subscribers
partition(destinationPlatformId='$1', build='$2');"|awk '{if(NR>1)print}'`
echo "${PARTITIONS}"
if [ -z "$PARTITIONS" ]
then
  exit 2
fi

echo "${PARTITIONS}"

hqlOut=`/usr/bin/hive -S -hiveconf destPlatId=$1 -hiveconf newWorkFlowId=$3 -hiveconf oldWorkFlowId=$2 -f /opt/nis/ddziak-dev/nis-
hadoop/dapLib/updateSubscriberHiveTable.hql`

newPARTITIONS=`/usr/bin/hive -S -e "show partitions nis.subscribers partition(destinationPlatformId='$1');"|awk '{if(NR>1)print}'`
if [ -z "$newPARTITIONS" ]
then
  exit 3
fi


问:
Magic: The Gathering database design
I would like to create a database for MTG cards I own. What would the design be?
I would like to store the following information about each card:

```<code>1. Name of card.
2. Set the card belongs to.
3. Condition of card.
4. Price it sold for.
5. Price I bought it for.
</code>```

Here is a little info about MTG cards in general:

```<code>1. Every card has a name.
2. Every card belongs to a set.
3. A card may have a foil version of itself.
4. Card name, set it belongs to, and whether it's foil or not makes it unique.
5. A card may be in multiple sets.
6. A set has multiple cards.
</code>```

The gimmick is that in my collection I may have several copies of the same card but with different conditions, or purchased price, or sold price may be different.

I will have another collection of mtg cards that have been sold on eBay. This collection will have the price/condition/date/whether it was a "Buy It Now" or Bid, etc.

The idea is to find out what price I should sell my cards based on the eBay collection.

答:
I suggest you look at data file from www.mtgjson.com

By merely seeing what field types they selected and reading comments and documentation you will be likely to avoid many caveats.

For instance you will see how they handle duplicate names, cards that are related to each other like one is flipped or rotated or meld together version of another and many many more little nuances.

Title: Magic: The Gathering database design

Body:
I would like to create a database for MTG cards I own. What would the design be?
I would like to store the following information about each card:

1. Name of card.
2. Set the card belongs to.
3. Condition of card.
4. Price it sold for.
5. Price I bought it for.

Here is a little info about MTG cards in general:

1. Every card has a name.
2. Every card belongs to a set.
3. A card may have a foil version of itself.
4. Card name, set it belongs to, and whether it's foil or not makes it unique.
5. A card may be in multiple sets.
6. A set has multiple cards.

The gimmick is that in my collection I may have several copies of the same card but with different conditions, or purchased price, or sold price may be different.

I will have another collection of mtg cards that have been sold on eBay. This collection will have the price/condition/date/whether it was a "Buy It Now" or Bid, etc.

The idea is to find out what price I should sell my cards based on the eBay collection.


问:
Can't get files from public folder because of route
I am having problems with getting my js/css files from the public folder, i think it's because of my routes but i am not sure...

when my webpage loads, I get the next errors:

GET http://localhost:3000/ <view-file> /javascripts/ <js/css-file> net::ERR_ABORTED

my files are included like this:

the thing is that, i use the same method in all my views files and i don't get this problem

i think it's because the way i make my route for that view:

```<code>router.get(['/', '/:invID'], function(req, res, next) {
   if (!req.params.invID){
      // check if there is an invitation code
   } else {
      // here is an IF inviation code is invalid
        if ( // invite code invalid){
            // code....
        } else {
           // invite code is valid so render the view
            res.render('register', {
                title: 'Express',
                invID: req.params.invID,
                userData: // user data object
            });
        }
    });

}
});
</code>```

答:
No idea why it works, but i fixed it by adding an "/" before the javascript folder

i have 4 other views without the "/" and they work without problems...  wierd

Body:
I am having problems with getting my js/css files from the public folder, i think it's because of my routes but i am not sure...

when my webpage loads, I get the next errors:

GET http://localhost:3000/ <view-file> /javascripts/ <js/css-file> net::ERR_ABORTED

my files are included like this:

the thing is that, i use the same method in all my views files and i don't get this problem

i think it's because the way i make my route for that view:

router.get(['/', '/:invID'], function(req, res, next) {
   if (!req.params.invID){
      // check if there is an invitation code
   } else {
      // here is an IF inviation code is invalid
        if ( // invite code invalid){
            // code....
        } else {
           // invite code is valid so render the view
            res.render('register', {
                title: 'Express',
                invID: req.params.invID,
                userData: // user data object
            });
        }
    });

}
});

Body:
No idea why it works, but i fixed it by adding an "/" before the javascript folder

<script src="/javascripts/<filename>.js"></script>

i have 4 other views without the "/" and they work without problems...  wierd


问:
sum of positive entries until a negative occurs in R
As an example I have a vector of 20 mixed positive and negative integers.
I would like a generate a new vector where every positive integer is added together until a negative integers occurs and then every negative is added until a positive occurs again.

e.g. 2 4 3 -4 -4 -3 -2 3 4 5 2 5 -4 -4 -3 -3 3 4 5  would become 9 -13 19 -14 12.

What sort of code should I use?  Is this even possible?

答:
You could also use tapply with a grouping built from diff, abs, sign, and cumsum.

Using d.b's data, the result is

```<code>unname(tapply(x, cumsum(c(0, abs(diff(sign(x))))), sum))
 [1]  24 -17   6 -35  29 -10   4 -17  14 -19  15  -9
</code>```

sign returns -1, 1, and 0 depending on the value of its input. diff will determine where changes in sign occur, abs turns diff into and indicator, stripping off the negative values and cumsum is used to build groups for tapply.

Body:
You could also use tapply with a grouping built from diff, abs, sign, and cumsum.

Using d.b's data, the result is

unname(tapply(x, cumsum(c(0, abs(diff(sign(x))))), sum))
 [1]  24 -17   6 -35  29 -10   4 -17  14 -19  15  -9

sign returns -1, 1, and 0 depending on the value of its input. diff will determine where changes in sign occur, abs turns diff into and indicator, stripping off the negative values and cumsum is used to build groups for tapply.


问:
Nesting
 and
 tags?

Question:

Which of these is the proper way to nest the
 and
 tags, and what is your reasoning behind it?

Choice A:

```<code><article>
    <h1>Some Title</h1>
    <p>Here's some text and whatnot.</p>
    <p>Here's another paragraph filled with other text and other whatnots.</p>
</article>
</code>```

Choice B:

```<code><div class="post">
    <h1>Here's a Really Awesome Title</h1>
    <article>
        <p>Here's a paragraph with text and whatnot.</p>
        <p>And here's another paragraph. I think this one is pretty awesome too.</p>
    </article>
</div>
</code>```

Opinions seem mixed about this, and I'm not 100% which is the correct answer.

答:
Headers that talk about the article (meta-headers) should be out of
, headers that are part of the article (chapters, for example) should be in
.

All of that just IMHO.

Title: Nesting <article> and <h1> tags?

Body:
Question:

Which of these is the proper way to nest the
 and
 tags, and what is your reasoning behind it?

Choice A:

Some Title

Here's some text and whatnot.

Here's another paragraph filled with other text and other whatnots.

Choice B:

Here's a Really Awesome Title

Here's a paragraph with text and whatnot.

And here's another paragraph. I think this one is pretty awesome too.

Opinions seem mixed about this, and I'm not 100% which is the correct answer.

Body:
Headers that talk about the article (meta-headers) should be out of <article>, headers that are part of the article (chapters, for example) should be in <article>.

All of that just IMHO.


问:
How to call external non REST API from a spring cloud micro-service that use eureka to call other internal micro-service?
In our project we use Spring cloud + Eureka as service registry.
When we use the ribbon client to call internal micro-services, all URL are resolved via Eureka ... that's a problem to call external URLs.
As external API are old fashioned usage of Feign doesn't seem to be good choice.

What's the best way to call an external URL from such a service ?

Thanks in advance

Patrice

答:
You can use Ribbon without Eureka. For external APIs where you cannot configure in Eureka to abstract the discover. You can hard code their URLs in client and configure server list. The Ribbon client defaults to a configured server list, and you can supply the configuration like this:</p>

```<code>stores:
  ribbon:
    listOfServers: example.com, google.com
</code>```

Body:
You can use Ribbon without Eureka. For external APIs where you cannot configure in Eureka to abstract the discover. You can hard code their URLs in client and configure server list. The Ribbon client defaults to a configured server list, and you can supply the configuration like this:

stores:
  ribbon:
    listOfServers: example.com, google.com


问:
set emissiveIntensity in a-image (or on any material)
Using aframe, I would like to display a flat image with transparency (e.g. as png) which is dark when no light points at it. The parameter I figured out is emissiveIntensity, which is not recognized when using a-image (according to the console of my Chrome Browser):

```<code><a-image src="#img-colorwheel"
         position="8 3 -10"
         rotation="0 0 0"
         height="5"
         width="5"
         material="emissiveIntensity:0;">
</a-image>
</code>```

When using a regular a-entity, it works:

```<code><a-entity geometry="primitive: plane; height:5; width:5;"
          material="src:#img-colorwheel; emissiveIntensity:0;"
          position="0 2 -19.9"
          rotation="0 0 0">
</a-entity>
</code>```

My problem is, that in this case the transparent part of the png is displayed in white color.
Any hints - or workarounds?

Working with a-frame 0.7.0; same issue with 0.7.1

答:
The  does  not have the emissive mappings. You can also check it out, by searching for a-image in the source code, where You can see the mappings.

I would use the entity, since the a-image is clearly an abridged version of a-entity with the plane geometry.

If You really need the  with emissive, You need to change the shader, since  uses the meshBasicMaterial. Check out it's properties. No emissive. What needs to be done is:

```<code><a-image src="https://i.imgur.com/wjobVTN.jpg"
     position="0 2 -3"
     rotation="0 0 0"
     height="5"
     width="5"
     material = "shader:standard;color:blue;
     emissive:red;emissiveIntensity:2">
</a-image>
</code>```

like i did here.

Ofc You could make a component, which changes the material to any other, but the meshStandardMaterial should be sufficient.

Body:
Using aframe, I would like to display a flat image with transparency (e.g. as png) which is dark when no light points at it. The parameter I figured out is emissiveIntensity, which is not recognized when using a-image (according to the console of my Chrome Browser):

When using a regular a-entity, it works:

My problem is, that in this case the transparent part of the png is displayed in white color.
Any hints - or workarounds?

Working with a-frame 0.7.0; same issue with 0.7.1

Body:
The <a-image> does  not have the emissive mappings. You can also check it out, by searching for a-image in the source code, where You can see the mappings.

I would use the entity, since the a-image is clearly an abridged version of a-entity with the plane geometry.

If You really need the <a-image> with emissive, You need to change the shader, since <a-image> uses the meshBasicMaterial. Check out it's properties. No emissive. What needs to be done is:

<a-image src="https://i.imgur.com/wjobVTN.jpg"
     position="0 2 -3"
     rotation="0 0 0"
     height="5"
     width="5"
     material = "shader:standard;color:blue;
     emissive:red;emissiveIntensity:2">
</a-image>

like i did here.

Ofc You could make a component, which changes the material to any other, but the meshStandardMaterial should be sufficient.


问:
Can't load react-native app with expo app on the cellphone
I have created a React Native app with the npm package bootstrapper, then run the npm start command and everything seems to be right until then.

Now, when I go to the expo app on my cell phone and scan the QR code I always get this message "Something went wrong. Could not load exp://... . Network response timed out".

I'm on windows 10, and both the laptop and the cellphone are on the same wireless network.
I don't know what could be the problem, I followed the tutorial on this link:
https://facebook.github.io/react-native/docs/getting-started.html#content

I hope anyone can help me.

答:
Try using the offline option:

exp start --offline