问:
ConstraintLayout - centering views with next to each other vertically or horizontally
How to center align 3 buttons with next to each other vertically using ConstraintLayout?

To be clear, i want to convert this simple layout structure into flat UI using ConstraintLayout

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>
</FrameLayout>
</code>```

I have obtained a nearest solution as follows

```<code><android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/button2"
    />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="259dp"
    app:layout_constraintBottom_toTopOf="@+id/button3"
    app:layout_constraintTop_toBottomOf="@+id/button"
    app:layout_constraintRight_toRightOf="parent"/>

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    app:layout_constraintLeft_toLeftOf="parent"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="307dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button2"
    app:layout_constraintRight_toRightOf="parent"/>

 </android.support.constraint.ConstraintLayout>
</code>```

But clearly, you can see that the obtained output does not match to the required one. i don't want any margin or space in between the 3 buttons, all i want is to center align those 3 buttons next to each other vertically just like they are in a LinearLayout which has a vertical orientation.

答:
By Android Studio's 'Layout Editor'

drag and drop three buttons into the Android Studio's 'Layout Editor'

Select those buttons together by dragging mouse

Pack them vertically using the 'pack' button in 'Layout Editor'

Align them center horizontally using 'Align-Center horizontally' button

Align them center vertically using the 'Align-Center vertically' button

By xml

pack all those three buttons into a vertically packed chain using

```<code> app:layout_constraintVertical_chainStyle="packed"
</code>```

add left and right constraints for all those three buttons as parent

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="25dp"
tools:layout_editor_absoluteX="0dp">

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintVertical_chainStyle="packed"
    app:layout_constraintBottom_toTopOf="@+id/button2"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"/>

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="259dp"
    app:layout_constraintVertical_chainStyle="packed"
    app:layout_constraintBottom_toTopOf="@+id/button3"
    app:layout_constraintTop_toBottomOf="@+id/button1"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"/>

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="307dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button2"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"/>
</android.support.constraint.ConstraintLayout>
</code>```

Body:
How to center align 3 buttons with next to each other vertically using ConstraintLayout?

To be clear, i want to convert this simple layout structure into flat UI using ConstraintLayout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>
</FrameLayout>

I have obtained a nearest solution as follows

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/button2"
    />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="259dp"
    app:layout_constraintBottom_toTopOf="@+id/button3"
    app:layout_constraintTop_toBottomOf="@+id/button"
    app:layout_constraintRight_toRightOf="parent"/>

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    app:layout_constraintLeft_toLeftOf="parent"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="307dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button2"
    app:layout_constraintRight_toRightOf="parent"/>

 </android.support.constraint.ConstraintLayout>

But clearly, you can see that the obtained output does not match to the required one. i don't want any margin or space in between the 3 buttons, all i want is to center align those 3 buttons next to each other vertically just like they are in a LinearLayout which has a vertical orientation.

Body:
By Android Studio's 'Layout Editor'

drag and drop three buttons into the Android Studio's 'Layout Editor'

Select those buttons together by dragging mouse

Pack them vertically using the 'pack' button in 'Layout Editor'

Align them center horizontally using 'Align-Center horizontally' button

Align them center vertically using the 'Align-Center vertically' button

By xml

pack all those three buttons into a vertically packed chain using

 app:layout_constraintVertical_chainStyle="packed"

add left and right constraints for all those three buttons as parent

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="25dp"
tools:layout_editor_absoluteX="0dp">

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintVertical_chainStyle="packed"
    app:layout_constraintBottom_toTopOf="@+id/button2"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"/>

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="259dp"
    app:layout_constraintVertical_chainStyle="packed"
    app:layout_constraintBottom_toTopOf="@+id/button3"
    app:layout_constraintTop_toBottomOf="@+id/button1"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"/>

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:layout_conversion_absoluteHeight="48dp"
    tools:layout_conversion_absoluteWidth="88dp"
    tools:layout_conversion_absoluteX="148dp"
    tools:layout_conversion_absoluteY="307dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button2"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"/>
</android.support.constraint.ConstraintLayout>


来源: stackexchange

问:
Division Solution Results in Whole Numbers Only
I'm currently writing a math problem program for a school project. I'm stuck on a particular part for division portion.

The numerator needs to always be larger than the denominator, yet the quotient always needs to be a whole number. The program is supposed to generate numbers randomly from 1-20.

Ex: 14 / 7 = 2
Numerator > Denominator = Result is a whole number, not a decimal.

Thanks!

Note: we are not allowed to round our answers. The division always has to result in a whole number.

答:
Simply declare your variable as an Integer and then do the division. If you don't care about the remainder or how it is rounded. For example from Microsoft:

```<code> Dim resultValue As Integer
 resultValue = 11 \ 4 'result is 2
 resultValue = 9 \ 3 'result is 3
 resultValue = 100 \ 3 'result is 33
 resultValue = 67 \ -3 'result is -22
</code>```

If you want to round up or down you could simply do a double as your result value and set a new value as an integer. For example:

```<code>Public Function RoundUp(ByVal num) As Long
    If num >= 0 Then
        If num = Int(num) Then
            RoundUp = num
        Else
            RoundUp = Int(num) + 1
        End If
    ElseIf num < 0 Then
        RoundUp = Int(num)
    End If
End Function

Public Function RoundDown(ByVal num) As Long
    RoundDown = Fix(num)
    If num >= 0 Then
        If num = Int(num) Then
            RoundDown = num
        Else
            RoundDown = Int(num)
        End If
    ElseIf Number < 0 Then
        RoundDown = Int(num) - 1
    End If
End Function
</code>```

Edit. Is this what you are looking for?

```<code>Public Function InputIsValid(ByVal numerator, ByVal denominator) As Boolean
    If (numerator > denominator) AND (numerator Mod denominator = 0) Then
        Return True
    End If
    Return False
End Function
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Simply declare your variable as an Integer and then do the division. If you don't care about the remainder or how it is rounded. For example from Microsoft:

 Dim resultValue As Integer
 resultValue = 11 \ 4 'result is 2
 resultValue = 9 \ 3 'result is 3
 resultValue = 100 \ 3 'result is 33
 resultValue = 67 \ -3 'result is -22

If you want to round up or down you could simply do a double as your result value and set a new value as an integer. For example:

Public Function RoundUp(ByVal num) As Long
    If num >= 0 Then
        If num = Int(num) Then
            RoundUp = num
        Else
            RoundUp = Int(num) + 1
        End If
    ElseIf num < 0 Then
        RoundUp = Int(num)
    End If
End Function

Public Function RoundDown(ByVal num) As Long
    RoundDown = Fix(num)
    If num >= 0 Then
        If num = Int(num) Then
            RoundDown = num
        Else
            RoundDown = Int(num)
        End If
    ElseIf Number < 0 Then
        RoundDown = Int(num) - 1
    End If
End Function

Edit. Is this what you are looking for?

Public Function InputIsValid(ByVal numerator, ByVal denominator) As Boolean
    If (numerator > denominator) AND (numerator Mod denominator = 0) Then
        Return True
    End If
    Return False
End Function


问:
Is it possible to call a function on page_load event of pages that inherit from a specific Page subclass in asp.net WebFroms?
I want to execute a function on Page_load event of every System.Web.UI.Page from which derives my own CustomPage class (which obviously inherits from Page class as well)

what I have done so far it that I created CustomPage class like this:

```<code>public class CustomPage : System.Web.UI.Page
{
    protected virtual void Page_Load(object sender, EventArgs e)
    {
        CallTOTheDesiredFunction();  //this is the call to the function I want
    }
}
</code>```

And in the derived Page classes I am doing this:

```<code>public class DerivedPage : CustomPage
{
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        //the rest of the page load event which executes from here on
    }
}
</code>```

As it is obvious, this approach is working but it is not the best solution since I have to call base.Page_Load(sender, e) on every derived page.

Is there a better solution to what I am trying to achieve?
Thank you in advance

答:
Yes. It is better to override the Onload method rather than relying on deriving classes to call the base method.

You can still hook on the Load event in every page, but use the method in the base class.

```<code>public class CustomPage : System.Web.UI.Page
{
    protected override void OnLoad(EventArgs e)
    {
        CallTOTheDesiredFunction();  //this is the call to the function I want

        base.OnLoad(e);
    }
}
</code>```

Body:
I want to execute a function on Page_load event of every System.Web.UI.Page from which derives my own CustomPage class (which obviously inherits from Page class as well)

what I have done so far it that I created CustomPage class like this:

public class CustomPage : System.Web.UI.Page
{
    protected virtual void Page_Load(object sender, EventArgs e)
    {
        CallTOTheDesiredFunction();  //this is the call to the function I want
    }
}

And in the derived Page classes I am doing this:

public class DerivedPage : CustomPage
{
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        //the rest of the page load event which executes from here on
    }
}

As it is obvious, this approach is working but it is not the best solution since I have to call base.Page_Load(sender, e) on every derived page.

Is there a better solution to what I am trying to achieve?
Thank you in advance

Body:
Yes. It is better to override the Onload method rather than relying on deriving classes to call the base method.

You can still hook on the Load event in every page, but use the method in the base class.

public class CustomPage : System.Web.UI.Page
{
    protected override void OnLoad(EventArgs e)
    {
        CallTOTheDesiredFunction();  //this is the call to the function I want

        base.OnLoad(e);
    }
}


问:
Angular Directive and Childrens
I wan't to make a Directive for Angular 1.x. I'm thinking in something like this:

```<code><myDirective>
     <div class="title">Header</div>
     <div class="content>Content here</div>
