问:
TweetView cause ANR when first appear on screen
I use 3.0.0 version of Android Twitter SDK, init with:

```<code>        TwitterConfig config = new TwitterConfig.Builder(this)
                .twitterAuthConfig(new TwitterAuthConfig(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET))
                .logger(new DefaultLogger(Log.INFO))
                .debug(false)
                .build();
        Twitter.initialize(config);
</code>```

and simple create with:

```<code>    CompactTweetView tweetView = new CompactTweetView(activity, getTweetJsonData());
    tweetView.setTweetActionsEnabled(true);
</code>```

in RecyclerView, and after i going to this screen with CompactTweetView i got ANR problem around 15-20 secs. Only for first time in app instance, secondary and other items shows instantly. If i close and open screen again items also show instantly.

答:
The problem was been in sdk-init:

```<code>Twitter.initialize(config);
</code>```

That i call in NOT ui-thread (i call it in AsyncTask), after i change to Application.onCreate() method, problem has been solved

Body:
I use 3.0.0 version of Android Twitter SDK, init with:

        TwitterConfig config = new TwitterConfig.Builder(this)
                .twitterAuthConfig(new TwitterAuthConfig(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET))
                .logger(new DefaultLogger(Log.INFO))
                .debug(false)
                .build();
        Twitter.initialize(config);

and simple create with:

    CompactTweetView tweetView = new CompactTweetView(activity, getTweetJsonData());
    tweetView.setTweetActionsEnabled(true);

in RecyclerView, and after i going to this screen with CompactTweetView i got ANR problem around 15-20 secs. Only for first time in app instance, secondary and other items shows instantly. If i close and open screen again items also show instantly.

Body:
The problem was been in sdk-init:

Twitter.initialize(config);

That i call in NOT ui-thread (i call it in AsyncTask), after i change to Application.onCreate() method, problem has been solved


来源: stackexchange

问:
PHP Warning: Unknown: It is not safe to rely on the system's timezone settings
I am getting following error whien i use php -i

date

date/time support => enabled "Olson" Timezone Database Version =>
  0.system Timezone Database => internal PHP Warning:  Unknown: It is not safe to rely on the system's timezone settings.

  You are required to use the date.timezone setting or the
  date_default_timezon

  e_set() function. In case you used any of those methods and you are
  still gettin

  g this warning, you most likely misspelled the timezone identifier. We
  selected

  'UTC' for 'UTC/0.0/no DST' instead in Unknown on line 0 Default
  timezone => UTC

Directive => Local Value => Master Value date.default_latitude =>
  31.7667 => 31.7667 date.default_longitude => 35.2333 => 35.2333 date.sunrise_zenith => 90.583333 => 90.583333 date.sunset_zenith =>
  90.583333 => 90.583333 date.timezone => America/Los_Angeles => America/Los_Angeles

My /etc/php.ini has following setting

```<code>[Date]
; Defines the default timezone used by the date functions
; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
date.timezone = America/Los_Angeles

; http://www.php.net/manual/en/datetime.configuration.php#ini.date.default-latitude
;date.default_latitude = 31.7667

; http://www.php.net/manual/en/datetime.configuration.php#ini.date.default-longitude
;date.default_longitude = 35.2333

; http://www.php.net/manual/en/datetime.configuration.php#ini.date.sunrise-zenith
;date.sunrise_zenith = 90.583333

; http://www.php.net/manual/en/datetime.configuration.php#ini.date.sunset-zenith
;date.sunset_zenith = 90.583333
</code>```

PHP version details are as below

PHP 5.3.3 (cli) (built: Dec  5 2013 07:09:40) Copyright (c) 1997-2010
  The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend
  Technologies

Apache version as below

Server version: Apache/2.2.15 (Unix) Server built:   Jul 18 2014
  02:31:29

I have restarted Apache multiple times

答:
You could use inside of PHP file:

```<code>date_default_timezone_set( "YOUR DATE TIME ZONE");
</code>```

for example:

```<code>date_default_timezone_set( "Europe/Berlin");
</code>```

List of timezones: http://php.net/manual/en/timezones.php

or if you wish to continue using server timezone but want to hide warnings use:

```<code>ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ERROR);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am getting following error whien i use php -i

date

date/time support => enabled "Olson" Timezone Database Version =>
  0.system Timezone Database => internal PHP Warning:  Unknown: It is not safe to rely on the system's timezone settings.

  You are required to use the date.timezone setting or the
  date_default_timezon

  e_set() function. In case you used any of those methods and you are
  still gettin

  g this warning, you most likely misspelled the timezone identifier. We
  selected

  'UTC' for 'UTC/0.0/no DST' instead in Unknown on line 0 Default
  timezone => UTC

Directive => Local Value => Master Value date.default_latitude =>
  31.7667 => 31.7667 date.default_longitude => 35.2333 => 35.2333 date.sunrise_zenith => 90.583333 => 90.583333 date.sunset_zenith =>
  90.583333 => 90.583333 date.timezone => America/Los_Angeles => America/Los_Angeles

My /etc/php.ini has following setting

[Date]
; Defines the default timezone used by the date functions
; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
date.timezone = America/Los_Angeles

; http://www.php.net/manual/en/datetime.configuration.php#ini.date.default-latitude
;date.default_latitude = 31.7667

; http://www.php.net/manual/en/datetime.configuration.php#ini.date.default-longitude
;date.default_longitude = 35.2333

; http://www.php.net/manual/en/datetime.configuration.php#ini.date.sunrise-zenith
;date.sunrise_zenith = 90.583333

; http://www.php.net/manual/en/datetime.configuration.php#ini.date.sunset-zenith
;date.sunset_zenith = 90.583333

PHP version details are as below

PHP 5.3.3 (cli) (built: Dec  5 2013 07:09:40) Copyright (c) 1997-2010
  The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend
  Technologies

Apache version as below

Server version: Apache/2.2.15 (Unix) Server built:   Jul 18 2014
  02:31:29

I have restarted Apache multiple times

Body:
You could use inside of PHP file:

date_default_timezone_set( "YOUR DATE TIME ZONE");

for example:

date_default_timezone_set( "Europe/Berlin");

List of timezones: http://php.net/manual/en/timezones.php

or if you wish to continue using server timezone but want to hide warnings use:

ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ERROR);


问:
boost multiindex: lower_bound with value_type as argument
I'd like to use lower_bound with the value_type of a Boost MultiIndex Container. So far, I only managed to make this work by explicitly extracting the members:

```<code>#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/member.hpp>
#include <string>

struct name {
    std::string firstname;
    std::string lastname;
    name(const std::string & firstname, const std::string & lastname) :
        firstname(firstname), lastname(lastname) {}
};

typedef boost::multi_index::multi_index_container<
    name,
    boost::multi_index::indexed_by<
        boost::multi_index::ordered_unique<
            boost::multi_index::composite_key<
                name,
                boost::multi_index::member<name, std::string, &name::lastname>,
                boost::multi_index::member<name, std::string, &name::firstname>
            >,
            boost::multi_index::composite_key_compare<
                std::less<std::string>,
                std::less<std::string>
            >
        >
    >
> NameIndex;

int main(void) {
    NameIndex nameindex;
    nameindex.insert(name("Alfred", "Ammer"));
    nameindex.insert(name("Martin", "Mauser"));
    // In my real code, I get this object passed.
    name lookupname("Hans", "Hoffer");

    // Does not compile
    //auto it = nameindex.get<0>().lower_bound(lookupname);

    // compiles, but I have to take explicitly list the members - in the right order
    auto it = nameindex.get<0>().lower_bound(std::make_tuple(lookupname.lastname, lookupname.firstname));
}
</code>```

How can I avoid extracting the members?

答:
Try the following:

Live On Coliru

```<code>#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/member.hpp>
#include <string>

struct name {
    std::string firstname;
    std::string lastname;
    name(const std::string & firstname, const std::string & lastname) :
        firstname(firstname), lastname(lastname) {}
};

struct name_compare:
    boost::multi_index::composite_key_compare<
        std::less<std::string>,
        std::less<std::string>
    >
{
    using base=boost::multi_index::composite_key_compare<
        std::less<std::string>,
        std::less<std::string>
    >;

    using base::operator();

    template<typename T>
    bool operator()(const T& x,const name& y)const
    {
      return base::operator()(
          x,
          std::make_tuple(std::ref(y.firstname),std::ref(y.lastname)));
    }

    template<typename T>
    bool operator()(const name& x,const T& y)const
    {
      return base::operator()(
          std::make_tuple(std::ref(x.firstname),std::ref(x.lastname)),
          y);
    }
};

typedef boost::multi_index::multi_index_container<
    name,
    boost::multi_index::indexed_by<
        boost::multi_index::ordered_unique<
            boost::multi_index::composite_key<
                name,
                boost::multi_index::member<name, std::string, &name::lastname>,
                boost::multi_index::member<name, std::string, &name::firstname>
            >,
            name_compare
        >
    >
> NameIndex;

