问:
Android - Picasso - Retry with a different network policy
I'm using the following code to load an URL to an ImageView. It first tries to load from cache, and if it fails it tries to fetch it from internet:

```<code>Picasso.with(getActivity())
.load(imageUrl)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView, new Callback() {
    @Override
    public void onSuccess() {

    }

    @Override
    public void onError() {
        //Try again online if cache failed
        Picasso.with(getActivity())
                .load(imageUrl)
                .error(R.drawable.error_image)
                .into(imageView, new Callback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onError() {
                Log.v("Picasso","Could not fetch image");
            }
        });
    }
});
</code>```

It works just fine, but the problem is that is really cumbersome to write all this code every time I have to load an image, compared to the standard:

```<code>Picasso.with(getContext())
 .load(imageUrl)
 .into(imageView);
</code>```

Is there a way to encapsulate this behaviour ? Does Picasso provide any way to help it?

答:
try using this code this worked for me

this class uses a retry policy to download images

public class PicassoHelper {

```<code>private static final boolean isDebug = false;
private static final int MAX_RETRY_TIME = 10;         // Default is 3 in Picasso
private static final int MAX_DOWNLOADING_THREAD = 4;  // Recommand in Volley , it is 4
private static Picasso sPicasso;

public static Picasso Pwith(Context context) {
    // Mimicking Picasso's new OkHttpLoader(context), but with our custom OkHttpClient
    if (sPicasso == null) {
        OkHttpClient client = new OkHttpClient();
        client.setRetryOnConnectionFailure(true);
        // Create A Retry Policy
        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request request = chain.request();
                // try the request
                Response response = chain.proceed(request);
                int tryCount = 0;
                while (!response.isSuccessful() && tryCount < MAX_RETRY_TIME) {
                    Log.d("intercept :"," Request is not successful - " + tryCount);
                    tryCount++;
                    // retry the request
                    response = chain.proceed(request);
                }
                // otherwise just pass the original response on
                return response;
            }
        });
        sPicasso = new Picasso.Builder(context)
                .executor(Executors.newFixedThreadPool(MAX_DOWNLOADING_THREAD))
                .downloader(new OkHttpDownloader(client)).build();
        if(isDebug) {
            sPicasso.setIndicatorsEnabled(true);
            sPicasso.setLoggingEnabled(true);
        }
    }
    return sPicasso;
}
</code>```

}

Now after creating the class its time to use it in out code

PicassoHelper.Pwith(application_context).load(image_url).into(imageView);

Body:
I'm using the following code to load an URL to an ImageView. It first tries to load from cache, and if it fails it tries to fetch it from internet:

Picasso.with(getActivity())
.load(imageUrl)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView, new Callback() {
    @Override
    public void onSuccess() {

    }

    @Override
    public void onError() {
        //Try again online if cache failed
        Picasso.with(getActivity())
                .load(imageUrl)
                .error(R.drawable.error_image)
                .into(imageView, new Callback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onError() {
                Log.v("Picasso","Could not fetch image");
            }
        });
    }
});

It works just fine, but the problem is that is really cumbersome to write all this code every time I have to load an image, compared to the standard:

Picasso.with(getContext())
 .load(imageUrl)
 .into(imageView);

Is there a way to encapsulate this behaviour ? Does Picasso provide any way to help it?

Body:
try using this code this worked for me

this class uses a retry policy to download images

public class PicassoHelper {

private static final boolean isDebug = false;
private static final int MAX_RETRY_TIME = 10;         // Default is 3 in Picasso
private static final int MAX_DOWNLOADING_THREAD = 4;  // Recommand in Volley , it is 4
private static Picasso sPicasso;

public static Picasso Pwith(Context context) {
    // Mimicking Picasso's new OkHttpLoader(context), but with our custom OkHttpClient
    if (sPicasso == null) {
        OkHttpClient client = new OkHttpClient();
        client.setRetryOnConnectionFailure(true);
        // Create A Retry Policy
        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request request = chain.request();
                // try the request
                Response response = chain.proceed(request);
                int tryCount = 0;
                while (!response.isSuccessful() && tryCount < MAX_RETRY_TIME) {
                    Log.d("intercept :"," Request is not successful - " + tryCount);
                    tryCount++;
                    // retry the request
                    response = chain.proceed(request);
                }
                // otherwise just pass the original response on
                return response;
            }
        });
        sPicasso = new Picasso.Builder(context)
                .executor(Executors.newFixedThreadPool(MAX_DOWNLOADING_THREAD))
                .downloader(new OkHttpDownloader(client)).build();
        if(isDebug) {
            sPicasso.setIndicatorsEnabled(true);
            sPicasso.setLoggingEnabled(true);
        }
    }
    return sPicasso;
}

}

Now after creating the class its time to use it in out code

PicassoHelper.Pwith(application_context).load(image_url).into(imageView);


来源: stackexchange

问:
Why use std::forward in concepts?
I was reading the cppreference page on Constraints and noticed this example:

```<code>// example constraint from the standard library (ranges TS)
template <class T, class U = T>
concept bool Swappable = requires(T t, U u) {
    swap(std::forward<T>(t), std::forward<U>(u));
    swap(std::forward<U>(u), std::forward<T>(t));
};
</code>```

I'm puzzled why they're using std::forward.  Some attempt to support reference types in the template parameters?  Don't we want to call swap with lvalues, and wouldn't the forward expressions be rvalues when T and U are scalar (non-reference) types?

For example, I would expect this program to fail given their Swappable implementation:

```<code>#include <utility>

// example constraint from the standard library (ranges TS)
template <class T, class U = T>
concept bool Swappable = requires(T t, U u) {
    swap(std::forward<T>(t), std::forward<U>(u));
    swap(std::forward<U>(u), std::forward<T>(t));
};

class MyType {};
void swap(MyType&, MyType&) {}

void f(Swappable& x) {}

int main()
{
    MyType x;
    f(x);
}
</code>```

Unfortunately g++ 7.1.0 gives me an internal compiler error, which doesn't shed much light on this.

Here both T and U should be MyType, and std::forward<T>(t) should return MyType&&, which can't be passed to my swap function.

Is this implementation of Swappable wrong?  Have I missed something?

答:
Don't we want to call swap with lvalues […]

That’s a very good question. A question of API design specifically: what meaning or meanings should the designer of a concept library give to the parameters of its concepts?

A quick recap on Swappable requirements. That is, the actual requirements that already appear in today’s Standard and have been here since before concepts-lite:

An object t is swappable with an object u if and only if:

[…] the expressions swap(t, u) and swap(u, t) are valid […]

[…]

An rvalue or lvalue t is swappable if and only if t is swappable with any rvalue or lvalue, respectively, of type T.

(Excerpts butchered from Swappable requirements [swappable.requirements] to cut down on a whole lot of irrelevant details.)

Variables

Did you catch that? The first bit gives requirements that match your expectations. It’s quite straightforward to turn into an actual concept†, too:

†: as long as we’re willing to ignore a ton of details that are outside our scope

```<code>template<typename Lhs, typename Rhs = Lhs>
concept bool FirstKindOfSwappable = requires(Lhs lhs, Rhs rhs) {
    swap(lhs, rhs);
    swap(rhs, lhs);
};
</code>```

Now, very importantly we should immediately notice that this concept supports reference variables right out of the box:

```<code>int&& a_rref = 0;
int&& b_rref = 0;
// valid...
using std::swap;
swap(a_rref, b_rref);
// ...which is reflected here
static_assert( FirstKindOfSwappable<int&&> );
</code>```

