问:
Swift 4 - How do I test for TextView content did change?
Swift 4, iOS 11 - I have a UITextView that is pre-populated with text but I want users to be able to save any changes they make to the content there. I also have a Save button in the navigation bar and I would like to disable it until the user actually changes the text in the TextView.

I know how to test for empty but I don't know how to test for when the text has been edited. How do I modify the following to test for changes to the content of TextView?

```<code>@IBAction func textEditingChanged(_ sender: UITextView) {
    updateSaveButtonState()
  }

func updateSaveButtonState() {
    let descriptionText = descriptionTextView.text ?? ""
    saveButton.isEnabled = !descriptionText.isEmpty
  }
</code>```

答:
We'll to use it a dynamic way and not only in single place, i tried to make it easier to implement around the whole app, subclassing the UITextView is one of the only ways we got here @holex has suggested isEdited boolean flag and it gave me an idea, Thanks to that.

Here is the steps to implement it:

First of all set the defaultText of the textView and set the target of the method that will be called when the textView will be edited, so you can customize what ever you want.

```<code>@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var textView: SBTextView!{
    didSet{
        textView.defaultText = "Hello"
        textView.setTarget = (selector:#selector(self.updateSaveButtonState),target:self)
    }
}
</code>```

Lets say you'll setup the saveButton in viewDidLoad:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // setup save button action
    saveButton.action = #selector(saveAction(_:))
    saveButton.target = self
    self.updateSaveButtonState()

}
</code>```

And last is your save action and the selector to update the view using isEdited flag.

```<code>//MARK:- Actions

@objc private func updateSaveButtonState(){

    // has not been changed keep save button disabled
    if self.textView.isEdited == false{
        self.saveButton.isEnabled = false
        self.saveButton.tintColor = .gray
    }else {
        // text has been changed enable save button
        self.saveButton.isEnabled = true
        self.saveButton.tintColor = nil // will reset the color to default
    }
}

@objc private func saveAction(_ saveButton:UIBarButtonItem){

    self.textView.updateDefaultText()

}
</code>```

TextView Custom Class:

```<code>//
//  SBTextView.swift
//
//
//  Created by Saad Albasha on 11/17/17.
//  Copyright © 2017 AaoIi. All rights reserved.
//

import UIKit

class SBTextView: UITextView,UITextViewDelegate {

    var isEdited = false
    private var selector : Selector?
    private var target : UIViewController?
    var setTarget: (selector:Selector?,target:UIViewController?) {
        get{
            return (selector,target)
        }
        set(newVal) {
            selector = newVal.0
            target = newVal.1
        }
    }
    var textViewDefaultText = ""
    var defaultText: String {
        get {
            return textViewDefaultText
        }
        set(newVal) {
            textViewDefaultText = newVal
            self.text = newVal
            self.isEdited = false
        }
    }

    //MARK:- Life Cycle

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)

        self.setupTextview()

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.setupTextview()
    }

    private func setupTextview(){

        // setup textview
        self.text = textViewDefaultText
        self.delegate = self

    }

    func updateDefaultText(){

        self.defaultText = self.text!

        // update save button state
        target!.perform(self.selector, with: nil, with: nil)
    }

    //MARK:- Delegate

    internal func textViewDidChange(_ textView: UITextView) {

        if textViewDefaultText != textView.text! {
            isEdited = true
        }else {
            isEdited = false
        }

        // update save button state
        target!.perform(self.selector, with: nil, with: nil)
    }

}
</code>```

I hope this helps.

Body:
Swift 4, iOS 11 - I have a UITextView that is pre-populated with text but I want users to be able to save any changes they make to the content there. I also have a Save button in the navigation bar and I would like to disable it until the user actually changes the text in the TextView.

I know how to test for empty but I don't know how to test for when the text has been edited. How do I modify the following to test for changes to the content of TextView?

@IBAction func textEditingChanged(_ sender: UITextView) {
    updateSaveButtonState()
  }

func updateSaveButtonState() {
    let descriptionText = descriptionTextView.text ?? ""
    saveButton.isEnabled = !descriptionText.isEmpty
  }

Body:
We'll to use it a dynamic way and not only in single place, i tried to make it easier to implement around the whole app, subclassing the UITextView is one of the only ways we got here @holex has suggested isEdited boolean flag and it gave me an idea, Thanks to that.

Here is the steps to implement it:

First of all set the defaultText of the textView and set the target of the method that will be called when the textView will be edited, so you can customize what ever you want.

@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var textView: SBTextView!{
    didSet{
        textView.defaultText = "Hello"
        textView.setTarget = (selector:#selector(self.updateSaveButtonState),target:self)
    }
}

Lets say you'll setup the saveButton in viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()

    // setup save button action
    saveButton.action = #selector(saveAction(_:))
    saveButton.target = self
    self.updateSaveButtonState()

}

And last is your save action and the selector to update the view using isEdited flag.

//MARK:- Actions

@objc private func updateSaveButtonState(){

    // has not been changed keep save button disabled
    if self.textView.isEdited == false{
        self.saveButton.isEnabled = false
        self.saveButton.tintColor = .gray
    }else {
        // text has been changed enable save button
        self.saveButton.isEnabled = true
        self.saveButton.tintColor = nil // will reset the color to default
    }
}

@objc private func saveAction(_ saveButton:UIBarButtonItem){

    self.textView.updateDefaultText()

}

TextView Custom Class:

//
//  SBTextView.swift
//
//
//  Created by Saad Albasha on 11/17/17.
//  Copyright © 2017 AaoIi. All rights reserved.
//

import UIKit

class SBTextView: UITextView,UITextViewDelegate {

    var isEdited = false
    private var selector : Selector?
    private var target : UIViewController?
    var setTarget: (selector:Selector?,target:UIViewController?) {
        get{
            return (selector,target)
        }
        set(newVal) {
            selector = newVal.0
            target = newVal.1
        }
    }
    var textViewDefaultText = ""
    var defaultText: String {
        get {
            return textViewDefaultText
        }
        set(newVal) {
            textViewDefaultText = newVal
            self.text = newVal
            self.isEdited = false
        }
    }

    //MARK:- Life Cycle

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)

        self.setupTextview()

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.setupTextview()
    }

    private func setupTextview(){

        // setup textview
        self.text = textViewDefaultText
        self.delegate = self

    }

    func updateDefaultText(){

        self.defaultText = self.text!

        // update save button state
        target!.perform(self.selector, with: nil, with: nil)
    }

    //MARK:- Delegate

    internal func textViewDidChange(_ textView: UITextView) {

        if textViewDefaultText != textView.text! {
            isEdited = true
        }else {
            isEdited = false
        }

        // update save button state
        target!.perform(self.selector, with: nil, with: nil)
    }

}

I hope this helps.


来源: stackexchange

问:
R shiny: renderTable reset input$tableid_rows_selected value
Background : I'm creating a simple table using the following code:

```<code>output$mytable = DT::renderDataTable({
              datatable(data_frame_object, selection='single')
              })
</code>```

Note that selection='single' makes it so that only one row is shown as selected at a time.
I track the row that is selected by the user by using the following code:

```<code>index=input$mytable_rows_selected
</code>```

Problem :  The problem I am having is that I want to reset the value of index=input$mytable_rows_selected every time a new row is selected.
Currently, if user selects row 1, the index will have value [1]. If user then selects row 2, then index will have value of [1, 2]. However, I just want index to have value of [2].

Attempted solution:  My workaround has been to use index[length(index)] to get the row that was last selected,but this is not suitable for my purposes.

Working example using iris data:

```<code>library(shiny)
library(DT)

server <- function(input, output, session) {

  output$mytable = DT::renderDataTable({
    datatable(iris[,c(1,4,5)],selection='single')
  },
  options = list(lengthMenu = c(5, 30, 50), pageLength = 10, orderClasses=TRUE)
  )

  output$info = DT::renderDataTable({

    index=input$mytable_rows_selected

    if (length(index)){
      index2=index[length(index)]
    }
    else{
      index2=index
    }
    iris[index2,c(1,4)]
  },
  options = list(pageLength = 5, orderClasses=TRUE, searching=FALSE)
  )

}

ui <- fluidPage(

  fluidRow(
    column(4,dataTableOutput('mytable')),

    column(6,offset=1,
           tabsetPanel(type="tabs",
                       tabPanel("hi",dataTableOutput('info')))
    )
  )
)
</code>```

答:
Try this code</p>

```<code>library(shiny)
library(DT)

server <- function(input, output, session) {

  output$mytable = DT::renderDataTable({
    datatable(iris[,c(1,4,5)],selection='single')
  },
  options = list(lengthMenu = c(5, 30, 50), pageLength = 10, orderClasses=TRUE)
  )

  selected.rows <- reactiveValues(index = NULL)

  observe({
      selected.rows$index <- input$mytable_rows_selected
  })

  output$info = DT::renderDataTable({

    index=selected.rows$index

    if (length(index)){
      index2=index[length(index)]
    }
    else{
      index2=index
    }
    iris[index2,c(1,4)]
  },
  options = list(pageLength = 5, orderClasses=TRUE, searching=FALSE)
  )

}

ui <- fluidPage(

  fluidRow(
    column(4,dataTableOutput('mytable')),

    column(6,offset=1,
           tabsetPanel(type="tabs",
                       tabPanel("hi",dataTableOutput('info')))
    )
  )
)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Background : I'm creating a simple table using the following code:

output$mytable = DT::renderDataTable({
              datatable(data_frame_object, selection='single')
              })

Note that selection='single' makes it so that only one row is shown as selected at a time.
I track the row that is selected by the user by using the following code:

index=input$mytable_rows_selected

Problem :  The problem I am having is that I want to reset the value of index=input$mytable_rows_selected every time a new row is selected.
Currently, if user selects row 1, the index will have value [1]. If user then selects row 2, then index will have value of [1, 2]. However, I just want index to have value of [2].

Attempted solution:  My workaround has been to use index[length(index)] to get the row that was last selected,but this is not suitable for my purposes.

Working example using iris data:

library(shiny)
library(DT)

server <- function(input, output, session) {

  output$mytable = DT::renderDataTable({
    datatable(iris[,c(1,4,5)],selection='single')
  },
  options = list(lengthMenu = c(5, 30, 50), pageLength = 10, orderClasses=TRUE)
  )

  output$info = DT::renderDataTable({

    index=input$mytable_rows_selected

    if (length(index)){
      index2=index[length(index)]
    }
    else{
      index2=index
    }
    iris[index2,c(1,4)]
  },
  options = list(pageLength = 5, orderClasses=TRUE, searching=FALSE)
  )

}

