问:
Please suggest the best way to design my database
I have a table named Pages and a table named Categories. Each entry of the table Pages is linked to the table Categories. The Categories table has 5 entries, they are: Car, Websites, Technology, Mobile Phones, and Interest.

So each time I put an entry to the Pages table, I need to map it to the Categories table so are arranged properly.

Here's my table:

Pages

```<code>id [PK]
name
url
</code>```

Categories

```<code>id [PK]
Categoryname
</code>```

Pages2Categories

```<code>Pages.id
Categories.id
</code>```

So my question is, is this the most efficient way to create this kind of relationships between tables? It seems very amateur

答:
One suggestion: Have 2 tables - "pages" and "category". Columns in pages are:

Name [varchar]
URL [varchar]
Category [tinyint]

For Category, as you designed:

catID [1|2|4|8|16] (5 possible values for 5 categories)
catName [varchar]

I assume you have a small # of categories (<8), if this count goes upto 31, use an integer instead (using 4 instead of 1 byte per row). Now Category in the pages table need not be an FK to the other table. You could do a logical OR for insert/update and AND for select in your jdbc code if an URL belongs to more than 1 category. May not be the best DB design, but this should minimize the db-Space you consume, in case you have to save millions of pages. From your problem statement, I do not see why you need a PK in the table... eliminate it to save a few more bytes in every row. Regards, - M.S.

Body:
I have a table named Pages and a table named Categories. Each entry of the table Pages is linked to the table Categories. The Categories table has 5 entries, they are: Car, Websites, Technology, Mobile Phones, and Interest.

So each time I put an entry to the Pages table, I need to map it to the Categories table so are arranged properly.

Here's my table:

Pages

id [PK]
name
url

Categories

id [PK]
Categoryname

Pages2Categories

Pages.id
Categories.id

So my question is, is this the most efficient way to create this kind of relationships between tables? It seems very amateur


来源: stackexchange

问:
Wait for promise to complete
I have read some posts regarding this subject but I have still not found the solution for this.

This my scenario:

I have a service: PermissionService, which looks like:

```<code>constructor(private http: HttpClient){}
hasPermission(operation: string, objects: string): Observable<Permission> {
    let queryStr: HttpParams = new HttpParams();
    queryStr = queryStr.set(“operation”,operation);
    queryStr = queryStr.set(“objects”,objects);
    return this.http.get<Permission>(this.url + permissionType, { params: queryStr });
}
</code>```

In my component I have injected the service and I use it like this:

```<code>hasCreatePermission(){
        this.permissionsService.hasPermission("C","Categories").subscribe(
          res => {
              this.canCreate = res.data[0].result;
          }, (err: HttpErrorResponse) => {
          if (err.error instanceof Error) {
              console.log('An error occurred:', err.error.message);
          } else {
            console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
    });
}
</code>```

When the promise finalizes the variable canCreate is set with the value of the permission.

This variable is used in my template to hide or show some component such as buttons.

All this stuff is working properly. So my question is.. is there any way in
Angular to make it synchronous?

To be able to call the method like:

This.canCreate = this.servicePermission.hasPermission…. I do not contiune the executing until the promise is resolved so I can get the result before the template is rendered.

I need this because I cannot display a page with buttons that are going to disappear after some seconds due to the permissions.

I agree that some calls to the backend such as getting data from the server need to be async but in this case I need the result to be able to render the page appropriately.

答:
Http requests return Obseravbles, in order to not block the browser. If you want to delay the loading of your component/template consider using Resolvers in Angular. They are specially made for this scenario.

More on resolvers and prefetching
https://angular.io/guide/router#resolve-pre-fetching-component-data

ContentLicense: CC BY-SA 3.0

Title: Wait for promise to complete

Body:
I have read some posts regarding this subject but I have still not found the solution for this.

This my scenario:

I have a service: PermissionService, which looks like:

constructor(private http: HttpClient){}
hasPermission(operation: string, objects: string): Observable<Permission> {
    let queryStr: HttpParams = new HttpParams();
    queryStr = queryStr.set(“operation”,operation);
    queryStr = queryStr.set(“objects”,objects);
    return this.http.get<Permission>(this.url + permissionType, { params: queryStr });
}

In my component I have injected the service and I use it like this:

hasCreatePermission(){
        this.permissionsService.hasPermission("C","Categories").subscribe(
          res => {
              this.canCreate = res.data[0].result;
          }, (err: HttpErrorResponse) => {
          if (err.error instanceof Error) {
              console.log('An error occurred:', err.error.message);
          } else {
            console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
    });
}

When the promise finalizes the variable canCreate is set with the value of the permission.

This variable is used in my template to hide or show some component such as buttons.

All this stuff is working properly. So my question is.. is there any way in
Angular to make it synchronous?

To be able to call the method like:

This.canCreate = this.servicePermission.hasPermission…. I do not contiune the executing until the promise is resolved so I can get the result before the template is rendered.

I need this because I cannot display a page with buttons that are going to disappear after some seconds due to the permissions.

I agree that some calls to the backend such as getting data from the server need to be async but in this case I need the result to be able to render the page appropriately.


问:
Scala matching high order function return value
Hello im trying to use case match with a high order function. if function return true do things same for false. Thank you.</p>

```<code>def funk(ls:List[Int],f:Int=>Boolean):List[Int]=
{
  f match
  {
    case true => do something
    case false => do somethingelse
  }
}
</code>```

答:
Looks like a good place to apply "andThen" for partial function:

Here is possibly what you need:

```<code>def funk(ls: List[Int], f: Int => Boolean): List[Int] = {
  val z = f.andThen(r => r match {
    case true => List(1, 2) // ..something
    case false => List(3, 4) // somethingElse
  })
   // function application
  z(5)
}
</code>```

Just dig a bit around PartialFunction's:

http://www.scala-lang.org/api/current/scala/PartialFunction.html

Body:
Hello im trying to use case match with a high order function. if function return true do things same for false. Thank you.

def funk(ls:List[Int],f:Int=>Boolean):List[Int]=
{
  f match
  {
    case true => do something
    case false => do somethingelse
  }
}

Body:
Looks like a good place to apply "andThen" for partial function:

Here is possibly what you need:

def funk(ls: List[Int], f: Int => Boolean): List[Int] = {
  val z = f.andThen(r => r match {
    case true => List(1, 2) // ..something
    case false => List(3, 4) // somethingElse
  })
   // function application
  z(5)
}

Just dig a bit around PartialFunction's:

http://www.scala-lang.org/api/current/scala/PartialFunction.html


问:
Simple question on how to format a number
my question is the following and I guess is really simple.
I have a number echoed with PHP. For example 37452.
I would like to have a dot and be displayed like 37.452

My var is $numposts

How is this possible ?
Thank you

答:
As The MYYN correctly mentions, you should check out the number_format function:

In your example, you could use it as such:

```<code>echo number_format($numposts, 3, ',', '.');
</code>```

ContentLicense: CC BY-SA 2.5

Body:
As The MYYN correctly mentions, you should check out the number_format function:

In your example, you could use it as such:

echo number_format($numposts, 3, ',', '.');


问:
How can I oscillate numbers in a list?
Question: How can I make these oscillate as such that the first digits or expression is + the next is - the one after is + and so on and so forth for the lists provided below (without using a specially made function for oscillation if one even exists).

I'm currently getting output as shown below:

```<code>    x + x^3/6 + x^5/120 + x^7/5040 + x^9/362880
1. {1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69,
73, 77, 81, 85, 89}
</code>```

Expected output:

```<code>x - x^3/6 + x^5/120 - x^7/5040 + x^9/362880
2. {1, -5, 9, -13, 17, -21, 25, -29, 33, -37, 41, -45, 49, -53, 57, -61, 65, -69, 73, -77, 81, -85, 89}

Sum[x^j/Factorial[j], {j, 1, 9, 2}];
myOsc = Table[i, {i, 1, 89, 4}];
</code>```

Title: How can I oscillate numbers in a list?

Body:
Question: How can I make these oscillate as such that the first digits or expression is + the next is - the one after is + and so on and so forth for the lists provided below (without using a specially made function for oscillation if one even exists).

I'm currently getting output as shown below:

    x + x^3/6 + x^5/120 + x^7/5040 + x^9/362880
1. {1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69,
73, 77, 81, 85, 89}

Expected output:

x - x^3/6 + x^5/120 - x^7/5040 + x^9/362880
2. {1, -5, 9, -13, 17, -21, 25, -29, 33, -37, 41, -45, 49, -53, 57, -61, 65, -69, 73, -77, 81, -85, 89}

Sum[x^j/Factorial[j], {j, 1, 9, 2}];
myOsc = Table[i, {i, 1, 89, 4}];

Body:
Sum[If[OddQ[(j - 1)/2], -x^j, x^j]/Factorial[j], {j, 1, 9, 2}]

x - x^3/6 + x^5/120 - x^7/5040 + x^9/362880

myOsc = Table[If[OddQ[(i - 1)/4], -i, i], {i, 1, 89, 4}]

{1, -5, 9, -13, 17, -21, 25, -29, 33, -37, 41, -45, 49, -53, 57, -61, 65, -69, 73, -77, 81, -85, 89}


问:
Junit Matcher for comparators?
For several days I am using now Junit's Matchers feature. Everything is working OK but I am looking for a matcher which uses a comparator for comparing and which does not rely on the objects equals methodes.

I want to replace

```<code>Assert.assertThat(one, CoreMatchers.equalTo(two)
</code>```

with something like (pseudocode)

```<code>Assert.assertThat(eins, CoreMatchers.equalTo(operand, new MyComparator())
</code>```

Do you know whether there exists an easy out of the box solution? I did not find one in google and do not want to write one.

答:
Another one option is using AspectJ framework custom comparison strategy for object and iterables.

```<code>assertThat(frodo).usingComparator(raceComparator).isEqualTo(sam);
assertThat(fellowshipOfTheRing).usingElementComparator(raceComparator).contains(sauron);
</code>```

It has also Field by field comparisons, e.g. isEqualToComparingOnlyGivenFields and isEqualToIgnoringGivenFields comparators.

```<code>assertThat(frodo).isEqualToComparingOnlyGivenFields(sam, "race.name");
assertThat(frodo).isEqualToIgnoringGivenFields(sam, "name", "age");
</code>```

So, in most case, you can handle assertion without custom comparison strategy

Title: Junit Matcher for comparators?

Body:
For several days I am using now Junit's Matchers feature. Everything is working OK but I am looking for a matcher which uses a comparator for comparing and which does not rely on the objects equals methodes.

I want to replace

Assert.assertThat(one, CoreMatchers.equalTo(two)

with something like (pseudocode)

Assert.assertThat(eins, CoreMatchers.equalTo(operand, new MyComparator())

Do you know whether there exists an easy out of the box solution? I did not find one in google and do not want to write one.

Body:
Another one option is using AspectJ framework custom comparison strategy for object and iterables.

assertThat(frodo).usingComparator(raceComparator).isEqualTo(sam);
assertThat(fellowshipOfTheRing).usingElementComparator(raceComparator).contains(sauron);

It has also Field by field comparisons, e.g. isEqualToComparingOnlyGivenFields and isEqualToIgnoringGivenFields comparators.

assertThat(frodo).isEqualToComparingOnlyGivenFields(sam, "race.name");
assertThat(frodo).isEqualToIgnoringGivenFields(sam, "name", "age");

So, in most case, you can handle assertion without custom comparison strategy


问:
Trouble with getting an instance of a room-Database
I unfortunately have big issues with getting an instance of a Room-Database for my android project. I followed the instructions on https://developer.android.com/training/data-storage/room/index.html
But the last step won't work for me:

```<code>AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name").build();
</code>```

Their AppDatabase.java looks like this

```<code>@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
</code>```

My Problem: At "AppDatabase db" I get the error 'cannot resolve symbol "AppDatabase" '. This is quite senseful, because AppDatabase is just an abstract class. But how is this supposed to work in the tutorial?
I tried to get the instance in the onCreate method of my MainActivity.
Here are my gradlefiles:
    buildscript {

```<code>    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
       // NOTE: Do not place your application dependencies here; they belong
      // in the individual module build.gradle files
    }
}

ext {
    buildToolsVersion = "25.0.2"
    supportLibVersion = "25.3.1"
    archRoomVersion = "1.0.0-alpha1"
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

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

and the second one:

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.fabian.kohlmannkonstruktionen"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
compile 'android.arch.persistence.room:runtime:' +
rootProject.archRoomVersion
annotationProcessor 'android.arch.persistence.room:compiler:' +
rootProject.archRoomVersion

}
</code>```

MainActivity.java

```<code>package com.example.fabian.kohlmannkonstruktionen;

import android.app.AlertDialog;
import android.content.DialogInterface;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.content.Context;

public class MainActivity extends AppCompatActivity {

AppDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = AppDatabase.getInMemoryDatabase(getApplicationContext());
}
...
</code>```

AppDatabase.java

```<code>package com.example.fabian.kohlmannkonstruktionen;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.content.Context;

public class MainActivity extends AppCompatActivity {
    AppDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = AppDatabase.getInMemoryDatabase(getApplicationContext());
}
</code>```

Projekt.java

```<code>import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;

/**
 * Created by Fabian on 14.11.2017.
 */
@Entity
public class Projekt {
    @PrimaryKey(autoGenerate = true)
    Integer id;

    Integer projektnummer;
    Integer lohn,arbeitszeit;
    String projektname, firma;
    Boolean abgeschlossen;
    public Projekt(String projektname,String firma,Integer projektnummer){
        this.abgeschlossen=false;
        this.projektname=projektname;
        this.projektnummer=projektnummer;
        this.firma=firma;
    }
...getters and setters...
</code>```

ProjektDao.java

```<code>import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;

import java.util.List;

/**
 * Created by Fabian on 15.11.2017.
 */
@Dao
public interface ProjektDao {
    @Query("SELECT * FROM Projekt")
    List<Projekt> getAll();

    @Query("SELECT * FROM Projekt where id LIKE  :id")
    Projekt findByID(String id);

    @Query("SELECT COUNT(*) from Projekt")
    int countUsers();

    @Insert
    void insertAll(Projekt... projekts);

    @Delete
    void delete(Projekt projekt);
}
</code>```

Termin and TerminDao looks the same

This is the text from the gradle console:

```<code>Executing tasks: [assemble]

Configuration on demand is an incubating feature.
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.
:app:compileDebugJavaWithJavac
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\TerminDao.java:14: warning: The query returns some columns [pausenzeit, startzeit, endzeit, lohnproh, mitarbeiter, standort] which are not use by Projekt. You can use @ColumnInfo annotation on the fields to specify the mapping. Projekt has some fields [projektnummer, lohn, arbeitszeit, projektname, firma, abgeschlossen] which are not returned by the query. If they are not supposed to be read from the result, you can mark them with @Ignore annotation. You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: id, pausenzeit, startzeit, endzeit, lohnproh, mitarbeiter, standort. Fields in Projekt: id, projektnummer, lohn, arbeitszeit, projektname, firma, abgeschlossen.
    List<Projekt> getAll();
                  ^
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\AppDatabase.java:13: warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide `room.schemaLocation` annotation processor argument OR set exportSchema to false.
public abstract class AppDatabase extends RoomDatabase {
                ^
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\com\example\fabian\kohlmannkonstruktionen\MainActivity.java:13: error: cannot find symbol
    AppDatabase db = AppDatabase.getInMemoryDatabase(getApplicationContext());
    ^
  symbol:   class AppDatabase
  location: class MainActivity
1 error
2 warnings

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 5s

14 actionable tasks: 1 executed, 13 up-to-date
</code>```

答:
My AppDatabase.class is a little bit different to yours:

```<code>...
INSTANCE = Room.databaseBuilder(context, AppDatabase.class, "xxx")
                    // To simplify the codelab, allow queries on the main thread.
                    // Don't do this on a real app! See PersistenceBasicSample for an example.
                    .allowMainThreadQueries()
                    .build();
...
</code>```

And my build.gradle also includes lifecycle:

```<code>// for room
compile 'android.arch.lifecycle:extensions:1.0.0';
compile 'android.arch.persistence.room:runtime:1.0.0';
annotationProcessor 'android.arch.lifecycle:compiler:1.0.0';
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0';
</code>```

Body:
I unfortunately have big issues with getting an instance of a Room-Database for my android project. I followed the instructions on https://developer.android.com/training/data-storage/room/index.html
But the last step won't work for me:

AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name").build();

Their AppDatabase.java looks like this

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}

My Problem: At "AppDatabase db" I get the error 'cannot resolve symbol "AppDatabase" '. This is quite senseful, because AppDatabase is just an abstract class. But how is this supposed to work in the tutorial?
I tried to get the instance in the onCreate method of my MainActivity.
Here are my gradlefiles:
    buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
       // NOTE: Do not place your application dependencies here; they belong
      // in the individual module build.gradle files
    }
}

ext {
    buildToolsVersion = "25.0.2"
    supportLibVersion = "25.3.1"
    archRoomVersion = "1.0.0-alpha1"
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

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

and the second one:

apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.fabian.kohlmannkonstruktionen"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
compile 'android.arch.persistence.room:runtime:' +
rootProject.archRoomVersion
annotationProcessor 'android.arch.persistence.room:compiler:' +
rootProject.archRoomVersion

}

MainActivity.java

package com.example.fabian.kohlmannkonstruktionen;

import android.app.AlertDialog;
import android.content.DialogInterface;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.content.Context;

public class MainActivity extends AppCompatActivity {

AppDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = AppDatabase.getInMemoryDatabase(getApplicationContext());
}
...

AppDatabase.java

package com.example.fabian.kohlmannkonstruktionen;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.content.Context;

public class MainActivity extends AppCompatActivity {
    AppDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = AppDatabase.getInMemoryDatabase(getApplicationContext());
}

Projekt.java

import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;

/**
 * Created by Fabian on 14.11.2017.
 */
@Entity
public class Projekt {
    @PrimaryKey(autoGenerate = true)
    Integer id;

    Integer projektnummer;
    Integer lohn,arbeitszeit;
    String projektname, firma;
    Boolean abgeschlossen;
    public Projekt(String projektname,String firma,Integer projektnummer){
        this.abgeschlossen=false;
        this.projektname=projektname;
        this.projektnummer=projektnummer;
        this.firma=firma;
    }
...getters and setters...

ProjektDao.java

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;

import java.util.List;

/**
 * Created by Fabian on 15.11.2017.
 */
@Dao
public interface ProjektDao {
    @Query("SELECT * FROM Projekt")
    List<Projekt> getAll();

    @Query("SELECT * FROM Projekt where id LIKE  :id")
    Projekt findByID(String id);

    @Query("SELECT COUNT(*) from Projekt")
    int countUsers();

    @Insert
    void insertAll(Projekt... projekts);

    @Delete
    void delete(Projekt projekt);
}

Termin and TerminDao looks the same

This is the text from the gradle console:

Executing tasks: [assemble]

Configuration on demand is an incubating feature.
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.
:app:compileDebugJavaWithJavac
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\TerminDao.java:14: warning: The query returns some columns [pausenzeit, startzeit, endzeit, lohnproh, mitarbeiter, standort] which are not use by Projekt. You can use @ColumnInfo annotation on the fields to specify the mapping. Projekt has some fields [projektnummer, lohn, arbeitszeit, projektname, firma, abgeschlossen] which are not returned by the query. If they are not supposed to be read from the result, you can mark them with @Ignore annotation. You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: id, pausenzeit, startzeit, endzeit, lohnproh, mitarbeiter, standort. Fields in Projekt: id, projektnummer, lohn, arbeitszeit, projektname, firma, abgeschlossen.
    List<Projekt> getAll();
                  ^
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\AppDatabase.java:13: warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide `room.schemaLocation` annotation processor argument OR set exportSchema to false.
public abstract class AppDatabase extends RoomDatabase {
                ^
C:\Users\Fabian\AndroidStudioProjects\KohlmannKonstruktionen\app\src\main\java\com\example\fabian\kohlmannkonstruktionen\MainActivity.java:13: error: cannot find symbol
    AppDatabase db = AppDatabase.getInMemoryDatabase(getApplicationContext());
    ^
  symbol:   class AppDatabase
  location: class MainActivity
1 error
2 warnings

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 5s

14 actionable tasks: 1 executed, 13 up-to-date

Body:
My AppDatabase.class is a little bit different to yours:

...
INSTANCE = Room.databaseBuilder(context, AppDatabase.class, "xxx")
                    // To simplify the codelab, allow queries on the main thread.
                    // Don't do this on a real app! See PersistenceBasicSample for an example.
                    .allowMainThreadQueries()
                    .build();
...

And my build.gradle also includes lifecycle:

// for room
compile 'android.arch.lifecycle:extensions:1.0.0';
compile 'android.arch.persistence.room:runtime:1.0.0';
annotationProcessor 'android.arch.lifecycle:compiler:1.0.0';
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0';


问:
Cloud Functions for Firebase: log user in with email and password (server side)
I want to let the user log in by REST. My application sends me an emailaddress and a password, and I want Firebase to check whether that's a valid credential combination. Then a JWT is send back to the client to verify all requests.

However, the Firebase Admin SDK seems not to have a function like admin.auth.loginWithEmailAndPassword() or something. How can I log the user in completely server side?

The server is running on Cloud Functions for Firebase.

答: The normal approach for this would be to let the client validate the email/password and then send the resulting token to your server. That way the server can validate the token, instead of having to validate the credentials.</p>


问:
Bluetooth Thermal printer print half String
Please help me, I waste my whole day but could not figure out Why my Thermal Printer print half text in receipt. It's work perfectly in 58mm Mini Bluetooth Thermal Printer. But when I come in Thermal Printer LESHP 80mm Wireless Bluetooth Thermal this printer only print half text in receipt.

Here my code:

```<code>void findBT() {

    try {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null) {

        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {

                if (device.getName().contains("Printer")) {

                    mmDevice = device;

                }
            }

        }
        else {
            Toast.makeText(this,"device not pair.",Toast.LENGTH_LONG).show();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
 void SendDateBT() throws IOException {
    try {

        // Standard SerialPortService ID
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();
        mmOutputStream.write(mytext.getBytes());

        mmOutputStream.flush();
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

I call this two function when I want to print receipt :

```<code>findBT();
SendDatBt();
</code>```

答:
I have try this after lot of searching and its work for me. </p>

```<code>mmOutputStream.write(Mytext.getBytes(Charset.forName("UTF-8")));
</code>```

Body:
Please help me, I waste my whole day but could not figure out Why my Thermal Printer print half text in receipt. It's work perfectly in 58mm Mini Bluetooth Thermal Printer. But when I come in Thermal Printer LESHP 80mm Wireless Bluetooth Thermal this printer only print half text in receipt.

Here my code:

void findBT() {

    try {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null) {

        }

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {

                if (device.getName().contains("Printer")) {

                    mmDevice = device;

                }
            }

        }
        else {
            Toast.makeText(this,"device not pair.",Toast.LENGTH_LONG).show();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
 void SendDateBT() throws IOException {
    try {

        // Standard SerialPortService ID
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();
        mmOutputStream.write(mytext.getBytes());

        mmOutputStream.flush();
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

I call this two function when I want to print receipt :

findBT();
SendDatBt();

Body:
I have try this after lot of searching and its work for me.

mmOutputStream.write(Mytext.getBytes(Charset.forName("UTF-8")));


问:
What is this syntax: "Component.For<IOutput>()"?
I'm finding code examples all over the place in IoC and DI discussions that use < and > in their syntax, usually at the end of what looks like a method call.

Can someone

Tell me what language this is, and

Explain this syntax enough to help me understand the code examples, so I can make sure I understand the underlying principles.

答:
1.) The language looks like C#, but without reference/context I can't be 100% sure.

2.) Assuming C#, this syntax is used with generics.


问:
Show different views as a slideshow in ASP.NET MVC
I am working on a health and monitoring dashboard with several views and want to show all views one by one as a slide show periodically.

```<code><iframe src="http://jquery.com/" id="myFrame" width="500" marginwidth="0" height="500" marginheight="0" align="middle" scrolling="auto"></iframe>

    <script>
    setInterval(test, 10000);

    function test(){
    //setTimeout(loadPage1, 2000);

     setTimeout(loadPage2, 2000);

     setTimeout(loadPage3, 2000);
     }

        function loadPage1(){
            var loc = "http://www.w3schools.com/";
            document.getElementById('myFrame').setAttribute('src', loc);
        }

        function loadPage2(){
            var loc = "https://internalapplication/Controller/ActionName1";
            document.getElementById('myFrame').setAttribute('src', loc);
        }

        function loadPage3(){
            var loc = "https://internalapplication/Controller/ActionName2";
            document.getElementById('myFrame').setAttribute('src', loc);
        }

    </script>
</code>```

http://jsfiddle.net/35s3m6ru/2/

I am getting below error.

"Refused to display 'https://internalapplication/Controller/ActionName1' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'".

Any help or advise will be highly appreciated.

Edit: updated code with relative URLS

http://jsfiddle.net/35s3m6ru/6/

答:
Add the following method to your Global.asax.cs file

```<code>   protected void Application_PreSendRequestHeaders()
     {
     Response.Headers.Remove("X-Frame-Options");
     Response.AddHeader("X-Frame-Options", "AllowAll");
     }
</code>```

This should solve the issue.

Body:
I am working on a health and monitoring dashboard with several views and want to show all views one by one as a slide show periodically.

http://jsfiddle.net/35s3m6ru/2/

I am getting below error.

"Refused to display 'https://internalapplication/Controller/ActionName1' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'".

Any help or advise will be highly appreciated.

Edit: updated code with relative URLS

http://jsfiddle.net/35s3m6ru/6/

Body:
Add the following method to your Global.asax.cs file

   protected void Application_PreSendRequestHeaders()
     {
     Response.Headers.Remove("X-Frame-Options");
     Response.AddHeader("X-Frame-Options", "AllowAll");
     }

This should solve the issue.


问:
Knockout css data-bind doesn't apply class
So I'm having a very, very strange issue, so here's a code snippet where the problem is happening:

Basically what is going wrong is that it does not add the modified class. At all. Strangely, when I added a text binding, like modified:true, text: 'testatest', it does apply it.

What is going on? I'm not even close to a web developer expert, but I even asked my two senior project leads and they can't figure it out.

答:
There's another reason why a class might not be applied I ran into: It gets overridden by a subsequent css-declaration:

```<code><td class="editable ageCell" data-source="Age" data-bind="css: {'modified': true}, css: unrelatedcssclass"></td>
</code>```

In this case 'modified' will never appear, but 'unrelatedcssclass' will.
To fix that, merge both declarations to

```<code><td class="editable ageCell" data-source="Age" data-bind="css: {'modified': true, 'unrelatedcssclass' : true}"></td>
</code>```

Body:
There's another reason why a class might not be applied I ran into: It gets overridden by a subsequent css-declaration:

<td class="editable ageCell" data-source="Age" data-bind="css: {'modified': true}, css: unrelatedcssclass"></td>

In this case 'modified' will never appear, but 'unrelatedcssclass' will.
To fix that, merge both declarations to

<td class="editable ageCell" data-source="Age" data-bind="css: {'modified': true, 'unrelatedcssclass' : true}"></td>


问:
Angular Tutorial: Tour of Heroes lesson 2: data binding to hero from selectedHero
In Angular tutorial lesson 2 on https://embed.plnkr.co/?show=preview

I can see in HeroComponent template, [(ngModel)] is 2-way binding the selectedHero.name as the input value changes. How come it's binding and changing {{hero.name}} 1-way interpolation on the heroes list above at the same time? Should have made sense if it was {{selectedHero.name}} interpolation on the list, right?

Can someone please explain to me what basic logic I'm missing out?

Thanks in advance.

答:
if i understand your question:
onSelect(hero: Hero): void {
  this.selectedHero = hero;
}

with this instruction the hero: Hero is a pointer to the Element of type Hero.

this.selectedHero = hero is giving the same pointer to selectedHero, so they are 2 pointers to the same obj. This is why on the change of value they are changing both.


问:
Azure AD B2C Register users after validating an Invitation Token
Using Azure AD B2C I create a SignUp Policy that users can use to register in my Tenant Directory.

After creating the SignUp Policy in Azure AD B2C, I get an endpoint which is used to register users. The endpoint looks like this:

https://login.microsoftonline.com/tenantname.onmicrosoft.com/oauth2/v2.0/authorize?p=XXX&client_id=XXX&nonce=defaultNonce&redirect_uri=XXX&scope=openid&response_type=id_token&prompt=login

I programatically send an email to an email address, which contains the endpoint from above and an InvitationToken. The endpoint will be opened from the email, the user will register, and at the final step he will be asked to enter the InvitationToken that he received in the email.

I want to perform a validation at this step. I want to check if the InvitationToken entered by the user is the same as the one he received in the email. If the InvitationToken he enters is invalid, I don't want the user to be able to register in my Tenant Directory.

I don't know how to perform this. I can only implement a workaround.

I store in a table the users with the InvitationToken that they received in the email and the InvitationToken that they entered at the Register step. If the 2 InvitationTokens are different, then users will not be able to use my application. But the users are still created in the Azure Portal, and they can login in the Portal.

Is there any way to make the users unable to register in my Tenant Directory if they enter an invalid InvitationToken at the register step?

答:
You have two options:

Send input claims to your sign-up policy.  See this SO answer for more details.

Validate the InvitationToken provided by the user.  See this guide: Integrate REST API claims exchanges in your Azure AD B2C user journey as validation on user input

Both options require custom policies though*.

*Custom policies are designed primarily for identity pros who need to address complex scenarios.

There is an existing feature request for this: AADB2C: Send email invitation for new user to sign up


问:
section_id: nil WHEN IT SHOULD BE section_id: 1
I'm following a LYNDA.COM tutorial with Kevin Skoglund. I was following along in the "Many-to-many" associations: Rich" video when I had a problem. The last line I ran (section.section_edits)
resulted in the following:

```<code>SectionEdit id: 6, admin_user_id: 1, section_id: nil,  ...
</code>```

However Kevin's result on the tutorial was:

```<code>SectionEdit id: 1, admin_user_id: 1, section_id: 1,  ...
</code>```

Obviously I have went back several times to try to find my error which is why my SectionEdit id: is different from his. BUT MY QUESTION IS: why is my section_id: nil

EDIT: 09/25/16

I entered section.errors in my command prompts but don't fully understand the console response. @AlterLagos

irb(main):004:0> section = Section.create(:name => "Section One", :position => 1)
   (0.5ms)  BEGIN
   (1.0ms)  ROLLBACK
=> #

irb(main):005:0> section.errors
=> #<ActiveModel::Errors:0x6340fe0 @base=#
, @messages={:page=>["must exist"]}, @details={:page=>[{:error=>:blank}]}>

Below is my consol and associated classes. THANKS!

MY COMMAND PROMPT

```<code>C:\Users\David\My Documents\sites\simple_cms>rails console
Loading development environment (Rails 5.0.0.1)

irb(main):001:0> me = AdminUser.find(1)
  AdminUser Load (4.0ms)  SELECT  `admin_users`.* FROM `admin_users` WHERE`admin_users`.`id` = 1 LIMIT 1
=> #<AdminUser id: 1, first_name: "David", last_name: "Boyette", email: "", hashed_password: nil, created_at: "2016-09-08 02:52:57", updated_at: "2016-09-08 02:52:57", username: "dboyette", salt: nil>

irb(main):002:0> me.section_edits
  SectionEdit Load (3.5ms)  SELECT `section_edits`.* FROM `section_edits` WHERE `section_edits`.`admin_user_id` = 1
=> #<ActiveRecord::Associations::CollectionProxy [#<SectionEdit id: 1, admin_user_id: 1, section_id: nil, summary: "Test edit", created_at: "2016-09-09 01:19:08", updated_at: "2016-09-09 01:19:08">, #<SectionEdit id: 2, admin_user_id: 1, section_id: nil, summary: "Test edit", created_at: "2016-09-10 00:05:56", updated_at: "2016-09-10 00:05:56">, #<SectionEdit id: 3, admin_user_id: 1, section_id: nil, summary: "Ch-ch-ch-changes", created_at: "2016-09-10 00:09:39", updated_at: "2016-09-10 00:09:39">, #<SectionEdit id: 4, admin_user_id: 1, section_id: nil, summary: "Test edit", created_at: "2016-09-17 03:32:13", updated_at: "2016-09-17 03:32:13">, #<SectionEdit id: 5, admin_user_id: 1, section_id: nil, summary: "Test edit", created_at: "2016-09-18 00:48:40", updated_at: "2016-09-18 00:48:40">]>

irb(main):003:0> section = Section.create(:name => "Section One", :position => 1)
   (1.0ms)  BEGIN
   (1.0ms)  ROLLBACK
=> #<Section id: nil, page_id: nil, name: "Section One", position: 1, visible: false, content_type: nil, content: nil, created_at: nil, updated_at: nil>

irb(main):004:0> section.section_edits => #<ActiveRecord::Associations::CollectionProxy []>

irb(main):005:0> edit = SectionEdit.new
=> #<SectionEdit id: nil, admin_user_id: nil, section_id: nil, summary: nil, created_at: nil, updated_at: nil>

irb(main):006:0> edit.summary = "Test edit"
=> "Test edit"

irb(main):007:0> section.section_edits << edit
=> #<ActiveRecord::Associations::CollectionProxy [#<SectionEdit id: nil, admin_user_id: nil, section_id: nil, summary: "Test edit", created_at: nil, updated_at: nil>]>

irb(main):008:0> edit.editor = me
=> #<AdminUser id: 1, first_name: "David", last_name: "Boyette", email: "", hashed_password: nil, created_at: "2016-09-08 02:52:57", updated_at: "2016-09-08 02:52:57", username: "dboyette", salt: nil>

irb(main):009:0> edit.save
   (1.5ms)  BEGIN
  SQL (3.0ms)  INSERT INTO `section_edits` (`admin_user_id`, `summary`, `created_at`, `updated_at`) VALUES (1, 'Test edit', '2016-09-18 01:44:41', '2016-09-18 01:44:41')
   (69.3ms)  COMMIT
=> true

irb(main):010:0> section.section_edits
=> #<ActiveRecord::Associations::CollectionProxy [#<SectionEdit id: 6, admin_user_id: 1, section_id: nil, summary: "Test edit", created_at: "2016-09-18 01:44:41", updated_at: "2016-09-18 01:44:41">]>

irb(main):011:0>
</code>```

section.rb

```<code>class Section < ApplicationRecord

belongs_to :page
has_many :section_edits
has_many :editors, :through => :section_edits, :class_name => "AdminUser"
</code>```

end

Sections Migration

```<code>class CreateSections < ActiveRecord::Migration[5.0]
</code>```

def change
    create_table :sections do |t|

```<code>  t.integer "page_id"
  # same as t.reference :page
  t.string "name"
  t.integer "position"
  t.boolean "visible", :default => false
  t.string "content_type"
  t.text "content"
  t.timestamps

end

add_index("sections", "page_id")
</code>```

end
end

section_edit.rb

```<code>class SectionEdit < ApplicationRecord

belongs_to :editor, :class_name => "AdminUser", :foreign_key => 'admin_user_id'
belongs_to :section
</code>```

end

section_edits migration

```<code>class CreateSectionEdits < ActiveRecord::Migration[5.0]
</code>```

def change
    create_table :section_edits do |t|

```<code>t.references :admin_user
t.references :section
t.string "summary"
t.timestamps

end
add_index :section_edits, ['admin_user_id', 'section_id']
</code>```

end
end

Model: page.rb

`class Page < ApplicationRecord

```<code>belongs_to :subject
has_many :sections
has_and_belongs_to_many :editors, :class_name => "AdminUser"
</code>```

end
`

Controller: Pages

class PagesController < ApplicationController
end

Migration: Page

`class CreatePages < ActiveRecord::Migration[5.0]
  def change
    create_table :pages do |t|

```<code>  t.integer "subject_id"
  # same as t.references :subject
  t.string "name"
  t.string "permalink"
  t.integer "position"
  t.boolean "visible", :default => false
  t.timestamps

end
add_index("pages", "subject_id")
add_index("pages", "permalink")
</code>```

end
end`

答:
In section.rb file -
make it
belongs_to :page, {:optional => true}

then in rails console run-
section = Section.create(:name => "Section One", :position => 1)

Cheers

Body:
I'm following a LYNDA.COM tutorial with Kevin Skoglund. I was following along in the "Many-to-many" associations: Rich" video when I had a problem. The last line I ran (section.section_edits)
resulted in the following:

SectionEdit id: 6, admin_user_id: 1, section_id: nil,  ...

However Kevin's result on the tutorial was:

SectionEdit id: 1, admin_user_id: 1, section_id: 1,  ...

Obviously I have went back several times to try to find my error which is why my SectionEdit id: is different from his. BUT MY QUESTION IS: why is my section_id: nil

EDIT: 09/25/16

I entered section.errors in my command prompts but don't fully understand the console response. @AlterLagos

irb(main):004:0> section = Section.create(:name => "Section One", :position => 1)
   (0.5ms)  BEGIN
   (1.0ms)  ROLLBACK
=> #

irb(main):005:0> section.errors
=> #<ActiveModel::Errors:0x6340fe0 @base=#
, @messages={:page=>["must exist"]}, @details={:page=>[{:error=>:blank}]}>

Below is my consol and associated classes. THANKS!

MY COMMAND PROMPT

C:\Users\David\My Documents\sites\simple_cms>rails console
Loading development environment (Rails 5.0.0.1)

irb(main):001:0> me = AdminUser.find(1)
  AdminUser Load (4.0ms)  SELECT  `admin_users`.* FROM `admin_users` WHERE`admin_users`.`id` = 1 LIMIT 1
=> #<AdminUser id: 1, first_name: "David", last_name: "Boyette", email: "", hashed_password: nil, created_at: "2016-09-08 02:52:57", updated_at: "2016-09-08 02:52:57", username: "dboyette", salt: nil>

irb(main):002:0> me.section_edits
  SectionEdit Load (3.5ms)  SELECT `section_edits`.* FROM `section_edits` WHERE `section_edits`.`admin_user_id` = 1
=> #<ActiveRecord::Associations::CollectionProxy [#<SectionEdit id: 1, admin_user_id: 1, section_id: nil, summary: "Test edit", created_at: "2016-09-09 01:19:08", updated_at: "2016-09-09 01:19:08">, #<SectionEdit id: 2, admin_user_id: 1, section_id: nil, summary: "Test edit", created_at: "2016-09-10 00:05:56", updated_at: "2016-09-10 00:05:56">, #<SectionEdit id: 3, admin_user_id: 1, section_id: nil, summary: "Ch-ch-ch-changes", created_at: "2016-09-10 00:09:39", updated_at: "2016-09-10 00:09:39">, #<SectionEdit id: 4, admin_user_id: 1, section_id: nil, summary: "Test edit", created_at: "2016-09-17 03:32:13", updated_at: "2016-09-17 03:32:13">, #<SectionEdit id: 5, admin_user_id: 1, section_id: nil, summary: "Test edit", created_at: "2016-09-18 00:48:40", updated_at: "2016-09-18 00:48:40">]>

irb(main):003:0> section = Section.create(:name => "Section One", :position => 1)
   (1.0ms)  BEGIN
   (1.0ms)  ROLLBACK
=> #

irb(main):004:0> section.section_edits => #<ActiveRecord::Associations::CollectionProxy []>

irb(main):005:0> edit = SectionEdit.new
=> #<SectionEdit id: nil, admin_user_id: nil, section_id: nil, summary: nil, created_at: nil, updated_at: nil>

irb(main):006:0> edit.summary = "Test edit"
=> "Test edit"

irb(main):007:0> section.section_edits << edit
=> #<ActiveRecord::Associations::CollectionProxy [#<SectionEdit id: nil, admin_user_id: nil, section_id: nil, summary: "Test edit", created_at: nil, updated_at: nil>]>

irb(main):008:0> edit.editor = me
=> #<AdminUser id: 1, first_name: "David", last_name: "Boyette", email: "", hashed_password: nil, created_at: "2016-09-08 02:52:57", updated_at: "2016-09-08 02:52:57", username: "dboyette", salt: nil>

irb(main):009:0> edit.save
   (1.5ms)  BEGIN
  SQL (3.0ms)  INSERT INTO `section_edits` (`admin_user_id`, `summary`, `created_at`, `updated_at`) VALUES (1, 'Test edit', '2016-09-18 01:44:41', '2016-09-18 01:44:41')
   (69.3ms)  COMMIT
=> true

irb(main):010:0> section.section_edits
=> #<ActiveRecord::Associations::CollectionProxy [#<SectionEdit id: 6, admin_user_id: 1, section_id: nil, summary: "Test edit", created_at: "2016-09-18 01:44:41", updated_at: "2016-09-18 01:44:41">]>

irb(main):011:0>

section.rb

class Section < ApplicationRecord

belongs_to :page
has_many :section_edits
has_many :editors, :through => :section_edits, :class_name => "AdminUser"

end

Sections Migration

class CreateSections < ActiveRecord::Migration[5.0]

def change
    create_table :sections do |t|

  t.integer "page_id"
  # same as t.reference :page
  t.string "name"
  t.integer "position"
  t.boolean "visible", :default => false
  t.string "content_type"
  t.text "content"
  t.timestamps

end

add_index("sections", "page_id")

end
end

section_edit.rb

class SectionEdit < ApplicationRecord

belongs_to :editor, :class_name => "AdminUser", :foreign_key => 'admin_user_id'
belongs_to :section

end

section_edits migration

class CreateSectionEdits < ActiveRecord::Migration[5.0]

def change
    create_table :section_edits do |t|

t.references :admin_user
t.references :section
t.string "summary"
t.timestamps

end
add_index :section_edits, ['admin_user_id', 'section_id']

end
end

Model: page.rb

`class Page < ApplicationRecord

belongs_to :subject
has_many :sections
has_and_belongs_to_many :editors, :class_name => "AdminUser"

end
`

Controller: Pages

class PagesController < ApplicationController
end

Migration: Page

`class CreatePages < ActiveRecord::Migration[5.0]
  def change
    create_table :pages do |t|

  t.integer "subject_id"
  # same as t.references :subject
  t.string "name"
  t.string "permalink"
  t.integer "position"
  t.boolean "visible", :default => false
  t.timestamps

end
add_index("pages", "subject_id")
add_index("pages", "permalink")

end
end`


问:
How to get Index of an Item in ICollection<T>
I have this list of cars

```<code>ICollection<Cars> Cars
</code>```

and I also have a single car object, which I know is in the ICollection how do I get the index/position of the car in the list? I need to add it to a list of strings

This is what I have so far:

```<code>var index = cars.Where(b=> b.Id == car.id).Single().iWantTheIndex
stringList.Add(index)
</code>```

Any ideas?

答:
If you want to use an indexed collection then you should use IList<T>, not ICollection<T>.  An ICollection<T> is something that you can enumerate, add and remove items for, and get the count of, that's all.  An IList<T> is a collection in which the items are in a specified order, and can be accessed based on their position in the list.

Because an ICollection<T> doesn't necessarily represent an ordered collection, you cannot get a meaningful "index" of an item.  Items don't necessarily have a position.

Body:
I have this list of cars

ICollection<Cars> Cars

and I also have a single car object, which I know is in the ICollection how do I get the index/position of the car in the list? I need to add it to a list of strings

This is what I have so far:

var index = cars.Where(b=> b.Id == car.id).Single().iWantTheIndex
stringList.Add(index)

Any ideas?


问:
Check if means break certain limits R
I have a 100x2 dataset, where the first column identifies the sample, and the second column represents the measurement. Each sample is of size 4, so the dataset looks like:

```<code>V1  V2
1   125.8
1   128.4
1   129.0
1   121.0
2   125.2
2   127.0
2   130.4
2   124.6
3   121.8
3   126.8
..  ..
</code>```

I have calculated the mean for each sample using:

```<code>df2 = subset(data, select = c(2))
means =  t(sapply(split(df2,rep(seq(1,nrow(df2),4),each=4)),colMeans))
</code>```

So I now have a vector of 25 means. I want to check if each of these means falls outside certain limits (defined below), and then return an object containing the sample ID, the mean value for the sample, and information on which limit it broke, setting the output to be of class "shewart":

```<code>warning_upper: 130.4
action_upper: 132.1
warning_lower: 123.6
action_lower: 121.9
</code>```

答:
I was working on a solution at the same time when AntoniosK posted his.

I've also used the dplyr package:

```<code>library(dplyr)
df1 <- read.table(text = "V1  V2
1   125.8
1   128.4
1   129.0
1   121.0
2   125.2
2   127.0
2   130.4
2   124.6
3   121.8
3   126.8
3   133.8
3   144.5", header = TRUE)

warn_upper <- 130.4
action_upper  <- 132.1
warn_lower <- 123.6
action_lower  <- 121.9

df1 %>%
        group_by(V1) %>%
        summarize(smean = mean(V2)) %>%
        mutate(warn_hi   = (smean - warn_upper) > 0 ,
               action_hi = (smean - action_upper ) > 0,
               warn_lo   = (-1 * (smean - warn_lower)) > 0 ,
               action_lo = (-1 * (smean - action_lower )) > 0) %>%
        mutate(klass = if_else(warn_lo | action_lo |
                               warn_hi | action_hi, true = "shewart", false="" ))
</code>```

Result:

```<code>     V1 smean warn_hi action_hi warn_lo action_lo  klass
  <int> <dbl>   <lgl>     <lgl>   <lgl>     <lgl>   <chr>
1     1 126.0   FALSE     FALSE   FALSE     FALSE
2     2 126.8   FALSE     FALSE   FALSE     FALSE
3     3 131.7    TRUE     FALSE   FALSE     FALSE shewart
</code>```

Title: Check if means break certain limits R

Body:
I have a 100x2 dataset, where the first column identifies the sample, and the second column represents the measurement. Each sample is of size 4, so the dataset looks like:

V1  V2
1   125.8
1   128.4
1   129.0
1   121.0
2   125.2
2   127.0
2   130.4
2   124.6
3   121.8
3   126.8
..  ..

I have calculated the mean for each sample using:

df2 = subset(data, select = c(2))
means =  t(sapply(split(df2,rep(seq(1,nrow(df2),4),each=4)),colMeans))

So I now have a vector of 25 means. I want to check if each of these means falls outside certain limits (defined below), and then return an object containing the sample ID, the mean value for the sample, and information on which limit it broke, setting the output to be of class "shewart":

warning_upper: 130.4
action_upper: 132.1
warning_lower: 123.6
action_lower: 121.9

Body:
I was working on a solution at the same time when AntoniosK posted his.

I've also used the dplyr package:

library(dplyr)
df1 <- read.table(text = "V1  V2
1   125.8
1   128.4
1   129.0
1   121.0
2   125.2
2   127.0
2   130.4
2   124.6
3   121.8
3   126.8
3   133.8
3   144.5", header = TRUE)

warn_upper <- 130.4
action_upper  <- 132.1
warn_lower <- 123.6
action_lower  <- 121.9

df1 %>%
        group_by(V1) %>%
        summarize(smean = mean(V2)) %>%
        mutate(warn_hi   = (smean - warn_upper) > 0 ,
               action_hi = (smean - action_upper ) > 0,
               warn_lo   = (-1 * (smean - warn_lower)) > 0 ,
               action_lo = (-1 * (smean - action_lower )) > 0) %>%
        mutate(klass = if_else(warn_lo | action_lo |
                               warn_hi | action_hi, true = "shewart", false="" ))

Result:

     V1 smean warn_hi action_hi warn_lo action_lo  klass
  <int> <dbl>   <lgl>     <lgl>   <lgl>     <lgl>   <chr>
1     1 126.0   FALSE     FALSE   FALSE     FALSE
2     2 126.8   FALSE     FALSE   FALSE     FALSE
3     3 131.7    TRUE     FALSE   FALSE     FALSE shewart


问:
error CS0117: `UnityEditor.PlayerSettings' does not contain a definition for `mobileMTRendering'
Since I did an Unity update I can't build my videoplayer.

Assets/AVProVideo/Scripts/Editor/MediaPlayerEditor.cs(293,50): error CS0117: 'UnityEditor.PlayerSettings' does not contain a definition for 'mobileMTRendering'

I'm on Unity 2017.2

答:
Unity 2017.1 seems to provide a new function :

```<code>PlayerSettings.SetMobileMTRendering(BuildTargetGroup.iOS, true);
PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Android, true);
</code>```

Source : https://docs.unity3d.com/ScriptReference/PlayerSettings.SetMobileMTRendering.html

Body:
Unity 2017.1 seems to provide a new function :

PlayerSettings.SetMobileMTRendering(BuildTargetGroup.iOS, true);
PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Android, true);

Source : https://docs.unity3d.com/ScriptReference/PlayerSettings.SetMobileMTRendering.html


问:
My async TcpListener getting my CPU 50-60% load sometimes
I am stuck with this serious problem.

I have async TcpListener. Sometimes there are several connected clients and everything is fine. Sometimes even if there is one person. The server starts usage 50-60% of my CPU.

I think the problem could be in handling of reading exceptions but it's my only tip and I don't know how to test it.

Here is code for server:

```<code>class Server
{
    private TcpListener server;

    public Server(string hostname, int port = 25000)
    {
        server = new TcpListener(IPAddress.Parse(hostname), port);
    }

    public void ServerStart()
    {
        server.Start();
        WaitForClientConnect();
    }

    private async void WaitForClientConnect()
    {
        TcpClient client = await server.AcceptTcpClientAsync();
        Console.WriteLine("The async connection created for: " + ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());

        OnClientConnect(client);
    }

    private void OnClientConnect(TcpClient client)
    {
        ClientLowAPI clientReq = new ClientLowAPI(client);

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

Here is the code for handling a single client:

```<code>class ClientLowAPI
{
    private TcpClient client;
    private NetworkStream stream;

    public ClientLowAPI(TcpClient clientConnected)
    {
        client = clientConnected;
        stream = client.GetStream();
        WaitForHeader();
    }

    private async void WaitForHeader()
    {
        byte[] buffer = new byte[4];

        int bytesRead = 0;
        while (bytesRead < 4)
        {
            try
            {
                bytesRead += await stream.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead);
            }
            catch
            {
                stream.Close();
                client.Close();
                return;
            }
        }

        WaitForData(FourBytesToInt(buffer));
    }

    private async void WaitForData(int length)
    {
        byte[] buffer = new byte[length];

        int bytesRead = 0;
        while (bytesRead < length)
        {
            try
            {
                bytesRead += await stream.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead);
            }
            catch
            {
                stream.Close();
                client.Close();
                return;
            }
        }

        ExecuteMessage(buffer);
    }

    private void ExecuteMessage(byte[] binaryData)
    {
        // Do something with message
        WaitForHeader();
    }

    public async void SendMessage(byte[] message)
    {
        byte[] buffer = new byte[message.Length + 4];
        byte[] length = IntToFourBytes(message.Length);

        length.CopyTo(buffer, 0);
        message.CopyTo(buffer, 4);

        try
        {
            await stream.WriteAsync(buffer, 0, buffer.Length);
        }
        catch
        {
            stream.Close();
            client.Close();
            return;
        }
    }

    private int FourBytesToInt(byte[] array)
    {
        int res = 0;
        res += array[0] * 256 * 256 * 256;
        res += array[1] * 256 * 256;
        res += array[2] * 256;
        res += array[3];
        return res;
    }

    private byte[] IntToFourBytes(int intValue)
    {
        byte[] array = new byte[4];
        array[0] = (byte)(intValue >> 24);
        array[1] = (byte)(intValue >> 16);
        array[2] = (byte)(intValue >> 8);
        array[3] = (byte)intValue;
        return array;
    }
}
</code>```

答:
The problem was caused by this loop:

```<code>while (bytesRead < 4)
        {
            try
            {
                bytesRead += await stream.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead);
            }
            catch
            {
                stream.Close();
                client.Close();
                return;
            }
        }