int main(void) {
    NameIndex nameindex;
    nameindex.insert(name("Alfred", "Ammer"));
    nameindex.insert(name("Martin", "Mauser"));
    // In my real code, I get this object passed.
    name lookupname("Hans", "Hoffer");

    auto it = nameindex.get<0>().lower_bound(lookupname);

    // this also works, as before

    it = nameindex.get<0>().lower_bound(std::make_tuple(lookupname.lastname, lookupname.firstname));
}
</code>```

Body:
I'd like to use lower_bound with the value_type of a Boost MultiIndex Container. So far, I only managed to make this work by explicitly extracting the members:

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/member.hpp>
#include <string>

struct name {
    std::string firstname;
    std::string lastname;
    name(const std::string & firstname, const std::string & lastname) :
        firstname(firstname), lastname(lastname) {}
};

typedef boost::multi_index::multi_index_container<
    name,
    boost::multi_index::indexed_by<
        boost::multi_index::ordered_unique<
            boost::multi_index::composite_key<
                name,
                boost::multi_index::member<name, std::string, &name::lastname>,
                boost::multi_index::member<name, std::string, &name::firstname>
            >,
            boost::multi_index::composite_key_compare<
                std::less<std::string>,
                std::less<std::string>
            >
        >
    >
> NameIndex;

int main(void) {
    NameIndex nameindex;
    nameindex.insert(name("Alfred", "Ammer"));
    nameindex.insert(name("Martin", "Mauser"));
    // In my real code, I get this object passed.
    name lookupname("Hans", "Hoffer");

    // Does not compile
    //auto it = nameindex.get<0>().lower_bound(lookupname);

    // compiles, but I have to take explicitly list the members - in the right order
    auto it = nameindex.get<0>().lower_bound(std::make_tuple(lookupname.lastname, lookupname.firstname));
}

How can I avoid extracting the members?

Body:
Try the following:

Live On Coliru

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/member.hpp>
#include <string>

struct name {
    std::string firstname;
    std::string lastname;
    name(const std::string & firstname, const std::string & lastname) :
        firstname(firstname), lastname(lastname) {}
};

struct name_compare:
    boost::multi_index::composite_key_compare<
        std::less<std::string>,
        std::less<std::string>
    >
{
    using base=boost::multi_index::composite_key_compare<
        std::less<std::string>,
        std::less<std::string>
    >;

    using base::operator();

    template<typename T>
    bool operator()(const T& x,const name& y)const
    {
      return base::operator()(
          x,
          std::make_tuple(std::ref(y.firstname),std::ref(y.lastname)));
    }

    template<typename T>
    bool operator()(const name& x,const T& y)const
    {
      return base::operator()(
          std::make_tuple(std::ref(x.firstname),std::ref(x.lastname)),
          y);
    }
};

typedef boost::multi_index::multi_index_container<
    name,
    boost::multi_index::indexed_by<
        boost::multi_index::ordered_unique<
            boost::multi_index::composite_key<
                name,
                boost::multi_index::member<name, std::string, &name::lastname>,
                boost::multi_index::member<name, std::string, &name::firstname>
            >,
            name_compare
        >
    >
> NameIndex;

int main(void) {
    NameIndex nameindex;
    nameindex.insert(name("Alfred", "Ammer"));
    nameindex.insert(name("Martin", "Mauser"));
    // In my real code, I get this object passed.
    name lookupname("Hans", "Hoffer");

    auto it = nameindex.get<0>().lower_bound(lookupname);

    // this also works, as before

    it = nameindex.get<0>().lower_bound(std::make_tuple(lookupname.lastname, lookupname.firstname));
}


问:
Multiple child components in parent component have the same instance angular2
I have a child component file-upload which i use in parent component multiple times like below

```<code><form>
<fieldset>
    <legend>Input Files</legend>

    <file-upload id="s" imgpath="Image/saham.png" title="saham"></file-upload>
    <file-upload id="q" imgpath="Image/sandoq.png" title="sandoq"></file-upload>
    <file-upload id="o" imgpath="Image/oraq.png" title="oraq"></file-upload>

    <button type="submit" class="btn btn-success" (click)="save()" [disabled]="!cansave">Save</button>
</fieldset>
</code>```

in UI everything is fine, but in action it seems that there is only one object instance of file-upload which  is working and every input changes in each of file-upload components applies only to one of them(the first one).

the problem is for input and the way I am using it..when i use a simple button, every thing is fine. here is the html of file-upload

```<code>    <div class="upload" (dragover)="allowDrop($event)" (drop)="drop($event)">
    <p>{{title}}</p>
    <div class="drop-zone" [ngClass]="{'showdropzone' : showdropzone}">
        Drop Here Or...
        <div class="clickhere">
            <label for="files">Click Here</label>
            <input id="files" type="file" class="file" (change)="fileSelect($event)"><!--does not work-->
            <button (click)="fileSelect($event)">Click Me</button> <!--this is working-->
        </div>
    </div>
    <circle-progress class="myprogress" #circleProg1 [percent]="50" [ngClass]="{'showprogress' : showprogress}"></circle-progress>
    <span class="glyphicon glyphicon-warning-sign status"  [ngClass]="{'warninput' : haswarning}"></span>
    <span class="glyphicon glyphicon-ok-circle status"     [ngClass]="{'successinput' : succeeded}"></span>
</div>
</code>```

答:
You have a singleton FileService that's why they all have the same instance of that service. I am assuming you inject your provider in your AppModule, so remove it and try to inject your service at the component level like this

```<code>@Component){
  providers: [FileService]
  ...
}
export class FileUploadComponent
</code>```

For more information about multiple service instances, take a look at this from official docs.
Hope this helps

Body:
I have a child component file-upload which i use in parent component multiple times like below

<form>
<fieldset>
    <legend>Input Files</legend>

    <file-upload id="s" imgpath="Image/saham.png" title="saham"></file-upload>
    <file-upload id="q" imgpath="Image/sandoq.png" title="sandoq"></file-upload>
    <file-upload id="o" imgpath="Image/oraq.png" title="oraq"></file-upload>

    <button type="submit" class="btn btn-success" (click)="save()" [disabled]="!cansave">Save</button>
</fieldset>

in UI everything is fine, but in action it seems that there is only one object instance of file-upload which  is working and every input changes in each of file-upload components applies only to one of them(the first one).

the problem is for input and the way I am using it..when i use a simple button, every thing is fine. here is the html of file-upload

{{title}}

        Drop Here Or...

            Click Here
            <input id="files" type="file" class="file" (change)="fileSelect($event)">
            <button (click)="fileSelect($event)">Click Me</button>

    <circle-progress class="myprogress" #circleProg1 [percent]="50" [ngClass]="{'showprogress' : showprogress}"></circle-progress>

Body:
You have a singleton FileService that's why they all have the same instance of that service. I am assuming you inject your provider in your AppModule, so remove it and try to inject your service at the component level like this

@Component){
  providers: [FileService]
  ...
}
export class FileUploadComponent

For more information about multiple service instances, take a look at this from official docs.
Hope this helps


问:
How to send datagrams through a unix socket from PHP?
I'm doing:

```<code>$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
if (@socket_connect($socket, $path) === false) { ... }
</code>```

But I get this error:

```<code>(91): Protocol wrong type for socket
</code>```

Am I using any of the parameters wrong? I suspect from the second socket_create parameter. I could't find any help in the documentation: http://php.net/manual/es/function.socket-create.php

答: Have you tried using getprotobyname() for the 3rd (protocol) parameter?

ContentLicense: CC BY-SA 2.5

Body:
I'm doing:

$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
if (@socket_connect($socket, $path) === false) { ... }

But I get this error:

(91): Protocol wrong type for socket

Am I using any of the parameters wrong? I suspect from the second socket_create parameter. I could't find any help in the documentation: http://php.net/manual/es/function.socket-create.php


问:
What consumes memory in linux
I use atop cmd to check memory usage.
on the screenshot use can I see I have 1gb total, and 300mb free.
how do I found out what consumes other ~700mb?
I tried to use atop cmd, but that doesn't give me much information.

答: I think glances utility is better suited for this purpose. It is more user friendly and provides various options for real time server stats. For more information about the utility, see this page.</p>

Title: What consumes memory in linux


问:
Why does spread syntax convert my string into an array?
Why does spread syntax convert my string into an array?

```<code>var v = 'hello';
var [, ...w] = v; // ["e", "l", "l", "o"]
</code>```

Why is w not a string?

答:
Spread syntax can be applied only to iterable objects. Since String is iterable Spread operator works fine and splits your char array(String) in to char's.

You can check that with below sample which demonstrate that String is iterable by default.

```<code>var s = 'test';
for (k in s) {
  console.log(k);
}
</code>```

And ECMAScript6 specification even mentioned about this specific String case.

Spread Operator

Spreading of elements of an iterable collection (like an array or even a string) into both literal elements and individual function parameters.

http://es6-features.org/#SpreadOperator

```<code>var str = "foo";
var chars = [ ...str ]; // [ "f", "o", "o" ]
</code>```

And it is worth mentioning that this is a specific case and only happens when you use a direct String with spread operator. When you give a single String inside an array, the whole array will be treated as the iterable object and not the string inside.

```<code>var str = [ "hello" ,2 ];
var other = [  ...str ]; // [  "hello" ,2 ]
</code>```

I know the above example doesn't make much sense, but just to convey the fact that the String will be treated differently in this case.

Body:
Why does spread syntax convert my string into an array?

var v = 'hello';
var [, ...w] = v; // ["e", "l", "l", "o"]

Why is w not a string?

Body:
Spread syntax can be applied only to iterable objects. Since String is iterable Spread operator works fine and splits your char array(String) in to char's.

You can check that with below sample which demonstrate that String is iterable by default.

var s = 'test';
for (k in s) {
  console.log(k);
}

And ECMAScript6 specification even mentioned about this specific String case.

Spread Operator

Spreading of elements of an iterable collection (like an array or even a string) into both literal elements and individual function parameters.

http://es6-features.org/#SpreadOperator

var str = "foo";
var chars = [ ...str ]; // [ "f", "o", "o" ]

And it is worth mentioning that this is a specific case and only happens when you use a direct String with spread operator. When you give a single String inside an array, the whole array will be treated as the iterable object and not the string inside.

var str = [ "hello" ,2 ];
var other = [  ...str ]; // [  "hello" ,2 ]

I know the above example doesn't make much sense, but just to convey the fact that the String will be treated differently in this case.


问:
SharePoint 2013 people picker retrieves user's old information
I have imported users from AD and keep syncing them for a while. Today two of users' display names have been changed on AD and SharePoint synced them correctly. Just to be sure, I checked users from User Profile Service App which looks OK. New names are appearing correctly.

Yet when I try to add a list item and select user from people picker, I get old user info. This also happens when I try to insert a list item programmatically.

Tried to delete users from SharePoint, however I still get same old users. Do you have any idea for solving this situation?

Thanks in advance.

答:
This is may be because entry in SharePoint's hidden user-list - User Information List.

Browse to this list - http://{SiteCollectionURL}/_catalogs/users/detail.aspx

Check for the display name of the users you have updated. If you see old user name instead of new/updated, delete these users from this list.

After this ask user to login to the same site again.


问:
android different langues for single textview
How can I display multiple languages for single textview without changing system language?

here donor search is single textview with english and marathi languages at a time.

how to do this??

答:
This is how we do you can see the output

code

output

<string name="doner">Please search donor through code or name \n   (कोड किंवा नावाने दात्याला शोधा)</string>

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="@string/doner"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="18sp" />
</LinearLayout>```