(Now technically the Standard was talking in terms of objects which references aren't. Since references not only refer to objects or functions but are meant to transparently stand for them, we’ve actually provided a very desirable feature. Practically speaking we are now working in terms of variables, not just objects.)

There’s a very important connection here: int&& is the declared type of our variables, as well as the actual argument passed to the concept, which in turn ends up again as the declared type of our lhs and rhs requires parameters. Keep that in mind as we dig deeper.

Coliru demo

Expressions

Now what about that second bit that mentions lvalues and rvalues? Well, here we’re not dealing in variables any more but instead in terms of expressions. Can we write a concept for that? Well, there’s a certain expression-to-type encoding we can use. Namely the one used by decltype as well as std::declval in the other direction. This leads us to:

```<code>template<typenaome Lhs, typename Rhs = Lhs>
concept bool SecondKindOfSwappable = requires(Lhs lhs, Rhs rhs) {
    swap(std::forward<Lhs>(lhs), std::forward<Rhs>(rhs));
    swap(std::forward<Rhs>(rhs), std::forward<Lhs>(lhs));

    // another way to express the first requirement
    swap(std::declval<Lhs>(), std::declval<Rhs>());
};
</code>```

Which is what you ran into! And as you found out, the concept must be used in a different way:

```<code>// not valid
//swap(0, 0);
//     ^- rvalue expression of type int
//        decltype( (0) ) => int&&
static_assert( !SecondKindOfSwappable<int&&> );
// same effect because the expression-decltype/std::declval encoding
// cannot properly tell apart prvalues and xvalues
static_assert( !SecondKindOfSwappable<int> );

int a = 0, b = 0;
swap(a, b);
//   ^- lvalue expression of type int
//      decltype( (a) ) => int&
static_assert( SecondKindOfSwappable<int&> );
</code>```

If you find that non-obvious, take a look at the connection at play this time: we have an lvalue expression of type int, which becomes encoded as the int& argument to the concept, which gets restored to an expression in our constraint by std::declval<int&>(). Or in a more roundabout way, by std::forward<int&>(lhs).

Coliru demo

Putting it together

What appears on the cppreference entry is a summary of the Swappable concept specified by the Ranges TS. If I were to guess, I would say that the Ranges TS settled on giving the Swappable parameters to stand for expressions for the following reasons:

we can write SecondKindOfSwappable in terms of FirstKindOfSwappable as given by the following nearly:

```<code>template<typename Lhs, typename Rhs = Lhs>
concept bool FirstKindOfSwappable = SecondKindOfSwappable<Lhs&, Rhs&>;
</code>```

This recipe can be applied in many but not all cases, making it sometimes possible to express a concept parametrised on types-of-variables in terms of the same concept parametrised on expressions-hidden-in-types. But it’s usually not possible to go the other way around.

constraining on swap(std::forward<Lhs>(lhs), std::forward<Rhs>(rhs)) is expected to be an important enough scenario; off the top of my head it comes up in business such as:

```<code>template<typename Val, typename It>
void client_code(Val val, It it)
    requires Swappable<Val&, decltype(*it)>
//                           ^^^^^^^^^^^^^--.
//                                          |
//  hiding an expression into a type! ------`
{
    ranges::swap(val, *it);
}
</code>```

consistency: for the most part, other concepts of the TS follow the same convention and are parametrised over types of expressions

But why for the most part?

Because there is a third kind of concept parameter: the type that stand for… a type. A good example of that is DerivedFrom<Derived, Base>() which value does not give you valid expressions (or ways to use variables) in the usual sense.

In fact, in e.g. Constructible<Arg, Inits...>() the first argument Arg can arguably be interpreted in two ways:

Arg stands for a type, i.e. taking constructibility as an inherent property of a type

Arg is the declared type of a variable being constructed, i.e. the constraint implies that Arg imaginary_var { std::declval<Inits>()... }; is valid

How should I write my own concepts?

I’ll conclude with a personal note: I think the reader should not conclude (yet) that they should write their own concepts the same way just because concepts over expressions appear, at least from the perspective of a concept writer, to be a superset of concepts over variables.

There are other factors at play, and my concern is namely with usability from the perspective of a concept client and all these details I only mentioned in passing, too. But that doesn’t really have to do with the question and this answer is already long enough, so I’ll leave that story for another time.

ContentLicense: CC BY-SA 3.0

Title: Why use std::forward in concepts?

Body:
I was reading the cppreference page on Constraints and noticed this example:

// example constraint from the standard library (ranges TS)
template <class T, class U = T>
concept bool Swappable = requires(T t, U u) {
    swap(std::forward<T>(t), std::forward(u));
    swap(std::forward(u), std::forward<T>(t));
};

I'm puzzled why they're using std::forward.  Some attempt to support reference types in the template parameters?  Don't we want to call swap with lvalues, and wouldn't the forward expressions be rvalues when T and U are scalar (non-reference) types?

For example, I would expect this program to fail given their Swappable implementation:

#include <utility>

// example constraint from the standard library (ranges TS)
template <class T, class U = T>
concept bool Swappable = requires(T t, U u) {
    swap(std::forward<T>(t), std::forward(u));
    swap(std::forward(u), std::forward<T>(t));
};

class MyType {};
void swap(MyType&, MyType&) {}

void f(Swappable& x) {}

int main()
{
    MyType x;
    f(x);
}

Unfortunately g++ 7.1.0 gives me an internal compiler error, which doesn't shed much light on this.

Here both T and U should be MyType, and std::forward<T>(t) should return MyType&&, which can't be passed to my swap function.

Is this implementation of Swappable wrong?  Have I missed something?

Body:
Don't we want to call swap with lvalues […]

That’s a very good question. A question of API design specifically: what meaning or meanings should the designer of a concept library give to the parameters of its concepts?

A quick recap on Swappable requirements. That is, the actual requirements that already appear in today’s Standard and have been here since before concepts-lite:

An object t is swappable with an object u if and only if:

[…] the expressions swap(t, u) and swap(u, t) are valid […]

[…]

An rvalue or lvalue t is swappable if and only if t is swappable with any rvalue or lvalue, respectively, of type T.

(Excerpts butchered from Swappable requirements [swappable.requirements] to cut down on a whole lot of irrelevant details.)

Variables

Did you catch that? The first bit gives requirements that match your expectations. It’s quite straightforward to turn into an actual concept†, too:

†: as long as we’re willing to ignore a ton of details that are outside our scope

template<typename Lhs, typename Rhs = Lhs>
concept bool FirstKindOfSwappable = requires(Lhs lhs, Rhs rhs) {
    swap(lhs, rhs);
    swap(rhs, lhs);
};

Now, very importantly we should immediately notice that this concept supports reference variables right out of the box:

int&& a_rref = 0;
int&& b_rref = 0;
// valid...
using std::swap;
swap(a_rref, b_rref);
// ...which is reflected here
static_assert( FirstKindOfSwappable<int&&> );

(Now technically the Standard was talking in terms of objects which references aren't. Since references not only refer to objects or functions but are meant to transparently stand for them, we’ve actually provided a very desirable feature. Practically speaking we are now working in terms of variables, not just objects.)

There’s a very important connection here: int&& is the declared type of our variables, as well as the actual argument passed to the concept, which in turn ends up again as the declared type of our lhs and rhs requires parameters. Keep that in mind as we dig deeper.

Coliru demo

Expressions

Now what about that second bit that mentions lvalues and rvalues? Well, here we’re not dealing in variables any more but instead in terms of expressions. Can we write a concept for that? Well, there’s a certain expression-to-type encoding we can use. Namely the one used by decltype as well as std::declval in the other direction. This leads us to:

template<typenaome Lhs, typename Rhs = Lhs>
concept bool SecondKindOfSwappable = requires(Lhs lhs, Rhs rhs) {
    swap(std::forward<Lhs>(lhs), std::forward<Rhs>(rhs));
    swap(std::forward<Rhs>(rhs), std::forward<Lhs>(lhs));

    // another way to express the first requirement
    swap(std::declval<Lhs>(), std::declval<Rhs>());
};

Which is what you ran into! And as you found out, the concept must be used in a different way:

// not valid
//swap(0, 0);
//     ^- rvalue expression of type int
//        decltype( (0) ) => int&&
static_assert( !SecondKindOfSwappable<int&&> );
// same effect because the expression-decltype/std::declval encoding
// cannot properly tell apart prvalues and xvalues
static_assert( !SecondKindOfSwappable<int> );

int a = 0, b = 0;
swap(a, b);
//   ^- lvalue expression of type int
//      decltype( (a) ) => int&
static_assert( SecondKindOfSwappable<int&> );

If you find that non-obvious, take a look at the connection at play this time: we have an lvalue expression of type int, which becomes encoded as the int& argument to the concept, which gets restored to an expression in our constraint by std::declval<int&>(). Or in a more roundabout way, by std::forward<int&>(lhs).

Coliru demo

Putting it together

What appears on the cppreference entry is a summary of the Swappable concept specified by the Ranges TS. If I were to guess, I would say that the Ranges TS settled on giving the Swappable parameters to stand for expressions for the following reasons:

we can write SecondKindOfSwappable in terms of FirstKindOfSwappable as given by the following nearly:

template<typename Lhs, typename Rhs = Lhs>
concept bool FirstKindOfSwappable = SecondKindOfSwappable<Lhs&, Rhs&>;

This recipe can be applied in many but not all cases, making it sometimes possible to express a concept parametrised on types-of-variables in terms of the same concept parametrised on expressions-hidden-in-types. But it’s usually not possible to go the other way around.

constraining on swap(std::forward<Lhs>(lhs), std::forward<Rhs>(rhs)) is expected to be an important enough scenario; off the top of my head it comes up in business such as:

template<typename Val, typename It>
void client_code(Val val, It it)
    requires Swappable<Val&, decltype(*it)>
//                           ^^^^^^^^^^^^^--.
//                                          |
//  hiding an expression into a type! ------`
{
    ranges::swap(val, *it);
}

consistency: for the most part, other concepts of the TS follow the same convention and are parametrised over types of expressions

But why for the most part?

Because there is a third kind of concept parameter: the type that stand for… a type. A good example of that is DerivedFrom<Derived, Base>() which value does not give you valid expressions (or ways to use variables) in the usual sense.

In fact, in e.g. Constructible<Arg, Inits...>() the first argument Arg can arguably be interpreted in two ways:

Arg stands for a type, i.e. taking constructibility as an inherent property of a type

Arg is the declared type of a variable being constructed, i.e. the constraint implies that Arg imaginary_var { std::declval<Inits>()... }; is valid

How should I write my own concepts?

I’ll conclude with a personal note: I think the reader should not conclude (yet) that they should write their own concepts the same way just because concepts over expressions appear, at least from the perspective of a concept writer, to be a superset of concepts over variables.

There are other factors at play, and my concern is namely with usability from the perspective of a concept client and all these details I only mentioned in passing, too. But that doesn’t really have to do with the question and this answer is already long enough, so I’ll leave that story for another time.


问:
how to convert character type time to int?
I have a data frame containing time as a character type in the following manner.

```<code>time=c("5 mins 30 seconds","1 min 46 seconds","6 mins 40 seconds","20 seconds","2 seconds")
student=c("A","B","C")
df<-data.frame(student,time)
</code>```

I want to sort time taken by them and then plot. How should I proceed?

Also how to convert time to INT type in seconds?

答:
If the format remains same then, we can use strptime function in R</p>

```<code>time<- c("5 mins 30 seconds","3 mins 46 seconds","6 mins 40 seconds")
times <- strptime(time, "%M mins %S seconds")
times <- format(times, "%H:%M:%S")
student=c("A","B","C")
df<-data.frame(student,times)
</code>```

Body:
I have a data frame containing time as a character type in the following manner.

time=c("5 mins 30 seconds","1 min 46 seconds","6 mins 40 seconds","20 seconds","2 seconds")
student=c("A","B","C")
df<-data.frame(student,time)

I want to sort time taken by them and then plot. How should I proceed?

Also how to convert time to INT type in seconds?

Body:
If the format remains same then, we can use strptime function in R

time<- c("5 mins 30 seconds","3 mins 46 seconds","6 mins 40 seconds")
times <- strptime(time, "%M mins %S seconds")
times <- format(times, "%H:%M:%S")
student=c("A","B","C")
df<-data.frame(student,times)


问:
TID-owrsuwi8g WARN: NameError: uninitialized constant NewsWorker in Sidekiq of Rails
I am developing Rails application where send emails using Sidekiq gem.

Create worker then call it like:

```<code>Worker File: news_worker.rb

NewsWorker.perform_at(5.minutes.from_now, @news.title, @news.link, @news.image, user_detail.email, user_detail.category_name, type, email_template)
</code>```

But anyhow its not working and show error message like:

```<code>TID-owrsuwi8g WARN: NameError: uninitialized constant NewsWorker
</code>```

I tried to call from Model and Controller as well but still display same error. My old worked running fine but why this new create not working.. I found many ways but still not sortout.

Update

```<code># /app/workers/news_worker.rb

class NewsWorker
  include Sidekiq::Worker
  include Rails.application.routes.url_helpers

  def perform  news_title, news_link, news_image, email, category_name, type, email_template = nil
    send_to_email(news_title, news_link, news_image, email, category_name, type, email_template)
  end

  def send_to_email news_title, news_link, news_image, email, category_name, type, email_template
    SchoolMailer.send_news(news_title, news_link, news_image, email, category_name, type, email_template).deliver
  end
end
</code>```

Let me know if any one have idea.

Thanks

答:
I think it has something to do with autoload_paths; the workers directory is not auto-loaded.

In config/application.rb add the following line:

```<code>config.autoload_paths += %W(#{config.root}/app/workers)
</code>```

This should do the trick

Body:
I am developing Rails application where send emails using Sidekiq gem.

Create worker then call it like:

Worker File: news_worker.rb

NewsWorker.perform_at(5.minutes.from_now, @news.title, @news.link, @news.image, user_detail.email, user_detail.category_name, type, email_template)

But anyhow its not working and show error message like:

TID-owrsuwi8g WARN: NameError: uninitialized constant NewsWorker

I tried to call from Model and Controller as well but still display same error. My old worked running fine but why this new create not working.. I found many ways but still not sortout.

Update

# /app/workers/news_worker.rb

class NewsWorker
  include Sidekiq::Worker
  include Rails.application.routes.url_helpers

  def perform  news_title, news_link, news_image, email, category_name, type, email_template = nil
    send_to_email(news_title, news_link, news_image, email, category_name, type, email_template)
  end

  def send_to_email news_title, news_link, news_image, email, category_name, type, email_template
    SchoolMailer.send_news(news_title, news_link, news_image, email, category_name, type, email_template).deliver
  end
end

Let me know if any one have idea.

Thanks

Body:
I think it has something to do with autoload_paths; the workers directory is not auto-loaded.

In config/application.rb add the following line:

config.autoload_paths += %W(#{config.root}/app/workers)

This should do the trick


问:
How to read the json string through C# code in runtime?
```<code>{
    "StudentInformation": {
        "rollNumber": null,
        "isClassLeader": false,
        "result": "Pass"

    },

    "CollegeInformation": {
        "allClass": ["A", "B"],
        "currencyAccepted": "INR",
        "calendarDates": [],
        "currencyCode": "INR",
        "collegeCode": null,
        "hasBulidingFundPrices": false,
        "hasHostel": false,
        "hasSecurityFares": false

    },

    "Collegetrips": [{
        "tripsdate": [{
                "departureTripDate": "2017-08-15 00:00:00",
                    "Places": [{
                            "destination": "Bombay",
                            "price": [{
                                "priceAmount": 1726
                                    }]
                                }]
                        }]
             }]
}
</code>```

In the above json file i need to retrieve only "priceAmount": 1726. Please anyone suggest how can able to achieve?

答:
Hi try this,</p>

```<code>public void Main()
            {
                string sJSON = "{\"StudentInformation\": {\"rollNumber\": null,\"isClassLeader\": false,\"result\": \"Pass\"},\"CollegeInformation\": {\"allClass\": [\"A\", \"B\"],\"currencyAccepted\": \"INR\",\"calendarDates\": [],\"currencyCode\": \"INR\",\"collegeCode\": null,\"hasBulidingFundPrices\": false,\"hasHostel\": false,\"hasSecurityFares\": false},\"Collegetrips\": [{\"tripsdate\": [{\"departureTripDate\": \"2017-08-15 00:00:00\",\"Places\": [{\"destination\": \"Bombay\",\"price\": [{\"priceAmount\": 1726}]}]}]}]}";
                Rootobject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(sJSON);
                Price price = obj.Collegetrips.Select(ct =>
                {
                    var r = ct.tripsdate.Select(td =>
                    {
                        var r1 = td.Places.Select(p =>
                        {
                            Price itemPrice = p.price.FirstOrDefault();
                            return itemPrice;
                        }).FirstOrDefault();

                        return r1;

                    }).FirstOrDefault();
                    return r;
                }).FirstOrDefault();

                if (price != null)
                    Console.Write(price.priceAmount);
                else
                    Console.Write("Not Found!");

            }

    public class Rootobject
    {
        public Studentinformation StudentInformation { get; set; }
        public Collegeinformation CollegeInformation { get; set; }
        public Collegetrip[] Collegetrips { get; set; }
    }

    public class Studentinformation
    {
        public object rollNumber { get; set; }
        public bool isClassLeader { get; set; }
        public string result { get; set; }
    }

    public class Collegeinformation
    {
        public string[] allClass { get; set; }
        public string currencyAccepted { get; set; }
        public object[] calendarDates { get; set; }
        public string currencyCode { get; set; }
        public object collegeCode { get; set; }
        public bool hasBulidingFundPrices { get; set; }
        public bool hasHostel { get; set; }
        public bool hasSecurityFares { get; set; }
    }

    public class Collegetrip
    {
        public Tripsdate[] tripsdate { get; set; }
    }

    public class Tripsdate
    {
        public string departureTripDate { get; set; }
        public Place[] Places { get; set; }
    }

    public class Place
    {
        public string destination { get; set; }
        public Price[] price { get; set; }
    }

    public class Price
    {
        public int priceAmount { get; set; }
    }
</code>```

Body:
{
    "StudentInformation": {
        "rollNumber": null,
        "isClassLeader": false,
        "result": "Pass"

    },

    "CollegeInformation": {
        "allClass": ["A", "B"],
        "currencyAccepted": "INR",
        "calendarDates": [],
        "currencyCode": "INR",
        "collegeCode": null,
        "hasBulidingFundPrices": false,
        "hasHostel": false,
        "hasSecurityFares": false

    },

    "Collegetrips": [{
        "tripsdate": [{
                "departureTripDate": "2017-08-15 00:00:00",
                    "Places": [{
                            "destination": "Bombay",
                            "price": [{
                                "priceAmount": 1726
                                    }]
                                }]
                        }]
             }]
}

In the above json file i need to retrieve only "priceAmount": 1726. Please anyone suggest how can able to achieve?

Body:
Hi try this,

public void Main()
            {
                string sJSON = "{\"StudentInformation\": {\"rollNumber\": null,\"isClassLeader\": false,\"result\": \"Pass\"},\"CollegeInformation\": {\"allClass\": [\"A\", \"B\"],\"currencyAccepted\": \"INR\",\"calendarDates\": [],\"currencyCode\": \"INR\",\"collegeCode\": null,\"hasBulidingFundPrices\": false,\"hasHostel\": false,\"hasSecurityFares\": false},\"Collegetrips\": [{\"tripsdate\": [{\"departureTripDate\": \"2017-08-15 00:00:00\",\"Places\": [{\"destination\": \"Bombay\",\"price\": [{\"priceAmount\": 1726}]}]}]}]}";
                Rootobject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(sJSON);
                Price price = obj.Collegetrips.Select(ct =>
                {
                    var r = ct.tripsdate.Select(td =>
                    {
                        var r1 = td.Places.Select(p =>
                        {
                            Price itemPrice = p.price.FirstOrDefault();
                            return itemPrice;
                        }).FirstOrDefault();

                        return r1;

                    }).FirstOrDefault();
                    return r;
                }).FirstOrDefault();

                if (price != null)
                    Console.Write(price.priceAmount);
                else
                    Console.Write("Not Found!");

            }

    public class Rootobject
    {
        public Studentinformation StudentInformation { get; set; }
        public Collegeinformation CollegeInformation { get; set; }
        public Collegetrip[] Collegetrips { get; set; }
    }

    public class Studentinformation
    {
        public object rollNumber { get; set; }
        public bool isClassLeader { get; set; }
        public string result { get; set; }
    }

    public class Collegeinformation
    {
        public string[] allClass { get; set; }
        public string currencyAccepted { get; set; }
        public object[] calendarDates { get; set; }
        public string currencyCode { get; set; }
        public object collegeCode { get; set; }
        public bool hasBulidingFundPrices { get; set; }
        public bool hasHostel { get; set; }
        public bool hasSecurityFares { get; set; }
    }

    public class Collegetrip
    {
        public Tripsdate[] tripsdate { get; set; }
    }

    public class Tripsdate
    {
        public string departureTripDate { get; set; }
        public Place[] Places { get; set; }
    }

    public class Place
    {
        public string destination { get; set; }
        public Price[] price { get; set; }
    }

    public class Price
    {
        public int priceAmount { get; set; }
    }


问:
Typo3 Realurl urlcache is messed up by gclid-parameter
We use Google-Adwords for some campaigns which ads a gclid=xxxxx parameter to the URL.
Unfortunately, this messes up the RealUrl tables and when the page is called next time it results in a 404-error.

Is there any way to make RealUrl ignore this particular parameter?

答:
This is claimed to be solved on GitHub:

https://github.com/dmitryd/typo3-realurl/issues/377

Anyways I still had that problem that the gclid triggers a urldata entry which causes a redirect loop. For now I solved it with removing the gclid from the ignoredGetparameters Filter and then banning it:

```<code>        'cache' => array( // removed gclid from the filter, then ban it
            'ignoredGetParametersRegExp' => '/^(?:utm_[a-z]+|pk_campaign|pk_kwd|TSFE_ADMIN_PANEL.*)$/'
            'banUrlsRegExp' => '/gclid|tx_solr|tx_indexed_search|(?:^|\?|&)q=/',
        ),
</code>```

Body:
This is claimed to be solved on GitHub:

https://github.com/dmitryd/typo3-realurl/issues/377

Anyways I still had that problem that the gclid triggers a urldata entry which causes a redirect loop. For now I solved it with removing the gclid from the ignoredGetparameters Filter and then banning it:

        'cache' => array( // removed gclid from the filter, then ban it
            'ignoredGetParametersRegExp' => '/^(?:utm_[a-z]+|pk_campaign|pk_kwd|TSFE_ADMIN_PANEL.*)$/'
            'banUrlsRegExp' => '/gclid|tx_solr|tx_indexed_search|(?:^|\?|&)q=/',
        ),


问:
xcode 6 assistant editor Automatic results will not display
I can not drag anything to the code from the storyboard.  Files were in assistant editor under automatic but now there gone how do i get them back other then deleting and recreating them? Opening them up under manual it will come up but Xcode can't find the referance when dragging to the code and i get the error when naming it.</p>

答:
The issue is due to not completion of indexing - so there are few alternatives, that you can try for-

Way 01 : Check if indexing is showing in processes - then let it complete. Then, close the editor and reopen it

Way 02 : Just perform the clean action. It will start showing appropriate Viewcontrollers.

Way 03 : This is the most effective way - Just perform "Build" and then restart editor - it will surely going to work.


问:
CSS/HTML5: How to adjust div tag height equal to browser window's current height?
I want the height of my div tag exactly equal to the height of the browser's window. So if you resize the browser the  should adjust automatically.
So what should I set my height equal to in CSS.

I have tried

```<code>.class {
  height: 100%;
}
</code>```

Doesn't work.

em, rem, vh, wh apparently only work with the font.

If I however, hard-code the body tag to some amount of pixels, then the percentage works for the children tags but this is not dynamic.

What I want: Just as I am viewing this stack page in my browser. I wish when I resize the browser I still get the same amount of page viewership, only resized for the new size (responsive).

Thanks.

答:
Yes you can add VH height to a div and completely agree with @Nofel.

But it will will for mozilla and chrome. It will not work for Safari or IE.

Add vh property resize the window.

Body:
I want the height of my div tag exactly equal to the height of the browser's window. So if you resize the browser the  should adjust automatically.
So what should I set my height equal to in CSS.

I have tried

.class {
  height: 100%;
}

Doesn't work.

em, rem, vh, wh apparently only work with the font.

If I however, hard-code the body tag to some amount of pixels, then the percentage works for the children tags but this is not dynamic.

What I want: Just as I am viewing this stack page in my browser. I wish when I resize the browser I still get the same amount of page viewership, only resized for the new size (responsive).

Thanks.


问:
Display webview with basic authentication inside program
I have to display a webpage inside my Java software.( you can think it is one the page of a Wireless Device configuration)
But when Im gonna go to that page in browser,browser displays a user and password popup and I enter the user and password and go to that page.( notice that username is always root, but password can be different)
Now I am gonna display the page from Java software, I could link the page and open the page via Java, But the host inside the wireless device displays :
401 Unauthorized, The URL of the page I want to display is http://192.168.1.2/Wireless
I used Fiddler to monitor its behavior, that URL is continuously reloading.
And here is the Header of the Get method of that :

```<code>GET /Wireless HTTP/1.1
Host: 192.168.1.2
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.1.2/Wireless
Authorization: Basic xxxxxxxxx
Connection: keep-alive
</code>```

How can I do that? With HttpClient ?
Does anybody knows how to do that? And give me a solution?
Or a sample or anything can help me?|
Thanks.

EDIT :
Here is my code to display the webview :

```<code>         myFrame.setSize(mainJTabbed.getSize());
     myFrame.setLocationRelativeTo(mainJTabbed);
    myFrame.setVisible(true);
    myFrame.add(myFXPanel);
    Platform.runLater(() -> {
      BorderPane borderPane = new BorderPane();
      WebView webComponent = new WebView();

      webComponent.getEngine().load("myURL");

      borderPane.setCenter(webComponent);
      Scene scene = new Scene(borderPane,450,450);
      myFXPanel.setScene(scene);
});
</code>```

And even it is a GET method, the user and password does not post via URL.

答:
I did it in this way, I created a class with a constructor, the all is in constructor, notice that my constructor what I wanted, you can change it, but the algorithm is this : </p>

```<code>    import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;
import javax.swing.JFrame;
public class WebViewSample {

    public WebViewSample(String urlString, JFrame myFrame, JFXPanel myFXPanel) {

        try {
        // Sets the authenticator that will be used by the networking code
            // when a proxy or an HTTP server asks for authentication.
            Authenticator.setDefault(new CustomAuthenticator());

            URL url = new URL("http://" +urlString + "/wireless");
                            Platform.runLater(() -> {
                            BorderPane borderPane = new BorderPane();
                            WebView webComponent = new WebView();

                            webComponent.getEngine().load(url.toString());

                            borderPane.setCenter(webComponent);
                            Scene scene = new Scene(borderPane,450,450);
                            myFXPanel.setScene(scene);
                        });
                    }
        catch (MalformedURLException e) {
            System.out.println("Malformed URL: " + e.getMessage());
        }
        catch (IOException e) {
            System.out.println("I/O Error: " + e.getMessage());
        }
    }
    public static class CustomAuthenticator extends Authenticator {

        // Called when password authorization is needed
        protected PasswordAuthentication getPasswordAuthentication() {

            // Get information about the request
            String prompt = getRequestingPrompt();
            String hostname = getRequestingHost();
            InetAddress ipaddr = getRequestingSite();
            int port = getRequestingPort();

            String username = "myUserName";
            String password = "myPassword";
            // Return the information (a data holder that is used by Authenticator)
            return new PasswordAuthentication(username, password.toCharArray());
        }
    }
}
</code>```

Body:
I have to display a webpage inside my Java software.( you can think it is one the page of a Wireless Device configuration)
But when Im gonna go to that page in browser,browser displays a user and password popup and I enter the user and password and go to that page.( notice that username is always root, but password can be different)
Now I am gonna display the page from Java software, I could link the page and open the page via Java, But the host inside the wireless device displays :
401 Unauthorized, The URL of the page I want to display is http://192.168.1.2/Wireless
I used Fiddler to monitor its behavior, that URL is continuously reloading.
And here is the Header of the Get method of that :

GET /Wireless HTTP/1.1
Host: 192.168.1.2
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.1.2/Wireless
Authorization: Basic xxxxxxxxx
Connection: keep-alive

How can I do that? With HttpClient ?
Does anybody knows how to do that? And give me a solution?
Or a sample or anything can help me?|
Thanks.

EDIT :
Here is my code to display the webview :

         myFrame.setSize(mainJTabbed.getSize());
     myFrame.setLocationRelativeTo(mainJTabbed);
    myFrame.setVisible(true);
    myFrame.add(myFXPanel);
    Platform.runLater(() -> {
      BorderPane borderPane = new BorderPane();
      WebView webComponent = new WebView();

      webComponent.getEngine().load("myURL");

      borderPane.setCenter(webComponent);
      Scene scene = new Scene(borderPane,450,450);
      myFXPanel.setScene(scene);
});

And even it is a GET method, the user and password does not post via URL.

Body:
I did it in this way, I created a class with a constructor, the all is in constructor, notice that my constructor what I wanted, you can change it, but the algorithm is this :

    import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;
import javax.swing.JFrame;
public class WebViewSample {

    public WebViewSample(String urlString, JFrame myFrame, JFXPanel myFXPanel) {

        try {
        // Sets the authenticator that will be used by the networking code
            // when a proxy or an HTTP server asks for authentication.
            Authenticator.setDefault(new CustomAuthenticator());

            URL url = new URL("http://" +urlString + "/wireless");
                            Platform.runLater(() -> {
                            BorderPane borderPane = new BorderPane();
                            WebView webComponent = new WebView();

                            webComponent.getEngine().load(url.toString());

                            borderPane.setCenter(webComponent);
                            Scene scene = new Scene(borderPane,450,450);
                            myFXPanel.setScene(scene);
                        });
                    }
        catch (MalformedURLException e) {
            System.out.println("Malformed URL: " + e.getMessage());
        }
        catch (IOException e) {
            System.out.println("I/O Error: " + e.getMessage());
        }
    }
    public static class CustomAuthenticator extends Authenticator {

        // Called when password authorization is needed
        protected PasswordAuthentication getPasswordAuthentication() {

            // Get information about the request
            String prompt = getRequestingPrompt();
            String hostname = getRequestingHost();
            InetAddress ipaddr = getRequestingSite();
            int port = getRequestingPort();

            String username = "myUserName";
            String password = "myPassword";
            // Return the information (a data holder that is used by Authenticator)
            return new PasswordAuthentication(username, password.toCharArray());
        }
    }
}


问:
Hibernate mapping object to table having a certain value?
I have a table called Object that has a foreign key to ObjectType table.

For my domain model, I have an object for each ObjectType:  How do I map the domain object Article to the Object table where the objectTypeFk column maps to ObjectType row having the value Article.  I also have a domain object ObjectType which is simply an enum of all possible types (which I was hoping to tie into the mapping somehow).

I had no luck looking through the docs as I don't know what to search for (i.e. how to describe what I'm trying to achieve).

答:
Not sure this is possible without some hacks, but what you are describing sounds close to a inheritance strategy using "table per hierarchy", except that it would use "Article" as the discriminator (a simple varchar column) instead of a FK. </p>

<p>http://docs.jboss.org/hibernate/core/3.5/reference/en/html/inheritance.html#inheritance-tableperclass </p>

ContentLicense: CC BY-SA 2.5

Body:
Not sure this is possible without some hacks, but what you are describing sounds close to a inheritance strategy using "table per hierarchy", except that it would use "Article" as the discriminator (a simple varchar column) instead of a FK.

http://docs.jboss.org/hibernate/core/3.5/reference/en/html/inheritance.html#inheritance-tableperclass


问:
Connect to Amazon web services SQS (Simple Queue service) using Python?
I was wondering if somebody here knows how I can connect to AWS SQS using Python? Do I need a public Url?

Could someone provide a simple code example on how to do this?

Thank you.

答:
As I said in comments, use boto:

```<code>import boto3

# Create SQS client
sqs = boto3.client('sqs')

# List SQS queues
response = sqs.list_queues()

print(response['QueueUrls'])
</code>```

Documentation here

Body:
As I said in comments, use boto:

import boto3

# Create SQS client
sqs = boto3.client('sqs')

# List SQS queues
response = sqs.list_queues()

print(response['QueueUrls'])

Documentation here


问:
How to get only text in Custom Material Spinner with Image and Text
I have a Material Spinner which displays an image and text, but i want to retrieve just the text in OnItemSelected. But it is returning null.

My Adapter Class

```<code>   public class SpinnerCustomAdapter extends BaseAdapter {
    Context context;
    int cat_pics[];
    ArrayList<String> categoryNames;
    LayoutInflater inflter;

    public SpinnerCustomAdapter(Context applicationContext, int[] cat_pics, ArrayList<String> categoryNames) {
        this.context = applicationContext;
        this.cat_pics = cat_pics;
        this.categoryNames = categoryNames;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return cat_pics.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.custom_spinner_items, null);
        ImageView icon = (ImageView) view.findViewById(R.id.imageView);
        TextView names = (TextView) view.findViewById(R.id.textView);
        icon.setImageResource(cat_pics[i]);
        names.setText(categoryNames.get(i));
        return view;
    }
}
</code>```

Setting the Adapter in Main Activity

```<code> customAdapter=newSpinnerCustomAdapter(getApplicationContext(),cat_pics,allCatNames);
    spCategories.setAdapter(customAdapter);
    spCategories.setOnItemSelectedListener(this);
</code>```

onItemSelected

```<code>@Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Toast.makeText(parent.getContext(), "Selected Item : " + customAdapter.getItem(position) ,
                Toast.LENGTH_LONG).show();
    }
</code>```

答:
Try like this, may help you</p>

```<code>spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            String text = spinner.getItemAtPosition(i)
            Toast.makeText(getApplicationContext(), "Selected : " text, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
</code>```

Body:
I have a Material Spinner which displays an image and text, but i want to retrieve just the text in OnItemSelected. But it is returning null.

My Adapter Class

   public class SpinnerCustomAdapter extends BaseAdapter {
    Context context;
    int cat_pics[];
    ArrayList<String> categoryNames;
    LayoutInflater inflter;

    public SpinnerCustomAdapter(Context applicationContext, int[] cat_pics, ArrayList<String> categoryNames) {
        this.context = applicationContext;
        this.cat_pics = cat_pics;
        this.categoryNames = categoryNames;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return cat_pics.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.custom_spinner_items, null);
        ImageView icon = (ImageView) view.findViewById(R.id.imageView);
        TextView names = (TextView) view.findViewById(R.id.textView);
        icon.setImageResource(cat_pics[i]);
        names.setText(categoryNames.get(i));
        return view;
    }
}