</myDirective>
</code>```

So my question if it's posible access to "title" and "content" class of the html and change, for example, the background color for "title" element..

Anyone can help me?

答:
You could use ng-class to do it. Declare your CSS classes that will alternate in the directive, and use a condition in ng-class that will decide which will be active.

Some examples of how to use it:

```<code><div ng-class="{ 'text-success': awesome, 'text-large': giant }">

<div ng-class="$variableToEvaluate ? 'class-if-true' : 'class-if-false'">
</code>```

Here is the docs about it:

ng-class docs

You can look into this site for more details on how to use ng-class:

The many ways to use ng-class

Good luck!

Title: Angular Directive and Childrens

Body:
I wan't to make a Directive for Angular 1.x. I'm thinking in something like this:

<myDirective>

Header

Content here

</myDirective>

So my question if it's posible access to "title" and "content" class of the html and change, for example, the background color for "title" element..

Anyone can help me?

Body:
You could use ng-class to do it. Declare your CSS classes that will alternate in the directive, and use a condition in ng-class that will decide which will be active.

Some examples of how to use it:

<div ng-class="{ 'text-success': awesome, 'text-large': giant }">

<div ng-class="$variableToEvaluate ? 'class-if-true' : 'class-if-false'">

Here is the docs about it:

ng-class docs

You can look into this site for more details on how to use ng-class:

The many ways to use ng-class

Good luck!


问:
Java ORM for Hbase
Anyone knows a good Java ORM implementation for HBase. This one looks really nice for Ruby

http://www.stanford.edu/~sqs/rhino/doc/

But could not find one for Java.

Thanks.

答:
The strength of HBase as I see it is in keeping dynamic columns into static column families. From my experience developing applications with HBase I find that it is not as easy as SQL to determine cell qualifiers and values.

For example, a book as many authors, depending on your access patterns, author edits, app-layer cache implementation you might want to choose to save whole author in the book table (that is author resides in 2 table, author table and book table) or just the author id. Further more the collection of author can be saved into one cell as XML/JSON or individual cells for individual authors.

With this understanding I concluded writing a full-blown ORM such as Hibernate will not only be very difficult might not actually be conclusive. So I took a different approach, much more like as iBatis is to Hibernate.

My mini-framework: http://github.com/smart-it/smart-dao [smart-hbase]

Usage: https://github.com/smart-it/smart-cms [content-spi-impl module has the usages]

Usage: https://github.com/smart-it/jetty-session-hbase [hbase-impl module has the usages]

Let me try to explain how it works. For this I will use source codes from here and here.

The first and foremost task is to implement a ObjectRowConverter interface, in this case SessionDataObjectConverter. The abstract class encapsulates basic best practices as discussed and learnt from the HBase community. The extension basically gives you 100% control on how to convert your object to HBase row and vice-versa. For this only restriction from the API is that your domain objects must implement the interface PersistentDTO which is used internally to create Put, Delete, do byte[] to id object and vice versa.

Next task is to wire the dependencies as done in HBaseImplModule. Please let me know if you interested I will go through the dependency injections.

And thats it. How they are used are available here. It basically uses CommonReadDao, CommonWriteDao to read and write data to and from HBase. The common read dao implements multithreaded row to object conversion on queries, multithreaded get by ids, get by id and has its Hibernate Criteria like API to query to HBase via Scan (no aggregation functions available). Common write dao implements common write related code with some added facilities, such as optimistic/pessimistic locking, cell override/merge checking entity (non)-existence on save, update, delete etc.

This ORM has been developed for our internal purpose and I have been upto my neck and hence can not yet do some documentation. But if you are interested let me know and I will make time for documentation with priority.

ContentLicense: CC BY-SA 2.5

Title: Java ORM for Hbase


问:
Regex to check if the user submitted price is really a valid price
I'm trying to create a regex code to match a price with or without a dollar sign $, and with or without a comma or decimal point.

The following prices should be valid.

```<code>$1
$5.00
$.10
$.07
$03 //this should be interpreted as $0.03 in case if you are confused
$10,000
$10,000.00

1
5.00
.10
.07
03 //this should be interpreted as $0.03 in case if you are confused
10,000
10,000.00
</code>```

Here is my code so far:

```<code>preg_match('/^([1-9][0-9]*|0)(\.[0-9]{2})?$/', $price)
</code>```

答:
How do you like this?

```<code>preg_match(
    '/^' .
    '\$?' . // optional dollar sign
    '[\d]*' . // any digits (0 or not does not make a difference, 03 is valid as well as .03 or 0.03)
    '(,\d{3})*?' . // a comma has to be followed by 3 digits to be valid
    '(.\d\d)?' . // the point has to be followed by 2 digits to be valid
    '$/', // the end
    $price
);
</code>```

You have to adapt this, if you wanna force a comma after every three digits. However there are good regex if you google "regex float" (like http://www.regular-expressions.info/floatingpoint.html)

I am not sure why the "03" or "$03" is important. If you want to verify the string, okay. If you just want to convert it to a float, I would keep it simple, stupid:

```<code>$price = str_replace(['$', ','], '', $str);
    if ('0' === $price[0]) {
        $price = '.' . $price;
    }
    $price = (float) $price;
</code>```

Body:
I'm trying to create a regex code to match a price with or without a dollar sign $, and with or without a comma or decimal point.

The following prices should be valid.

$1
$5.00
$.10
$.07
$03 //this should be interpreted as $0.03 in case if you are confused
$10,000
$10,000.00

1
5.00
.10
.07
03 //this should be interpreted as $0.03 in case if you are confused
10,000
10,000.00

Here is my code so far:

preg_match('/^([1-9][0-9]*|0)(\.[0-9]{2})?$/', $price)

Body:
How do you like this?

preg_match(
    '/^' .
    '\$?' . // optional dollar sign
    '[\d]*' . // any digits (0 or not does not make a difference, 03 is valid as well as .03 or 0.03)
    '(,\d{3})*?' . // a comma has to be followed by 3 digits to be valid
    '(.\d\d)?' . // the point has to be followed by 2 digits to be valid
    '$/', // the end
    $price
);

You have to adapt this, if you wanna force a comma after every three digits. However there are good regex if you google "regex float" (like http://www.regular-expressions.info/floatingpoint.html)

I am not sure why the "03" or "$03" is important. If you want to verify the string, okay. If you just want to convert it to a float, I would keep it simple, stupid:

$price = str_replace(['$', ','], '', $str);
    if ('0' === $price[0]) {
        $price = '.' . $price;
    }
    $price = (float) $price;


问:
"The method selectByValue(String) undefined for the type WebElement" in Selenium
Can you please some one help me to finish this..

I want to write selenium code for drop down. when I'm trying to use below syntax. Im getting this error in eclipse "The method selectByValue(String) undefined for the type WebElement".

I'm using below syntax:

```<code>ele.selectByIndex(5);
ele.selectByValue("3");
ele.selectByVisibleText(Feb);
</code>```

Thanks in advance...

I have updated after I found the solution.
I have written the code like this for others can use. it's working fine for me.

```<code>public void selectCreditCardType(WebElement selectCreditCardType) throws Exception {
    logger.info("Select Card");
    browser.selectByText(selectCreditCardType, "Visa Card");
    browser.Wait(10);
}
</code>```

答:
Carefully look at the error message.

"The method selectByValue(String) undefined for the type WebElement"

It's saying that you are doing the equivalent of WebElement.selectByValue() which is not defined. .selectByValue() is defined for a Select. You didn't post all the relevant code to your example but you likely have code like

```<code>WebElement ele = driver.findElement(locator);
ele.selectByIndex(5);
</code>```

which means that ele is of WebElement type. You are trying to set a value in a SELECT element so you would want to use the Select class. You can do this like

```<code>WebElement ele = driver.findElement(locator);
Select select = new Select(ele);
select.selectByIndex(5);
</code>```

You should spend some time reviewing the Selenium docs for Java, especially the Select class.

Body:
Can you please some one help me to finish this..

I want to write selenium code for drop down. when I'm trying to use below syntax. Im getting this error in eclipse "The method selectByValue(String) undefined for the type WebElement".

I'm using below syntax:

ele.selectByIndex(5);
ele.selectByValue("3");
ele.selectByVisibleText(Feb);

Thanks in advance...

I have updated after I found the solution.
I have written the code like this for others can use. it's working fine for me.

public void selectCreditCardType(WebElement selectCreditCardType) throws Exception {
    logger.info("Select Card");
    browser.selectByText(selectCreditCardType, "Visa Card");
    browser.Wait(10);
}

Body:
Carefully look at the error message.

"The method selectByValue(String) undefined for the type WebElement"

It's saying that you are doing the equivalent of WebElement.selectByValue() which is not defined. .selectByValue() is defined for a Select. You didn't post all the relevant code to your example but you likely have code like

WebElement ele = driver.findElement(locator);
ele.selectByIndex(5);

which means that ele is of WebElement type. You are trying to set a value in a SELECT element so you would want to use the Select class. You can do this like

WebElement ele = driver.findElement(locator);
Select select = new Select(ele);
select.selectByIndex(5);

You should spend some time reviewing the Selenium docs for Java, especially the Select class.


问:
Prefix in recursion does not work correctly
This is my code:

```<code>class Backwards {
    String str;
    Backwards(String s) {
        str = s;
    }

    void backward(int idx) {
        if(idx != str.length()-1) {
            System.out.println(idx);
            backward(++idx);
        }
        System.out.print(str.charAt(idx));
    }
}