</code>```

Normally was connection killed by force and server has raised exception but sometimes the connection was properly closed by client by TcpClient.Close() then the exception was not raised and the stream.ReadAsync method start returns 0 which caused infinty loop with huge CPU usage.

for fast fix i used the following condition:

```<code>        if (bytesRead == 0)
        {
            throw new System.IO.IOException();
        }
</code>```

Body:
I am stuck with this serious problem.

I have async TcpListener. Sometimes there are several connected clients and everything is fine. Sometimes even if there is one person. The server starts usage 50-60% of my CPU.

I think the problem could be in handling of reading exceptions but it's my only tip and I don't know how to test it.

Here is code for server:

class Server
{
    private TcpListener server;

    public Server(string hostname, int port = 25000)
    {
        server = new TcpListener(IPAddress.Parse(hostname), port);
    }

    public void ServerStart()
    {
        server.Start();
        WaitForClientConnect();
    }

    private async void WaitForClientConnect()
    {
        TcpClient client = await server.AcceptTcpClientAsync();
        Console.WriteLine("The async connection created for: " + ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());

        OnClientConnect(client);
    }

    private void OnClientConnect(TcpClient client)
    {
        ClientLowAPI clientReq = new ClientLowAPI(client);

        WaitForClientConnect();
    }
}

Here is the code for handling a single client:

class ClientLowAPI
{
    private TcpClient client;
    private NetworkStream stream;

    public ClientLowAPI(TcpClient clientConnected)
    {
        client = clientConnected;
        stream = client.GetStream();
        WaitForHeader();
    }

    private async void WaitForHeader()
    {
        byte[] buffer = new byte[4];

        int bytesRead = 0;
        while (bytesRead < 4)
        {
            try
            {
                bytesRead += await stream.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead);
            }
            catch
            {
                stream.Close();
                client.Close();
                return;
            }
        }

        WaitForData(FourBytesToInt(buffer));
    }

    private async void WaitForData(int length)
    {
        byte[] buffer = new byte[length];

        int bytesRead = 0;
        while (bytesRead < length)
        {
            try
            {
                bytesRead += await stream.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead);
            }
            catch
            {
                stream.Close();
                client.Close();
                return;
            }
        }

        ExecuteMessage(buffer);
    }

    private void ExecuteMessage(byte[] binaryData)
    {
        // Do something with message
        WaitForHeader();
    }

    public async void SendMessage(byte[] message)
    {
        byte[] buffer = new byte[message.Length + 4];
        byte[] length = IntToFourBytes(message.Length);

        length.CopyTo(buffer, 0);
        message.CopyTo(buffer, 4);

        try
        {
            await stream.WriteAsync(buffer, 0, buffer.Length);
        }
        catch
        {
            stream.Close();
            client.Close();
            return;
        }
    }

    private int FourBytesToInt(byte[] array)
    {
        int res = 0;
        res += array[0] * 256 * 256 * 256;
        res += array[1] * 256 * 256;
        res += array[2] * 256;
        res += array[3];
        return res;
    }

    private byte[] IntToFourBytes(int intValue)
    {
        byte[] array = new byte[4];
        array[0] = (byte)(intValue >> 24);
        array[1] = (byte)(intValue >> 16);
        array[2] = (byte)(intValue >> 8);
        array[3] = (byte)intValue;
        return array;
    }
}

Body:
The problem was caused by this loop:

while (bytesRead < 4)
        {
            try
            {
                bytesRead += await stream.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead);
            }
            catch
            {
                stream.Close();
                client.Close();
                return;
            }
        }

Normally was connection killed by force and server has raised exception but sometimes the connection was properly closed by client by TcpClient.Close() then the exception was not raised and the stream.ReadAsync method start returns 0 which caused infinty loop with huge CPU usage.

for fast fix i used the following condition:

        if (bytesRead == 0)
        {
            throw new System.IO.IOException();
        }


问:
AWS hosted data storage for storing simple entities
I need to choose data storage for simple system. The main purpose of the system is storing events - simple entities with timestamp, user id and type. No joins. Just single table.

Stored data will be fetched rarely (compared with writes). I expect following read operations:

get latest events for a list of users

get latest events of a type for a list of users

I expect about 0.5-1 million writes a day. Data older than 2 years can be removed.

I'm looking for best fitted service provided by AWS. I wonder if using redshift is like taking a sledgehammer to crack a nut?

答:
I would also like to check the AWS Simple DB as it looks more fit(in a first glance) for your requirements.

Please refer this article which explains some practical user experience.

http://www.masonzhang.com/2013/06/2-reasons-why-we-select-simpledb.html


问:
How can I alter a column to a user-defined type in Postgres if there are already values that won't match?
I have a Postgres table with a column that is currently of type "character varying (50)".  I want to change the type of that column to a user-defined type to restrict the allowable values to those specified in my user-defined type "fruit_types".

Is there a way that I can use an ALTER COLUMN statement to basically say "convert the existing values in this column to  one of the pre-defined fruit_types and if you cannot convert, set to other "?

Here is my user-defined type:

```<code>CREATE TYPE food.fruit_types AS ENUM
    ('apple', 'banana', 'peach', 'other');