doner">Please search donor through code or name \n   (कोड किंवा नावाने दात्याला शोधा)

Body:
This is how we do you can see the output

code

output

<string name="doner">Please search donor through code or name \n   (कोड किंवा नावाने दात्याला शोधा)</string>

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="@string/doner"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="18sp" />
</LinearLayout>

doner">Please search donor through code or name \n   (कोड किंवा नावाने दात्याला शोधा)


问:
How to make a button not show up but still be used by javascript?
I am using a button that has to be invible and should be used by a javascript function.

```<code><asp:Button ID ="btnDummy1" runat="server" Visible ="true" OnClick="btnSubmit1_Click" width="0px" height="0px"/
</code>```

I cannot keep visible = false as it the javascript will not use invible content in the poage. I havetried to give width=0 and height=0, still it showws up in Chrome. What do you guys think i should do?

Thanks in advance :)

答:
If you set it to Visible="False" then the code will not be executed.

Instead I think you should wrap it in a
 and set display:none via css:

```<code><div style="display: none;">
   <asp:Button ID ="btnDummy1" runat="server" OnClick="btnSubmit1_Click" />
</div>
</code>```

Body:
I am using a button that has to be invible and should be used by a javascript function.

<asp:Button ID ="btnDummy1" runat="server" Visible ="true" OnClick="btnSubmit1_Click" width="0px" height="0px"/

I cannot keep visible = false as it the javascript will not use invible content in the poage. I havetried to give width=0 and height=0, still it showws up in Chrome. What do you guys think i should do?

Thanks in advance :)

Body:
If you set it to Visible="False" then the code will not be executed.

Instead I think you should wrap it in a <div> and set display:none via css:

<div style="display: none;">
   <asp:Button ID ="btnDummy1" runat="server" OnClick="btnSubmit1_Click" />
</div>

ContentLicense: CC BY-SA 4.0


问:
Scala: default return type of Option.getOrElse(...)
The signature of the function getOrElse(...) of Scala's Option[+A] class is

```<code> final def getOrElse[B >: A](default: ⇒ B): B
</code>```

If I use the example

```<code>val o1 = Option("Hi")
val o2: Option[String] = Option(null)

println(o1.getOrElse(() => "Else"))
println(o2.getOrElse(() => "Else"))
</code>```

I get the output

```<code>Hi
<function0>
</code>```

The Scala API says about getOrElse(...):

Returns the option's value if the option is nonempty, otherwise return the result of evaluating default.

But () => "Else") is not evaluated.
The result cannot be evaluated by using brackets:

```<code>o2.getOrElse(() => "Else")()

error: Object does not take parameters
   o2.getOrElse( () => "Else")()
                              ^
</code>```

How can I evaluate the result and why it is not evaluated automatically?

Is default: ⇒ B the same as default: () ⇒ B ?

答:
Consider this:

val e: Function0[String] = () => "Else"
```

<p>Then you can write:</p>

<pre class="lang-scala prettyprint-override"><code>println(o1.getOrElse(e)) //Hi
println(o2.getOrElse(e)) //<function0>
println(o2.getOrElse(e())) //Else
println(o2.getOrElse((() => "Else")())) //Else
</code>```

Body:
The signature of the function getOrElse(...) of Scala's Option[+A] class is

 final def getOrElse[B >: A](default: ⇒ B): B

If I use the example

val o1 = Option("Hi")
val o2: Option[String] = Option(null)

println(o1.getOrElse(() => "Else"))
println(o2.getOrElse(() => "Else"))

I get the output

Hi
<function0>

The Scala API says about getOrElse(...):

Returns the option's value if the option is nonempty, otherwise return the result of evaluating default.

But () => "Else") is not evaluated.
The result cannot be evaluated by using brackets:

o2.getOrElse(() => "Else")()

error: Object does not take parameters
   o2.getOrElse( () => "Else")()
                              ^

How can I evaluate the result and why it is not evaluated automatically?

Is default: ⇒ B the same as default: () ⇒ B ?

Body:
Consider this:

val e: Function0[String] = () => "Else"

Then you can write:

println(o1.getOrElse(e)) //Hi
println(o2.getOrElse(e)) //<function0>
println(o2.getOrElse(e())) //Else
println(o2.getOrElse((() => "Else")())) //Else


问:
Spring @AutoWired always null
I'm trying to call SOAP service from another system on my program. I've generated the java classes needed from WSDL by using wsimport command.

Here's my program's configuration

 web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>PTDAM Promo Engine</display-name>
    <description>Promo Engine using Elastic Search</description>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/cxf-servlet.xml</param-value>

    </context-param>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>promoengine</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <display-name>CXF Servlet</display-name>
        <servlet-class>
            org.apache.cxf.transport.servlet.CXFServlet
        </servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

and here's my xml configuration file where i store the config location

UPDATE: added ESCreditRunner class as a bean below, and still got the same error

cxf-servlet.xml

```<code>    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
           xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxws="http://cxf.apache.org/jaxws"
           xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:http="http://cxf.apache.org/transports/http/configuration"
           xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"

           xsi:schemaLocation="http://www.springframework.org/schema/beans
                      http://www.springframework.org/schema/beans/spring-beans.xsd
                      http://cxf.apache.org/transports/http/configuration
                      http://cxf.apache.org/schemas/configuration/http-conf.xsd
                  http://cxf.apache.org/configuration/security
                  http://cxf.apache.org/schemas/configuration/security.xsd
                  http://cxf.apache.org/jaxrs
                  http://cxf.apache.org/schemas/jaxrs.xsd
                  http://cxf.apache.org/core
                  http://cxf.apache.org/schemas/core.xsd
                  http://cxf.apache.org/jaxws
                  http://cxf.apache.org/schemas/jaxws.xsd
                  http://www.springframework.org/schema/context
                  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

         <!-- use this to enable @AutoWired -->
         <context:annotation-config />
         <context:component-scan base-package="ptdam.emoney.webservice.transactions" />

         <import resource="classpath:META-INF/cxf/cxf.xml" />
         <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
         <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

        <!-- Client -->
        <jaxws:client id="topupWebService"
            serviceClass="ptdam.emoney.webservice.transactions.TopupWebService"
            address="http://localhost:8080/ecash-core-engine-dev-mitigasi/services/emoneytopup"

<!-- Beans -->
    <bean id="esCreditRunner" class="com.ptdam.promo.services.ESCreditRunner" />
        />
    </beans>
</code>```

and here's how i use the @AutoWired, to call the SOAP service topupWebService.. on the testCall() method

ESCreditRunner.java

```<code>package ptdam.emoney.webservice.transactions;
public class ESCreditRunner {
        private File statusFile;
        private Properties status;
        private static final Logger logger = Logger.getLogger(ESCreditRunner.class);

        @Autowired
        private TopupWebService topupWebService;
        public void setTopupWebService(TopupWebService topupWebService) {
            this.topupWebService = topupWebService;
        }

        // testing 04/07/2017
        public void testCall(){
            topupWebService.echoTest("Luki");
        }
    }
</code>```

when i run the testCall() method, i always get NullPointerException on the topupWebService variable. It looks like it's not injected properly..

what i'm missing here?

Update:
i've made another thread as a continuation of this thread. Kindly check it here :) Spring WebService with Endpoint vs no Endpoint