class StrBackDemo {
    public static void main(String args[]) {
        Backwards s = new Backwards("This is a test");
        s.backward(0);
    }
}
</code>```

when I call function itself with expression idx +1 it works nicely, but with ++idx, it prints first character twice and doesn't print last character at all.

```<code>With <+idx> output: ttset a si sih
With <idx +1> output: tset a si sihT
</code>```

答:
It happens cause on the the recursive call backward(++idx) you pass incremented value and also increment value itself.
Operator ++ sets value of idx to idx + 1

On the last call you finish with situation when method gets index 13 and print char for it and the previous call also has index 13. In same time first call of method has index 1.

To fix your code use:

```<code>    void backward(int idx) {
        if(idx != str.length()-1) {
            System.out.println(idx);
            backward(idx + 1);
        }
        System.out.print(str.charAt(idx));
    }
</code>```

With use of idx + 1 value of idx will stay same where it is called.

Body:
This is my code:

class Backwards {
    String str;
    Backwards(String s) {
        str = s;
    }

    void backward(int idx) {
        if(idx != str.length()-1) {
            System.out.println(idx);
            backward(++idx);
        }
        System.out.print(str.charAt(idx));
    }
}

class StrBackDemo {
    public static void main(String args[]) {
        Backwards s = new Backwards("This is a test");
        s.backward(0);
    }
}

when I call function itself with expression idx +1 it works nicely, but with ++idx, it prints first character twice and doesn't print last character at all.

With <+idx> output: ttset a si sih
With <idx +1> output: tset a si sihT

Body:
It happens cause on the the recursive call backward(++idx) you pass incremented value and also increment value itself.
Operator ++ sets value of idx to idx + 1

On the last call you finish with situation when method gets index 13 and print char for it and the previous call also has index 13. In same time first call of method has index 1.

To fix your code use:

    void backward(int idx) {
        if(idx != str.length()-1) {
            System.out.println(idx);
            backward(idx + 1);
        }
        System.out.print(str.charAt(idx));
    }

With use of idx + 1 value of idx will stay same where it is called.


问:
I have cloned a ruby project from gitlab and trying to run but gem is not installing
I have cloned the project and also resolved so many issues related to gems installation and other configuration but now i am stuck on this issue

```<code>RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.14.6/lib/bundler/spec_set.rb:87:in `block in materialize': Could not find mini_portile2-2.0.0 in any of the sources (Bundler::GemNotFound)
</code>```

I have tried a lot to install this gem but no avail.
when i try to install this gem this message shows

```<code>$ gem install miniportile --version "2-2.0.0"
ERROR:  Could not find a valid gem 'miniportile' (= 2.pre.2.0.0) in any repository
</code>```

答:
https://rubygems.org/gems/mini_portile

choose a valid version of that gem, e.g. 0.6.2 Note the underscore in the gem name:

```<code>    $ gem install mini_portile --version 0.6.2
</code>```

Body:
I have cloned the project and also resolved so many issues related to gems installation and other configuration but now i am stuck on this issue

RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.14.6/lib/bundler/spec_set.rb:87:in `block in materialize': Could not find mini_portile2-2.0.0 in any of the sources (Bundler::GemNotFound)

I have tried a lot to install this gem but no avail.
when i try to install this gem this message shows

$ gem install miniportile --version "2-2.0.0"
ERROR:  Could not find a valid gem 'miniportile' (= 2.pre.2.0.0) in any repository

Body:
https://rubygems.org/gems/mini_portile

choose a valid version of that gem, e.g. 0.6.2 Note the underscore in the gem name:

    $ gem install mini_portile --version 0.6.2


问:
Docker is not creating new container but recreates running one
so I have the following problem. I'm using docker-compose to build and start two container. I did this multiple times with different docker-compose.yml files (image and container name differ) and it worked fine and three container run parallel. The only difference is, that one container exposes a specific port and the other runs an application that connects to a specific endpoint.
So in total the containers are not that different, but they are.

But now I created three additional compose configurations and tried to run them parallel like I'm already doing with the three others. The Problem now is, that with docker-compose, one container is being build and started. But the second one will stop the created container and recreate it.
I tried to do docker-compose build --no-cache and after that docker-compose up -d, but I still ended up with the same problem. The images though were different (ID). Before that I tried it just with docker-compose up -d --build for the first and second (new) container and it would be recreated like mentioned. But looking at the images, they would get the same ID (but different name).

So I thought docker has a problem with caching. That's why I ended up deleting all my container and images and started from scratch with the option --no-cache like mentioned above. Didn't work though.

Here are two docker-compose.yml that work:

```<code>version: '2'
services:
    ruby:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ruby
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ruby_foo_ge01
        container_name: ruby_container_ge01
        volumes:
            - /home/foo/log/GE01/:/usr/src/app/log/
    ssl:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ssl
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ssl_ge01
        container_name: ssl_container_ge01
        volumes:
            - /home/foo/log/GE01/nginx/:/var/log/nginx/
        ports:
            - "3003:443"
        links:
            - ruby
</code>```

and the other one:

```<code>version: '2'
services:
    ruby:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ruby
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ruby_foo
        container_name: ruby_container
        volumes:
            - /home/foo/log/:/usr/src/app/log/
    ssl:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ssl
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ssl_gt01
        container_name: ssl_container
        volumes:
            - /home/foo/log/nginx/:/var/log/nginx/
        ports:
            - "3001:443"
        links:
            - ruby
</code>```

Running this two and one other quite similar with docker-compose up -d --build is no problem.

And here are two .yml files of the container that fail:

```<code>version: '2'
services:
    ruby:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ruby
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ruby_foo_websock_gt01
        container_name: ruby_containerWSgt01
        volumes:
            - /home/foo/websockGT01/log/:/usr/src/app/log/
    ssl:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ssl
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ssl_websock_gt01
        container_name: ssl_containerWSgt01
        volumes:
            - /home/foo/websockGT01/log/nginx/:/var/log/nginx/
        ports:
            - "3010:443"
        links:
            - ruby
</code>```

And the second one:

```<code>version: '2'
services:
    ruby:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ruby
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ruby_foo_websock_ge01
        container_name: ruby_containerWSge01
        volumes:
            - /home/foo/websockGE01/log/:/usr/src/app/log/
    ssl:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ssl
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ssl_websock_ge01
        container_name: ssl_containerWSge01
        volumes:
            - /home/foo/websockGE01/log/nginx/:/var/log/nginx/
        ports:
            - "3030:443"
        links:
            - ruby
</code>```

As you can see there is no big difference in the working .yml files and the ones that fail. (Or did I miss something?) The image and container names change as does the exposed port and volume path.
All of the files have their own working dir where also the application code is saved per instance. All the used Dockerfiles are the same in each working dir.

TL;DR: Why is my docker-compose not starting a new container, but stops a running one and recreates that one? Is there a maximum amount of running container? Have I done something wrong in my .yml file? As mentioned at the beginning --no-cache does not help.

Kind regards and sorry for that wall of text

答:
Short(ish) answer

It looks as though you're using the same project name some of the time when you run docker-compose up; since you use the same service names (i.e. ruby and ssl) between docker-compose.yml files, Docker Compose treats the different configurations as modifications of the same service, rather than considering them to be separate services completely.

My guess is that the parent directory of some of the docker-compose.yml files is the same, so if you want to run these containers at the same time you have a few options:

Change the names of the parent directories so they're all different

Specify a different project name on each invocation of docker-compose up, e.g. docker-compose -p project1 up -d, docker-compose -p project2 up -d

Change the service names so they're not all the same across the different docker-compose.yml files

Longer answer

From a quick test it appears that Docker Compose uses the project name and service name to identify a specific service.  The project name can be set with the -p flag when running Docker Compose commands, otherwise it uses the value of the COMPOSE_PROJECT_NAME environment variable if set, and if neither of those are specified it'll default to the name of the parent directory of the docker-compose.yml file (see https://docs.docker.com/compose/reference/overview).

So, given a directory structure such as:

```<code>.
├── a
│   └── z
│       └── docker-compose.yml
├── b
│   └── z
│       └── docker-compose.yml
└── c
    └── y
        └── docker-compose.yml