ui <- fluidPage(

  fluidRow(
    column(4,dataTableOutput('mytable')),

    column(6,offset=1,
           tabsetPanel(type="tabs",
                       tabPanel("hi",dataTableOutput('info')))
    )
  )
)

Body:
Try this code

library(shiny)
library(DT)

server <- function(input, output, session) {

  output$mytable = DT::renderDataTable({
    datatable(iris[,c(1,4,5)],selection='single')
  },
  options = list(lengthMenu = c(5, 30, 50), pageLength = 10, orderClasses=TRUE)
  )

  selected.rows <- reactiveValues(index = NULL)

  observe({
      selected.rows$index <- input$mytable_rows_selected
  })

  output$info = DT::renderDataTable({

    index=selected.rows$index

    if (length(index)){
      index2=index[length(index)]
    }
    else{
      index2=index
    }
    iris[index2,c(1,4)]
  },
  options = list(pageLength = 5, orderClasses=TRUE, searching=FALSE)
  )

}

ui <- fluidPage(

  fluidRow(
    column(4,dataTableOutput('mytable')),

    column(6,offset=1,
           tabsetPanel(type="tabs",
                       tabPanel("hi",dataTableOutput('info')))
    )
  )
)


问:
R: Webscraping an xml page
I am trying to webscrape a XML page into a dataframe to create a table as in
https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield

I tried:

```<code>library("XML")
library("methods")
xmldataframe <- xmlToDataFrame("http://data.treasury.gov/feed.svc/DailyTreasuryYieldCurveRateData?$filter=month(NEW_DATE)%20eq%2011%20and%20year(NEW_DATE)%20eq%202017")
xmldataframe
</code>```

But I could not get it to work properly.
Thank you for any help.

Title: R: Webscraping an xml page

Body:
I am trying to webscrape a XML page into a dataframe to create a table as in
https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield

I tried:

library("XML")
library("methods")
xmldataframe <- xmlToDataFrame("http://data.treasury.gov/feed.svc/DailyTreasuryYieldCurveRateData?$filter=month(NEW_DATE)%20eq%2011%20and%20year(NEW_DATE)%20eq%202017")
xmldataframe

But I could not get it to work properly.
Thank you for any help.

Body:
I prefer to use the package rvest, so try this

To download:

if(!require("rvest")){install.packages("rvest");library("rvest")}
url <- "https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield"

xml_page <- read_html(url)

detail <- xml_page %>%
  html_nodes(".text_view_data") %>% #node of the table
  html_text()

Result

> detail
  [1] "11/01/17" "1.06"     "1.18"     "1.30"     "1.46"     "1.61"     "1.74"     "2.01"
  [9] "2.22"     "2.37"     "2.63"     "2.85"     "11/02/17" "1.02"     "1.17"     "1.29"
 [17] "1.46"     "1.61"     "1.73"     "2.00"     "2.21"     "2.35"     "2.61"     "2.83"
 [25] "11/03/17" "1.02"     "1.18"     "1.31"     "1.49"     "1.63"     "1.74"     "1.99"
 [33] "2.19"     "2.34"     "2.59"     "2.82"     "11/06/17" "1.03"     "1.19"     "1.30"
 [41] "1.50"     "1.61"     "1.73"     "1.99"     "2.17"     "2.32"     "2.58"     "2.80"
 [49] "11/07/17" "1.05"     "1.22"     "1.33"     "1.49"     "1.63"     "1.75"     "1.99"
 [57] "2.17"     "2.32"     "2.56"     "2.77"     "11/08/17" "1.05"     "1.23"     "1.35"
 [65] "1.53"     "1.65"     "1.77"     "2.01"     "2.19"     "2.32"     "2.57"     "2.79"
 [73] "11/09/17" "1.07"     "1.24"     "1.36"     "1.53"     "1.63"     "1.75"     "2.01"
 [81] "2.20"     "2.33"     "2.59"     "2.81"     "11/10/17" "1.06"     "1.23"     "1.37"
 [89] "1.54"     "1.67"     "1.79"     "2.06"     "2.27"     "2.40"     "2.67"     "2.88"
 [97] "11/13/17" "1.07"     "1.24"     "1.37"     "1.55"     "1.70"     "1.82"     "2.08"
[105] "2.27"     "2.40"     "2.67"     "2.87"     "11/14/17" "1.06"     "1.26"     "1.40"
[113] "1.55"     "1.68"     "1.81"     "2.06"     "2.26"     "2.38"     "2.64"     "2.84"

Then, you have to adapt it to the format you need

Edit:

To dataframe

This is clearly not a ellegant way but it works.

table_names<-c("Date","1 Mo","3 Mo",    "6 Mo", "1 Yr", "2 Yr", "3 Yr", "5 Yr", "7 Yr", "10 Yr",    "20 Yr",    "30 Yr")
ndates<-sum(grepl("/",detail))
df_detail<-as.data.frame(matrix(nrow = ndates,ncol = length(table_names)))
names(df_detail)<-table_names

pos1<-which(grepl("/",detail))
pos2<-which(grepl("/",detail))-1
pos2<-pos2[-1]
pos2<-c(pos2,length(detail))

for(i in 1:ndates){
  df_detail[i,]<-detail[pos1[i]:pos2[i]]

}

Result

> df_detail
       Date 1 Mo 3 Mo 6 Mo 1 Yr 2 Yr 3 Yr 5 Yr 7 Yr 10 Yr 20 Yr 30 Yr
1  11/01/17 1.06 1.18 1.30 1.46 1.61 1.74 2.01 2.22  2.37  2.63  2.85
2  11/02/17 1.02 1.17 1.29 1.46 1.61 1.73 2.00 2.21  2.35  2.61  2.83
3  11/03/17 1.02 1.18 1.31 1.49 1.63 1.74 1.99 2.19  2.34  2.59  2.82
4  11/06/17 1.03 1.19 1.30 1.50 1.61 1.73 1.99 2.17  2.32  2.58  2.80
5  11/07/17 1.05 1.22 1.33 1.49 1.63 1.75 1.99 2.17  2.32  2.56  2.77
6  11/08/17 1.05 1.23 1.35 1.53 1.65 1.77 2.01 2.19  2.32  2.57  2.79
7  11/09/17 1.07 1.24 1.36 1.53 1.63 1.75 2.01 2.20  2.33  2.59  2.81
8  11/10/17 1.06 1.23 1.37 1.54 1.67 1.79 2.06 2.27  2.40  2.67  2.88
9  11/13/17 1.07 1.24 1.37 1.55 1.70 1.82 2.08 2.27  2.40  2.67  2.87
10 11/14/17 1.06 1.26 1.40 1.55 1.68 1.81 2.06 2.26  2.38  2.64  2.84


问:
Snackbar action getView()
in my Activity I have implement OnClickListener interface

MainActivity extends AppCompatActivity implements View.OnClickListener

init snackbar like this:

```<code>snackbar = Snackbar.make(view, R.string.msg, Snackbar.LENGTH_LONG);
snackbar.setAction(R.string.action_undo, this);
</code>```

but I cannot handle it on implemented OnClickListener interface method

```<code>@Override
public void onClick(View v) {
    // this not work!
    // snackbar id is different from snackbar action id
    if (v.getId() == snackbar.getView().getId()) {

    }
}
</code>```

Someone know how to get action view from snackbar?

答:
```<code>v.getId()
</code>```

is always (Reserved) :

```<code>android.support.design.R.id.snackbar_action
</code>```

Doc

Title: Snackbar action getView()

Body:
in my Activity I have implement OnClickListener interface

MainActivity extends AppCompatActivity implements View.OnClickListener

init snackbar like this:

snackbar = Snackbar.make(view, R.string.msg, Snackbar.LENGTH_LONG);
snackbar.setAction(R.string.action_undo, this);

but I cannot handle it on implemented OnClickListener interface method

@Override
public void onClick(View v) {
    // this not work!
    // snackbar id is different from snackbar action id
    if (v.getId() == snackbar.getView().getId()) {

    }
}

Someone know how to get action view from snackbar?

Body:
v.getId()

is always (Reserved) :

android.support.design.R.id.snackbar_action

Doc


问:
Room Persistence Library run time exception when calling Rooms inMemoryBuilder method
When following the tutorial for setting up the Room persistence library I run in to this error when testing on an Android device.

java.lang.RuntimeException: cannot find implementation for PackageName.AppDatabase. AppDatabase_Impl does not exist

I know a similar question has been asked however the issues were due to kotlin gradle issues. Possible Duplicate

Test class:

```<code>@RunWith(AndroidJUnit4.class)
public class LocalDatabaseTest {

    private PhotoDao mPhotoDao;
    private AppDatabase mDb;

    @Before
    public void createDb() {
        Context context = InstrumentationRegistry.getTargetContext();
        mDb = Room.inMemoryDatabaseBuilder(context.getApplicationContext(), AppDatabase.class).build();
        mPhotoDao = mDb.photoDao();
    }

    @After
    public void closeDb() throws IOException {
    //mDb.close();
}

    @Test
    public void testPreConditions() {
        assertNotNull(mDb);
   }
</code>```

Dao:

```<code>    @Dao
    public interface PhotoDao {
    @Delete()
    public void delete(Photo... photos);

    @Update
    public void update(Photo ... photos);

    @Insert
    public void insert(Photo ... photos);
    }
</code>```

Database:

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

Stack Trace:

```<code>java.lang.RuntimeException: cannot find implementation for *PackageName*.AppDatabase. AppDatabase_Impl does not exist
at android.arch.persistence.room.Room.getGeneratedImplementation(Room.java:90)
at android.arch.persistence.room.RoomDatabase$Builder.build(RoomDatabase.java:340)
at pics.chooz.choozpics.LocalDatabaseTest.createDb(LocalDatabaseTest.java:40)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1853)
</code>```

Gradle:

```<code>apply plugin: "com.android.application"
apply plugin: "android-apt"

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "*Package Name*"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 50
        versionName "1.0.32"
        multiDexEnabled true
        testInstrumentationRunner     "android.support.test.runner.AndroidJUnitRunner"
}

dexOptions {
    javaMaxHeapSize "4g"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
    }
    debug {
        debuggable true
    }
}

lintOptions {
    abortOnError false
    disable "ResourceType"
}

sourceCompatibility = 1.7
targetCompatibility = 1.7
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

packagingOptions {
    exclude 'META-INF/ASL2.0'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE'
}
}
dependencies {

androidTestCompile "com.android.support:support-annotations:$androidVersion"
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test:rules:0.5'

    compile "android.arch.persistence.room:runtime:1.0.0-alpha1"
    annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"
}
</code>```