答: I have solved using @Component on my class and setting @Autowired to all object called in cascade from the controller or check your package in settings like that spring mvc @Autowired error Unsatisfied 'required' dependency of type

Title: Spring @AutoWired always null

Body:
I'm trying to call SOAP service from another system on my program. I've generated the java classes needed from WSDL by using wsimport command.

Here's my program's configuration

 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>PTDAM Promo Engine</display-name>
    <description>Promo Engine using Elastic Search</description>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/cxf-servlet.xml</param-value>

    </context-param>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>promoengine</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <display-name>CXF Servlet</display-name>
        <servlet-class>
            org.apache.cxf.transport.servlet.CXFServlet
        </servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

and here's my xml configuration file where i store the config location

UPDATE: added ESCreditRunner class as a bean below, and still got the same error

cxf-servlet.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
           xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxws="http://cxf.apache.org/jaxws"
           xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:http="http://cxf.apache.org/transports/http/configuration"
           xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"

           xsi:schemaLocation="http://www.springframework.org/schema/beans
                      http://www.springframework.org/schema/beans/spring-beans.xsd
                      http://cxf.apache.org/transports/http/configuration
                      http://cxf.apache.org/schemas/configuration/http-conf.xsd
                  http://cxf.apache.org/configuration/security
                  http://cxf.apache.org/schemas/configuration/security.xsd
                  http://cxf.apache.org/jaxrs
                  http://cxf.apache.org/schemas/jaxrs.xsd
                  http://cxf.apache.org/core
                  http://cxf.apache.org/schemas/core.xsd
                  http://cxf.apache.org/jaxws
                  http://cxf.apache.org/schemas/jaxws.xsd
                  http://www.springframework.org/schema/context
                  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

         <context:annotation-config />
         <context:component-scan base-package="ptdam.emoney.webservice.transactions" />

         <import resource="classpath:META-INF/cxf/cxf.xml" />
         <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
         <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

        <jaxws:client id="topupWebService"
            serviceClass="ptdam.emoney.webservice.transactions.TopupWebService"
            address="http://localhost:8080/ecash-core-engine-dev-mitigasi/services/emoneytopup"

    <bean id="esCreditRunner" class="com.ptdam.promo.services.ESCreditRunner" />
        />
    </beans>

and here's how i use the @AutoWired, to call the SOAP service topupWebService.. on the testCall() method

ESCreditRunner.java

package ptdam.emoney.webservice.transactions;
public class ESCreditRunner {
        private File statusFile;
        private Properties status;
        private static final Logger logger = Logger.getLogger(ESCreditRunner.class);

        @Autowired
        private TopupWebService topupWebService;
        public void setTopupWebService(TopupWebService topupWebService) {
            this.topupWebService = topupWebService;
        }

        // testing 04/07/2017
        public void testCall(){
            topupWebService.echoTest("Luki");
        }
    }

when i run the testCall() method, i always get NullPointerException on the topupWebService variable. It looks like it's not injected properly..

what i'm missing here?

Update:
i've made another thread as a continuation of this thread. Kindly check it here :) Spring WebService with Endpoint vs no Endpoint


问:
How do I perform calculations on a string in pandas?
I have a dataframe like this:

```<code>Country     Sales    Assets
China       4B        320B
China       3B        125B
India       112M      100B
USA         39M       200B...
</code>```

The Sales and assests columns have some values in billions and some in millions. Billions are denoted by B and millions as M. Now I want to check the total sales of a country but I can't do so as the values are object type. So I stripped the B from the columns and tried converting them to float values. But the values like 39M cause a problem.

Since 1 billion=1000 million, I want to convert the values in millions to that in billions. Like the values like 39M should be converted to 0.039B. So later I can strip off all the B's and convert them to float.

How do I do that?

答:
Something like this should work</p>

```<code>data=df['Sales']

for value in data:

     char=value[-1]

     if char=='M'

        toadd=float(value[:-1]/1000.0)

     elif char=='B':
        toadd=float(value[:-1])

    totalsales=totalsales+toadd
</code>```

Body:
I have a dataframe like this:

Country     Sales    Assets
China       4B        320B
China       3B        125B
India       112M      100B
USA         39M       200B...

The Sales and assests columns have some values in billions and some in millions. Billions are denoted by B and millions as M. Now I want to check the total sales of a country but I can't do so as the values are object type. So I stripped the B from the columns and tried converting them to float values. But the values like 39M cause a problem.

Since 1 billion=1000 million, I want to convert the values in millions to that in billions. Like the values like 39M should be converted to 0.039B. So later I can strip off all the B's and convert them to float.

How do I do that?

Body:
Something like this should work

data=df['Sales']

for value in data:

     char=value[-1]

     if char=='M'

        toadd=float(value[:-1]/1000.0)

     elif char=='B':
        toadd=float(value[:-1])

    totalsales=totalsales+toadd


问:
Markdown rendered with Redcarpet missing dashes for lists and new lines between sections
I have some markdown that I generated which looks like this in text form:

"### We're looking for someone with…\r\n\r\n- Significant Rails
  experience\r\n- Good communication skills
  (recommended)\r\n\r\n\r\n### You should be located near:\r\n\r\n-
  Berlin\r\n- San Francisco\r\n- Toronto\r\n"

In ApplicationHelper.rb, I have the following:

```<code>module ApplicationHelper
    def markdown(content)
      return '' if content.blank?

      @options = {
           autolink: true,
           space_after_headers: true,
           underline: true,
           link_attributes: {rel: 'nofollow', target: "_blank"}
       }

      markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, @options)

      markdown.render(content).html_safe
    end
end
</code>```

No matter how many line breaks I add between each of the H3 sections (in this case it's 3 new lines), the two sections hug right up next to each other instead of respecting the 3 \ns in the text.

Also, there's no - or * character before each item in a list.

I looked on the Redcarpet docs and I don't see anything that I can enable to respect the new lines and the list items. Whitelisting every single html tag that markdown compiles to doesn't seem like the right solution.

Any help would be appreciated. Thanks!

答:
these sample option may be can help you solve your problem, choose and delete the one that you don't needed. for rails change your data type to text not string, as it cannot use line break.

```<code>options = {
    :fenced_code_blocks => true,
    :no_intra_emphasis => true,
    :autolink => true,
    :strikethrough => true,
    :lax_html_blocks => true,
    # :superscript => true,
    :tables => true,
    :with_toc_data => true
  }
</code>```

and you should test with this,

```<code>### We're looking for someone with

- Significant Rails experience
- Good communication skills (recommended)

### You should be located near

- Berlin
- San Francisco
- Toronto
</code>```

Body:
I have some markdown that I generated which looks like this in text form:

"### We're looking for someone with…\r\n\r\n- Significant Rails
  experience\r\n- Good communication skills
  (recommended)\r\n\r\n\r\n### You should be located near:\r\n\r\n-
  Berlin\r\n- San Francisco\r\n- Toronto\r\n"

In ApplicationHelper.rb, I have the following:

module ApplicationHelper
    def markdown(content)
      return '' if content.blank?

      @options = {
           autolink: true,
           space_after_headers: true,
           underline: true,
           link_attributes: {rel: 'nofollow', target: "_blank"}
       }

      markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, @options)

      markdown.render(content).html_safe
    end
end