</code>```

Running docker-compose up -d from the a/z directory (or using docker-compose -f a/z/docker-compose.yml up -d) will start ruby and ssl services in project z, named using the container names specified in the docker-compose.yml.

If you then run docker-compose up -d from theb/z directory, Docker Compose will see you trying to again bring up the ruby and ssl services in project z, but this time with some differences, e.g. to names and ports.  It will treat this as if you had modified the original docker-compose.yml, and restart the containers with the new configuration.  If you were to now run docker-compose up -d from the c/y directory then you would get two new containers running in parallel with the first two, ruby and ssl services running in project y.

So you'll need to ensure that the combination of project and service name differs across the different sets of containers you'd like to run, either by changing the service names or by setting the project differently each time.

Body:
so I have the following problem. I'm using docker-compose to build and start two container. I did this multiple times with different docker-compose.yml files (image and container name differ) and it worked fine and three container run parallel. The only difference is, that one container exposes a specific port and the other runs an application that connects to a specific endpoint.
So in total the containers are not that different, but they are.

But now I created three additional compose configurations and tried to run them parallel like I'm already doing with the three others. The Problem now is, that with docker-compose, one container is being build and started. But the second one will stop the created container and recreate it.
I tried to do docker-compose build --no-cache and after that docker-compose up -d, but I still ended up with the same problem. The images though were different (ID). Before that I tried it just with docker-compose up -d --build for the first and second (new) container and it would be recreated like mentioned. But looking at the images, they would get the same ID (but different name).

So I thought docker has a problem with caching. That's why I ended up deleting all my container and images and started from scratch with the option --no-cache like mentioned above. Didn't work though.

Here are two docker-compose.yml that work:

version: '2'
services:
    ruby:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ruby
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ruby_foo_ge01
        container_name: ruby_container_ge01
        volumes:
            - /home/foo/log/GE01/:/usr/src/app/log/
    ssl:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ssl
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ssl_ge01
        container_name: ssl_container_ge01
        volumes:
            - /home/foo/log/GE01/nginx/:/var/log/nginx/
        ports:
            - "3003:443"
        links:
            - ruby

and the other one:

version: '2'
services:
    ruby:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ruby
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ruby_foo
        container_name: ruby_container
        volumes:
            - /home/foo/log/:/usr/src/app/log/
    ssl:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ssl
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ssl_gt01
        container_name: ssl_container
        volumes:
            - /home/foo/log/nginx/:/var/log/nginx/
        ports:
            - "3001:443"
        links:
            - ruby

Running this two and one other quite similar with docker-compose up -d --build is no problem.

And here are two .yml files of the container that fail:

version: '2'
services:
    ruby:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ruby
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ruby_foo_websock_gt01
        container_name: ruby_containerWSgt01
        volumes:
            - /home/foo/websockGT01/log/:/usr/src/app/log/
    ssl:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ssl
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ssl_websock_gt01
        container_name: ssl_containerWSgt01
        volumes:
            - /home/foo/websockGT01/log/nginx/:/var/log/nginx/
        ports:
            - "3010:443"
        links:
            - ruby

And the second one:

version: '2'
services:
    ruby:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ruby
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ruby_foo_websock_ge01
        container_name: ruby_containerWSge01
        volumes:
            - /home/foo/websockGE01/log/:/usr/src/app/log/
    ssl:
        security_opt:
            - seccomp:unconfined
        build:
            context: .
            dockerfile: Dockerfile_ssl
            args:
                - http_proxy=http://someIP:3128
                - https_proxy=http://someIP:3128
        image: ssl_websock_ge01
        container_name: ssl_containerWSge01
        volumes:
            - /home/foo/websockGE01/log/nginx/:/var/log/nginx/
        ports:
            - "3030:443"
        links:
            - ruby

As you can see there is no big difference in the working .yml files and the ones that fail. (Or did I miss something?) The image and container names change as does the exposed port and volume path.
All of the files have their own working dir where also the application code is saved per instance. All the used Dockerfiles are the same in each working dir.

TL;DR: Why is my docker-compose not starting a new container, but stops a running one and recreates that one? Is there a maximum amount of running container? Have I done something wrong in my .yml file? As mentioned at the beginning --no-cache does not help.

Kind regards and sorry for that wall of text

Body:
Short(ish) answer

It looks as though you're using the same project name some of the time when you run docker-compose up; since you use the same service names (i.e. ruby and ssl) between docker-compose.yml files, Docker Compose treats the different configurations as modifications of the same service, rather than considering them to be separate services completely.

My guess is that the parent directory of some of the docker-compose.yml files is the same, so if you want to run these containers at the same time you have a few options:

Change the names of the parent directories so they're all different

Specify a different project name on each invocation of docker-compose up, e.g. docker-compose -p project1 up -d, docker-compose -p project2 up -d

Change the service names so they're not all the same across the different docker-compose.yml files

Longer answer

From a quick test it appears that Docker Compose uses the project name and service name to identify a specific service.  The project name can be set with the -p flag when running Docker Compose commands, otherwise it uses the value of the COMPOSE_PROJECT_NAME environment variable if set, and if neither of those are specified it'll default to the name of the parent directory of the docker-compose.yml file (see https://docs.docker.com/compose/reference/overview).

So, given a directory structure such as:

.
├── a
│   └── z
│       └── docker-compose.yml
├── b
│   └── z
│       └── docker-compose.yml
└── c
    └── y
        └── docker-compose.yml

Running docker-compose up -d from the a/z directory (or using docker-compose -f a/z/docker-compose.yml up -d) will start ruby and ssl services in project z, named using the container names specified in the docker-compose.yml.

If you then run docker-compose up -d from theb/z directory, Docker Compose will see you trying to again bring up the ruby and ssl services in project z, but this time with some differences, e.g. to names and ports.  It will treat this as if you had modified the original docker-compose.yml, and restart the containers with the new configuration.  If you were to now run docker-compose up -d from the c/y directory then you would get two new containers running in parallel with the first two, ruby and ssl services running in project y.

So you'll need to ensure that the combination of project and service name differs across the different sets of containers you'd like to run, either by changing the service names or by setting the project differently each time.


问:
Convert String to datetime [Wed Mar 01, 2017 6:00 AM] this format in c#
I have excel sheet with columns of date and time, date format is Wed Mar 01, 2017 this while time format is this 6:00 AM I get the vales from excel sheet and combine these two columns with a space between which makes it Wed Mar 01, 2017 6:00 AM look like this. Now I want to convert this string to datetime. I have tried many things but I get the error that string is not valid datetime format.

```<code>string startDate = row.Cells[0].Value.ToString();
 string startTime = row.Cells[1].Value.ToString();

 var mydate = startDate+ " " + startTime; // it creates Wed Mar 01, 2017 6:00 AM, this is shown in debugger
 DateTime finaldate = DateTime.ParseExact(mydate, "r", null);
</code>```

I want this converted to datetime in same format because I have another column which tells me hours too add in this time and I am using addHours() to do that. so I want the output in same format after adding hours.
I cant make the date format string for this format to give to ParseExact. Any help is appreciated. Thanks

答:
You can specify custom format:</p>

```<code>DateTime finaldate = DateTime.ParseExact(mydate, "ddd MMM dd, yyyy h:mm tt", CultureInfo.InvariantCulture);
</code>```

Body:
I have excel sheet with columns of date and time, date format is Wed Mar 01, 2017 this while time format is this 6:00 AM I get the vales from excel sheet and combine these two columns with a space between which makes it Wed Mar 01, 2017 6:00 AM look like this. Now I want to convert this string to datetime. I have tried many things but I get the error that string is not valid datetime format.

string startDate = row.Cells[0].Value.ToString();
 string startTime = row.Cells[1].Value.ToString();

 var mydate = startDate+ " " + startTime; // it creates Wed Mar 01, 2017 6:00 AM, this is shown in debugger
 DateTime finaldate = DateTime.ParseExact(mydate, "r", null);

I want this converted to datetime in same format because I have another column which tells me hours too add in this time and I am using addHours() to do that. so I want the output in same format after adding hours.
I cant make the date format string for this format to give to ParseExact. Any help is appreciated. Thanks

Body:
You can specify custom format:

DateTime finaldate = DateTime.ParseExact(mydate, "ddd MMM dd, yyyy h:mm tt", CultureInfo.InvariantCulture);


问:
How can I set the location of a stylesheet with jQuery?
How can I set the location of a stylesheet with jQuery?</p>

答:
One approach is to give the <link> element an ID and use that as your selector, changing the href property on the matching element:

```<code>$("#myStyle")[0].href = "/path/to/new.css";
</code>```

Another approach is to have multiple style sheets attached to your document and enable/disable them when necessary:

```<code><link id="style1" href="style1.css" />
<link id="style2" href="style2.css" disabled="disabled" />
</code>```

```<code>$("#style1").attr("disabled", true).next().attr("disabled", false);</code>```

This approach is best when regularly switching all the styles for your page.

Body:
One approach is to give the <link> element an ID and use that as your selector, changing the href property on the matching element:

$("#myStyle")[0].href = "/path/to/new.css";

Another approach is to have multiple style sheets attached to your document and enable/disable them when necessary:

<link id="style1" href="style1.css" />
<link id="style2" href="style2.css" disabled="disabled" />

$("#style1").attr("disabled", true).next().attr("disabled", false);

This approach is best when regularly switching all the styles for your page.


问:
Changing array element?
My aim is there is an array like this int arrMarks[] = {10,-15,25,102,30} and I need to make it equal to zero when an element is below zero or higher than 100. Then these elements should be in the last place of the array and the other one's position removed one place. So how can I do this without using any package or shortages?</p>

```<code>public void validateMarks(int [] array){
        int [] array1 = new int[5];

        for(int i = 0; i<array.length; i++){
            if(array[i] < 0 || array[i] > 100){
                int f= array1.length-1;

                array1[f] = array[i];
                array1[f] = 0;
                f--;
            }

            else if(array[i] > 0 || array[i] < 100){

                array1[i] = array[i];

            }
            System.out.println(array1[i]);
        }
    }
