问:
Scrollview flashing when inflating view and calling scrollBy
I am developing an Android application where an activity displays content in a scrollview. At the top of the content there is a placeholder for an image to be displayed. The image is downloaded from the Internet and may take a few seconds until it is ready to be displayed. The image placeholder is initially empty. When the image is downloaded, it is dynamically added to the placeholder.

Initially I had the following problem.

The user starts the activity and scrolls down

The image starts to download in the background. When available, it is added to the placeholder

When the image is added to the placeholder, the contents of the scrollview change and the user experience is disrupted by the unwanted scrolling that occurs

To fix this, I added code to adjust the scroll position once the image view is added to the placeholder. The problem with this is that a flickering is caused on the scrollview during the display-image and adjust-scrollview process. The reason is that the scrollBy function is called from a runnable. Calling scrollBy outside the runnable does not cause flickering but the scroll position is incorrect - the reason for this is that there is not enough time for the items on the scroll view to recalculate/measure their dimensions/heights.

Here is a sample application the illustrates this problem:

```<code>public class MainActivity extends AppCompatActivity {

    ScrollView scrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        scrollView = findViewById(R.id.scrollview);

        startImageDownload();
        simulateImageScroll();
    }

    private void simulateImageScroll() {
        // scroll to the bottom of the scroll view
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.scrollTo(0, scrollView.getMaxScrollAmount());
            }
        });
    }

    private void startImageDownload() {
        Handler handler = new Handler(getMainLooper());
        // simulate a delay for the image download to illustrate the flashing problem in the scrollview
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                displayImage("");
            }
        }, 2000);

    }

    // when the image is downloaded we add it to the image container
    private void displayImage(String imageFilename) {
        // dynamically create an image and add it to the image container layout
        RelativeLayout container = findViewById(R.id.imageContainer);
        ImageView img = new ImageView(this);

        // image should be loaded from the given filename - for now use a solid background and fixed height
        img.setBackgroundColor(Color.BLUE);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, 500);
        container.addView(img, params);

        adjustScrolling(container);
    }

    private void adjustScrolling(RelativeLayout container) {
        // adjust scroll if the image is loaded before the current content
        if (scrollView.getScrollY() > container.getTop()) {
            container.measure(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            final int amountToScroll = container.getMeasuredHeight();

            // the following does not cause flickering but scrolls to the wrong position
            //scrollView.scrollBy(0, amountToScroll);

            // adjust the scrollview so that it keeps the current view unchanged
            scrollView.post(new Runnable() {
                @Override
                public void run() {
                    // this causes flickering but scrolls to the correct position
                    scrollView.scrollBy(0, amountToScroll);
                }
            });
        }
    }

}
</code>```

And here is the layout file:

```<code><ScrollView
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/imageContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:background="#aa0000" >

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:background="#aa0000" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="1"
                android:textColor="#ffffff"
                android:textSize="128dp"/>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:background="#aa0000" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="2"
                android:textColor="#ffffff"
                android:textSize="128dp"/>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:background="#aa0000" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="3"
                android:textColor="#ffffff"
                android:textSize="128dp"/>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:background="#aa0000" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="4"
                android:textColor="#ffffff"
                android:textSize="128dp"/>
        </RelativeLayout>

    </LinearLayout>
</ScrollView>
</code>```

Any ideas on how to fix this problem?

答:
Edited:
Currently, your layout is flickering, because adding blue view cause redraw layout (and scroll). So scroll occurred once, and next you scrolled to the position you want. That's the second moving.

To solve this problem, you need to know how android draws view.
https://developer.android.com/guide/topics/ui/how-android-draws.html

Simply, onMeasure() - onLayout() - onDraw(). And you can add your layout code between onLayout() and onDraw(), by ViewTreeObserver().addOnGlobalLayoutListener().

https://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html

ps: I still recommend using nice and lovely image library, Picasso.

Fixed code is: Set scroll before draw() called. By this, you can draw only once.

```<code>public class MainActivity extends AppCompatActivity {

    ScrollView scrollView;
    int amountToScroll = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        scrollView = findViewById(R.id.scrollview);
        scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                scrollView.scrollBy(0, amountToScroll);
                amountToScroll = 0;
            }
        });
        startImageDownload();
        simulateImageScroll();
    }

    private void simulateImageScroll() {
        // scroll to the bottom of the scroll view
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.scrollTo(0, scrollView.getMaxScrollAmount());
            }
        });
    }

    private void startImageDownload() {
        Handler handler = new Handler(getMainLooper());
        // simulate a delay for the image download to illustrate the flashing problem in the scrollview
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                displayImage("");
            }
        }, 2000);

    }

    // when the image is downloaded we add it to the image container
    private void displayImage(String imageFilename) {
        // dynamically create an image and add it to the image container layout
        RelativeLayout container = findViewById(R.id.imageContainer);
        ImageView img = new ImageView(this);

        // image should be loaded from the given filename - for now use a solid background and fixed height
        img.setBackgroundColor(Color.BLUE);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, 500);
        container.addView(img, params);

        adjustScrolling(container);
    }

    private void adjustScrolling(RelativeLayout container) {
        // adjust scroll if the image is loaded before the current content
        if (scrollView.getScrollY() > container.getTop()) {
            container.measure(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            amountToScroll = container.getMeasuredHeight();
        }
    }
}
</code>```

I strongly recommend using Picasso. http://square.github.io/picasso/

This one line will fix all of your problem.

```<code>Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
</code>```

You can load your local image file or network image (url) into your imageView.

In your case, remove both startImageDownload() and simulateImageScroll(), and on onResume(), call displayImage().

Fixed displayImage():

```<code>private void displayImage(String imageFilename) {
    // dynamically create an image and add it to the image container layout
    RelativeLayout container = findViewById(R.id.imageContainer);
    ImageView img = new ImageView(this);

    // image should be loaded from the given filename - for now use a solid background and fixed height
    img.setBackgroundColor(Color.BLUE);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, 500);
    container.addView(img, params);
    Picasso.with(this).load(imageFilename).into(img);

    adjustScrolling(container);
}
</code>```

Or, if you want to solve this problem directly for academic reasons,

Do not adjust your scroll. It seems that it is not a real solution to use scrollBy to fix your problem. The real cause is the code that cause the UI to redraw. May be calling invalidate() or something like that.

Adding ImageView programmatically is not a good idea. Because your RecyclerView or ViewHolder of ListView cannot reuse the view, so it cause degrade performance. If you can avoid it, do that. (eg. use xml)

It seems that adding your ImageView to imageContainer is real problem. imageContainer has android:layout_height="wrap_content" property, and this means it has no fixed height, it depends on it's own child. Try to change to fixed value, for example: android:layout_height="500dp"

Body:
I am developing an Android application where an activity displays content in a scrollview. At the top of the content there is a placeholder for an image to be displayed. The image is downloaded from the Internet and may take a few seconds until it is ready to be displayed. The image placeholder is initially empty. When the image is downloaded, it is dynamically added to the placeholder.

Initially I had the following problem.

The user starts the activity and scrolls down

The image starts to download in the background. When available, it is added to the placeholder

When the image is added to the placeholder, the contents of the scrollview change and the user experience is disrupted by the unwanted scrolling that occurs

To fix this, I added code to adjust the scroll position once the image view is added to the placeholder. The problem with this is that a flickering is caused on the scrollview during the display-image and adjust-scrollview process. The reason is that the scrollBy function is called from a runnable. Calling scrollBy outside the runnable does not cause flickering but the scroll position is incorrect - the reason for this is that there is not enough time for the items on the scroll view to recalculate/measure their dimensions/heights.

Here is a sample application the illustrates this problem:

public class MainActivity extends AppCompatActivity {

    ScrollView scrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        scrollView = findViewById(R.id.scrollview);

        startImageDownload();
        simulateImageScroll();
    }

    private void simulateImageScroll() {
        // scroll to the bottom of the scroll view
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.scrollTo(0, scrollView.getMaxScrollAmount());
            }
        });
    }

    private void startImageDownload() {
        Handler handler = new Handler(getMainLooper());
        // simulate a delay for the image download to illustrate the flashing problem in the scrollview
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                displayImage("");
            }
        }, 2000);

    }

    // when the image is downloaded we add it to the image container
    private void displayImage(String imageFilename) {
        // dynamically create an image and add it to the image container layout
        RelativeLayout container = findViewById(R.id.imageContainer);
        ImageView img = new ImageView(this);

        // image should be loaded from the given filename - for now use a solid background and fixed height
        img.setBackgroundColor(Color.BLUE);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, 500);
        container.addView(img, params);

        adjustScrolling(container);
    }

    private void adjustScrolling(RelativeLayout container) {
        // adjust scroll if the image is loaded before the current content
        if (scrollView.getScrollY() > container.getTop()) {
            container.measure(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            final int amountToScroll = container.getMeasuredHeight();

            // the following does not cause flickering but scrolls to the wrong position
            //scrollView.scrollBy(0, amountToScroll);

            // adjust the scrollview so that it keeps the current view unchanged
            scrollView.post(new Runnable() {
                @Override
                public void run() {
                    // this causes flickering but scrolls to the correct position
                    scrollView.scrollBy(0, amountToScroll);
                }
            });
        }
    }

}

And here is the layout file:

<ScrollView
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/imageContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:background="#aa0000" >

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:background="#aa0000" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="1"
                android:textColor="#ffffff"
                android:textSize="128dp"/>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:background="#aa0000" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="2"
                android:textColor="#ffffff"
                android:textSize="128dp"/>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:background="#aa0000" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="3"
                android:textColor="#ffffff"
                android:textSize="128dp"/>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:background="#aa0000" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="4"
                android:textColor="#ffffff"
                android:textSize="128dp"/>
        </RelativeLayout>

    </LinearLayout>
</ScrollView>

Any ideas on how to fix this problem?

Body:
Edited:
Currently, your layout is flickering, because adding blue view cause redraw layout (and scroll). So scroll occurred once, and next you scrolled to the position you want. That's the second moving.

To solve this problem, you need to know how android draws view.
https://developer.android.com/guide/topics/ui/how-android-draws.html

Simply, onMeasure() - onLayout() - onDraw(). And you can add your layout code between onLayout() and onDraw(), by ViewTreeObserver().addOnGlobalLayoutListener().

