问:
RobotFramework: How to convert date to lose leading zeros from single digit days
See below. From checking dateformats, the %d should work but doesnt seem to - see output.

```<code>Log to console  Completion Date ${completion_date}
${date_to_search_for}=  Convert Date  ${completion_date}  date_format=%Y-%m-%d %H:%m:%S.%f  result_format=%d %b %Y 00:00:00  exclude_millis=True
Log to console  Completion Date ${date_to_search_for}
</code>```

Outputs for  ${completion_date}

```<code>Completion Date 2017-07-01 08:37:13.656083
</code>```

Outputs for ${date_to_search_for}

```<code>Completion Date 01 Jul 2017 00:00:00
</code>```

答:
As far as I can tell from the documentation %dworks exactly as described in the example in the documentation for a Custom Timestamp.

For your desired effect please have a look at the Python datetime example:

```<code>${datetime} =   Convert Date    2014-06-11 10:07:42.123 datetime
Should Be Equal As Integers    ${datetime.year}      2014
Should Be Equal As Integers    ${datetime.month}         6
Should Be Equal As Integers    ${datetime.day}           11
Should Be Equal As Integers    ${datetime.hour}      10
Should Be Equal As Integers    ${datetime.minute}        7
Should Be Equal As Integers    ${datetime.second}        42
Should Be Equal As Integers    ${datetime.microsecond}  123000
</code>```

Body:
See below. From checking dateformats, the %d should work but doesnt seem to - see output.

Log to console  Completion Date ${completion_date}
${date_to_search_for}=  Convert Date  ${completion_date}  date_format=%Y-%m-%d %H:%m:%S.%f  result_format=%d %b %Y 00:00:00  exclude_millis=True
Log to console  Completion Date ${date_to_search_for}

Outputs for  ${completion_date}

Completion Date 2017-07-01 08:37:13.656083

Outputs for ${date_to_search_for}

Completion Date 01 Jul 2017 00:00:00

Body:
As far as I can tell from the documentation %dworks exactly as described in the example in the documentation for a Custom Timestamp.

For your desired effect please have a look at the Python datetime example:

${datetime} =   Convert Date    2014-06-11 10:07:42.123 datetime
Should Be Equal As Integers    ${datetime.year}      2014
Should Be Equal As Integers    ${datetime.month}         6
Should Be Equal As Integers    ${datetime.day}           11
Should Be Equal As Integers    ${datetime.hour}      10
Should Be Equal As Integers    ${datetime.minute}        7
Should Be Equal As Integers    ${datetime.second}        42
Should Be Equal As Integers    ${datetime.microsecond}  123000


来源: stackexchange

问:
In Delphi: How to skip sections of code while debugging?
I often accidently step into code that I'm not interested in while debugging in Delphi.

Let's start by saying that I know that you can step over with F8, and that you can run to a certain line with f4.

Example:

```<code>function TMyClass.DoStuff():Integer;
begin
  // do some stuff
  bla();
end;

procedure TMyClass.Foo()
begin
  if DoStuff()=0 then // press F7 when entering this line
    beep;
end;
</code>```

Example: I want to step into method DoStuff() by pressing F7, but instead of going there, I first end up in FastMM4.FastGetMem(), which is a massive blob of assembly code that obviously I'm not interested in at the moment.

There are several ways to go about this, and I don't like any of them:

Add a breakpoint on "bla" (almost useless if you only want to step into DoStuff on special occasions, like iteration 23498938);

Instead of pressing F7, manually move the cursor to "bla", and press F4 (Works for this simple example. In practice, it doesn't);

In case of FastMM: temporarily disable fastmm;

Is there any way to hint the IDE that I'm never interested into stepping into a certain block of code, or do I always have to set extra breakpoints or use F4 to try to avoid this?

I'm hoping for some magic compiler directive like {$NODEBUG BEGIN/END} or something like that.

In most cases being able to exclude entire units would be fine-grained enough for me, but being able to avoid certain methods or even lines of code would be even better.

Update: Maybe codegear should introduce something like skip-points (as opposed to break-points) :-)

答:
Although it isn't a direct answer to your question, you could modify your first suggested solution by putting breakpoint at bla that is only enabled when a breakpoint at Foo is passed (or some other condition of your choose, such as iteration count). Then it will only break when you want it to.

As an aside, I am finding more and more that I am not halting execution at break points, but rather dumping variable values or stack dumps to the message log. This allows more careful analysis than on-the-fly inspection of variables, etc. FWIW.

OwnerDisplayName: Wouter van Nifterick

ContentLicense: CC BY-SA 2.5

Body:
I often accidently step into code that I'm not interested in while debugging in Delphi.

Let's start by saying that I know that you can step over with F8, and that you can run to a certain line with f4.

Example:

function TMyClass.DoStuff():Integer;
begin
  // do some stuff
  bla();
end;

procedure TMyClass.Foo()
begin
  if DoStuff()=0 then // press F7 when entering this line
    beep;
end;

Example: I want to step into method DoStuff() by pressing F7, but instead of going there, I first end up in FastMM4.FastGetMem(), which is a massive blob of assembly code that obviously I'm not interested in at the moment.

There are several ways to go about this, and I don't like any of them:

Add a breakpoint on "bla" (almost useless if you only want to step into DoStuff on special occasions, like iteration 23498938);

Instead of pressing F7, manually move the cursor to "bla", and press F4 (Works for this simple example. In practice, it doesn't);

In case of FastMM: temporarily disable fastmm;

Is there any way to hint the IDE that I'm never interested into stepping into a certain block of code, or do I always have to set extra breakpoints or use F4 to try to avoid this?

I'm hoping for some magic compiler directive like {$NODEBUG BEGIN/END} or something like that.

In most cases being able to exclude entire units would be fine-grained enough for me, but being able to avoid certain methods or even lines of code would be even better.

Update: Maybe codegear should introduce something like skip-points (as opposed to break-points) :-)

LastEditorDisplayName: Wouter van Nifterick

OwnerDisplayName: Richard


问:
Win32API Mouse vs Real Mouse Click
I have recently started using win32api to simulate mouse events and was wondering if it was at all detectable?

For example, does the api follow the exact same process/run the exact same commands as if done when using a real mouse - or are there some slight differences which can be detected? Furthermore, is this the same case with win32com SendKeys (via Shell Script/Python)?

I ask, because in the past I have had a few applications detect the Java robot library - but they all seem to work fine when using the Python win32api. Thanks.

答: The SendInput function will insert input events into the same queue as a hardware device but the events are marked with a LLMHF_INJECTED flag that can be detected by hooks. To avoid this flag you probably have to write a custom driver.

ContentLicense: CC BY-SA 3.0

Title: Win32API Mouse vs Real Mouse Click


问:
Android: Getting "Manifest merger failed" error after updating to a new version of gradle
After accepting to update the project to new version of gradle I get this error:

```<code>Error:Execution failed for task ':app:processDebugManifest'.
Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.0-alpha1) from [com.android.support:cardview-v7:26.0.0-alpha1] AndroidManifest.xml:24:9-38
    is also present at [com.android.support:design:25.3.1] AndroidManifest.xml:27:9-31 value=(25.3.1).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:22:5-24:41 to override.
</code>```

How can I solve this problem?
This is my app's build.gradle file:

```<code>android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.sample.bookReader"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    ...
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:+'
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile 'com.android.support:cardview-v7:26.0.0-alpha1'
    compile 'com.android.support:design:25+'
    compile 'com.jakewharton:butterknife:8.2.1'
    apt 'com.jakewharton:butterknife-compiler:8.2.1'
    ...
}
</code>```

And this is the project's build.gradle:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://www.jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

How do I fix this error while maintaining the changes made by updating the gradle version?

答:
I changed all support library versions to 25.3.1 and worked like a charm:

```<code>compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
</code>```

You also need to change compileSdkVersion and targetSdkVersion to 25:

```<code>compileSdkVersion 25
targetSdkVersion 25
</code>```

Body:
After accepting to update the project to new version of gradle I get this error:

Error:Execution failed for task ':app:processDebugManifest'.
Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.0-alpha1) from [com.android.support:cardview-v7:26.0.0-alpha1] AndroidManifest.xml:24:9-38
    is also present at [com.android.support:design:25.3.1] AndroidManifest.xml:27:9-31 value=(25.3.1).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:22:5-24:41 to override.

How can I solve this problem?
This is my app's build.gradle file:

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.sample.bookReader"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    ...
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:+'
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile 'com.android.support:cardview-v7:26.0.0-alpha1'
    compile 'com.android.support:design:25+'
    compile 'com.jakewharton:butterknife:8.2.1'
    apt 'com.jakewharton:butterknife-compiler:8.2.1'
    ...
}

And this is the project's build.gradle:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://www.jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

How do I fix this error while maintaining the changes made by updating the gradle version?

Body:
I changed all support library versions to 25.3.1 and worked like a charm:

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'

You also need to change compileSdkVersion and targetSdkVersion to 25:

compileSdkVersion 25
targetSdkVersion 25


问:
Python Importing with OOP
This question concerns when you should have imports for Python modules and how it all interacts when you are trying to take an OOP approach to what you're making.

Let's say we have the following Modules:

ClassA.py:

```<code>class Class_A:

    def doSomething(self):
        #doSomething
</code>```

ClassB.py

```<code>class Class_B:

    def doSomethingElse(self):
        #doSomethingElse
</code>```

ClassC.py

```<code>class Class_C:

    def __init__(self, ClassAobj, ClassBobj):
        self.a = ClassAobj
        self.b = ClassBobj

    def doTheThing(self):
        self.a.doSomething()
        self.b.doSomethingElse()
</code>```

Main.py:

```<code>from ClassA import Class_A
from ClassB import Class_B
from ClassC import Class_C

a = Class_A()
b = Class_B()
c = Class_C(a,b)
</code>```

In here Class_C uses objects of Class_A and Class_B however it does not have import statements for those classes.  Do you see this creating errors down the line, or is this fine?  Is it bad practice to do this?

Would having imports for Class_A and Class_B inside of Class_C cause the program as a whole to use more memory since it would be importing them for both Main.py and ClassC.py?  Or will the Python compiler see that those modules have already been imported and just skip over them?

I'm just trying to figure out how Python as a language ticks with concerns to importing and using modules.  Basically, if at the topmost level of your program (your Main function) if you import everything there, would import statements in other modules be redundant?

答:
You don't use Class_A or Class_B directly in Class_C, so you don't need to import them there.

Extra imports don't really use extra memory, there is only a single instance of each module in memory. Import just creates a name for the module in the current module namespace.

In Python, it's not idiomatic to have a single class per file. It's normal to have closely related classes all in the same file. A module name "ClassA" looks silly, that is the name of a class, not of a module.

You can only use a module inside another one if it's imported there. For instance the sys module is probably already in memory after Python starts, as so many things use it, including import statements.

An import foo statement does two things:

If the foo module is not in memory yet, it is loaded, parsed, executed and then placed in sys.modules['foo'].

A local name foo is created that also refers to the module in sys.modules.

So if you have say a print() in your module (not inside a function), then that is only executed the first time the module is imported.

Then later statements after the import can do things with foo, like foo.somefunc() or print(foo.__name__).

Title: Python Importing with OOP

Body:
This question concerns when you should have imports for Python modules and how it all interacts when you are trying to take an OOP approach to what you're making.