答:
You must add the annotation processor dependency to the module where your AppDatabase is. I assumed that the app would take the depencency from my API library module, where my data model classes are, but apparently this is not the case.

Answer came from this google issue:
https://issuetracker.google.com/issues/67520422
And this SO answer:
https://stackoverflow.com/a/43918701/1959110

Body:
When following the tutorial for setting up the Room persistence library I run in to this error when testing on an Android device.

java.lang.RuntimeException: cannot find implementation for PackageName.AppDatabase. AppDatabase_Impl does not exist

I know a similar question has been asked however the issues were due to kotlin gradle issues. Possible Duplicate

Test class:

@RunWith(AndroidJUnit4.class)
public class LocalDatabaseTest {

    private PhotoDao mPhotoDao;
    private AppDatabase mDb;

    @Before
    public void createDb() {
        Context context = InstrumentationRegistry.getTargetContext();
        mDb = Room.inMemoryDatabaseBuilder(context.getApplicationContext(), AppDatabase.class).build();
        mPhotoDao = mDb.photoDao();
    }

    @After
    public void closeDb() throws IOException {
    //mDb.close();
}

    @Test
    public void testPreConditions() {
        assertNotNull(mDb);
   }

Dao:

    @Dao
    public interface PhotoDao {
    @Delete()
    public void delete(Photo... photos);

    @Update
    public void update(Photo ... photos);

    @Insert
    public void insert(Photo ... photos);
    }

Database:

@Database(entities = {Photo.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract PhotoDao photoDao();
}

Stack Trace:

java.lang.RuntimeException: cannot find implementation for *PackageName*.AppDatabase. AppDatabase_Impl does not exist
at android.arch.persistence.room.Room.getGeneratedImplementation(Room.java:90)
at android.arch.persistence.room.RoomDatabase$Builder.build(RoomDatabase.java:340)
at pics.chooz.choozpics.LocalDatabaseTest.createDb(LocalDatabaseTest.java:40)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1853)

Gradle:

apply plugin: "com.android.application"
apply plugin: "android-apt"

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "*Package Name*"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 50
        versionName "1.0.32"
        multiDexEnabled true
        testInstrumentationRunner     "android.support.test.runner.AndroidJUnitRunner"
}

dexOptions {
    javaMaxHeapSize "4g"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
    }
    debug {
        debuggable true
    }
}

lintOptions {
    abortOnError false
    disable "ResourceType"
}

sourceCompatibility = 1.7
targetCompatibility = 1.7
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

packagingOptions {
    exclude 'META-INF/ASL2.0'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/NOTICE'
}
}
dependencies {

androidTestCompile "com.android.support:support-annotations:$androidVersion"
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test:rules:0.5'

    compile "android.arch.persistence.room:runtime:1.0.0-alpha1"
    annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"
}


问:
Angular: How to use result of `.subscribe()` in consequent Observable
Angular2: I want to use the result of .subscribe() in a consequent observable.

This is in order to use the id from the parent subscribe in the nested subscribe.

I've tried using .switchMap() first, but this doesn't seem to work.

This is my attempt:

```<code>this.serviceA.getOrg()
    .switchMap(org => this.serviceB.getOrgType(org.id))
    .subscribe(type => {
        console.log(type);
});
</code>```

答:
Try flatMap:

 this.serviceA.getOrg()
    .flatMap(org => this.serviceB.getOrgType(org.id))
    .subscribe(type=> {
      console.log(type);
    });```

Body:
Angular2: I want to use the result of .subscribe() in a consequent observable.

This is in order to use the id from the parent subscribe in the nested subscribe.

I've tried using .switchMap() first, but this doesn't seem to work.

This is my attempt:

this.serviceA.getOrg()
    .switchMap(org => this.serviceB.getOrgType(org.id))
    .subscribe(type => {
        console.log(type);
});


问:
Decode JSON Swift 4
Can someone tell what is wrong with the code? I'm trying to parse the JSON from the server into variables to store the values. When i'm running the code, i'm not getting any errors. When i'm doing the print(users) after decoding the data, it's not returning anything. Can someone help me with this issue?

This is the code i'm using to retrieve the data from the server.

```<code>guard let url = URL(string: "my-url") else { return }
        let session = URLSession.shared
        let task = session.dataTask(with: url) { (data, _, _) in
            guard let data = data else { return }

            do {

                let user = try JSONDecoder().decode(User.self, from: data)
                print(user)

            } catch {}
        }
        task.resume()