Setting the Adapter in Main Activity

 customAdapter=newSpinnerCustomAdapter(getApplicationContext(),cat_pics,allCatNames);
    spCategories.setAdapter(customAdapter);
    spCategories.setOnItemSelectedListener(this);

onItemSelected

@Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Toast.makeText(parent.getContext(), "Selected Item : " + customAdapter.getItem(position) ,
                Toast.LENGTH_LONG).show();
    }

Body:
Try like this, may help you

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            String text = spinner.getItemAtPosition(i)
            Toast.makeText(getApplicationContext(), "Selected : " text, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });


问:
UIAlertController with text field - hitting return button only hides keyboard, does not perform action?
I'm trying to use the iOS 8 UIAlertController in place of where I would have used a UIAlertView in the past. I want the user to be able to enter text into this alert and hit "OK" to process the text or "Cancel" to cancel.

Here's the basic code:

```<code>UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Change Value" message:@"Enter your new value."];
[alert addTextFieldWithConfigurationHandler:nil];

[alert addAction: [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    UITextField *textField = alert.textFields[0];
    NSLog(@"text was %@", textField.text);
}]];

[alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    NSLog(@"Cancel pressed");
}]];

[presentingVC presentViewController:alert animated:YES completion:nil];
</code>```

With the old UIAlertView, I would tag it with an alertViewStyle of UIAlertViewStylePlainTextInput. Then, if the user hit the "Return" button on their keyboard after entering text, the UIAlertViewDelegate method willDismissWithButtonIndex: would be called with some buttonIndex (depending on what buttons had been specified in the UIAlertView).