Let's say we have the following Modules:

ClassA.py:

class Class_A:

    def doSomething(self):
        #doSomething

ClassB.py

class Class_B:

    def doSomethingElse(self):
        #doSomethingElse

ClassC.py

class Class_C:

    def __init__(self, ClassAobj, ClassBobj):
        self.a = ClassAobj
        self.b = ClassBobj

    def doTheThing(self):
        self.a.doSomething()
        self.b.doSomethingElse()

Main.py:

from ClassA import Class_A
from ClassB import Class_B
from ClassC import Class_C

a = Class_A()
b = Class_B()
c = Class_C(a,b)

In here Class_C uses objects of Class_A and Class_B however it does not have import statements for those classes.  Do you see this creating errors down the line, or is this fine?  Is it bad practice to do this?

Would having imports for Class_A and Class_B inside of Class_C cause the program as a whole to use more memory since it would be importing them for both Main.py and ClassC.py?  Or will the Python compiler see that those modules have already been imported and just skip over them?

I'm just trying to figure out how Python as a language ticks with concerns to importing and using modules.  Basically, if at the topmost level of your program (your Main function) if you import everything there, would import statements in other modules be redundant?


问:
Dynamically create an object based on a field
I receive from a network API a JSON like this one:

{
  ...
  "foobar":
    {
      "type": "...",
      "keyTypeA": "value"
    }
}
```

<p>With <code>foobar</code> having different object types depending on its <code>type</code> field.
So, <code>foobar</code> can be:</p>

<pre class="lang-js prettyprint-override"><code>{
  "type": "typeA",
  "keyA1": "...",
  "keyA2": "...",
  ...
}
</code>```

or

{
  "type": "typeB",
  "keyB1": "...",
  "keyB2": "...",
  ...
}
```

<p>etc.</p>

<p>How can I parse these JSON models into my POJO classes defined here:</p>

<pre class="lang-java prettyprint-override"><code>public class FoobarTypeBase {
    @SerializedName("type")
    public String type;
}

public class FoobarTypeA extends FoobarTypeBase {
    @SerializedName("keyA1")
    public SomeObject keyA1;
    @SerializedName("keyA2")
    public SomeObject keyA2;
}

public class FoobarTypeB extends FoobarTypeBase {
    @SerializedName("keyB1")
    public SomeObject keyB1;
    @SerializedName("keyB2")
    public SomeObject keyB2;
}
</code>```

I guess I have to deal with TypeAdapterFactory and TypeAdapter but I don't known how to do it efficiently.

答:
I usually use a combination of Retrofit + Gson and do it this way:

```<code>RuntimeTypeAdapterFactory<FoobarTypeBase> itemFactory = RuntimeTypeAdapterFactory
            .of(FoobarTypeBase.class, "type") // The field that defines the type
            .registerSubtype(FoobarTypeA.class, "foobar")
            .registerSubtype(FoobarTypeB.class) // if the flag equals the class name, you can skip the second parameter.

Gson gson = new GsonBuilder()
            .registerTypeAdapterFactory(itemFactory)
            .create();
</code>```

Then I initialize Retrofit like this:

```<code>Retrofit.Builder builder = new Retrofit.Builder();
    builder.baseUrl(BASE_URL);
    builder.addConverterFactory(GsonConverterFactory.create(gson));

Retrofit retrofit = builder.build();
</code>```

Body:
I receive from a network API a JSON like this one:

{
  ...
  "foobar":
    {
      "type": "...",
      "keyTypeA": "value"
    }
}

With foobar having different object types depending on its type field.
So, foobar can be:

{
  "type": "typeA",
  "keyA1": "...",
  "keyA2": "...",
  ...
}

or

{
  "type": "typeB",
  "keyB1": "...",
  "keyB2": "...",
  ...
}

etc.

How can I parse these JSON models into my POJO classes defined here:

public class FoobarTypeBase {
    @SerializedName("type")
    public String type;
}

public class FoobarTypeA extends FoobarTypeBase {
    @SerializedName("keyA1")
    public SomeObject keyA1;
    @SerializedName("keyA2")
    public SomeObject keyA2;
}

public class FoobarTypeB extends FoobarTypeBase {
    @SerializedName("keyB1")
    public SomeObject keyB1;
    @SerializedName("keyB2")
    public SomeObject keyB2;
}

I guess I have to deal with TypeAdapterFactory and TypeAdapter but I don't known how to do it efficiently.

Body:
I usually use a combination of Retrofit + Gson and do it this way:

RuntimeTypeAdapterFactory<FoobarTypeBase> itemFactory = RuntimeTypeAdapterFactory
            .of(FoobarTypeBase.class, "type") // The field that defines the type
            .registerSubtype(FoobarTypeA.class, "foobar")
            .registerSubtype(FoobarTypeB.class) // if the flag equals the class name, you can skip the second parameter.

Gson gson = new GsonBuilder()
            .registerTypeAdapterFactory(itemFactory)
            .create();

Then I initialize Retrofit like this:

Retrofit.Builder builder = new Retrofit.Builder();
    builder.baseUrl(BASE_URL);
    builder.addConverterFactory(GsonConverterFactory.create(gson));

Retrofit retrofit = builder.build();


问:
Cannot tokenize words when using lucene SynonymFilter
```<code>public class SynonymAnalyzer extends Analyzer {

    @Override
    protected TokenStreamComponents createComponents(String s, Reader reader) {
        SynonymMap synonymMap = null;
        SynonymMap.Builder builder=null;
        try {
            addTo(builder,new String[]{"dns"},new String[]{"domain name system"});
            synonymMap = builder.build();
        }catch (Exception e) {
            e.printStackTrace();
        }
        Tokenizer tokenizer = new StandardTokenizer(reader);
        TokenStream filter = new SynonymFilter(tokenizer, synonymMap, true);
        return new TokenStreamComponents(tokenizer, filter);
    }

     private void addTo(SynonymMap.Builder builder, String[] from, String[] to) {
         for (String input : from) {
             for (String output : to) {
                 builder.add(new CharsRef(input), new CharsRef(output), false);
             }
         }
     }
 }
</code>```

If I use this SynonymAnalyzer,and search for dns is down, query formed is +n:domain name system +n:is +n:down. domain name system is not tokenized as seperate tokens but I need that as seperate tokens.

答:
When adding multi-word synonyms, you need to separate words with SynonymMap.WORD_SEPARATOR:

```<code>addTo(builder,new String[]{"dns"},new String[]{
    "domain" + SynonymMap.WORD_SEPARATOR
    + "name" + SynonymMap.WORD_SEPARATOR
    + "system"});
</code>```

(By the way, your createComponents, as written, will throw an NPE. Judging by what you've written, I'll assume this is an error in the example, not your code in production)

Body:
public class SynonymAnalyzer extends Analyzer {

    @Override
    protected TokenStreamComponents createComponents(String s, Reader reader) {
        SynonymMap synonymMap = null;
        SynonymMap.Builder builder=null;
        try {
            addTo(builder,new String[]{"dns"},new String[]{"domain name system"});
            synonymMap = builder.build();
        }catch (Exception e) {
            e.printStackTrace();
        }
        Tokenizer tokenizer = new StandardTokenizer(reader);
        TokenStream filter = new SynonymFilter(tokenizer, synonymMap, true);
        return new TokenStreamComponents(tokenizer, filter);
    }

     private void addTo(SynonymMap.Builder builder, String[] from, String[] to) {
         for (String input : from) {
             for (String output : to) {
                 builder.add(new CharsRef(input), new CharsRef(output), false);
             }
         }
     }
 }

If I use this SynonymAnalyzer,and search for dns is down, query formed is +n:domain name system +n:is +n:down. domain name system is not tokenized as seperate tokens but I need that as seperate tokens.

Body:
When adding multi-word synonyms, you need to separate words with SynonymMap.WORD_SEPARATOR:

addTo(builder,new String[]{"dns"},new String[]{
    "domain" + SynonymMap.WORD_SEPARATOR
    + "name" + SynonymMap.WORD_SEPARATOR
    + "system"});

(By the way, your createComponents, as written, will throw an NPE. Judging by what you've written, I'll assume this is an error in the example, not your code in production)


问:
iOS - Reload UIView when tab icon clicked?
I have an application that uses a UITabBarController, and inside each tab I have Navigation Controllers.

I would like to make one of the views reload itself after an action happens in another view, so that when the user goes back to that view - it's updated.

Is it possible?

答: The simplest way to accomplish this is to put your loading code into viewWillAppear: instead of viewDidLoad. While viewDidLoad may only get called once, when your view is initialized, viewWillAppear: is called any time your view controller is about to be presented, whether it be in the tab bar, in a navigation controller, etc., which gives you a nice hook to implement loading and layout functionality.

ContentLicense: CC BY-SA 4.0


问:
How to add md-switch to angular 4
i want to add md-switch from AngularJS Material to my angular4 project, but i'm getting the following error:

```<code>Uncaught Error: Template parse errors:
'md-switch' is not a known element:
1. If 'md-switch' is an Angular component, then verify that it is part of this module.
2. If 'md-switch' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message
</code>```

===============================

UPDATE

test.component.html:

```<code><md-slide-toggle>Slide me!</md-slide-toggle>
</code>```

test.component.ts:

```<code>@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
</code>```

test.module.ts

```<code>import { MaterialModule, MdButtonModule, MdSlideToggleModule} from '@angular/material';
import { NgModule } from '@angular/core';
import { TestComponent } from './test.component';

@NgModule({
  declarations: [
    TestComponent
  ],
  imports: [
    MaterialModule, MdSlideToggleModule,
  ],
})
export class TestModule { }
</code>```

package.json

```<code>{
  "name": "web-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/material": "^2.0.0-beta.7",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.1.3",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "2.5.45",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}
</code>```

What am i missing?

答:
You are using the angular1 lib docs for an angular2 module...

If you already have this repo installed just import the desired functionality from material to your module, else install package:

```<code>npm install @angular/material
</code>```

Don´t forget to include the feature component module on your selected module:

test.module.ts:

```<code>import {MatSlideToggleModule} from '@angular/material/slide-toggle';

    imports:      [ MatSlideToggleModule,
</code>```

test.component.html:

```<code><mat-slide-toggle>Slide me!</mat-slide-toggle>
</code>```

test.component.ts:

```<code>import {Component} from '@angular/core';

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
})
export class testComponent{}
</code>```

Title: How to add md-switch to angular 4

Body:
i want to add md-switch from AngularJS Material to my angular4 project, but i'm getting the following error:

Uncaught Error: Template parse errors:
'md-switch' is not a known element:
1. If 'md-switch' is an Angular component, then verify that it is part of this module.
2. If 'md-switch' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message

===============================

UPDATE

test.component.html:

<md-slide-toggle>Slide me!</md-slide-toggle>

test.component.ts:

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})

test.module.ts

import { MaterialModule, MdButtonModule, MdSlideToggleModule} from '@angular/material';
import { NgModule } from '@angular/core';
import { TestComponent } from './test.component';

@NgModule({
  declarations: [
    TestComponent
  ],
  imports: [
    MaterialModule, MdSlideToggleModule,
  ],
})
export class TestModule { }

package.json