https://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html

ps: I still recommend using nice and lovely image library, Picasso.

Fixed code is: Set scroll before draw() called. By this, you can draw only once.

public class MainActivity extends AppCompatActivity {

    ScrollView scrollView;
    int amountToScroll = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        scrollView = findViewById(R.id.scrollview);
        scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                scrollView.scrollBy(0, amountToScroll);
                amountToScroll = 0;
            }
        });
        startImageDownload();
        simulateImageScroll();
    }

    private void simulateImageScroll() {
        // scroll to the bottom of the scroll view
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.scrollTo(0, scrollView.getMaxScrollAmount());
            }
        });
    }

    private void startImageDownload() {
        Handler handler = new Handler(getMainLooper());
        // simulate a delay for the image download to illustrate the flashing problem in the scrollview
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                displayImage("");
            }
        }, 2000);

    }

    // when the image is downloaded we add it to the image container
    private void displayImage(String imageFilename) {
        // dynamically create an image and add it to the image container layout
        RelativeLayout container = findViewById(R.id.imageContainer);
        ImageView img = new ImageView(this);

        // image should be loaded from the given filename - for now use a solid background and fixed height
        img.setBackgroundColor(Color.BLUE);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, 500);
        container.addView(img, params);

        adjustScrolling(container);
    }

    private void adjustScrolling(RelativeLayout container) {
        // adjust scroll if the image is loaded before the current content
        if (scrollView.getScrollY() > container.getTop()) {
            container.measure(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            amountToScroll = container.getMeasuredHeight();
        }
    }
}

I strongly recommend using Picasso. http://square.github.io/picasso/

This one line will fix all of your problem.

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

You can load your local image file or network image (url) into your imageView.

In your case, remove both startImageDownload() and simulateImageScroll(), and on onResume(), call displayImage().

Fixed displayImage():

private void displayImage(String imageFilename) {
    // dynamically create an image and add it to the image container layout
    RelativeLayout container = findViewById(R.id.imageContainer);
    ImageView img = new ImageView(this);

    // image should be loaded from the given filename - for now use a solid background and fixed height
    img.setBackgroundColor(Color.BLUE);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, 500);
    container.addView(img, params);
    Picasso.with(this).load(imageFilename).into(img);

    adjustScrolling(container);
}

Or, if you want to solve this problem directly for academic reasons,

Do not adjust your scroll. It seems that it is not a real solution to use scrollBy to fix your problem. The real cause is the code that cause the UI to redraw. May be calling invalidate() or something like that.

Adding ImageView programmatically is not a good idea. Because your RecyclerView or ViewHolder of ListView cannot reuse the view, so it cause degrade performance. If you can avoid it, do that. (eg. use xml)

It seems that adding your ImageView to imageContainer is real problem. imageContainer has android:layout_height="wrap_content" property, and this means it has no fixed height, it depends on it's own child. Try to change to fixed value, for example: android:layout_height="500dp"


来源: stackexchange

问:
I have a weird error that pops up when I compile referring to std::ostream
the error makes no sense to me, I've done stuff like this before and followed it to a tee but now it just pops up.

```<code>#ifndef MATRICA_HPP_INCLUDED
#define MATRICA_HPP_INCLUDED

#include <iostream>
#include <cstdio>

#define MAX_POLJA 6
using namespace std;

class Matrica {
private:
short int **mtr;
short int **ivicaX;
short int **ivicaY;
int lenX, lenY;
public:
Matrica(short int, short int);
~Matrica();

int initiate_edge(const char *, const char *);
short int get_vrednost (short int, short int) const;
short int operator = (const short int);
int check_if_fit(int *);

friend ostream& operator << (ostream&, const Matrica&) const; // HAPPENS HERE <====
};

#endif // MATRICA_HPP_INCLUDED
</code>```

this is the error:

error: non-member function 'std::ostream& operator<<(std::ostream&, const Matrica&)' cannot have cv-qualifier|

答:
```<code>friend ostream& operator << (ostream&, const Matrica&) const;
</code>```

You declare ostream& operator << (ostream&, const Matrica&) as friend, which makes it a free function, not a member function. Free functions do not have the this pointer, which is being affected by const modifier at the end of function declarations. It means that if you have a free function, you cannot make it a const function, since there is no this pointer to be affected by it. Simply delete it like so:

```<code>friend ostream& operator << (ostream&, const Matrica&);
</code>```

And you are ready to go.

ContentLicense: CC BY-SA 3.0

Body:
the error makes no sense to me, I've done stuff like this before and followed it to a tee but now it just pops up.

#ifndef MATRICA_HPP_INCLUDED
#define MATRICA_HPP_INCLUDED

#include <iostream>
#include <cstdio>

#define MAX_POLJA 6
using namespace std;

class Matrica {
private:
short int **mtr;
short int **ivicaX;
short int **ivicaY;
int lenX, lenY;
public:
Matrica(short int, short int);
~Matrica();

int initiate_edge(const char *, const char *);
short int get_vrednost (short int, short int) const;
short int operator = (const short int);
int check_if_fit(int *);

friend ostream& operator << (ostream&, const Matrica&) const; // HAPPENS HERE <====
};

#endif // MATRICA_HPP_INCLUDED

this is the error:

error: non-member function 'std::ostream& operator<<(std::ostream&, const Matrica&)' cannot have cv-qualifier|

Body:
friend ostream& operator << (ostream&, const Matrica&) const;

You declare ostream& operator << (ostream&, const Matrica&) as friend, which makes it a free function, not a member function. Free functions do not have the this pointer, which is being affected by const modifier at the end of function declarations. It means that if you have a free function, you cannot make it a const function, since there is no this pointer to be affected by it. Simply delete it like so:

friend ostream& operator << (ostream&, const Matrica&);

And you are ready to go.


问:
Purpose of Immutable or Unmodifiable Collections
What are the real benefits of Immutable or Unmodifiable collections, or objects?

As programmers, we try to write code without bugs, such that a user cannot break the system, and that bad actors cannot hack into it. To me, Immutable objects seem to try to prevent programmers from making silly mistakes.

Is there more to it than that?

答: Immutable classes and collections really help to avoid concurrency issues with multiple threads trying to modify the same objects.</p>


问:
Get price of phone number from Twilio
I am trying to get the price of a phone number in Twilio. I have this to get the phone numbers

```<code>var localAvailableNumbers = Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry.LocalResource.Read("US");
</code>```

And this to get the prices

```<code>var prices = Twilio.Rest.Pricing.V1.PhoneNumber.CountryResource.Fetch("US");
</code>```

But I can't see any way to map each of the phone numbers to a price?

This is an example of the response from the phone numbers request

```<code>{
  "uri": "\/2010-04-01\/Accounts\/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\/AvailablePhoneNumbers\/US\/Local.json?AreaCode=510",
  "available_phone_numbers": [
    {
      "friendly_name": "(510) 564-7903",
      "phone_number": "+15105647903",
      "lata": "722",
      "rate_center": "OKLD TRNID",
      "latitude": "37.780000",
      "longitude": "-122.380000",
      "region": "CA",
      "postal_code": "94703",
      "iso_country": "US",
      "capabilities":{
        "voice": true,
        "SMS": true,
        "MMS": false
      },
      "beta": false
    }
  ]
}
</code>```

Nowhere does it tell me if this is local, mobile, toll free etc.

答:
Phone numbers are priced by location and type, so all phone numbers in [Country] of [Type] will be the same price.

In your code above you are querying the Pricing API for US phone number prices so you'll get two PhoneNumberPrice records back that tell you the price of local and toll free numbers, each of which has a NumberType property that tells you the type of number the price applies to.  If you made the same query for another country like the UK you might get local, mobile, national and toll free prices.

```<code>var country = Twilio.Rest.Pricing.V1.PhoneNumber.CountryResource.Fetch("US");
var prices = country.PhoneNumberPrices;
foreach(var price in prices)
{
    Console.Writeline(price.NumberType.ToString());
}
</code>```

Now, when you know the price for the country and type, you can query for available phone numbers of one of those types.  In your code above your asking for Local US phone numbers which will all be $1/month.

Hope that helps.

Title: Get price of phone number from Twilio

Body:
I am trying to get the price of a phone number in Twilio. I have this to get the phone numbers

var localAvailableNumbers = Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry.LocalResource.Read("US");

And this to get the prices

var prices = Twilio.Rest.Pricing.V1.PhoneNumber.CountryResource.Fetch("US");

But I can't see any way to map each of the phone numbers to a price?

This is an example of the response from the phone numbers request

{
  "uri": "\/2010-04-01\/Accounts\/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\/AvailablePhoneNumbers\/US\/Local.json?AreaCode=510",
  "available_phone_numbers": [
    {
      "friendly_name": "(510) 564-7903",
      "phone_number": "+15105647903",
      "lata": "722",
      "rate_center": "OKLD TRNID",
      "latitude": "37.780000",
      "longitude": "-122.380000",
      "region": "CA",
      "postal_code": "94703",
      "iso_country": "US",
      "capabilities":{
        "voice": true,
        "SMS": true,
        "MMS": false
      },
      "beta": false
    }
  ]
}

Nowhere does it tell me if this is local, mobile, toll free etc.

Body:
Phone numbers are priced by location and type, so all phone numbers in [Country] of [Type] will be the same price.

In your code above you are querying the Pricing API for US phone number prices so you'll get two PhoneNumberPrice records back that tell you the price of local and toll free numbers, each of which has a NumberType property that tells you the type of number the price applies to.  If you made the same query for another country like the UK you might get local, mobile, national and toll free prices.

var country = Twilio.Rest.Pricing.V1.PhoneNumber.CountryResource.Fetch("US");
var prices = country.PhoneNumberPrices;
foreach(var price in prices)
{
    Console.Writeline(price.NumberType.ToString());
}

Now, when you know the price for the country and type, you can query for available phone numbers of one of those types.  In your code above your asking for Local US phone numbers which will all be $1/month.

Hope that helps.


问:
Can I return fields as nested objects on Sequelize js?
I have the following query in sequelize.js:

```<code>getBookingById: (req, res) => {
  models.booking.findAll({
    where: {
      id: { $in: [1, 2, 3] },
    },
    include: [{
      model: models.cust,
      attributes: ['name', 'id'],
    }],
    attributes: [['id', 'bookingId'], 'propertyKey', 'propertyId'] })
  .then((result) => {
    if (!result) return res.status(204);

    return res.status(200).json(result);
  }).catch(err => res.status(500);
};
</code>```

My response is as following:

```<code>[{
   "bookingId": 1,
   "propertyKey": "ABC",
   "propertyId": "123",
   "cust": {
      "name": "David David",
      "id": 8
   }
},

{
   "bookingId": 2,
   "propertyKey": "ABC",
   "propertyId": "123",
   "cust": {
      "name": "David David",
      "id": 8
   }
}]
</code>```

I want to return propertyKey and propertyId fields as a nested object as:

```<code>"property": {
   "propertyKey": "ABC",
   "propertyId": "123",
}
</code>```

Is it possible to do it within sequelize query or, should I parse the result after?

答:
You can change result variable before returning.

```<code>  .then((result) => {
    if (!result) return res.status(204);
    for (var i = 0; i < result.length ; i++){
       result[i].property = {
                        "propertyKey" : result.propertyKey ,
                        "propertyId": result.propertyId
                      }
        delete result[i].propertyKey;
        delete result[i].propertyId;
    }
    return res.status(200).json(result);
  }).catch(err => res.status(500);
</code>```

Body:
I have the following query in sequelize.js:

getBookingById: (req, res) => {
  models.booking.findAll({
    where: {
      id: { $in: [1, 2, 3] },
    },
    include: [{
      model: models.cust,
      attributes: ['name', 'id'],
    }],
    attributes: [['id', 'bookingId'], 'propertyKey', 'propertyId'] })
  .then((result) => {
    if (!result) return res.status(204);

    return res.status(200).json(result);
  }).catch(err => res.status(500);
};

My response is as following:

[{
   "bookingId": 1,
   "propertyKey": "ABC",
   "propertyId": "123",
   "cust": {
      "name": "David David",
      "id": 8
   }
},

{
   "bookingId": 2,
   "propertyKey": "ABC",
   "propertyId": "123",
   "cust": {
      "name": "David David",
      "id": 8
   }
}]

I want to return propertyKey and propertyId fields as a nested object as:

"property": {
   "propertyKey": "ABC",
   "propertyId": "123",
}

Is it possible to do it within sequelize query or, should I parse the result after?

Body:
You can change result variable before returning.

  .then((result) => {
    if (!result) return res.status(204);
    for (var i = 0; i < result.length ; i++){
       result[i].property = {
                        "propertyKey" : result.propertyKey ,
                        "propertyId": result.propertyId
                      }
        delete result[i].propertyKey;
        delete result[i].propertyId;
    }
    return res.status(200).json(result);
  }).catch(err => res.status(500);


问:
Order the elements of an array (Swift)
I have this code that I use to download nearby places (I'm working with Google place API).

```<code>if let response = response {
    self.response = response
    if response.status == "OK" {
        if let placesDownloaded = response.places {
            var number = numberPlaces / (categories?.count)!
            number = number == 0 ? 1 : number

            let firstPlace = placesDownloaded.prefix(1)

            var isRestaurant = false
            var isGym = false
            var isSpa = false
            var isBar = false
            var isNight_Club = false
            var isMuseum = false
            var isMovie_Theater = false

            for place in firstPlace {
                for type in place.types! {
                    if (type.lowercased() == "restaurant") {
                        isRestaurant = true
                    }
                    else if (type.lowercased() == "gym") {
                        isGym = true
                    }
                    else if (type.lowercased() == "spa") {
                        isSpa = true
                    }
                    else if (type.lowercased() == "bar") {
                        isBar = true
                    }
                    else if (type.lowercased() == "night_club") {
                        isNight_Club = true
                    }
                    else if (type.lowercased() == "museum") {
                        isMuseum = true
                    }
                    else if (type.lowercased() == "movie_theater") {
                        isMovie_Theater = true
                    }
                }
            }
            if(isRestaurant) && numberPlaces <= 4 {
                number = 1
            }
            else if(isGym) && numberPlaces > 1 {
                number = 1
            }
            else if(isSpa) && numberPlaces <= 6 {
                number = 1
            }
            else if(isNight_Club) && numberPlaces <= 3 {
                number = 1
            }
            else if(isMuseum) && numberPlaces <= 2 {
                number = 1
            }
            else if(isMovie_Theater) && numberPlaces <= 7 {
                number = 1
            }
            else if(isBar) && numberPlaces <= 2 {
                number = 1
            }

            places.append(contentsOf: placesDownloaded.prefix(number))
        }
    }
}
</code>```

What I would like to do is to create an if statement to order the elements of the array categories. For example, something like this:

```<code>else if(isBar) && (isMuseum)  {
    // museum becomes the element [0] of `categories` and bar becomes the element [1]
}
</code>```

But I really don't know how to do this. Can someone help me with an example?

答:
Use Array.sorted() to get an ordered array:

```<code>let sortedCategories = categories.sorted()
</code>```

You can pass a function to sorted() as well if you don't want it just sorted alphabetically but by a sorting function that you define yourself. Here for instance I am getting an array sorted by the length of each string, from shortest to longest:

```<code>let sortedCategoriesByLength = categories.sorted { (first, second) -> Bool in
    return first.count < second.count
}
</code>```

Title: Order the elements of an array (Swift)

Body:
I have this code that I use to download nearby places (I'm working with Google place API).

if let response = response {
    self.response = response
    if response.status == "OK" {
        if let placesDownloaded = response.places {
            var number = numberPlaces / (categories?.count)!
            number = number == 0 ? 1 : number

            let firstPlace = placesDownloaded.prefix(1)

            var isRestaurant = false
            var isGym = false
            var isSpa = false
            var isBar = false
            var isNight_Club = false
            var isMuseum = false
            var isMovie_Theater = false

            for place in firstPlace {
                for type in place.types! {
                    if (type.lowercased() == "restaurant") {
                        isRestaurant = true
                    }
                    else if (type.lowercased() == "gym") {
                        isGym = true
                    }
                    else if (type.lowercased() == "spa") {
                        isSpa = true
                    }
                    else if (type.lowercased() == "bar") {
                        isBar = true
                    }
                    else if (type.lowercased() == "night_club") {
                        isNight_Club = true
                    }
                    else if (type.lowercased() == "museum") {
                        isMuseum = true
                    }
                    else if (type.lowercased() == "movie_theater") {
                        isMovie_Theater = true
                    }
                }
            }
            if(isRestaurant) && numberPlaces <= 4 {
                number = 1
            }
            else if(isGym) && numberPlaces > 1 {
                number = 1
            }
            else if(isSpa) && numberPlaces <= 6 {
                number = 1
            }
            else if(isNight_Club) && numberPlaces <= 3 {
                number = 1
            }
            else if(isMuseum) && numberPlaces <= 2 {
                number = 1
            }
            else if(isMovie_Theater) && numberPlaces <= 7 {
                number = 1
            }
            else if(isBar) && numberPlaces <= 2 {
                number = 1
            }

            places.append(contentsOf: placesDownloaded.prefix(number))
        }
    }
}

What I would like to do is to create an if statement to order the elements of the array categories. For example, something like this:

else if(isBar) && (isMuseum)  {
    // museum becomes the element [0] of `categories` and bar becomes the element [1]
}

But I really don't know how to do this. Can someone help me with an example?

Body:
Use Array.sorted() to get an ordered array:

let sortedCategories = categories.sorted()

You can pass a function to sorted() as well if you don't want it just sorted alphabetically but by a sorting function that you define yourself. Here for instance I am getting an array sorted by the length of each string, from shortest to longest:

let sortedCategoriesByLength = categories.sorted { (first, second) -> Bool in
    return first.count < second.count
}


问:
Keeping pages inside an iframe
I am trying to put a website inside an iframe, but this code on the site keeps changing the window of the page. Is there anyway I can get around this? Or better yet, can I disable javascript in an iframe?</p>

```<code>if(top!=self){
  if(top.location)
    top.location=self.location;
  else
    top.location='http://example.com/not_subframe.html';
}
</code>```

答:
You can only access the content of one frame from within another frame if both frames are from the same domain.

Otherwise this would be an XSS issue which is therefore forbidden by a browser.

ContentLicense: CC BY-SA 2.5

Title: Keeping pages inside an iframe

Body:
I am trying to put a website inside an iframe, but this code on the site keeps changing the window of the page. Is there anyway I can get around this? Or better yet, can I disable javascript in an iframe?

if(top!=self){
  if(top.location)
    top.location=self.location;
  else
    top.location='http://example.com/not_subframe.html';
}


问:
Spring Boot 2.0 disable default security
I want to use Spring Security for JWT authentication. But it comes with default authentication. I am trying to disable it, but the old approach of doing this - disabling it through application.properties - is deprecated in 2.0.

This is what I tried:

```<code>@Configuration
public class StackWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable();
        // http.authorizeRequests().anyRequest().permitAll(); // Also doesn't work.
    }
}
</code>```

How can I simply disable basic security?

UPDATE

It might be nice to know that I am not using web mvc but web flux.

Screenshot:

答:
I think what you are looking for is to override the default authentication entry point which is set to BasicAuthenticationEntryPoint.

This entrypoint adds the

"WWW-Authenticate": "Basic realm=..."

header that tells your browser to use Basic Auth.

ContentLicense: CC BY-SA 4.0

Body:
I want to use Spring Security for JWT authentication. But it comes with default authentication. I am trying to disable it, but the old approach of doing this - disabling it through application.properties - is deprecated in 2.0.

This is what I tried:

@Configuration
public class StackWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable();
        // http.authorizeRequests().anyRequest().permitAll(); // Also doesn't work.
    }
}

How can I simply disable basic security?

UPDATE

It might be nice to know that I am not using web mvc but web flux.

Screenshot:


问:
I can't create server in pgadmin4 (http://127.0.0.1:5050/browser/) on ubuntu

I installed pgadmin4 for my Ubuntu 16.10 and run it on http://127.0.0.1:5050/browser/ but it just have sever group. I create sever but it alert like in picture.

```<code>Unable to connect to server:

could not connect to server: Connection refused
Is the server running on host "htphuocdl-desktop" (127.0.1.1) and accepting
TCP/IP connections on port 5432?
</code>```

答:
Create server:

Please configure host name/address:127.0.0.1 with default IP or custom IP address, Incase if you used custom IP in your application provide proper IP address while configure.

Add following code in your config_local.py

```<code>import os
DATA_DIR = os.path.realpath(os.path.expanduser(u'~/.pgadmin/'))
LOG_FILE = os.path.join(DATA_DIR, 'pgadmin4.log')
SQLITE_PATH = os.path.join(DATA_DIR, 'pgadmin4.db')
SESSION_DB_PATH = os.path.join(DATA_DIR, 'sessions')
STORAGE_DIR = os.path.join(DATA_DIR, 'storage')
SERVER_MODE = True
#Please provide default IP or custom IP address
DEFAULT_SERVER='127.0.0.1'
</code>```

Body:
I installed pgadmin4 for my Ubuntu 16.10 and run it on http://127.0.0.1:5050/browser/ but it just have sever group. I create sever but it alert like in picture.

Unable to connect to server:

could not connect to server: Connection refused
Is the server running on host "htphuocdl-desktop" (127.0.1.1) and accepting
TCP/IP connections on port 5432?

Body:
Create server:

Please configure host name/address:127.0.0.1 with default IP or custom IP address, Incase if you used custom IP in your application provide proper IP address while configure.

Add following code in your config_local.py

import os
DATA_DIR = os.path.realpath(os.path.expanduser(u'~/.pgadmin/'))
LOG_FILE = os.path.join(DATA_DIR, 'pgadmin4.log')
SQLITE_PATH = os.path.join(DATA_DIR, 'pgadmin4.db')
SESSION_DB_PATH = os.path.join(DATA_DIR, 'sessions')
STORAGE_DIR = os.path.join(DATA_DIR, 'storage')
SERVER_MODE = True
#Please provide default IP or custom IP address
DEFAULT_SERVER='127.0.0.1'


问:
Is there any function in Perl similar to GetType() in C#?
I have been learning Perl for a bit now and found it very different from other OOP languages I know.
I tried to translate a C# code which goes like:

```<code>class Car{}, class CarList{}, class Program{}
</code>```

and a method (pseudocode) :

```<code>if (var.GetType() == Car)
{
}
else if (var.GetType == CarList)
{
}
</code>```

how do I write this in perl without a GetType function or is there one?

答: ref should be what you need.</p>

Body:
I have been learning Perl for a bit now and found it very different from other OOP languages I know.
I tried to translate a C# code which goes like:

class Car{}, class CarList{}, class Program{}

and a method (pseudocode) :

if (var.GetType() == Car)
{
}
else if (var.GetType == CarList)
{
}

how do I write this in perl without a GetType function or is there one?

Body: ref should be what you need.


问:
update timestamp just on insert
Last night, I created a column called time in my table, the type is TIMESTAMP and default is CURRENT_TIMESTAMP and attribute is on update CURRENT_TIMESTAMP (all set by default) and it will add timestamp when a new data is inserted, it works fine, and it shows all data (items) on my front page ORDER by this timestamp but this morning I noticed that one of my item's timestamp updated automatically! only hour changed. Now this problem repeated on another item.

Then I figured out that when I open the link to an item (another page that shows all the data belonging to the item), the timestamp will update. In this page I just fetch data from db

```<code>print_r($ads);
</code>```

And the query is simple SELECT FROM TABLE, I'm wondering why this happen?

I know I should post code here, but this is mysql thing and there is no related code. If need, please let me know, then update my post.

Edit: i forget something, when this page open, it increase counter:

```<code>$sql = "UPDATE ads SET view = view + 1 WHERE id = $id";
</code>```

答:
... i just want insert timestamp when new data inserted ...

Change the on update trigger to before insert on. This should limit the time field change action to only when the row is inserted.

Title: update timestamp just on insert

Body:
Last night, I created a column called time in my table, the type is TIMESTAMP and default is CURRENT_TIMESTAMP and attribute is on update CURRENT_TIMESTAMP (all set by default) and it will add timestamp when a new data is inserted, it works fine, and it shows all data (items) on my front page ORDER by this timestamp but this morning I noticed that one of my item's timestamp updated automatically! only hour changed. Now this problem repeated on another item.

Then I figured out that when I open the link to an item (another page that shows all the data belonging to the item), the timestamp will update. In this page I just fetch data from db

print_r($ads);

And the query is simple SELECT FROM TABLE, I'm wondering why this happen?

I know I should post code here, but this is mysql thing and there is no related code. If need, please let me know, then update my post.

Edit: i forget something, when this page open, it increase counter:

$sql = "UPDATE ads SET view = view + 1 WHERE id = $id";


问:
Ambari-Update failed (Ambari 2.4 to 2.6) - Hadoop services won't start anymore
I just worked through this Upgrade guide for the Hortonworks Data Platform:
https://docs.hortonworks.com/HDPDocuments/Ambari-2.6.0.0/bk_ambari-upgrade/bk_ambari-upgrade.pdf

I did all the steps as described in section 1 - 4 (Ambari upgrade). But now I have the problem, that my services won't start anymore!

Ambari can find all hosts, but they won't start!

E.g. for the HDFS starting I got the following error message:

```<code>2017-11-13 19:41:11,427 - Unable to load available packages
Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 771, in load_available_packages
    self.available_packages_in_repos = pkg_provider.get_available_packages_in_repos(repos)
  File "/usr/lib/python2.6/site-packages/resource_management/core/providers/package/yumrpm.py", line 85, in get_available_packages_in_repos
    available_packages.extend(self._get_available_packages(repo))
  File "/usr/lib/python2.6/site-packages/resource_management/core/providers/package/yumrpm.py", line 146, in _get_available_packages
    return self._lookup_packages(cmd, 'Available Packages')
  File "/usr/lib/python2.6/site-packages/resource_management/core/providers/package/yumrpm.py", line 191, in _lookup_packages
    if items[i + 2].find('@') == 0:
IndexError: list index out of range
Traceback (most recent call last):
  File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 73, in <module>
    HdfsClient().execute()
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 367, in execute
    method(env)
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 930, in restart
    self.install(env)
  File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 35, in install
    import params
  File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/params.py", line 25, in <module>
    from params_linux import *
  File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/params_linux.py", line 391, in <module>
    lzo_packages = get_lzo_packages(stack_version_unformatted)
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/functions/get_lzo_packages.py", line 45, in get_lzo_packages
    lzo_packages += [script_instance.format_package_name("hadooplzo_${stack_version}"),
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 538, in format_package_name
    raise Fail("Cannot match package for regexp name {0}. Available packages: {1}".format(name, self.available_packages_in_repos))
resource_management.core.exceptions.Fail: Cannot match package for regexp name hadooplzo_${stack_version}. Available packages: []
</code>```

(I think the most important part is the message resource_management.core.exceptions.Fail: Cannot match package for regexp name hadooplzo_${stack_version}. Available packages: [] which looks like there would be no version (package) available...!

I just saw, that I upgraded also the Ambari Metrics Monitor, Ambari Metrics Hadoop Sink and the Metrics Collector before starting the Services once (the manual is a little bit confusing here, see step 4.3.3)! Was this a mistake?

I tried to upgrade from Ambari 2.4 to Ambari 2.6 (HDP 2.5 installed)! Operating system is CentOS 7.

However, I need to reset / downgrade the Ambari or upgrade the Services to be able to start them again! Can someone help? Any help would be appreciated! Thank you!

答:
Finally I was able to downgrade my Ambari installation back to version 2.4.2 as it was before starting the upgrade process.

To make a downgrade you have to do the following steps on the appropriate nodes:

```<code># delete the new ambari repo file
rm /etc/yum.repos.d/ambari.repo

# download the old ambari repo file (for me version 2.4.2), as described in ambari installation guide (here for Centos 7)
wget -nv http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.4.2.0/ambari.repo -O /etc/yum.repos.d/ambari.repo

yum clean all
yum repolist
# check for the correct version (e.g. 2.4.2) of the Ambari repo

# Downgrade all components to this version
yum downgrade ambari-metrics-monitor
yum downgrade ambari-metrics-hadoop-sink
yum downgrade ambari-agent
...
</code>```

Afterwards I upgraded again, but to Ambari version 2.5.2.0, which now worked without a problem. I also was able to upgrade my HDP installation to version 2.6.3.0 via this Ambari version.

I will skip Ambari 2.6.0 and will try to upgrade Ambari with a later future release.

Body:
I just worked through this Upgrade guide for the Hortonworks Data Platform:
https://docs.hortonworks.com/HDPDocuments/Ambari-2.6.0.0/bk_ambari-upgrade/bk_ambari-upgrade.pdf

I did all the steps as described in section 1 - 4 (Ambari upgrade). But now I have the problem, that my services won't start anymore!

Ambari can find all hosts, but they won't start!

E.g. for the HDFS starting I got the following error message:

2017-11-13 19:41:11,427 - Unable to load available packages
Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 771, in load_available_packages
    self.available_packages_in_repos = pkg_provider.get_available_packages_in_repos(repos)
  File "/usr/lib/python2.6/site-packages/resource_management/core/providers/package/yumrpm.py", line 85, in get_available_packages_in_repos
    available_packages.extend(self._get_available_packages(repo))
  File "/usr/lib/python2.6/site-packages/resource_management/core/providers/package/yumrpm.py", line 146, in _get_available_packages
    return self._lookup_packages(cmd, 'Available Packages')
  File "/usr/lib/python2.6/site-packages/resource_management/core/providers/package/yumrpm.py", line 191, in _lookup_packages
    if items[i + 2].find('@') == 0:
IndexError: list index out of range
Traceback (most recent call last):
  File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 73, in <module>
    HdfsClient().execute()
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 367, in execute
    method(env)
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 930, in restart
    self.install(env)
  File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/hdfs_client.py", line 35, in install
    import params
  File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/params.py", line 25, in <module>
    from params_linux import *
  File "/var/lib/ambari-agent/cache/common-services/HDFS/2.1.0.2.0/package/scripts/params_linux.py", line 391, in <module>
    lzo_packages = get_lzo_packages(stack_version_unformatted)
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/functions/get_lzo_packages.py", line 45, in get_lzo_packages
    lzo_packages += [script_instance.format_package_name("hadooplzo_${stack_version}"),
  File "/usr/lib/python2.6/site-packages/resource_management/libraries/script/script.py", line 538, in format_package_name
    raise Fail("Cannot match package for regexp name {0}. Available packages: {1}".format(name, self.available_packages_in_repos))
resource_management.core.exceptions.Fail: Cannot match package for regexp name hadooplzo_${stack_version}. Available packages: []

(I think the most important part is the message resource_management.core.exceptions.Fail: Cannot match package for regexp name hadooplzo_${stack_version}. Available packages: [] which looks like there would be no version (package) available...!

I just saw, that I upgraded also the Ambari Metrics Monitor, Ambari Metrics Hadoop Sink and the Metrics Collector before starting the Services once (the manual is a little bit confusing here, see step 4.3.3)! Was this a mistake?

I tried to upgrade from Ambari 2.4 to Ambari 2.6 (HDP 2.5 installed)! Operating system is CentOS 7.

However, I need to reset / downgrade the Ambari or upgrade the Services to be able to start them again! Can someone help? Any help would be appreciated! Thank you!

Body:
Finally I was able to downgrade my Ambari installation back to version 2.4.2 as it was before starting the upgrade process.

To make a downgrade you have to do the following steps on the appropriate nodes:

# delete the new ambari repo file
rm /etc/yum.repos.d/ambari.repo

# download the old ambari repo file (for me version 2.4.2), as described in ambari installation guide (here for Centos 7)
wget -nv http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.4.2.0/ambari.repo -O /etc/yum.repos.d/ambari.repo

yum clean all
yum repolist
# check for the correct version (e.g. 2.4.2) of the Ambari repo

# Downgrade all components to this version
yum downgrade ambari-metrics-monitor
yum downgrade ambari-metrics-hadoop-sink
yum downgrade ambari-agent
...

Afterwards I upgraded again, but to Ambari version 2.5.2.0, which now worked without a problem. I also was able to upgrade my HDP installation to version 2.6.3.0 via this Ambari version.

I will skip Ambari 2.6.0 and will try to upgrade Ambari with a later future release.


问:
how to write a query to get find value in a json field in django
I have a json field in my database which is like

```<code>jsonfield = {'username':'chingo','reputation':'5'}
</code>```

how can i write a query so that i can find if a user name exists. something like

```<code>username = 'chingo'
query = User.objects.get(jsonfield['username']=username)
</code>```

I know the above query is a wrong but I wanted to know if there is a way to access it?

答:
Here is the way I have found out that will solve your problem:

search_filter = '"username":{0}'.format(username)
query = User.objects.get(jsonfield__contains=search_filter)
```

Hope this helps.

Body:
I have a json field in my database which is like

jsonfield = {'username':'chingo','reputation':'5'}

how can i write a query so that i can find if a user name exists. something like

username = 'chingo'
query = User.objects.get(jsonfield['username']=username)

I know the above query is a wrong but I wanted to know if there is a way to access it?

Body:
Here is the way I have found out that will solve your problem:

search_filter = '"username":{0}'.format(username)
query = User.objects.get(jsonfield__contains=search_filter)

Hope this helps.


问:
How to compute the bazel workspace name in a macro?
I want to compute the workspace name during the execution of a bazel macro. If this was in a rule I could use ctx.workspace_name(), but I don't have a ctx object in a macro. There are native.package_name() and native.repository_name() but no native.workspace_name().

I need this as I want to compute the path within the docker image that my files are put by the docker rules, so that I can construct the correct entrypoint argument.

https://github.com/bazelbuild/rules_docker/blob/master/lang/image.bzl#L84

答: native.repository_name() is exactly what you are looking for. It's confusing that there is workspace_name() from ctx and repository_name() from native (#4092).


问:
Shapeless: own HList constraint using Coproduct
(NOTE: Split from Shapeless: Trying to restrict HList elements by their type )

Question 2 - Own Constraint using Coproduct

What I really wanted to do is to write a new constraint using Coproduct.

```<code>trait CPConstraint[L <: HList, CP <: Coproduct] extends Serializable
object CPConstraint {
  import shapeless.ops.coproduct.Selector._

  def apply[L <: HList, CP <: Coproduct](implicit cpc: CPConstraint[L, CP]): CPConstraint[L, CP] = cpc

  type <*<[CP <: Coproduct] = {  // TODO: just invented a symbol ... what would be an appropriate one?
    type λ[L <: HList] = CPConstraint[L, CP]
  }

implicit def hnilCP[HN <: HNil, CP <: Coproduct]: CPConstraint[HN, CP] = new CPConstraint[HN, CP] {}
implicit def hlistCP[H, T <: HList, CP <: Coproduct](implicit ev: coproduct.Selector[CP, H], cpct: CPConstraint[T, CP]): CPConstraint[H :: T, CP] = new CPConstraint[H :: T, CP] {}

}

object testCPConstraint {
  import shapeless.ops.coproduct.Selector._
  import CPConstraint._

  type CPType = Long :+: String :+: CNil

  implicit val selLong = implicitly[Selector[CPType, Long]]
  implicit val selString = implicitly[Selector[CPType, String]]

  def acceptCP[L <: HList : <*<[CPType]#λ](l: L) = true

  val hlLong: ::[Long, HNil] = 1L :: HNil
  val hlString: ::[String, HNil] = "blabla" :: HNil
  val hlMixed: ::[String, ::[Long, HNil]] = "blabla" :: 1L :: HNil
  val hlMixedRev: ::[Long, ::[String, HNil]] = 1L :: "blabla" :: HNil
  val hlInvalid: ::[Double, HNil] = 1.0d :: HNil

  implicit val scpcEmpty: CPConstraint[HNil, CPType] = implicitly[CPConstraint[HNil, CPType]]

  implicit val scpcEmptyLong1: CPConstraint[::[Long,HNil], CPType] = new CPConstraint[::[Long,HNil], CPType] {}
</code>```

//  implicit val scpcEmptyLong2: CPConstraint[hlLong.type, CPType] = new CPConstraint[hlLong.type, CPType] {}
// above line would fit the missing implicit - WHY???

```<code>  implicit val cpcLong = implicitly[CPConstraint[hlLong.type, CPType]]

  val validEmpty = acceptCP(HNil: HNil)
  val validLong = acceptCP(1l :: HNil)
  val validMixed = acceptCP("blabla" :: 1l :: HNil)

  val invalid = acceptCP(1.0d :: HNil) // should fail due to missing evidence
}
</code>```

答:
This answer is shamelessly copied from gitter, all credit to @SystemFW.

Use the LiftAll witness, like so:

```<code>import shapeless._, ops.hlist.LiftAll, ops.coproduct.Inject

type Cop = Int :+: Long :+: CNil

def foo[H <: HList](implicit ev: LiftAll[Inject[Cop,?], H]) = null

foo[Int :: Long :: HNil]
foo[HNil]
foo[Int :: Int :: HNil]
//foo[Int :: Long :: String :: HNil] doesn't compile
</code>```

Where Inject[Cop,?] is type I[X] = Inject[Cop,X] (or you can use the kind projector plugin for the ? syntax).

Body:
(NOTE: Split from Shapeless: Trying to restrict HList elements by their type )

Question 2 - Own Constraint using Coproduct

What I really wanted to do is to write a new constraint using Coproduct.

trait CPConstraint[L <: HList, CP <: Coproduct] extends Serializable
object CPConstraint {
  import shapeless.ops.coproduct.Selector._

  def apply[L <: HList, CP <: Coproduct](implicit cpc: CPConstraint[L, CP]): CPConstraint[L, CP] = cpc

  type <*<[CP <: Coproduct] = {  // TODO: just invented a symbol ... what would be an appropriate one?
    type λ[L <: HList] = CPConstraint[L, CP]
  }

implicit def hnilCP[HN <: HNil, CP <: Coproduct]: CPConstraint[HN, CP] = new CPConstraint[HN, CP] {}
implicit def hlistCP[H, T <: HList, CP <: Coproduct](implicit ev: coproduct.Selector[CP, H], cpct: CPConstraint[T, CP]): CPConstraint[H :: T, CP] = new CPConstraint[H :: T, CP] {}

}

object testCPConstraint {
  import shapeless.ops.coproduct.Selector._
  import CPConstraint._

  type CPType = Long :+: String :+: CNil

  implicit val selLong = implicitly[Selector[CPType, Long]]
  implicit val selString = implicitly[Selector[CPType, String]]

  def acceptCP[L <: HList : <*<[CPType]#λ](l: L) = true

  val hlLong: ::[Long, HNil] = 1L :: HNil
  val hlString: ::[String, HNil] = "blabla" :: HNil
  val hlMixed: ::[String, ::[Long, HNil]] = "blabla" :: 1L :: HNil
  val hlMixedRev: ::[Long, ::[String, HNil]] = 1L :: "blabla" :: HNil
  val hlInvalid: ::[Double, HNil] = 1.0d :: HNil

  implicit val scpcEmpty: CPConstraint[HNil, CPType] = implicitly[CPConstraint[HNil, CPType]]

  implicit val scpcEmptyLong1: CPConstraint[::[Long,HNil], CPType] = new CPConstraint[::[Long,HNil], CPType] {}

//  implicit val scpcEmptyLong2: CPConstraint[hlLong.type, CPType] = new CPConstraint[hlLong.type, CPType] {}
// above line would fit the missing implicit - WHY???

  implicit val cpcLong = implicitly[CPConstraint[hlLong.type, CPType]]

  val validEmpty = acceptCP(HNil: HNil)
  val validLong = acceptCP(1l :: HNil)
  val validMixed = acceptCP("blabla" :: 1l :: HNil)

  val invalid = acceptCP(1.0d :: HNil) // should fail due to missing evidence
}

Body:
This answer is shamelessly copied from gitter, all credit to @SystemFW.

Use the LiftAll witness, like so:

import shapeless._, ops.hlist.LiftAll, ops.coproduct.Inject

type Cop = Int :+: Long :+: CNil

def foo[H <: HList](implicit ev: LiftAll[Inject[Cop,?], H]) = null

foo[Int :: Long :: HNil]
foo[HNil]
foo[Int :: Int :: HNil]
//foo[Int :: Long :: String :: HNil] doesn't compile

Where Inject[Cop,?] is type I[X] = Inject[Cop,X] (or you can use the kind projector plugin for the ? syntax).


问:
Have a draggable item in jsPlumb which is made of multiple items
I'd like to create a single draggable item in jsPlumb which is actually composed of multiple items: a "main item" which has an anchor which is a connection target (isTarget: true), and multiple "sub items" which display stacked up, each of which has an anchor which is a connection source. Something like this:

Subthings should always be presented in the way above; they aren't draggable around inside the item, nor are they draggable to other items. Dragging anywhere on the main item or any subitem drags the whole group around from place to place.

Am I best to model this as separate things in a jsPlumb.Group, or is this really all just one "wrapper" div with many divs inside it? If it's the latter, how do I add anchors to the main and subitems within the wrapper, if it's the wrapper that I tell jsPlumb about?

答:
As far as I can tell, this Just Works.

```<code>const a = document.createElement("article");
const d = document.createElement("div");
const p = document.createElement("p");
a.appendChild(d);
a.appendChild(p);
pane.appendChild(a);
jsPlumb.draggable(a);
var endpoint1 = jsPlumb.addEndpoint(d, { isTarget:true, anchors: ["Top"] });
var endpoint2 = jsPlumb.addEndpoint(p, { isSource:true, anchors: ["Right"] });
</code>```

Create a "wrapper" (here a, an article), and mark it draggable; append subitems to it, and add Endpoints to them; everything works. Done.

Body:
As far as I can tell, this Just Works.

const a = document.createElement("article");
const d = document.createElement("div");
const p = document.createElement("p");
a.appendChild(d);
a.appendChild(p);
pane.appendChild(a);
jsPlumb.draggable(a);
var endpoint1 = jsPlumb.addEndpoint(d, { isTarget:true, anchors: ["Top"] });
var endpoint2 = jsPlumb.addEndpoint(p, { isSource:true, anchors: ["Right"] });

Create a "wrapper" (here a, an article), and mark it draggable; append subitems to it, and add Endpoints to them; everything works. Done.


问:
Mysql Query Slow on large table
Trying to run the following query on a mysql table that has over 3 million rows. Its very slow to the point it pretty much hangs until the script times out. Below is the query and the explain from that query, any suggestions?

```<code>SELECT SQL_CALC_FOUND_ROWS
listing_track.listingid,
listing_track.commid,
listing.listingname,
listing_package.packagename,
listing.active,
community.commname,
SUM( listing_track.impression ) AS listing_impressions,
SUM( listing_track.view ) AS listing_views,
SUM( listing_track.phone ) AS listing_phones,
SUM( listing_track.forward ) AS listing_forward,
SUM( listing_track.coupon ) AS listing_coupons,
SUM( listing_track.email ) AS listing_emails
FROM listing_track
INNER JOIN listing ON listing_track.listingid = listing.id
INNER JOIN community ON listing_track.commid = community.id
INNER JOIN listing_package ON listing.packageid = listing_package.id
WHERE listing_track.commid =2
GROUP BY listing_track.commid, listing_track.listingid, listing_track.trackip
LIMIT 0 , 25
</code>```

Here is the explain:

答:
It looks good, applicable primary keys per respective table.  I would add ONE THING...

SELECT  STRAIGHT_JOIN  SQL_CALC_FOUND_ROWS ...

This tells MySQL to do in the order you tell it.  I had similar going against gov't data of 14+ million rows linked to over 15 lookup tables (joins).  MySQL was trying to use the smaller lookup tables as the basis of joining since they were smaller and thus hung the process (I mean over 30+ hours before I killed it).  By adding STRAIGHT_JOIN since you KNOW your LISTING_TRACK is the basis of everything, and the OTHER tables are the secondary references, it should fly though that much quicker.  That being said, it will still have some work to do going over 1+ million rows in your table, but obviously more limited by your COMMID column = 2.

One other is to possibly remove your "SQL_CALC_FOUND_ROWS" as it was noted in other searches as being "buggy", but don't know its importance for you on total records that qualified before the limit was applied.

BTW, my gov't query after adding STRAIGHT_JOIN ran in under 2 hours.

HTH

Title: Mysql Query Slow on large table

Body:
Trying to run the following query on a mysql table that has over 3 million rows. Its very slow to the point it pretty much hangs until the script times out. Below is the query and the explain from that query, any suggestions?

SELECT SQL_CALC_FOUND_ROWS
listing_track.listingid,
listing_track.commid,
listing.listingname,
listing_package.packagename,
listing.active,
community.commname,
SUM( listing_track.impression ) AS listing_impressions,
SUM( listing_track.view ) AS listing_views,
SUM( listing_track.phone ) AS listing_phones,
SUM( listing_track.forward ) AS listing_forward,
SUM( listing_track.coupon ) AS listing_coupons,
SUM( listing_track.email ) AS listing_emails
FROM listing_track
INNER JOIN listing ON listing_track.listingid = listing.id
INNER JOIN community ON listing_track.commid = community.id
INNER JOIN listing_package ON listing.packageid = listing_package.id
WHERE listing_track.commid =2
GROUP BY listing_track.commid, listing_track.listingid, listing_track.trackip
LIMIT 0 , 25

Here is the explain:


问:
Drillthrough function in Power BI column chart - show day numbers instead of dates
I have created 2 different column charts in my Power BI report. The charts show the report usage by month and day (Day 1-31) - in this case for October. Only one month can be selected at a time.

I have added a drill-through function to the chart so the user can access a more detailed report. This works fine with the first chart when the Date field is placed under Axis (example: 2017-11-14).

When I instead try to use the Year, Month, Day fields under Axis only the day is being sent through to the drill-through report. For example November 6'th 2017 is being picked up at 6'th of each month. It seems that the drill-though function is only using the lowest level of data.

The first option works fine, however I would like it to look the the chart below where you see the number of each day instead of the entire date.

Any thoughts or suggestions?

Edit:

This is what the drillthrough filters look like on the drillthrough report page (I have selected November 9'th on the other page):

(År = Year, Månad = Month, Dag = Day)

答:
For your second option to work, you need to add Year/Month/Day values to Axis, then on drill-through report page also make sure you add these 3 fields to Drillthrough filters.

But if you only need to show shorter version of days instead of whole date, take a look at the formatting options ==> X-Axis, there you can turn off Concatenate labels and grindlines to get a nicer looking graph like in a picture below.

Main graph:

Drillthrough report:


问:
Should().Contain() with equivalency options
I am attempting to assert that a collection of Claims contains an expected set of claims. The problem that I seem to be running into is that there's no way to check for a subset and supply my own equivalency options.

```<code>var expected = new[] {
    new Claim(ClaimTypes.Name, "joshdev"),
    new Claim(ClaimTypes.Email, "test@test.com"),
    new Claim(ClaimTypes.GivenName, "Josh"),
    new Claim(ClaimTypes.Surname, "Perry"),
};

var identity = GetIdentity();
</code>```

What I've tried...

```<code>identity.Claims.ShouldAllBeEquivalentTo(expected, options => options.Including(x => x.Type).Including(x => x.Value));
</code>```

This fails if the identity's claims are not exactly the expected set, e.g. there are more than just those claims.

```<code>identity.Claims.Should().Contain(expected);
</code>```

This fails because Contain simply uses the object::Equals method which the Claim type does not implement.

What I need is some way to do Contain but with the same equivalency options as ShouldAllBeEquivalentTo exposes. I thought perhaps ShouldBeEquivalentTo would be what I wanted, but that provides for asserting the collection object itself, not the items in the collection.

答:
If you use Shouldly, you can use ShouldAllBe with Contains.

```<code>collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};

collection1.ShouldAllBe(item=>collection2.Contains(item)); // true
</code>```

And finally, you can write an extension.

```<code>public static class ShouldlyIEnumerableExtensions
{
    public static void ShouldEquivalentTo<T>(this IEnumerable<T> list, IEnumerable<T> equivalent)
    {
        list.ShouldAllBe(l => equivalent.Contains(l));
    }
}
</code>```

UPDATE

An optional parameter exists on ShouldBe method.

collection1.ShouldBe(collection2, ignoreOrder: true); // true
```

Body:
I am attempting to assert that a collection of Claims contains an expected set of claims. The problem that I seem to be running into is that there's no way to check for a subset and supply my own equivalency options.

var expected = new[] {
    new Claim(ClaimTypes.Name, "joshdev"),
    new Claim(ClaimTypes.Email, "test@test.com"),
    new Claim(ClaimTypes.GivenName, "Josh"),
    new Claim(ClaimTypes.Surname, "Perry"),
};

var identity = GetIdentity();

What I've tried...

identity.Claims.ShouldAllBeEquivalentTo(expected, options => options.Including(x => x.Type).Including(x => x.Value));

This fails if the identity's claims are not exactly the expected set, e.g. there are more than just those claims.

identity.Claims.Should().Contain(expected);

This fails because Contain simply uses the object::Equals method which the Claim type does not implement.

What I need is some way to do Contain but with the same equivalency options as ShouldAllBeEquivalentTo exposes. I thought perhaps ShouldBeEquivalentTo would be what I wanted, but that provides for asserting the collection object itself, not the items in the collection.

Body:
If you use Shouldly, you can use ShouldAllBe with Contains.

collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};

collection1.ShouldAllBe(item=>collection2.Contains(item)); // true

And finally, you can write an extension.

public static class ShouldlyIEnumerableExtensions
{
    public static void ShouldEquivalentTo<T>(this IEnumerable<T> list, IEnumerable<T> equivalent)
    {
        list.ShouldAllBe(l => equivalent.Contains(l));
    }
}

UPDATE

An optional parameter exists on ShouldBe method.

collection1.ShouldBe(collection2, ignoreOrder: true); // true


问:
Create plot with averages and standard deviation computed after every iteration
I have a data frame with this row:

```<code>read.table(text = "            V1        V2        V3        V4        V5        V6        V7        V8        V9       V10
 BACC 0.6203474 0.4466501 0.4820099 0.7003722 0.4851117 0.5173697 0.6073201 0.5911911 0.3759305 0.4627792")
</code>```

Each of the columns is the same calculation being done repeatedly (random sample changes, so value of balanced accuracy changes). I want to generate a plot which shows an iterative mean value with error bars (standard deviation). So for example, at x = 1 iteration, it just plots the point given in column V1. For the second, it averages the first and second columns and calculates the std. dev. and plots this. For the third, it averages first, second, and third columns and does the same all the way until it eventually averages all and computes standard deviation of all.

How can this plot be made? Or a data frame which contains each iterative mean/standard deviation? My real data has 1000 columns (not 10) so I would like something that can be expanded to as large of a data set as possible. Also, if I only want to compute average/standard deviation every 5 iterations, how would that be done?

I would really appreciate if you could help me with this.

Thanks!

答:
You can do this using some tidyverse packages and TTR

Since ggplot2 likes tidy data in a long format, this solution uses gather to get all of your measurement columns into rows.  This also makes it easier to perform a running mean and running standard deviation on your data.

```<code>library(tidyverse) #for dplyr, tidyr, ggplot2
library(TTR) # for runMean and runSD

df <- read.table(text = "            V1        V2        V3        V4        V5        V6        V7        V8        V9       V10
 BACC 0.6203474 0.4466501 0.4820099 0.7003722 0.4851117 0.5173697 0.6073201 0.5911911 0.3759305 0.4627792")

plot_data <- df %>%
  gather(measurement, value) %>%
  mutate(cum_mean = ifelse(value == first(value), value, runMean(value, 1, cumulative = TRUE)),
         cum_sd = runSD(value, 1, cumulative = TRUE))

ggplot(plot_data, aes(x = measurement, y = cum_mean)) +
  geom_col() +
  geom_errorbar(aes(ymin = cum_mean - cum_sd, ymax = cum_mean + cum_sd), size = 0.2)
</code>```

If you want to do this over a sequence of rows, e.g every 5th row, you can achieve this using slice and including the sequence over the number of rows in the data frame.

```<code>plot_data <- df %>%
  gather(measurement, value) %>%
  slice(seq(1, nrow(.), 5)) %>%
  mutate(cum_mean = ifelse(value == first(value), value, runMean(value, 1, cumulative = TRUE)),
         cum_sd = runSD(value, 1, cumulative = TRUE))
</code>```

Body:
I have a data frame with this row:

read.table(text = "            V1        V2        V3        V4        V5        V6        V7        V8        V9       V10
 BACC 0.6203474 0.4466501 0.4820099 0.7003722 0.4851117 0.5173697 0.6073201 0.5911911 0.3759305 0.4627792")

Each of the columns is the same calculation being done repeatedly (random sample changes, so value of balanced accuracy changes). I want to generate a plot which shows an iterative mean value with error bars (standard deviation). So for example, at x = 1 iteration, it just plots the point given in column V1. For the second, it averages the first and second columns and calculates the std. dev. and plots this. For the third, it averages first, second, and third columns and does the same all the way until it eventually averages all and computes standard deviation of all.

How can this plot be made? Or a data frame which contains each iterative mean/standard deviation? My real data has 1000 columns (not 10) so I would like something that can be expanded to as large of a data set as possible. Also, if I only want to compute average/standard deviation every 5 iterations, how would that be done?

I would really appreciate if you could help me with this.

Thanks!

Body:
You can do this using some tidyverse packages and TTR

Since ggplot2 likes tidy data in a long format, this solution uses gather to get all of your measurement columns into rows.  This also makes it easier to perform a running mean and running standard deviation on your data.

library(tidyverse) #for dplyr, tidyr, ggplot2
library(TTR) # for runMean and runSD

df <- read.table(text = "            V1        V2        V3        V4        V5        V6        V7        V8        V9       V10
 BACC 0.6203474 0.4466501 0.4820099 0.7003722 0.4851117 0.5173697 0.6073201 0.5911911 0.3759305 0.4627792")

plot_data <- df %>%
  gather(measurement, value) %>%
  mutate(cum_mean = ifelse(value == first(value), value, runMean(value, 1, cumulative = TRUE)),
         cum_sd = runSD(value, 1, cumulative = TRUE))

ggplot(plot_data, aes(x = measurement, y = cum_mean)) +
  geom_col() +
  geom_errorbar(aes(ymin = cum_mean - cum_sd, ymax = cum_mean + cum_sd), size = 0.2)

If you want to do this over a sequence of rows, e.g every 5th row, you can achieve this using slice and including the sequence over the number of rows in the data frame.

plot_data <- df %>%
  gather(measurement, value) %>%
  slice(seq(1, nrow(.), 5)) %>%
  mutate(cum_mean = ifelse(value == first(value), value, runMean(value, 1, cumulative = TRUE)),
         cum_sd = runSD(value, 1, cumulative = TRUE))


问:
Drools - Sliding window not working as expected
I'm new to drools.  I've defined the following rule to add the last two numbers in the stream together.  I then send in a stream of 100 events, with the values set from 1 to 100.  So I would expect the output to be 0, 1, 3, 5, 7, 9, 11, 13 etc.

```<code>declare TestEvent
     @role( event )
     value : int
end
rule "Simple Rule"
when
    $sum : Integer() from accumulate ( TestEvent( $value : value ) over window:length( 2 ); sum( $value)  )
then
    System.out.println("Value: " + $sum );
end
</code>```

The session is started using "fireUntilHalt" in a separate thread. If I put a delay of 10 milliseconds between every event inserted it works as expected.  However when I don't have the delay, the results aren't as expected.  Usually it just prints 0 and 197.  Sometimes I might get a number or two in-between as well.

Why does this happen and what I should do to fix?

答:
Sliding windows are a crutch. Replace it by simple logic.

```<code>class Pred {
   Integer pred;
}

rule procInt1
when
  $p: Pred( pred == null )
  $i: Integer()
then
  modify( $p ){ setPred( $i ); }
end

rule procInt
when
  $p: Pred( $i1: pred != null )
  $i2: Integer()
then
  System.out.println( $i1 + $i2 );
  modify( $p ){ setPred( $i2 ); }
end
</code>```

The fact that you have two threads doesn't mean that you can't have race conditions. The thread inserting events isn't suspended and so everything is possible.

Body:
I'm new to drools.  I've defined the following rule to add the last two numbers in the stream together.  I then send in a stream of 100 events, with the values set from 1 to 100.  So I would expect the output to be 0, 1, 3, 5, 7, 9, 11, 13 etc.

declare TestEvent
     @role( event )
     value : int
end
rule "Simple Rule"
when
    $sum : Integer() from accumulate ( TestEvent( $value : value ) over window:length( 2 ); sum( $value)  )
then
    System.out.println("Value: " + $sum );
end

The session is started using "fireUntilHalt" in a separate thread. If I put a delay of 10 milliseconds between every event inserted it works as expected.  However when I don't have the delay, the results aren't as expected.  Usually it just prints 0 and 197.  Sometimes I might get a number or two in-between as well.

Why does this happen and what I should do to fix?

Body:
Sliding windows are a crutch. Replace it by simple logic.

class Pred {
   Integer pred;
}

rule procInt1
when
  $p: Pred( pred == null )
  $i: Integer()
then
  modify( $p ){ setPred( $i ); }
end

rule procInt
when
  $p: Pred( $i1: pred != null )
  $i2: Integer()
then
  System.out.println( $i1 + $i2 );
  modify( $p ){ setPred( $i2 ); }
end

The fact that you have two threads doesn't mean that you can't have race conditions. The thread inserting events isn't suspended and so everything is possible.


问:
Rails way of Where Between
I need to check for the following condition:

```<code>lower_limit <= VALUE < upper_limit
</code>```

I can do the above using

```<code>Model.where("lower_limit <= ? AND upper_limit > ?", value, value)
</code>```

but how do I do the same using ranges ? (..)/(...)

Please note the operators:

The first operator of between is "<=" and second operator is ">".
Had they been same, I could have used (..) or (...).

答:
You cannot do that with a range in the query, but you can still make use of BETWEEN. In MySQL, BETWEEN is inclusive. You could write something like:

```<code>Model.where("? BETWEEN lower_limit AND upper_limit - 1", value)
</code>```

Which would generate SQL like:

```<code>SELECT * FROM models WHERE (37 BETWEEN lower_limit AND upper_limit - 1)
</code>```

Title: Rails way of Where Between

Body:
I need to check for the following condition:

lower_limit <= VALUE < upper_limit

I can do the above using

Model.where("lower_limit <= ? AND upper_limit > ?", value, value)

but how do I do the same using ranges ? (..)/(...)

Please note the operators:

The first operator of between is "<=" and second operator is ">".
Had they been same, I could have used (..) or (...).

Body:
You cannot do that with a range in the query, but you can still make use of BETWEEN. In MySQL, BETWEEN is inclusive. You could write something like:

Model.where("? BETWEEN lower_limit AND upper_limit - 1", value)

Which would generate SQL like:

SELECT * FROM models WHERE (37 BETWEEN lower_limit AND upper_limit - 1)


问:
jQuery equivalent of querySelector
What is the jQuery equivalent of querySelector? The only way I've found so far is to select all then pick the first selection:

```<code>$(selectorString)[0]
</code>```

With the above expression, is jQuery smart enough to stop after finding the first match?

Update: @Mutnowski suggested using eq() and first, but after reading the jQuery documentation those two methods seem to have the same drawback: jQuery will first get all matches, then only filter out the first element.

答:
you can write a simple plugin (compatibility notes)</p>
```<code>$.fn.findFirst = function(sel) {
    const len = this.length;
    for(let i = 0; i < len; i++){
        const match = this[i].querySelector(sel);
        if (match) return $(match);
    }
    return $();
}
</code>```

Title: jQuery equivalent of querySelector

Body:
What is the jQuery equivalent of querySelector? The only way I've found so far is to select all then pick the first selection:

$(selectorString)[0]

With the above expression, is jQuery smart enough to stop after finding the first match?

Update: @Mutnowski suggested using eq() and first, but after reading the jQuery documentation those two methods seem to have the same drawback: jQuery will first get all matches, then only filter out the first element.

Body:
you can write a simple plugin (compatibility notes)

$.fn.findFirst = function(sel) {
    const len = this.length;
    for(let i = 0; i < len; i++){
        const match = this[i].querySelector(sel);
        if (match) return $(match);
    }
    return $();
}


问:
How to select first 8 bit from bitset<16> in c++?
I have a variable and it's type is bitset<16>. I want to get first 8 bit of my variable and put it into char variable. I know how to convert bitset to char, but I don't know how to select first 8 bit and convert it to char.</p>

答:
From the doc of the std::bitset constructor:

If the value representation of val is greater than the bitset size,
  only the least significant bits of val are taken into consideration.

So another solution could be:

```<code>#include <iostream>

int main() {
    std::bitset<16> myBits16(0b0110110001111101);
    std::bitset<8> myBits8(myBits16.to_ulong());
    char reg = static_cast<char>(myBits8.to_ulong());
}
</code>```

Body:
From the doc of the std::bitset constructor:

If the value representation of val is greater than the bitset size,
  only the least significant bits of val are taken into consideration.

So another solution could be:

#include <iostream>

int main() {
    std::bitset<16> myBits16(0b0110110001111101);
    std::bitset<8> myBits8(myBits16.to_ulong());
    char reg = static_cast<char>(myBits8.to_ulong());
}


问:
Debugging keyboard events like 'Ctrl+Up Arrow'
I want to debug a part of a program that is intended to respond to keyboard input such as Ctrl+↑.

So, I put a breakpoint in the code in the area interest. However, once I press the Ctrl key the program jumps to that breakpoint. This happens before I have pressed an arrow key, so I'm finding this situation difficult to debug.

So, how can I debug a multi-key input event such as Ctrl+↑?

答: In general your only option is to print some messages to console or error log. Otherwise debugger UI will interfere with your code. Visual Studio debugger, for example, can print values of expressions on hitting breakpoint, so you don't need to write special code.</p>


问:
Error "The root element must match the name of the section referencing the file", when root element does match the name of the section
I am trying to move appSettings config section to an external file using "file" attribute and keep getting the error:

System.Configuration.ConfigurationErrorsException : The root element
  must match the name of the section referencing the file, 'appSettings'

The problem is that root element in the external file is already 'appSettings'.
Tried using root 'configuration' and custom config Sections, and it didn't help either

External file Test.config is below

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
  <add key="URL" value="https://www.google.com" />
</appSettings>
```

<p>Main <code>App.config</code> file </p>

<pre class="lang-html prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow"/>
  </configSections>
  <specFlow>
    <!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config -->
  </specFlow>
  <appSettings file="Test.config"/>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
</configuration>
</code>```

Can anyone help me with this?

Thank you.

答:
For me this was a path issue.  The default behavior from visual studio is to not include the file in the output directory.  I changed the file properties to "Copy Always" for each build to ensure you have the most recent file.  If you have added it to your project in the properties section then the file reference should include the properties folder in the path.
 </p>

Body:
I am trying to move appSettings config section to an external file using "file" attribute and keep getting the error:

System.Configuration.ConfigurationErrorsException : The root element
  must match the name of the section referencing the file, 'appSettings'

The problem is that root element in the external file is already 'appSettings'.
Tried using root 'configuration' and custom config Sections, and it didn't help either

External file Test.config is below

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
  <add key="URL" value="https://www.google.com" />
</appSettings>

Main App.config file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

  </configSections>
  <specFlow>

  </specFlow>
  <appSettings file="Test.config"/>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
</configuration>

Can anyone help me with this?

Thank you.


问:
How can I use std::shared_ptr with the Mysql prepared statements?
How can I use std::shared_ptr with the Mysql prepared statements? is there any requirements which I should know in this case? is there any difference between boost::shared_ptr and std::shared_ptr in this case?

答:
You didn't provide any details about MSQL API functions that you actually use, so this answer is also generic.

If you should create and delete your pointer using the following API functions:

```<code>API_OBJ *api_obj_create( ... );
api_obj_delete(API_OBJ*);
</code>```

To manage your pointer with std::shared_ptr you need to provide the custom deleter:

```<code>std::shared_ptr<API_OBJ> my_s_ptr(api_obj_create( ... ),
    [](API_OBJ* p) { api_obj_delete(p); });
</code>```

Standard library is usually preferred over boost library.

Body:
You didn't provide any details about MSQL API functions that you actually use, so this answer is also generic.

If you should create and delete your pointer using the following API functions:

API_OBJ *api_obj_create( ... );
api_obj_delete(API_OBJ*);

To manage your pointer with std::shared_ptr you need to provide the custom deleter:

std::shared_ptr<API_OBJ> my_s_ptr(api_obj_create( ... ),
    [](API_OBJ* p) { api_obj_delete(p); });

Standard library is usually preferred over boost library.


问:
Non linear fit with R
I try to obtain the first three coefficients for Cauchy's dispersion equation for Silicon. Using a csv containing the refractive index for some wavelengths (that you can find here), I try to fit the following model :

```<code>library(readr)
library(tidyverse)
library(magrittr)
library(modelr)
library(broom)
library(splines)

# CSV parsing
RefractiveIndexINFO <- read_csv("./silicon-index.csv")

# Cleaning the output of the csv-parsing
indlong = tibble(RefractiveIndexINFO$`Wavelength. µm`,RefractiveIndexINFO$n)
names(indlong) = c('w','n')

# Remove some wavelengths that might not fit
indlong_non_uv = indlong %>% filter(indlong$w >= 0.4)

# Renaming variables
w = indlong_non_uv$w
n = indlong_non_uv$n

# Creating the non linear model
model = nls(n ~ a + b*ns(w,-2) + c*ns(w,-4), data = indlong_non_uv)

# Gathering informations on the fitted model
cor(indlong_non_uv$n,predict(model))
tidy(model)
</code>```

Which gives the following error :

```<code>Error in c * ns(w, -4) : non-numeric argument to binary operator
</code>```

How can I circumvent this situation and get the three coefficients (a,b,c) in a row ?

Obviously, using model = nls(n ~ a + b*ns(w,-2), data = indlong_non_uv) does not give an error.

答:
Try this:

```<code>library(readr)
library(tidyverse)
library(magrittr)
library(modelr)
library(broom)
library(splines)

# CSV parsing
RefractiveIndexINFO <- read_csv("aspnes.csv")
RefractiveIndexINFO <- RefractiveIndexINFO[1:46,]
RefractiveIndexINFO <- as.data.frame(apply(RefractiveIndexINFO,2,as.numeric))
names(RefractiveIndexINFO) <- c('w','n')

indlong_non_uv = RefractiveIndexINFO %>% filter(RefractiveIndexINFO$w >= 0.4)

# Creating the nonlinear model
model <- nls(n ~ a + b*w^(-2) + c*w^(-4), data = indlong_non_uv,
   start=list(a=1, b=1, c=1))

# Gathering informations on the fitted model
cor(indlong_non_uv$n,predict(model))
# [1] 0.9991006

tidy(model)
#   term    estimate   std.error statistic      p.value
# 1    a  3.65925186 0.039368851 92.947896 9.686805e-20
# 2    b -0.04981151 0.024099580 -2.066904 5.926046e-02
# 3    c  0.05282668 0.003306895 15.974707 6.334197e-10
</code>```

Alternatively, you can use linear regression:

```<code>model2 <- lm(n ~ I(w^(-2)) + I(w^(-4)), data = indlong_non_uv)
summary(model2)

# Coefficients:
#              Estimate Std. Error t value Pr(>|t|)
# (Intercept)  3.659252   0.039369  92.948  < 2e-16 ***
# I(w^(-2))   -0.049812   0.024100  -2.067   0.0593 .
# I(w^(-4))    0.052827   0.003307  15.975 6.33e-10 ***
</code>```

Title: Non linear fit with R

Body:
I try to obtain the first three coefficients for Cauchy's dispersion equation for Silicon. Using a csv containing the refractive index for some wavelengths (that you can find here), I try to fit the following model :

library(readr)
library(tidyverse)
library(magrittr)
library(modelr)
library(broom)
library(splines)

# CSV parsing
RefractiveIndexINFO <- read_csv("./silicon-index.csv")

# Cleaning the output of the csv-parsing
indlong = tibble(RefractiveIndexINFO$`Wavelength. µm`,RefractiveIndexINFO$n)
names(indlong) = c('w','n')

# Remove some wavelengths that might not fit
indlong_non_uv = indlong %>% filter(indlong$w >= 0.4)

# Renaming variables
w = indlong_non_uv$w
n = indlong_non_uv$n

# Creating the non linear model
model = nls(n ~ a + b*ns(w,-2) + c*ns(w,-4), data = indlong_non_uv)

# Gathering informations on the fitted model
cor(indlong_non_uv$n,predict(model))
tidy(model)

Which gives the following error :

Error in c * ns(w, -4) : non-numeric argument to binary operator

How can I circumvent this situation and get the three coefficients (a,b,c) in a row ?

Obviously, using model = nls(n ~ a + b*ns(w,-2), data = indlong_non_uv) does not give an error.

Body:
Try this:

library(readr)
library(tidyverse)
library(magrittr)
library(modelr)
library(broom)
library(splines)

# CSV parsing
RefractiveIndexINFO <- read_csv("aspnes.csv")
RefractiveIndexINFO <- RefractiveIndexINFO[1:46,]
RefractiveIndexINFO <- as.data.frame(apply(RefractiveIndexINFO,2,as.numeric))
names(RefractiveIndexINFO) <- c('w','n')

indlong_non_uv = RefractiveIndexINFO %>% filter(RefractiveIndexINFO$w >= 0.4)

# Creating the nonlinear model
model <- nls(n ~ a + b*w^(-2) + c*w^(-4), data = indlong_non_uv,
   start=list(a=1, b=1, c=1))

# Gathering informations on the fitted model
cor(indlong_non_uv$n,predict(model))
# [1] 0.9991006

tidy(model)
#   term    estimate   std.error statistic      p.value
# 1    a  3.65925186 0.039368851 92.947896 9.686805e-20
# 2    b -0.04981151 0.024099580 -2.066904 5.926046e-02
# 3    c  0.05282668 0.003306895 15.974707 6.334197e-10

Alternatively, you can use linear regression:

model2 <- lm(n ~ I(w^(-2)) + I(w^(-4)), data = indlong_non_uv)
summary(model2)

# Coefficients:
#              Estimate Std. Error t value Pr(>|t|)
# (Intercept)  3.659252   0.039369  92.948  < 2e-16 ***
# I(w^(-2))   -0.049812   0.024100  -2.067   0.0593 .
# I(w^(-4))    0.052827   0.003307  15.975 6.33e-10 ***