</code>```

答:
```<code>public void validateMarks(int[] array){
    int[] array1 = new int[array.length];
    int pos = 0;
    for (int i = 0; i < array.length; i++){
        if (array[i] >= 0 && array[i] <= 100)
            array1[pos++] = array[i];
    }
    for (int i = 0; i < array.length; i++){
        System.out.println(array1[i]);
    }
}
</code>```

Lessons to be learned here:

Don't hard code values (5 changed to array.length)

Learn scoping rules (f and pos need to be declared outside of the for loop)

Sometimes you don't need to store values

That last point hints that array1 isn't actually necessary. I leave that challenge up to the OP.

Title: Changing array element?

Body:
My aim is there is an array like this int arrMarks[] = {10,-15,25,102,30} and I need to make it equal to zero when an element is below zero or higher than 100. Then these elements should be in the last place of the array and the other one's position removed one place. So how can I do this without using any package or shortages?

public void validateMarks(int [] array){
        int [] array1 = new int[5];

        for(int i = 0; i<array.length; i++){
            if(array[i] < 0 || array[i] > 100){
                int f= array1.length-1;

                array1[f] = array[i];
                array1[f] = 0;
                f--;
            }

            else if(array[i] > 0 || array[i] < 100){

                array1[i] = array[i];

            }
            System.out.println(array1[i]);
        }
    }

Body:
public void validateMarks(int[] array){
    int[] array1 = new int[array.length];
    int pos = 0;
    for (int i = 0; i < array.length; i++){
        if (array[i] >= 0 && array[i] <= 100)
            array1[pos++] = array[i];
    }
    for (int i = 0; i < array.length; i++){
        System.out.println(array1[i]);
    }
}

Lessons to be learned here:

Don't hard code values (5 changed to array.length)

Learn scoping rules (f and pos need to be declared outside of the for loop)

Sometimes you don't need to store values

That last point hints that array1 isn't actually necessary. I leave that challenge up to the OP.


问:
Merging lists of different sizes in clojure
I have 2 lists

s = [1 2 3 4 5]

and

p = [:a :b :c :d :e :f :h :i :j :k :l :m]

I would like to take N elements from p where N is a random number between 1 to K and create a mapping from s to these N elements from p.

the resulting mapping could be something like

((1 :a) (1 :b) (1 :c) (2 :d) (2 :e) (3 :f) (4 :h) (4 :i) (5 :j) (5 :k) (5 :l))

for K=3.

it's fine if not all the elements in p are used but there are enough elements to cover the case where N is max for all elements in s.

I've come up with this but it's missing the take random N elements part and assigns an (almost) equal number of elements to each element in s

(partition 2 (interleave (cycle s) (shuffle p))))

this results in

((1 :d) (2 :f) (3 :h) (4 :e) (5 :l) (1 :b) (2 :k) (3 :a) (4 :j) (5 :g) (1 :i) (2 :c) (3 :m))

UPDATE:
Let me add some more context to the question for a better understanding.
I'm trying to generate a galaxy where each star will have 1 to N planets in it's system. The s list contains the ids of the stars, and the p list contains the ids of planets. I would like to map planet ids to star ids so each system has 1 to N random planets in the system.

答:
Each star must have a random number of planets. Here at least 1 but maximum of 3:

```<code>(def stars [1 2 3 4 5])
(def planets [:a :b :c :d :e :f :h :i :j :k :l :m])