In the new UIAlertController, if the user taps the "OK" or "Cancel" buttons, then their corresponding actions are performed as expected; but if the user just hits the "Return" key on the keyboard, it just hides the keyboard, but the alert remains on screen and no action is performed.

I've thought about configuring the text field to set the UITextFieldDelegate to self, and then maybe overriding the textFieldDidReturn: method, but I also don't know if there's a way to call one of the UIAlertController's actions programmatically. And this is sounding sort of messy/hacky anyway. Am I missing something obvious?

答: You shouldn't set two "UIAlertActionStyleCancel" in UIAlertAction.</p>

Body:
I'm trying to use the iOS 8 UIAlertController in place of where I would have used a UIAlertView in the past. I want the user to be able to enter text into this alert and hit "OK" to process the text or "Cancel" to cancel.

Here's the basic code:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Change Value" message:@"Enter your new value."];
[alert addTextFieldWithConfigurationHandler:nil];

[alert addAction: [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    UITextField *textField = alert.textFields[0];
    NSLog(@"text was %@", textField.text);
}]];

[alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    NSLog(@"Cancel pressed");
}]];

[presentingVC presentViewController:alert animated:YES completion:nil];

With the old UIAlertView, I would tag it with an alertViewStyle of UIAlertViewStylePlainTextInput. Then, if the user hit the "Return" button on their keyboard after entering text, the UIAlertViewDelegate method willDismissWithButtonIndex: would be called with some buttonIndex (depending on what buttons had been specified in the UIAlertView).