{
  "name": "web-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/material": "^2.0.0-beta.7",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.1.3",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "2.5.45",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}

What am i missing?

Body:
You are using the angular1 lib docs for an angular2 module...

If you already have this repo installed just import the desired functionality from material to your module, else install package:

npm install @angular/material

Don´t forget to include the feature component module on your selected module:

test.module.ts:

import {MatSlideToggleModule} from '@angular/material/slide-toggle';

    imports:      [ MatSlideToggleModule,

test.component.html:

<mat-slide-toggle>Slide me!</mat-slide-toggle>

test.component.ts:

import {Component} from '@angular/core';

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
})
export class testComponent{}


问:
Cygnus-NGSI won't save data in PostgreSQL
Im trying to save some data in a postgreSQL database using cygnus-ngsi, but nothing happens. Im running all services in a docker container using docker-compose.

docker-compose.yml:

```<code>...
cygnus:
 image: fiware/cygnus-ngsi:latest
 hostname: cygnus
 container_name: cygnus_fiware
 volumes:
   - ./config/cygnus/cygnus.conf:/opt/apache-flume/conf/agent.conf
   - ./config/cygnus/grouping_rules.conf:/opt/apache-flume/conf/grouping_rules.conf
 links:
   - orion
   - postgres
 expose:
   - "5050"
 ports:
   - "5050:5050"

postgres:
 restart: always
 image: postgres:latest
 container_name: postgres_fiware
 volumes:
   - ./data/db/postgres:/var/lib/postgresql/data
 ports:
   - "5432:5432"
 expose:
   - "5432"
 environment:
   - POSTGRES_USER=teste
   - POSTGRES_DB=newdb
   - POSTGRES_PASSWORD=123456789
</code>```

agent.conf

```<code>cygnus-ngsi.sources = http-source
cygnus-ngsi.sinks = postgresql-sink
cygnus-ngsi.channels = postgresql-channel

#=============================================
# source configuration
# channel name where to write the notification events
cygnus-ngsi.sources.http-source.channels = postgresql-channel
# source class, must not be changed
cygnus-ngsi.sources.http-source.type = org.apache.flume.source.http.HTTPSource
# listening port the Flume source will use for receiving incoming notifications
cygnus-ngsi.sources.http-source.port = 5050
# Flume handler that will parse the notifications, must not be changed
cygnus-ngsi.sources.http-source.handler = com.telefonica.iot.cygnus.handlers.NGSIRestHandler
# URL target
cygnus-ngsi.sources.http-source.handler.notification_target = /notify
# default service (service semantic depends on the persistence sink)
cygnus-ngsi.sources.http-source.handler.default_service = default
# default service path (service path semantic depends on the persistence sink)
cygnus-ngsi.sources.http-source.handler.default_service_path = /
# source interceptors, do not change
cygnus-ngsi.sources.http-source.interceptors = ts gi
# TimestampInterceptor, do not change
cygnus-ngsi.sources.http-source.interceptors.ts.type = timestamp
# GroupingInterceptor, do not change
cygnus-ngsi.sources.http-source.interceptors.gi.type = com.telefonica.iot.cygnus.interceptors.NGSIGroupingInterceptor$Builder
# Grouping rules for the GroupingInterceptor, put the right absolute path to the file if necessary
# see the doc/design/interceptors document for more details
cygnus-ngsi.sources.http-source.interceptors.gi.grouping_rules_conf_file = /opt/apache-flume/conf/grouping_rules.conf

# ============================================
# NGSIPostgreSQLSink configuration
# channel name from where to read notification events
cygnus-ngsi.sinks.postgresql-sink.channel = postgresql-channel
# sink class, must not be changed
cygnus-ngsi.sinks.postgresql-sink.type = com.telefonica.iot.cygnus.sinks.NGSIPostgreSQLSink
# true applies the new encoding, false applies the old encoding.
cygnus-ngsi.sinks.postgresql-sink.enable_encoding = false
# true if name mappings are enabled for this sink, false otherwise
cygnus-ngsi.sinks.postgresql-sink.enable_name_mappings = false
# true if the grouping feature is enabled for this sink, false otherwise
cygnus-ngsi.sinks.postgresql-sink.enable_grouping = false
# true if lower case is wanted to forced in all the element names, false otherwise
cygnus-ngsi.sinks.postgresql-sink.enable_lowercase = false
# the FQDN/IP address where the PostgreSQL server runs
cygnus-ngsi.sinks.postgresql-sink.postgresql_host = postgres
# the port where the PostgreSQL server listens for incomming connections
cygnus-ngsi.sinks.postgresql-sink.postgresql_port = 5432
# the name of the postgresql database
cygnus-ngsi.sinks.postgresql-sink.postgresql_database = newdb
# a valid user in the PostgreSQL server
cygnus-ngsi.sinks.postgresql-sink.postgresql_username = teste
# password for the user above
cygnus-ngsi.sinks.postgresql-sink.postgresql_password = 123456789
# how the attributes are stored, either per row either per column (row, column)
cygnus-ngsi.sinks.postgresql-sink.attr_persistence = row
# select the data_model: dm-by-service-path or dm-by-entity
cygnus-ngsi.sinks.postgresql-sink.data_model = dm-by-entity
# number of notifications to be included within a processing batch
cygnus-ngsi.sinks.postgresql-sink.batch_size = 100
# timeout for batch accumulation
cygnus-ngsi.sinks.postgresql-sink.batch_timeout = 30
# number of retries upon persistence error
cygnus-ngsi.sinks.postgresql-sink.batch_ttl = 10

# =============================================
# postgresql-channel configuration
# channel type (must not be changed)
cygnus-ngsi.channels.postgresql-channel.type = memory
# capacity of the channel
cygnus-ngsi.channels.postgresql-channel.capacity = 1000
# amount of bytes that can be sent per transaction
cygnus-ngsi.channels.postgresql-channel.transactionCapacity = 100
</code>```

Messages from docker-compose:

```<code>cygnus_fiware | time=2017-06-19T15:11:15.132Z | lvl=WARN | corr=4af15a0c-5501-11e7-aa0a-0242ac130004 | trans=508576db-1443-4c64-bfc9-629d1a0b250e | srv=espometeo | subsrv=/environment | comp=cygnus-ngsi | op=getEvents | msg=com.telefonica.iot.cygnus.handlers.NGSIRestHandler[257] : [NGSIRestHandler] Unnecessary header
cygnus_fiware | time=2017-06-19T15:11:15.133Z | lvl=INFO | corr=89ac4c66-5501-11e7-850f-0242ac130004 | trans=3ae0dc99-de51-49a3-937f-42d887b7e7d7 | srv=espometeo | subsrv=/environment | comp=cygnus-ngsi | op=getEvents | msg=com.telefonica.iot.cygnus.handlers.NGSIRestHandler[282] : [NGSIRestHandler] Starting internal transaction (3ae0dc99-de51-49a3-937f-42d887b7e7d7)
cygnus_fiware | time=2017-06-19T15:11:15.133Z | lvl=INFO | corr=89ac4c66-5501-11e7-850f-0242ac130004 | trans=3ae0dc99-de51-49a3-937f-42d887b7e7d7 | srv=espometeo | subsrv=/environment | comp=cygnus-ngsi | op=getEvents | msg=com.telefonica.iot.cygnus.handlers.NGSIRestHandler[299] : [NGSIRestHandler] Received data ({  "subscriptionId" : "5947d328e143997a02b11008",  "originator" : "localhost",  "contextResponses" : [    {      "contextElement" : {        "type" : "EstacaoMeteo",        "isPattern" : "false",        "id" : "Estacao3",        "attributes" : [          {            "name" : "Humidity",            "type" : "float",            "value" : "35.3",            "metadatas" : [              {                "name" : "TimeInstant",                "type" : "ISO8601",                "value" : "2017-06-24T13:03:00"              }            ]          },          {            "name" : "Temperature",            "type" : "float",            "value" : "15.2",            "metadatas" : [              {                "name" : "TimeInstant",                "type" : "ISO8601",                "value" : "2017-06-24T13:03:00"              }            ]          }        ]      },      "statusCode" : {        "code" : "200",        "reasonPhrase" : "OK"      }    }  ]})

cygnus_fiware | time=2017-06-19T15:11:36.141Z | lvl=INFO | corr=89ac4c66-5501-11e7-850f-0242ac130004 | trans=3ae0dc99-de51-49a3-937f-42d887b7e7d7 | srv=espometeo | subsrv=/environment | comp=cygnus-ngsi | op=persistAggregation | msg=com.telefonica.iot.cygnus.sinks.NGSIPostgreSQLSink[479] : [postgresql-sink] Persisting data at NGSIPostgreSQLSink. Schema (espometeo), Table (environment_estacao3_estacaometeo), Fields ((recvTimeTs,recvTime,fiwareServicePath,entityId,entityType,attrName,attrType,attrValue,attrMd)), Values (('1497885075139','2017-06-19T15:11:15.139Z','/environment','Estacao3','EstacaoMeteo','Humidity','float','35.3','[{"name":"TimeInstant","type":"ISO8601","value":"2017-06-24T13:03:00"}]'),('1497885075139','2017-06-19T15:11:15.139Z','/environment','Estacao3','EstacaoMeteo','Temperature','float','15.2','[{"name":"TimeInstant","type":"ISO8601","value":"2017-06-24T13:03:00"}]'))
cygnus_fiware | time=2017-06-19T15:11:36.142Z | lvl=WARN | corr=89ac4c66-5501-11e7-850f-0242ac130004 | trans=3ae0dc99-de51-49a3-937f-42d887b7e7d7 | srv=espometeo | subsrv=/environment | comp=cygnus-ngsi | op=processNewBatches | msg=com.telefonica.iot.cygnus.sinks.NGSISink[541] :
</code>```

Seems like cygnus is getting all the data from the Orion and putting it right, but when i go to the postgresql db, there nothing. Some one already have this problem?

Persistance ERROR message:

```<code>cygnus_fiware | time=2017-06-22T09:45:06.092Z | lvl=ERROR | corr=N/A | trans=N/A | srv=N/A | subsrv=N/A | comp=cygnus-ngsi | op=processRollbackedBatches | msg=com.telefonica.iot.cygnus.sinks.NGSISink[398] : CygnusPersistenceError. -, null. Stack trace: [com.telefonica.iot.cygnus.sinks.NGSIPostgreSQLSink.persistAggregation(NGSIPostgreSQLSink.java:504), com.telefonica.iot.cygnus.sinks.NGSIPostgreSQLSink.persistBatch(NGSIPostgreSQLSink.java:231), com.telefonica.iot.cygnus.sinks.NGSISink.processRollbackedBatches(NGSISink.java:390), com.telefonica.iot.cygnus.sinks.NGSISink.process(NGSISink.java:372), org.apache.flume.sink.DefaultSinkProcessor.process(DefaultSinkProcessor.java:68), org.apache.flume.SinkRunner$PollingRunner.run(SinkRunner.java:147), java.lang.Thread.run(Thread.java:748)]
</code>```

Cygnus start ERRORS:

```<code>cygnus_fiware | + exec /usr/lib/jvm/java-6-sun/bin/java -Xms512m -Xmx1g -Dcom.sun.management.jmxremote -Dflume.root.logger=INFO,console -Duser.timezone=UTC -Dfile.encoding=UTF-8 -cp '/opt/apache-flume/conf:/opt/apache-flume/lib/*:/opt/apache-flume/plugins.d/cygnus/lib/*:/opt/apache-flume/plugins.d/cygnus/libext/*' -Djava.library.path= com.telefonica.iot.cygnus.nodes.CygnusApplication -f /opt/apache-flume/conf/agent.conf -n cygnus-ngsi -p 8081
cygnus_fiware | /opt/apache-flume/bin/cygnus-flume-ng: line 232: /usr/lib/jvm/java-6-sun/bin/java: No such file or directory
cygnus_fiware | /opt/apache-flume/bin/cygnus-flume-ng: line 232: exec: /usr/lib/jvm/java-6-sun/bin/java: cannot execute: No such file or directory
</code>```

答: I solved the issue by changing false to true in agent.conf file: cygnus-ngsi.sinks.postgresql-sink.backend.enable_cache = true.</p>

Body:
Im trying to save some data in a postgreSQL database using cygnus-ngsi, but nothing happens. Im running all services in a docker container using docker-compose.

docker-compose.yml:

...
cygnus:
 image: fiware/cygnus-ngsi:latest
 hostname: cygnus
 container_name: cygnus_fiware
 volumes:
   - ./config/cygnus/cygnus.conf:/opt/apache-flume/conf/agent.conf
   - ./config/cygnus/grouping_rules.conf:/opt/apache-flume/conf/grouping_rules.conf
 links:
   - orion
   - postgres
 expose:
   - "5050"
 ports:
   - "5050:5050"

postgres:
 restart: always
 image: postgres:latest
 container_name: postgres_fiware
 volumes:
   - ./data/db/postgres:/var/lib/postgresql/data
 ports:
   - "5432:5432"
 expose:
   - "5432"
 environment:
   - POSTGRES_USER=teste
   - POSTGRES_DB=newdb
   - POSTGRES_PASSWORD=123456789

agent.conf

cygnus-ngsi.sources = http-source
cygnus-ngsi.sinks = postgresql-sink
cygnus-ngsi.channels = postgresql-channel

#=============================================
# source configuration
# channel name where to write the notification events
cygnus-ngsi.sources.http-source.channels = postgresql-channel
# source class, must not be changed
cygnus-ngsi.sources.http-source.type = org.apache.flume.source.http.HTTPSource
# listening port the Flume source will use for receiving incoming notifications
cygnus-ngsi.sources.http-source.port = 5050
# Flume handler that will parse the notifications, must not be changed
cygnus-ngsi.sources.http-source.handler = com.telefonica.iot.cygnus.handlers.NGSIRestHandler
# URL target
cygnus-ngsi.sources.http-source.handler.notification_target = /notify
# default service (service semantic depends on the persistence sink)
cygnus-ngsi.sources.http-source.handler.default_service = default
# default service path (service path semantic depends on the persistence sink)
cygnus-ngsi.sources.http-source.handler.default_service_path = /
# source interceptors, do not change
cygnus-ngsi.sources.http-source.interceptors = ts gi
# TimestampInterceptor, do not change
cygnus-ngsi.sources.http-source.interceptors.ts.type = timestamp
# GroupingInterceptor, do not change
cygnus-ngsi.sources.http-source.interceptors.gi.type = com.telefonica.iot.cygnus.interceptors.NGSIGroupingInterceptor$Builder
# Grouping rules for the GroupingInterceptor, put the right absolute path to the file if necessary
# see the doc/design/interceptors document for more details
cygnus-ngsi.sources.http-source.interceptors.gi.grouping_rules_conf_file = /opt/apache-flume/conf/grouping_rules.conf

# ============================================
# NGSIPostgreSQLSink configuration
# channel name from where to read notification events
cygnus-ngsi.sinks.postgresql-sink.channel = postgresql-channel
# sink class, must not be changed
cygnus-ngsi.sinks.postgresql-sink.type = com.telefonica.iot.cygnus.sinks.NGSIPostgreSQLSink
# true applies the new encoding, false applies the old encoding.
cygnus-ngsi.sinks.postgresql-sink.enable_encoding = false
# true if name mappings are enabled for this sink, false otherwise
cygnus-ngsi.sinks.postgresql-sink.enable_name_mappings = false
# true if the grouping feature is enabled for this sink, false otherwise
cygnus-ngsi.sinks.postgresql-sink.enable_grouping = false
# true if lower case is wanted to forced in all the element names, false otherwise
cygnus-ngsi.sinks.postgresql-sink.enable_lowercase = false
# the FQDN/IP address where the PostgreSQL server runs
cygnus-ngsi.sinks.postgresql-sink.postgresql_host = postgres
# the port where the PostgreSQL server listens for incomming connections
cygnus-ngsi.sinks.postgresql-sink.postgresql_port = 5432
# the name of the postgresql database
cygnus-ngsi.sinks.postgresql-sink.postgresql_database = newdb
# a valid user in the PostgreSQL server
cygnus-ngsi.sinks.postgresql-sink.postgresql_username = teste
# password for the user above
cygnus-ngsi.sinks.postgresql-sink.postgresql_password = 123456789
# how the attributes are stored, either per row either per column (row, column)
cygnus-ngsi.sinks.postgresql-sink.attr_persistence = row
# select the data_model: dm-by-service-path or dm-by-entity
cygnus-ngsi.sinks.postgresql-sink.data_model = dm-by-entity
# number of notifications to be included within a processing batch
cygnus-ngsi.sinks.postgresql-sink.batch_size = 100
# timeout for batch accumulation
cygnus-ngsi.sinks.postgresql-sink.batch_timeout = 30
# number of retries upon persistence error
cygnus-ngsi.sinks.postgresql-sink.batch_ttl = 10

# =============================================
# postgresql-channel configuration
# channel type (must not be changed)
cygnus-ngsi.channels.postgresql-channel.type = memory
# capacity of the channel
cygnus-ngsi.channels.postgresql-channel.capacity = 1000
# amount of bytes that can be sent per transaction
cygnus-ngsi.channels.postgresql-channel.transactionCapacity = 100

Messages from docker-compose:

cygnus_fiware | time=2017-06-19T15:11:15.132Z | lvl=WARN | corr=4af15a0c-5501-11e7-aa0a-0242ac130004 | trans=508576db-1443-4c64-bfc9-629d1a0b250e | srv=espometeo | subsrv=/environment | comp=cygnus-ngsi | op=getEvents | msg=com.telefonica.iot.cygnus.handlers.NGSIRestHandler[257] : [NGSIRestHandler] Unnecessary header
cygnus_fiware | time=2017-06-19T15:11:15.133Z | lvl=INFO | corr=89ac4c66-5501-11e7-850f-0242ac130004 | trans=3ae0dc99-de51-49a3-937f-42d887b7e7d7 | srv=espometeo | subsrv=/environment | comp=cygnus-ngsi | op=getEvents | msg=com.telefonica.iot.cygnus.handlers.NGSIRestHandler[282] : [NGSIRestHandler] Starting internal transaction (3ae0dc99-de51-49a3-937f-42d887b7e7d7)
cygnus_fiware | time=2017-06-19T15:11:15.133Z | lvl=INFO | corr=89ac4c66-5501-11e7-850f-0242ac130004 | trans=3ae0dc99-de51-49a3-937f-42d887b7e7d7 | srv=espometeo | subsrv=/environment | comp=cygnus-ngsi | op=getEvents | msg=com.telefonica.iot.cygnus.handlers.NGSIRestHandler[299] : [NGSIRestHandler] Received data ({  "subscriptionId" : "5947d328e143997a02b11008",  "originator" : "localhost",  "contextResponses" : [    {      "contextElement" : {        "type" : "EstacaoMeteo",        "isPattern" : "false",        "id" : "Estacao3",        "attributes" : [          {            "name" : "Humidity",            "type" : "float",            "value" : "35.3",            "metadatas" : [              {                "name" : "TimeInstant",                "type" : "ISO8601",                "value" : "2017-06-24T13:03:00"              }            ]          },          {            "name" : "Temperature",            "type" : "float",            "value" : "15.2",            "metadatas" : [              {                "name" : "TimeInstant",                "type" : "ISO8601",                "value" : "2017-06-24T13:03:00"              }            ]          }        ]      },      "statusCode" : {        "code" : "200",        "reasonPhrase" : "OK"      }    }  ]})

cygnus_fiware | time=2017-06-19T15:11:36.141Z | lvl=INFO | corr=89ac4c66-5501-11e7-850f-0242ac130004 | trans=3ae0dc99-de51-49a3-937f-42d887b7e7d7 | srv=espometeo | subsrv=/environment | comp=cygnus-ngsi | op=persistAggregation | msg=com.telefonica.iot.cygnus.sinks.NGSIPostgreSQLSink[479] : [postgresql-sink] Persisting data at NGSIPostgreSQLSink. Schema (espometeo), Table (environment_estacao3_estacaometeo), Fields ((recvTimeTs,recvTime,fiwareServicePath,entityId,entityType,attrName,attrType,attrValue,attrMd)), Values (('1497885075139','2017-06-19T15:11:15.139Z','/environment','Estacao3','EstacaoMeteo','Humidity','float','35.3','[{"name":"TimeInstant","type":"ISO8601","value":"2017-06-24T13:03:00"}]'),('1497885075139','2017-06-19T15:11:15.139Z','/environment','Estacao3','EstacaoMeteo','Temperature','float','15.2','[{"name":"TimeInstant","type":"ISO8601","value":"2017-06-24T13:03:00"}]'))
cygnus_fiware | time=2017-06-19T15:11:36.142Z | lvl=WARN | corr=89ac4c66-5501-11e7-850f-0242ac130004 | trans=3ae0dc99-de51-49a3-937f-42d887b7e7d7 | srv=espometeo | subsrv=/environment | comp=cygnus-ngsi | op=processNewBatches | msg=com.telefonica.iot.cygnus.sinks.NGSISink[541] :

Seems like cygnus is getting all the data from the Orion and putting it right, but when i go to the postgresql db, there nothing. Some one already have this problem?

Persistance ERROR message:

cygnus_fiware | time=2017-06-22T09:45:06.092Z | lvl=ERROR | corr=N/A | trans=N/A | srv=N/A | subsrv=N/A | comp=cygnus-ngsi | op=processRollbackedBatches | msg=com.telefonica.iot.cygnus.sinks.NGSISink[398] : CygnusPersistenceError. -, null. Stack trace: [com.telefonica.iot.cygnus.sinks.NGSIPostgreSQLSink.persistAggregation(NGSIPostgreSQLSink.java:504), com.telefonica.iot.cygnus.sinks.NGSIPostgreSQLSink.persistBatch(NGSIPostgreSQLSink.java:231), com.telefonica.iot.cygnus.sinks.NGSISink.processRollbackedBatches(NGSISink.java:390), com.telefonica.iot.cygnus.sinks.NGSISink.process(NGSISink.java:372), org.apache.flume.sink.DefaultSinkProcessor.process(DefaultSinkProcessor.java:68), org.apache.flume.SinkRunner$PollingRunner.run(SinkRunner.java:147), java.lang.Thread.run(Thread.java:748)]

Cygnus start ERRORS:

cygnus_fiware | + exec /usr/lib/jvm/java-6-sun/bin/java -Xms512m -Xmx1g -Dcom.sun.management.jmxremote -Dflume.root.logger=INFO,console -Duser.timezone=UTC -Dfile.encoding=UTF-8 -cp '/opt/apache-flume/conf:/opt/apache-flume/lib/*:/opt/apache-flume/plugins.d/cygnus/lib/*:/opt/apache-flume/plugins.d/cygnus/libext/*' -Djava.library.path= com.telefonica.iot.cygnus.nodes.CygnusApplication -f /opt/apache-flume/conf/agent.conf -n cygnus-ngsi -p 8081
cygnus_fiware | /opt/apache-flume/bin/cygnus-flume-ng: line 232: /usr/lib/jvm/java-6-sun/bin/java: No such file or directory
cygnus_fiware | /opt/apache-flume/bin/cygnus-flume-ng: line 232: exec: /usr/lib/jvm/java-6-sun/bin/java: cannot execute: No such file or directory


问:
Generic type 'Component
' requires 2 type argument(s)
I'm trying to use ts and react-router v4 to make a demo, and I will get the error.

```<code>Failed to compile.

Error in D:\data\code\taven\react-components-usage-ts\node_modules\@types\react-router\lib\withRouter.d.ts

(3,99): error TS2314: Generic type 'PureComponent<P, S>' requires 2 type argument(s).
</code>```

答:
I also saw this error. This error was made in the latest version for 2 weeks ago in version 4.0.12. Use the previous version. In it everything works OK.

npm install --save @types/react-router@4.0.11

The same thing happened with react-route-dom. Use:

npm install --save @types/react-router-dom@4.0.4

Title: Generic type 'Component<P, S>' requires 2 type argument(s)

Body:
I'm trying to use ts and react-router v4 to make a demo, and I will get the error.

Failed to compile.

Error in D:\data\code\taven\react-components-usage-ts\node_modules\@types\react-router\lib\withRouter.d.ts

(3,99): error TS2314: Generic type 'PureComponent
' requires 2 type argument(s).


问:
SQL Server Data Optimization Techniques
I want implement one of the data optimization techniques on my SQL database.
I preferred to go for creating indexes first, for which i used Tuning Advisor.
Tuning advisor recommended me many of the Non-Clustered Indexes.

Shall I create all these indexes to improve performance ?  Or Can create those only having less in size?

Please suggest me..as I am very new to this area ..

答:
As for your question in implementing indexes, you must know that the first step towards monitoring, and intelligently responding to index usage needs, is to collect and maintain a simple and easy-to-use data set of index usage metrics.

This data set should allow you to quickly search for common scenarios in which you might consider removing or altering an index:

Unused indexes

Minimally used indexes

Indexes that are written to significantly more than they are read

Indexes that are scanned often, but rarely the target of seeks

Indexes that are very similar and can be combined

SQL Server provides a dynamic management view that tracks all index usage: sys.dm_db_index_usage_stats.

This view is a cumulative total of operations against indexes and is reset when SQL Server services are restarted.

To learn more, please refer to this article https://www.sqlshack.com/sql-server-index-performance-tuning-using-built-in-index-utilization-metrics/

Title: SQL Server Data Optimization Techniques


问:
C# word automation find and replace long text field
I have a function to find and replace a text placeholder inside a word document. Which works fine for short text strings.  Does nothing however when attempting to replace with larger text strings i.e. a paragraph of text.

```<code>DocReplaceField(ref Word.Document objDoc, string Field, string Value)
{
   object missing = System.Reflection.Missing.Value;

   Word.Range range = objDoc.Content;

   object findtext = Field;
   object f = false;
   object findreplacement = Value;
   object findforward = false;
   object findformat = true;
   object findwrap = WdFindWrap.wdFindContinue;
   object findmatchcase = false;
   object findmatchwholeword = false;
   object findmatchwildcards = false;
   object findmatchsoundslike = false;
   object findmatchallwordforms = false;
   object findreplace = WdReplace.wdReplaceAll;

   range.Find.Execute(
       findtext,
       findmatchcase,
       findmatchwholeword,
       findmatchwildcards,
       findmatchsoundslike,
       findmatchallwordforms,
       findforward,
       findwrap,
       findformat,
       findreplacement,
       findreplace,
       missing,
       missing,
       missing,
       missing);
}
</code>```

This works find if i try replacing "[placeholder]" with "Something" but how do i replace "[placeholder]" with

"Nullam non lorem sapien, et imperdiet sapien. Curabitur vestibulum justo eu enim bibendum vulputate. Integer vel velit non elit molestie auctor non ut nisi. Suspendisse potenti. Donec augue nulla, vestibulum a pulvinar id, scelerisque quis mauris. Integer eget ullamcorper velit. Sed at purus sit amet felis pulvinar dictum at non neque. Praesent laoreet mauris id sem venenatis pellentesque."

for example

UPDATE:

The issue seems to be that word's find and replace cannot replace with more than 255 characters.  The search is matching the placeholder but cannot actually replace the text. Does anyone have an example of calling the find to locate the placeholder but then manually selecting the text and inserting new text. Instead of using the word find and replace.

答:
Here is a quick and short solution to your problem. If the range.Find.Execute method does not work for more than 255 characters than you can simply scan the document manually and search for the text, than issue the replacement from the string of text.

To use the code below you must include the following:

```<code>Using Word = Microsoft.Office.Interop.Word;
Using System.Text.RegularExpressions;   //This is used for Regex
</code>```

You need to add in the Microsoft Word object library. Below is the code from start to finish.

```<code>string filePath = @"C:\YourfilePathHere";
string findText = "Your text to locate goes here";
string replaceText = "The replacement text longer than 255 characters";
Word.Application fileOpen = new Word.Application;
Word.Document doc = fileOpen.Documents.Open(filePath, ReadOnly: false);
foreach (Word.Paragraph para in doc.Paragraphs) {
   Word.Range paraRange = para.Range;
   string text = paraRange.Text;
   Regex regex = new Regex(findText);
   string final = regex.Replace(text, replaceText);
   paraRange.Text = final;
}
</code>```

Now the above will have replaced your text with an unlimited sized replacement.

Body:
I have a function to find and replace a text placeholder inside a word document. Which works fine for short text strings.  Does nothing however when attempting to replace with larger text strings i.e. a paragraph of text.

DocReplaceField(ref Word.Document objDoc, string Field, string Value)
{
   object missing = System.Reflection.Missing.Value;

   Word.Range range = objDoc.Content;

   object findtext = Field;
   object f = false;
   object findreplacement = Value;
   object findforward = false;
   object findformat = true;
   object findwrap = WdFindWrap.wdFindContinue;
   object findmatchcase = false;
   object findmatchwholeword = false;
   object findmatchwildcards = false;
   object findmatchsoundslike = false;
   object findmatchallwordforms = false;
   object findreplace = WdReplace.wdReplaceAll;

   range.Find.Execute(
       findtext,
       findmatchcase,
       findmatchwholeword,
       findmatchwildcards,
       findmatchsoundslike,
       findmatchallwordforms,
       findforward,
       findwrap,
       findformat,
       findreplacement,
       findreplace,
       missing,
       missing,
       missing,
       missing);
}

This works find if i try replacing "[placeholder]" with "Something" but how do i replace "[placeholder]" with

"Nullam non lorem sapien, et imperdiet sapien. Curabitur vestibulum justo eu enim bibendum vulputate. Integer vel velit non elit molestie auctor non ut nisi. Suspendisse potenti. Donec augue nulla, vestibulum a pulvinar id, scelerisque quis mauris. Integer eget ullamcorper velit. Sed at purus sit amet felis pulvinar dictum at non neque. Praesent laoreet mauris id sem venenatis pellentesque."

for example

UPDATE:

The issue seems to be that word's find and replace cannot replace with more than 255 characters.  The search is matching the placeholder but cannot actually replace the text. Does anyone have an example of calling the find to locate the placeholder but then manually selecting the text and inserting new text. Instead of using the word find and replace.

Body:
Here is a quick and short solution to your problem. If the range.Find.Execute method does not work for more than 255 characters than you can simply scan the document manually and search for the text, than issue the replacement from the string of text.

To use the code below you must include the following:

Using Word = Microsoft.Office.Interop.Word;
Using System.Text.RegularExpressions;   //This is used for Regex

You need to add in the Microsoft Word object library. Below is the code from start to finish.

string filePath = @"C:\YourfilePathHere";
string findText = "Your text to locate goes here";
string replaceText = "The replacement text longer than 255 characters";
Word.Application fileOpen = new Word.Application;
Word.Document doc = fileOpen.Documents.Open(filePath, ReadOnly: false);
foreach (Word.Paragraph para in doc.Paragraphs) {
   Word.Range paraRange = para.Range;
   string text = paraRange.Text;
   Regex regex = new Regex(findText);
   string final = regex.Replace(text, replaceText);
   paraRange.Text = final;
}

Now the above will have replaced your text with an unlimited sized replacement.


问:
Is there size limit on appending ORC data files to Vora tables
I created a Vora table in Vora 1.3 and tried to append data to that table from ORC files that I got from SAP BW archiving process (NLS on Hadoop). I had 20 files, in total containing approx 50 Mio records.

When I tried to use the "files" setting in the APPEND statement as "/path/*", after approx 1 hour Vora returned this error message:

```<code>com.sap.spark.vora.client.VoraClientException: Could not load table F002_5F: [Vora [eba156.extendtec.com.au:42681.1640438]] java.lang.RuntimeException: Wrong magic number in response, expected: 0x56320170, actual: 0x00000000. An unsuccessful attempt to load a table might lead to an inconsistent table state. Please drop the table and re-create it if necessary. with error code 0, status ERROR_STATUS
</code>```

Next thing I tried was appending data from each file using separate APPEND statements. On the 15th append (of 20) I've got the same error message.

答:
The error indicates that the Vora engine on node eba156.extendtec.com.au is not available. I suspect it either crashed or ran into an out-of-memory situtation.

You can check the log directory for a crash dump. If you find one, please open a customer message for further investigation.

If you do not find a crash dump, it is likely a out-of-memory situation. You should find confirmation in either the engine log file or in /var/log/messages (if the oom killer ended the process). In that case, the available memory is not sufficient to load the data.

Body:
I created a Vora table in Vora 1.3 and tried to append data to that table from ORC files that I got from SAP BW archiving process (NLS on Hadoop). I had 20 files, in total containing approx 50 Mio records.

When I tried to use the "files" setting in the APPEND statement as "/path/*", after approx 1 hour Vora returned this error message:

com.sap.spark.vora.client.VoraClientException: Could not load table F002_5F: [Vora [eba156.extendtec.com.au:42681.1640438]] java.lang.RuntimeException: Wrong magic number in response, expected: 0x56320170, actual: 0x00000000. An unsuccessful attempt to load a table might lead to an inconsistent table state. Please drop the table and re-create it if necessary. with error code 0, status ERROR_STATUS

Next thing I tried was appending data from each file using separate APPEND statements. On the 15th append (of 20) I've got the same error message.


问:
Avoid error 'The selector of the component should be named kebab-case and include dash '
How could I avoid error 'The selector of the component should be named kebab-case and include dash ' in Angular2, if I don't want to rename the selector? Is there any workaround?..</p>

答:
Try</p>

```<code>import {CUSTOM_ELEMENTS_SCHEMA} from "@angular/core";

@NgModule({
    schemas: [
        CUSTOM_ELEMENTS_SCHEMA
    ]
})
</code>```