No matter how many line breaks I add between each of the H3 sections (in this case it's 3 new lines), the two sections hug right up next to each other instead of respecting the 3 \ns in the text.

Also, there's no - or * character before each item in a list.

I looked on the Redcarpet docs and I don't see anything that I can enable to respect the new lines and the list items. Whitelisting every single html tag that markdown compiles to doesn't seem like the right solution.

Any help would be appreciated. Thanks!

Body:
these sample option may be can help you solve your problem, choose and delete the one that you don't needed. for rails change your data type to text not string, as it cannot use line break.

options = {
    :fenced_code_blocks => true,
    :no_intra_emphasis => true,
    :autolink => true,
    :strikethrough => true,
    :lax_html_blocks => true,
    # :superscript => true,
    :tables => true,
    :with_toc_data => true
  }

and you should test with this,

### We're looking for someone with

- Significant Rails experience
- Good communication skills (recommended)

### You should be located near

- Berlin
- San Francisco
- Toronto


问:
What happens to messages sent to an actor while it is suspended?
Here is the situation, One my actors (A) is supervised by a Backoff supervisor (B).

The sequence of events that interest me is the following:

The system starts and everybody is happy

A fails while processing a message

B now considers A to be suspended until the backoff delay elapses

B receives some messages (MM) that he is meant to forward to A

The backoff delay elaspes and B restarts A

Everybody is happy again

On step 4, what happens to those messages?

Are they lost? Sent to dead-letters? stashed inside B somewhere, and sent to A when it restarts / resumes?

Now let's add another layer: A is not a standard Actor but an Actor with Stash.

What happens to the stash of messages between the failure of A and its restart/resume?
Is it discarded? Is it unstashed? Is it kept inside the stash?

答:
After a few experiments, I think I can answer both of my questions above:

What happens to messages sent to an actor supervised by a Backoff supervisor between the moment the actor fails and the moment it is restarted?

They are sent to deadLetters()

What happens to the stash of messages between the failure of an actor and its restart?

Nothing happens to the stash until the restart is actually attempted. When the restarting process starts, the preRestart() step of the stash calls unstashAll() to return all messages to the mailbox. Therefore messages are not lost, and not kept in the stash, but just unstashed and returned to the mailbox.


问:
How to call same job twise in pentaho job with different parameter?
I am creating pentaho jobs

In first set variable box i am passing value sysdate the first dfp job working perfectly.

In second set variable box i am passing value sysdate+1 ,so sysdate+1 file is picked correctly to process but second dfp job only getting error.

Is this logic is possible in pentaho Jobs?

答:
I have numerous example of that kind that works perfectly every night. And I guess the Set variables have the appropriate level (valid in parent job).

So the bug is probably in the value you give to the variable in Set variable 2. The value sysdate+1 has the literal value (the string "sysdate+1") not the Date of tomorrow.

You must first compute that value. Which is done in a transformation replacing Set variable 2, which would do something like this:


问:
Rails active record: update a list of records
I have two tables: 'countries' and 'airports'. I want to set all the countries, which have at least one airport, as 'active'. This does not work:

```<code>  def self.activate_by_airports
    update_all('active = 1', ['country_code IN (?)', Airport.select('DISTINCT(country_code)').where(:active => 1)])
  end
</code>```

As I understand, Airport.select(...) returns a list of Airport objects, when I need a list of country codes.

What is the right syntax in this case?

答: Use Airport.select('DISTINCT(country_code)').where(:active => 1).toArray or Airport.select('DISTINCT(country_code)').where(:active => 1).all -  Rails 3 only

Body:
I have two tables: 'countries' and 'airports'. I want to set all the countries, which have at least one airport, as 'active'. This does not work:

  def self.activate_by_airports
    update_all('active = 1', ['country_code IN (?)', Airport.select('DISTINCT(country_code)').where(:active => 1)])
  end

As I understand, Airport.select(...) returns a list of Airport objects, when I need a list of country codes.

What is the right syntax in this case?


问:
Split string based on spaces and read that in angular2
I am creating a pipe in angular2 where I want to split the string on white spaces and later on read it as an array.

```<code>let stringToSplit = "abc def ghi";
StringToSplit.split(" ");
console.log(stringToSplit[0]);
</code>```

When I log this, I always get "a" as output. Where I am going wrong?

答:
```<code>let stringToSplit = "abc def ghi";
StringToSplit.split(" ");
console.log(stringToSplit[0]);
</code>```

First, stringToSplit and StringToSplit are not the same. JS is case sensitive. Also you dont save result of StringToSplit.split(" ") anywhere and then you just output the first character of the string stringToSplit which is a. You could do like this:

    let stringToSplit = "abc def ghi";
    console.log(stringToSplit.split(" ")[0]); // stringToSplit.split(" ") returns array and then we take the first element of the array with [0]```

PS. also it is more about JavaScript than TypeScript or Angular.

Body:
I am creating a pipe in angular2 where I want to split the string on white spaces and later on read it as an array.

let stringToSplit = "abc def ghi";
StringToSplit.split(" ");
console.log(stringToSplit[0]);

When I log this, I always get "a" as output. Where I am going wrong?

Body:
let stringToSplit = "abc def ghi";
StringToSplit.split(" ");
console.log(stringToSplit[0]);

First, stringToSplit and StringToSplit are not the same. JS is case sensitive. Also you dont save result of StringToSplit.split(" ") anywhere and then you just output the first character of the string stringToSplit which is a. You could do like this:

    let stringToSplit = "abc def ghi";
    console.log(stringToSplit.split(" ")[0]); // stringToSplit.split(" ") returns array and then we take the first element of the array with [0]

PS. also it is more about JavaScript than TypeScript or Angular.


问:
SQL stored procedure for picking a random sample based on multiple criteria
I am new to SQL. I looked for all over the internet for a solution that matches the problem I have but I couldn't find any. I have a table named 'tblItemReviewItems' in an SQL server 2012.
tblItemReviewItems

Information:

1. ItemReviewId column is the PK.

2. Deleted column will have only "Yes" and "No" value.

3. Audited column will have only "Yes" and "No" value.

I want to create a stored procedure to do the followings:

Pick a random sample of 10% of all ItemReviewId for distinct 'UserId' and distinct 'ReviewDate' in a given date range. 10% sample should include- 5% of the total population from Deleted (No) and 5% of the total population from Deleted (Yes). Audited ="Yes" will be excluded from the sample.

For example – A user has 118 records. Out of the 118 records, 17 records have  Deleted column value "No" and 101 records have Deleted column value "Yes".  We need to pick a random sample of 12 records. Out of those 12 records, 6 should have Deleted column value "No" and 6 should have Deleted column value "Yes".

Update Audited column value to "Check" for the picked sample.

How can I achieve this?

This is the stored procedure I used to pick a sample of 5% of Deleted column value "No" and 5% of Deleted column value "Yes". Now the situation is different.

```<code>ALTER PROC [dbo].[spItemReviewQcPickSample]
    (
         @StartDate Datetime
        ,@EndDate Datetime
     )
    AS
    BEGIN
    WITH CTE
      AS (SELECT ItemReviewId
                ,100.0
                *row_number() OVER(PARTITION BY UserId
                                               ,ReviewDate
                                               ,Deleted
                                       order by newid()
                                  )
                /count(*) OVER(PARTITION BY UserId
                                           ,Reviewdate
                                           ,Deleted
                              )
                 AS pct
           FROM tblItemReviewItems
           WHERE ReviewDate BETWEEN @StartDate AND @EndDate
             AND Deleted in ('Yes','No')
             AND Audited='No'
         )
    SELECT a.*
      FROM tblItemReviewItems AS a
           INNER JOIN cte AS b
                   ON b.ItemReviewId=a.ItemReviewId
                  AND b.pct<=6
    ;
    WITH CTE
      AS (SELECT ItemReviewId
                ,100.00
                *row_number() OVER(PARTITION BY UserId
                                               ,ReviewDate
                                               ,Deleted
                                       ORDER BY newid()
                                  )
                /COUNT(*) OVER(PARTITION BY UserId
                                           ,Reviewdate
                                           ,Deleted
                              )
                 AS pct
            FROM tblItemReviewItems
           WHERE ReviewDate BETWEEN @StartDate AND @EndDate
             AND deleted IN ('Yes','No')
             AND audited='No'
         )
    UPDATE a
       SET Audited='Check'
      FROM tblItemReviewItems AS a
           INNER JOIN cte AS b
                   ON b.ItemReviewId=a.ItemReviewId
                  AND b.pct<=6
    ;
    END
</code>```

Any help would be highly appreciated. Thanks in advance.

答:
This may assist you in getting started. My idea is, you create the temp tables you need, and load the specific data into the (deleted, not deleted etc.). You then run something along the lines of:

```<code>IF OBJECT_ID('tempdb..#tmpTest') IS NOT NULL DROP TABLE #tmpTest
GO
CREATE TABLE #tmpTest
(
    ID  INT                 ,
    Random_Order INT
)

INSERT INTO #tmpTest
(
    ID
)
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9 UNION ALL
SELECT 10 UNION ALL
SELECT 11 UNION ALL
SELECT 12 UNION ALL
SELECT 13 UNION ALL
SELECT 14 UNION ALL
SELECT 15 UNION ALL
SELECT 16;

DECLARE @intMinID   INT ,
        @intMaxID   INT;

SELECT  @intMinID = MIN(ID)
FROM    #tmpTest;

SELECT  @intMaxID = MAX(ID)
FROM    #tmpTest;

WHILE @intMinID <= @intMaxID

    BEGIN
        UPDATE  #tmpTest
        SET     Random_Order = 10 + CONVERT(INT, (30-10+1)*RAND())
        WHERE   ID = @intMinID;

        SELECT @intMinID = @intMinID + 1;
    END

SELECT      TOP 5 *
FROM        #tmpTest
ORDER BY    Random_Order;
</code>```

This assigns a random number to a column, that you then use in conjunction with a TOP 5 clause, to get a random top 5 selection.

Appreciate a loop may not be efficient, but you may be able to update to a random number without it, and the same principle could be implemented. Hope that gives you some ideas.

Body:
I am new to SQL. I looked for all over the internet for a solution that matches the problem I have but I couldn't find any. I have a table named 'tblItemReviewItems' in an SQL server 2012.
tblItemReviewItems

Information:

1. ItemReviewId column is the PK.

2. Deleted column will have only "Yes" and "No" value.

3. Audited column will have only "Yes" and "No" value.

I want to create a stored procedure to do the followings:

Pick a random sample of 10% of all ItemReviewId for distinct 'UserId' and distinct 'ReviewDate' in a given date range. 10% sample should include- 5% of the total population from Deleted (No) and 5% of the total population from Deleted (Yes). Audited ="Yes" will be excluded from the sample.

For example – A user has 118 records. Out of the 118 records, 17 records have  Deleted column value "No" and 101 records have Deleted column value "Yes".  We need to pick a random sample of 12 records. Out of those 12 records, 6 should have Deleted column value "No" and 6 should have Deleted column value "Yes".

Update Audited column value to "Check" for the picked sample.

How can I achieve this?

This is the stored procedure I used to pick a sample of 5% of Deleted column value "No" and 5% of Deleted column value "Yes". Now the situation is different.

ALTER PROC [dbo].[spItemReviewQcPickSample]
    (
         @StartDate Datetime
        ,@EndDate Datetime
     )
    AS
    BEGIN
    WITH CTE
      AS (SELECT ItemReviewId
                ,100.0
                *row_number() OVER(PARTITION BY UserId
                                               ,ReviewDate
                                               ,Deleted
                                       order by newid()
                                  )
                /count(*) OVER(PARTITION BY UserId
                                           ,Reviewdate
                                           ,Deleted
                              )
                 AS pct
           FROM tblItemReviewItems
           WHERE ReviewDate BETWEEN @StartDate AND @EndDate
             AND Deleted in ('Yes','No')
             AND Audited='No'
         )
    SELECT a.*
      FROM tblItemReviewItems AS a
           INNER JOIN cte AS b
                   ON b.ItemReviewId=a.ItemReviewId
                  AND b.pct<=6
    ;
    WITH CTE
      AS (SELECT ItemReviewId
                ,100.00
                *row_number() OVER(PARTITION BY UserId
                                               ,ReviewDate
                                               ,Deleted
                                       ORDER BY newid()
                                  )
                /COUNT(*) OVER(PARTITION BY UserId
                                           ,Reviewdate
                                           ,Deleted
                              )
                 AS pct
            FROM tblItemReviewItems
           WHERE ReviewDate BETWEEN @StartDate AND @EndDate
             AND deleted IN ('Yes','No')
             AND audited='No'
         )
    UPDATE a
       SET Audited='Check'
      FROM tblItemReviewItems AS a
           INNER JOIN cte AS b
                   ON b.ItemReviewId=a.ItemReviewId
                  AND b.pct<=6
    ;
    END

Any help would be highly appreciated. Thanks in advance.

Body:
This may assist you in getting started. My idea is, you create the temp tables you need, and load the specific data into the (deleted, not deleted etc.). You then run something along the lines of:

IF OBJECT_ID('tempdb..#tmpTest') IS NOT NULL DROP TABLE #tmpTest
GO
CREATE TABLE #tmpTest
(
    ID  INT                 ,
    Random_Order INT
)

INSERT INTO #tmpTest
(
    ID
)
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9 UNION ALL
SELECT 10 UNION ALL
SELECT 11 UNION ALL
SELECT 12 UNION ALL
SELECT 13 UNION ALL
SELECT 14 UNION ALL
SELECT 15 UNION ALL
SELECT 16;

DECLARE @intMinID   INT ,
        @intMaxID   INT;

SELECT  @intMinID = MIN(ID)
FROM    #tmpTest;

SELECT  @intMaxID = MAX(ID)
FROM    #tmpTest;

WHILE @intMinID <= @intMaxID

    BEGIN
        UPDATE  #tmpTest
        SET     Random_Order = 10 + CONVERT(INT, (30-10+1)*RAND())
        WHERE   ID = @intMinID;

        SELECT @intMinID = @intMinID + 1;
    END

SELECT      TOP 5 *
FROM        #tmpTest
ORDER BY    Random_Order;

This assigns a random number to a column, that you then use in conjunction with a TOP 5 clause, to get a random top 5 selection.

Appreciate a loop may not be efficient, but you may be able to update to a random number without it, and the same principle could be implemented. Hope that gives you some ideas.


问:
Why does the delegate of an UIAlertView not work?
When I use my class AlertView for displaying an UIAlertView, I set the delegate to this class object and expect alertView:clickedButtonAt to run, but when I click abutton on the UIAlertView, it doesn't work. Why? Thanks!

```<code>import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window : UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow()
        window!.rootViewController = UIViewController()
        window!.rootViewController!.view.backgroundColor = .blue
        window!.makeKeyAndVisible()
        let a = AlertView()
        a.show()
        return true
    }

}
class AlertView : UIViewController,UIAlertViewDelegate{
    var done : ((_ buttonIndex: Int)->Void)?
    func show(){
        var createAccountErrorAlert: UIAlertView = UIAlertView()

        createAccountErrorAlert.delegate = self

        createAccountErrorAlert.title = "Oops"
        createAccountErrorAlert.message = "Could not create account!"
        createAccountErrorAlert.addButton(withTitle: "Dismiss")
        createAccountErrorAlert.addButton(withTitle: "Retry")

        createAccountErrorAlert.show()

    }
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int){
            print("Why delegate of alert view does not work?")
    }
}
</code>```

答: You are declaring your UIAlertView instance as a local variable and that way, it does not have a reference. Make it a global variable, so the delegate method could execute properly.

Body:
When I use my class AlertView for displaying an UIAlertView, I set the delegate to this class object and expect alertView:clickedButtonAt to run, but when I click abutton on the UIAlertView, it doesn't work. Why? Thanks!

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window : UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow()
        window!.rootViewController = UIViewController()
        window!.rootViewController!.view.backgroundColor = .blue
        window!.makeKeyAndVisible()
        let a = AlertView()
        a.show()
        return true
    }

}
class AlertView : UIViewController,UIAlertViewDelegate{
    var done : ((_ buttonIndex: Int)->Void)?
    func show(){
        var createAccountErrorAlert: UIAlertView = UIAlertView()

        createAccountErrorAlert.delegate = self

        createAccountErrorAlert.title = "Oops"
        createAccountErrorAlert.message = "Could not create account!"
        createAccountErrorAlert.addButton(withTitle: "Dismiss")
        createAccountErrorAlert.addButton(withTitle: "Retry")

        createAccountErrorAlert.show()

    }
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int){
            print("Why delegate of alert view does not work?")
    }
}