</code>```

JSON result from the server

```<code>{
"UserId": "55844ef7-3f05-4560-8b37-216df422ffb8",
"ContactsDto": [
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "e61d09f8-9aec-4035-b0be-c36abea2d82b",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "54943597",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "b2e0d6d7-d97c-475e-a2ab-71cb8091a7a0",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "207-7575",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "8f8d6061-3a69-4641-ac40-329a824ff4e1",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "58511968",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "40c1e461-eb98-4e18-9363-13cfa460fe7e",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "57864550",
        "InviteStatus": "accepted",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    }
],
"ErrorCode": 0,
"ErrorMessage": null
</code>```

}

My Structure

```<code>struct User: Decodable {

let UserId: String?
let ContactsDto: [ContactsDto]?
let ErrorCode: Int?
let ErrorMessage: String?
</code>```

}

```<code>struct ContactsDto : Decodable {

let Id : String?
let UserId : String?
let FriendUserId : String?
let FirstName : String?
let LastName : String?
let Email : String?
let PhonePrefix : String?
let Phone : String?
let InviteStatus : String?
let UserStatus : String?
let ErrorCode : String?
let ErrorMessage : String?
</code>```

}

答:
Based on your errors and as Josh told you in the comments, the types on your model are not correct.

For example, one of your ContactDto object is this:

```<code>{
    "Id": null,
    "UserId": null,
    "FriendUserId": "e61d09f8-9aec-4035-b0be-c36abea2d82b",
    "FirstName": null,
    "LastName": null,
    "Email": "",
    "PhonePrefix": null,
    "Phone": "54943597",
    "InviteStatus": "pending",
    "UserStatus": null,
    "ErrorCode": 0,
    "ErrorMessage": null
},
</code>```

The ErrorCode type is a number (it looks like an integer), but in your model struct is a String?.

Please check every field to get all types, then fix the model and try again.

Title: Decode JSON Swift 4

Body:
Can someone tell what is wrong with the code? I'm trying to parse the JSON from the server into variables to store the values. When i'm running the code, i'm not getting any errors. When i'm doing the print(users) after decoding the data, it's not returning anything. Can someone help me with this issue?

This is the code i'm using to retrieve the data from the server.

guard let url = URL(string: "my-url") else { return }
        let session = URLSession.shared
        let task = session.dataTask(with: url) { (data, _, _) in
            guard let data = data else { return }

            do {

                let user = try JSONDecoder().decode(User.self, from: data)
                print(user)

            } catch {}
        }
        task.resume()

JSON result from the server

{
"UserId": "55844ef7-3f05-4560-8b37-216df422ffb8",
"ContactsDto": [
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "e61d09f8-9aec-4035-b0be-c36abea2d82b",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "54943597",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "b2e0d6d7-d97c-475e-a2ab-71cb8091a7a0",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "207-7575",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "8f8d6061-3a69-4641-ac40-329a824ff4e1",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "58511968",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "40c1e461-eb98-4e18-9363-13cfa460fe7e",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "57864550",
        "InviteStatus": "accepted",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    }
],
"ErrorCode": 0,
"ErrorMessage": null

}

My Structure

struct User: Decodable {

let UserId: String?
let ContactsDto: [ContactsDto]?
let ErrorCode: Int?
let ErrorMessage: String?

}

struct ContactsDto : Decodable {

let Id : String?
let UserId : String?
let FriendUserId : String?
let FirstName : String?
let LastName : String?
let Email : String?
let PhonePrefix : String?
let Phone : String?
let InviteStatus : String?
let UserStatus : String?
let ErrorCode : String?
let ErrorMessage : String?

}

Body:
Based on your errors and as Josh told you in the comments, the types on your model are not correct.

For example, one of your ContactDto object is this:

{
    "Id": null,
    "UserId": null,
    "FriendUserId": "e61d09f8-9aec-4035-b0be-c36abea2d82b",
    "FirstName": null,
    "LastName": null,
    "Email": "",
    "PhonePrefix": null,
    "Phone": "54943597",
    "InviteStatus": "pending",
    "UserStatus": null,
    "ErrorCode": 0,
    "ErrorMessage": null
},

The ErrorCode type is a number (it looks like an integer), but in your model struct is a String?.

Please check every field to get all types, then fix the model and try again.


问:
stop synonyms.txt file Solr from being stemmed
In synonyms.txt file I have an entry
marine => saltwater,marine but both the words are getting stemmed to 'saltwat', 'marin' respectively inspite of being in protected words file. Is there a way to avoid it?

schema.xml

```<code> <fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" ignoreCase="true" words="lang/stopwords_en.txt" />
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
      <filter class="solr.SynonymGraphFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true" analyzer="org.apache.lucene.analysis.en.EnglishAnalyzer" />
    </analyzer>
  </fieldType>
</code>```

synonyms.txt

```<code>marine => saltwater,marine
</code>```

protwords.txt

```<code>saltwater
marine
</code>```

now when I do the analysis in admin panel and query for saltwat then saltwat | marin comes up. which means that saltwater did get stemmed to saltwat in synonyms.txt file

答:
The solr analysis works in the same sequence you declare it inside your fieldType definition in schema. So, if you declare any Stem filter after the Synonyms filter, it will be applied after the synonyms changes. If you don't want this, the SynonymsFilter should be configured after the StemFilter, for example:

```<code><fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" ignoreCase="true" words="lang/stopwords_en.txt" />
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
      <filter class="solr.SynonymGraphFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true" />
    </analyzer>
  </fieldType>
</code>```

I recommend you to check Solr Analysis tool in your Solr Admin to check what's going on with your field in both indexing and querying time.

Please share your schema if you need more help.

Body:
In synonyms.txt file I have an entry
marine => saltwater,marine but both the words are getting stemmed to 'saltwat', 'marin' respectively inspite of being in protected words file. Is there a way to avoid it?

schema.xml

 <fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" ignoreCase="true" words="lang/stopwords_en.txt" />
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
      <filter class="solr.SynonymGraphFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true" analyzer="org.apache.lucene.analysis.en.EnglishAnalyzer" />
    </analyzer>
  </fieldType>

synonyms.txt

marine => saltwater,marine

protwords.txt

saltwater
marine

now when I do the analysis in admin panel and query for saltwat then saltwat | marin comes up. which means that saltwater did get stemmed to saltwat in synonyms.txt file

Body:
The solr analysis works in the same sequence you declare it inside your fieldType definition in schema. So, if you declare any Stem filter after the Synonyms filter, it will be applied after the synonyms changes. If you don't want this, the SynonymsFilter should be configured after the StemFilter, for example:

<fieldType name="text_en" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" ignoreCase="true" words="lang/stopwords_en.txt" />
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.EnglishPossessiveFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.CommonGramsFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.PorterStemFilterFactory"/>
      <filter class="solr.SynonymGraphFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true" />
    </analyzer>
  </fieldType>

I recommend you to check Solr Analysis tool in your Solr Admin to check what's going on with your field in both indexing and querying time.

Please share your schema if you need more help.


问:
Difference between doAfterTerminate and doFinally
Does anybody knows what is the difference between operators "doAfterTerminate" and "doFinally" in RxJava 2 ?</p>

答:
The difference is that doFinally executes the provided Action if the downstream cancels/disposes the sequence in addition to the regular onError or onComplete termination paths. This allows cleaning up and releasing resources by all three means. The operator also guarantees that the action gets executed exactly once per subscription even in case if the onError or onComplete signals race with a cancellation.

In contrast, doAfterTerminate only covers onError and onComplete.

You can emulate doFinally with doAfterTerminate + doOnCancel, however, being split a operation, the action parameters may be both executed and cause problems with non-idempotent cleanup logic.


问:
unity3d - Accelerometer sensitivity
I am testing the accelerometer code in Unity3D 4.3. What I want to do is simple change the object angle while tilting the ipad, to fake view angle like real live. Everything works fine except for the fact that the accelerometer is a bit too sensitive and I can see the GameObject is like of flickering even I put it on table. How can I make it less sensitive so that even when you hold with your hand the angle will change according to the tilt and the object remain steady?

Here are my code:

```<code>void Update () {
        Vector3 dir = Vector3.zero;

        dir.x = Mathf.Round(Input.acceleration.x * 1000.0f) / 1000.0f;
        dir.y = Mathf.Round(Input.acceleration.y * 1000.0f) / 1000.0f;
        dir.z = Mathf.Round(Input.acceleration.z * 1000.0f) / 1000.0f;

        // clamp acceleration vector to the unit sphere
        if (dir.sqrMagnitude > 1)
            dir.Normalize();

        // Make it move 10 meters per second instead of 10 meters per frame...
        dir *= Time.deltaTime;
        dir *= speed;

        acx = dir.x;
        acy = dir.y;
        acz = dir.z;
        transform.rotation = Quaternion.Euler(dir.y-20, -dir.x, 0);
    }
</code>```

答:
I couldn't make Kay's example work as it was not multiplying the last part, so here's my small correction:</p>

```<code>Vector3 aNew = Input.acceleration;
a = (0.1 * aNew) + (0.9 * a);
</code>```

Title: unity3d - Accelerometer sensitivity

Body:
I am testing the accelerometer code in Unity3D 4.3. What I want to do is simple change the object angle while tilting the ipad, to fake view angle like real live. Everything works fine except for the fact that the accelerometer is a bit too sensitive and I can see the GameObject is like of flickering even I put it on table. How can I make it less sensitive so that even when you hold with your hand the angle will change according to the tilt and the object remain steady?

Here are my code:

void Update () {
        Vector3 dir = Vector3.zero;

        dir.x = Mathf.Round(Input.acceleration.x * 1000.0f) / 1000.0f;
        dir.y = Mathf.Round(Input.acceleration.y * 1000.0f) / 1000.0f;
        dir.z = Mathf.Round(Input.acceleration.z * 1000.0f) / 1000.0f;

        // clamp acceleration vector to the unit sphere
        if (dir.sqrMagnitude > 1)
            dir.Normalize();

        // Make it move 10 meters per second instead of 10 meters per frame...
        dir *= Time.deltaTime;
        dir *= speed;

        acx = dir.x;
        acy = dir.y;
        acz = dir.z;
        transform.rotation = Quaternion.Euler(dir.y-20, -dir.x, 0);
    }

Body:
I couldn't make Kay's example work as it was not multiplying the last part, so here's my small correction:

Vector3 aNew = Input.acceleration;
a = (0.1 * aNew) + (0.9 * a);


问:
How to run commands in REMOTE machine with the subprocess approach using passwordless authentication in python3?
I am trying to write a script which should perform some commands (defined by Payload) in a ssh enable remote computer. I want to have a passworless connection. So that I can use the public and private key authentication. I know how to do it in paramiko and its working. Is there any way to do it by subprocess and get the output? Is there any sample code for that?

My sample code is something like that. For example,  I want to execute more connection later on.

```<code>import subprocess
def __init__ (type, options):
    if type=="ssh":
        ssh(options)
    else if type="fsexec":
        fsexec(options)

def ssh(self, ip, user, sshkey_file, payload):
    try:
        command = "ssh "
        prog = subprocess.call(["ssh -i sshkey_file -t user@ip 'payload'"])
        print(prog)
        print("Returncode:", prog)

def fsexec(self, ip, user, sshkey_file, payload):
    try:
        command = "ssh "
        prog = subprocess.call(["fsexec  -t user@ip 'payload'"])
        print(prog)
        print("Returncode:", prog)
</code>```

答:
You should use the Paramiko library to log in with ssh and the keyfile.

I copied an exmaple from a gist (https://gist.github.com/batok/2352501):

```<code>import paramiko
k = paramiko.RSAKey.from_private_key_file("/Users/whatever/Downloads/mykey.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "connecting"
c.connect( hostname = "www.acme.com", username = "ubuntu", pkey = k )
print "connected"
commands = [ "/home/ubuntu/firstscript.sh", "/home/ubuntu/secondscript.sh" ]
for command in commands:
    print "Executing {}".format( command )
    stdin , stdout, stderr = c.exec_command(command)
    print stdout.read()
    print( "Errors")
    print stderr.read()
c.close()
</code>```

Body:
I am trying to write a script which should perform some commands (defined by Payload) in a ssh enable remote computer. I want to have a passworless connection. So that I can use the public and private key authentication. I know how to do it in paramiko and its working. Is there any way to do it by subprocess and get the output? Is there any sample code for that?

My sample code is something like that. For example,  I want to execute more connection later on.

import subprocess
def __init__ (type, options):
    if type=="ssh":
        ssh(options)
    else if type="fsexec":
        fsexec(options)

def ssh(self, ip, user, sshkey_file, payload):
    try:
        command = "ssh "
        prog = subprocess.call(["ssh -i sshkey_file -t user@ip 'payload'"])
        print(prog)
        print("Returncode:", prog)

def fsexec(self, ip, user, sshkey_file, payload):
    try:
        command = "ssh "
        prog = subprocess.call(["fsexec  -t user@ip 'payload'"])
        print(prog)
        print("Returncode:", prog)

Body:
You should use the Paramiko library to log in with ssh and the keyfile.

I copied an exmaple from a gist (https://gist.github.com/batok/2352501):

import paramiko
k = paramiko.RSAKey.from_private_key_file("/Users/whatever/Downloads/mykey.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "connecting"
c.connect( hostname = "www.acme.com", username = "ubuntu", pkey = k )
print "connected"
commands = [ "/home/ubuntu/firstscript.sh", "/home/ubuntu/secondscript.sh" ]
for command in commands:
    print "Executing {}".format( command )
    stdin , stdout, stderr = c.exec_command(command)
    print stdout.read()
    print( "Errors")
    print stderr.read()
c.close()


问:
regex to count english words as single char inside char count of asian words
need some help from a regex jedi master:

If I have a string of mb chars (specifically, Japanese, Korean or Chinese) with English words sprinkled throughout, I would like to count:

asian characters as 1 per single char

english "words" (no dictionary check needed - just a string of consecutive english letters) as a single char.

English only is fine - don't worry about special spanish, swedish, etc. chars.

I am searching for a regex pattern I can use to count these strings, that will function in php and js.

Example:

これは猫です、けどKittyも大丈夫。

should count as 13 chars.

thanks for your help!

jeff

答:
Something like /[[:ascii:]]+|./ will match one non-ASCII character or one or more ASCII characters. Probably is that'll give 15. So it seems that you want to ignore punctuation. So possibly: /[A-Za-z]+|[^[:punct:]]/

```<code>$ perl -E 'use utf8; $f = "これは猫です、けどKittyも大丈夫。"; ++$c while $f =~ /[A-Za-z]+|[^[:punct:]]/g; say $c'
13
</code>```

So, that works in Perl at least. Probably in JS and PHP as well, provided their [[:punct:]] understands Unicode.

The alternative approach is to filter out stuff instead.

ContentLicense: CC BY-SA 2.5

Body:
Something like /[[:ascii:]]+|./ will match one non-ASCII character or one or more ASCII characters. Probably is that'll give 15. So it seems that you want to ignore punctuation. So possibly: /[A-Za-z]+|[^[:punct:]]/

$ perl -E 'use utf8; $f = "これは猫です、けどKittyも大丈夫。"; ++$c while $f =~ /[A-Za-z]+|[^[:punct:]]/g; say $c'
13

So, that works in Perl at least. Probably in JS and PHP as well, provided their [[:punct:]] understands Unicode.

The alternative approach is to filter out stuff instead.


问:
How to reshape a pandas.Series
It looks to me like a bug in pandas.Series.

```<code>a = pd.Series([1,2,3,4])
b = a.reshape(2,2)
b
</code>```

b has type Series but can not be displayed, the last statement gives exception, very lengthy, the last line is "TypeError: %d format: a number is required, not numpy.ndarray". b.shape returns (2,2), which contradicts its type Series. I am guessing perhaps pandas.Series does not implement reshape function and I am calling the version from np.array? Anyone see this error as well? I am at pandas 0.9.1.

答:
Just use this below code:

```<code>b=a.values.reshape(2,2)
</code>```

I think it will help you.
u can directly use only reshape() function.but it will give future warning

ContentLicense: CC BY-SA 4.0

Title: How to reshape a pandas.Series

Body:
It looks to me like a bug in pandas.Series.

a = pd.Series([1,2,3,4])
b = a.reshape(2,2)
b

b has type Series but can not be displayed, the last statement gives exception, very lengthy, the last line is "TypeError: %d format: a number is required, not numpy.ndarray". b.shape returns (2,2), which contradicts its type Series. I am guessing perhaps pandas.Series does not implement reshape function and I am calling the version from np.array? Anyone see this error as well? I am at pandas 0.9.1.

Body:
Just use this below code:

b=a.values.reshape(2,2)

I think it will help you.
u can directly use only reshape() function.but it will give future warning


问:
Object class toString() combined with Widening
My code is below, i have three output and in three toString() method of Object class is called which gives output in form of class@hashcodeinhexadecimal form then why in output 1 in which autoboxing and widening happens internally the value of object get print ?</p>

```<code>public class AutoBoxingUn
{

    static Object pp= new Object ();

    public static void main(String[] args)
    {

        int q = 10;
        Object o=q;
        System.out.println("O"+"..."+o.toString());     \\ O...10    ( output 1 )

        System.out.println(pp.toString());          \\ java.lang.Object@ee7d9f1 ( output 2 )

        A aa= new A(11);
        System.out.println(aa);                 \\ A@1edf1c96   ( output 3 )
    }

}

class A extends AutoBoxingUn
{   int o;
    A(int o)
    {
        this.o=o;
    }
    void m2()
    {}
}
</code>```

答: Object o internally hold Integer value, therefore at runtime toString() method of Integer class is called which overrides Object class toString() method for printing the object / integer</p>

Body:
My code is below, i have three output and in three toString() method of Object class is called which gives output in form of class@hashcodeinhexadecimal form then why in output 1 in which autoboxing and widening happens internally the value of object get print ?

public class AutoBoxingUn
{

    static Object pp= new Object ();

    public static void main(String[] args)
    {

        int q = 10;
        Object o=q;
        System.out.println("O"+"..."+o.toString());     \\ O...10    ( output 1 )

        System.out.println(pp.toString());          \\ java.lang.Object@ee7d9f1 ( output 2 )

        A aa= new A(11);
        System.out.println(aa);                 \\ A@1edf1c96   ( output 3 )
    }

}

class A extends AutoBoxingUn
{   int o;
    A(int o)
    {
        this.o=o;
    }
    void m2()
    {}
}


问:
Retrieve Non-Duplicate Data With Criteria
I wish to retrieve non-duplicate data with criteria based on 2 tables in SQL Server database.

Table Subject

```
ID       NAME                                       COURSE
-------  -----------------------------------------  ---------------------------------
SUB1234  SOFTWARE QUALITY AND PROCESS MANAGEMENT    AUPAS AMERICAN UNIVERSITY PROGRAM
SUB2234  SOFTWARE QUALITY AND PROCESS MANAGEMENT 1  AUPAS AMERICAN UNIVERSITY PROGRAM
SUB3234  SOFTWARE QUALITY AND PROCESS MANAGEMENT 2  AUPAS AMERICAN UNIVERSITY PROGRAM
```

Table Result

```<code>ID       SUBJECT  RESULT
-------  -------  ------
STU0001  SUB1234  NULL
</code>```

Desired Output:

Get SUB2234 and SUB3234 from table Subject when ID = STU0001 and Course = AUPAS AMERICAN UNIVERSITY PROGRAM.

Using query below, I only able to retrieve non-duplicate data.

```<code>SELECT SUB.ID, SUB.NAME
FROM SUBJECT SUB LEFT JOIN
     RESULT RES
     ON RES.SUBJECT = SUB.ID
WHERE RES.SUBJECT IS NULL;
</code>```

答:
think this is what you're after</p>

```<code>select res.id as student, sub.id as 'subject'
from @result res, @subject sub
where sub.id != res.subj
</code>```

Body:
I wish to retrieve non-duplicate data with criteria based on 2 tables in SQL Server database.

Table Subject

ID       NAME                                       COURSE
-------  -----------------------------------------  ---------------------------------
SUB1234  SOFTWARE QUALITY AND PROCESS MANAGEMENT    AUPAS AMERICAN UNIVERSITY PROGRAM
SUB2234  SOFTWARE QUALITY AND PROCESS MANAGEMENT 1  AUPAS AMERICAN UNIVERSITY PROGRAM
SUB3234  SOFTWARE QUALITY AND PROCESS MANAGEMENT 2  AUPAS AMERICAN UNIVERSITY PROGRAM

Table Result

ID       SUBJECT  RESULT
-------  -------  ------
STU0001  SUB1234  NULL

Desired Output:

Get SUB2234 and SUB3234 from table Subject when ID = STU0001 and Course = AUPAS AMERICAN UNIVERSITY PROGRAM.

Using query below, I only able to retrieve non-duplicate data.

SELECT SUB.ID, SUB.NAME
FROM SUBJECT SUB LEFT JOIN
     RESULT RES
     ON RES.SUBJECT = SUB.ID
WHERE RES.SUBJECT IS NULL;

Body:
think this is what you're after

select res.id as student, sub.id as 'subject'
from @result res, @subject sub
where sub.id != res.subj


问:
Perl: Need assistance converting if-elsif-else to something simpler
I've been reading up on dispatch tables and I get the general idea of how they work, but I'm having some trouble taking what I see online and applying the concept to some code I originally wrote as an ugly mess of if-elsif-else statements.

I have options parsing configured by using GetOpt::Long, and in turn, those options set a value in the %OPTIONS hash, depending on the option used.

Taking the below code as an example... (UPDATED WITH MORE DETAIL)

```<code>use     5.008008;
use     strict;
use     warnings;
use     File::Basename qw(basename);
use     Getopt::Long qw(HelpMessage VersionMessage :config posix_default require_order no_ignore_case auto_version auto_help);

my $EMPTY      => q{};

sub usage
{
    my $PROG = basename($0);
    print {*STDERR} $_ for @_;
    print {*STDERR} "Try $PROG --help for more information.\n";
    exit(1);
}

sub process_args
{
    my %OPTIONS;

    $OPTIONS{host}              = $EMPTY;
    $OPTIONS{bash}              = 0;
    $OPTIONS{nic}               = 0;
    $OPTIONS{nicName}           = $EMPTY;
    $OPTIONS{console}           = 0;
    $OPTIONS{virtual}           = 0;
    $OPTIONS{cmdb}              = 0;
    $OPTIONS{policyid}          = 0;
    $OPTIONS{showcompliant}     = 0;
    $OPTIONS{backup}            = 0;
    $OPTIONS{backuphistory}     = 0;
    $OPTIONS{page}              = $EMPTY;

    GetOptions
      (
        'host|h=s'              => \$OPTIONS{host}               ,
        'use-bash-script'       => \$OPTIONS{bash}               ,
        'remote-console|r!'     => \$OPTIONS{console}            ,
        'virtual-console|v!'    => \$OPTIONS{virtual}            ,
        'nic|n!'                => \$OPTIONS{nic}                ,
        'nic-name|m=s'          => \$OPTIONS{nicName}            ,
        'cmdb|d!'               => \$OPTIONS{cmdb}               ,
        'policy|p=i'            => \$OPTIONS{policyid}           ,
        'show-compliant|c!'     => \$OPTIONS{showcompliant}      ,
        'backup|b!'             => \$OPTIONS{backup}             ,
        'backup-history|s!'     => \$OPTIONS{backuphistory}      ,
        'page|g=s'              => \$OPTIONS{page}               ,
        'help'                  => sub      { HelpMessage(-exitval => 0, -verbose ->1)     },
        'version'               => sub      { VersionMessage()  },
      ) or usage;

    if ($OPTIONS{host} eq $EMPTY)
    {
        print {*STDERR} "ERROR: Must specify a host with -h flag\n";
        HelpMessage;
    }

    sanity_check_options(\%OPTIONS);

    # Parse anything else on the command line and throw usage
    for (@ARGV)
    {
        warn "Unknown argument: $_\n";
        HelpMessage;
    }

    return {%OPTIONS};
}

sub sanity_check_options
{
    my $OPTIONS     = shift;

    if (($OPTIONS->{console}) and ($OPTIONS->{virtual}))
    {
        print "ERROR: Cannot use flags -r and -v together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -r and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -r and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -r and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{virtual}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -v and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -v and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -v and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{backup}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -b and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{backup}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -b and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{nic}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -n and -d together\n";
        HelpMessage;
    }

    if (($OPTIONS->{policyid} != 0) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -p without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{showcompliant}) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -c without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{backuphistory}) and not ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flag -s without also specifying -b\n";
        HelpMessage;
    }

    if (($OPTIONS->{nicName}) and not ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flag -m without also specifying -n\n";
        HelpMessage;
    }

    return %{$OPTIONS};
}
</code>```

I'd like to turn the above code into a dispatch table, but can't figure out how to do it.

Any help is appreciated.

答:
You can use a dispatch table if there are a lot of options. I would build that table programmatically. It might not be the best option here, but it works and the configuration is more readable than your elsif construct.

```<code>use strict;
use warnings;
use Ref::Util::XS 'is_arrayref';    # or Ref::Util

sub create_key {
    my $input = shift;

    # this would come from somewhere else, probably the Getopt config
    my @opts = qw( host bash nic nicName console virtual cmdb
        policyid showcompliant backup backuphistory page );

    # this is to cover the configuration with easier syntax
    $input = { map { $_ => 1 } @{$input} }
        if is_arrayref($input);

    # options are always prefilled with false values
    return join q{}, map { $input->{$_} ? 1 : 0 }
        sort @opts;
}

my %forbidden_combinations = (
    map { create_key( $_->[0] ) => $_->[1] } (
        [ [qw( console virtual )] => q{Cannot use flags -r and -v together} ],
        [ [qw( console cmdb )]    => q{Cannot use flags -r and -d together} ],
        [ [qw( console backup )]  => q{Cannot use flags -r and -b together} ],
        [ [qw( console nic )]     => q{Cannot use flags -r and -n together} ],
    )
);

p %forbidden_combinations; # from Data::Printer
</code>```

The output of the p function is the dispatch table.

```<code>{
    00101   "Cannot use flags -r and -v together",
    00110   "Cannot use flags -r and -n together",
    01100   "Cannot use flags -r and -d together",
    10100   "Cannot use flags -r and -b together"
}
</code>```

As you can see, we've sorted all the options ascii-betically to use them as keys. That way, you could in theory build all kinds of combinations like exclusive options.

Let's take a look at the configuration itself.

```<code>my %forbidden_combinations = (
    map { create_key( $_->[0] ) => $_->[1] } (
        [ [qw( console virtual )] => q{Cannot use flags -r and -v together} ],
        # ...
    )
);
</code>```

We use a list of array references. Each entry is on one line and contains two pieces of information. Using the fat comma => makes it easy to read. The first part, which is much like a key in a hash, is the combination. It's a list of fields that should not occur together. The second element in the array ref is the error message. I've removed all the recurring elements, like the newline, to make it easier to change how and where the error can be displayed.

The map around this list of combination configuration runs the options through our create_key function, which translates it to a simple bitmap-style string. We assign all of it to a hash of that map and the error message.

Inside create_key, we check if it was called with an array reference as its argument. If that's the case, the call was for building the table, and we convert it to a hash reference so we have a proper map to look stuff up in. We know that the %OPTIONS always contains all the keys that exist, and that those are pre-filled with values that all evaluate to false. We can harness that convert the truthiness of those values to 1 or 0, which then builds our key.

We will see in a moment why that is useful.

Now how do we use this?

```<code>sub HelpMessage { exit; }; # as a placeholder

# set up OPTIONS
my %OPTIONS = (
    host          => q{},
    bash          => 0,
    nic           => 0,
    nicName       => q{},
    console       => 0,
    virtual       => 0,
    cmdb          => 0,
    policyid      => 0,
    showcompliant => 0,
    backup        => 0,
    backuphistory => 0,
    page          => q{},
);

# read options with Getopt::Long ...
$OPTIONS{console} = $OPTIONS{virtual} = 1;

# ... and check for wrong invocations
if ( exists $forbidden_combinations{ my $key = create_key($OPTIONS) } ) {
    warn "ERROR: $forbidden_combinations{$key}\n";
    HelpMessage;
}
</code>```

All we need to do now is get the $OPTIONS hash reference from Getopt::Long, and pass it through our create_key function to turn it into the map string. Then we can simply see if that key exists in our %forbidden_combinations dispatch table and show the corresponding error message.

Advantages of this approach

If you want to add more parameters, all you need to do is include them in @opts. In a full implementation that would probably be auto-generated from the config for the Getopt call. The keys will change under the hood, but since that is abstracted away you don't have to care.

Furthermore, this is easy to read. The create_key aside, the actual dispatch table syntax is quite concise and even has documentary character.

Disadvantages of this approach

There is a lot of programmatic generation going on for just a single call. It's certainly not the most efficient way to do it.

To take this further, you can write functions that auto-generate entries for certain scenarios.

I suggest you take a look at the second chapter in Mark Jason Dominus' excellent book Higher-Order Perl, which is available for free as a PDF.

Body:
I've been reading up on dispatch tables and I get the general idea of how they work, but I'm having some trouble taking what I see online and applying the concept to some code I originally wrote as an ugly mess of if-elsif-else statements.

I have options parsing configured by using GetOpt::Long, and in turn, those options set a value in the %OPTIONS hash, depending on the option used.

Taking the below code as an example... (UPDATED WITH MORE DETAIL)

use     5.008008;
use     strict;
use     warnings;
use     File::Basename qw(basename);
use     Getopt::Long qw(HelpMessage VersionMessage :config posix_default require_order no_ignore_case auto_version auto_help);

my $EMPTY      => q{};

sub usage
{
    my $PROG = basename($0);
    print {*STDERR} $_ for @_;
    print {*STDERR} "Try $PROG --help for more information.\n";
    exit(1);
}

sub process_args
{
    my %OPTIONS;

    $OPTIONS{host}              = $EMPTY;
    $OPTIONS{bash}              = 0;
    $OPTIONS{nic}               = 0;
    $OPTIONS{nicName}           = $EMPTY;
    $OPTIONS{console}           = 0;
    $OPTIONS{virtual}           = 0;
    $OPTIONS{cmdb}              = 0;
    $OPTIONS{policyid}          = 0;
    $OPTIONS{showcompliant}     = 0;
    $OPTIONS{backup}            = 0;
    $OPTIONS{backuphistory}     = 0;
    $OPTIONS{page}              = $EMPTY;

    GetOptions
      (
        'host|h=s'              => \$OPTIONS{host}               ,
        'use-bash-script'       => \$OPTIONS{bash}               ,
        'remote-console|r!'     => \$OPTIONS{console}            ,
        'virtual-console|v!'    => \$OPTIONS{virtual}            ,
        'nic|n!'                => \$OPTIONS{nic}                ,
        'nic-name|m=s'          => \$OPTIONS{nicName}            ,
        'cmdb|d!'               => \$OPTIONS{cmdb}               ,
        'policy|p=i'            => \$OPTIONS{policyid}           ,
        'show-compliant|c!'     => \$OPTIONS{showcompliant}      ,
        'backup|b!'             => \$OPTIONS{backup}             ,
        'backup-history|s!'     => \$OPTIONS{backuphistory}      ,
        'page|g=s'              => \$OPTIONS{page}               ,
        'help'                  => sub      { HelpMessage(-exitval => 0, -verbose ->1)     },
        'version'               => sub      { VersionMessage()  },
      ) or usage;

    if ($OPTIONS{host} eq $EMPTY)
    {
        print {*STDERR} "ERROR: Must specify a host with -h flag\n";
        HelpMessage;
    }

    sanity_check_options(\%OPTIONS);

    # Parse anything else on the command line and throw usage
    for (@ARGV)
    {
        warn "Unknown argument: $_\n";
        HelpMessage;
    }

    return {%OPTIONS};
}

sub sanity_check_options
{
    my $OPTIONS     = shift;

    if (($OPTIONS->{console}) and ($OPTIONS->{virtual}))
    {
        print "ERROR: Cannot use flags -r and -v together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -r and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -r and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{console}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -r and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{virtual}) and ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flags -v and -b together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -v and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{virtual}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -v and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{backup}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -b and -d together\n";
        HelpMessage;
    }
    elsif (($OPTIONS->{backup}) and ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flags -b and -n together\n";
        HelpMessage;
    }

    if (($OPTIONS->{nic}) and ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flags -n and -d together\n";
        HelpMessage;
    }

    if (($OPTIONS->{policyid} != 0) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -p without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{showcompliant}) and not ($OPTIONS->{cmdb}))
    {
        print "ERROR: Cannot use flag -c without also specifying -d\n";
        HelpMessage;
    }

    if (($OPTIONS->{backuphistory}) and not ($OPTIONS->{backup}))
    {
        print "ERROR: Cannot use flag -s without also specifying -b\n";
        HelpMessage;
    }

    if (($OPTIONS->{nicName}) and not ($OPTIONS->{nic}))
    {
        print "ERROR: Cannot use flag -m without also specifying -n\n";
        HelpMessage;
    }

    return %{$OPTIONS};
}

I'd like to turn the above code into a dispatch table, but can't figure out how to do it.

Any help is appreciated.

Body:
You can use a dispatch table if there are a lot of options. I would build that table programmatically. It might not be the best option here, but it works and the configuration is more readable than your elsif construct.

use strict;
use warnings;
use Ref::Util::XS 'is_arrayref';    # or Ref::Util

sub create_key {
    my $input = shift;

    # this would come from somewhere else, probably the Getopt config
    my @opts = qw( host bash nic nicName console virtual cmdb
        policyid showcompliant backup backuphistory page );

    # this is to cover the configuration with easier syntax
    $input = { map { $_ => 1 } @{$input} }
        if is_arrayref($input);

    # options are always prefilled with false values
    return join q{}, map { $input->{$_} ? 1 : 0 }
        sort @opts;
}

my %forbidden_combinations = (
    map { create_key( $_->[0] ) => $_->[1] } (
        [ [qw( console virtual )] => q{Cannot use flags -r and -v together} ],
        [ [qw( console cmdb )]    => q{Cannot use flags -r and -d together} ],
        [ [qw( console backup )]  => q{Cannot use flags -r and -b together} ],
        [ [qw( console nic )]     => q{Cannot use flags -r and -n together} ],
    )
);

p %forbidden_combinations; # from Data::Printer

The output of the p function is the dispatch table.

{
    00101   "Cannot use flags -r and -v together",
    00110   "Cannot use flags -r and -n together",
    01100   "Cannot use flags -r and -d together",
    10100   "Cannot use flags -r and -b together"
}

As you can see, we've sorted all the options ascii-betically to use them as keys. That way, you could in theory build all kinds of combinations like exclusive options.

Let's take a look at the configuration itself.

my %forbidden_combinations = (
    map { create_key( $_->[0] ) => $_->[1] } (
        [ [qw( console virtual )] => q{Cannot use flags -r and -v together} ],
        # ...
    )
);

We use a list of array references. Each entry is on one line and contains two pieces of information. Using the fat comma => makes it easy to read. The first part, which is much like a key in a hash, is the combination. It's a list of fields that should not occur together. The second element in the array ref is the error message. I've removed all the recurring elements, like the newline, to make it easier to change how and where the error can be displayed.

The map around this list of combination configuration runs the options through our create_key function, which translates it to a simple bitmap-style string. We assign all of it to a hash of that map and the error message.

Inside create_key, we check if it was called with an array reference as its argument. If that's the case, the call was for building the table, and we convert it to a hash reference so we have a proper map to look stuff up in. We know that the %OPTIONS always contains all the keys that exist, and that those are pre-filled with values that all evaluate to false. We can harness that convert the truthiness of those values to 1 or 0, which then builds our key.

We will see in a moment why that is useful.

Now how do we use this?

sub HelpMessage { exit; }; # as a placeholder

# set up OPTIONS
my %OPTIONS = (
    host          => q{},
    bash          => 0,
    nic           => 0,
    nicName       => q{},
    console       => 0,
    virtual       => 0,
    cmdb          => 0,
    policyid      => 0,
    showcompliant => 0,
    backup        => 0,
    backuphistory => 0,
    page          => q{},
);

# read options with Getopt::Long ...
$OPTIONS{console} = $OPTIONS{virtual} = 1;

# ... and check for wrong invocations
if ( exists $forbidden_combinations{ my $key = create_key($OPTIONS) } ) {
    warn "ERROR: $forbidden_combinations{$key}\n";
    HelpMessage;
}

All we need to do now is get the $OPTIONS hash reference from Getopt::Long, and pass it through our create_key function to turn it into the map string. Then we can simply see if that key exists in our %forbidden_combinations dispatch table and show the corresponding error message.

Advantages of this approach

If you want to add more parameters, all you need to do is include them in @opts. In a full implementation that would probably be auto-generated from the config for the Getopt call. The keys will change under the hood, but since that is abstracted away you don't have to care.

Furthermore, this is easy to read. The create_key aside, the actual dispatch table syntax is quite concise and even has documentary character.

Disadvantages of this approach

There is a lot of programmatic generation going on for just a single call. It's certainly not the most efficient way to do it.

To take this further, you can write functions that auto-generate entries for certain scenarios.

I suggest you take a look at the second chapter in Mark Jason Dominus' excellent book Higher-Order Perl, which is available for free as a PDF.


问:
Why does EF DetectChanges() actually modify objects?
Up until now I've let EF ChangeTracker do whatever it needs to do behind the scenes, but I'm here forced to intervene because it's actually modifying the properties on my objects:

```<code>db.Configuration.AutoDetectChangesEnabled = false;
var loadedEntity = db.SomeEntity.Include(e => e.SomeChildren);

//modify the loadedEntity in some way

//if I debug and inspect 'loadedEntity' here, everything looks good!

db.ChangeTracker.DetectChanges();

//if I inspect here, the properties inside 'loadedEntity' have changed!
</code>```

In my case, EF has for some reason nulled a foreign key on one of the children which is causing me problems. This key was correct in debug before DetectChanges() was called.

Is what's showing in debug incorrect, or does DetectChanges() actually modify the object behind the scenes? It's not clear why this is happening, so I'm trying to gain an understanding.

I previously assumed ChangeTracker simply kept its own list/values of original and new properties and figured it what needed to do when SaveChanges() was called? I wouldn't expect the tracker to modify the objects themselves.

```<code>(Entity Framework 6.1.3)
</code>```

答:
Let me guess.

There are entities referenced by SomeChildern and I think Lazy loading is enabled in the application. According to documentation header of Include it is returning IQueriable so you need to call .ToList or .Load after Include so that the elements will be fetched from the database.

```<code>DbContext.Entry(someEntity).Include(e => e.SomeChildren).Load();
</code>```

Body:
Up until now I've let EF ChangeTracker do whatever it needs to do behind the scenes, but I'm here forced to intervene because it's actually modifying the properties on my objects:

db.Configuration.AutoDetectChangesEnabled = false;
var loadedEntity = db.SomeEntity.Include(e => e.SomeChildren);

//modify the loadedEntity in some way

//if I debug and inspect 'loadedEntity' here, everything looks good!

db.ChangeTracker.DetectChanges();

//if I inspect here, the properties inside 'loadedEntity' have changed!

In my case, EF has for some reason nulled a foreign key on one of the children which is causing me problems. This key was correct in debug before DetectChanges() was called.

Is what's showing in debug incorrect, or does DetectChanges() actually modify the object behind the scenes? It's not clear why this is happening, so I'm trying to gain an understanding.

I previously assumed ChangeTracker simply kept its own list/values of original and new properties and figured it what needed to do when SaveChanges() was called? I wouldn't expect the tracker to modify the objects themselves.

(Entity Framework 6.1.3)

Body:
Let me guess.

There are entities referenced by SomeChildern and I think Lazy loading is enabled in the application. According to documentation header of Include it is returning IQueriable so you need to call .ToList or .Load after Include so that the elements will be fetched from the database.

DbContext.Entry(someEntity).Include(e => e.SomeChildren).Load();


问:
Can't build Angular 5 with AOT systemjs
I've been looking for a solution for my problem with no luck. So maybe someone can help me with it.

I'm upgrading from ng 4.4.4 to 5.0.1 everything seems to work properly in JIT mode but when I try to compile to AOT mode it doesn't work.

The error says that module app.module.ngfactory can not be found and it seems to make sense since it is not being generated for some reason.

These are my files:

main-aot.ts

```<code>import { platformBrowser } from '@angular/platform-browser';
import { enableProdMode } from '@angular/core';
import { AppModuleNgFactory } from '../Scripts/dist/aot/tsScripts/app.module.ngfactory';

enableProdMode();
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);
</code>```

tsconfig-aot.json

```<code>{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2015",
      "dom"
    ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "Scripts/dist/aot",
    "typeRoots": [
      "node_modules/@types/"
    ]
  },
  "files": [
    "tsScripts/app.module.ts",
    "tsScripts/main-aot.ts"
  ],
  "angularCompilerOptions": {
    "genDir": "Scripts/dist/aot",
    "skipMetadataEmit": true,
    "preserveWhitespaces": false
  }
}
</code>```

And the command I'm using to compile is:

```<code>ngc -p tsconfig-aot.json && rollup -c rollup-config.js
</code>```

Can anyone help me?

Thanks in advance

答: Finally, I moved my project structure to use angular-cli and everything worked again.</p>

Title: Can't build Angular 5 with AOT systemjs

Body:
I've been looking for a solution for my problem with no luck. So maybe someone can help me with it.

I'm upgrading from ng 4.4.4 to 5.0.1 everything seems to work properly in JIT mode but when I try to compile to AOT mode it doesn't work.

The error says that module app.module.ngfactory can not be found and it seems to make sense since it is not being generated for some reason.

These are my files:

main-aot.ts

import { platformBrowser } from '@angular/platform-browser';
import { enableProdMode } from '@angular/core';
import { AppModuleNgFactory } from '../Scripts/dist/aot/tsScripts/app.module.ngfactory';

enableProdMode();
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);

tsconfig-aot.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2015",
      "dom"
    ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "Scripts/dist/aot",
    "typeRoots": [
      "node_modules/@types/"
    ]
  },
  "files": [
    "tsScripts/app.module.ts",
    "tsScripts/main-aot.ts"
  ],
  "angularCompilerOptions": {
    "genDir": "Scripts/dist/aot",
    "skipMetadataEmit": true,
    "preserveWhitespaces": false
  }
}

And the command I'm using to compile is:

ngc -p tsconfig-aot.json && rollup -c rollup-config.js

Can anyone help me?

Thanks in advance


问:
Java script Popup window is opening with fullscreen in Windows10+IE Edge
In Windows10 with IE edge when I want to open a popup with below code its always showing full screen pop up window.Ideally by default 'fullscreen=no' but same code is working in windows7 with IE11.

Sample code :

```<code>myaddress=url //to for popupwindows
win = window.open(myaddress,"test","width=500,height=500,location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=1");
</code>```

As I am new to javascript could you please help me on this

Thanks,
SPradhan

答:
Thanks for your suggestions and help.Now I am able to resolve the issue.

function test(){
  window.open('google.com',"test","width=500,height=500,location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=1,fullscreen=no");
}

fullscreen=no works perfectly in Windows10 + IE Edge

Thanks & Regards,
SPRADHAN

Body:
In Windows10 with IE edge when I want to open a popup with below code its always showing full screen pop up window.Ideally by default 'fullscreen=no' but same code is working in windows7 with IE11.

Sample code :

myaddress=url //to for popupwindows
win = window.open(myaddress,"test","width=500,height=500,location=no,status=no,menubar=no,toolbar=no,resizable=no,scrollbars=1");

As I am new to javascript could you please help me on this

Thanks,
SPradhan


答:
try like this :</p>

```<code>this.serviceA.getOrg()
    .flatMap((org) => {
        console.log('org', org);
        return this.serviceB.getOrgType(org.id)
    })
    .subscribe((type) => {
        console.log('type', type);
    });