In the new UIAlertController, if the user taps the "OK" or "Cancel" buttons, then their corresponding actions are performed as expected; but if the user just hits the "Return" key on the keyboard, it just hides the keyboard, but the alert remains on screen and no action is performed.

I've thought about configuring the text field to set the UITextFieldDelegate to self, and then maybe overriding the textFieldDidReturn: method, but I also don't know if there's a way to call one of the UIAlertController's actions programmatically. And this is sounding sort of messy/hacky anyway. Am I missing something obvious?


答:
You can bind a function to resize the container on window resize.

HTML:

```<code><div class="container">
   Content
</div>
</code>```

CSS:

```<code>.container {
   height: 100vh;
}
</code>```

JavaScript:

```<code>function resize_container() {
   var height = $(window).height(),
       container = $('.container');

   container.css('height', height);
}

$(window).resize(resize_container);
</code>```

Title: CSS/HTML5: How to adjust div tag height equal to browser window's current height?

Body:
You can bind a function to resize the container on window resize.

HTML:

<div class="container">
   Content
</div>

CSS:

.container {
   height: 100vh;
}

JavaScript:

function resize_container() {
   var height = $(window).height(),
       container = $('.container');

   container.css('height', height);
}

$(window).resize(resize_container);


问:
Bottom Navigation View not responsive
I need that BottomNavigationView to be responsive. When I use a Nexus 4 it has the exact measurement, but with Nexus 6 it does not. Any idea?</p>

```<code><android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    app:itemIconTint="@drawable/selector"
    app:itemTextColor="@color/colorPrimary"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation"/>
</code>```

答:
If you are talking about the width not matching the parent, check this answer. You have to play with the background by setting its color with the same color as the item</p>

```<code> android:background="@color/bottom_view_color"
 app:itemBackground="@color/bottom_view_color"
</code>```

Title: Bottom Navigation View not responsive

Body:
I need that BottomNavigationView to be responsive. When I use a Nexus 4 it has the exact measurement, but with Nexus 6 it does not. Any idea?

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    app:itemIconTint="@drawable/selector"
    app:itemTextColor="@color/colorPrimary"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation"/>

Body:
If you are talking about the width not matching the parent, check this answer. You have to play with the background by setting its color with the same color as the item

 android:background="@color/bottom_view_color"
 app:itemBackground="@color/bottom_view_color"


问:
Incorrect height iphone
I have a problem when viewing a page in landscape mode on iphones (testing on model SE but it seems like a lot of people have the same problem with other iphones).

I have made an example below, it is a simple webpage with two lines of texts one text in the top and one in the bottom.

The problem is that when i view the page in normal mode everything looks fine, but when rotating the phone in landscape mode the addressbar covers the top and the toolbar covers the bottom of the page. I have added some javascript to scroll the page so that it starts under the address bar, but since the page is now scrolled down the last line is hidden behind the toolbar.

I have tested a lot of meta tags and different css hacks but to no good.

I just want both text to be shown when going to this page, i dont want to have to scroll, but just for info i want to be able to zoom in on the page later on so the solution can't block zoom on the page.

Code:

```<code><html>
<meta content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<script>
window.addEventListener("load",function() {
    setTimeout(function(){
        window.scrollTo(0, 1);
    }, 0);
});
window.addEventListener("resize",function() {
    setTimeout(function(){
        window.scrollTo(0, 1);
    }, 0);
});
</script>
<style>
div {
        position: absolute;
        bottom: 0;
        margin: auto;
}
</style>
<body>
Top
<div>
Bottom
</div>
</body>
</html>
</code>```

答:
Try to add meta viewport like,

```<code><meta name="viewport" content="width=device-width, initial-scale=1">
</code>```

Also read Using the Viewport

Title: Incorrect height iphone

Body:
I have a problem when viewing a page in landscape mode on iphones (testing on model SE but it seems like a lot of people have the same problem with other iphones).

I have made an example below, it is a simple webpage with two lines of texts one text in the top and one in the bottom.

The problem is that when i view the page in normal mode everything looks fine, but when rotating the phone in landscape mode the addressbar covers the top and the toolbar covers the bottom of the page. I have added some javascript to scroll the page so that it starts under the address bar, but since the page is now scrolled down the last line is hidden behind the toolbar.

I have tested a lot of meta tags and different css hacks but to no good.

I just want both text to be shown when going to this page, i dont want to have to scroll, but just for info i want to be able to zoom in on the page later on so the solution can't block zoom on the page.

Code:

<meta content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />

Top

Bottom

Body:
Try to add meta viewport like,

<meta name="viewport" content="width=device-width, initial-scale=1">

Also read Using the Viewport


问:
Infragistics igDataChart in AngularJS
Here i am using infragistics data chart in my Angular Js (1.4) application..
The tool top showing point values are not coming up , and how can show legend to describe what each series is for ?

Here is my sample HTML :

```<code>     <div id="lineLegend" style="float: left"></div>
                    <ig-data-chart id="datachart1"
                     data-source="ctrl.dataChart" auto-margin-height="12"  legend="{ element: "legend" }" >
        <axes>
            <axis name="NameAxis"
                    type="categoryX"
                    title="Country"
                    label="Day"></axis>

            <axis name="PopulationAxis"
                    type="numericY"
                    minimumvalue="0"
                    ></axis>

        </axes>
        <series>
            <series name="Systolic"
                    type="area"
                      showTooltip ="true"

                    is-highlighting-enabled="true"
                    is-transition-in-enabled="true"
                    x-axis="NameAxis"
                    y-axis="PopulationAxis"
                    value-member-path="Systolic">
            </series>
            <series name="Diastolic"
                    type="area"
                      showTooltip ="true"

                    is-highlighting-enabled="true"
                    is-transition-in-enabled="true"
                    x-axis="NameAxis"
                    trendLineBrush: "#000"
                    y-axis="PopulationAxis"
                    value-member-path="Diastolic">
            </series>

        </series>

    </ig-data-chart>
</code>```