</code>```

And here is the statement that will work as long as all of the text matches a value in my user-defined type:

```<code>ALTER TABLE food.fruit
  ALTER COLUMN fruit_type TYPE food.fruit_types USING
   (fruit_type::TEXT::food.fruit_types);
</code>```

But if I have a value in that column that isn't in the user-defined type (for example "kiwi") then I get this error message:

```<code>invalid input value for enum food.fruit_types: "kiwi"
</code>```

答:
You can check whether a label exists in an enum type with the function enum_range():

```<code>ALTER TABLE food.fruit
    ALTER COLUMN fruit_type TYPE food.fruit_types USING (
        CASE
            WHEN fruit_type = ANY(enum_range(NULL::food.fruit_types)::text[])
            THEN fruit_type::food.fruit_types
            ELSE 'other'::food.fruit_types
        END)
</code>```

Body:
I have a Postgres table with a column that is currently of type "character varying (50)".  I want to change the type of that column to a user-defined type to restrict the allowable values to those specified in my user-defined type "fruit_types".

Is there a way that I can use an ALTER COLUMN statement to basically say "convert the existing values in this column to  one of the pre-defined fruit_types and if you cannot convert, set to other "?

Here is my user-defined type:

CREATE TYPE food.fruit_types AS ENUM
    ('apple', 'banana', 'peach', 'other');

And here is the statement that will work as long as all of the text matches a value in my user-defined type:

ALTER TABLE food.fruit
  ALTER COLUMN fruit_type TYPE food.fruit_types USING
   (fruit_type::TEXT::food.fruit_types);

But if I have a value in that column that isn't in the user-defined type (for example "kiwi") then I get this error message:

invalid input value for enum food.fruit_types: "kiwi"

Body:
You can check whether a label exists in an enum type with the function enum_range():

ALTER TABLE food.fruit
    ALTER COLUMN fruit_type TYPE food.fruit_types USING (
        CASE
            WHEN fruit_type = ANY(enum_range(NULL::food.fruit_types)::text[])
            THEN fruit_type::food.fruit_types
            ELSE 'other'::food.fruit_types
        END)


问:
Adding SPFieldType.File to a custom list
When I try to add a File type field to a custom list I get

System.InvalidOperationException: Operation is not valid due to the current state of the object

```<code>Guid listGuid = adminWeb.Lists.Add(queueListName, "DotNetNuke Document Queue", SPListTemplateType.GenericList);