</code>```

Title: Angular: How to use result of `.subscribe()` in consequent Observable

Body:
Angular2: I want to use the result of .subscribe() in a consequent observable.

This is in order to use the id from the parent subscribe in the nested subscribe.

I've tried using .switchMap() first, but this doesn't seem to work.

This is my attempt:

this.serviceA.getOrg()
    .switchMap(org => this.serviceB.getOrgType(org.id))
    .subscribe(type => {
        console.log(type);
});

Body:
try like this :

this.serviceA.getOrg()
    .flatMap((org) => {
        console.log('org', org);
        return this.serviceB.getOrgType(org.id)
    })
    .subscribe((type) => {
        console.log('type', type);
    });


问:
How to add git to PATH (Bash on Windows)
I am using Bash on Ubuntu on Windows, and I installed git. How do I add git to my PATH?</p>

答:
The solution assumes u want to access git inside WSL in your Windows Environment

Check this Out
https://github.com/ardevd/gitwrap/releases

This wrapper pipes output from WSL to windows and also works on android studio claimed by the developer

This Wrapper was not developed by me
for any issues plz post on the github page


问:
Check to see if a key exists in a query string - htaccess
my url has query string(s) as follows:

```<code>?v=11&icid=someid&near=far
OR
?icid=some&v=11&near=far
OR
?icid=some&near=far&v=11
OR
?v=11
OR
There may be more but "v" exists
</code>```

in htaccess, how do I do the following please?

if key "v" exists
and
the value is not [1-11]
redirect to my site

so far I've got the following:

sample url: http://www.mysite.com/2010/01/17/breaking-news/? (one of the above QS's)

RewriteCond %{QUERY_STRING} v

RewriteCond %{QUERY_STRING} v=([^1-11]+)

RewriteRule ([1000-9999]+)/([^/]+)/([^/]+)/([^/]+)/?([0-99]+)?$ http: // %{HTTP_HOST}/? [R,L]

Any help on this is much appreciated.

Thanks,

L

答:
```<code>RewriteCond %{QUERY_STRING} v=([^&]+)
RewriteCond %1 !^(?:\d|11)$
RewiteRule ... stuff
</code>```

Body:
my url has query string(s) as follows:

?v=11&icid=someid&near=far
OR
?icid=some&v=11&near=far
OR
?icid=some&near=far&v=11
OR
?v=11
OR
There may be more but "v" exists

in htaccess, how do I do the following please?

if key "v" exists
and
the value is not [1-11]
redirect to my site

so far I've got the following:

sample url: http://www.mysite.com/2010/01/17/breaking-news/? (one of the above QS's)

RewriteCond %{QUERY_STRING} v

RewriteCond %{QUERY_STRING} v=([^1-11]+)

RewriteRule ([1000-9999]+)/([^/]+)/([^/]+)/([^/]+)/?([0-99]+)?$ http: // %{HTTP_HOST}/? [R,L]

Any help on this is much appreciated.

Thanks,

L


问:
Equivalent Java Config for spring messaging xml config
I am trying to implements spring batch remote chunking using rabbitMQ. I following this link

what are the equivalent java config for this

```<code><int:channel id="requests"/>
<int:channel id="replies"/>