Body:
Try

import {CUSTOM_ELEMENTS_SCHEMA} from "@angular/core";

@NgModule({
    schemas: [
        CUSTOM_ELEMENTS_SCHEMA
    ]
})


问:
Selecting all rows with only one value in column with another common value
my table:

```<code>drop table if exists new_table;
create table if not exists new_table(
    obj_type int(4),
    user_id varchar(30),
    payer_id varchar(30)
);

insert into new_table (obj_type, user_id, payer_id) values
    (1, 'user1', 'payer1'),
    (1, 'user2', 'payer1'),
    (2, 'user3', 'payer1'),
    (1, 'user1', 'payer2'),
    (1, 'user2', 'payer2'),
    (2, 'user3', 'payer2'),
    (3, 'user1', 'payer3'),
    (3, 'user2', 'payer3');
</code>```

I am trying to select all the payer id's whose obj_type is only one value and not any other values. In other words, even though each payer has multiple users, I only want the payers who are only using one obj_type.

I have tried using a query like this:

```<code>select * from new_table
    where obj_type = 1
    group by payer_id;
</code>```

But this returns rows whose payers also have other user's with other obj_types. I am trying to get a result that looks like:

```<code>obj | user  |  payer
----|-------|--------
3   | user1 |  payer3
3   | user2 |  payer3
</code>```

Thanks in advance.

答:
That is actually easy:

```<code>SELECT player_id
FROM new_table
GROUP BY player_id
HAVING COUNT(DISTINCT obj_type) = 1
</code>```

Having filters rows just like WHERE but it does so after the aggregation.

The difference is best explained by an example:

```<code>SELECT dept_id, SUM(salary)
FROM employees
WHERE salary > 100000
GROUP BY dept_id
</code>```

This will give you the sum of the salaries of people earning more than 100000 each.

```<code>SELECT dept_id, SUM(salary)
FROM employees
GROUP BY dept_id
HAVINF salary > 100000
</code>```

The second query will give you the departments where all employees together earn more than 100000 even if no single employee earns that much.

Body:
my table:

drop table if exists new_table;
create table if not exists new_table(
    obj_type int(4),
    user_id varchar(30),
    payer_id varchar(30)
);

insert into new_table (obj_type, user_id, payer_id) values
    (1, 'user1', 'payer1'),
    (1, 'user2', 'payer1'),
    (2, 'user3', 'payer1'),
    (1, 'user1', 'payer2'),
    (1, 'user2', 'payer2'),
    (2, 'user3', 'payer2'),
    (3, 'user1', 'payer3'),
    (3, 'user2', 'payer3');

I am trying to select all the payer id's whose obj_type is only one value and not any other values. In other words, even though each payer has multiple users, I only want the payers who are only using one obj_type.

I have tried using a query like this:

select * from new_table
    where obj_type = 1
    group by payer_id;

But this returns rows whose payers also have other user's with other obj_types. I am trying to get a result that looks like:

obj | user  |  payer
----|-------|--------
3   | user1 |  payer3
3   | user2 |  payer3

Thanks in advance.

Body:
That is actually easy:

SELECT player_id
FROM new_table
GROUP BY player_id
HAVING COUNT(DISTINCT obj_type) = 1

Having filters rows just like WHERE but it does so after the aggregation.

The difference is best explained by an example:

SELECT dept_id, SUM(salary)
FROM employees
WHERE salary > 100000
GROUP BY dept_id

This will give you the sum of the salaries of people earning more than 100000 each.

SELECT dept_id, SUM(salary)
FROM employees
GROUP BY dept_id
HAVINF salary > 100000

The second query will give you the departments where all employees together earn more than 100000 even if no single employee earns that much.


问:
Constraining time with LINQ
I'm having difficulty constraining time in a LINQ statement. I am still pretty new with LINQ. The SQL I want to emulate is something like this:

```<code>SELECT ID, Token, StartTime
FROM Tokens
WHERE Token = '050'
AND StartTime > DATEADD(MI, -30, CURRENT_TIMESTAMP)
</code>```

This SQL statement gets only rows where the time in the StartTime column is less than 30 minutes from the current time. How would I do this with LINQ? So far my best guess is

```<code>DateTime cutoff = DateTime.Now - new TimeSpan(0, 30, 0);
IEnumerable<Tokens> token = dataContext.Tokens.Where(row => row.Token == "050" &&
                                                            row.StartTime > cutoff);
</code>```

But that doesn't seem to be working. Any advise?

答:
You may add 30 days to token's StartTime and compare it to current date. You should probably also compare token text as string (double quotes), as it possibly might be a VARCHAR2 type.

```<code>var token = dataContext.Tokens.Where(r =>
  r.Token == "5" &&
  r.StartTime.AddDays(30).Date >= DateTime.Now.Date
);
</code>```

Edit: probably you want to show last 30 days of operation, to do this date and time should be rounded to date - changed code.

Title: Constraining time with LINQ

Body:
I'm having difficulty constraining time in a LINQ statement. I am still pretty new with LINQ. The SQL I want to emulate is something like this:

SELECT ID, Token, StartTime
FROM Tokens
WHERE Token = '050'
AND StartTime > DATEADD(MI, -30, CURRENT_TIMESTAMP)

This SQL statement gets only rows where the time in the StartTime column is less than 30 minutes from the current time. How would I do this with LINQ? So far my best guess is

DateTime cutoff = DateTime.Now - new TimeSpan(0, 30, 0);
IEnumerable<Tokens> token = dataContext.Tokens.Where(row => row.Token == "050" &&
                                                            row.StartTime > cutoff);

But that doesn't seem to be working. Any advise?

Body:
You may add 30 days to token's StartTime and compare it to current date. You should probably also compare token text as string (double quotes), as it possibly might be a VARCHAR2 type.

var token = dataContext.Tokens.Where(r =>
  r.Token == "5" &&
  r.StartTime.AddDays(30).Date >= DateTime.Now.Date
);

Edit: probably you want to show last 30 days of operation, to do this date and time should be rounded to date - changed code.


问:
Group DataFrame, apply function with inputs then add result back to original
Can't find this question anywhere, so just try here instead:

What I'm trying to do is basically alter an existing DataFrame object using groupby-functionality, and a self-written function:

```<code>benchmark =

x    y    z    field_1

1    1    3    a
1    2    5    b
9    2    4    a
1    2    5    c
4    6    1    c
</code>```

What I want to do, is to groupby field_1, apply a function using specific columns as input, in this case columns x and y, then add back the result to the original DataFrame benchmark as a new column called new_field. The function itself is dependent on the value in field_1, i.e. field_1=a will yield a different result compared to field_1=b etc. (hence the grouping to start with).

Pseudo-code would be something like:

```<code>1. grouped_data = benchmark.groupby(['field_1'])
2. apply own_function to grouped_data; with inputs ('x', 'y', grouped_data)
3. add back result from function to benchmark as column 'new_field'
</code>```

Thanks,

ALTERATION:

```<code>benchmark =

x    y    z    field_1

1    1    3    a
1    2    5    b
9    2    4    a
1    2    5    c
4    6    1    c
</code>```

Elaboration:

I also have a DataFrame separate_data containing separate values for x,

```<code>separate_data =

x    a    b    c

1    1    3    7
2    2    5    6
3    2    4    4
4    2    5    9
5    6    1    10
</code>```

that will need to be interpolated onto the existing benchmark DataFrame. Which column in separate_data that should be used for interpolation is dependent on column field_1 in benchmark (i.e. values in set (a,b,c) above). The interpolated value in the new column, is based on x-value in benchmark.

Result:

benchmark =

```<code>x    y    z    field_1  field_new

1    1    3    a        interpolate using separate_data with x=1 and col=a
1    2    5    b        interpolate using separate_data with x=1 and col=b
9    2    4    a        ... etc
1    2    5    c        ...
4    6    1    c        ...
</code>```

Makes sense?

答:
EDIT:

I think you need reshape separate_data first by set_index + stack, set index names by rename_axis and set name of Serie by rename.

Then is possible groupby by both levels and use some function.

Then join it to benchmark with default left join:

```<code>separate_data1 =separate_data.set_index('x').stack().rename_axis(('x','field_1')).rename('d')
print (separate_data1)
x  field_1
1  a           1
   b           3
   c           7
2  a           2
   b           5
   c           6
3  a           2
   b           4
   c           4
4  a           2
   b           5
   c           9
5  a           6
   b           1
   c          10
Name: d, dtype: int64
</code>```

If necessary use some function, mainly if some duplicates in pairs x with field_1 it return nice unique pairs:

```<code>def func(x):
    #sample function
    return x / 2 + x ** 2

separate_data1 = separate_data1.groupby(level=['x','field_1']).apply(func)
print (separate_data1)
x  field_1
1  a            1.5
   b           10.5
   c           52.5
2  a            5.0
   b           27.5
   c           39.0
3  a            5.0
   b           18.0
   c           18.0
4  a            5.0
   b           27.5
   c           85.5
5  a           39.0
   b            1.5
   c          105.0
Name: d, dtype: float64

benchmark = benchmark.join(separate_data1, on=['x','field_1'])
print (benchmark)

   x  y  z field_1     d
0  1  1  3       a   1.5
1  1  2  5       b  10.5
2  9  2  4       a   NaN
3  1  2  5       c  52.5
4  4  6  1       c  85.5
</code>```

I think you cannot use transform because multiple columns which are read together.

So use apply:

```<code>df1 = benchmark.groupby(['field_1']).apply(func)
</code>```

And then for new column are multiple solutions, e.g. use join (default left join) or map.

Sample solution with both method is here.

Or is possible use flexible apply which can return new DataFrame with new column.

Body:
Can't find this question anywhere, so just try here instead:

What I'm trying to do is basically alter an existing DataFrame object using groupby-functionality, and a self-written function:

benchmark =

x    y    z    field_1

1    1    3    a
1    2    5    b
9    2    4    a
1    2    5    c
4    6    1    c

What I want to do, is to groupby field_1, apply a function using specific columns as input, in this case columns x and y, then add back the result to the original DataFrame benchmark as a new column called new_field. The function itself is dependent on the value in field_1, i.e. field_1=a will yield a different result compared to field_1=b etc. (hence the grouping to start with).

Pseudo-code would be something like:

1. grouped_data = benchmark.groupby(['field_1'])
2. apply own_function to grouped_data; with inputs ('x', 'y', grouped_data)
3. add back result from function to benchmark as column 'new_field'

Thanks,

ALTERATION:

benchmark =

x    y    z    field_1

1    1    3    a
1    2    5    b
9    2    4    a
1    2    5    c
4    6    1    c

Elaboration:

I also have a DataFrame separate_data containing separate values for x,

separate_data =

x    a    b    c

1    1    3    7
2    2    5    6
3    2    4    4
4    2    5    9
5    6    1    10

that will need to be interpolated onto the existing benchmark DataFrame. Which column in separate_data that should be used for interpolation is dependent on column field_1 in benchmark (i.e. values in set (a,b,c) above). The interpolated value in the new column, is based on x-value in benchmark.

Result:

benchmark =

x    y    z    field_1  field_new

1    1    3    a        interpolate using separate_data with x=1 and col=a
1    2    5    b        interpolate using separate_data with x=1 and col=b
9    2    4    a        ... etc
1    2    5    c        ...
4    6    1    c        ...