queueList = adminWeb.Lists[listGuid];
queueList.Fields.Add("Status", SPFieldType.File, false);

queueList.Update();
</code>```

答:
I don't believe that you can have a "File" field. If you look in the UI, there is no "File" field type for custom/generic list.

If you need 1 file per item and it is mandatory, then you should be using a document library.

If you need more than 1 file per list item, then file attachments is the way to go.

Body:
When I try to add a File type field to a custom list I get

System.InvalidOperationException: Operation is not valid due to the current state of the object

Guid listGuid = adminWeb.Lists.Add(queueListName, "DotNetNuke Document Queue", SPListTemplateType.GenericList);

queueList = adminWeb.Lists[listGuid];
queueList.Fields.Add("Status", SPFieldType.File, false);

queueList.Update();


问:
Bash change number to another value on specific line
i'm new with bash scripting , and i looking for solution to change a number to another value on specific line.
I have file named foo.config and in this file i have about 100 lines of configuration.
For example i have

<UpdateInterval>2</UpdateInterval>

and i need to find this line on foo.config and replace number(this can be number for 0 to 10 and for my example is 2) for 0 as always.

Like this :
<UpdateInterval>0</UpdateInterval>

How can i do it with sed ? please suggest

the part of lines:

```<code><InstallUrl />
<TargetCulture>en</TargetCulture>
<ApplicationVersion>1.0.1.8</ApplicationVersion>
<AutoIncrementApplicationRevision>true</AutoIncrementApplicationRevision>
<UpdateEnabled>true</UpdateEnabled>
<UpdateInterval>2</UpdateInterval>
<UpdateIntervalUnits>hours</UpdateIntervalUnits>
<ProductName>xxxxxxxxxxxx</ProductName>
<PublisherName />
<SupportUrl />
<FriendlyName>xxxxxxxxxxxx</FriendlyName>
<OfficeApplicationDescription />
<LoadBehavior>3</LoadBehavior>
</code>```

答:
sed and others(grep, awk) never be a good tools for parsing xml/html data. Use a proper xml/html parsers, like xmlstarlet:

```<code>xmlstarlet ed -L -O -u "//UpdateInterval" -v 0 foo.config
</code>```

ed - edit mode

-L - edit the file inplace

-O - omit xml declaration

-u - update action

"//UpdateInterval" - xpath expression

-v 0 - the new value of the element to be updated

The final (exemplary) foo.config contents:

```<code><root>
  <InstallUrl/>
  <TargetCulture>en</TargetCulture>
  <ApplicationVersion>1.0.1.8</ApplicationVersion>
  <AutoIncrementApplicationRevision>true</AutoIncrementApplicationRevision>
  <UpdateEnabled>true</UpdateEnabled>
  <UpdateInterval>0</UpdateInterval>
  <UpdateIntervalUnits>hours</UpdateIntervalUnits>
  <ProductName>xxxxxxxxxxxx</ProductName>
  <PublisherName/>
  <SupportUrl/>
  <FriendlyName>xxxxxxxxxxxx</FriendlyName>
  <OfficeApplicationDescription/>
  <LoadBehavior>3</LoadBehavior>