Ctrl

```<code>  vm.dataChart =   [
                    { "Day": "Mon", "Systolic": 80, "Diastolic": 100  },
                    { "Day": "Tue", "Systolic": 10, "Diastolic": 30  },
                    { "Day": "Wed", "Systolic": 266, "Diastolic": 295  },
                    { "Day": "Thu", "Systolic": 397, "Diastolic": 229 },
                    { "Day": "Fri", "Systolic": 161, "Diastolic": 300  },
                    { "Day": "Sat", "Systolic": 61, "Diastolic": 130  },
                    { "Day": "Sun", "Systolic": 361, "Diastolic": 30  },

                ];
</code>```

答:
Make sure you have defined all the properties correctly:

```<code>showTooltip="true"
</code>```

should be

```<code>show-tooltip="true"
</code>```

Title: Infragistics igDataChart in AngularJS

Body:
Here i am using infragistics data chart in my Angular Js (1.4) application..
The tool top showing point values are not coming up , and how can show legend to describe what each series is for ?

Here is my sample HTML :

                    <ig-data-chart id="datachart1"
                     data-source="ctrl.dataChart" auto-margin-height="12"  legend="{ element: "legend" }" >
        <axes>
            <axis name="NameAxis"
                    type="categoryX"
                    title="Country"
                    label="Day"></axis>

            <axis name="PopulationAxis"
                    type="numericY"
                    minimumvalue="0"
                    ></axis>

        </axes>
        <series>
            <series name="Systolic"
                    type="area"
                      showTooltip ="true"

                    is-highlighting-enabled="true"
                    is-transition-in-enabled="true"
                    x-axis="NameAxis"
                    y-axis="PopulationAxis"
                    value-member-path="Systolic">
            </series>
            <series name="Diastolic"
                    type="area"
                      showTooltip ="true"

                    is-highlighting-enabled="true"
                    is-transition-in-enabled="true"
                    x-axis="NameAxis"
                    trendLineBrush: "#000"
                    y-axis="PopulationAxis"
                    value-member-path="Diastolic">
            </series>

        </series>

    </ig-data-chart>

Ctrl

  vm.dataChart =   [
                    { "Day": "Mon", "Systolic": 80, "Diastolic": 100  },
                    { "Day": "Tue", "Systolic": 10, "Diastolic": 30  },
                    { "Day": "Wed", "Systolic": 266, "Diastolic": 295  },
                    { "Day": "Thu", "Systolic": 397, "Diastolic": 229 },
                    { "Day": "Fri", "Systolic": 161, "Diastolic": 300  },
                    { "Day": "Sat", "Systolic": 61, "Diastolic": 130  },
                    { "Day": "Sun", "Systolic": 361, "Diastolic": 30  },

                ];

Body:
Make sure you have defined all the properties correctly:

showTooltip="true"

should be

show-tooltip="true"


问:
is there a programmatic way to check the correctness of recaptcha public and private key?
I developed an admin part of a website where the admin can disable or enable the re-captcha for the website also he can decide to use version 1 or 2.

But I stopped at a point where he enters the public and private key; he can enter wrong or invalid public or private key.

So Is there a way to check whether he enters a valid public & private key based on the request (current) domain ... I thought about connecting to Google APIs but I don't know if what I aim is applicable or not, and if applicable how can I achieve that?

any help is appreciated

答:
You can validate the private key by submitting an empty response to the verification api, and if 'invalid-input-secret' isn't in the 'error-codes' array in the result, the private key is valid.

However, that api doesn't take the public key as a parameter, so it can't be validated that way.

I too would vastly prefer some way to validate the public key on the server side, rather than asking users if the reCAPTCHA UI is displayed correctly. If anyone knows a way to do that, please speak up.

If this is really a gap in the reCAPTCHA api, I hope Google sees fit to fill it. I've submitted an issue to the project, hopefully something useful will come of it.


问:
How do you count the elements of an array in java
Say i have the array

```<code>int theArray = new int[20];
</code>```

The length of the array is 20 but the count is 0. How can i get the count?

答: You can use a for each loop and count the number of integer values that are significant. You could also use an ArrayList which will keep track of the couny for you. Everytime you add or remove objects from the list it will automatically update the count. Calling the size() method will give you the current number of elements.</p>

Body:
Say i have the array

int theArray = new int[20];

The length of the array is 20 but the count is 0. How can i get the count?


问:
Detect log file rotation (while watching log file for modification)
I use the following code to track ssh log-ins:

```<code>def follow(thefile):
  thefile.seek(0,2)
  while True:
    line = thefile.readline()
    if not line:
      time.sleep(0.1)
      continue
    yield line

if __name__ == '__main__':
  logfile = open('/var/log/auth.log', 'r')
  loglines = follow(logfile)
  for line in loglines:
    print 'do something here'
</code>```

I've noticed that this script suddenly stops working after a couple of days. I don't get any error, it doesn't terminate, it just stops working, as if readline() would never return.

So I executed a echo 'test' >> auth.log.1 and this indeed ends up getting processed by the script, because sometime ago auth.log got renamed to auth.log.1

How can I track when such a log rotation happens and adjust accordingly?

答:
Using e4c5's answer I ended up with this code, which also solves the issue of calling readline() multiple times per second.

During the first invocation it skips to the end of the file and waits for modifications. When the file is moved, it reopens the file and reads the entire content, then starts to wait.

```<code>import os
import time
import traceback
import threading
import inotify.adapters

logfile = b'/var/log/auth.log'
#logfile = b'logfile.log'

##################################################################

def process(line, history=False):
  if history:
    print '=', line.strip('\n')
  else:
    print '>', line.strip('\n')

##################################################################

from_beginning = False
notifier = inotify.adapters.Inotify()
while True:
  try:
    #------------------------- check
    if not os.path.exists(logfile):
      print 'logfile does not exist'
      time.sleep(1)
      continue
    print 'opening and starting to watch', logfile
    #------------------------- open
    file = open(logfile, 'r')
    if from_beginning:
      for line in file.readlines():
        process(line, history=True)
    else:
      file.seek(0,2)
      from_beginning = True
    #------------------------- watch
    notifier.add_watch(logfile)
    try:
      for event in notifier.event_gen():
        if event is not None:
          (header, type_names, watch_path, filename) = event
          if set(type_names) & set(['IN_MOVE_SELF']): # moved
            print 'logfile moved'
            notifier.remove_watch(logfile)
            file.close()
            time.sleep(1)
            break
          elif set(type_names) & set(['IN_MODIFY']): # modified
            for line in file.readlines():
              process(line, history=False)
    except (KeyboardInterrupt, SystemExit):
      raise
    except:
      notifier.remove_watch(logfile)
      file.close()
      time.sleep(1)
    #-------------------------
  except (KeyboardInterrupt, SystemExit):
    break
  except inotify.calls.InotifyError:
    time.sleep(1)
  except IOError:
    time.sleep(1)
  except:
    traceback.print_exc()
    time.sleep(1)

##################################################################
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I use the following code to track ssh log-ins:

def follow(thefile):
  thefile.seek(0,2)
  while True:
    line = thefile.readline()
    if not line:
      time.sleep(0.1)
      continue
    yield line

if __name__ == '__main__':
  logfile = open('/var/log/auth.log', 'r')
  loglines = follow(logfile)
  for line in loglines:
    print 'do something here'

I've noticed that this script suddenly stops working after a couple of days. I don't get any error, it doesn't terminate, it just stops working, as if readline() would never return.

So I executed a echo 'test' >> auth.log.1 and this indeed ends up getting processed by the script, because sometime ago auth.log got renamed to auth.log.1

How can I track when such a log rotation happens and adjust accordingly?

Body:
Using e4c5's answer I ended up with this code, which also solves the issue of calling readline() multiple times per second.

During the first invocation it skips to the end of the file and waits for modifications. When the file is moved, it reopens the file and reads the entire content, then starts to wait.

import os
import time
import traceback
import threading
import inotify.adapters

logfile = b'/var/log/auth.log'
#logfile = b'logfile.log'

##################################################################

def process(line, history=False):
  if history:
    print '=', line.strip('\n')
  else:
    print '>', line.strip('\n')

##################################################################

from_beginning = False
notifier = inotify.adapters.Inotify()
while True:
  try:
    #------------------------- check
    if not os.path.exists(logfile):
      print 'logfile does not exist'
      time.sleep(1)
      continue
    print 'opening and starting to watch', logfile
    #------------------------- open
    file = open(logfile, 'r')
    if from_beginning:
      for line in file.readlines():
        process(line, history=True)
    else:
      file.seek(0,2)
      from_beginning = True
    #------------------------- watch
    notifier.add_watch(logfile)
    try:
      for event in notifier.event_gen():
        if event is not None:
          (header, type_names, watch_path, filename) = event
          if set(type_names) & set(['IN_MOVE_SELF']): # moved
            print 'logfile moved'
            notifier.remove_watch(logfile)
            file.close()
            time.sleep(1)
            break
          elif set(type_names) & set(['IN_MODIFY']): # modified
            for line in file.readlines():
              process(line, history=False)
    except (KeyboardInterrupt, SystemExit):
      raise
    except:
      notifier.remove_watch(logfile)
      file.close()
      time.sleep(1)
    #-------------------------
  except (KeyboardInterrupt, SystemExit):
    break
  except inotify.calls.InotifyError:
    time.sleep(1)
  except IOError:
    time.sleep(1)
  except:
    traceback.print_exc()
    time.sleep(1)

##################################################################


问:
Get link text using Selenium and Java
I have a problem with getting the text of a link.

On a site, I have the text link
ZZ-10048. The part with ZZ- is static, the number increments and it isn't known for me earlier. I need to get this number.

I used looking at: Get link text - Selenium, Java, but there I have all links, URLs (not the text of the links).

I also tried: How to gettext() of an element in Selenium Webdriver, but I got output Printing null every time I changed and looked for a solution.

And the solution: Java Selenium, how to get linkText (anchor) from link WebElement is not good either, because it doesn't recognise "a[href*='ZZ-']".

So, the closest one is:

```<code>List<WebElement> elements = driver.findElements(By.tagName("a"));
for (int i = 0; i < elements.size(); i++) {
   System.out.println(elements.get(i).getAttribute("href"));
}
</code>```

But how can I change to view not only URLs, but names of the link? (especially one which starts from ZZ-)

答:
```<code>WebElement element = driver.findElement(By.partialLinkText("ZZ-10048"));
String txt = element.getText();
String[] words = txt.split("-");
System.out.println(words[1]);
</code>```

Title: Get link text using Selenium and Java

Body:
I have a problem with getting the text of a link.

On a site, I have the text link
ZZ-10048. The part with ZZ- is static, the number increments and it isn't known for me earlier. I need to get this number.

I used looking at: Get link text - Selenium, Java, but there I have all links, URLs (not the text of the links).

I also tried: How to gettext() of an element in Selenium Webdriver, but I got output Printing null every time I changed and looked for a solution.

And the solution: Java Selenium, how to get linkText (anchor) from link WebElement is not good either, because it doesn't recognise "a[href*='ZZ-']".

So, the closest one is:

List<WebElement> elements = driver.findElements(By.tagName("a"));
for (int i = 0; i < elements.size(); i++) {
   System.out.println(elements.get(i).getAttribute("href"));
}

But how can I change to view not only URLs, but names of the link? (especially one which starts from ZZ-)


问:
How can I use a dictionary to obtain indices in a range of interest such that I can slice multiple lists at these indices?
I am trying to count indices to find the region of interest in a large amount of data. This way, I can use slice notation at the appropriate indices for fast performance. I originally tried using the .count() method but I am now trying to use a dictionary module. As an example, I created a txt file and obtained the number of occurrences of values. How can I use this to count indices in the range of interest?

Simple example:

The txt file contains the following data.

```<code>1     100       1
1     101       2
1     102       3
2     103       4
2     104       5
3     105       6
3     106       7
3     107       8
3     108       9
4     109       10
5     110       11
</code>```

I use the two functions below to read the file and organize the data into the appropriate lists.

```<code>def get_list_from_int(lines, col_number):
    list = []
    for col in lines:
        datum = col.split()
        list.append(float(datum[col_number]))
    return list

