问:
GIT re-merge files from dev to master
My master GIT branch seams to have some errors thus I'd like to recheck, re-merge or possibly clone my dev branch over the master branch so the master branch would be a copy of dev.

How can I do that?
Thx.

答:
From you comments it seems there are three possible cases:

The master index contains correct code and the working copy is broken.

The working copy is fine and the index is now broken.

Both are broken.

First, back everything up. Then:

In case 1, use git reset --hard HEAD to throw away the broken working copy.

In case 2, add and commit everything in the working copy.

In case 3, use git reset --hard dev to throw away both the index and the working copy. Alternatively, git reset --hard SOME_COMMIT_ID_THAT_ISN'T_BROKEN

In all three cases tell your friend to never use --force unless they really know what they're doing.

Also, it's probably best not to push into a non-bare repository (i.e. one with a working copy). I'd suggest you set up a bare repository somewhere that you both push and pull from rather than pushing directly into a repo that has a working copy. Use git init --bare to create a bare repo.

Did I mention back everything up? Good. Do it.

Title: GIT re-merge files from dev to master


来源: stackexchange

问:
Is this reducer compliant with the Redux rules?
I'm confused because I don't return state here, only action.payload (code snippet):

```<code>case HISTORY_SELECTED:
  return action.payload;
</code>```

All that reducer code:

```<code>import { HISTORY_SELECTED } from '../actions/index';

export default function (state = null, action) {
  switch (action.type) {
    case HISTORY_SELECTED:
      return action.payload;
    default:
      return state;
  }
}
</code>```

EDIT: Added 3 more cases.

If I understood answer in the right way, also CASE 2, CASE 3 and CASE 4 are ok, yes?

CASE 2 (reducer_note_selected.js)

```<code>import { NOTE_SELECTED, DEL_NOTE_SUCCESS } from '../actions/actions';

export default function (state = null, action) {
  switch (action.type) {
    case NOTE_SELECTED:
      return action.payload;
    case DEL_NOTE_SUCCESS:
      return null;
    default:
      return state;
  }
}
</code>```