</root>
</code>```

The <root> tag was specified for demonstration purpose, your xml/html structure should have its own "root"(most parent) tag

Body:
i'm new with bash scripting , and i looking for solution to change a number to another value on specific line.
I have file named foo.config and in this file i have about 100 lines of configuration.
For example i have

<UpdateInterval>2</UpdateInterval>

and i need to find this line on foo.config and replace number(this can be number for 0 to 10 and for my example is 2) for 0 as always.

Like this :
<UpdateInterval>0</UpdateInterval>

How can i do it with sed ? please suggest

the part of lines:

<InstallUrl />
<TargetCulture>en</TargetCulture>
<ApplicationVersion>1.0.1.8</ApplicationVersion>
<AutoIncrementApplicationRevision>true</AutoIncrementApplicationRevision>
<UpdateEnabled>true</UpdateEnabled>
<UpdateInterval>2</UpdateInterval>
<UpdateIntervalUnits>hours</UpdateIntervalUnits>
<ProductName>xxxxxxxxxxxx</ProductName>
<PublisherName />
<SupportUrl />
<FriendlyName>xxxxxxxxxxxx</FriendlyName>
<OfficeApplicationDescription />
<LoadBehavior>3</LoadBehavior>

Body:
sed and others(grep, awk) never be a good tools for parsing xml/html data. Use a proper xml/html parsers, like xmlstarlet:

xmlstarlet ed -L -O -u "//UpdateInterval" -v 0 foo.config

ed - edit mode

-L - edit the file inplace

-O - omit xml declaration

-u - update action

"//UpdateInterval" - xpath expression

-v 0 - the new value of the element to be updated

The final (exemplary) foo.config contents:

<root>
  <InstallUrl/>
  <TargetCulture>en</TargetCulture>
  <ApplicationVersion>1.0.1.8</ApplicationVersion>
  <AutoIncrementApplicationRevision>true</AutoIncrementApplicationRevision>
  <UpdateEnabled>true</UpdateEnabled>
  <UpdateInterval>0</UpdateInterval>
  <UpdateIntervalUnits>hours</UpdateIntervalUnits>
  <ProductName>xxxxxxxxxxxx</ProductName>
  <PublisherName/>
  <SupportUrl/>
  <FriendlyName>xxxxxxxxxxxx</FriendlyName>
  <OfficeApplicationDescription/>
  <LoadBehavior>3</LoadBehavior>
</root>

The <root> tag was specified for demonstration purpose, your xml/html structure should have its own "root"(most parent) tag


问:
Why does camel retain exchanges in inflightrepository?
My team has a working (very simple) service running through apache camel, functionally everything tests ok but load-testing shows that the service consumes memory over time. Digging into a the heap-dumps it turns out that the memory consumption is coming from the inflight-repository. It appears that every single exchange sent over the route is being retained but we can't identify any reason why an exchange should be retained once the route completes and the exchange is successfully delivered.

The initial (knee-jerk) reaction to the problem from my team is that it was a memory-leak but I don't believe this is the case - we just have an unexpected action - the exchanges are never de-referenced so garbage collection doesn't attempt to dispose of them.

The hard part is that it isn't just one copy of an exchange that appears to be retained it is every step of the exchange lifecycle that is retained, while the route isn't particularly complex it does implement a split-aggregate route that then exaggerates the problem.

We've considered adding a component to flush stale exchanges from the inflightrepository but that rather misses the point.

Can anyone explain why Camel is behaving like this?

答:
After considerable digging the solution turned out to be pretty trivial. The route generates custom a exchangeId to simplify the tracking of an exchange against requests made by clients. The result, at the end of the route, is that when an exchange is destroyed (removed from inflight repository) the key:value map of exchangeId:exchange in the repository doesn't contain the custom exchangeId and, for obvious reasons, does not remove the completed exchange.

This appears to be a side-effect of using an aggregate strategy. Without this the exchanges are removed as expected.

In short it was user error...


问:
Python : MySQLdb
I'm setting up my website on a EC2 Amazon-Linux instance and it uses some Python.

After a lot of tuning I had big troubles setting up Python.
Especially the following code throws an error:

```<code> >>> import MySQLdb

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "MySQLdb/__init__.py", line 19, in <module>
    import _mysql