<int-jms:message-driven-channel-adapter id="jmsIn"
    destination-name="requests"
    channel="requests"/>

<int-jms:outbound-channel-adapter id="outgoingReplies"
    destination-name="replies"
    channel="replies">
</int-jms:outbound-channel-adapter>
</code>```

答:
for INBOUND:

```<code>@Bean(AMQP_INPUT_CHANNEL)
public MessageChannel amqpInputChannel() {
    return new DirectChannel();
}

@Bean
public AmqpInboundChannelAdapter inbound(SimpleMessageListenerContainer listenerContainer,
                                         @Qualifier(AMQP_INPUT_CHANNEL) MessageChannel channel,
                                         Jackson2JsonMessageConverter messageConverter) {
    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
    adapter.setMessageConverter(messageConverter);
    adapter.setOutputChannel(channel);
    return adapter;
}

@Bean
public SimpleMessageListenerContainer container(ConnectionFactory connectionFactory) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setConcurrentConsumers(5);
    container.setQueueNames("Queue_Name");
    return container;
}
</code>```

For OUTBOUND:

```<code>@Bean
public MessageChannel amqpOutboundChannel() {
    return new DirectChannel();
}

@Bean
@ServiceActivator(inputChannel = "amqpOutboundChannel")
public AmqpOutboundEndpoint amqpOutbound(AmqpTemplate amqpTemplate) {
    AmqpOutboundEndpoint outbound = new AmqpOutboundEndpoint(amqpTemplate);
    outbound.setRoutingKey("ERROR-QUEUE");
    return outbound;
}