(let [max-num-planets 3
      solar-systems (mapcat #(repeat (inc (rand-int max-num-planets)) %) stars)]
  (map #(list %1 %2) solar-systems (shuffle planets))
</code>```

Every time you run it the answer will be different, but each star will be included as each star has between 1 and 3 planets. Example outputs:

```<code>;; ((1 :a) (1 :b) (1 :c) (2 :d) (2 :e) (3 :f) (4 :h) (4 :i) (4 :j) (5 :k) (5:l) (5 :m))
;; ((1 :a) (1 :b) (1 :c) (2 :d) (3 :e) (3 :f) (4 :h) (5 :i))
</code>```

Not all the planets are always used, and a planet is never repeated - because of course a planet can't exist in more than one solar system.

Body:
Each star must have a random number of planets. Here at least 1 but maximum of 3:

(def stars [1 2 3 4 5])
(def planets [:a :b :c :d :e :f :h :i :j :k :l :m])

(let [max-num-planets 3
      solar-systems (mapcat #(repeat (inc (rand-int max-num-planets)) %) stars)]
  (map #(list %1 %2) solar-systems (shuffle planets))

Every time you run it the answer will be different, but each star will be included as each star has between 1 and 3 planets. Example outputs:

;; ((1 :a) (1 :b) (1 :c) (2 :d) (2 :e) (3 :f) (4 :h) (4 :i) (4 :j) (5 :k) (5:l) (5 :m))
;; ((1 :a) (1 :b) (1 :c) (2 :d) (3 :e) (3 :f) (4 :h) (5 :i))

Not all the planets are always used, and a planet is never repeated - because of course a planet can't exist in more than one solar system.


问:
Error Fetching http headers in wsdltophp.com
I am using wsdltophp.com to generate php files that access a web service.

Everything works fine except when I am using one service that will probably take a while to run. After 60 seconds it gives up and I get this error:

Error Fetching http headers

After looking at other answers on stackoverflow.com I assume this is just a timeout error and I can find some suggestions on how to fix it, but I am not sure how to work those suggestions into the files from wsdltophp.com. Can anybody help me with that?

The suggestions included disabling "keep_alive" and editing "default_socket_timeout". But where do I edit these settings in the wsdltophp.com files?

答:
```<code>ini_set('default_socket_timeout', 5000);
</code>```

did the trick for me.

Body:
ini_set('default_socket_timeout', 5000);

did the trick for me.


问:
Typedef & enum in C format and advtantages
I’m trying to figure out how to use typedef enum properly. What exactly can I do with the following, how would I call values from typedef enum, and can I link one of the values in typedef enum to a number in an Array? Thanks</p>

```<code>typedef enum
{
  A1 = 10,
  A2 = 20,
  A7 = 25,
  A9 = 91
} Select;
</code>```

答:
If you are new to C, you must first understand what typedef and enums are used for, before figuring out the intention of that enum typedef (which I assume is from some assignment ?). Checkout the answer provided in this post: How do I use typedef and typedef enum in C?

Coming to your question - " how would I call values from typedef enum, and can I link one of the values in typedef enum to a number in an Array?" -
The "values" in an enum are actually constants (like Macro definitions). They can be assigned to variables and passed to functions like any constants.

What can you do with a typedef enum, you ask? For one thing, if used properly, it can improve code readability. When you typedef an enum, you are specifying a new data type. Variables declared with this new type, can be expected to take values specified in the enum. Nothing stops these variables from taking other values, but the code becomes more readable, and the intent of the variables is clear to anyone reading the code. It is common to have enums for error codes. So status variables that are declared using such typedef enums can be expected to contain one of the error codes listed in the enum.

If I would hazard a guess, the enum you have specified probably holds indices of interest in an array, or expected values at certain indices in the array. Anyway, if you go through the rest of your code, you will find out your self!

Body:
I’m trying to figure out how to use typedef enum properly. What exactly can I do with the following, how would I call values from typedef enum, and can I link one of the values in typedef enum to a number in an Array? Thanks

typedef enum
{
  A1 = 10,
  A2 = 20,
  A7 = 25,
  A9 = 91
} Select;


问:
Getting device's local timezone
2010-06-14 02:21:49+0400 or 2010-06-14 02:21:49-0400

is there a way to convert this string to the date according to the local machine time zone with format 2010-06-14 02:21 AM

答:
You can do all sorts of fancy formatting and localisation of dates using the DateFormat class. There's very good, complete documentation at the start of the API page here:
http://download.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html

Most regular cases can be handled with the built in SimpleDateFormat object. Its details are here:
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

The SimpleDateFormat output pattern string for the example you have above would be:

```<code>yyyy-MM-dd hh:mm a
</code>```

Title: Getting device's local timezone

Body:
You can do all sorts of fancy formatting and localisation of dates using the DateFormat class. There's very good, complete documentation at the start of the API page here:
http://download.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html

Most regular cases can be handled with the built in SimpleDateFormat object. Its details are here:
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

The SimpleDateFormat output pattern string for the example you have above would be:

yyyy-MM-dd hh:mm a


问:
Convert object function to function pointer
I'm trying convert a object function to function pointer but can't get it, i've done something like this, simple example:

```<code>typedef struct
{
    int v1;

    int DoSome(int a)
    {
        return v1 * a;
    }
} strx;

int main()
{
    strx a; // instance...
    a.v1 = 2;

    std::function<int(strx* instance, int value)> DoSome = std::mem_fn(&strx::DoSome);

    cout << DoSome(&a, 4) << endl; // 16 ok

    int(*pDoSome)(strx* instance, int value) = (int(*)(strx*, int))std::mem_fn(&strx::DoSome); // syntax error

    // ptr method...
    pDoSome(&a ,4);

    return 0;
}
</code>```

and i have obtained something like:

main.cpp [Error] invalid cast from type 'std::_Mem_fn' to type 'int ()(strx, int)'

How i can do correctly the casting?

答:
How i can do correctly the casting?

You cannot. Object pointers and function pointers are totally different concepts. Only nullptr can be used to initialize both types of pointers. Otherwise, they are not guaranteed to be compatible.

I suggest sticking with the std::function.

If you must have a function pointer, you have to use a non-member function or a static member function of a class.

E.g.

```<code>int doSomeFunction(strx* instance, int value)
{
   // Use instance any way you please.
   // ...
   //
   return 0;
}

int main()
{
    strx a; // instance...
    a.v1 = 2;

    int(*pDoSome)(strx* instance, int value) = doSomeFunction;

    // ptr method...
    pDoSome(&a ,4);

    return 0;
}
</code>```

Body:
I'm trying convert a object function to function pointer but can't get it, i've done something like this, simple example:

typedef struct
{
    int v1;

    int DoSome(int a)
    {
        return v1 * a;
    }
} strx;

int main()
{
    strx a; // instance...
    a.v1 = 2;

    std::function<int(strx* instance, int value)> DoSome = std::mem_fn(&strx::DoSome);

    cout << DoSome(&a, 4) << endl; // 16 ok

    int(*pDoSome)(strx* instance, int value) = (int(*)(strx*, int))std::mem_fn(&strx::DoSome); // syntax error

    // ptr method...
    pDoSome(&a ,4);

    return 0;
}

and i have obtained something like:

main.cpp [Error] invalid cast from type 'std::_Mem_fn' to type 'int ()(strx, int)'

How i can do correctly the casting?

Body:
How i can do correctly the casting?

You cannot. Object pointers and function pointers are totally different concepts. Only nullptr can be used to initialize both types of pointers. Otherwise, they are not guaranteed to be compatible.

I suggest sticking with the std::function.

If you must have a function pointer, you have to use a non-member function or a static member function of a class.

E.g.

int doSomeFunction(strx* instance, int value)
{
   // Use instance any way you please.
   // ...
   //
   return 0;
}

int main()
{
    strx a; // instance...
    a.v1 = 2;

    int(*pDoSome)(strx* instance, int value) = doSomeFunction;

    // ptr method...
    pDoSome(&a ,4);

    return 0;
}


问:
Inventory CD segment mask and selector
We are trying to implement an "InventoryCD" (string) field in a custom page (not an Inventory ID Int field). We need this InventoryCD field to to work just like the Stock Item InventoryCD field (field mask for segment display and selector for existing items). Currently the issue is the same aspx PXSegmentMask and DAC attributes are not working the same. We are using InventoryRawAttribute on our field the exact same way found on the InventoryItemMaint cache attached for InventoryItem.InventoryCD. The only exception is the Inventory CD field is NOT a key in our custom page.

Our problem is the display of our Inventory CD field for the segment mask only displays when we are not entering or focused on the field (user has to click move to another field). This makes it difficult for users to follow which segments they are entering values into. So my question is what are we missing?

Here is what we have done so far:

(1) DAC - InventoryCD (same as InventoryItem.InventoryCD from InventoryItemMaint cache attached - except IsKey = false):

```<code>public abstract class inventoryCD : PX.Data.IBqlField
{}

protected String _InventoryCD;

[PXDefault()]
[InventoryRaw(typeof(Where<InventoryItem.stkItem, Equal<True>>), DisplayName = "Inventory ID", Filterable = true)]
public virtual String InventoryCD
{
    get
    {
        return this._InventoryCD;
    }
    set
    {
        this._InventoryCD = value;
    }
}
</code>```

(2) Page - InventoryCD (Copied from stock items IN202500):

```<code><px:PXSegmentMask ID="edInventoryCD" runat="server" DataField="InventoryCD"
    DataSourceID="ds" AutoRefresh="true" >
    <GridProperties FastFilterFields="InventoryCD,Descr" />
</px:PXSegmentMask>
</code>```

Here is a sample of the results I am seeing (refer to the image below). Note what the fields look like when entering values or just clicking into the field. On our custom page, clicking into the Inventory CD field shows no segmented separation. Doing the same on the Stock Item page will show the segmented separation so the user can following the segments. How do we get the segmented display to work in our custom page?

EDIT: If you set ValidComboRequired = true in InventoryRawAttribute the mask displays correctly the same as stock item, however you loose the selector for all items and the selector then becomes a selector for each item segment value (making the issue worse). Just an FYI in case anyone can see some type of combination I need as it might relate to ValidComboRequired (the mask when true, and the selector when false).

EDIT2: Tried making the field a key (but not the only key in the DAC) and no difference

答:
To get input mask, you can set AutoComplete to false in aspx without customizing out-of-box InventoryRaw attribute.

Example:

using PX.Data;
using PX.Objects.IN;

namespace PXDemoPkg
{
    public class INSetupDemoExt : PXCacheExtension<INSetup>
    {
        public abstract class usrInventoryID : IBqlField { }

        #region UsrInventoryID
        [PXDefault]
        [PXUIField(DisplayName = "InventoryID")]
        [InventoryRaw(typeof(Where<InventoryItem.stkItem, Equal<True>>),
                        DisplayName = "Inventory ID", Filterable = true)]
        public virtual string UsrInventoryID { get; set; }

        #endregion
    }
}
```

Title: Inventory CD segment mask and selector

Body:
We are trying to implement an "InventoryCD" (string) field in a custom page (not an Inventory ID Int field). We need this InventoryCD field to to work just like the Stock Item InventoryCD field (field mask for segment display and selector for existing items). Currently the issue is the same aspx PXSegmentMask and DAC attributes are not working the same. We are using InventoryRawAttribute on our field the exact same way found on the InventoryItemMaint cache attached for InventoryItem.InventoryCD. The only exception is the Inventory CD field is NOT a key in our custom page.

Our problem is the display of our Inventory CD field for the segment mask only displays when we are not entering or focused on the field (user has to click move to another field). This makes it difficult for users to follow which segments they are entering values into. So my question is what are we missing?

Here is what we have done so far:

(1) DAC - InventoryCD (same as InventoryItem.InventoryCD from InventoryItemMaint cache attached - except IsKey = false):

public abstract class inventoryCD : PX.Data.IBqlField
{}

protected String _InventoryCD;

[PXDefault()]
[InventoryRaw(typeof(Where<InventoryItem.stkItem, Equal<True>>), DisplayName = "Inventory ID", Filterable = true)]
public virtual String InventoryCD
{
    get
    {
        return this._InventoryCD;
    }
    set
    {
        this._InventoryCD = value;
    }
}

(2) Page - InventoryCD (Copied from stock items IN202500):

<px:PXSegmentMask ID="edInventoryCD" runat="server" DataField="InventoryCD"
    DataSourceID="ds" AutoRefresh="true" >
    <GridProperties FastFilterFields="InventoryCD,Descr" />
</px:PXSegmentMask>

Here is a sample of the results I am seeing (refer to the image below). Note what the fields look like when entering values or just clicking into the field. On our custom page, clicking into the Inventory CD field shows no segmented separation. Doing the same on the Stock Item page will show the segmented separation so the user can following the segments. How do we get the segmented display to work in our custom page?

EDIT: If you set ValidComboRequired = true in InventoryRawAttribute the mask displays correctly the same as stock item, however you loose the selector for all items and the selector then becomes a selector for each item segment value (making the issue worse). Just an FYI in case anyone can see some type of combination I need as it might relate to ValidComboRequired (the mask when true, and the selector when false).

EDIT2: Tried making the field a key (but not the only key in the DAC) and no difference


问:
Rails 3: Update database and scaffold
I'm starting in the big wooly world of Ruby on Rails and i'm trying to get my head around scaffolds and models. (cue, I'm a designer)

I use the rails generate scaffold command

```<code>rails generate scaffold Lesson title:string description:text
</code>```

But is it possible to update the Lesson table with new key, values with rails?

I tried:

```<code>rails generate model Lesson title:string description:text dtstart:datetime
</code>```

But when I run the db:migrate it fails and the only way around I know of to do that is to delete all of the scaffold and regenerate it.

I'm sure there must be an easier solution :)

I think (but im not sure, that it is because of the db/development.sqlite3 file that is not updated, when I delete the content by hand it then run the bd:migrate) is there a way to have evrything updated at once?

答: I think you must also update (in rails 5 at least) your lesson_params in lessons_controller.rb in order to allow the new parameters to be passed from the view to the model.</p>

Title: Rails 3: Update database and scaffold

Body:
I'm starting in the big wooly world of Ruby on Rails and i'm trying to get my head around scaffolds and models. (cue, I'm a designer)

I use the rails generate scaffold command

rails generate scaffold Lesson title:string description:text

But is it possible to update the Lesson table with new key, values with rails?

I tried:

rails generate model Lesson title:string description:text dtstart:datetime

But when I run the db:migrate it fails and the only way around I know of to do that is to delete all of the scaffold and regenerate it.

I'm sure there must be an easier solution :)

I think (but im not sure, that it is because of the db/development.sqlite3 file that is not updated, when I delete the content by hand it then run the bd:migrate) is there a way to have evrything updated at once?


问:
Don't REST control a URL in Spring Boot? Exclude url?
I am using some angular ui routing in some places, and I wanted the java server to not control some of the urls.

Perhaps it makes more sense to run the java app elsewhere? The reason I have the angularJS in the same url is because there are some authentication checks for my springboot app. So I want most URLs controlled.

But there's a few where I may want to control the authentication----but not the templating.

I think my problem is my Spring Boot code is trying to use velocity, when some of those URLs should just forward to AngularJS routing.

So a URL=/myreport/

--> goes to Java 404 error, instead of just forwarding to Angular UI Routing

--> But in some cases, Java should return 404/500/403 et al

Is there a way to do like a RestController that just forwards to AngularJS after authenticating? or to disable velocity??

答:
This would probably be more straightforward if you limit your Spring Boot code to just doing authentication and providing an API, and implement all of your UI in the Angular app.

You can then still use Spring Security to control access to the API.
On the Angular side, you can use AuthGuards in your routes to control access to parts of your UI based on the user's role.

To get a nice, clean separation, it is helpful to use token-based authentication instead of, say, Form-Based or Basic authentication. That way, the Angular app can present the login UI, and make a REST call to the Spring Boot app to log in, and get a token back, which is used on subsequent calls.

If you use JWT, you can have the back-end produce a token that includes the users' role, and then read that in the Angular app.

I recently wrote a 2-part blog post showing how to create an Angular 2 app with a Spring Boot back-end using JWT.
See http://chariotsolutions.com/blog/post/angular-2-spring-boot-jwt-cors_part1 and http://chariotsolutions.com/blog/post/angular-2-spring-boot-jwt-cors_part2


问:
What is the simplest way in C++98 to get and continue to call a class method, the type of which the current class does not know?
Example:
Suppose we are developing a simple graphical interface:

We have windows and controls. What do we want:

There is a base window class that implements the GUI functionality
hidden from the user.

From the base window, the user inherits a specific window.

There is a class of a button, an instance of which the user can add to his window.

The user can transfer the method of his window to button, and it will be executed when clicking this button.

I'm interested in how to reach the last point.

Kind of pseudo-code:

```<code>class BaseWindow;

class Button
{
public:
            Button(BaseWindow* parent)
            {
                        parent->AddButton(this);
            }

            void SetBehavior(/*Owners pointer and owner's methos*/)
            {
                        /* Save Owner pointer and owner's method*/
            }

            void Clicked(/*coords*/)
            {
                        if(/*coords == my coords*/)
                        {
                                    /*Call Owner's method*/
                        }
            }
};

class BaseWindow
{
            vector<Button*> Buttons;

            WindowClicked(/*coords*/)
            {
                    for (std::vector<Button*>::iterator it = Buttons.begin(); it != Buttons.end(); ++it)
                    {
                                it->Clicked(/*coords*/);
                    }
            }

public:
            void AddButton(Button* butt)
            {
                            Buttons<<butt;
            }

};

class UserWindow:public BaseWindow
{
            Button MyButton;
public:
            void FunctionForButton(Button* butt){ cout<<"Say Hello, my sweet button";}

            UserWindow():MyButton(this)
            {
                        MyButton.SetBehavior(/*Put here my Function for Button and my pointer*/);
            }
};
</code>```

答:
You might consider using some "pure" abstract classes (nice to conceptually think of as interfaces so I'll call them that!) to create an ad hoc protocol for handling these events.

Examples:

```<code>class IEventHandler
{
public:
    virtual ~IEventHandler() { }
    virtual void HandleEvent(IEventData* const pEventData) = 0;
};
</code>```

IEventHandler provides a simple abstract base class interface for handling events, declaring a method called HandleEvent, accepting an argument of pointer to IEventData.

```<code>class IEventData
{
public:
    virtual ~IEventData() = 0;
};

inline IEventData::~IEventData()
{
}
</code>```

IEventData provides a simple abstract base class interface for providing data to IEventHandler::HandleEvent.

Then (using your original pseudo-code as a starting point, embellished with more pseudo-code :-)):

```<code>class BaseWindow;

class Button
{
public:
            Button(BaseWindow* parent)
            : pEventHandler_(NULL)
            {
                        parent->AddButton(this);
            }

            void SetBehavior(IEventHandler* pEventHandler)
            {
                        /* Save Owner pointer and owner's method*/
                        pEventHandler_ = pEventHandler;
            }

            void Clicked(/*coords*/)
            {
                        if(/*coords == my coords*/)
                        {
                                    IEventData* pData = new CoordinateEventData(/*coords*/);
                                    /*Call Owner's method*/
                                    pEventHandler_->HandleEvent(pData);
                                    delete pData; /* if ownership not transferred to handler */
                        }
            }
protected:
            IEventHandler* pEventHandler_;
};

class BaseWindow
{
            vector<Button*> Buttons;

            WindowClicked(/*coords*/)
            {
                    for(auto i:Buttons)
                    {
                                i->Clicked(/*coords*/);
                    }
            }

public:
            void AddButton(Button* butt)
            {
                            Buttons<<butt;
            }

};

class UserWindow:public BaseWindow
{
            Button MyButton;
public:
            void FunctionForButton(Button* butt){ cout<<"Say Hello, my sweet button";}

            UserWindow():MyButton(this)
            {
                        IEventHandler* pHandler = new CoordinateEventHandler(/*things and stuff*/);
                        MyButton.SetBehavior(pHandler);
            }
};
</code>```

You would package the data applicable to the coordinates from your Button::Clicked method into the CoordinateEventData.

You would transition/adapt the implementation of your UserWindow::FunctionForButton method to the CoordinateEventHandler::HandleEvent method.

Alternately, you could have UserWindow "implement" (derive from) IEventHandler and implement IEventHandler::HandleEvent using the code from (or by calling) UserWindow::FunctionForButton, and use MyButton.SetBehavior(this) to wire it up.

As usual, you'll want to be mindful of pointer ownership to avoid leaks.

Hope that gives you some ideas...

Body:
Example:
Suppose we are developing a simple graphical interface:

We have windows and controls. What do we want:

There is a base window class that implements the GUI functionality
hidden from the user.

From the base window, the user inherits a specific window.

There is a class of a button, an instance of which the user can add to his window.

The user can transfer the method of his window to button, and it will be executed when clicking this button.

I'm interested in how to reach the last point.

Kind of pseudo-code:

class BaseWindow;

class Button
{
public:
            Button(BaseWindow* parent)
            {
                        parent->AddButton(this);
            }

            void SetBehavior(/*Owners pointer and owner's methos*/)
            {
                        /* Save Owner pointer and owner's method*/
            }

            void Clicked(/*coords*/)
            {
                        if(/*coords == my coords*/)
                        {
                                    /*Call Owner's method*/
                        }
            }
};

class BaseWindow
{
            vector<Button*> Buttons;

            WindowClicked(/*coords*/)
            {
                    for (std::vector<Button*>::iterator it = Buttons.begin(); it != Buttons.end(); ++it)
                    {
                                it->Clicked(/*coords*/);
                    }
            }

public:
            void AddButton(Button* butt)
            {
                            Buttons<<butt;
            }

};

class UserWindow:public BaseWindow
{
            Button MyButton;
public:
            void FunctionForButton(Button* butt){ cout<<"Say Hello, my sweet button";}

            UserWindow():MyButton(this)
            {
                        MyButton.SetBehavior(/*Put here my Function for Button and my pointer*/);
            }
};

Body:
You might consider using some "pure" abstract classes (nice to conceptually think of as interfaces so I'll call them that!) to create an ad hoc protocol for handling these events.

Examples:

class IEventHandler
{
public:
    virtual ~IEventHandler() { }
    virtual void HandleEvent(IEventData* const pEventData) = 0;
};

IEventHandler provides a simple abstract base class interface for handling events, declaring a method called HandleEvent, accepting an argument of pointer to IEventData.

class IEventData
{
public:
    virtual ~IEventData() = 0;
};

inline IEventData::~IEventData()
{
}

IEventData provides a simple abstract base class interface for providing data to IEventHandler::HandleEvent.

Then (using your original pseudo-code as a starting point, embellished with more pseudo-code :-)):

class BaseWindow;

class Button
{
public:
            Button(BaseWindow* parent)
            : pEventHandler_(NULL)
            {
                        parent->AddButton(this);
            }

            void SetBehavior(IEventHandler* pEventHandler)
            {
                        /* Save Owner pointer and owner's method*/
                        pEventHandler_ = pEventHandler;
            }

            void Clicked(/*coords*/)
            {
                        if(/*coords == my coords*/)
                        {
                                    IEventData* pData = new CoordinateEventData(/*coords*/);
                                    /*Call Owner's method*/
                                    pEventHandler_->HandleEvent(pData);
                                    delete pData; /* if ownership not transferred to handler */
                        }
            }
protected:
            IEventHandler* pEventHandler_;
};

class BaseWindow
{
            vector<Button*> Buttons;

            WindowClicked(/*coords*/)
            {
                    for(auto i:Buttons)
                    {
                                i->Clicked(/*coords*/);
                    }
            }

public:
            void AddButton(Button* butt)
            {
                            Buttons<<butt;
            }

};

class UserWindow:public BaseWindow
{
            Button MyButton;
public:
            void FunctionForButton(Button* butt){ cout<<"Say Hello, my sweet button";}

            UserWindow():MyButton(this)
            {
                        IEventHandler* pHandler = new CoordinateEventHandler(/*things and stuff*/);
                        MyButton.SetBehavior(pHandler);
            }
};

You would package the data applicable to the coordinates from your Button::Clicked method into the CoordinateEventData.

You would transition/adapt the implementation of your UserWindow::FunctionForButton method to the CoordinateEventHandler::HandleEvent method.

Alternately, you could have UserWindow "implement" (derive from) IEventHandler and implement IEventHandler::HandleEvent using the code from (or by calling) UserWindow::FunctionForButton, and use MyButton.SetBehavior(this) to wire it up.

As usual, you'll want to be mindful of pointer ownership to avoid leaks.

Hope that gives you some ideas...


问:
Is String str = new String("my string") really less efficient?
I often saw people saying String str = new String("my string") is less efficient than writing String str = "my string", because the former creates a static "my string" object and then new's a String object that gets copied from the static one.

However, given that the language here is so simple and unambiguous, I can hardly imagine that Java optimizer won't take any effort to simply convert the former to the latter. Why would it really choose to do it the more laborious way? What can any negative side effects be if Java does optimize it?

答:
You should always write the simplest, clearest code you can. Developer efficiency is more important than processor efficiency 90+% of the time. So even if the JIT could optimise it, which it doesn't, you are placing a burden on the developer to work out; why is this code more complicated than it needs to be? and the hardest answer to find is; no good reason at all.

Why would it really choose to do it the more laborious way?

When people migrate from other languages like C++ they take their idioms with them. In C++ for example you would need to write new string("some text") but in Java this is needlessly redundant.

What can any negative side effects be if Java does optimize it?

Java can optimise it with escape analysis. If the String doesn't escape the current method after inlining, the new String can be places on the stack and thus eliminated as it's redundant. But that is beside the point. You have already made life harder for anyone who has to maintain the code and the JIT won't help you with that.


问:
setting up routes with navigation menu angular 2
I have a tab menu and i set up my routes in my app.module.ts but i am not sure how to bridge between my tabs and my routes appropriately.

here is my tab html:

```<code><tabs>
    <tab [tabTitle]="'Home Page'">
    </tab>
    <tab tabTitle="Feedback"> </tab>
    <tab tabTitle="Background"> </tab>
    <tab tabTitle="What we do"> </tab>
</tabs>
</code>```

my routes in app.module.ts:

```<code>const appRoutes: Routes = [
  { path: './app/homepage/homepage.component.html', component: AppComponent },
  { path: './app/feedback/feedback.component.html', component: FeedbackComponent },
  { path: './app/background/background.component.html', component: BackgroundComponent },
  { path: './app/whatwedo/whatwedo.component.html', component: WhatwedoComponent}
];
</code>```

What are the steps i need to take to link the tabs with the correct route link.

答:
follow this example from this page https://material.angular.io/

here

```<code>    <li *ngFor="let component of category.items">
      <a [routerLink]="['/components/component/', component.id]"
         routerLinkActive="docs-component-viewer-sidenav-item-
  selected">
        {{component.name}}
      </a>
    </li>
</code>```

one key point is

```<code>[routerLink]="['/components/component/', component.id]"
</code>```

ante router will look like this

```<code>  {
    path: 'components',
    component: ComponentSidenav,
    children: [

    {path: 'components/:id', component: ComponentViewer},
    ],
   },
</code>```

notice that the component that the parent and the child component have absolute paths, it will work

Body:
I have a tab menu and i set up my routes in my app.module.ts but i am not sure how to bridge between my tabs and my routes appropriately.

here is my tab html:

<tabs>
    <tab [tabTitle]="'Home Page'">
    </tab>
    <tab tabTitle="Feedback"> </tab>
    <tab tabTitle="Background"> </tab>
    <tab tabTitle="What we do"> </tab>
</tabs>

my routes in app.module.ts:

const appRoutes: Routes = [
  { path: './app/homepage/homepage.component.html', component: AppComponent },
  { path: './app/feedback/feedback.component.html', component: FeedbackComponent },
  { path: './app/background/background.component.html', component: BackgroundComponent },
  { path: './app/whatwedo/whatwedo.component.html', component: WhatwedoComponent}
];

What are the steps i need to take to link the tabs with the correct route link.

Body:
follow this example from this page https://material.angular.io/

here

    <li *ngFor="let component of category.items">
      <a [routerLink]="['/components/component/', component.id]"
         routerLinkActive="docs-component-viewer-sidenav-item-
  selected">
        {{component.name}}
      </a>
    </li>

one key point is

[routerLink]="['/components/component/', component.id]"

ante router will look like this

  {
    path: 'components',
    component: ComponentSidenav,
    children: [

    {path: 'components/:id', component: ComponentViewer},
    ],
   },

notice that the component that the parent and the child component have absolute paths, it will work


问:
How can I override confirm dialog box in Dropzone.js?
I am trying to implement dropzone on my project. I have created a custom confirm dialog box and I have used it on every parts of my project. I want to use the same custom confirm dialog box on dropzone as well. How can I do it?</p>

```<code>const initDropzone = (obj) => {
const newobj = obj;
console.log(newobj);
console.log(newobj.options);
newobj.confirm = function (question, accepted, rejected) {
  console.log('asking question');
  mscConfirm({
    title: 'Management Console',
    subtitle: question,
    dismissOverlay: true,
    onOk() {
      accepted();
    },
  });
};
return newobj;
}
</code>```

答:
Here is what worked for me... I have added this code:

```<code>$("div#resource_upload_{{ $lecture->id }}").dropzone({

    // here go your other dropzone options

    // this option stops the files form auto-uploading
    autoProcessQueue: false,

    // here we add the question
    init: function (){

    // get the dropzone object
    myDropzone = this;

    // overwrite the addedfile function
    myDropzone.on("addedfile", function(event) {

        // this is my confirm function, you can insert your
        var r = confirm("Press a button!");

        if (r == true) {
            txt = "You pressed OK!";
            // this starts the upload proces....
            myDropzone.processQueue();
        } else {
            // ...or not
            txt = "You pressed Cancel!";
        }
    });
});
</code>```

So, autoProcessQueue stops the files from uploading, and then you overwrite the "addedfile" function, and do as you please in it.
myDropzone.processQueue() continues the file upload.

Hope this helps.

Body:
I am trying to implement dropzone on my project. I have created a custom confirm dialog box and I have used it on every parts of my project. I want to use the same custom confirm dialog box on dropzone as well. How can I do it?

const initDropzone = (obj) => {
const newobj = obj;
console.log(newobj);
console.log(newobj.options);
newobj.confirm = function (question, accepted, rejected) {
  console.log('asking question');
  mscConfirm({
    title: 'Management Console',
    subtitle: question,
    dismissOverlay: true,
    onOk() {
      accepted();
    },
  });
};
return newobj;
}

Body:
Here is what worked for me... I have added this code:

$("div#resource_upload_{{ $lecture->id }}").dropzone({

    // here go your other dropzone options

    // this option stops the files form auto-uploading
    autoProcessQueue: false,

    // here we add the question
    init: function (){

    // get the dropzone object
    myDropzone = this;

    // overwrite the addedfile function
    myDropzone.on("addedfile", function(event) {

        // this is my confirm function, you can insert your
        var r = confirm("Press a button!");

        if (r == true) {
            txt = "You pressed OK!";
            // this starts the upload proces....
            myDropzone.processQueue();
        } else {
            // ...or not
            txt = "You pressed Cancel!";
        }
    });
});

So, autoProcessQueue stops the files from uploading, and then you overwrite the "addedfile" function, and do as you please in it.
myDropzone.processQueue() continues the file upload.

Hope this helps.


问:
Cover Flow Advice
I need to implement cover flow in our iphone app. Our app need to display images from server. We already have webservice to return list of pictures. Number of pictures will grow over time to 1000s of pictures.

Here I need your help to decide which library is good for my situation without any memory issues. and any experiences you have in similar scenario.

I appreciate any input you can give in my scenario

Here is list of libraries in mind.

tapkul

OpenFlow

FlowCover

Please help deciding which library to use and

答:
I can't help on the issue of which library is best to use, but be aware apps have been rejected in the past for doing including cover-flow like features.

If you really must include cover-flow functionality, I'd recommend you write a little test app with each of the available libraries and see which fits your requirements the best.  You might also try memory profiling the different solutions and see which consumes the least resources.

There probably isn't a "one size fits all" answer to this question, as everyone's requirements will be slightly different.

Title: Cover Flow Advice


问:
php Mysql issue with a prepared query in joint table
I'm creating an app, and I have a joint table between Blog posts and Comments.
So let say I have a page with the list of posts, when I want to see the detail view then I put the Id of that post in parameter in the url which I hydrate my setters with somewhere in my app.
In that detail view of the post I have a form to add comments; however when I try to insert the IDs of both the post and the comment itself, It doesn't work here is my query/method that does that:

```<code>Public function insertPost(Articles $article)
    {
//here I insert the comment
        $sql = $this->getBdd()->prepare('INSERT INTO comments(comment, date_comment)
                                                    VALUES (?,NOW())');
        $sql->execute(array($article->getContent()));

//here I try to insert the ID of the comment and the related ID of my post (since I added the class as a dependency in my method I can still get the id)
        $sql2 = $this->getBdd()->prepare('
INSERT INTO joint_a_comments(id_comment,id_article)
SELECT comments.id, articles.id
FROM comments, articles
WHERE comments.id = (SELECT id FROM comments ORDER BY id DESC LIMIT 0,1)
                                                    AND articles.id = "'.$article->getId().'" ');
        $sql2->execute();
    }
</code>```

Do you guys see anything wrong?

Thanks for your help!

答:
If the id is an AUTO_INCREMENT column, you can use SELECT LAST_INSERT_ID() right after the execution of the first INSERT statement. LAST_INSERT_ID() will return the inserted value of an AUTO_INCREMENT column.

Try this one:

```<code>public function insertPost(Articles $article)
{
    $db = $this->getBdd();
    //here I insert the comment
    $sql = $db->prepare(
        'INSERT INTO comments(comment, date_comment) VALUES (?,NOW())'
    );

    $sql->execute(array($article->getContent()));
    $commentId = $db->query('SELECT LAST_INSERT_ID()')->fetchColumn();

    //here I try to insert the ID of the comment and the related ID of my post (since I added the class as a dependency in my method I can still get the id)
    $sql2 = $db->prepare(
        'INSERT INTO joint_a_comments(id_comment,id_article)
            SELECT comments.id, articles.id
            FROM comments, articles
            WHERE
                comments.id = ? AND
                articles.id = ?'
    );

    $sql2->execute([$commentId, $article->getId()]);
}
</code>```

Body:
I'm creating an app, and I have a joint table between Blog posts and Comments.
So let say I have a page with the list of posts, when I want to see the detail view then I put the Id of that post in parameter in the url which I hydrate my setters with somewhere in my app.
In that detail view of the post I have a form to add comments; however when I try to insert the IDs of both the post and the comment itself, It doesn't work here is my query/method that does that:

Public function insertPost(Articles $article)
    {
//here I insert the comment
        $sql = $this->getBdd()->prepare('INSERT INTO comments(comment, date_comment)
                                                    VALUES (?,NOW())');
        $sql->execute(array($article->getContent()));

//here I try to insert the ID of the comment and the related ID of my post (since I added the class as a dependency in my method I can still get the id)
        $sql2 = $this->getBdd()->prepare('
INSERT INTO joint_a_comments(id_comment,id_article)
SELECT comments.id, articles.id
FROM comments, articles
WHERE comments.id = (SELECT id FROM comments ORDER BY id DESC LIMIT 0,1)
                                                    AND articles.id = "'.$article->getId().'" ');
        $sql2->execute();
    }

Do you guys see anything wrong?

Thanks for your help!

Body:
If the id is an AUTO_INCREMENT column, you can use SELECT LAST_INSERT_ID() right after the execution of the first INSERT statement. LAST_INSERT_ID() will return the inserted value of an AUTO_INCREMENT column.

Try this one:

public function insertPost(Articles $article)
{
    $db = $this->getBdd();
    //here I insert the comment
    $sql = $db->prepare(
        'INSERT INTO comments(comment, date_comment) VALUES (?,NOW())'
    );

    $sql->execute(array($article->getContent()));
    $commentId = $db->query('SELECT LAST_INSERT_ID()')->fetchColumn();

    //here I try to insert the ID of the comment and the related ID of my post (since I added the class as a dependency in my method I can still get the id)
    $sql2 = $db->prepare(
        'INSERT INTO joint_a_comments(id_comment,id_article)
            SELECT comments.id, articles.id
            FROM comments, articles
            WHERE
                comments.id = ? AND
                articles.id = ?'
    );

    $sql2->execute([$commentId, $article->getId()]);
}