问:
Problem with too many try catch
Is it possible to write a method like outType? TryDo(func, out exception, params) that call func(arg1,arg2,arg3,...) which params contains arg1,arg2,arg3,... and then it return func return value and if any exception occurred return null and set the exception?

Can this be done better by another function signature?

for example I have
string Foo1(int i) { return i.ToString()}

void Foo2(int[] a) {throw new Exception();}

and then call

string t = TryDo(Foo1, out ex, {i});

TryDo(Foo2, out ex, {});

-----------Edited------------------

```<code>        string t;
        SomeClass c;
        try
        {
            t = Foo1(4, 2, new OtherClass());
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }

        try
        {
            Foo2();
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }
        .
        .
        .
</code>```

I want to make it like this.

```<code>        string t = TryDo(Foo1, out ex, {4, 2, new OtherClass());
        Examine(ex);
        SomeClass c = TryDo(Foo2, out ex, {});
        Examine(ex);
</code>```

答:
Yes, it's possible.

But why would you like to return a possible exception this way? You could throw further and process at the needed place.

Title: Problem with too many try catch

Body:
Is it possible to write a method like outType? TryDo(func, out exception, params) that call func(arg1,arg2,arg3,...) which params contains arg1,arg2,arg3,... and then it return func return value and if any exception occurred return null and set the exception?

Can this be done better by another function signature?

for example I have
string Foo1(int i) { return i.ToString()}

void Foo2(int[] a) {throw new Exception();}

and then call

string t = TryDo(Foo1, out ex, {i});

TryDo(Foo2, out ex, {});

-----------Edited------------------

        string t;
        SomeClass c;
        try
        {
            t = Foo1(4, 2, new OtherClass());
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }

        try
        {
            Foo2();
        }
        catch (Exception ex)
        {
            Log(ex);
            if (/*ex has some features*/)
                throw ex;
        }
        .
        .
        .