CASE 3 (reducer_notes_status_fetch.js - here I'm returning just strings)

```<code> import {
 FETCH_ALL_NOTES_STARTED,
 FETCH_ALL_NOTES_ERROR,
 FETCH_ALL_NOTES_SUCCESS
} from '../actions/actions';

    export default function (state = {}, action) {
      switch (action.type) {
        case FETCH_ALL_NOTES_STARTED:
          return 'fetching_started';
        case FETCH_ALL_NOTES_ERROR:
          return 'error';
        case FETCH_ALL_NOTES_SUCCESS:
          return 'fetch_all_notes_success';
        default:
          return state;
      }
    }
</code>```

CASE 4 (reducer_notes_general.js)

```<code>import _ from 'lodash';
import { FETCH_ALL_NOTES_SUCCESS, DEL_NOTE_SUCCESS } from '../actions/actions';

export default function (state = {}, action) {
  switch (action.type) {
    case FETCH_ALL_NOTES_SUCCESS:
      return _.mapKeys(action.payload.data, '_id');
    case DEL_NOTE_SUCCESS:
      return _.omit(state, action.payload);
    default:
      return state;
  }
}
</code>```

答:
I disagree with @hindmost, you are replacing the state with your payload value. This is how the react-redux chain works. Hopefully this will clear things up for you.

React - Someone clicked a button (any event), ill send this to the
action.

Action - Got it. I will dispatch the action so the reducer    can
update the state

Reducer - I got the current state and new action.    Ill make a new
copy of state and pass it along

Store - I see the    reducer updated the state. Ill make sure all the
connected components    are aware of the change

React-Redux - Got the new data. ill determine    if i should update
react about these changes. I don't want to bother    updating the UI
if its not necessary.

React - Got the new data in my    props from the store. Ill update
the UI to reflect the changes.

ContentLicense: CC BY-SA 3.0

Body:
I'm confused because I don't return state here, only action.payload (code snippet):

case HISTORY_SELECTED:
  return action.payload;

All that reducer code:

import { HISTORY_SELECTED } from '../actions/index';

export default function (state = null, action) {
  switch (action.type) {
    case HISTORY_SELECTED:
      return action.payload;
    default:
      return state;
  }
}

EDIT: Added 3 more cases.

If I understood answer in the right way, also CASE 2, CASE 3 and CASE 4 are ok, yes?

CASE 2 (reducer_note_selected.js)

import { NOTE_SELECTED, DEL_NOTE_SUCCESS } from '../actions/actions';

export default function (state = null, action) {
  switch (action.type) {
    case NOTE_SELECTED:
      return action.payload;
    case DEL_NOTE_SUCCESS:
      return null;
    default:
      return state;
  }
}

CASE 3 (reducer_notes_status_fetch.js - here I'm returning just strings)

 import {
 FETCH_ALL_NOTES_STARTED,
 FETCH_ALL_NOTES_ERROR,
 FETCH_ALL_NOTES_SUCCESS
} from '../actions/actions';

    export default function (state = {}, action) {
      switch (action.type) {
        case FETCH_ALL_NOTES_STARTED:
          return 'fetching_started';
        case FETCH_ALL_NOTES_ERROR:
          return 'error';
        case FETCH_ALL_NOTES_SUCCESS:
          return 'fetch_all_notes_success';
        default:
          return state;
      }
    }

CASE 4 (reducer_notes_general.js)

import _ from 'lodash';
import { FETCH_ALL_NOTES_SUCCESS, DEL_NOTE_SUCCESS } from '../actions/actions';

export default function (state = {}, action) {
  switch (action.type) {
    case FETCH_ALL_NOTES_SUCCESS:
      return _.mapKeys(action.payload.data, '_id');
    case DEL_NOTE_SUCCESS:
      return _.omit(state, action.payload);
    default:
      return state;
  }
}


问:
Background images - even small ones - not displaying on mobile
I've never encountered this one before - my background images are fine on the desktop but completely invisible on mobile. Not even a "bitmappy" version appears, though the space for them is held open, so to speak.

http://www.compassionglobally.org

I've read several similar questions here on StackOverflow but the issue always seems to be the file size (and iOS's enforced limits in that area). But even quite small images - there are four of them down the page - don't show up.

This is a WordPress site, but I feel like that's probably not relevant here... but I guess I should mention that.

Any ideas or suggestions are much appreciated!

答:
This is one of the images not showing, right?

http://localhost/compassionglobally.org/wordpress/wp-content/themes/cg/library/images/site/baby.jpg

Well,

The link above is pointed to an image on the computer that is hosting the site (localhost). That file cannot be found on either your phone, or my laptop.

The fact that "the space for them is held open" is irrelevent, as you've set the div to be 250px high and 250px wide.

To solve the problem, you just need to remove the "localhost/" from the start of the links, like this:

http://compassionglobally.org/wordpress/wp-content/themes/cg/library/images/site/baby.jpg


问:
Using MySQL's COUNT with two tables
I have the following MySQL table called tbl_pet_owners:

```<code>+--------+----------+--------+
| name   | pet      | city   |
+========+==========+========+
| jane   | cat      | Boston |
+--------+----------+--------+
| jane   | dog      | Boston |
+--------+----------+--------+
| jack   | cat      | Boston |
+--------+----------+--------+
| jim    | snake    | Boston |
+--------+----------+--------+
| jim    | goldfish | Boston |
+--------+----------+--------+
| joseph | cat      | NYC    |
+--------+----------+--------+
</code>```

I want to use COUNT to get the number of pets per city, BUT if an individual owns two or more pets of the same type, then those pets are counted as one. The pet types are listed in another MySQL table called tbl_pet_types:

```<code>+----------+---------+
| pet      | type    |
+==========+=========+
| cat      | mammal  |
+----------+---------+
| dog      | mammal  |
+----------+---------+
| snake    | reptile |
+----------+---------+
| goldfish | fish    |
+----------+---------+
</code>```

So since jane's cat and dog are of the same type, they're considered one pet.
In this example, the result would be:

```<code>Boston 4
NYC    1
</code>```

Any tips on how to achieve this?

答:
It can be optimized, but works:</p>

```<code>select count(*), result.city from (
    select owners.city, types.type, owners.name
    from tbl_pet_owners owners
    left join tbl_pet_types types on owners.pet = types.pet group by owners.city, owners.name, types.type
) as result
group by result.city;
</code>```

Title: Using MySQL's COUNT with two tables

Body:
I have the following MySQL table called tbl_pet_owners:

+--------+----------+--------+
| name   | pet      | city   |
+========+==========+========+
| jane   | cat      | Boston |
+--------+----------+--------+
| jane   | dog      | Boston |
+--------+----------+--------+
| jack   | cat      | Boston |
+--------+----------+--------+
| jim    | snake    | Boston |
+--------+----------+--------+
| jim    | goldfish | Boston |
+--------+----------+--------+
| joseph | cat      | NYC    |
+--------+----------+--------+

I want to use COUNT to get the number of pets per city, BUT if an individual owns two or more pets of the same type, then those pets are counted as one. The pet types are listed in another MySQL table called tbl_pet_types:

+----------+---------+
| pet      | type    |
+==========+=========+
| cat      | mammal  |
+----------+---------+
| dog      | mammal  |
+----------+---------+
| snake    | reptile |
+----------+---------+
| goldfish | fish    |
+----------+---------+

So since jane's cat and dog are of the same type, they're considered one pet.
In this example, the result would be:

Boston 4
NYC    1

Any tips on how to achieve this?

Body:
It can be optimized, but works:

select count(*), result.city from (
    select owners.city, types.type, owners.name
    from tbl_pet_owners owners
    left join tbl_pet_types types on owners.pet = types.pet group by owners.city, owners.name, types.type
) as result
group by result.city;


问:
Mockito : Testing void methods gives InvalidUseOfMatchersException
I'm having problems with two void methods. In encouragedVenturesScoring I've followed this answer mocking an arraylist that will be looped in a for loop and haven't mocked the list, but passed a real list and added mocked objects.

Mockito gives me an InvalidUseOfMatchersException on this line

verify(effectList.get(Mockito.anyInt())).execute(playerHandler);

There are lots of questions on SO on this exception , and I think it's because of anyInt(). Anyway I changed it to

```<code>verify(effectList.get(0)).execute(playerHandler);
</code>```

And now it's saying Wanted but not invoked effect.execute(playerHandler)
Actually there were zero interactions with this mock

Is it because I put doNothing ?
doNothing().when(effect).execute(playerHandler);

In my second method militaryStrengthScoring() method is there a way to skip the first chunk of code and just test the if..else condition? What would be the best approach to test this method?

Thank you for your time.

This is the class to be tested

```<code> public class EndGameScoringBaseController implements EndGameScoringHandler {

private static final int[] TERRITORIES_REWARD = {0,0,1,4,10,20};
private static final int[] CHARACTERS_REWARD = {1,3,6,10,15,21};
private static final int RESOURCES_RATE = 5;
private static final int FIRST_MILITARY_REWARD = 5;
private static final int SECOND_MILITARY_REWARD = 2;

private PlayerHandler player;

public EndGameScoringBaseController(PlayerHandler player) {
    super();
    this.player = player;
}

@Override
public void encouragedVenturesScoring() {
    for (DevelopmentCard card : player.getPlayer().getPersonalBoard().getVentures()) {
        for (Effect e : card.getPermanentEffects())
            e.execute(player);
    }
}

@Override
public void militaryStrengthScoring(GameController game) {
    Set<Integer> points = new HashSet<>();
    int myPoints = this.player.getPointsHandler().getMilitaryPoints();

    for (PlayerHandler p: game.getPlayers()) {
        points.add(p.getPointsHandler().getMilitaryPoints());
    }
    int[] rank = new int[points.size()];
    int j = 0;
    for (Integer i : points) {
        rank[j] = i;
        j++;
    }

    Arrays.sort(rank);

    if (rank[rank.length-1] == myPoints) {
        player.getPointsHandler().winMilitaryPoints(FIRST_MILITARY_REWARD);
    }
    else if (rank[rank.length-2] == myPoints) {
        player.getPointsHandler().winVictoryPoints(SECOND_MILITARY_REWARD);
    }

}
</code>```

Tested method for encouragedVenturesScoring

```<code>@Test
public void encouragedVenturesScoringTest() {
    //given
    List<DevelopmentCard> ventureList;
    ventureList = Arrays.asList(developmentCard, developmentCard);
    when(playerHandler.getPlayer().getPersonalBoard().getVentures()).thenReturn(ventureList);
    List<Effect> effectList;
    effectList = Arrays.asList(effect, effect);
    when(developmentCard.getPermanentEffects()).thenReturn(effectList);
    doNothing().when(effect).execute(playerHandler);

    //when
    endgameController.encouragedVenturesScoring();

    //then
    verify(effectList.get(Mockito.anyInt())).execute(playerHandler);
}
</code>```

Incomplete tested method for militaryStrengthScoring

```<code>@Test
public void militaryStrengthScoringTest() {

//given
when(playerHandler.getPointsHandler().getMilitaryPoints()).thenReturn(4);
doNothing().when(playerHandler.getPointsHandler()).winMilitaryPoints(FIRST_MILITARY_REWARD);

//when
endgameController.militaryStrengthScoring(gameController);

//then
/../
}
</code>```

答:
You can only verify mock objects created by Mockito.

But effectList is a "real" list. Therefore Mockito knows nothing about that object. Thus any attempt to verify that list must fail.

If you want to verify that object - then you have to mock it!

Of course, this means that you have specify all calls that will go to the mocked list.

Body:
I'm having problems with two void methods. In encouragedVenturesScoring I've followed this answer mocking an arraylist that will be looped in a for loop and haven't mocked the list, but passed a real list and added mocked objects.

Mockito gives me an InvalidUseOfMatchersException on this line

verify(effectList.get(Mockito.anyInt())).execute(playerHandler);

There are lots of questions on SO on this exception , and I think it's because of anyInt(). Anyway I changed it to

verify(effectList.get(0)).execute(playerHandler);

And now it's saying Wanted but not invoked effect.execute(playerHandler)
Actually there were zero interactions with this mock

Is it because I put doNothing ?
doNothing().when(effect).execute(playerHandler);

In my second method militaryStrengthScoring() method is there a way to skip the first chunk of code and just test the if..else condition? What would be the best approach to test this method?

Thank you for your time.

This is the class to be tested

 public class EndGameScoringBaseController implements EndGameScoringHandler {

private static final int[] TERRITORIES_REWARD = {0,0,1,4,10,20};
private static final int[] CHARACTERS_REWARD = {1,3,6,10,15,21};
private static final int RESOURCES_RATE = 5;
private static final int FIRST_MILITARY_REWARD = 5;
private static final int SECOND_MILITARY_REWARD = 2;

private PlayerHandler player;

public EndGameScoringBaseController(PlayerHandler player) {
    super();
    this.player = player;
}

@Override
public void encouragedVenturesScoring() {
    for (DevelopmentCard card : player.getPlayer().getPersonalBoard().getVentures()) {
        for (Effect e : card.getPermanentEffects())
            e.execute(player);
    }
}

@Override
public void militaryStrengthScoring(GameController game) {
    Set<Integer> points = new HashSet<>();
    int myPoints = this.player.getPointsHandler().getMilitaryPoints();

    for (PlayerHandler p: game.getPlayers()) {
        points.add(p.getPointsHandler().getMilitaryPoints());
    }
    int[] rank = new int[points.size()];
    int j = 0;
    for (Integer i : points) {
        rank[j] = i;
        j++;
    }

    Arrays.sort(rank);

    if (rank[rank.length-1] == myPoints) {
        player.getPointsHandler().winMilitaryPoints(FIRST_MILITARY_REWARD);
    }
    else if (rank[rank.length-2] == myPoints) {
        player.getPointsHandler().winVictoryPoints(SECOND_MILITARY_REWARD);
    }

}

Tested method for encouragedVenturesScoring

@Test
public void encouragedVenturesScoringTest() {
    //given
    List<DevelopmentCard> ventureList;
    ventureList = Arrays.asList(developmentCard, developmentCard);
    when(playerHandler.getPlayer().getPersonalBoard().getVentures()).thenReturn(ventureList);
    List<Effect> effectList;
    effectList = Arrays.asList(effect, effect);
    when(developmentCard.getPermanentEffects()).thenReturn(effectList);
    doNothing().when(effect).execute(playerHandler);

    //when
    endgameController.encouragedVenturesScoring();

    //then
    verify(effectList.get(Mockito.anyInt())).execute(playerHandler);
}

Incomplete tested method for militaryStrengthScoring

@Test
public void militaryStrengthScoringTest() {

//given
when(playerHandler.getPointsHandler().getMilitaryPoints()).thenReturn(4);
doNothing().when(playerHandler.getPointsHandler()).winMilitaryPoints(FIRST_MILITARY_REWARD);

//when
endgameController.militaryStrengthScoring(gameController);

//then
/../
}


问:
dplyr::select_if(., is.numeric) super slow
This (the part y = ...) runs abnormally slowly:

```<code>library(dplyr)
n <- 10000
p <- 1000

x <- as.tbl(as.data.frame(matrix(rnorm(n * p), nc = p)))
y = x %>%
  select_if(., is.numeric)
</code>```

in fact, it is one of the smallest part of my data cleaning code. Is there a better way to do this?

(dplyr 0.7.1)

答:
This runs faster despite being more clunky:</p>

```<code>x %>% select(which(lapply(x,class) == "numeric"))
</code>```

Body:
This (the part y = ...) runs abnormally slowly:

library(dplyr)
n <- 10000
p <- 1000

x <- as.tbl(as.data.frame(matrix(rnorm(n * p), nc = p)))
y = x %>%
  select_if(., is.numeric)

in fact, it is one of the smallest part of my data cleaning code. Is there a better way to do this?

(dplyr 0.7.1)

Body:
This runs faster despite being more clunky:

x %>% select(which(lapply(x,class) == "numeric"))


问:
Django models update when backend database updated
I am relatively new to Django.
I have managed to create a basic app and all that without problems and it works fine.

The question probably has been asked before.
Is there a way to update existing Django models already mapped to existing databases when the underlying database is modified?

To be specific, I have mysql database that I use for my Django app as well as some standalone python and R scripts. Now, it is much easier to update the mysql database with, say, daily stock prices, everyday from my existing scripts outside Django models. Ideally, what I would like is to have my Django models that are already mapped to these tables to reflect the updated data.

I know there is $ python manage.py inspectdb for creating models from existing databases. But that is not the objective.

From what I have gathered so far from the docs and online searches, it is imperative to update the backend database through Django models. Not outside of it. Is it the case really? As long as the table structure doesn;t change I really don't see the why this should not be allowed. Database is meant to serve multiple customers isn't it? With Django being one of it.

And I can not provide a reproducible example as it is a conceptual question.
If this functionality doesn't exist, imho, it really should.

Thanks,
Kaustubh

答: You don't need to update models if you just added new data. Models are related to a database structure only.</p>


问:
What is the right way to pass data from PHP application to JS?
Let's say i want to open a PHP page and without another request, pass some JSON data directly to the browser, so it will be accessible to my Javascript functions.

I don't know the right way to do it, but what i do currently is something like this :

```<code><textarea id="mydata" style:"display:none">[{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}]</textarea>
</code>```

I put the data inside a invisible textarea and now the data inside 'mydata' textarea is accessible by JS doing something like this :

```<code>var myData = JSON.parse($('#mydata').val());
</code>```

Although this works, somehow it does not seem to me the right way to do it... I know i could avoid to 'dirty' the html code by getting the data using Ajax after the page opens, but what i'm trying to do here is avoid more requests, so with only one request, everything will be accessible. Actually in my application i have about 5 textareas like these, so with only 1 request to the server i get all data needed.

Thanks

答:
From PHP's perspective, there is no difference between this:

```<code><textarea id="mydata" style:"display:none">[{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}]</textarea>
</code>```

and this:

```<code>var myData = [{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}];
</code>```

Both of the above take the form of:

```<code>[a string][the serialized object][a string]
</code>```

Whether you're surrounding the values with HTML or with JavaScript, that surrounding decoration is just raw output strings as far as PHP is concerned.  So there's no need to add the extra step of outputting the JSON to a form element and then using JavaScript to get the form element's value as a string and parse it back to an object.  You can just emit the object itself directly to JavaScript code.

Body:
Let's say i want to open a PHP page and without another request, pass some JSON data directly to the browser, so it will be accessible to my Javascript functions.

I don't know the right way to do it, but what i do currently is something like this :

<textarea id="mydata" style:"display:none">[{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}]</textarea>

I put the data inside a invisible textarea and now the data inside 'mydata' textarea is accessible by JS doing something like this :

var myData = JSON.parse($('#mydata').val());

Although this works, somehow it does not seem to me the right way to do it... I know i could avoid to 'dirty' the html code by getting the data using Ajax after the page opens, but what i'm trying to do here is avoid more requests, so with only one request, everything will be accessible. Actually in my application i have about 5 textareas like these, so with only 1 request to the server i get all data needed.

Thanks

Body:
From PHP's perspective, there is no difference between this:

<textarea id="mydata" style:"display:none">[{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}]</textarea>

and this:

var myData = [{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}];

Both of the above take the form of:

[a string][the serialized object][a string]

Whether you're surrounding the values with HTML or with JavaScript, that surrounding decoration is just raw output strings as far as PHP is concerned.  So there's no need to add the extra step of outputting the JSON to a form element and then using JavaScript to get the form element's value as a string and parse it back to an object.  You can just emit the object itself directly to JavaScript code.


问:
Woocommerce completed order email - only manually
I am trying to cancel/remove the automatic customer emails that are sent when saving order status as "completed" after the order was shipped.

The reason for not wanting automatic emails to be sent is because I added a a code to the email template file (override) /woocommerce/email/customer-completed-order.php which will display the new order note created in the admin in the email sent to the customer and if we add the order note and save it and then change the order status to completed and save it, a new note is created and an email is sent. So now the note showing in the email sent to the customer is not the note that we wanted to display in the email.
The entire intention of this is to have a nicely designed email with status update "shipped" and include the tracking number of the shipment.
The code that adds the last/newest order note to the email:

```<code><?php
$args = array(
'status' => 'approve',
'post_id' => $order->id
);
$comments = get_comments($args);
foreach($comments as $comment) {
if ($comment === reset ($comments))
echo $comment->comment_content . '.<br />';
}
</code>```

So I now found a solution for this.
Adding the function from this link:
https://docs.woocommerce.com/document/unhookremove-woocommerce-emails/

```<code>add_action( 'woocommerce_email', 'unhook_those_pesky_emails' );

function unhook_those_pesky_emails( $email_class ) {

remove_action( 'woocommerce_order_status_completed_notification', array( $email_class->emails['WC_Email_Customer_Completed_Order'], 'trigger' ) );
}
</code>```

The above function will disable the automatic email that is sent when saving the order with the status "completed" but you can still manually send the order completed email using the "order actions" and control which last order note is saved while sending the email.
So now we simply change the order status to completed and save, then we add an "order note to customer" (not private) which only contains the tracking number and save it ("add note") and lastly we use the "order actions" to manually send the order completed email to the customer.

Feel free if any questions...

答:
```<code><?php
  $args = array(
   'status' => 'approve',
   'post_id' => $order->id
   );
  $comments = get_comments($args);
  foreach($comments as $comment)
   {
     if ($comment === reset ($comments))
        echo $comment->comment_content . '.<br />';
   }
</code>```

The above code does not give the desired output(i.e. the last order note to the customer) in WooCommerce(WC) 3.1.0

The working of the above code was due to a bug which was fixed in WC 3.1.0. For the above code to work(to return the last order note to the customer) do the following:
    remove the code line: $comments = get_comments($args);
    and replace it with:

```<code>`remove_filter( 'comments_clauses', array( 'WC_Comments','exclude_order_comments' ), 10, 1 );
 $comments = get_comments( $args );
 add_filter( 'comments_clauses', array( 'WC_Comments','exclude_order_comments' ), 10, 1 );`
</code>```

Fo more details on the bug :https://github.com/woocommerce/woocommerce/issues/15982#issuecomment-313235066

Body:
I am trying to cancel/remove the automatic customer emails that are sent when saving order status as "completed" after the order was shipped.

The reason for not wanting automatic emails to be sent is because I added a a code to the email template file (override) /woocommerce/email/customer-completed-order.php which will display the new order note created in the admin in the email sent to the customer and if we add the order note and save it and then change the order status to completed and save it, a new note is created and an email is sent. So now the note showing in the email sent to the customer is not the note that we wanted to display in the email.
The entire intention of this is to have a nicely designed email with status update "shipped" and include the tracking number of the shipment.
The code that adds the last/newest order note to the email:

<?php
$args = array(
'status' => 'approve',
'post_id' => $order->id
);
$comments = get_comments($args);
foreach($comments as $comment) {
if ($comment === reset ($comments))
echo $comment->comment_content . '.
';
}

So I now found a solution for this.
Adding the function from this link:
https://docs.woocommerce.com/document/unhookremove-woocommerce-emails/

add_action( 'woocommerce_email', 'unhook_those_pesky_emails' );

function unhook_those_pesky_emails( $email_class ) {

remove_action( 'woocommerce_order_status_completed_notification', array( $email_class->emails['WC_Email_Customer_Completed_Order'], 'trigger' ) );
}

The above function will disable the automatic email that is sent when saving the order with the status "completed" but you can still manually send the order completed email using the "order actions" and control which last order note is saved while sending the email.
So now we simply change the order status to completed and save, then we add an "order note to customer" (not private) which only contains the tracking number and save it ("add note") and lastly we use the "order actions" to manually send the order completed email to the customer.

Feel free if any questions...

Body:
<?php
  $args = array(
   'status' => 'approve',
   'post_id' => $order->id
   );
  $comments = get_comments($args);
  foreach($comments as $comment)
   {
     if ($comment === reset ($comments))
        echo $comment->comment_content . '.<br />';
   }

The above code does not give the desired output(i.e. the last order note to the customer) in WooCommerce(WC) 3.1.0

The working of the above code was due to a bug which was fixed in WC 3.1.0. For the above code to work(to return the last order note to the customer) do the following:
    remove the code line: $comments = get_comments($args);
    and replace it with:

`remove_filter( 'comments_clauses', array( 'WC_Comments','exclude_order_comments' ), 10, 1 );
 $comments = get_comments( $args );
 add_filter( 'comments_clauses', array( 'WC_Comments','exclude_order_comments' ), 10, 1 );`

Fo more details on the bug :https://github.com/woocommerce/woocommerce/issues/15982#issuecomment-313235066


问:
Store negative integer in Core Data
I can properly assign and retrieve a positive integer to an attribute of a managed object model instance. However, assigning a negative integer to this attribute records the number "4294967295" to my core data persistant store (an xml file). Thus, when the application reloads and the managed object is re-instantiated, the attribute reads "4294967295".

This attribute is specified in my DataModel as type Integer 32 and has a "Min Value" of "-12". I'm guessing this has something to do with storing negative integers as strings. This code produces the same "4294967295":

```<code>NSLog(@"Log -1: %u", -1);
=> "Log -1: 4294967295"
</code>```

What's the proper way to store a negative integer in Core Data?

答: It's not a problem with Core Data, it's a problem with your format specifier. %u means that you want the argument formatted as an unsigned integer, which cannot be negative. Use %d or %i instead (these mean signed integers).

ContentLicense: CC BY-SA 2.5

Title: Store negative integer in Core Data

Body:
I can properly assign and retrieve a positive integer to an attribute of a managed object model instance. However, assigning a negative integer to this attribute records the number "4294967295" to my core data persistant store (an xml file). Thus, when the application reloads and the managed object is re-instantiated, the attribute reads "4294967295".

This attribute is specified in my DataModel as type Integer 32 and has a "Min Value" of "-12". I'm guessing this has something to do with storing negative integers as strings. This code produces the same "4294967295":

NSLog(@"Log -1: %u", -1);
=> "Log -1: 4294967295"

What's the proper way to store a negative integer in Core Data?


问:
Splitting Column Header Into Row Elements In R
After performing data analysis on a larger data set using R, I get output as shown in following sample data:

```<code>   A_B C_D E_F G_H
1   1   1   0   0
2   1   0   1   1
3   1   1   0   1
4   0   0   1   1
5   1   0   1   1
6   0   0   0   1
</code>```

Currently, I am trying to split the column header into such that they appear in two different column as element, and I get the sum of the column they represented. It will look something like this:

```<code>   P1  P2  Sum
1   A   B   4
2   C   D   2
3   E   F   3
4   G   H   5
</code>```

For sum of each column, I can directly make use of colSums(), however I am getting tangled on how splitting the column header and making them appear as cell element described above.

Please let me know any suggestions on how I can approach this, thanks.

答:
Generate Sample Data

```<code>df1 <- structure(list(A_B = c(1L, 1L, 1L, 0L, 1L, 0L), C_D = c(1L, 0L,
 1L, 0L, 0L, 0L), E_F = c(0L, 1L, 0L, 1L, 1L, 0L), G_H = c(0L,
1L, 1L, 1L, 1L, 1L)), .Names = c("A_B", "C_D", "E_F", "G_H"),
 class = "data.frame", row.names = c("1",
 "2", "3", "4", "5", "6"))
</code>```

Method 1: strsplit

```<code>d1 <- data.frame(do.call(rbind, strsplit(names(df1), "_")), Sum = as.vector(colSums(df1)))
names(d1)[1:2] <- c('P1', 'P2')
d1
#   P1 P2 Sum
#1  A  B   4
#2  C  D   2
#3  E  F   3
#4  G  H   5
</code>```

Method 2:  tidyverse

```<code>library(tidyverse)
gather(df1) %>%
       separate(key, into = c('P1', 'P2')) %>%
       group_by(P1, P2) %>%
       summarise(Sum = sum(value))
# A tibble: 4 x 3
# Groups:   P1 [?]
#     P1    P2   Sum
#  <chr> <chr> <int>
#1     A     B     4
#2     C     D     2
#3     E     F     3
#4     G     H     5
</code>```

Body:
After performing data analysis on a larger data set using R, I get output as shown in following sample data:

   A_B C_D E_F G_H
1   1   1   0   0
2   1   0   1   1
3   1   1   0   1
4   0   0   1   1
5   1   0   1   1
6   0   0   0   1

Currently, I am trying to split the column header into such that they appear in two different column as element, and I get the sum of the column they represented. It will look something like this:

   P1  P2  Sum
1   A   B   4
2   C   D   2
3   E   F   3
4   G   H   5

For sum of each column, I can directly make use of colSums(), however I am getting tangled on how splitting the column header and making them appear as cell element described above.

Please let me know any suggestions on how I can approach this, thanks.

Body:
Generate Sample Data

df1 <- structure(list(A_B = c(1L, 1L, 1L, 0L, 1L, 0L), C_D = c(1L, 0L,
 1L, 0L, 0L, 0L), E_F = c(0L, 1L, 0L, 1L, 1L, 0L), G_H = c(0L,
1L, 1L, 1L, 1L, 1L)), .Names = c("A_B", "C_D", "E_F", "G_H"),
 class = "data.frame", row.names = c("1",
 "2", "3", "4", "5", "6"))

Method 1: strsplit

d1 <- data.frame(do.call(rbind, strsplit(names(df1), "_")), Sum = as.vector(colSums(df1)))
names(d1)[1:2] <- c('P1', 'P2')
d1
#   P1 P2 Sum
#1  A  B   4
#2  C  D   2
#3  E  F   3
#4  G  H   5

Method 2:  tidyverse

library(tidyverse)
gather(df1) %>%
       separate(key, into = c('P1', 'P2')) %>%
       group_by(P1, P2) %>%
       summarise(Sum = sum(value))
# A tibble: 4 x 3
# Groups:   P1 [?]
#     P1    P2   Sum
#  <chr> <chr> <int>
#1     A     B     4
#2     C     D     2
#3     E     F     3
#4     G     H     5


问:
Extract Insert statements from Oracle DB through Shell script
I want to extract the insert statements for the data in a table in Oracle DB through the shell script. It would be similar to DB backup but I need insert statements for data in all tables in DB.</p>

答: If you have TOAD for Oracle you can exact the results of a query from Data Grid of a Editor window.  Click the Export Dataset button above the resulting data set and select insert statements.</p>


问:
How to nest using selenium elements C#
I've made a number of tests using Selenium. I was curious if I'm nesting correctly. I'm not sure if there is a better way and if there is I would be happy to hear it.

At the moment I open a PowerPoint session in my start up using the WinApp Driver. Then when nesting I do the following. Here I'm finding an element called Linking. A child of Linking in the tree of elements is Update and so on.

```<code>var linking = session.FindElementByName("Linking");
var update = linking.FindElementByName("Update");// within the linking element there is an update button
update.Click();
session.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
var all =update.FindElementByName("All");// within the update element there is a dropdown menu with an "All" button
session.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
all.Click();
</code>```

答:
In a comment, you mentioned the issue with the code was that all wasn't clickable unless you put in a sleep.

Use an explicit wait. Something like:

```<code>new WebDriverWait(session, TimeSpan.FromSeconds(10))
    .Until(ExpectedConditions.ElementToBeClickable(update.FindElementByName("All"))
</code>```

Things might be a bit different for the WinApp Driver, but that's the basic idea.

Title: How to nest using selenium elements C#

Body:
I've made a number of tests using Selenium. I was curious if I'm nesting correctly. I'm not sure if there is a better way and if there is I would be happy to hear it.

At the moment I open a PowerPoint session in my start up using the WinApp Driver. Then when nesting I do the following. Here I'm finding an element called Linking. A child of Linking in the tree of elements is Update and so on.

var linking = session.FindElementByName("Linking");
var update = linking.FindElementByName("Update");// within the linking element there is an update button
update.Click();
session.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
var all =update.FindElementByName("All");// within the update element there is a dropdown menu with an "All" button
session.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
all.Click();

Body:
In a comment, you mentioned the issue with the code was that all wasn't clickable unless you put in a sleep.

Use an explicit wait. Something like:

new WebDriverWait(session, TimeSpan.FromSeconds(10))
    .Until(ExpectedConditions.ElementToBeClickable(update.FindElementByName("All"))

Things might be a bit different for the WinApp Driver, but that's the basic idea.


问:
jQuery Watermark and using .Val()
I have a problem in that I am using a simple watermark plugin such that it works

```<code>jQuery('#selector').Watermark('Watermark text here ...');
</code>```

The problem is - when I try and use something like

```<code>if (jQuery('#selector').val() != "") { //do stuff }
</code>```

The statement is True because of the watermark. Is there anyway I can somehow "ignore" this watermark value for my If statement ?

Thanks

答:
Similar question here:

Jquery: Is there some way to make val() return an empty string instead of 'undefined' for an empty list?

The gist of the solution in your case would be:

```<code>if ((jQuery('#selector').not('.watermark').val()||'') != "") { //do stuff }
</code>```

Title: jQuery Watermark and using .Val()

Body:
I have a problem in that I am using a simple watermark plugin such that it works

jQuery('#selector').Watermark('Watermark text here ...');

The problem is - when I try and use something like

if (jQuery('#selector').val() != "") { //do stuff }

The statement is True because of the watermark. Is there anyway I can somehow "ignore" this watermark value for my If statement ?

Thanks

Body:
Similar question here:

Jquery: Is there some way to make val() return an empty string instead of 'undefined' for an empty list?

The gist of the solution in your case would be:

if ((jQuery('#selector').not('.watermark').val()||'') != "") { //do stuff }


问:
Decimal model binder not working with globalization
I'm posting some data from the client to the server like this

```<code>$.post(url, myData)
   .done(function (data) {
   });
</code>```

here's the controller's action

```<code>public class MyModel
{
   decimal Precision { get; set; }
}

[HttpPost]
public ActionResult PostInfo(MyModel postBack)
{
}
</code>```

when I use the English culture PostInfo works as expected however when I change the culture to Spanish and Precision = 1,2 then I get the following error

The value 1,2 is not valid for Precision

Can someone please tell me why the default model binder is failing to parse 1,2 when the CurrentCulture is Spanish?

I change the culture in _Layout.cshtml. It's for testing purpose only.

```<code>@{
    System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("es", "ES");
}
</code>```

答:
the last time i checked, the default model binder doesn't handle internationalization formats. you would have to roll you own.</p>

```<code>public class DecimalModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        var valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        var modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
            //Check if this is a nullable decimal and a null or empty string has been passed
            var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType &&
                                      string.IsNullOrEmpty(valueResult.AttemptedValue));

            //If not nullable and null then we should try and parse the decimal
            if (!isNullableAndNull)
            {
                actualValue = decimal.Parse(valueResult.AttemptedValue, NumberStyles.Any, CultureInfo.CurrentCulture);
            }
        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
}
</code>```

Body:
I'm posting some data from the client to the server like this

$.post(url, myData)
   .done(function (data) {
   });

here's the controller's action

public class MyModel
{
   decimal Precision { get; set; }
}

[HttpPost]
public ActionResult PostInfo(MyModel postBack)
{
}

when I use the English culture PostInfo works as expected however when I change the culture to Spanish and Precision = 1,2 then I get the following error

The value 1,2 is not valid for Precision

Can someone please tell me why the default model binder is failing to parse 1,2 when the CurrentCulture is Spanish?

I change the culture in _Layout.cshtml. It's for testing purpose only.

@{
    System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("es", "ES");
}

Body:
the last time i checked, the default model binder doesn't handle internationalization formats. you would have to roll you own.

public class DecimalModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        var valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        var modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
            //Check if this is a nullable decimal and a null or empty string has been passed
            var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType &&
                                      string.IsNullOrEmpty(valueResult.AttemptedValue));

            //If not nullable and null then we should try and parse the decimal
            if (!isNullableAndNull)
            {
                actualValue = decimal.Parse(valueResult.AttemptedValue, NumberStyles.Any, CultureInfo.CurrentCulture);
            }
        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
}


问:
scripting a write command to another user
I'm testing a script to write a predefined message to another user.  I'm starting by trying to write to myself (two logins on the same machine).  The script hangs without delivering a message until I manually terminate with ctrl+c on the sending login, at which point the receiving login only shows that I sent EOF.  The script follows:

```<code>#!/bin/bash
write myName
message
!kill $$
</code>```

Even when I uncomment the kill command, its like the write command doesn't see the following message.  When i termante the sender with ctrl+c, I see the following....

```<code>[....]$ ./writeScript.sh
write: myName is logged in more than once; writing to pts/112    (hangs here)
^C./writeScript.sh: line 3: message: command not found
Terminated
[...]$
</code>```

and the receiver sees...

```<code>Message from myName@myPlace on pts/143 at 09:53 ...
EOF
</code>```

How do I make this message send successfully?  Thanks.

答:
You need to give input to write.  Something like:

```<code>#!/bin/bash
write myName << EOM
message
EOM
</code>```

or:

```<code>echo message | write myName
</code>```

Body:
I'm testing a script to write a predefined message to another user.  I'm starting by trying to write to myself (two logins on the same machine).  The script hangs without delivering a message until I manually terminate with ctrl+c on the sending login, at which point the receiving login only shows that I sent EOF.  The script follows:

#!/bin/bash
write myName
message
!kill $$

Even when I uncomment the kill command, its like the write command doesn't see the following message.  When i termante the sender with ctrl+c, I see the following....

[....]$ ./writeScript.sh
write: myName is logged in more than once; writing to pts/112    (hangs here)
^C./writeScript.sh: line 3: message: command not found
Terminated
[...]$

and the receiver sees...

Message from myName@myPlace on pts/143 at 09:53 ...
EOF

How do I make this message send successfully?  Thanks.

Body:
You need to give input to write.  Something like:

#!/bin/bash
write myName << EOM
message
EOM

or:

echo message | write myName


问:
Watching a directory with nodejs - Not registering files uploaded by ftp
I'm trying to watch for any newly added files to an ftp server, which has the directory mapped to a drive on the server that's running the node application. The problem is that it doesn't register any events for files added through ftp; when files are modified or created through the node application they are picked up fine.

I'm currently using chokidar to watch the directory and log any events with the simple code below:

```<code>const watcher = chokidar.watch('./myDir', {
persistent: true,
awaitWriteFinish: {
  stabilityThreshold: 2000,
  pollInterval: 100
}
});

watcher
.on('add', path => console.log(`File ${path} has been added`))
.on('change', path => console.log(`File ${path} has been changed`));
</code>```

I've added the awaitWriteFinish option to try to see if it will register when the file is completed from the ftp transfer, but with no joy.

Any suggestions?

答:
You can watch a directory using the native module fs:

```<code>const fs = require('fs');
const folderPath = './test';
const pollInterval = 300;

let folderItems = {};
setInterval(() => {
  fs.readdirSync(folderPath)
  .forEach((file) => {
    let path = `${folderPath}/${file}`;
    let lastModification = fs.statSync(path).mtimeMs;
    if (!folderItems[file]) {
      folderItems[file] = lastModification;
      console.log(`File ${path} has been added`);
    } else if (folderItems[file] !== lastModification) {
      folderItems[file] = lastModification;
      console.log(`File ${path} has been changed`);
    }
  });
}, pollInterval);
</code>```

But the above example will not watch the files in subfolders. Another approach to watch all subfolders, is to use unix find through the node child_process.exec function.

```<code>const fs = require('fs');
const {execSync} = require('child_process');
const folderPath = './test';
const pollInterval = 500;

let folderItems = {};
setInterval(() => {
  let fileList = execSync(`find ${folderPath}`).toString().split('\n');
  for (let file of fileList) {
    if (file.length < 1) continue;
    let lastModification = fs.statSync(file).mtimeMs;
    if (!folderItems[file]) {
      folderItems[file] = lastModification;
      console.log(`File ${file} has been added`);
    } else if (folderItems[file] !== lastModification) {
      folderItems[file] = lastModification;
      console.log(`File ${file} has been changed`);
    }
  }
}, pollInterval);
</code>```

Body:
I'm trying to watch for any newly added files to an ftp server, which has the directory mapped to a drive on the server that's running the node application. The problem is that it doesn't register any events for files added through ftp; when files are modified or created through the node application they are picked up fine.

I'm currently using chokidar to watch the directory and log any events with the simple code below:

const watcher = chokidar.watch('./myDir', {
persistent: true,
awaitWriteFinish: {
  stabilityThreshold: 2000,
  pollInterval: 100
}
});

watcher
.on('add', path => console.log(`File ${path} has been added`))
.on('change', path => console.log(`File ${path} has been changed`));

I've added the awaitWriteFinish option to try to see if it will register when the file is completed from the ftp transfer, but with no joy.

Any suggestions?

Body:
You can watch a directory using the native module fs:

const fs = require('fs');
const folderPath = './test';
const pollInterval = 300;

let folderItems = {};
setInterval(() => {
  fs.readdirSync(folderPath)
  .forEach((file) => {
    let path = `${folderPath}/${file}`;
    let lastModification = fs.statSync(path).mtimeMs;
    if (!folderItems[file]) {
      folderItems[file] = lastModification;
      console.log(`File ${path} has been added`);
    } else if (folderItems[file] !== lastModification) {
      folderItems[file] = lastModification;
      console.log(`File ${path} has been changed`);
    }
  });
}, pollInterval);

But the above example will not watch the files in subfolders. Another approach to watch all subfolders, is to use unix find through the node child_process.exec function.

const fs = require('fs');
const {execSync} = require('child_process');
const folderPath = './test';
const pollInterval = 500;

let folderItems = {};
setInterval(() => {
  let fileList = execSync(`find ${folderPath}`).toString().split('\n');
  for (let file of fileList) {
    if (file.length < 1) continue;
    let lastModification = fs.statSync(file).mtimeMs;
    if (!folderItems[file]) {
      folderItems[file] = lastModification;
      console.log(`File ${file} has been added`);
    } else if (folderItems[file] !== lastModification) {
      folderItems[file] = lastModification;
      console.log(`File ${file} has been changed`);
    }
  }
}, pollInterval);


问:
Flink Avro 1.8.1 NoSuchMethodError when running on cluster
We run Flink 1.3.0 CEP jobs and rely on Avro 1.8.1 (LogicalType does not exist in Avro 1.7.7) to serialize complex events (as POJOs). It's working when run from within the IDE (IntelliJ), but when we package the jar-file and deploy it to the cluster we get:

```<code>java.lang.NoSuchMethodError: org.apache.avro.Schema.setLogicalType(Lorg/apache/avro/LogicalType;)V
at org.apache.avro.LogicalType.addToSchema(LogicalType.java:72)
</code>```

However, it seems that we build the jar containing the right Avro package version (1.8.1) regarding the build output.

```<code>mvn clean package -Pbuild-jar
...
[INFO] Including org.apache.avro:avro:jar:1.8.1 in the shaded jar.
...
</code>```

Question: How can we assure that our Flink cluster uses the correct Avro version (1.8.1)?

Our pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.group.flink</groupId>
<artifactId>cep</artifactId>
<version>0.2</version>
<packaging>jar</packaging>

<name>Complex Event Processing</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <flink.version>1.3.0</flink.version>
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
    <kafka.version>0.10.2.1</kafka.version>
    <scala.version>2.11</scala.version>
    <avro.version>1.8.1</avro.version>
    <junit.version>5.0.0-M4</junit.version>
</properties>

<repositories>
    <repository>
        <id>apache.snapshots</id>
        <name>Apache Development Snapshot Repository</name>
        <url>https://repository.apache.org/content/repositories/snapshots/</url>
        <releases>
            <enabled>false</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

<!--

    Execute "mvn clean package -Pbuild-jar"
    to build a jar file out of this project!

    How to use the Flink Quickstart pom:

    a) Adding new dependencies:
        You can add dependencies to the list below.
        Please check if the maven-shade-plugin below is filtering out your dependency
        and remove the exclude from there.

    b) Build a jar for running on the cluster:
        There are two options for creating a jar from this project

        b.1) "mvn clean package" -> this will create a fat jar which contains all
                dependencies necessary for running the jar created by this pom in a cluster.
                The "maven-shade-plugin" excludes everything that is provided on a running Flink cluster.

        b.2) "mvn clean package -Pbuild-jar" -> This will also create a fat-jar, but with much
                nicer dependency exclusion handling. This approach is preferred and leads to
                much cleaner jar files.