Makes sense?

Body:
EDIT:

I think you need reshape separate_data first by set_index + stack, set index names by rename_axis and set name of Serie by rename.

Then is possible groupby by both levels and use some function.

Then join it to benchmark with default left join:

separate_data1 =separate_data.set_index('x').stack().rename_axis(('x','field_1')).rename('d')
print (separate_data1)
x  field_1
1  a           1
   b           3
   c           7
2  a           2
   b           5
   c           6
3  a           2
   b           4
   c           4
4  a           2
   b           5
   c           9
5  a           6
   b           1
   c          10
Name: d, dtype: int64

If necessary use some function, mainly if some duplicates in pairs x with field_1 it return nice unique pairs:

def func(x):
    #sample function
    return x / 2 + x ** 2

separate_data1 = separate_data1.groupby(level=['x','field_1']).apply(func)
print (separate_data1)
x  field_1
1  a            1.5
   b           10.5
   c           52.5
2  a            5.0
   b           27.5
   c           39.0
3  a            5.0
   b           18.0
   c           18.0
4  a            5.0
   b           27.5
   c           85.5
5  a           39.0
   b            1.5
   c          105.0
Name: d, dtype: float64

benchmark = benchmark.join(separate_data1, on=['x','field_1'])
print (benchmark)

   x  y  z field_1     d
0  1  1  3       a   1.5
1  1  2  5       b  10.5
2  9  2  4       a   NaN
3  1  2  5       c  52.5
4  4  6  1       c  85.5

I think you cannot use transform because multiple columns which are read together.

So use apply:

df1 = benchmark.groupby(['field_1']).apply(func)

And then for new column are multiple solutions, e.g. use join (default left join) or map.

Sample solution with both method is here.

Or is possible use flexible apply which can return new DataFrame with new column.


问:
Result query to attribute
I'm a beginner on JPA and I don't know pass result of a query to attribute entity.
Let me explain in one example:

I have an entity called Team, and another called Players:
The player is children of Team.

Class Team:

```<code>public class Team{
...

(relationship with Player has been hidden)
...

@Column(name = "AMOUNT_PLAYERS")
private Short amountPlayers;

@Column(name = "AMOUNT_FIRSTSTRING_PLAYERS")
private Short amountFirstStringPlayers;

@Column(name = "AMOUNT_SECONDSTRING_PLAYERS")
private Short amountSecondStringPlayers;

...

}
</code>```

Class Player:

```<code>Public class Player{

...

@Column("STATUS_PLAYER")
private Short statusPlayer;
...

}
</code>```

I have two questions about this.

1) In the amountPlayers, I want number total of player from this team;

In the  amountFirstStringPlayers, I want number total of players (first-string) with statusPlayer of Player equals 1;

And in the amountSecondStringPlayers, I want number total of players (second-string) with statusPlayer of Player equals 2;

How I can get this values when I Find entity with JPA.

Example:

```<code>SELECT team FROM Team team
</code>```

When I execute this, I want amountPlayers, amountFirstStringPlayers and amountSecondStringPlayers.

2) Put the resultQuery in an attribute of an entity, on an entity is a good practice?

答:
You can use hibernate formula which are very convenient for these cases where you dont really need to persist these computed datas.

ex :

```<code>@Formula("(select count(*) from Player p where p.team_id = id)")
private Short amountPlayers;

@Formula("(select count(*) from Player p where p.team_id = id and p.statusPLayer=1)")
private Short amountFirstStringPlayers;

@Formula("(select count(*) from Player p where p.team_id = id and p.statusPLayer=2)")
private Short amountSecondStringPlayers;
</code>```

Formula accepts sql string as parameter and here in the example id is the id of the current entity. You must replace with your entity id name and column.

If you don't want to use Formula you can also compute these values in memory based on players relation in your team entity.

ex:

```<code>@OneToMany(mappedBy="team")
private List<Player> players; // Here your onetomany association

public short getAmountPlayers(){
return players!= null ? players.size() : 0;
}
</code>```

Title: Result query to attribute

Body:
I'm a beginner on JPA and I don't know pass result of a query to attribute entity.
Let me explain in one example:

I have an entity called Team, and another called Players:
The player is children of Team.

Class Team:

public class Team{
...

(relationship with Player has been hidden)
...

@Column(name = "AMOUNT_PLAYERS")
private Short amountPlayers;

@Column(name = "AMOUNT_FIRSTSTRING_PLAYERS")
private Short amountFirstStringPlayers;

@Column(name = "AMOUNT_SECONDSTRING_PLAYERS")
private Short amountSecondStringPlayers;

...

}

Class Player:

Public class Player{

...

@Column("STATUS_PLAYER")
private Short statusPlayer;
...

}

I have two questions about this.

1) In the amountPlayers, I want number total of player from this team;

In the  amountFirstStringPlayers, I want number total of players (first-string) with statusPlayer of Player equals 1;

And in the amountSecondStringPlayers, I want number total of players (second-string) with statusPlayer of Player equals 2;

How I can get this values when I Find entity with JPA.

Example:

SELECT team FROM Team team

When I execute this, I want amountPlayers, amountFirstStringPlayers and amountSecondStringPlayers.

2) Put the resultQuery in an attribute of an entity, on an entity is a good practice?

Body:
You can use hibernate formula which are very convenient for these cases where you dont really need to persist these computed datas.

ex :

@Formula("(select count(*) from Player p where p.team_id = id)")
private Short amountPlayers;

@Formula("(select count(*) from Player p where p.team_id = id and p.statusPLayer=1)")
private Short amountFirstStringPlayers;

@Formula("(select count(*) from Player p where p.team_id = id and p.statusPLayer=2)")
private Short amountSecondStringPlayers;

Formula accepts sql string as parameter and here in the example id is the id of the current entity. You must replace with your entity id name and column.

If you don't want to use Formula you can also compute these values in memory based on players relation in your team entity.

ex:

@OneToMany(mappedBy="team")
private List<Player> players; // Here your onetomany association

public short getAmountPlayers(){
return players!= null ? players.size() : 0;
}


问:
Entity Framework : Insert causes violation of PRIMARY KEY constraint using Azure SQL, not local
I'm in the process of migrating a local SQL Server 2014 database for use in Azure. I have an Asp.net MVC app running in IIS 8, connected to an Azure SQL Server database using Entity Framework in the usual way.

I have a dbContext

Using(... dbContext.Database.BeginTransaction())

other entities added and SaveChanges() runs successfully

For one entity in particular, I do db.entity.add(newEntity), then SaveChanges() and I get:

Exception: Violation of PRIMARY KEY constraint 'PK_entity'. Cannot insert duplicate key in object 'dbo.entity'. The duplicate key value is (2).

The primary key is an auto increment number and I'm the only user running this. There are 156 records in this table already.

What's bizarre is that this works fine when I run this on my local machine using a local SQL Server instance, but when run from IIS and Azure db, this exception occurs.

The entity has no other relations/constraints at all.

I do feel there may be a clue in that if I keep trying to save this record (ISS and Azure), the failed duplicate key value increments by 1 each time.

答:
That´s very strange, maybe the index of identity coll in Azure Bd is set to 1.
You can force your identity coll to a index greater than your last Id in table:

In sql server you can check next Id:

```<code>SELECT IDENT_CURRENT ('tablename') AS Current_Identity;
</code>```

You can force it to other number:

```<code>DBCC CHECKIDENT ('tablename', RESEED, 157);
</code>```

Body:
That´s very strange, maybe the index of identity coll in Azure Bd is set to 1.
You can force your identity coll to a index greater than your last Id in table:

In sql server you can check next Id:

SELECT IDENT_CURRENT ('tablename') AS Current_Identity;

You can force it to other number:

DBCC CHECKIDENT ('tablename', RESEED, 157);


问:
How do I add attributes to existing HTML elements in TypeScript/JSX?
Anyone know how to properly add/extend all native HTML element attributes with custom ones?

With the TypeScript documentation for merging interfaces, I thought that I could just do this:

```<code>interface HTMLElement {
    block?: BEM.Block;
    element?: BEM.Element;
    modifiers?: BEM.Modifiers;
}

<div block="foo" />; // error
</code>```

But I get the following Intellisense error in vscode 1.6.1 (latest):

[ts] Property 'block' does not exist on type 'HTMLProps'.

The HTMLProps to which they are referring is React.HTMLProps<T> and the div element is declared to use it like so:

```<code>namespace JSX {
    interface IntrinsicElements {
        div: React.HTMLProps<HTMLDivElement>
    }
}
</code>```

I tried redeclaring the div, but to no avail.

Related: https://github.com/Microsoft/TypeScript/issues/11684

Edit: Here's what ended up working for me:

```<code>declare module 'react' {
    interface HTMLAttributes<T> extends DOMAttributes<T> {
        block?: string
        element?: string
        modifiers?: Modifiers // <-- custom interface
    }
}
</code>```

答:
I wanted to use glamor's createElement replacement which adds a css prop to every element.

To add to the accepted answer, module augmentation seems to do the trick but HTMLProps only worked for non-input elements. The correct interfaces to extend seems to be HTMLAttributes and SVGAttributes.

```<code>declare module 'react' {
  interface HTMLAttributes<T> {
    css?: any
  }

  interface SVGAttributes<T> {
    css?: any
  }
}
</code>```

To avoid importing the module augmentation in every component, re-export  createElement:

```<code>// createElement.ts
import { createElement } from 'glamor/react'

declare module 'react' {
  interface HTMLAttributes<T> {
    css?: any
  }

  interface SVGAttributes<T> {
    css?: any
  }
}

export default createElement
</code>```

Then tell TS to use our createElement for JSX with this tsconfig:

```<code>{
  "compilerOptions": {
    "jsx": "react",
    "jsxFactory": "createElement"
  }
}
</code>```

Usage:

```<code>// MyComponent.tsx
import createElement from './createElement'

export default function MyComponent() {
  return <div css={{ color: 'red' }} />
}
</code>```

Body:
Anyone know how to properly add/extend all native HTML element attributes with custom ones?

With the TypeScript documentation for merging interfaces, I thought that I could just do this:

interface HTMLElement {
    block?: BEM.Block;
    element?: BEM.Element;
    modifiers?: BEM.Modifiers;
}

; // error

But I get the following Intellisense error in vscode 1.6.1 (latest):

[ts] Property 'block' does not exist on type 'HTMLProps'.

The HTMLProps to which they are referring is React.HTMLProps<T> and the div element is declared to use it like so:

namespace JSX {
    interface IntrinsicElements {
        div: React.HTMLProps<HTMLDivElement>
    }
}

I tried redeclaring the div, but to no avail.

Related: https://github.com/Microsoft/TypeScript/issues/11684

Edit: Here's what ended up working for me:

declare module 'react' {
    interface HTMLAttributes<T> extends DOMAttributes<T> {
        block?: string
        element?: string
        modifiers?: Modifiers // <-- custom interface
    }
}

Body:
I wanted to use glamor's createElement replacement which adds a css prop to every element.

To add to the accepted answer, module augmentation seems to do the trick but HTMLProps only worked for non-input elements. The correct interfaces to extend seems to be HTMLAttributes and SVGAttributes.

declare module 'react' {
  interface HTMLAttributes<T> {
    css?: any
  }