I want to make it like this.

        string t = TryDo(Foo1, out ex, {4, 2, new OtherClass());
        Examine(ex);
        SomeClass c = TryDo(Foo2, out ex, {});
        Examine(ex);


答:
Is default: ⇒ B the same as default: () ⇒ B

No, the first is call by name and the second is a thunk. The type of a call by name parameter is the type of the parameter itself, where the type of a thunk is () => T which is the same as Function0[T].

When you do o1.getOrElse(() => "Else") you are working with heterogeneous types, so Scala will find the least common super type which is in this case is Any.

```<code>val orElse: Any = o1.getOrElse(() => "Else")
</code>```

Title: Scala: default return type of Option.getOrElse(...)

Body:
Is default: ⇒ B the same as default: () ⇒ B

No, the first is call by name and the second is a thunk. The type of a call by name parameter is the type of the parameter itself, where the type of a thunk is () => T which is the same as Function0[T].

When you do o1.getOrElse(() => "Else") you are working with heterogeneous types, so Scala will find the least common super type which is in this case is Any.

val orElse: Any = o1.getOrElse(() => "Else")


问:
remove all fields from 2nd col which is not 5 consecutive numerical digits
```<code> Record | RegistrationID

 41-1|10551
 1-105|5569
  4-7|10043
  78-3|2176
   3-1|19826
   12-1|1981
</code>```

Output file has to

```<code> Record | RegistrationID
1-1|10551
3-1|19826
5-7|10043
</code>```

My file is a Pipe delimited

any number in the 2nd col which is less than or more than 5lenght must be removed i.e only records that have 5 consecutive numbers must remain.I'm with google since an hour to fix this out any advice given would be highly appreciable. thanks in advance

tried this grep -E ' [0-9]{5}$|$' filename   - > not getting any results ,tx to cyrus

答:
Add --re-interval option to support the interval expression in the regular expression.</p>

```<code>gawk --re-interval -F'|' '$NF~/^[0-9]{4,5}$/' file
</code>```

Body:
 Record | RegistrationID

 41-1|10551
 1-105|5569
  4-7|10043
  78-3|2176
   3-1|19826
   12-1|1981

Output file has to

 Record | RegistrationID
1-1|10551
3-1|19826
5-7|10043

My file is a Pipe delimited

any number in the 2nd col which is less than or more than 5lenght must be removed i.e only records that have 5 consecutive numbers must remain.I'm with google since an hour to fix this out any advice given would be highly appreciable. thanks in advance

tried this grep -E ' [0-9]{5}$|$' filename   - > not getting any results ,tx to cyrus

Body:
Add --re-interval option to support the interval expression in the regular expression.

gawk --re-interval -F'|' '$NF~/^[0-9]{4,5}$/' file


问:
AnjularJS ng-repeat get item from different scope object
I have two different scope objects. First one is 'Details' object, the second one is 'Country' object. I want to fetch data from my 'Country' object using 'CountryId' which is in the 'Details' object.

I have created a function in my scope and I can fetch my Country data (please see the below code. it is working properly) but I'm sure that it should be a better way in AngularJS.
Is there?

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
    var app = angular.module("myApp", []);
    app.controller("myCtrl", function($scope) {
        $scope.FindSpecificItem = function(obj, field, value, returnField) {
            return jQuery.grep(obj, function(item) {
                return (item[field] == value);
            })[0][returnField];
        };
        $scope.details = [{
            "Name": "John",
            "CountryId": "1"
        }, {
            "Name": "Dave",
            "CountryId": "2"
        }]
        $scope.Countries = [{
            "Id": "1",
            "Country": "USA"
        }, {
            "Id": "2",
            "Country": "England"
        }]
    });
</script>

<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        <table>
            <tr ng-repeat="d in details">
                <td>{{d.Name}}</td>
                <td>{{FindSpecificItem(Countries,"Id",d.CountryId,"Country")}}</td>
            </tr>
        </table>
    </div>

</body>

</html>
</code>```

答:
try this

```<code><!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script
 src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<script>
  var app = angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {
    $scope.FindSpecificItem  = function(countryId) {
    var result = "";
      angular.forEach($scope.Countries,function(country){
          if(country.Id == countryId)
            result = country.Country;
      })

      return result;
    };
    $scope.details = [{
        "Name": "John",
        "CountryId": "1"
    }, {
        "Name": "Dave",
        "CountryId": "2"
    }]
    $scope.Countries = [{
        "Id": "1",
        "Country": "USA"
    }, {
        "Id": "2",
        "Country": "England"
    }]
  });
</script>

<body>

<div ng-app="myApp" ng-controller="myCtrl">
    <table>
        <tr ng-repeat="d in details">
            <td>{{d.Name}}</td>
            <td>{{FindSpecificItem(d.CountryId)}}
        </tr>
    </table>
</div>
</code>```

Body:
I have two different scope objects. First one is 'Details' object, the second one is 'Country' object. I want to fetch data from my 'Country' object using 'CountryId' which is in the 'Details' object.

I have created a function in my scope and I can fetch my Country data (please see the below code. it is working properly) but I'm sure that it should be a better way in AngularJS.
Is there?

<!DOCTYPE html>

                {{d.Name}}
                {{FindSpecificItem(Countries,"Id",d.CountryId,"Country")}}

Body:
try this

<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script
 src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<script>
  var app = angular.module("myApp", []);
  app.controller("myCtrl", function($scope) {
    $scope.FindSpecificItem  = function(countryId) {
    var result = "";
      angular.forEach($scope.Countries,function(country){
          if(country.Id == countryId)
            result = country.Country;
      })

      return result;
    };
    $scope.details = [{
        "Name": "John",
        "CountryId": "1"
    }, {
        "Name": "Dave",
        "CountryId": "2"
    }]
    $scope.Countries = [{
        "Id": "1",
        "Country": "USA"
    }, {
        "Id": "2",
        "Country": "England"
    }]
  });
</script>

<body>

<div ng-app="myApp" ng-controller="myCtrl">
    <table>
        <tr ng-repeat="d in details">
            <td>{{d.Name}}</td>
            <td>{{FindSpecificItem(d.CountryId)}}
        </tr>
    </table>
</div>


问:
In Swift, how can I check that a user is no longer touching the screen after touchesMoved is triggered?
I need to know that a user started to touch the screen and then know when he is not touching it anymore.

With touchesBegan and touchesEnded I can get such information. However, if the user is swiping his fingers, then I know he started doing it with touchesMoved.
However I am not able to check when he is no longer touching the screen.
Basically , touchesEnded will not fire after the user stopped swipping.
Any ideas?

Example of my code:

```<code>override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if let touch = touches.first {
    print("Finger touched!")
    }
    super.touchesBegan(touches, withEvent:event)
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {

        print("Finger is swipping!")

    }
    super.touchesBegan(touches, withEvent:event)
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {

        print("finger is not touching.") //this will not fire if finger stopped swipping

    }
    super.touchesBegan(touches, withEvent:event)
}
</code>```

答:
working in Swift 3 </p>

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
        print("Finger touched!")
    }

}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
        print("finger is not touching.")
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
        print("Touch Move")
    }
}
</code>```

Body:
I need to know that a user started to touch the screen and then know when he is not touching it anymore.

With touchesBegan and touchesEnded I can get such information. However, if the user is swiping his fingers, then I know he started doing it with touchesMoved.
However I am not able to check when he is no longer touching the screen.
Basically , touchesEnded will not fire after the user stopped swipping.
Any ideas?

Example of my code:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if let touch = touches.first {
    print("Finger touched!")
    }
    super.touchesBegan(touches, withEvent:event)
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {

        print("Finger is swipping!")

    }
    super.touchesBegan(touches, withEvent:event)
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {

        print("finger is not touching.") //this will not fire if finger stopped swipping

    }
    super.touchesBegan(touches, withEvent:event)
}

Body:
working in Swift 3

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
        print("Finger touched!")
    }

}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
        print("finger is not touching.")
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
        print("Touch Move")
    }
}


答:
I would avoid using out parameters unless absolutely necessary.

Here is a quote from the Design Guidelines for Developing Framework Libraries:

Avoid using out or reference parameters.

Working with members that define out or reference parameters requires that the developer understand pointers, subtle differences between value types and reference types, and initialization differences between out and reference parameters.

You can instead create a return type that wraps the result of your call:

```<code>class CallResult<T> where T : class {
  public CallResult(T result) { Result = result; }
  public CallResult(Exception exception) { Exception = exception; }
  public T Result { get; private set; }
  public Exception Exception { get; private set; }
  public Boolean IsSuccessful { get { return Exception == null; } }
}
</code>```

Your method could then be implemented like this:

```<code>CallResult<T> TryDo<T>(Func<Object[], T> action, params Object[] args) where T : class {
  try {
    return new CallResult<T>(action(args));
  }
  catch (Exception ex) {
    return new CallResult<T>(ex);
  }
}
</code>```

You can call it like this:

```<code>var callResult = TryDo<String>(Foo1, 4, 2, new OtherClass());
if (!callResult.IsSuccessful)
  Examine(callResult.Exception);
</code>```

However, if you intend to rethrow the exception in the Examine method loosing the stacktrace you should really reconsider your approach.

Title: Problem with too many try catch

Body:
I would avoid using out parameters unless absolutely necessary.

Here is a quote from the Design Guidelines for Developing Framework Libraries:

Avoid using out or reference parameters.

Working with members that define out or reference parameters requires that the developer understand pointers, subtle differences between value types and reference types, and initialization differences between out and reference parameters.

You can instead create a return type that wraps the result of your call:

class CallResult<T> where T : class {
  public CallResult(T result) { Result = result; }
  public CallResult(Exception exception) { Exception = exception; }
  public T Result { get; private set; }
  public Exception Exception { get; private set; }
  public Boolean IsSuccessful { get { return Exception == null; } }
}

Your method could then be implemented like this:

CallResult<T> TryDo<T>(Func<Object[], T> action, params Object[] args) where T : class {
  try {
    return new CallResult<T>(action(args));
  }
  catch (Exception ex) {
    return new CallResult<T>(ex);
  }
}

You can call it like this:

var callResult = TryDo<String>(Foo1, 4, 2, new OtherClass());
if (!callResult.IsSuccessful)
  Examine(callResult.Exception);

However, if you intend to rethrow the exception in the Examine method loosing the stacktrace you should really reconsider your approach.


问:
Create loadbalancer inside a vnet with azure
I want to create a load balancer for all my agents.
In the official docs I found a guide for an external load balancer, but I want to connect it with the api management so it has to be only visible in the vnet.

This post works if you only have one agent (you enter the private ip of the agent in your api route). But it does not handle the second agent.
Is it possible to use Azure API Management and Azure ACS (kubernetes) as frontend and backend?

So in my case I need to create a load balancer that handles all agents for the service and has a private ip in a vnet in that the api management service also is.

答:
well, nothing prevents you from connecting api management to an external endpoint, so there's that.

and if you really want internal endpoint I doubt that it is possible, since a NIC can only be attached to a single load balancer. maybe if you detach agent nics from the external load balancer and attach them to internal load balancer... that might work, but looks like a solid hack.

other way around this might be using ACS engine to generate a template for you and alter the template to deploy internal load balancer.


问:
how to create a new user jazn-data.xml programmatically?
I'm using JDeveloper 11g.
I want to create a new user programmatically in 'jazn-data.xml'. Is this possible and how can I do it?</p>