def read_data(filename): # filename = "User/Desktop/fileloc/filename.txt"
    lines = list(open(filename, 'r'))
    xs = get_list_from_int(lines, 0) # column 1
    ys = get_list_from_int(lines, 1) # column 2
    zs = get_list_from_int(lines, 2) # column 3
    return xs, ys, zs
</code>```

I then use Counter via the collections module.

```<code>X = Counter(xs)
print(X)
>> Counter({3.0: 4, 1.0: 3, 2.0: 2, 4.0: 1, 5.0: 1})
</code>```

Problem:
Suppose I would like the indices for which 3 ≤ xs ≤ 4. I can apply slice notation to obtain the same indices of the corresponding ys and zs. How can I obtain the sum of values of the keys greater than or equal to 3 but less than or equal to 4? Ideally, the obtained result would be [6, 10], but [6, 7, 8, 9, 10] would work too.

Original approach (worth abandoning?):
My original approach was to use define a function that counts the indices from the first element of a list until the first element of the range of interest, and then to continue counting until the last element in the range of interest; the function would take the the boundary elements of the range of interest as inputs using start += data_list.count(index) for index in range(1, boundary_1) and end += data_list.count(index) for index in range(boundary_1, boundary_2+1), but I could not get the function to work correctly.

答:
```<code>def choose_slice(start, end, xs):
    # subfunction called by get_slice() -- defined below
    go, stop = 0, 0
    cx = sorted(Counter(xs).items()) # sort to count consecutively
    for val, key in cx:
        if val < start:
            go += key # match index at boundary of region of interest
            # print("count = %d" %key, "value = %.2f" %val)
        elif val >= start and val <= end:
            stop += key # inbetweeen the boundaries, in the region of interest
            # print("count = %d" %key, "value = %.2f" %val)
        elif val > end: # match index at boundary of region of interest
            break
    stop = go + stop
    return go, stop

def get_slice(start, end, xs=xs, ys=ys, zs=zs):
    go, stop = choose_slice(start, end, xs) # get indices
    return xs[go:stop], ys[go:stop], zs[go:stop] # get values at indices

xx, yy, zz = get_slice(3, 4)
print(xx)
>> [3.0, 3.0, 3.0, 3.0, 4.0]
</code>```

This works for my dataset of size ~10^4. But I'm still curious about other approaches to this.

Body:
I am trying to count indices to find the region of interest in a large amount of data. This way, I can use slice notation at the appropriate indices for fast performance. I originally tried using the .count() method but I am now trying to use a dictionary module. As an example, I created a txt file and obtained the number of occurrences of values. How can I use this to count indices in the range of interest?

Simple example:

The txt file contains the following data.

1     100       1
1     101       2
1     102       3
2     103       4
2     104       5
3     105       6
3     106       7
3     107       8
3     108       9
4     109       10
5     110       11

I use the two functions below to read the file and organize the data into the appropriate lists.

def get_list_from_int(lines, col_number):
    list = []
    for col in lines:
        datum = col.split()
        list.append(float(datum[col_number]))
    return list

def read_data(filename): # filename = "User/Desktop/fileloc/filename.txt"
    lines = list(open(filename, 'r'))
    xs = get_list_from_int(lines, 0) # column 1
    ys = get_list_from_int(lines, 1) # column 2
    zs = get_list_from_int(lines, 2) # column 3
    return xs, ys, zs

I then use Counter via the collections module.

X = Counter(xs)
print(X)
>> Counter({3.0: 4, 1.0: 3, 2.0: 2, 4.0: 1, 5.0: 1})

Problem:
Suppose I would like the indices for which 3 ≤ xs ≤ 4. I can apply slice notation to obtain the same indices of the corresponding ys and zs. How can I obtain the sum of values of the keys greater than or equal to 3 but less than or equal to 4? Ideally, the obtained result would be [6, 10], but [6, 7, 8, 9, 10] would work too.

Original approach (worth abandoning?):
My original approach was to use define a function that counts the indices from the first element of a list until the first element of the range of interest, and then to continue counting until the last element in the range of interest; the function would take the the boundary elements of the range of interest as inputs using start += data_list.count(index) for index in range(1, boundary_1) and end += data_list.count(index) for index in range(boundary_1, boundary_2+1), but I could not get the function to work correctly.

Body:
def choose_slice(start, end, xs):
    # subfunction called by get_slice() -- defined below
    go, stop = 0, 0
    cx = sorted(Counter(xs).items()) # sort to count consecutively
    for val, key in cx:
        if val < start:
            go += key # match index at boundary of region of interest
            # print("count = %d" %key, "value = %.2f" %val)
        elif val >= start and val <= end:
            stop += key # inbetweeen the boundaries, in the region of interest
            # print("count = %d" %key, "value = %.2f" %val)
        elif val > end: # match index at boundary of region of interest
            break
    stop = go + stop
    return go, stop

def get_slice(start, end, xs=xs, ys=ys, zs=zs):
    go, stop = choose_slice(start, end, xs) # get indices
    return xs[go:stop], ys[go:stop], zs[go:stop] # get values at indices

xx, yy, zz = get_slice(3, 4)
print(xx)
>> [3.0, 3.0, 3.0, 3.0, 4.0]

This works for my dataset of size ~10^4. But I'm still curious about other approaches to this.


问:
StoryBoard Assistant Editor stopped showing associated file
Xcode storyboard assistant editor stopped showing related files.
"Automatic" is selected and "Class" is filled in Identity Inspector.

It was working before, but know it has stopped.
"Auto" or "CounterPart" modes are still woking for other files except StoryBoard.

A few days ago, I tried to update from Xcode 5 to 6, but later on gave up.
Would that have something to do with it?

答:
For Xcode 8+ versions

Check at top process indicator that if Xcode is "indexing" files... if yes, then, please wait until it finishes. Once it get finished. Your file will automatically appear as counterpart in Automatic section.

If Xcode is not showing "indexing" in process bar, then perform as @Anna Chiara's Answer


问:
How can I set the sampling rate in a Movesense device?
I can subscribe to the acceleration or angular velocity values with the movesense mobile libraries, but is there a way to change the sampling rate of the sensor?</p>

答:
The new movesense-device-lib (released today) has the new sensor API's that make it possible. The API's provide convenient and generic way to access all the "fast" sensors: Accelerometer, Gyroscope and Magnetic field. The paths have also been changed to make them less verbose (saves flash memory).

Here's a small intro on how the new API's work:

For each sensor there is a resource under root /Meas. /Meas/Acc, /Meas/Gyro and /Meas/Magn and they all work the same way.

Under the sensors root there is an Info resource that returns available sample rates as well as ranges. This is the result from GET'ing the /Meas/Acc/Info:

```<code>{
"SampleRates" : [13,26,52,104,208],
"Ranges" : [2,4,8,16]
}
</code>```

Also under the sensors root there is a Config resource when one can GET & PUT the sensors global settings. At the moment the only setting in Accelerometer is GRange.

The data can be only SUBSCRIBED (no more GET in API), and the sample rate wanted is set as URL parameter: /Meas/Acc/{SampleRate} where the {SampleRate} is one of the values from the Info resource.

The sbuscribed data is returned in the object of the form: {timestamp, array of FloatVector3D's}. Different sample rates can return different number of measurements per notification in the array.

Word of caution: We have tested the accelerometer upto 208 Hz (as of today) so even if the API advertises higher rates, we have not yet tested how far we can push the sensor in practice.

Full Disclosure: I work for Movesense team

Body:
The new movesense-device-lib (released today) has the new sensor API's that make it possible. The API's provide convenient and generic way to access all the "fast" sensors: Accelerometer, Gyroscope and Magnetic field. The paths have also been changed to make them less verbose (saves flash memory).

Here's a small intro on how the new API's work:

For each sensor there is a resource under root /Meas. /Meas/Acc, /Meas/Gyro and /Meas/Magn and they all work the same way.

Under the sensors root there is an Info resource that returns available sample rates as well as ranges. This is the result from GET'ing the /Meas/Acc/Info:

{
"SampleRates" : [13,26,52,104,208],
"Ranges" : [2,4,8,16]
}

Also under the sensors root there is a Config resource when one can GET & PUT the sensors global settings. At the moment the only setting in Accelerometer is GRange.

The data can be only SUBSCRIBED (no more GET in API), and the sample rate wanted is set as URL parameter: /Meas/Acc/{SampleRate} where the {SampleRate} is one of the values from the Info resource.

The sbuscribed data is returned in the object of the form: {timestamp, array of FloatVector3D's}. Different sample rates can return different number of measurements per notification in the array.

Word of caution: We have tested the accelerometer upto 208 Hz (as of today) so even if the API advertises higher rates, we have not yet tested how far we can push the sensor in practice.

Full Disclosure: I work for Movesense team


问:
Replace occurrences globally one by one in SublimeText3
Let's say we want to replace "apple" to "banana" in every file in the current project. We can do this with Cmd+Shift+F (Find in Files...) and "Replace" button. But this button replaces all simultaneously. What I want to do is replacing one by one. I know this can be done in a single file with Alt+Cmd+F and "Replace" button.

Is there any ways to do in SublimeText3?

Thank you

答:
You can't replace across multiple files in the same way as you can replace in a single file.

The closest you can get is to use Find in Files, make sure Use Buffer is toggled on, and then use Find to perform the search, a Find Results buffer will open. Now you can use F4 to jump straight to the next results line (Shift+F4 to the previous), but you need to manually move the cursor to the relevant section(s) of the line and make the alterations manually.

When performing replacements across files, if it's not a simple case of replacing all of some text with some other text, I have found it best to use a regex to make sure that only the matches I want changed will get changed. Occasionally, if creating a complex regex, I will end up testing the regex using Find to be certain of what it matches, before then running the same regex with replace.


问:
Neo4J Multi Tenancy and Role Based Access to Nodes
I am trying to define a user management and permissions model for Neo4j. I have a web application (Angular 2) that connects to Neo4j via an API (KOANEO4J). Neo4j is the only database or persistent storage that the application uses. Through the application a user can add/edit/delete content which uses the API to carry out these instructions in Neo4j by running Cypher Statements. Up to now I have not worried about supporting multiple users but as a next step I am starting to think about this.

The product will be used by multiple different companies and each company will have multiple users so I need some way to support this. The model I am considering in Neo4J is as follows:

An "Orgaization" is represented by a node and it can have 1 or more "Organization Catalogs". All of the nodes belonging to that catalog will be children of one of the "Organization Catalogs".

Each user will also be represented by a node in the database. They will belong to an Organisation. They will have certain access permissions on an Organization Catalog identified by a an edge.

I am looking for some advice on whether or not this is an appropriate model to follow or if there are any examples or documents that describe how to achieve this in Neo4j.

If I do implement this model then would it be better to model the permissions as seperate nodes so a user is connected to a permission  node (e.g. Read Only Access) that is then connected to the Organization Catalog.

Any suggestions on how I would actually get the API to work with this type of model. I'm sure I can pass the User Id to Neo4j as part of each query and then filter the results to show only nodes the user has access to but this doesn't seem like a very elegant solution - it also means that all of the security would be dependant on carefully written Cypher queries that don't leak data that a user isnt supposed to access.

Thanks a lot

答:
I am looking for some advice on whether or not this is an appropriate
  model to follow or if there are any examples or documents that
  describe how to achieve this in Neo4j.

The answer for this question is: it depends. Remember that when modelling a graph database you should consider the queries that are asked to the database. If this model fits the queries that you are asking to the database then this model is appropriated, otherwise, not. Take a look in the Chapter 5 (Graphs in the Real World) of the book Graph Databases (by Ian Robison, Jim Webber and Emil Eifrem. Available for download here). This chapter shows the modelling process of an Authorization and Access Control system in Neo4j. Can be enlightening and helpful to you.

If I do implement this model then would it be better to model the
  permissions as seperate nodes so a user is connected to a permission
  node (e.g. Read Only Access) that is then connected to the
  Organization Catalog.

Again, it depends. Do it if the Permission entity has connection to others entities of your application besides an User and an Organization Catalog. Otherwise I believe that your permission can be modeled as a relationship between an user and an organization catalog.

Any suggestions on how I would actually get the API to work with this
  type of model. I'm sure I can pass the User Id to Neo4j as part of
  each query and then filter the results to show only nodes the user has
  access to but this doesn't seem like a very elegant solution - it also
  means that all of the security would be dependant on carefully written
  Cypher queries that don't leak data that a user isnt supposed to
  access.

Maybe is a good idea add another layer of software between your AngularJS client app and the Neo4j database. This way in this new layer of software (a Node.js application, for example) you can implement a access control system, then verifiy if the authenticated user can access the resource that is being requested.


问:
Scala structured data extraction via regex and pattern matching
Given structured data in a string format how do I extract parts of the data effectively using pattern matching and regular expressions?

Example:

```<code>val input = Seq("name-12345","inval1d-12345","invalid-12here123","hello-54321","inval1d-1aa2")