@MessagingGateway(defaultRequestChannel = "amqpOutboundChannel")
public interface BatchServiceMessagingGateway {
    void sendMessage(String data);
}
</code>```

Body:
I am trying to implements spring batch remote chunking using rabbitMQ. I following this link

what are the equivalent java config for this

<int:channel id="requests"/>
<int:channel id="replies"/>

<int-jms:message-driven-channel-adapter id="jmsIn"
    destination-name="requests"
    channel="requests"/>

<int-jms:outbound-channel-adapter id="outgoingReplies"
    destination-name="replies"
    channel="replies">
</int-jms:outbound-channel-adapter>

Body:
for INBOUND:

@Bean(AMQP_INPUT_CHANNEL)
public MessageChannel amqpInputChannel() {
    return new DirectChannel();
}

@Bean
public AmqpInboundChannelAdapter inbound(SimpleMessageListenerContainer listenerContainer,
                                         @Qualifier(AMQP_INPUT_CHANNEL) MessageChannel channel,
                                         Jackson2JsonMessageConverter messageConverter) {
    AmqpInboundChannelAdapter adapter = new AmqpInboundChannelAdapter(listenerContainer);
    adapter.setMessageConverter(messageConverter);
    adapter.setOutputChannel(channel);
    return adapter;
}

@Bean
public SimpleMessageListenerContainer container(ConnectionFactory connectionFactory) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setConcurrentConsumers(5);
    container.setQueueNames("Queue_Name");
    return container;
}

For OUTBOUND:

@Bean
public MessageChannel amqpOutboundChannel() {
    return new DirectChannel();
}

@Bean
@ServiceActivator(inputChannel = "amqpOutboundChannel")
public AmqpOutboundEndpoint amqpOutbound(AmqpTemplate amqpTemplate) {
    AmqpOutboundEndpoint outbound = new AmqpOutboundEndpoint(amqpTemplate);
    outbound.setRoutingKey("ERROR-QUEUE");
    return outbound;
}

@MessagingGateway(defaultRequestChannel = "amqpOutboundChannel")
public interface BatchServiceMessagingGateway {
    void sendMessage(String data);
}


问:
Organize a groupBy within another groupBy using Collection in CakePHP
I have the following array and I would like to be able to organize it through collection

```<code>$collection =  Collection($total);
$filter = $collection->groupBy('date_general')->toArray();