答:
Yes, is possible.
Technically speaking, you do not create users in jazn-data.xml, this is just a file used at development time. At runtime, you create users in weblogic.

Please find below a link:

Creating WebLogic users programmatically from a standalone Java client


问:
How does the window operation work with the keyBy in Flink?
I have data in Kafka that looks like this:

```<code>{
  "account": "iOS", //Possible values: iOS, android, web, windows
  "events": [
    {
      "timestamp": "2017-07-03T20:19:35Z"
    }
  ]
}
</code>```

The timestamp goes from 2017-07-03T20:19:35Z to 2017-07-03T20:22:30Z (about 3 minutes). I have this Flink program that ingests the data from the kafka topic above:

```<code>object TestWindow {
  def main(args: Array[String]) = {
    val props = new Properties()
    props.put(...)

    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

    env.addSource(new FlinkKafkaConsumer010[String]("topic", new SimpleStringSchema(), props)).
      keyBy(jsonStr => {
        val jsonParser = new JsonParser()
        val jsonObject = jsonParser.parse(jsonStr).getAsJsonObject()
        jsonObject.get("account")
    }).window(TumblingEventTimeWindows.of(Time.seconds(10)))
      .reduce({(v1, v2) =>
        println(v1 + " " + v2)
        ""
      })
    env.execute()
  }
}
</code>```

I am having trouble understanding how windowing works with the keyBy operation.

I understand that the keyBy operation above will create different partitions containing elements of the same key. But I am confused on when the windows are created and how each partition is added to which window?

My guess is that as each JSON object arrives it will be keyed by the keyBy operation and then based on the event timeStamp of that JSON object it will create a window for 10 seconds?

So for example if a JSON object with a timestamp of "2017-07-03T20:19:35Z" arrives and has a account type of iOS then a keyed by partition for iOS will be created and a window will also be created for "2017-07-03T20:19:35Z" to "2017-07-03T20:19:45Z"? Or is a window created every 10 seconds regardless of the event timestamp that is from the JSON object from Kafka?

答:
Your assumption about keyBy is correct. keyBy partitions the stream on the defined key attribute(s) and windows are computed per key.

The TumblingEventTimeWindow that you are using in your example has fixed window borders, i.e., the borders do not depend on the timestamps of your data. A 10 seconds tumbling window will create windows from [00:00:00.000, 00:00:10.000), [00:00:10.000, 00:00:20.000) and so on. Records that arrive at the window operator will be assigned to the window that intersects with their timestamp. When the window is closed (the local time of the operator passes the end timestamp of the window), the result of the window is computed and emitted. Note that windows are only instantiated with the first record, i.e., empty windows do not trigger a computation and cannot emit data, as for example a zero count.

Other window types such as a session window have data-driven boundaries. In case of a session window, all records that are not more than some time interval apart from each other are grouped into a window.

Body:
I have data in Kafka that looks like this:

{
  "account": "iOS", //Possible values: iOS, android, web, windows
  "events": [
    {
      "timestamp": "2017-07-03T20:19:35Z"
    }
  ]
}

The timestamp goes from 2017-07-03T20:19:35Z to 2017-07-03T20:22:30Z (about 3 minutes). I have this Flink program that ingests the data from the kafka topic above:

object TestWindow {
  def main(args: Array[String]) = {
    val props = new Properties()
    props.put(...)

    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

    env.addSource(new FlinkKafkaConsumer010[String]("topic", new SimpleStringSchema(), props)).
      keyBy(jsonStr => {
        val jsonParser = new JsonParser()
        val jsonObject = jsonParser.parse(jsonStr).getAsJsonObject()
        jsonObject.get("account")
    }).window(TumblingEventTimeWindows.of(Time.seconds(10)))
      .reduce({(v1, v2) =>
        println(v1 + " " + v2)
        ""
      })
    env.execute()
  }
}

I am having trouble understanding how windowing works with the keyBy operation.

I understand that the keyBy operation above will create different partitions containing elements of the same key. But I am confused on when the windows are created and how each partition is added to which window?

My guess is that as each JSON object arrives it will be keyed by the keyBy operation and then based on the event timeStamp of that JSON object it will create a window for 10 seconds?

So for example if a JSON object with a timestamp of "2017-07-03T20:19:35Z" arrives and has a account type of iOS then a keyed by partition for iOS will be created and a window will also be created for "2017-07-03T20:19:35Z" to "2017-07-03T20:19:45Z"? Or is a window created every 10 seconds regardless of the event timestamp that is from the JSON object from Kafka?


问:
Best practice to implement classes if every object behaves differently in Java
Let's take a real-world example.

Suppose, I have three Dogs, but one dog can differ from the other.

The first dog likes barking and eating, the second dog likes playing and chasing cats and the third dog likes running and jogging (consider these actions as methods).

How do I implement this in Java? What I have to use, what is the best practice? Abstract classes, interfaces or both of them?

答:
```<code>// Common interface. i.e. All dogs should be capable of barking!
public interface iDog {
    public void bark();
}

// Common definition. i.e. All dogs bark like this unless specified otherwise
public abstract class Dog implements iDog {
    public void bark() {
        System.out.println("Woof!");
    }
}

// Concrete Dog 1. Special type of bark, and eats.
public class BarkingEatingDog extends Dog {
    public void bark() {
        System.out.println("Big Woof!");
    }

    private void eating() {
        System.out.println("Yum!");
    }
}

// Concrete Dog 2. Plays and chases cats.
public class PlayingCatChasingDog extends Dog {
    public void play() {
        System.out.println("Playing!");
    }

    private void chaseCats() {
        System.out.println("GET OUT OF HERE STUPID CAT!");
    }
}

// Concrete Dog 3. Runs, jogs and barks differently
public class RunningJoggingDog extends Dog {
    public void run() {
        System.out.println("Running!");
    }

    private void jog() {
        System.out.println("Jogging!");
    }

    public void bark() {
        System.out.println("Barkety Bark Bark!");
    }
}
</code>```


问:
how can we show/hide div tags using value of radio buttons in jquery or javascript?
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

```

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

答:
This is one way to do it:

```<code>$( "#r0" ).bind( "click", function() {
  $("#OwnVehicle").show();
  $("#TwoWheeler").hide();
});

$( "#r1" ).bind( "click", function() {
  $("#OwnVehicle").hide();
  $("#TwoWheeler").show();
});
</code>```

Here a working fiddle
https://jsfiddle.net/0aa8w2sj/

It can be improved

Body:
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

Body:
This is one way to do it:

$( "#r0" ).bind( "click", function() {
  $("#OwnVehicle").show();
  $("#TwoWheeler").hide();
});

$( "#r1" ).bind( "click", function() {
  $("#OwnVehicle").hide();
  $("#TwoWheeler").show();
});

Here a working fiddle
https://jsfiddle.net/0aa8w2sj/

It can be improved


答:
Here is what you can do easily with JQuery

$(document).ready(function(){
 $("input[name='vehicleList']").click(function(){
   var selectedValue = $(this).val();
   if(selectedValue === "1"){
      $('#TwoWheeler').show();
      $('#FourWheeler').hide();
   }else{
      $('#TwoWheeler').hide();
      $('#FourWheeler').show();
   }
 });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="OwnVehicle">
                        <label>
                            <input type="radio" name="vehicleList" id="two" value="1" />Two Wheeler
                        </label>
                        <label>
                            <input type="radio" name="vehicleList" id="four"  value="2" />Four Wheeler
                        </label>
</div>

<div id="TwoWheeler" style="display:none">
                        <label>
                            <input type="radio" name="TwoWheeler" value="6" />Electric
                        </label>
                        <label>
                            <input type="radio" name="TwoWheeler" value="7" />Petrol
                        </label>
</div>
<div id="FourWheeler" style="display:none">
                        <label>
                            <input type="radio" name="FourWheeler" value="1" />Electric
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="2" />Petrol
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="3" />Diesel
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="4" />CNG
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="5" />LPG
                        </label>
</div></code>```

Title: how can we show/hide div tags using value of radio buttons in jquery or javascript?

Body:
Here is what you can do easily with JQuery

$(document).ready(function(){
 $("input[name='vehicleList']").click(function(){
   var selectedValue = $(this).val();
   if(selectedValue === "1"){
      $('#TwoWheeler').show();
      $('#FourWheeler').hide();
   }else{
      $('#TwoWheeler').hide();
      $('#FourWheeler').show();
   }
 });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="OwnVehicle">
                        <label>
                            <input type="radio" name="vehicleList" id="two" value="1" />Two Wheeler
                        </label>
                        <label>
                            <input type="radio" name="vehicleList" id="four"  value="2" />Four Wheeler
                        </label>
</div>

<div id="TwoWheeler" style="display:none">
                        <label>
                            <input type="radio" name="TwoWheeler" value="6" />Electric
                        </label>
                        <label>
                            <input type="radio" name="TwoWheeler" value="7" />Petrol
                        </label>
</div>
<div id="FourWheeler" style="display:none">
                        <label>
                            <input type="radio" name="FourWheeler" value="1" />Electric
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="2" />Petrol
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="3" />Diesel
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="4" />CNG
                        </label>
                        <label>
                            <input type="radio" name="FourWheeler" value="5" />LPG
                        </label>
</div>