  interface SVGAttributes<T> {
    css?: any
  }
}

To avoid importing the module augmentation in every component, re-export  createElement:

// createElement.ts
import { createElement } from 'glamor/react'

declare module 'react' {
  interface HTMLAttributes<T> {
    css?: any
  }

  interface SVGAttributes<T> {
    css?: any
  }
}

export default createElement

Then tell TS to use our createElement for JSX with this tsconfig:

{
  "compilerOptions": {
    "jsx": "react",
    "jsxFactory": "createElement"
  }
}

Usage:

// MyComponent.tsx
import createElement from './createElement'

export default function MyComponent() {
  return <div css={{ color: 'red' }} />
}


问:
Analogs of Intel's Cluster OpenMP
Are there analogs of Intel Cluster OpenMP? This library simulates shared-memory machine (like SMP or NUMA) while running on distributed memory machine (like Ethernet-connected cluster of PC's).

This library allows to start openmp programs directly on cluster.

I search for

libraries, which allow multithreaded programms run on distributed cluster

or libraries (replacement of e.g. libgomp), which allow OpenMP programms run on distributed cluster

or compilers, capable of generating cluster code from openmp programms, besides Intel C++

答:
The keyword you want to be searching for is "distributed shared memory"; there's a Wikipedia page on the subject.  MOSIX, which became openMOSIX, which is now being developed as part of LinuxPMI, is the closest thing I'm aware of; but I don't have much experience with the current LinuxPMI project.

One thing you need to be aware of is that none of these systems work especially well, performance-wise.  (Maybe a more optimistic way of saying it is that it's a tribute to the developers that these things work at all).   You can't just abstract away the fact that accessing on-node memory is very very different from memory on some other node over a network.  Even making local memory systems fast is difficult and requires a lot of hardware; you can't just hope that a little bit of software will hide the fact that you're now doing things over a network.

The performance ramifications are especially important when you consider that OpenMP programs you might want to run are almost always going to be written assuming that memory accesses are local and thus cheap, because, well, that's what OpenMP is for.    False sharing is bad enough when you're talking about different sockets accessing a common cache line - page-based false sharing across a network is just disasterous.

Now, it could well be that you have a very simple program with very little actual shared state, and a distributed shared memory system wouldn't be so bad -- but in that case I've got to think you'd be better off in the long run just migrating the problem away from a shared-memory-based model like OpenMP towards something that'll work better in a cluster environment anyway.

Title: Analogs of Intel's Cluster OpenMP


问:
How to make rowIndex as sequentially increasing number across all page numbers in gridview paging?
I have a GridView with pagination and each page contains 10 rows. When navigating to second page(OnPageIndexChanging) I want to consider rowIndex as sequentially increasing number across all page numbers.

For example, if the rowindex ends at 9 on page 1 then the rowindex should start with 10 for the first row in the next page of the GridView.

Any Ideas?

答:
An idea is:

Create a ViewState and count indexes on every page and put the last index in ViewState.


问:
Google maps not showing on signed apk android
In my project the Maps and everything, but when I generate a signed APK it doesn't works, I already have the "google_maps_key" in my project, I went to Google Console and put any restriction so I could test not just from my Android Device and still nothing! </p>

答:
You should create a release key and add it to your project .
Release APK file not showing google maps
This link answers you proble. It's a common problem .
You should create a .jks file first and store it somewhere in you app folder.
Then Create a SHA1 Fingerprint n put it on the credentials site.</p>


问:
Display big image from SD card in Android
In Android, how do you display an image (of any size) from the SD card, without getting an out of memory error?

Is it necessary to put the image in the Media Store first?

A pseudo-code example would be greatly appreciated. Extra points if the displayed image is as big as the memory level of the device allows.

答:
I'm displaying any sized images using code:</p>

```<code>ImageView imageView=new ImageView(this);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setAdjustViewBounds(true);
FileInputStream fis=new FileInputStream(file);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2; //try to decrease decoded image
options.inPurgeable=true; //if necessary purge pixels into disk
options.inScaled=true; //scale down image to actual device density
Bitmap bm=BitmapFactory.decodeStream(is, null, options);
imageView.setImageBitmap(bm);
fis.close();
</code>```

Body:
I'm displaying any sized images using code:

ImageView imageView=new ImageView(this);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setAdjustViewBounds(true);
FileInputStream fis=new FileInputStream(file);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2; //try to decrease decoded image
options.inPurgeable=true; //if necessary purge pixels into disk
options.inScaled=true; //scale down image to actual device density
Bitmap bm=BitmapFactory.decodeStream(is, null, options);
imageView.setImageBitmap(bm);
fis.close();


问:
Installing a CMake library: also ship find modules for the dependencies?
My CMake library, MyLibrary, has a dependency for OtherLibrary, that I import with a non-standard FindOtherLibrary.cmake.

My library depends on OtherLibrary publicly:

```<code>target_link_libraries(MyLibrary PUBLIC OtherLibrary::OtherLibrary)
</code>```

When I install MyLibrary (together with MyLibraryConfig.cmake), and users want to link against it, they therefore need to import OtherLibrary.

Is there a good practice regarding how to distribute FindOtherLibrary.cmake along MyLibrary?

Ideally, one could make things even easier for users of MyLibrary by importing OtherLibrary automatically from the installed config file MyLibraryConfig.cmake, if it contains something like

```<code>include(CMakeFindDependencyMacro)
find_dependency(OtherLibrary)
</code>```

and knows where FindOtherLibrary.cmake is.

Is this at all possible?

答:
"Transitive" behavior for module-mode find_package() is not supported.

In fact, I don't believe it is even possible since it requires modifying downstream CMake module path with information you would not have available to you. That's one of the reasons there is a config-mode find_package() (see here).

To be clear, a user of your library, which has a dependency on a FindModule library, has no choice but to know how to get a copy of the FindModule script and add it to their CMake module path. This is typically done through documentation. You as the author of a library that uses the FindModule cannot shortcut that process for the end user in any general way. So, there is no "good practice" for such a process.

Otherwise, good practice is to use FindModules only for non-CMake projects and use Config.cmake for CMake projects. If a dependent CMake library has no Config.cmake, you're out of luck (tell them they need it to support CMake in a Bug/Issue report).

Body:
My CMake library, MyLibrary, has a dependency for OtherLibrary, that I import with a non-standard FindOtherLibrary.cmake.

My library depends on OtherLibrary publicly:

target_link_libraries(MyLibrary PUBLIC OtherLibrary::OtherLibrary)

When I install MyLibrary (together with MyLibraryConfig.cmake), and users want to link against it, they therefore need to import OtherLibrary.

Is there a good practice regarding how to distribute FindOtherLibrary.cmake along MyLibrary?

Ideally, one could make things even easier for users of MyLibrary by importing OtherLibrary automatically from the installed config file MyLibraryConfig.cmake, if it contains something like

include(CMakeFindDependencyMacro)
find_dependency(OtherLibrary)

and knows where FindOtherLibrary.cmake is.

Is this at all possible?


问:
How to make a 1s second pause inside a forEach loop reading a firebase file?
I have the follow javascript function that reads data from firebase inside an each loop.

I am using it to plot the data in a google map trough its API.

I would like to know how to make a 1second pause between each round of the loop.

var markers = [];
var mapObject;
var z = 0;
var myLatLngA = [];

$(function() {
  firebase.database().ref('clicks').on('value', function(snapshot) {
    snapshot.forEach(function(item) {
      var objc = {
        lat: item.val().lat,
        lng: item.val().lng
      };
      myLatLngA.push(objc);
      //setMapOnAll(null);
      var marker = new google.maps.Marker({
        position: myLatLngA[z],
        map: mapObject
      });
      markers.push(marker);
      marker.setMap(mapObject);
      z++;
    });
  });
});
```

答:
I don't know if i get it very well, but you can use setTimeout() between every iteration of the forEach.

ES6 syntax

```<code>let  markers = [];let mapObject;let z = 0;let myLatLngA = [];

$(function() {
  firebase.database().ref('clicks').on('value', function(snapshot) {
    snapshot.forEach(function(item) {
      settimeout(()=>{
        var objc = {
          lat: item.val().lat,
          lng: item.val().lng
        };
        myLatLngA.push(objc);
        //setMapOnAll(null);
        var marker = new google.maps.Marker({
          position: myLatLngA[z],
          map: mapObject
        });
        markers.push(marker);
        marker.setMap(mapObject);
        z++;
      }, 1000);
    });
  });
});
</code>```

Body:
I don't know if i get it very well, but you can use setTimeout() between every iteration of the forEach.

ES6 syntax

let  markers = [];let mapObject;let z = 0;let myLatLngA = [];

$(function() {
  firebase.database().ref('clicks').on('value', function(snapshot) {
    snapshot.forEach(function(item) {
      settimeout(()=>{
        var objc = {
          lat: item.val().lat,
          lng: item.val().lng
        };
        myLatLngA.push(objc);
        //setMapOnAll(null);
        var marker = new google.maps.Marker({
          position: myLatLngA[z],
          map: mapObject
        });
        markers.push(marker);
        marker.setMap(mapObject);
        z++;
      }, 1000);
    });
  });
});


问:
How to skip rerendering a reactive component
I have a component with reactive properties.
I want the properties to be changed and want to know when its changing using any possible event but I don't want to rerender the DOM.

How can I achieve that?

答:
It's not entirely clear what you're trying to achieve, but here's one interpretation of what you're asking for. The component takes a prop for value and one to indicate whether it is paused. It has a data item to cache its value and a computed that will update that cached value to the prop value only when not paused; the computed always returns the cached value.

The upshot is that you can pause DOM updates on the component. When you unpause, it updates and stays updated.

new Vue({
  el: '#app',
  data: {
    value: 'red',
    paused: false
  },
  components: {
    cPausable: {
      template: '
{{proxyValue}}, {{paused}}
',
      data() {
        return {
          cachedValue: this.value
        }
      },
      props: {
        paused: {
          type: Boolean,
          default: false
        },
        value: {}
      },
      computed: {
        proxyValue() {
          if (!this.paused) {
            this.cachedValue = this.value;
          }
          return this.cachedValue;
        }
      }
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <input v-model="value">
  <input type="checkbox" v-model="paused">
  <c-pausable :value="value" :paused="paused"></c-pausable>
</div></code>```

Body:
It's not entirely clear what you're trying to achieve, but here's one interpretation of what you're asking for. The component takes a prop for value and one to indicate whether it is paused. It has a data item to cache its value and a computed that will update that cached value to the prop value only when not paused; the computed always returns the cached value.

The upshot is that you can pause DOM updates on the component. When you unpause, it updates and stays updated.

new Vue({
  el: '#app',
  data: {
    value: 'red',
    paused: false
  },
  components: {
    cPausable: {
      template: '<div>{{proxyValue}}, {{paused}}</div>',
      data() {
        return {
          cachedValue: this.value
        }
      },
      props: {
        paused: {
          type: Boolean,
          default: false
        },
        value: {}
      },
      computed: {
        proxyValue() {
          if (!this.paused) {
            this.cachedValue = this.value;
          }
          return this.cachedValue;
        }
      }
    }
  }
});

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <input v-model="value">
  <input type="checkbox" v-model="paused">
  <c-pausable :value="value" :paused="paused"></c-pausable>
</div>