[2017-11-14] => Array
    (
        [0] => Array
            (
                [status] => pending
                [date_general] => 2017-11-14
                [user_id] => 164
            )

        [1] => Array
            (
                [status] => pending
                [date_general] => 2017-11-14
                [user_id] => 112
            )
    )
</code>```

Up to this point I already have the array organized by dates. Now within each date I need to organize it by user, that is to say that it is:

```<code>[2017-11-14] => Array
    (
        [164] => Array
            (
                [0] => Array
                    (
                        [status] => pending
                        [date_general] => 2017-11-14
                        [user_id] => 164
                    )
            )
        [112] => Array
            (
               [0] => Array
                (
                    [status] => pending
                    [date_general] => 2017-11-14
                    [user_id] => 112
                )
            )
    )
</code>```

答:
You'll have to process each date group and individually group their contents.

```<code>$collection = collection($total)
    ->groupBy('date_general')
    ->map(function ($data) {
        return collection($data)->groupBy('user_id')->toArray();
    });
</code>```

See also

Cookbook > Collections

Body:
I have the following array and I would like to be able to organize it through collection

$collection =  Collection($total);
$filter = $collection->groupBy('date_general')->toArray();

[2017-11-14] => Array
    (
        [0] => Array
            (
                [status] => pending
                [date_general] => 2017-11-14
                [user_id] => 164
            )

        [1] => Array
            (
                [status] => pending
                [date_general] => 2017-11-14
                [user_id] => 112
            )
    )

Up to this point I already have the array organized by dates. Now within each date I need to organize it by user, that is to say that it is:

[2017-11-14] => Array
    (
        [164] => Array
            (
                [0] => Array
                    (
                        [status] => pending
                        [date_general] => 2017-11-14
                        [user_id] => 164
                    )
            )
        [112] => Array
            (
               [0] => Array
                (
                    [status] => pending
                    [date_general] => 2017-11-14
                    [user_id] => 112
                )
            )
    )

Body:
You'll have to process each date group and individually group their contents.

$collection = collection($total)
    ->groupBy('date_general')
    ->map(function ($data) {
        return collection($data)->groupBy('user_id')->toArray();
    });

See also

Cookbook > Collections


问:
Descendants (MDX) of root member
Environment: SSAS v12.

Why the following function

DESCENDANTS([Dim1].[Hier1].[(All)])

returns only [Dim1].[Hier1].[(All)] ?

Expectation is to return the root member and all it's descendants.

Or how to achieve that?

PS Specifying [ , Level_Expression [ ,Desc_Flag ] ] does not help...

Many thanks in advance.

答:
You can specify how far down you want to go, whether it's to a specific level or to the leaves:</p>

```<code>DESCENDANTS([Dim1].[Hier1].CurrentMember, [Dim1].[Hier1].[Hier1], LEAVES)
</code>```

Title: Descendants (MDX) of root member

Body:
You can specify how far down you want to go, whether it's to a specific level or to the leaves:

DESCENDANTS([Dim1].[Hier1].CurrentMember, [Dim1].[Hier1].[Hier1], LEAVES)


问:
jquery radio button change event not working
I want to display some form when the specific radio button is checked and to hide it when user selects other radio button

```<code><div class="col-sm-6" id="addresses">
  <input type="radio" name="deco_request[address]" value="value["id"]"> Some address<br>
  <input type="radio" name="deco_request[address]" value="other" id="other-address"> Other Address<br>
</div>
</code>```

js code:

```<code>$("#other-address").on("change", function() {
  if ($("#other-address").is(':checked')) {
    return $("#new-address").show();
  } else {
    return $("#new-address").hide();
  }
});
</code>```

from what I see the change event is not firing up, I also tried click event but didn't have any success with it too, also I noticed when I check the radio button no checked attributes is added but .is(':checked') returns true

答:
you don't need return and use prop to check

PS: your check syntax is valid but sometimes is not working properly

```<code>$("#other-address").on("change", function() {
  if ($("#other-address").prop("checked", true)) {
     $("#new-address").show();
  } else {
     $("#new-address").hide();
  }
});
</code>```

Body:
I want to display some form when the specific radio button is checked and to hide it when user selects other radio button

  <input type="radio" name="deco_request[address]" value="value["id"]"> Some address

  <input type="radio" name="deco_request[address]" value="other" id="other-address"> Other Address

js code:

$("#other-address").on("change", function() {
  if ($("#other-address").is(':checked')) {
    return $("#new-address").show();
  } else {
    return $("#new-address").hide();
  }
});

from what I see the change event is not firing up, I also tried click event but didn't have any success with it too, also I noticed when I check the radio button no checked attributes is added but .is(':checked') returns true

Body:
you don't need return and use prop to check

PS: your check syntax is valid but sometimes is not working properly

$("#other-address").on("change", function() {
  if ($("#other-address").prop("checked", true)) {
     $("#new-address").show();
  } else {
     $("#new-address").hide();
  }
});


问:
How to disable UISlider without making image gray
```<code>[_slider setThumbImage:[UIImage imageNamed:@"disableImage"]  forState:UIControlStateDisabled];
</code>```

The method does't make sense, because when i set _slider.enable=NO;
the disableImage become a little bit gray.

Is there any attribute just like adjustsImageWhenDisabled to forbid color fading？

答:
The .enable property influence whether the button does anything or not.

You have several choices to disable/hide your UISlider.

You can :

Use hidden to make it invisible

Set the .alpha between 0.0 and 1.0

Disable User Interaction

Body:
[_slider setThumbImage:[UIImage imageNamed:@"disableImage"]  forState:UIControlStateDisabled];

The method does't make sense, because when i set _slider.enable=NO;
the disableImage become a little bit gray.

Is there any attribute just like adjustsImageWhenDisabled to forbid color fading？


问:
Angular: How to use result of `.subscribe()` in consequent Observable
Angular2: I want to use the result of .subscribe() in a consequent observable.

This is in order to use the id from the parent subscribe in the nested subscribe.

I've tried using .switchMap() first, but this doesn't seem to work.

This is my attempt:

```<code>this.serviceA.getOrg()
    .switchMap(org => this.serviceB.getOrgType(org.id))
    .subscribe(type => {
        console.log(type);
});
</code>```

答:
Try using .flatMap() instead:

```<code>this.serviceA.getOrg()
    .flatMap((org) => this.serviceB.getOrgType(org.id))
    .subscribe((type) => {
        console.log(type);
});
</code>```

Body:
Try using .flatMap() instead:

this.serviceA.getOrg()
    .flatMap((org) => this.serviceB.getOrgType(org.id))
    .subscribe((type) => {
        console.log(type);
});