-->

<dependencies>
    <!-- Apache Flink dependencies -->
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-java</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-streaming-java_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-clients_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-cep_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-connector-kafka-0.10_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>

    <!-- explicitly add a standard loggin framework, as Flink does not (in the future) have
        a hard dependency on one specific framework by default -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka_${scala.version}</artifactId>
        <version>${kafka.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.avro</groupId>
        <artifactId>avro</artifactId>
        <version>${avro.version}</version>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>${junit.version}</version>
    </dependency>
    <dependency>
        <groupId>com.github.smueller18</groupId>
        <artifactId>avro-builder</artifactId>
        <version>0.5</version>
    </dependency>
    <dependency>
        <groupId>com.github.smueller18</groupId>
        <artifactId>flink-serialization</artifactId>
        <version>0.6</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.9.9</version>
    </dependency>

</dependencies>

<profiles>
    <profile>
        <!-- Profile for packaging correct JAR files -->
        <id>build-jar</id>

        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>

        <dependencies>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-java</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-streaming-java_${scala.version}</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-clients_${scala.version}</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>${slf4j.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>

        <build>
            <plugins>
                <!-- disable the exclusion rules -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-shade-plugin</artifactId>
                    <version>2.4.1</version>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>shade</goal>
                            </goals>
                            <configuration>
                                <artifactSet>
                                    <excludes combine.self="override"></excludes>
                                </artifactSet>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

<build>
    <plugins>
        <!-- We use the maven-shade plugin to create a fat jar that contains all dependencies
        except flink and it's transitive dependencies. The resulting fat-jar can be executed
        on a cluster. Change the value of Program-Class if your program entry point changes. -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.4.1</version>
            <executions>
                <!-- Run shade goal on package phase -->
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <artifactSet>
                            <excludes>
                                <!-- This list contains all dependencies of flink-dist
                                Everything else will be packaged into the fat-jar
                                -->
                                <exclude>org.apache.flink:flink-annotations</exclude>
                                <exclude>org.apache.flink:flink-shaded-hadoop2</exclude>
                                <exclude>org.apache.flink:flink-shaded-curator-recipes</exclude>
                                <exclude>org.apache.flink:flink-core</exclude>
                                <exclude>org.apache.flink:flink-java</exclude>
                                <exclude>org.apache.flink:flink-scala_2.11</exclude>
                                <exclude>org.apache.flink:flink-runtime_2.11</exclude>
                                <exclude>org.apache.flink:flink-optimizer_2.11</exclude>
                                <exclude>org.apache.flink:flink-clients_2.11</exclude>
                                <exclude>org.apache.flink:flink-avro_2.11</exclude>
                                <exclude>org.apache.flink:flink-examples-batch_2.11</exclude>
                                <exclude>org.apache.flink:flink-examples-streaming_2.11</exclude>
                                <exclude>org.apache.flink:flink-streaming-java_2.11</exclude>
                                <exclude>org.apache.flink:flink-streaming-scala_2.11</exclude>
                                <exclude>org.apache.flink:flink-scala-shell_2.11</exclude>
                                <exclude>org.apache.flink:flink-python</exclude>
                                <exclude>org.apache.flink:flink-metrics-core</exclude>
                                <exclude>org.apache.flink:flink-metrics-jmx</exclude>
                                <exclude>org.apache.flink:flink-statebackend-rocksdb_2.11</exclude>

                                <!-- Also exclude very big transitive dependencies of Flink

                                WARNING: You have to remove these excludes if your code relies on other
                                versions of these dependencies.

                                -->

                                <exclude>log4j:log4j</exclude>
                                <exclude>org.scala-lang:scala-library</exclude>
                                <exclude>org.scala-lang:scala-compiler</exclude>
                                <exclude>org.scala-lang:scala-reflect</exclude>
                                <exclude>com.data-artisans:flakka-actor_*</exclude>
                                <exclude>com.data-artisans:flakka-remote_*</exclude>
                                <exclude>com.data-artisans:flakka-slf4j_*</exclude>
                                <exclude>io.netty:netty-all</exclude>
                                <exclude>io.netty:netty</exclude>
                                <exclude>commons-fileupload:commons-fileupload</exclude>
                                <!--<exclude>org.apache.avro:avro</exclude>-->
                                <exclude>commons-collections:commons-collections</exclude>
                                <exclude>org.codehaus.jackson:jackson-core-asl</exclude>
                                <exclude>org.codehaus.jackson:jackson-mapper-asl</exclude>
                                <exclude>com.thoughtworks.paranamer:paranamer</exclude>
                                <exclude>org.xerial.snappy:snappy-java</exclude>
                                <exclude>org.apache.commons:commons-compress</exclude>
                                <exclude>org.tukaani:xz</exclude>
                                <exclude>com.esotericsoftware.kryo:kryo</exclude>
                                <exclude>com.esotericsoftware.minlog:minlog</exclude>
                                <exclude>org.objenesis:objenesis</exclude>
                                <exclude>com.twitter:chill_*</exclude>
                                <exclude>com.twitter:chill-java</exclude>
                                <exclude>commons-lang:commons-lang</exclude>
                                <exclude>junit:junit</exclude>
                                <exclude>org.apache.commons:commons-lang3</exclude>
                                <exclude>org.slf4j:slf4j-api</exclude>
                                <exclude>org.slf4j:slf4j-log4j12</exclude>
                                <exclude>log4j:log4j</exclude>
                                <exclude>org.apache.commons:commons-math</exclude>
                                <exclude>org.apache.sling:org.apache.sling.commons.json</exclude>
                                <exclude>commons-logging:commons-logging</exclude>
                                <exclude>commons-codec:commons-codec</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-core</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-databind</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-annotations</exclude>
                                <exclude>stax:stax-api</exclude>
                                <exclude>com.typesafe:config</exclude>
                                <exclude>org.uncommons.maths:uncommons-maths</exclude>
                                <exclude>com.github.scopt:scopt_*</exclude>
                                <exclude>commons-io:commons-io</exclude>
                                <exclude>commons-cli:commons-cli</exclude>
                            </excludes>
                        </artifactSet>
                        <filters>
                            <filter>
                                <artifact>org.apache.flink:*</artifact>
                                <excludes>
                                    <!-- exclude shaded google but include shaded curator -->
                                    <exclude>org/apache/flink/shaded/com/**</exclude>
                                    <exclude>web-docs/**</exclude>
                                </excludes>
                            </filter>
                            <filter>
                                <!-- Do not copy the signatures in the META-INF folder.
                                Otherwise, this might cause SecurityExceptions when using the JAR. -->
                                <artifact>*:*</artifact>
                                <excludes>
                                    <exclude>META-INF/*.SF</exclude>
                                    <exclude>META-INF/*.DSA</exclude>
                                    <exclude>META-INF/*.RSA</exclude>
                                </excludes>
                            </filter>
                        </filters>
                        <!-- If you want to use ./bin/flink run <quickstart jar> uncomment the following lines.
                        This will add a Main-Class entry to the manifest file -->
                        <!--
                        <transformers>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>de.hska.stcs.cep.StreamingJob</mainClass>
                            </transformer>
                        </transformers>
                        -->
                        <createDependencyReducedPom>false</createDependencyReducedPom>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source> <!-- If you want to use Java 8, change this to "1.8" -->
                <target>1.8</target> <!-- If you want to use Java 8, change this to "1.8" -->
            </configuration>
        </plugin>
    </plugins>

    <!-- If you want to use Java 8 Lambda Expressions uncomment the following lines -->
    <!--
    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerId>jdt</compilerId>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.eclipse.tycho</groupId>
                        <artifactId>tycho-compiler-jdt</artifactId>
                        <version>0.21.0</version>
                    </dependency>
                </dependencies>
            </plugin>

            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-assembly-plugin</artifactId>
                                    <versionRange>[2.4,)</versionRange>
                                    <goals>
                                        <goal>single</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore/>
                                </action>
                            </pluginExecution>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-compiler-plugin</artifactId>
                                    <versionRange>[3.1,)</versionRange>
                                    <goals>
                                        <goal>testCompile</goal>
                                        <goal>compile</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore/>
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
    -->
</build>
</code>```

UPDATE: I build flink 1.3 from source and updated the avro version (from 1.7.7 to 1.8.1) in the project's pom.xml and it seems to work for now. Still unsure why it's not working when building the fat jar.

答:
try to use latest version of avro</p>

```<code><dependency>
  <groupId>org.apache.avro</groupId>
  <artifactId>avro</artifactId>
  <version>1.8.2</version>
</dependency>
</code>```

Body:
We run Flink 1.3.0 CEP jobs and rely on Avro 1.8.1 (LogicalType does not exist in Avro 1.7.7) to serialize complex events (as POJOs). It's working when run from within the IDE (IntelliJ), but when we package the jar-file and deploy it to the cluster we get:

java.lang.NoSuchMethodError: org.apache.avro.Schema.setLogicalType(Lorg/apache/avro/LogicalType;)V
at org.apache.avro.LogicalType.addToSchema(LogicalType.java:72)

However, it seems that we build the jar containing the right Avro package version (1.8.1) regarding the build output.

mvn clean package -Pbuild-jar
...
[INFO] Including org.apache.avro:avro:jar:1.8.1 in the shaded jar.
...

Question: How can we assure that our Flink cluster uses the correct Avro version (1.8.1)?

Our pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.group.flink</groupId>
<artifactId>cep</artifactId>
<version>0.2</version>
<packaging>jar</packaging>

<name>Complex Event Processing</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <flink.version>1.3.0</flink.version>
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
    <kafka.version>0.10.2.1</kafka.version>
    <scala.version>2.11</scala.version>
    <avro.version>1.8.1</avro.version>
    <junit.version>5.0.0-M4</junit.version>
</properties>

<repositories>
    <repository>
        <id>apache.snapshots</id>
        <name>Apache Development Snapshot Repository</name>
        <url>https://repository.apache.org/content/repositories/snapshots/</url>
        <releases>
            <enabled>false</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

<dependencies>

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-java</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-streaming-java_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-clients_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-cep_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-connector-kafka-0.10_${scala.version}</artifactId>
        <version>${flink.version}</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka_${scala.version}</artifactId>
        <version>${kafka.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.avro</groupId>
        <artifactId>avro</artifactId>
        <version>${avro.version}</version>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>${junit.version}</version>
    </dependency>
    <dependency>
        <groupId>com.github.smueller18</groupId>
        <artifactId>avro-builder</artifactId>
        <version>0.5</version>
    </dependency>
    <dependency>
        <groupId>com.github.smueller18</groupId>
        <artifactId>flink-serialization</artifactId>
        <version>0.6</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.9.9</version>
    </dependency>

</dependencies>

<profiles>
    <profile>

        <id>build-jar</id>

        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>

        <dependencies>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-java</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-streaming-java_${scala.version}</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.flink</groupId>
                <artifactId>flink-clients_${scala.version}</artifactId>
                <version>${flink.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>${slf4j.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>

        <build>
            <plugins>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-shade-plugin</artifactId>
                    <version>2.4.1</version>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>shade</goal>
                            </goals>
                            <configuration>
                                <artifactSet>
                                    <excludes combine.self="override"></excludes>
                                </artifactSet>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

<build>
    <plugins>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.4.1</version>
            <executions>

                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <artifactSet>
                            <excludes>

                                <exclude>org.apache.flink:flink-annotations</exclude>
                                <exclude>org.apache.flink:flink-shaded-hadoop2</exclude>
                                <exclude>org.apache.flink:flink-shaded-curator-recipes</exclude>
                                <exclude>org.apache.flink:flink-core</exclude>
                                <exclude>org.apache.flink:flink-java</exclude>
                                <exclude>org.apache.flink:flink-scala_2.11</exclude>
                                <exclude>org.apache.flink:flink-runtime_2.11</exclude>
                                <exclude>org.apache.flink:flink-optimizer_2.11</exclude>
                                <exclude>org.apache.flink:flink-clients_2.11</exclude>
                                <exclude>org.apache.flink:flink-avro_2.11</exclude>
                                <exclude>org.apache.flink:flink-examples-batch_2.11</exclude>
                                <exclude>org.apache.flink:flink-examples-streaming_2.11</exclude>
                                <exclude>org.apache.flink:flink-streaming-java_2.11</exclude>
                                <exclude>org.apache.flink:flink-streaming-scala_2.11</exclude>
                                <exclude>org.apache.flink:flink-scala-shell_2.11</exclude>
                                <exclude>org.apache.flink:flink-python</exclude>
                                <exclude>org.apache.flink:flink-metrics-core</exclude>
                                <exclude>org.apache.flink:flink-metrics-jmx</exclude>
                                <exclude>org.apache.flink:flink-statebackend-rocksdb_2.11</exclude>

                                <exclude>log4j:log4j</exclude>
                                <exclude>org.scala-lang:scala-library</exclude>
                                <exclude>org.scala-lang:scala-compiler</exclude>
                                <exclude>org.scala-lang:scala-reflect</exclude>
                                <exclude>com.data-artisans:flakka-actor_*</exclude>
                                <exclude>com.data-artisans:flakka-remote_*</exclude>
                                <exclude>com.data-artisans:flakka-slf4j_*</exclude>
                                <exclude>io.netty:netty-all</exclude>
                                <exclude>io.netty:netty</exclude>
                                <exclude>commons-fileupload:commons-fileupload</exclude>

                                <exclude>commons-collections:commons-collections</exclude>
                                <exclude>org.codehaus.jackson:jackson-core-asl</exclude>
                                <exclude>org.codehaus.jackson:jackson-mapper-asl</exclude>
                                <exclude>com.thoughtworks.paranamer:paranamer</exclude>
                                <exclude>org.xerial.snappy:snappy-java</exclude>
                                <exclude>org.apache.commons:commons-compress</exclude>
                                <exclude>org.tukaani:xz</exclude>
                                <exclude>com.esotericsoftware.kryo:kryo</exclude>
                                <exclude>com.esotericsoftware.minlog:minlog</exclude>
                                <exclude>org.objenesis:objenesis</exclude>
                                <exclude>com.twitter:chill_*</exclude>
                                <exclude>com.twitter:chill-java</exclude>
                                <exclude>commons-lang:commons-lang</exclude>
                                <exclude>junit:junit</exclude>
                                <exclude>org.apache.commons:commons-lang3</exclude>
                                <exclude>org.slf4j:slf4j-api</exclude>
                                <exclude>org.slf4j:slf4j-log4j12</exclude>
                                <exclude>log4j:log4j</exclude>
                                <exclude>org.apache.commons:commons-math</exclude>
                                <exclude>org.apache.sling:org.apache.sling.commons.json</exclude>
                                <exclude>commons-logging:commons-logging</exclude>
                                <exclude>commons-codec:commons-codec</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-core</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-databind</exclude>
                                <exclude>com.fasterxml.jackson.core:jackson-annotations</exclude>
                                <exclude>stax:stax-api</exclude>
                                <exclude>com.typesafe:config</exclude>
                                <exclude>org.uncommons.maths:uncommons-maths</exclude>
                                <exclude>com.github.scopt:scopt_*</exclude>
                                <exclude>commons-io:commons-io</exclude>
                                <exclude>commons-cli:commons-cli</exclude>
                            </excludes>
                        </artifactSet>
                        <filters>
                            <filter>
                                <artifact>org.apache.flink:*</artifact>
                                <excludes>

                                    <exclude>org/apache/flink/shaded/com/**</exclude>
                                    <exclude>web-docs/**</exclude>
                                </excludes>
                            </filter>
                            <filter>

                                <artifact>*:*</artifact>
                                <excludes>
                                    <exclude>META-INF/*.SF</exclude>
                                    <exclude>META-INF/*.DSA</exclude>
                                    <exclude>META-INF/*.RSA</exclude>
                                </excludes>
                            </filter>
                        </filters>

                        <createDependencyReducedPom>false</createDependencyReducedPom>
                    </configuration>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>

</build>

UPDATE: I build flink 1.3 from source and updated the avro version (from 1.7.7 to 1.8.1) in the project's pom.xml and it seems to work for now. Still unsure why it's not working when building the fat jar.

Body:
try to use latest version of avro

<dependency>
  <groupId>org.apache.avro</groupId>
  <artifactId>avro</artifactId>
  <version>1.8.2</version>
</dependency>


问:
What is devops?
What is devops?  It has something to do with combining dev and ops but I don't get it.</p>

答:
From Wikipedia:

DevOps is a set of processes, methods
  and systems for communication,
  collaboration and integration between
  departments for Development
  (Applications/Software Engineering),
  Technology Operations and Quality
  Assurance (QA)

Title: What is devops?


问:
Formatting output to a fixed precision in Python
I would like to have always 5 numbers after coma.

Example :
My data is like 105.56565  105. 165.54......

I want the same length like this: 105.56565 105.00000 165.54000....

script :

```<code>from pylab import*
from rtlsdr import*
from bluetooth import*
import sys

#configure device
sdr= RtlSdr()
sdr.sample_rate=double(sys.argv[3])
sdr.gain=double(sys.argv[2])
sdr.center_freq=double(sys.argv[1])

#Bluetooth connection

server_sock=BluetoothSocket(RFCOMM)
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port=server_sock.getsockname()[1]
uuid="94f39d29-7d6d-437d-973b-fba39e49d4ee"
client_sock,client_info=server_sock.accept()

while(1):
        samples=sdr.read_samples(256*1024)
        result=psd(samples,NFFT=1024, Fs=sdr.sample_rate/1e6, Fc=sdr.center_freq*1e6/1e6)
        freq=result[1]/1e6
        value_freq=str(freq)[1:-1]
        print format(freq, '%5f') // he do not work
</code>```

答:
On that last line, I think you want to do:

```<code>print "%5f" % freq
</code>```

Hope this helps!

Body:
I would like to have always 5 numbers after coma.

Example :
My data is like 105.56565  105. 165.54......

I want the same length like this: 105.56565 105.00000 165.54000....

script :

from pylab import*
from rtlsdr import*
from bluetooth import*
import sys

#configure device
sdr= RtlSdr()
sdr.sample_rate=double(sys.argv[3])
sdr.gain=double(sys.argv[2])
sdr.center_freq=double(sys.argv[1])

#Bluetooth connection

server_sock=BluetoothSocket(RFCOMM)
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port=server_sock.getsockname()[1]
uuid="94f39d29-7d6d-437d-973b-fba39e49d4ee"
client_sock,client_info=server_sock.accept()

while(1):
        samples=sdr.read_samples(256*1024)
        result=psd(samples,NFFT=1024, Fs=sdr.sample_rate/1e6, Fc=sdr.center_freq*1e6/1e6)
        freq=result[1]/1e6
        value_freq=str(freq)[1:-1]
        print format(freq, '%5f') // he do not work

Body:
On that last line, I think you want to do:

print "%5f" % freq

Hope this helps!


问:
Will CallableStatement.close() cause performance issue
I have a question about performance.

The app I work on is a Spring MVC app (v3.2.9). It's hosted on a WebSphere Application Server (v8.5.5). It is connected to an AS400 DB2 system (driver is  JTOpen v9.1). My app calls a stored procedure on an IBM AS400 system. It is being called using Spring's JdbcTemplate.execute method. Here's the code:

```<code>jdbcTemplate.execute(new CallableStatementCreator() {
        @Override
        public CallableStatement createCallableStatement(Connection con) throws SQLException {
            CallableStatement cs = con.prepareCall("{CALL XXXXXXSP ( ?, ? )}");
            cs.setString(1, xxx);
            cs.setString(2, xxx);
            return cs;
        }
    },
    new CallableStatementCallback<String>() {
        @Override
        public String doInCallableStatement(CallableStatement cs)throws SQLException, DataAccessException {
            cs.execute();
            return null;
        }
    });
</code>```

We're running into some issues where the calling of this procedure occasionally throws an error "[SQL0501] Cursor C1 not open" After turning up the logging and reviewing, it looks like this error only happens when the app attempts to re-use a CallableStatement. The respective cursor was closed the last time this CallableStatement was used, which results in the error (I'm not 100% sure if this re-use is expected behavior or not). The error happens around 20 times per day, which is a relatively low percentage as this application has much higher traffic.

My question is, will adding cs.close(); to the code after cs.execute(); cause a deterioration in the performance of the code?

答:
In general you should call close() method to close statement ,as it release resources. there is no any issue with this.

But JdbcTemplate close statement for you , so do not need it.

here is what JdbcTemplate  do at the end of execution execute(CallableStatementCreator csc, CallableStatementCallback<T> action) method :

```<code>JdbcUtils.closeStatement(cs);
DataSourceUtils.releaseConnection(con, getDataSource());
</code>```

And from CallableStatementCallback api :

```<code> doInCallableStatement(CallableStatement cs) throws SQLException ,DataAccessException
</code>```

Gets called by JdbcTemplate.execute with an active JDBC
  CallableStatement. Does not need to care about closing the Statement
  or the Connection, or about handling transactions: this will all be
  handled by Spring's JdbcTemplate. NOTE: Any ResultSets opened should
  be closed in finally blocks within the callback implementation. Spring
  will close the Statement object after the callback returned, but this
  does not necessarily imply that the ResultSet resources will be
  closed: the Statement objects might get pooled by the connection pool,
  with close calls only returning the object to the pool but not
  physically closing the resources.

Body:
I have a question about performance.

The app I work on is a Spring MVC app (v3.2.9). It's hosted on a WebSphere Application Server (v8.5.5). It is connected to an AS400 DB2 system (driver is  JTOpen v9.1). My app calls a stored procedure on an IBM AS400 system. It is being called using Spring's JdbcTemplate.execute method. Here's the code:

jdbcTemplate.execute(new CallableStatementCreator() {
        @Override
        public CallableStatement createCallableStatement(Connection con) throws SQLException {
            CallableStatement cs = con.prepareCall("{CALL XXXXXXSP ( ?, ? )}");
            cs.setString(1, xxx);
            cs.setString(2, xxx);
            return cs;
        }
    },
    new CallableStatementCallback<String>() {
        @Override
        public String doInCallableStatement(CallableStatement cs)throws SQLException, DataAccessException {
            cs.execute();
            return null;
        }
    });

We're running into some issues where the calling of this procedure occasionally throws an error "[SQL0501] Cursor C1 not open" After turning up the logging and reviewing, it looks like this error only happens when the app attempts to re-use a CallableStatement. The respective cursor was closed the last time this CallableStatement was used, which results in the error (I'm not 100% sure if this re-use is expected behavior or not). The error happens around 20 times per day, which is a relatively low percentage as this application has much higher traffic.

My question is, will adding cs.close(); to the code after cs.execute(); cause a deterioration in the performance of the code?

Body:
In general you should call close() method to close statement ,as it release resources. there is no any issue with this.

But JdbcTemplate close statement for you , so do not need it.

here is what JdbcTemplate  do at the end of execution execute(CallableStatementCreator csc, CallableStatementCallback<T> action) method :

JdbcUtils.closeStatement(cs);
DataSourceUtils.releaseConnection(con, getDataSource());

And from CallableStatementCallback api :

 doInCallableStatement(CallableStatement cs) throws SQLException ,DataAccessException

Gets called by JdbcTemplate.execute with an active JDBC
  CallableStatement. Does not need to care about closing the Statement
  or the Connection, or about handling transactions: this will all be
  handled by Spring's JdbcTemplate. NOTE: Any ResultSets opened should
  be closed in finally blocks within the callback implementation. Spring
  will close the Statement object after the callback returned, but this
  does not necessarily imply that the ResultSet resources will be
  closed: the Statement objects might get pooled by the connection pool,
  with close calls only returning the object to the pool but not
  physically closing the resources.


问:
Multiple inserts from multiple WITH/CTE
I have a table like this:

```<code>CREATE TABLE mytable
(
  col1 character varying(50),
  mydate timestamp without time zone
);
</code>```

I want to insert data to this table, but also I want to store the maximum id from my source:

```<code>insert into mytable (select myid, col1, mydate from sourcetable);
</code>```

I don't have a myid  column in mytable, and I can't ask later something like this: select max(myid) from sourcetable because I'm getting a snapshot and the sourcetable is a transactional table (hundreds of new records by second) so I need to get the maximum id from that snapshot

I tried something like this:

```<code>with query1 as (select myid, col1, mydate from sourcetable),
query2 as (select max(myid) id from query1)
insert into mytable (select co1, mydate from query1);
update anothertable set value=(select myid from query2) where col2='avalue';
</code>```

But I get this error:

```<code>ERROR:  relation "query2" does not exist
LINE 1: update anothertable set value=(select myid from query2) wher...
</code>```

Is there a way to solve this?

答:
The problem is that you have two queries after the CTEs.  Only one.  The CTE is connected to the queries.  So, just add another CTE.  Something like this:

```<code>with query1 as (
      select myid, col1, mydate
      from sourcetable
     ),
     query2 as (
      select max(myid) as id
      from query1
     ),
     i as (
      insert into mytable   -- You should really list the columns here
          select co1, mydate
          from query1
     )
update anothertable
    set value = (select myid from query2)
    where col2 = 'avalue';
</code>```

Title: Multiple inserts from multiple WITH/CTE

Body:
I have a table like this:

CREATE TABLE mytable
(
  col1 character varying(50),
  mydate timestamp without time zone
);

I want to insert data to this table, but also I want to store the maximum id from my source:

insert into mytable (select myid, col1, mydate from sourcetable);

I don't have a myid  column in mytable, and I can't ask later something like this: select max(myid) from sourcetable because I'm getting a snapshot and the sourcetable is a transactional table (hundreds of new records by second) so I need to get the maximum id from that snapshot

I tried something like this:

with query1 as (select myid, col1, mydate from sourcetable),
query2 as (select max(myid) id from query1)
insert into mytable (select co1, mydate from query1);
update anothertable set value=(select myid from query2) where col2='avalue';

But I get this error:

ERROR:  relation "query2" does not exist
LINE 1: update anothertable set value=(select myid from query2) wher...

Is there a way to solve this?

Body:
The problem is that you have two queries after the CTEs.  Only one.  The CTE is connected to the queries.  So, just add another CTE.  Something like this:

with query1 as (
      select myid, col1, mydate
      from sourcetable
     ),
     query2 as (
      select max(myid) as id
      from query1
     ),
     i as (
      insert into mytable   -- You should really list the columns here
          select co1, mydate
          from query1
     )
update anothertable
    set value = (select myid from query2)
    where col2 = 'avalue';


问:
Configuring Set-Cookie in IIS
I have to set requireSSL flag in my Classic ASP Application.

Is it possible to set it in IIS using HTTP Response Header configuration?

I have configured "X-Frame-Options" in IIS so I am hoping there should be something similar like Set-Cookie - secure in IIS Manager.

答:
Please check this post https://blogs.msdn.microsoft.com/rahulso/2007/06/19/cookies-case-study-with-ssl-and-frames-classic-asp/

TL;DR Now, enable SSL on your website. Open a command prompts and go to C:\Inetpub\AdminScripts
  Issue the following command and reset IIS> adsutil set
  w3svc/1/AspKeepSessionIDSecure 0.

Title: Configuring Set-Cookie in IIS


问:
big numbers from factorials
I'm working with factorials around 30! and I can't get a very good result for the value. I only want it accurate to 6 significant figures, or anything that gives a reasonable result. Currently my code is...

```<code>    static void Main(string[] args)
    {
        {
            int number = 30;
            long fact;
            factorial(number, out  fact);
        }
    }
    public static void factorial(int events, out  long  eventfact)
    {
        eventfact = 1;
        for (int tt = 1; tt <= events; tt++)
        {
            eventfact = eventfact * tt;
        }

    }
</code>```

This returns the result

```<code>-8764578968847253504
</code>```

this is far from

```<code>2.65252859812191E+32
</code>```

I've looked up about the different types of integers but nothing seems to be large enough for the numbers that I am working with.

Any help would be great!

答:
You can use this library, you should not have any problem with 30! with this.

https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx

You can do something like ( I dont have a compiler here so)

```<code>using System.Numerics;
    static void Main(string[] args)
    {
        {
            int number = 30;
            long fact;
            factorial(number, out  fact);
        }
    }
    public static void factorial(int events, out  BigInteger eventfact)
    {
        eventfact = 1;
        for (int tt = 1; tt <= events; tt++)
        {
            eventfact = BigInteger.Multiply(eventfact, tt); }

    }
</code>```

Title: big numbers from factorials

Body:
I'm working with factorials around 30! and I can't get a very good result for the value. I only want it accurate to 6 significant figures, or anything that gives a reasonable result. Currently my code is...

    static void Main(string[] args)
    {
        {
            int number = 30;
            long fact;
            factorial(number, out  fact);
        }
    }
    public static void factorial(int events, out  long  eventfact)
    {
        eventfact = 1;
        for (int tt = 1; tt <= events; tt++)
        {
            eventfact = eventfact * tt;
        }

    }

This returns the result

-8764578968847253504

this is far from

2.65252859812191E+32

I've looked up about the different types of integers but nothing seems to be large enough for the numbers that I am working with.

Any help would be great!

Body:
You can use this library, you should not have any problem with 30! with this.

https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx

You can do something like ( I dont have a compiler here so)

using System.Numerics;
    static void Main(string[] args)
    {
        {
            int number = 30;
            long fact;
            factorial(number, out  fact);
        }
    }
    public static void factorial(int events, out  BigInteger eventfact)
    {
        eventfact = 1;
        for (int tt = 1; tt <= events; tt++)
        {
            eventfact = BigInteger.Multiply(eventfact, tt); }

    }