ImportError: libmysqlclient.so.1020: cannot open shared object file: No such file or directory
</code>```

My instances setup is the following:

```<code>Python 2.7.12
MySql  5.7.18
</code>```

Installing MySQL via pip went fine

```<code>sudo pip install MySQL-python
Successfully installed MySQL-python-1.2.5
</code>```

Sébastien

答:
Amazon Linux comes with MySQL-python27 packages that you can install, if you're using the standard Python installation from the system.

I'd suggest removing your current one and installing the one provided via yum, like so:

```<code>sudo yum remove MySQL-python
sudo yum install MySQL-python27
</code>```

Otherwise, you probably need to remove the module, install the MySQL 5.7 libs, and then reinstall the module.

```<code>sudo pip uninstall MySQL-python
sudo yum install mysql57-libs
sudo pip install MySQL-python
</code>```

There is also a pure Python implementation of a MySQL driver which is more actively maintained.

```<code>sudo pip install PyMySQL
</code>```

Title: Python : MySQLdb

Body:
I'm setting up my website on a EC2 Amazon-Linux instance and it uses some Python.

After a lot of tuning I had big troubles setting up Python.
Especially the following code throws an error:

 >>> import MySQLdb

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "MySQLdb/__init__.py", line 19, in <module>
    import _mysql
ImportError: libmysqlclient.so.1020: cannot open shared object file: No such file or directory

My instances setup is the following:

Python 2.7.12
MySql  5.7.18

Installing MySQL via pip went fine

sudo pip install MySQL-python
Successfully installed MySQL-python-1.2.5

Sébastien

Body:
Amazon Linux comes with MySQL-python27 packages that you can install, if you're using the standard Python installation from the system.

I'd suggest removing your current one and installing the one provided via yum, like so:

sudo yum remove MySQL-python
sudo yum install MySQL-python27

Otherwise, you probably need to remove the module, install the MySQL 5.7 libs, and then reinstall the module.

sudo pip uninstall MySQL-python
sudo yum install mysql57-libs
sudo pip install MySQL-python

There is also a pure Python implementation of a MySQL driver which is more actively maintained.

sudo pip install PyMySQL


问:
virtualenvwrapper: how to update project path?
When I move a project folders I have to manually update the project path in the .project file to get the workon command to work. Is it possible to update the path automatically?</p>

答:
You can just activate your virtual environment, go to the folder you want as project folder and call setvirtualenvproject:

```<code>$ workon [your_project]
$ cd [desired_project_folder]
$ setvirtualenvproject
</code>```

Then the current folder will be set as project folder in the current virtualenv.

Body:
You can just activate your virtual environment, go to the folder you want as project folder and call setvirtualenvproject:

$ workon [your_project]
$ cd [desired_project_folder]
$ setvirtualenvproject

Then the current folder will be set as project folder in the current virtualenv.


问:
C# -- injecting an IDictionary<A, IList>
I'd like to inject an instance an IDictionary<A, IList> into a class, but want to keep control over the implementation of IList used. The way I have of doing it -- with generics -- feels clunky. It makes the class definition unwieldy, and would only get worse if there were multiple similar objects I wanted to inject.

```<code>public class Lookup<T1, T2, T3> where T2 : IList<T3>, new()
{
    private IDictionary<T1, T2> _underlyingDict;

    public Lookup(IDictionary<T1, T2> dict)
    {
        _underlyingDict = dict;
    }

    public T2 Get(T1 key)
    {
        return _underlyingDict[key];
    }

    public void Add(T1 key, T3 value)
    {
        if (!_underlyingDict.ContainsKey(key))
        {
            _underlyingDict[key] = new T2();
        }
        _underlyingDict[key].Add(value);
    }
}
</code>```

Are there any problems with this approach, and is there a cleaner solution?

答:
While it is possible to do what you're doing you may want to consider this:

If you are doing dependency-injection you typically don't inject primitive types. This includes basic collections.  Dependency-injection works best when injecting long-lived singleton-scoped objects, akin to services in DDD-speak.

You may want to consider making a type to encompass the idea that this IDictionary<int, IList> is trying to represent.  What is this object used for?  How does it interact with other objects in your system?  The answers to those questions may lead for a complex type, perhaps with some functionality mixed in. Maybe its a FooRepository and you only need certain methods of the full IDictionary object exposed so you end up with something like this:

```<code>public class FooRepository<T>
{
    private IDictionary<int, IList<T>> m_repository;

    FooRepository()
    {
        m_repository = new Dictionary<int, List<T>>();
    }

    public Add(int key, IList<T> value)
    {
        m_repository.Add(key, value);
    }

    // other public methods to expose
}
</code>```

The reason you might consider doing this is that anything using the IDictionary<int, List<T>> probably has access to way more methods than it needs and you want to follow good data encapsulation practices to allow consumers of this object to access only those things that they require.

Title: C# -- injecting an IDictionary<A, IList<B>>

Body:
I'd like to inject an instance an IDictionary<A, IList> into a class, but want to keep control over the implementation of IList used. The way I have of doing it -- with generics -- feels clunky. It makes the class definition unwieldy, and would only get worse if there were multiple similar objects I wanted to inject.

public class Lookup<T1, T2, T3> where T2 : IList<T3>, new()
{
    private IDictionary<T1, T2> _underlyingDict;

    public Lookup(IDictionary<T1, T2> dict)
    {
        _underlyingDict = dict;
    }

    public T2 Get(T1 key)
    {
        return _underlyingDict[key];
    }

    public void Add(T1 key, T3 value)
    {
        if (!_underlyingDict.ContainsKey(key))
        {
            _underlyingDict[key] = new T2();
        }
        _underlyingDict[key].Add(value);
    }
}

Are there any problems with this approach, and is there a cleaner solution?

Body:
While it is possible to do what you're doing you may want to consider this:

If you are doing dependency-injection you typically don't inject primitive types. This includes basic collections.  Dependency-injection works best when injecting long-lived singleton-scoped objects, akin to services in DDD-speak.

You may want to consider making a type to encompass the idea that this IDictionary<int, IList<B>> is trying to represent.  What is this object used for?  How does it interact with other objects in your system?  The answers to those questions may lead for a complex type, perhaps with some functionality mixed in. Maybe its a FooRepository and you only need certain methods of the full IDictionary object exposed so you end up with something like this:

public class FooRepository<T>
{
    private IDictionary<int, IList<T>> m_repository;

    FooRepository()
    {
        m_repository = new Dictionary<int, List<T>>();
    }

    public Add(int key, IList<T> value)
    {
        m_repository.Add(key, value);
    }

    // other public methods to expose
}

The reason you might consider doing this is that anything using the IDictionary<int, List<T>> probably has access to way more methods than it needs and you want to follow good data encapsulation practices to allow consumers of this object to access only those things that they require.


问:
How can I build regular expression in R?
I have the following dataframe:

```<code>aa123 aa123.1 aa456 aa456.1
1     2       3     4
</code>```

I want to take only the columns that match a pattern: "aa[numbers].1".
In other words to extract only the columns that end with ".1".

I have tried to use regular expression pattern for grep and dplyr select/filter + ends_with() with pattern = ".1"

But nothing seems to work, please advise me how can I build such pattern and point me to a guide how in the future to build the pattern I need.

答:
You want to use a regular expression that matches a dot (\.) followed with 1 followed with end of string ($).

Use the following regex then:

```<code>"\\.1$"
</code>```

The dot must be escaped to match a literal dot.

See the regex demo.

Body:
I have the following dataframe:

aa123 aa123.1 aa456 aa456.1
1     2       3     4

I want to take only the columns that match a pattern: "aa[numbers].1".
In other words to extract only the columns that end with ".1".

I have tried to use regular expression pattern for grep and dplyr select/filter + ends_with() with pattern = ".1"

But nothing seems to work, please advise me how can I build such pattern and point me to a guide how in the future to build the pattern I need.

Body:
You want to use a regular expression that matches a dot (\.) followed with 1 followed with end of string ($).

Use the following regex then:

"\\.1$"

The dot must be escaped to match a literal dot.

See the regex demo.


问:
What do parameters of Snap.svg's unclick do?
Snap.svg is a js library to process SVG in DOM. It has a method unclickand a number of similarly named methods. Their purpose is to unbind event handlers. According to docs they all have callback parameters. What purpose do these parameters serve? Is executing these methods without parameters not enough?

答: Elements can have more than one click handler. You need to pass in the original click handler so it know which one to remove.</p>


问:
Access host cmd from guest
I'm running Slackware as a guest on Win 7 Virtualbox as host. On the Slack i'm running ssh server which i can access from outside (by port forwarding). Is there a way to issue a commands on host (for e.g. start host's ssh server) via ssh server on guest?</p>

答:
No.

If there is no SSH Server running on your windows machine (the host), there is no way to use ssh from the guest OS...

Title: Access host cmd from guest


问:
How do I add data to particular column in exisiting table?
How can I insert data to only one column in an existing table?

I dont want other column get disturbed or altered..

答:
If you mean "insert" as in "update" then</p>

```<code># to a fixed value
update tbl set col = "abc"
# WHERE <some condition>  # optionally identify which record

# add to existing value
update tbl set col = concat(col, "abc")   # add "abc" to the end of the current value
# WHERE <some condition>  # optionally identify which record
</code>```

Body:
If you mean "insert" as in "update" then

# to a fixed value
update tbl set col = "abc"
# WHERE <some condition>  # optionally identify which record

# add to existing value
update tbl set col = concat(col, "abc")   # add "abc" to the end of the current value
# WHERE <some condition>  # optionally identify which record