case class Client(name:Option[String],clientID:Option[Int])

def parseClient(input:String):Option[Client] = {
  val clientRegex = """([a-zA-Z]+)-([0-9]+)""".r
  Option(input).flatMap(in => {
    in match {
      case clientRegex(name,clientID) => Some(Client(Some(name),Some(clientID.toInt)))
      case _ => None
    }
  })
}

input.map(parseClient)
</code>```

The issue with this however is that if I fail to validate a single part of the structured data then I parse None of it.

How could I use regular expressions to define in a hierarchical manor such as:

```<code>val nameRegex = """([a-zA-Z]+)""".r
val clientIDRegex = """([0-9]+)""".r
</code>```

Then match these combined within a pattern?

The output from the example:

```<code>Seq(
 Some(Client(Some("name"),Some(12345)))
 ,None
 ,None
 ,Some(Client(Some("hello"),Some(54321)))
 ,None
)
</code>```

The required output:

```<code>Seq(
 Some(Client(Some("name"),Some(12345)))
 ,Some(Client(None,Some(12345)))
 ,Some(Client(Some("invalid"),None))
 ,Some(Client(Some("hello"),Some(54321)))
 ,None
)
</code>```

答:
You are probably looking for something like applicative you can chain.
you can do something like this using the Validated type from cats:

```<code>val houseNumber = parseClient("house_number").andThen{ n =>
   if (isValid(n)) Validated.valid(n)
   else Validated.invalid(ParseError("house_number"))
}
</code>```

and
I would opt to using to atto:
it has the ParseResult type the keeps all the information on parsing the string.

Body:
Given structured data in a string format how do I extract parts of the data effectively using pattern matching and regular expressions?

Example:

val input = Seq("name-12345","inval1d-12345","invalid-12here123","hello-54321","inval1d-1aa2")

case class Client(name:Option[String],clientID:Option[Int])

def parseClient(input:String):Option[Client] = {
  val clientRegex = """([a-zA-Z]+)-([0-9]+)""".r
  Option(input).flatMap(in => {
    in match {
      case clientRegex(name,clientID) => Some(Client(Some(name),Some(clientID.toInt)))
      case _ => None
    }
  })
}

input.map(parseClient)

The issue with this however is that if I fail to validate a single part of the structured data then I parse None of it.

How could I use regular expressions to define in a hierarchical manor such as:

val nameRegex = """([a-zA-Z]+)""".r
val clientIDRegex = """([0-9]+)""".r

Then match these combined within a pattern?

The output from the example:

Seq(
 Some(Client(Some("name"),Some(12345)))
 ,None
 ,None
 ,Some(Client(Some("hello"),Some(54321)))
 ,None
)

The required output:

Seq(
 Some(Client(Some("name"),Some(12345)))
 ,Some(Client(None,Some(12345)))
 ,Some(Client(Some("invalid"),None))
 ,Some(Client(Some("hello"),Some(54321)))
 ,None
)

Body:
You are probably looking for something like applicative you can chain.
you can do something like this using the Validated type from cats:

val houseNumber = parseClient("house_number").andThen{ n =>
   if (isValid(n)) Validated.valid(n)
   else Validated.invalid(ParseError("house_number"))
}

and
I would opt to using to atto:
it has the ParseResult type the keeps all the information on parsing the string.


问:
When to use an object or an array in javascript?
I just found out that Arrays inherit directly from Object in javascript.  I'm finding the difference between an array and an object is fairly minuscule.

How do i know when to use one over the other?

答: You often use arrays when you have a series of related items that you want ordered and indexed.</p>


问:
ScrollView does not come back to the beginning of layout - Android
How do I make a ScrollView always come back to the beginning? I have a ScrollView, and inside it a LinearLayout (vertical) with a TextView and a Button called "next". This button changes the TextView text, however the text is not shown at the beginning, but always of where it was visible on screen when the button was clicked. The user then has to scroll to see the beginning of the text.

Is there a way to make the ScrollView go back to the begging when the button is clicked?

Thank you

答: Just call scrollTo(0,0) on your Scrollview.


问:
How to print multiple icons in Uikit?
Here is a code which i am using to print multiple icons using a loop which may not be a conventional method when you are using the UIkit but it is not printing the icon 10 times.

Fiddle

```<code>var ic = document.createElement('a');

ic.setAttribute("uk-icon","icon:heart");

var main = document.getElementById("lol");

for(var i = 0; i < 10; ++i){

      main.appendChild(ic);
}
</code>```

References/Documentation:
UiKit icons

Uikit Javascript Documentation

答:
is this you wanted ???
fiddle: https://jsfiddle.net/pnfh3v4m/</p>

```<code>var main = document.getElementById("lol");
for(var i = 0; i < 10; i++){
        var ic = document.createElement('a');
        ic.setAttribute("uk-icon","icon:heart");
        main.appendChild(ic);

}
</code>```

Title: How to print multiple icons in Uikit?

Body:
Here is a code which i am using to print multiple icons using a loop which may not be a conventional method when you are using the UIkit but it is not printing the icon 10 times.

Fiddle

var ic = document.createElement('a');

ic.setAttribute("uk-icon","icon:heart");

var main = document.getElementById("lol");

for(var i = 0; i < 10; ++i){

      main.appendChild(ic);
}

References/Documentation:
UiKit icons

Uikit Javascript Documentation

Body:
is this you wanted ???
fiddle: https://jsfiddle.net/pnfh3v4m/

var main = document.getElementById("lol");
for(var i = 0; i < 10; i++){
        var ic = document.createElement('a');
        ic.setAttribute("uk-icon","icon:heart");
        main.appendChild(ic);

}