问:
How to convert string to floating point number inside a Perl hash?
My motive is to convert the string number into floating point number while creating a hash.

I have placed my entire code and error below. Please help me to solve this issue.

Sample code

```<code>use strict;
use warnings;

use Data::Dumper;

my $price = 8.5;

my $g={};
$g->{'get'}=sprintf('%.02f',$price);

print Dumper($g);
</code>```

Current output

```<code>$VAR1 = {
          'get' => '8.50'
        };
</code>```

Expected output

```<code>$VAR1 = {
          'get' => 8.50
        };
</code>```

答:
I suspect you're worrying unnecessarily here. Perl treats strings and numbers as largely interchangeable and will generally do the right thing with data of either type. The number of times when you should care if you have a string or a number is tiny.

In fact, even if you explicitly give Perl a number in code like yours, it will be displayed as a string:

```<code>$ perl -MData::Dumper -E'say Dumper { get => 8.5 }'
$VAR1 = {
          'get' => '8.5'
        };
</code>```

Body:
My motive is to convert the string number into floating point number while creating a hash.

I have placed my entire code and error below. Please help me to solve this issue.

Sample code

use strict;
use warnings;

use Data::Dumper;

my $price = 8.5;

my $g={};
$g->{'get'}=sprintf('%.02f',$price);

print Dumper($g);

Current output

$VAR1 = {
          'get' => '8.50'
        };

Expected output

$VAR1 = {
          'get' => 8.50
        };

Body:
I suspect you're worrying unnecessarily here. Perl treats strings and numbers as largely interchangeable and will generally do the right thing with data of either type. The number of times when you should care if you have a string or a number is tiny.

In fact, even if you explicitly give Perl a number in code like yours, it will be displayed as a string:

$ perl -MData::Dumper -E'say Dumper { get => 8.5 }'
$VAR1 = {
          'get' => '8.5'
        };


来源: stackexchange

问:
How to model and create a custom deck of cards in rails?
I'm trying to model a card game in order to learn Rails. This is different than a standard deck of playing cards in that there can be multiple copies of a card in the deck. I'm running into problems while trying to initialize the deck. So far I've got a basic Card model with various attributes (such as copies_in_deck) but no associations. A DeckCard model which represents the cards in the deck (this is due to having multiples of the same card in the deck):

```<code>class DeckCard < ActiveRecord::Base
  belongs_to :card
  belongs_to :deck
end
</code>```

These DeckCards will eventually have attributes reflecting position; such as in discard pile, in draw pile, etc.

A Deck model with

```<code>belongs_to :game
has_many :deck_cards
</code>```

I'm trying to inialize the deck and am having various problems. I'm trying the following in Deck

```<code>def initialize
  @cards = Card.find(:all)
  @cards.each do |card|
    # eventually another loop here on copies_in_deck
      @deck_cards.build(card)
  end
end
</code>```

When I do Deck.new I get an error on nil.build.  Why is @deck_cards nil?

I'm using InstantRails2, which has rails 2.0.2. I found this article  about creating multiple models in one action, so I tried using Deck.create! instead, and got an error about the wrong number of arguments.

Any suggestions?

答:
subclasses of ActiveRecord should not define an initialize method since ActiveRecord takes care of that for you.

Sounds like you want one record per card. And the Model DeckCard can hold more than one pack of cards at a time.

Re:  Why is @deck_cards nil?
Because you haven't set it anywhere.

@deck_cards is an instance variable. You're trying to call the build method on it, but you haven't set it to anything. You should be calling the build (or create or new method) on the class DeckCard.

If you want to create and save a card in the DeckCard model:

    DeckCard.create(card) # not @deck_cards.build(card)

Larry

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to model a card game in order to learn Rails. This is different than a standard deck of playing cards in that there can be multiple copies of a card in the deck. I'm running into problems while trying to initialize the deck. So far I've got a basic Card model with various attributes (such as copies_in_deck) but no associations. A DeckCard model which represents the cards in the deck (this is due to having multiples of the same card in the deck):

class DeckCard < ActiveRecord::Base
  belongs_to :card
  belongs_to :deck
end

These DeckCards will eventually have attributes reflecting position; such as in discard pile, in draw pile, etc.

A Deck model with

belongs_to :game
has_many :deck_cards

I'm trying to inialize the deck and am having various problems. I'm trying the following in Deck

def initialize
  @cards = Card.find(:all)
  @cards.each do |card|
    # eventually another loop here on copies_in_deck
      @deck_cards.build(card)
  end
end

When I do Deck.new I get an error on nil.build.  Why is @deck_cards nil?

I'm using InstantRails2, which has rails 2.0.2. I found this article  about creating multiple models in one action, so I tried using Deck.create! instead, and got an error about the wrong number of arguments.

Any suggestions?

OwnerDisplayName: Larry K


问:
How to translate ListView texts?
My android application includes ListView binded with SimpleCursorAdapter to the database. This database contains column, which contains data like

```<code>somenameofrow
anothername
thirdname
</code>```

However instead of directly displaying these texts in the ListView, I would like to read according texts (actually - translations) from the Android resources.
How should I do it?

I think that I can use setViewValue for the same, name in the code below is TextView item, which displays my text:

```<code>case R.id.name:
    TextView elName = (TextView) view;
    elName.setText(getApplicationContext().getString(R.string.));
    return true;
</code>```

I am not sure how to understand what is correct id of the resource I am looking for (probably, cursor.getString(columnIndex) or elName.getText()) and how to get the value?

Upd. What if I exclude names from the database and will use ids instead. Will it help?

答:
If you read the android guide ListView tutorial, you will find:

Note that using a hard-coded string array is not the best design practice. One is used in this tutorial for simplicity, in order to demonstrate the ListView widget. The better practice is to reference a string array defined by an external resource, such as with a  resource in your project res/values/strings.xml file

Simply create different string-arrays items in res/values-XX, where XX are the locales you want to translate.

See the dev guide for more details about resources and i18n: http://developer.android.com/guide/topics/resources/localization.html

ContentLicense: CC BY-SA 3.0

Title: How to translate ListView texts?

Body:
My android application includes ListView binded with SimpleCursorAdapter to the database. This database contains column, which contains data like

somenameofrow
anothername
thirdname

However instead of directly displaying these texts in the ListView, I would like to read according texts (actually - translations) from the Android resources.
How should I do it?

I think that I can use setViewValue for the same, name in the code below is TextView item, which displays my text:

case R.id.name:
    TextView elName = (TextView) view;
    elName.setText(getApplicationContext().getString(R.string.));
    return true;

I am not sure how to understand what is correct id of the resource I am looking for (probably, cursor.getString(columnIndex) or elName.getText()) and how to get the value?

Upd. What if I exclude names from the database and will use ids instead. Will it help?


问:
WordPress > Get custom taxonomy from a custom post type

Installed Custom Post Type UI wordpress plugin

Created a custom post type  = 'products'

Registered a custom taxonomy categories (different from category) using

1. How to display all custom post types and have a filter above with categories that works as filter tabs?

2.How to loop in a custom template through the custom taxonomy 'categories' and display links?

HTML structure

Custom Post type URL :
/wp-admin/edit-tags.php?taxonomy=categories&post_type=products

PHP

```<code><?php get_term( $term, $taxonomy, $output, $filter ) ?>

<?php
$args=array(
  'name' => 'categories'
);
$output = 'products'; // or names
$taxonomies=get_taxonomies($args,$output);
if  ($taxonomies) {
  foreach ($taxonomies  as $taxonomy ) {
    echo '<p>' . $taxonomy->name . '</p>';
  }
}
?>

<?php
$args = array(
  'public'   => true,
  '_builtin' => false

);
$output = 'names'; // or objects
$operator = 'and'; // 'and' or 'or'
$taxonomies = get_taxonomies( $args, $output, $operator );
if ( $taxonomies ) {
  foreach ( $taxonomies  as $taxonomy ) {
    echo '<p>' . $taxonomy . '</p>';
  }
}
</code>```

答:
To find the taxonomies associated with a given post type, use the WordPress get_object_taxonomies() function like this:

$taxonomies = get_object_taxonomies('post', 'objects');
```
<p><code>$taxonomies</code> will be an array of <code>WP_Taxonomy</code> objects. Omit the second argument to get an array of taxonomy slugs.</p>
<p>To query by a custom taxonomy, create a new WP_Query something like this:</p>
<pre class="lang-php prettyprint-override"><code>$args = [
    'posts_per_page' => -1,
    'tax_query' => [
        [
            'taxonomy' => 'categories',
            'field' => 'slug',
            'terms' => ['your-term'],
        ],
    ],
];
$filterQuery = new WP_Query($args);
</code>```

While taxonomy associations can be declared on post_types using register_post_type, the association is optional and very weak. Internally, WordPress goes the other way and assigns post_types to Taxonomies.

Each Taxonomy has an object_type property which is an array of slugs for the post_types it knows about. Digging into the register_post_type source code, we see it calls register_taxonomy_for_object_type for each item in the  taxonomies argument property, then simply adds a slug to the Taxonomy's object_type array. This is the only time the post_type's taxonomy property is used. I prefer to declare post_types when registering the Taxonomy since it's closer to how WordPress works and misunderstanding that association caused me a lot of grief in the past.

Body:
Installed Custom Post Type UI wordpress plugin

Created a custom post type  = 'products'

Registered a custom taxonomy categories (different from category) using

1. How to display all custom post types and have a filter above with categories that works as filter tabs?

2.How to loop in a custom template through the custom taxonomy 'categories' and display links?

HTML structure

Custom Post type URL :
/wp-admin/edit-tags.php?taxonomy=categories&post_type=products

PHP

<?php get_term( $term, $taxonomy, $output, $filter ) ?>

<?php
$args=array(
  'name' => 'categories'
);
$output = 'products'; // or names
$taxonomies=get_taxonomies($args,$output);
if  ($taxonomies) {
  foreach ($taxonomies  as $taxonomy ) {
    echo '
' . $taxonomy->name . '
';
  }
}
?>

<?php
$args = array(
  'public'   => true,
  '_builtin' => false

);
$output = 'names'; // or objects
$operator = 'and'; // 'and' or 'or'
$taxonomies = get_taxonomies( $args, $output, $operator );
if ( $taxonomies ) {
  foreach ( $taxonomies  as $taxonomy ) {
    echo '
' . $taxonomy . '
';
  }
}

Body:
To find the taxonomies associated with a given post type, use the WordPress get_object_taxonomies() function like this:

$taxonomies = get_object_taxonomies('post', 'objects');

$taxonomies will be an array of WP_Taxonomy objects. Omit the second argument to get an array of taxonomy slugs.

To query by a custom taxonomy, create a new WP_Query something like this:

$args = [
    'posts_per_page' => -1,
    'tax_query' => [
        [
            'taxonomy' => 'categories',
            'field' => 'slug',
            'terms' => ['your-term'],
        ],
    ],
];
$filterQuery = new WP_Query($args);

While taxonomy associations can be declared on post_types using register_post_type, the association is optional and very weak. Internally, WordPress goes the other way and assigns post_types to Taxonomies.

Each Taxonomy has an object_type property which is an array of slugs for the post_types it knows about. Digging into the register_post_type source code, we see it calls register_taxonomy_for_object_type for each item in the  taxonomies argument property, then simply adds a slug to the Taxonomy's object_type array. This is the only time the post_type's taxonomy property is used. I prefer to declare post_types when registering the Taxonomy since it's closer to how WordPress works and misunderstanding that association caused me a lot of grief in the past.

ContentLicense: CC BY-SA 4.0


问:
How does m2e detect which profile to use for build?
I observe m2e picks up my desired profile for replacing properties during build.
Where does it get the profile from?
My parent pom has many profiles.
My profile is not present in activeProfiles section in settings.xml

All I do is right click on project and RUn as maven build.

答: In Eclipse oxygen you can see this and choose which profile is using m2e by right clicking on your project / Maven / Select Maven Profiles ...


问:
Vert.x: How to process event sequences in whole worker thread pool
My question is:

If I receive multiple event sequences in event loop threads, how could I process every sequence blocking and ordered but different sequences be processed by the whole worker thread pool.

Use case:

I have gRPC client in a vert.x with 4 event loop and 20 worker threads. I start remote calls in 10 threads.

Every call receives 2 events StreamObserver.onNext and   StreamObserver.onCompleted

On every such event I'd like to start blocking task in such way that for a gRPC call onNext and onClose
are ordered, while for different gRPC calls events are executed in
different worker threads.

The goal is to distribute call execution to as much worker threads as possible but events for single call to be ordered.

If I use executeBlocking with ordered true - they will be executed in a worker thread per event thread.

If false - there will be no order in processing onNext and onClose.

答:
I think it's a good usecase for Kafka.

You can keep working with a worker pool with every thread creating and listening kafka with a consumer. Instead of a worker pool, you can also instanciate multiple verticles in the same java process or even multiple jvm instances (or even containers, why not :p ). I prefer this second approach to handle the dynamic scalability in an event-driven and distributed architecture (I wrote more details about that in this answer).

Either way, all the consumers needs to be instanciate with the same group.id to be a part of the same group of consumers. That way, kafka will be able to assign the partitions of the topic to each group's member (a single partition cannot be read by two members at the same time).

And finally to be able to create "event sequences", you only need to produce the events in the kafka topic with a distribution key that will define your sequence (two messages produced with the same distribution key will be stored in the same partition and will be read by the same consumer of the group).


问:
What is wrong with my image slideshow? - Vanilla Javascript
I've coded a simple image slideshow using Vanilla JS which unfortunately isn't working. It's structured in a 'section', within a 'container'. The overflow of the container is hidden, and there are relative 'span' circles below it which I want to use to control the slideshow.

Here is my code so far:

// Variables

let i;
let image = document.getElementsByClassName("image");
let slideIndex = 1;
let dots = document.getElementsByClassName("dots");

// Functions

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showImage(n) {
  if (n > image.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = image.length;
  }

  for (i = 0; i < image.length; i++) {
    image[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace("active", "");
  }
  image[slideIndex-1].style.display = "block";
  dots[slideIndex-1].classList.add("active");
}

showImage(slideIndex);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  font-family: Helvetica;
}

.image-section {
  height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  background-color: #303960;
}

.image-container {
  height: 600px;
  width: 900px;
  overflow: hidden;
  background-color: #f9f9f9;
}

.image {
  height: 600px;
  width: 900px;
}

.image-controller {
  height: 10vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dots {
  height: 30px;
  width: 30px;
  border-radius: 100%;
  background-color: #fff;
  margin: 0 10px;
  cursor: pointer;
}

.active {
  background-color: #f96d80;
}</code>```

```

I'm assuming it's a problem with my for loop, but I could be wrong. Any advice would be great!

答:
Was this something you had in mind? You made the code a bit too complex.

I changed everything in your javascript code, because nothing really worked with all your different method names and how they were called. Thought it was easier for me to just type a few lines of code to show a different way of thinking.

Your images (it should be called "images", not "image" because there are several of them) and dots arrays start at position 0, so use that. Start by adding 0 as a parameter in your onclick method on your first dot element.

Then just keep track of the previous index (prevSelection) and remove the .active class from the previously selected image and dot, while adding .active to the newly selected image and dot. I added CSS style for .active for .image.

If you want to add a sliding animation, this is not the way to go, however.

// Variables

let images = document.getElementsByClassName("image");
let dots = document.getElementsByClassName("dots");

var prevSelection = 0;

function showSlides(slidePosition) {
  removeClass('active', prevSelection);
  addClass('active', slidePosition);

  prevSelection = slidePosition;
}

function removeClass(className, slidePosition) {
  dots  [slidePosition].classList.remove(className);
  images[slidePosition].classList.remove(className);
}

function addClass(className, slidePosition) {
  dots  [slidePosition].classList.add(className);
  images[slidePosition].classList.add(className);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  font-family: Helvetica;
}

.image-section {
  height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  background-color: #303960;
}

.image-container {
  height: 600px;
  width: 900px;
  overflow: hidden;
  background-color: #f9f9f9;
}

.image {
  display: none;
  height: 600px;
  width: 900px;
}

.image.active { /* added this */
  display: block;
}

.image-controller {
  height: 10vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dots {
  height: 30px;
  width: 30px;
  border-radius: 100%;
  background-color: #fff;
  margin: 0 10px;
  cursor: pointer;
}

.dots.active { /* added .dots for better clarity */
  background-color: #f96d80;
}</code>```

```

Body:
I've coded a simple image slideshow using Vanilla JS which unfortunately isn't working. It's structured in a 'section', within a 'container'. The overflow of the container is hidden, and there are relative 'span' circles below it which I want to use to control the slideshow.

Here is my code so far:

// Variables

let i;
let image = document.getElementsByClassName("image");
let slideIndex = 1;
let dots = document.getElementsByClassName("dots");

// Functions

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showImage(n) {
  if (n > image.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = image.length;
  }

  for (i = 0; i < image.length; i++) {
    image[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace("active", "");
  }
  image[slideIndex-1].style.display = "block";
  dots[slideIndex-1].classList.add("active");
}

showImage(slideIndex);

body {
  margin: 0;
  padding: 0;
  font-family: Helvetica;
}

.image-section {
  height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  background-color: #303960;
}

.image-container {
  height: 600px;
  width: 900px;
  overflow: hidden;
  background-color: #f9f9f9;
}

.image {
  height: 600px;
  width: 900px;
}

.image-controller {
  height: 10vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dots {
  height: 30px;
  width: 30px;
  border-radius: 100%;
  background-color: #fff;
  margin: 0 10px;
  cursor: pointer;
}

.active {
  background-color: #f96d80;
}

I'm assuming it's a problem with my for loop, but I could be wrong. Any advice would be great!

Body:
Was this something you had in mind? You made the code a bit too complex.

I changed everything in your javascript code, because nothing really worked with all your different method names and how they were called. Thought it was easier for me to just type a few lines of code to show a different way of thinking.

Your images (it should be called "images", not "image" because there are several of them) and dots arrays start at position 0, so use that. Start by adding 0 as a parameter in your onclick method on your first dot element.

Then just keep track of the previous index (prevSelection) and remove the .active class from the previously selected image and dot, while adding .active to the newly selected image and dot. I added CSS style for .active for .image.

If you want to add a sliding animation, this is not the way to go, however.

// Variables

let images = document.getElementsByClassName("image");
let dots = document.getElementsByClassName("dots");

var prevSelection = 0;

function showSlides(slidePosition) {
  removeClass('active', prevSelection);
  addClass('active', slidePosition);

  prevSelection = slidePosition;
}

function removeClass(className, slidePosition) {
  dots  [slidePosition].classList.remove(className);
  images[slidePosition].classList.remove(className);
}

function addClass(className, slidePosition) {
  dots  [slidePosition].classList.add(className);
  images[slidePosition].classList.add(className);
}

body {
  margin: 0;
  padding: 0;
  font-family: Helvetica;
}

.image-section {
  height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  background-color: #303960;
}

.image-container {
  height: 600px;
  width: 900px;
  overflow: hidden;
  background-color: #f9f9f9;
}

.image {
  display: none;
  height: 600px;
  width: 900px;
}

.image.active { /* added this */
  display: block;
}

.image-controller {
  height: 10vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dots {
  height: 30px;
  width: 30px;
  border-radius: 100%;
  background-color: #fff;
  margin: 0 10px;
  cursor: pointer;
}

.dots.active { /* added .dots for better clarity */
  background-color: #f96d80;
}

<section class="image-section">
      <div class="image-container">
        <div class="active image" style="background-color: black">

        </div>
        <div class="image" style="background-color: red">

        </div>
        <div class="image" style="background-color: blue">

        </div>
        <div class="image" style="background-color: orange">

        </div>
        <div class="image" style="background-color: purple">

        </div>
        <div class="image" style="background-color: brown">

        </div>
      </div>
      <div class="image-controller">
        <span class="active dots" onclick="showSlides(0)"></span>
        <span class="dots" onclick="showSlides(1)"></span>
        <span class="dots" onclick="showSlides(2)"></span>
        <span class="dots" onclick="showSlides(3)"></span>
        <span class="dots" onclick="showSlides(4)"></span>
        <span class="dots" onclick="showSlides(5)"></span>
      </div>
    </section>


问:
PHP String replace on certain lines only
I currently have a file such as this.

```<code>[Line 1] Hello
[Line 2] World
[Line 3] Hello World
</code>```

I wish to look for all lines containing "Hello" which would be Line 1 and 3.

Then I would like to change on that line all cases of "Line" to "Changed" so the output would be

```<code>[Changed 1] Hello
[Line 2] World
[Changed 3] Hello World
</code>```

With line two being untouched. I currently have code to locate all lines with Hello in them, but am unsure how to edit those lines alone and no other.

For example the code below does find all the lines, but also deletes everything in the process with the str_replace, so I know it's not str_replace I'm seeking.

```<code>$lines = file("lines.html");
$find = "Hello";
$repl = "Changed";
foreach($lines as $key => $line)
  if(stristr($line, $find)){$line = str_replace("$find","$repl",$line);}
</code>```

答:
To change anything, you will have to write a new file with the existing lines and the newly changed lines. Here is a simple example

```<code>// create a new output file
$out = fopen('test2.txt', 'w');

$input = file("lines.html");
$find = "Hello";
foreach($input as $key => $line){
    $tmp = $line;
    if(stristr($line, $find)){
        $tmp = str_replace('[Line', '[Changed', $line);
        // or if `[Line` can appear more than once in the line
        //$tmp = substr_replace($line, '[Changed', 0, 5);
    }
    fwrite($out, $tmp);
}
fclose($out);
</code>```

RESULT

```<code>[Changed 1] Hello
[Line 2] World
[Changed 3] Hello World
</code>```

Body:
I currently have a file such as this.

[Line 1] Hello
[Line 2] World
[Line 3] Hello World

I wish to look for all lines containing "Hello" which would be Line 1 and 3.

Then I would like to change on that line all cases of "Line" to "Changed" so the output would be

[Changed 1] Hello
[Line 2] World
[Changed 3] Hello World

With line two being untouched. I currently have code to locate all lines with Hello in them, but am unsure how to edit those lines alone and no other.

For example the code below does find all the lines, but also deletes everything in the process with the str_replace, so I know it's not str_replace I'm seeking.

$lines = file("lines.html");
$find = "Hello";
$repl = "Changed";
foreach($lines as $key => $line)
  if(stristr($line, $find)){$line = str_replace("$find","$repl",$line);}

Body:
To change anything, you will have to write a new file with the existing lines and the newly changed lines. Here is a simple example

// create a new output file
$out = fopen('test2.txt', 'w');

$input = file("lines.html");
$find = "Hello";
foreach($input as $key => $line){
    $tmp = $line;
    if(stristr($line, $find)){
        $tmp = str_replace('[Line', '[Changed', $line);
        // or if `[Line` can appear more than once in the line
        //$tmp = substr_replace($line, '[Changed', 0, 5);
    }
    fwrite($out, $tmp);
}
fclose($out);

RESULT

[Changed 1] Hello
[Line 2] World
[Changed 3] Hello World


问:
Is it possible to somehow shorten the code with changing the classlist state
Is it possible to somehow shorten the code with changing the classlist state. The code looks very confusing and incomprehensible. Every time we have to add or remove a class when we click on the Play button or when we run setInterval - when it expires or when we stop it ourselves. Can it be improved somehow?
Link to jsfiddle: https://jsfiddle.net/ameli7777/po7qdwk8/57/

const spinBlock = document.querySelector('.spin-block');
const spin = document.querySelector('.spin');
const spinStop = document.querySelector('.spin-stop');
const disableBtn = document.querySelectorAll('.dis');
const amountOfRotation = document.querySelector('.feature-block-list');
const countdownNumbValue = document.querySelector('.countdown-numb-value');
const countdown = document.querySelector('.countdown');
const autoButton = document.querySelector('.auto-button');
const stopActive = document.querySelector('.stop-active');
const autoSpinBlock = document.querySelector('.auto-spin-block');

  amountOfRotation.addEventListener('click', ({ target: { dataset } }) => {
    countdown.classList.remove('stop-game');
    autoButton.classList.add('stop-game');
    countdownNumbValue.innerHTML = dataset.count;
    spin.classList.add('stop-game');
    spinStop.classList.remove('stop-game');
    disableBtn.forEach(item => item.classList.add('disable-btn-clone'));
    spinBlock.classList.add('disable-btn-spin');
    let timerId = setInterval(() => {
      countdownNumbValue.innerHTML--;
        spinBlock.classList.toggle('spin-block-dis');
        stopActive.classList.toggle('stop-btn-inactive');
        autoSpinBlock.classList.add('disable-hover');
        if(countdownNumbValue.innerHTML <= 0) {
            clearInterval(timerId);
            countdown.classList.add('stop-game');
            autoButton.classList.remove('stop-game');
            spinBlock.classList.remove('spin-block-dis');
            autoSpinBlock.classList.remove('disable-hover');
            stopActive.classList.remove('stop-btn-inactive');
            spin.classList.remove('stop-game');
            spinStop.classList.add('stop-game');
            spinBlock.classList.remove('disable-btn-spin');
            disableBtn.forEach(item => item.classList.remove('disable-btn-clone'));
        };
    }, 1500);

    countdown.addEventListener('click', () => {
        countdown.classList.add('stop-game');
        autoButton.classList.remove('stop-game');
        spin.classList.remove('stop-game');
        spinStop.classList.add('stop-game');
        spinBlock.classList.remove('disable-btn-spin');
        spinBlock.classList.remove('spin-block-dis');
        clearInterval(timerId);
        autoSpinBlock.classList.remove('disable-hover');
        stopActive.classList.remove('stop-btn-inactive');
        disableBtn.forEach(item => item.classList.remove('disable-btn-clone'));
    })
  });

spinBlock.addEventListener('click', () => {
    spin.classList.toggle('stop-game');
    spinStop.classList.toggle('stop-game');
    disableBtn.forEach(item => item.classList.toggle('disable-btn-clone'));
    autoSpinBlock.classList.toggle('disable-hover');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
display: flex;
margin-top: 20%;
}
.button-plus, .button-minus {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}
.button-minus-block {
    width: 33%;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 88%;
    margin-left: 2%;
}
.button-plus-block {
    width: 33%;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 88%;
    margin-right: 2%;
}
.bet-block {
    width: 15.5%;
    display: flex;
    align-items: center;
    height: 41px;
    margin-left: 0.5%;
    margin-top: 2.5%;
}

.total-count, .coin-count {
    color: #ffd100;
    margin: 0;
    font-size: 12px;
}

.auto-button {
    width: 24%;
    display: flex;
    margin-left: 20%;
    margin-top: 1%;
}
.auto-block {
    width: 90%;
    height: 41px;
    display: flex;
    align-items: center;
    cursor: pointer;
    z-index: 100;
}

.spin-block {
    background: yellow;
    display: flex;
    align-items: center;
    z-index: 100;
    width: 112px;
    height: 112px;
    justify-content: center;
    cursor: pointer;
}
.spin-block-dis {
    background: red;
}
.spin {
    width: 70%;
    height: 62px;
}
.spin-stop {
    width: 48%;
}
.feature-block {
    position: absolute;
    margin-left: 6px;
    /* bottom: 70%; */
    width: 8%;
    height: 122px;
    z-index: -1;
    max-height: 0px;
    overflow: hidden;
    /* transition: max-height 0.4s linear; */
    margin-top: -120px;
}
.feature-block ul {
    list-style-type: none;
    color: #ffd100;
    font-size: 14px;
    padding: 10%;
    margin-top: -10%;
}
.feature-block p {
    color: #ffd100;
    font-size: 10px;
    padding: 10%;
    margin: 0;
    padding-bottom: 0;
}
.feature-block ul li:hover {
    color: white;
    cursor: pointer;
}
.auto-spin-block {
    width: 18%;
    height: 41px;
    margin-top: 2.5%;
    margin-left: 0.5%;
    z-index: 10;
}
.auto-spin-block:hover .feature-block {
    max-height: 160px;
    height: 122px;
}
.disable-btn-clone {
    pointer-events: none;
    opacity: 0.4;
}
.disable-btn-spin {
    pointer-events: none;
}
.countdown-txt {
    color: #3d0000;
}
.countdown {
    width: 55%;
    display: flex;
    align-items: center;
    margin-left: 9%;
}
.countdown-numb {
    width: 29px;
    color: #ffd100;
    height: 29px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 5%;
}
.stop-game {
    display: none;
}
.stop-btn-inactive {
    opacity: 0.3;
}
.disable-hover:hover .feature-block {
    max-height: 0px;
    height: 122px;
}</code>```

                        <button>
                        -
                        </button>

TOTAL

$1.50

                       <button>
                       +
                       </button>

                        hover on

                        STOP

25

20

15

10

5

                    Play

                    Stop

```

答:
One simple solution is to look at the body tag as the control tag, so you would toggle a SINGLE class on the BODY for example:

```<code>document.body.classList.toggle("game-stopped");
</code>```

Then on each element that you are HIDING with your stop-game class, give them all the same class like (where game-element is the new class)

```<code><div class="auto-button game-element dis">
<p>hover on</p>
</div>
</code>```

Then create the following CSS:

```<code>.game-stopped .game-element{display:none;}
</code>```

What you are doing is when you give body the class of game-stopped, EVERY element that you has 'game-element' class, will be hidden.

Body:
Is it possible to somehow shorten the code with changing the classlist state. The code looks very confusing and incomprehensible. Every time we have to add or remove a class when we click on the Play button or when we run setInterval - when it expires or when we stop it ourselves. Can it be improved somehow?
Link to jsfiddle: https://jsfiddle.net/ameli7777/po7qdwk8/57/

const spinBlock = document.querySelector('.spin-block');
const spin = document.querySelector('.spin');
const spinStop = document.querySelector('.spin-stop');
const disableBtn = document.querySelectorAll('.dis');
const amountOfRotation = document.querySelector('.feature-block-list');
const countdownNumbValue = document.querySelector('.countdown-numb-value');
const countdown = document.querySelector('.countdown');
const autoButton = document.querySelector('.auto-button');
const stopActive = document.querySelector('.stop-active');
const autoSpinBlock = document.querySelector('.auto-spin-block');

  amountOfRotation.addEventListener('click', ({ target: { dataset } }) => {
    countdown.classList.remove('stop-game');
    autoButton.classList.add('stop-game');
    countdownNumbValue.innerHTML = dataset.count;
    spin.classList.add('stop-game');
    spinStop.classList.remove('stop-game');
    disableBtn.forEach(item => item.classList.add('disable-btn-clone'));
    spinBlock.classList.add('disable-btn-spin');
    let timerId = setInterval(() => {
      countdownNumbValue.innerHTML--;
        spinBlock.classList.toggle('spin-block-dis');
        stopActive.classList.toggle('stop-btn-inactive');
        autoSpinBlock.classList.add('disable-hover');
        if(countdownNumbValue.innerHTML <= 0) {
            clearInterval(timerId);
            countdown.classList.add('stop-game');
            autoButton.classList.remove('stop-game');
            spinBlock.classList.remove('spin-block-dis');
            autoSpinBlock.classList.remove('disable-hover');
            stopActive.classList.remove('stop-btn-inactive');
            spin.classList.remove('stop-game');
            spinStop.classList.add('stop-game');
            spinBlock.classList.remove('disable-btn-spin');
            disableBtn.forEach(item => item.classList.remove('disable-btn-clone'));
        };
    }, 1500);

    countdown.addEventListener('click', () => {
        countdown.classList.add('stop-game');
        autoButton.classList.remove('stop-game');
        spin.classList.remove('stop-game');
        spinStop.classList.add('stop-game');
        spinBlock.classList.remove('disable-btn-spin');
        spinBlock.classList.remove('spin-block-dis');
        clearInterval(timerId);
        autoSpinBlock.classList.remove('disable-hover');
        stopActive.classList.remove('stop-btn-inactive');
        disableBtn.forEach(item => item.classList.remove('disable-btn-clone'));
    })
  });

spinBlock.addEventListener('click', () => {
    spin.classList.toggle('stop-game');
    spinStop.classList.toggle('stop-game');
    disableBtn.forEach(item => item.classList.toggle('disable-btn-clone'));
    autoSpinBlock.classList.toggle('disable-hover');
});

.wrapper {
display: flex;
margin-top: 20%;
}
.button-plus, .button-minus {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}
.button-minus-block {
    width: 33%;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 88%;
    margin-left: 2%;
}
.button-plus-block {
    width: 33%;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 88%;
    margin-right: 2%;
}
.bet-block {
    width: 15.5%;
    display: flex;
    align-items: center;
    height: 41px;
    margin-left: 0.5%;
    margin-top: 2.5%;
}

.total-count, .coin-count {
    color: #ffd100;
    margin: 0;
    font-size: 12px;
}

.auto-button {
    width: 24%;
    display: flex;
    margin-left: 20%;
    margin-top: 1%;
}
.auto-block {
    width: 90%;
    height: 41px;
    display: flex;
    align-items: center;
    cursor: pointer;
    z-index: 100;
}

.spin-block {
    background: yellow;
    display: flex;
    align-items: center;
    z-index: 100;
    width: 112px;
    height: 112px;
    justify-content: center;
    cursor: pointer;
}
.spin-block-dis {
    background: red;
}
.spin {
    width: 70%;
    height: 62px;
}
.spin-stop {
    width: 48%;
}
.feature-block {
    position: absolute;
    margin-left: 6px;
    /* bottom: 70%; */
    width: 8%;
    height: 122px;
    z-index: -1;
    max-height: 0px;
    overflow: hidden;
    /* transition: max-height 0.4s linear; */
    margin-top: -120px;
}
.feature-block ul {
    list-style-type: none;
    color: #ffd100;
    font-size: 14px;
    padding: 10%;
    margin-top: -10%;
}
.feature-block p {
    color: #ffd100;
    font-size: 10px;
    padding: 10%;
    margin: 0;
    padding-bottom: 0;
}
.feature-block ul li:hover {
    color: white;
    cursor: pointer;
}
.auto-spin-block {
    width: 18%;
    height: 41px;
    margin-top: 2.5%;
    margin-left: 0.5%;
    z-index: 10;
}
.auto-spin-block:hover .feature-block {
    max-height: 160px;
    height: 122px;
}
.disable-btn-clone {
    pointer-events: none;
    opacity: 0.4;
}
.disable-btn-spin {
    pointer-events: none;
}
.countdown-txt {
    color: #3d0000;
}
.countdown {
    width: 55%;
    display: flex;
    align-items: center;
    margin-left: 9%;
}
.countdown-numb {
    width: 29px;
    color: #ffd100;
    height: 29px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 5%;
}
.stop-game {
    display: none;
}
.stop-btn-inactive {
    opacity: 0.3;
}
.disable-hover:hover .feature-block {
    max-height: 0px;
    height: 122px;
}

                        <button>
                        -
                        </button>

TOTAL

$1.50

                       <button>
                       +
                       </button>

                        hover on

                        STOP

25

20

15

10

5

                    Play

                    Stop

Body:
One simple solution is to look at the body tag as the control tag, so you would toggle a SINGLE class on the BODY for example:

document.body.classList.toggle("game-stopped");

Then on each element that you are HIDING with your stop-game class, give them all the same class like (where game-element is the new class)

<div class="auto-button game-element dis">
<p>hover on</p>
</div>

Then create the following CSS:

.game-stopped .game-element{display:none;}

What you are doing is when you give body the class of game-stopped, EVERY element that you has 'game-element' class, will be hidden.


问:
Why are values in the console but not being displayed in the page?
Values are not displayed on page, but are displayed in console.log

```<code>//app.components.ts
    import { Component } from '@angular/core';
import {AngularFireDatabase } from 'angularfire2/database';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  posts: any[];
  constructor(db: AngularFireDatabase){
    db.list('posts').valueChanges().subscribe(posts => {  this.posts = posts; console.log(this.posts); });

  }
}

//app.component.html

    <ul>
  <li *ngFor="let post of posts">
{{post.$value}}
  </li>
</ul>
</code>```

//firebase

答:
```<code><ul>
  <li *ngFor="let post of posts">
{{post}}
  </li>
</ul>
</code>```

Body:
Values are not displayed on page, but are displayed in console.log

//app.components.ts
    import { Component } from '@angular/core';
import {AngularFireDatabase } from 'angularfire2/database';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  posts: any[];
  constructor(db: AngularFireDatabase){
    db.list('posts').valueChanges().subscribe(posts => {  this.posts = posts; console.log(this.posts); });

  }
}

//app.component.html

{{post.$value}}

//firebase


问:
Creating multiple buttons with tkinter
I'm trying to create several buttons with tkinter in a for loop, but I'm having some trouble with the command passed to them and, since the number of buttons I'll need to create isn't fixed, I can't create them manually (minesweeper game).

The buttons are correctly created and displayed in grid form, but the command is the same for all (that of the last button created).

My code looks something like:

```<code>rows = 5
columns = 5
buttons_dict = {}

for i, row in enumerate(range(rows)):
    for j, column in enumerate(range(columns)):

        buttons_dict[(i, j)] = tk.Button(top_board_frame, command=lambda: btn_click(i, j))
        buttons_dict[(i, j)].grid(row=i, column=j)
</code>```

My intention is to pass each button a function that, on click, returns the buttons' coordinates. Something like:

```<code>def btn_click(i, j):
    current_pair = (i, j)
    print(current_pair)
</code>```

The problem with the code above is it return the coordinates of the last button created, no matter which button is clicked.

答:
You could do something like this. Pass a reference to the button in the command.</p>

```<code>btn = buttons_dict[(i, j)] = tk.Button(top_board_frame)
btn.configure(command=lambda: btn_click(btn, i, j))
</code>```

Title: Creating multiple buttons with tkinter

Body:
I'm trying to create several buttons with tkinter in a for loop, but I'm having some trouble with the command passed to them and, since the number of buttons I'll need to create isn't fixed, I can't create them manually (minesweeper game).

The buttons are correctly created and displayed in grid form, but the command is the same for all (that of the last button created).

My code looks something like:

rows = 5
columns = 5
buttons_dict = {}

for i, row in enumerate(range(rows)):
    for j, column in enumerate(range(columns)):

        buttons_dict[(i, j)] = tk.Button(top_board_frame, command=lambda: btn_click(i, j))
        buttons_dict[(i, j)].grid(row=i, column=j)

My intention is to pass each button a function that, on click, returns the buttons' coordinates. Something like:

def btn_click(i, j):
    current_pair = (i, j)
    print(current_pair)

The problem with the code above is it return the coordinates of the last button created, no matter which button is clicked.

Body:
You could do something like this. Pass a reference to the button in the command.

btn = buttons_dict[(i, j)] = tk.Button(top_board_frame)
btn.configure(command=lambda: btn_click(btn, i, j))


问:
Java Spring JPA magical update
I am having two Entities:
Aircraft

```<code>import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
//@ToString
public class Aircraft extends AbstractPersistable<Long> {

    private String name;
    @ManyToOne
    private Airport airport;

    @Override
    public String toString(){
        return name;
    }
}
</code>```

And Airport:

```<code>public class Airport extends AbstractPersistable<Long> {

    private String identifier;
    private String name;
    @OneToMany(mappedBy = "airport")
    private List<Aircraft> aircrafts = new ArrayList<>();

    @Override
    public String toString(){
        String aircraftString = aircrafts.stream().map(r -> r.toString()).collect(Collectors.joining(", "));
        return "airport " + name + " " + "[" + aircraftString + "]";
    }
}
</code>```

And a @PostMapping in @Controller like this:

```<code>@PostMapping("/aircrafts/{aircraftId}/airports")
    public String assignAirport(@RequestParam Long airportId,@PathVariable Long aircraftId){
        Aircraft aircraft = aircraftRepository.getOne(aircraftId);
        Airport airport = airportRepository.getOne(airportId);

        aircraft.setAirport(airport);
        aircraftRepository.save(aircraft)
        System.out.println(airport.toString());
        System.out.println(aircraft.toString());
        return "redirect:/aircrafts";
    }
</code>```

This works. But I can not figure out how does this

```<code>private List<Aircraft> aircrafts = new ArrayList<>();
</code>```

List get updated?
I first figured it should work like this in @Controller

```<code>airport.getAircrafts().add(aircraft);
</code>```

But that does not do anything.

答:
The OneToMany relation in the airport class only reflecting what is persisted in the ManyToOne relation in the aircraft class so whenever you will add a new plane that has an airport, this airport planes List will be updated.
Side Note:
  If you want to achieve the behavior you were expecting you can add

```<code> @OneToMany(mappedBy = "airport", cascade = CascadeType.ALL)
 private List<Aircraft> aircrafts = new ArrayList<>();

 public void addAircraft(Aircraft aircraft){
     aircraft.setAirport(this);
     aircrafts.add(aircraft);
 }
</code>```

to your airport class and then save the airport entity.
but I think this isn't what you want and also it's not beneficial in your current case

Title: Java Spring JPA magical update

Body:
I am having two Entities:
Aircraft

import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
//@ToString
public class Aircraft extends AbstractPersistable<Long> {

    private String name;
    @ManyToOne
    private Airport airport;

    @Override
    public String toString(){
        return name;
    }
}

And Airport:

public class Airport extends AbstractPersistable<Long> {

    private String identifier;
    private String name;
    @OneToMany(mappedBy = "airport")
    private List<Aircraft> aircrafts = new ArrayList<>();

    @Override
    public String toString(){
        String aircraftString = aircrafts.stream().map(r -> r.toString()).collect(Collectors.joining(", "));
        return "airport " + name + " " + "[" + aircraftString + "]";
    }
}

And a @PostMapping in @Controller like this:

@PostMapping("/aircrafts/{aircraftId}/airports")
    public String assignAirport(@RequestParam Long airportId,@PathVariable Long aircraftId){
        Aircraft aircraft = aircraftRepository.getOne(aircraftId);
        Airport airport = airportRepository.getOne(airportId);

        aircraft.setAirport(airport);
        aircraftRepository.save(aircraft)
        System.out.println(airport.toString());
        System.out.println(aircraft.toString());
        return "redirect:/aircrafts";
    }

This works. But I can not figure out how does this

private List<Aircraft> aircrafts = new ArrayList<>();

List get updated?
I first figured it should work like this in @Controller

airport.getAircrafts().add(aircraft);

But that does not do anything.

Body:
The OneToMany relation in the airport class only reflecting what is persisted in the ManyToOne relation in the aircraft class so whenever you will add a new plane that has an airport, this airport planes List will be updated.
Side Note:
  If you want to achieve the behavior you were expecting you can add

 @OneToMany(mappedBy = "airport", cascade = CascadeType.ALL)
 private List<Aircraft> aircrafts = new ArrayList<>();

 public void addAircraft(Aircraft aircraft){
     aircraft.setAirport(this);
     aircrafts.add(aircraft);
 }

to your airport class and then save the airport entity.
but I think this isn't what you want and also it's not beneficial in your current case


问:
echoing text field value in a while loop
```<code>echo " <table bgcolor='#d3fcfe'   align='center'>  ";

while ($row = mysql_fetch_array($result)) {

echo '</div> <tr onmouseout="this.bgColor=\'#d3fcfe\';"  onmouseover= "this   .bgColor=\'#fffdcd\';" >  ';
 $numq2=$row['username'] ;

{
echo '<td ><div class="iddiv"> <input name="" type="text" value="$numq2" />   <div>    </td> ';
}

echo '  </table>';
}
</code>```

<p>i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script? </p>

答:
wrong quote use.

use either

```<code>echo '...value="'.$numq2.'" />...';
</code>```

or

```<code>echo " ... value=\"$numq2\" /> ...";
</code>```

Body:
echo "
  ";

while ($row = mysql_fetch_array($result)) {

echo '

  ';
 $numq2=$row['username'] ;

{
echo '
 <input name="" type="text" value="$numq2" />
    	 ';
}

echo '
';
}

i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script?

Body:
wrong quote use.

use either

echo '...value="'.$numq2.'" />...';

or

echo " ... value=\"$numq2\" /> ...";


问:
Length of the key to encrypt a file
Many years ago I used this code to encrypt an entire file:

```<code>    public static void CryptFile(string sInputFilename, string sOutputFilename, string sKey)
    {
        FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);

        FileStream fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);
        DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
        ICryptoTransform desencrypt = DES.CreateEncryptor();
        CryptoStream cryptostream = new CryptoStream(fsEncrypted,desencrypt,CryptoStreamMode.Write);

        byte[] bytearrayinput = new byte[fsInput.Length];
        fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
        cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
        cryptostream.Close();
        fsInput.Close();
        fsEncrypted.Close();
    }
</code>```

Today I tried to use it again but I always get this error:
the specified key size is not valid for this algorithm.
I have tried with many strings of varying length but cannot understand which is the correct length to use.

答: The correct length is 8 characters, such as "12345678"</p>

Title: Length of the key to encrypt a file

Body:
Many years ago I used this code to encrypt an entire file:

    public static void CryptFile(string sInputFilename, string sOutputFilename, string sKey)
    {
        FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);

        FileStream fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);
        DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
        ICryptoTransform desencrypt = DES.CreateEncryptor();
        CryptoStream cryptostream = new CryptoStream(fsEncrypted,desencrypt,CryptoStreamMode.Write);

        byte[] bytearrayinput = new byte[fsInput.Length];
        fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
        cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
        cryptostream.Close();
        fsInput.Close();
        fsEncrypted.Close();
    }

Today I tried to use it again but I always get this error:
the specified key size is not valid for this algorithm.
I have tried with many strings of varying length but cannot understand which is the correct length to use.


问:
Microsoft Teams webhook on TFS
I have discovered Microsoft Teams and I like it.
I am now trying to trigger pullrequest messages from TFS to Microsoft Teams.
I have a Teams Group webhook url that works fine with curl.
But when I test it with TFS (Service Hooks -> Web Hooks) then I only get bad requests.
Do any of you have an idea why that could be? </p>

答:
Maybe you figure it out by now cause obviously the question was asked 3 years ago, but I wanted to post my answer in order to help other people in the future.
There actually a way to hook TFS with Microsoft Teams yay!!
From TFS go to Service Hooks --> office 365 instead of (Service Hooks -> Web Hooks) because "Microsoft teams" is part of the suite 365 and as easy as that :).

PS: Of course you need to create a channel on Teams first, then click on the 3 dots --> Connectors --> Incoming Webhooks(configure) --> give your hook a name --> Create. And you're done; just copy the link generated by Teams and past it in TFS when u're asked for it ;)

Title: Microsoft Teams webhook on TFS


问:
Is there a way to recursively find the different ways a set of numbers can add up to a certain number?
I want to be able to find all the different ways a set of numbers(x) can be summed into a certain value, y but I'm having trouble even getting the base case right.

For example:

If I have x = set (1,2,3,4,5) and I want to see how many different ways y = 5 can be summed up using numbers from x:

my recursive function would return 7 because:

```<code>'''
5
4+1
3+2
3+1+1
2+2+1
2+1+1+1
1+1+1+1+1
'''
def recur(x,y):
    if y == x:
        v += 1
    if y > x:
        v += 0
    else:
         #call recursively
</code>```

答:
This does not use recursion, but itertools.combinations_with_replacement:

```<code>def all_combs(y, x=range(1, 5+1)):
    all_combs = []
    for i in range(1, y+1):
        combs = combinations_with_replacement(x, i)
        all_combs.extend([comb for comb in combs if sum(comb) == y])
    return all_combs

combs = all_combs(5)
# [(5,), (1, 4), (2, 3), (1, 1, 3), (1, 2, 2), (1, 1, 1, 2), (1, 1, 1, 1, 1)]
num_combs = len(combs) # 7
</code>```

Body:
I want to be able to find all the different ways a set of numbers(x) can be summed into a certain value, y but I'm having trouble even getting the base case right.

For example:

If I have x = set (1,2,3,4,5) and I want to see how many different ways y = 5 can be summed up using numbers from x:

my recursive function would return 7 because:

'''
5
4+1
3+2
3+1+1
2+2+1
2+1+1+1
1+1+1+1+1
'''
def recur(x,y):
    if y == x:
        v += 1
    if y > x:
        v += 0
    else:
         #call recursively

Body:
This does not use recursion, but itertools.combinations_with_replacement:

def all_combs(y, x=range(1, 5+1)):
    all_combs = []
    for i in range(1, y+1):
        combs = combinations_with_replacement(x, i)
        all_combs.extend([comb for comb in combs if sum(comb) == y])
    return all_combs

combs = all_combs(5)
# [(5,), (1, 4), (2, 3), (1, 1, 3), (1, 2, 2), (1, 1, 1, 2), (1, 1, 1, 1, 1)]
num_combs = len(combs) # 7


问:
Can't pop git stash, 'Your local changes to the following files would be overwritten by merge'
So I had a load of changes and some untracked files. I needed to tweak something, so I used git stash -u, modified a couple of things, committed those changes, pushed them, and then tried to git stash pop.

Because I'd modified a couple of files that I'd stashed, I got the following message:

```<code>error: Your local changes to the following files would be overwritten by merge:
    file_1.py
    file_2.py
Please, commit your changes or stash them before you can merge.
Aborting
</code>```

This seems odd, I had committed all new changes, my checkout was clean when I ran the command.

It seems the git stash pop operation un-stashed half of my changes and the untracked files, but if I try and git stash pop again I get output like:

```<code>some_file.html already exists, no checkout
some_other_file.html already exists, no checkout
yet_another_file.html already exists, no checkout
Could not restore untracked files from stash
</code>```

git stash show still shows a list of my stashed changes, but I'm at a loss as to what I do now.

How can I get myself unstuck?

答: None of these solutions worked for me. I was using git stash index command to restore a specific stash id. So, I ended up doing a commit of my local changes to local repo. Then git stash index worked for me. And finally I rolled back my commit using git reset (with keep changes). Problem solved.</p>

Body:
So I had a load of changes and some untracked files. I needed to tweak something, so I used git stash -u, modified a couple of things, committed those changes, pushed them, and then tried to git stash pop.

Because I'd modified a couple of files that I'd stashed, I got the following message:

error: Your local changes to the following files would be overwritten by merge:
    file_1.py
    file_2.py
Please, commit your changes or stash them before you can merge.
Aborting

This seems odd, I had committed all new changes, my checkout was clean when I ran the command.

It seems the git stash pop operation un-stashed half of my changes and the untracked files, but if I try and git stash pop again I get output like:

some_file.html already exists, no checkout
some_other_file.html already exists, no checkout
yet_another_file.html already exists, no checkout
Could not restore untracked files from stash

git stash show still shows a list of my stashed changes, but I'm at a loss as to what I do now.

How can I get myself unstuck?


问:
spring-boot-starter-web with web application type NONE. Why?
I had never used CommandLineRunner before, because I've always written web servers. This time I'm building a microservice (CRON job) that wakes up, make some rest and db calls, and stops.

For this project, like others, initially I had the following dependency:

```<code>implementation "org.springframework.boot:spring-boot-starter-web:$springBootVersion"
</code>```

Until I found out there is something called CommandLineRunner and, as I don't need a web server running, I can actually turn it off by .setWebApplicationType(WebApplicationType.NONE);

Now I'm wondering what's the point of including spring-boot-starter-web if we turn off its web server? I'm using Spring Boot framework to use its dependencies by default (things like jackson, etc.) and for its dependency management framework.

(Side note: I tried to move to sprint-boot-starter but there the following issue that I couldn't resolve, so I think I keep using spring-boot-starter-web :

Correct the classpath of your application so that it contains a single, compatible version of org.springframework.http.converter.json.Jackson2ObjectMapperBuilder)

答:
We can see that spring-boot-starter-web includes:

```<code>spring-boot-starter
spring-boot-starter-json
spring-boot-starter-tomcat
spring-web
spring-webmvc
hibernate-validator
</code>```

Looking at where Jackson2ObjectMapperBuilder is located we can see that it is in spring-web which is included by spring-boot-starter-json.

I suspect if you add spring-boot-starter-json you will be one step closer to running your service without the web server component.

Maven dependency analyzers can save quite a bit of trouble in the future by starting at the top and looking at what each of the POM files include.

Body:
I had never used CommandLineRunner before, because I've always written web servers. This time I'm building a microservice (CRON job) that wakes up, make some rest and db calls, and stops.

For this project, like others, initially I had the following dependency:

implementation "org.springframework.boot:spring-boot-starter-web:$springBootVersion"

Until I found out there is something called CommandLineRunner and, as I don't need a web server running, I can actually turn it off by .setWebApplicationType(WebApplicationType.NONE);

Now I'm wondering what's the point of including spring-boot-starter-web if we turn off its web server? I'm using Spring Boot framework to use its dependencies by default (things like jackson, etc.) and for its dependency management framework.

(Side note: I tried to move to sprint-boot-starter but there the following issue that I couldn't resolve, so I think I keep using spring-boot-starter-web :

Correct the classpath of your application so that it contains a single, compatible version of org.springframework.http.converter.json.Jackson2ObjectMapperBuilder)

Body:
We can see that spring-boot-starter-web includes:

spring-boot-starter
spring-boot-starter-json
spring-boot-starter-tomcat
spring-web
spring-webmvc
hibernate-validator

Looking at where Jackson2ObjectMapperBuilder is located we can see that it is in spring-web which is included by spring-boot-starter-json.

I suspect if you add spring-boot-starter-json you will be one step closer to running your service without the web server component.

Maven dependency analyzers can save quite a bit of trouble in the future by starting at the top and looking at what each of the POM files include.


问:
Native debug on Android
It has been a few years since I last needed to debug any native applications on Android. After poking around a bit I found this Google reference referring to gdbserver and gdbclient.py.

I found the former in the NDK

```<code>$NDK/prebuilt/android-arm[64]/gdbserver/gdbserver
</code>```

And the latter in the SDK

```<code>$SDK/development/scripts/gdbclient.py
</code>```

When I went to run the python script I am met with:

```<code>$ python gdbclient.py
Traceback (most recent call last):
  File "gdbclient.py", line 27, in <module>
    import gdbrunner
ImportError: No module named gdbrunner
</code>```

For the life of me I cannot find any information on what gdbrunner is. Nor have I found any other reference to it in the [S/N]DKs.

Any idea? Is there another method to debug native components of Android not reliant upon this script?

答:
you can try this:

1.in app/build.gradle:

at dependencies label:

```<code>releaseCompile project(path: ':youModuleName', configuration: 'release')
debugCompile project(path: ':youModuleName', configuration: 'debug')
</code>```

2.in youModule/build.gradle:

at android label:

publishNonDefault true

demo:

https://github.com/sunalong/JNIDemo

Title: Native debug on Android

Body:
It has been a few years since I last needed to debug any native applications on Android. After poking around a bit I found this Google reference referring to gdbserver and gdbclient.py.

I found the former in the NDK

$NDK/prebuilt/android-arm[64]/gdbserver/gdbserver

And the latter in the SDK

$SDK/development/scripts/gdbclient.py

When I went to run the python script I am met with:

$ python gdbclient.py
Traceback (most recent call last):
  File "gdbclient.py", line 27, in <module>
    import gdbrunner
ImportError: No module named gdbrunner

For the life of me I cannot find any information on what gdbrunner is. Nor have I found any other reference to it in the [S/N]DKs.

Any idea? Is there another method to debug native components of Android not reliant upon this script?

Body:
you can try this:

1.in app/build.gradle:

at dependencies label:

releaseCompile project(path: ':youModuleName', configuration: 'release')
debugCompile project(path: ':youModuleName', configuration: 'debug')

2.in youModule/build.gradle:

at android label:

publishNonDefault true

demo:

https://github.com/sunalong/JNIDemo


问:
How can I import bulk data from a CSV file into DynamoDB?
I am trying to import a CSV file data into AWS DynamoDB.

Here's what my CSV file looks like:

```<code>first_name  last_name
sri ram
Rahul   Dravid
JetPay  Underwriter
Anil Kumar  Gurram
</code>```

答:
One way of importing/exporting stuff:</p>

```<code>"""
Batch-writes data from a file to a dynamo-db database.
"""

import json
import boto3

# Get items from DynamoDB table like this:
# aws dynamodb scan --table-name <table-name>

# Create dynamodb client.
client = boto3.client(
    'dynamodb',
    aws_access_key_id='',
    aws_secret_access_key=''
)

with open('', 'r') as file:
    data = json.loads(file.read())['Items']

    # Execute write-data request for each item.
    for item in data:
        client.put_item(
            TableName='',
            Item=item
        )
</code>```

Body:
I am trying to import a CSV file data into AWS DynamoDB.

Here's what my CSV file looks like:

first_name  last_name
sri ram
Rahul   Dravid
JetPay  Underwriter
Anil Kumar  Gurram

Body:
One way of importing/exporting stuff:

"""
Batch-writes data from a file to a dynamo-db database.
"""

import json
import boto3

# Get items from DynamoDB table like this:
# aws dynamodb scan --table-name <table-name>

# Create dynamodb client.
client = boto3.client(
    'dynamodb',
    aws_access_key_id='',
    aws_secret_access_key=''
)

with open('', 'r') as file:
    data = json.loads(file.read())['Items']

    # Execute write-data request for each item.
    for item in data:
        client.put_item(
            TableName='',
            Item=item
        )


问:
RichFaces: Clear required fields when clicking cancel button
Lets say I have three inputs in a modal dialog panel:

Field A:

```<code><h:inputText id="fieldA" value="#{callbackDialog.fieldA}" required="true">
</code>```

Field B:

```<code><h:inputTextarea id="fieldB" value="#{callbackDialog.fieldB}" required="false" rows="4" onkeyup="this.value = this.value.substring(0, 255);"/>
</code>```

Field C:

```<code><h:selectOneMenu id="fieldC" value="#{callbackDialog.fieldC}" required="true">
    <s:selectItems value="#{callbackDialog.fieldCList}"
        var="fieldC"
        label="#{fieldC.name}"
        hideNoSelectionLabel="true"
        noSelectionLabel="Empty"/>
    <s:convertEntity />
</h:selectOneMenu>t>
</code>```

I also have a Cancel button on the modal panel:

```<code><a4j:commandLink styleClass="btn-standard"
    immediate="true"
    action="#{generalDialogAction.forwardCancelButton()}"
    oncomplete="#{rich:component('modalPanel')}.hide(); Event.stop(event); return false;">
<span><h:outputText value="Cancel"></h:outputText></span>
</a4j:commandLink>
</code>```

Now field A and C are required fields. Is there a generic way in which a button (the Cancel button in this case) can check which input fields on a page are required, and if they are, clear their values when Cancel is clicked? Please help!

答:
Just a guess... try,</p>

```<code><h:commandButton id="btnReset" value="Cancel" type="reset" />
</code>```

Body:
Lets say I have three inputs in a modal dialog panel:

Field A:

<h:inputText id="fieldA" value="#{callbackDialog.fieldA}" required="true">

Field B:

<h:inputTextarea id="fieldB" value="#{callbackDialog.fieldB}" required="false" rows="4" onkeyup="this.value = this.value.substring(0, 255);"/>

Field C:

<h:selectOneMenu id="fieldC" value="#{callbackDialog.fieldC}" required="true">
    <s:selectItems value="#{callbackDialog.fieldCList}"
        var="fieldC"
        label="#{fieldC.name}"
        hideNoSelectionLabel="true"
        noSelectionLabel="Empty"/>
    <s:convertEntity />
</h:selectOneMenu>t>

I also have a Cancel button on the modal panel:

<a4j:commandLink styleClass="btn-standard"
    immediate="true"
    action="#{generalDialogAction.forwardCancelButton()}"
    oncomplete="#{rich:component('modalPanel')}.hide(); Event.stop(event); return false;">
<h:outputText value="Cancel"></h:outputText>
</a4j:commandLink>

Now field A and C are required fields. Is there a generic way in which a button (the Cancel button in this case) can check which input fields on a page are required, and if they are, clear their values when Cancel is clicked? Please help!

Body:
Just a guess... try,

<h:commandButton id="btnReset" value="Cancel" type="reset" />


问:
Mean of the selected row in grouped dataframe
can you please help me with the following situation? I want to groupby my df based on team and season and then I want to get mean of the goals scored till the date of the match. I thought about using rolling, but I cant figure it out how, since for each row it will different.

DF:

```<code>Date      Home   Away    Season  Home_goals  Away_goals
1.1.2019  Team 1 Team 2  2019    1           1
2.1.2019  Team 3 Team 4  2019    2           3
3.1.2019  Team 1 Team 3  2019    2           1
2.1.2020  Team 1 Team 4  2020    3           4
4.1.2019  Team 1 Team 5  2019    1           3
</code>```

Expected output:

```<code>Date      Home   Away    Season  Home_goals  Away_goals  Mean_home_goals
1.1.2019  Team 1 Team 2  2019    1           1           1
2.1.2019  Team 3 Team 4  2019    2           3           2
3.1.2019  Team 1 Team 3  2019    2           1           1.5((1+3)/2)
2.1.2020  Team 1 Team 4  2020    3           4           3 (its new season)
4.1.2019  Team 1 Team 5  2019    1           3           1.33 ((1+3+1)/3)
</code>```

Thanks

答:
If you sort by the date, you can then group everything by Home and Season, and then just calculated an expanding mean on it:

```<code>In [327]: df.sort_values("Date").groupby(["Home", "Season"])["Home_goals"].expanding().mean()
Out[327]:
Home    Season
Team 1  2019    0    1.000000
                2    1.500000
                4    1.333333
        2020    3    3.000000
Team 3  2019    1    2.000000
Name: Home_goals, dtype: float64
</code>```

Body:
can you please help me with the following situation? I want to groupby my df based on team and season and then I want to get mean of the goals scored till the date of the match. I thought about using rolling, but I cant figure it out how, since for each row it will different.

DF:

Date      Home   Away    Season  Home_goals  Away_goals
1.1.2019  Team 1 Team 2  2019    1           1
2.1.2019  Team 3 Team 4  2019    2           3
3.1.2019  Team 1 Team 3  2019    2           1
2.1.2020  Team 1 Team 4  2020    3           4
4.1.2019  Team 1 Team 5  2019    1           3

Expected output:

Date      Home   Away    Season  Home_goals  Away_goals  Mean_home_goals
1.1.2019  Team 1 Team 2  2019    1           1           1
2.1.2019  Team 3 Team 4  2019    2           3           2
3.1.2019  Team 1 Team 3  2019    2           1           1.5((1+3)/2)
2.1.2020  Team 1 Team 4  2020    3           4           3 (its new season)
4.1.2019  Team 1 Team 5  2019    1           3           1.33 ((1+3+1)/3)

Thanks

Body:
If you sort by the date, you can then group everything by Home and Season, and then just calculated an expanding mean on it:

In [327]: df.sort_values("Date").groupby(["Home", "Season"])["Home_goals"].expanding().mean()
Out[327]:
Home    Season
Team 1  2019    0    1.000000
                2    1.500000
                4    1.333333
        2020    3    3.000000
Team 3  2019    1    2.000000
Name: Home_goals, dtype: float64


问:
Using Splunk - extract fields from xml data in a log file using xpath
I am using Splunk to extract a number of fields from xml data this is contained in a log file.  So to limit the search to be MOSTLY the xml file I start the search with this:
sourcetype="name of type here" "RULE"

This returns:

```<code>0123459 TripMessage.createMessage MsgSource <?xml version="1.0" encoding="UTF-8"?>
<tmsTrip xmlns="<link to trip" xmlns:ns2="link to common">
</code>```

...

The file is very large.  This is part of it.

```<code><?xml version="1.0" encoding="UTF-8"?>
<tmsTrip xmlns="trip" xmlns:ns2="Common">
   <recordType>PURCHASEDLINEHAUL</recordType>
   <eventType>APPROVE</eventType>
.... more lines here that are not important
     <purchasedCost>
      <purchasedCostTripSegment>
         <purchCostReference>1587040</purchCostReference>
         <carrier information>
         <origin>
            <contact information>
         </origin>
</code>```

This query selects the xml part text in the logging file and some of the fields are extracted and I can add to a table. (not including the source and sourcetype..)

```<code>| xmlkv | table purchCostReference, eventType, carrier, billingMethod
</code>```

But need more fields that are child elements within the xml data. One of them is the numberCode. I am trying to use xpath to extract these additional fields.

```<code>| xmlkv | xpath
"//tmsTrip/purchasedCost/purchasedCostTripSegment/origin/ns2:numberCode" outfield=Origin | table purchCostReference, eventType, carrier, billingMethod, Origin
</code>```

But no Origin data is returned when I add the field to the table.  There is no error.  The Origin column is empty.

UPDATE
I think the problem is that I need to add the field parameter.  The xml file is within a log text file.  I limit the search to get the xml file but not only the xml.  So I think xpath is struggling with the other text that is not xml.

UPDATE
I tried creating an extracted field using the wizard of the xml file that is within the logging statement.  The xml is huge and I can only select about 30% of it.  If anyone is good at regex, maybe they can give me some pointers as to how to complete the regex command to get all of the xml.  (I tried updating the props.conf file but do not have permission to add TRUNCATE = 0).
This is the xml file sample:

```<code><?xml version="1.0" encoding="UTF-8"?>
<tmsTrip xmlns="trip" xmlns:ns2="Common">
   <recordType>PURCHASEDLINEHAUL</recordType>
   <eventType>APPROVE</eventType>
   <tripId>143642990</tripId>
   <legId>129014817</legId>
   <tripNumber>129014817</tripNumber>
   <tripLegNumber>1</tripLegNumber>
   <updatedDateGMT>2020-05-22T00:53:21.000Z</updatedDateGMT>
   <origin>
     <contact info>
   </origin>
   <destination>
     <contact info>
   </destination>
   <schedDispatchDateGMT>2020-05-22T13:00:00.000Z</schedDispatchDateGMT>
   <estimatedArrivalDateGMT>2020-05-26T06:00:00.000Z</estimatedArrivalDateGMT>
   <drop/>
   <hook/>
   <actualRoute>
     <info>
   </actualRoute>
   <standardRoute>
    <info>
   </standardRoute>
   <paidRoute>
     <info>
   </paidRoute>
   <settlement>
      <contact info>
               <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
            </ns2:stopOffLocation>
         </stopOff>
         <schedDispatchDate>2020-05-22T05:00:00.000Z</schedDispatchDate>
         <estimatedArrivalDate>2020-05-26T01:00:00.000Z</estimatedArrivalDate>
         <billingMethod>LOCAL</billingMethod>
         <STCCCode>4711110</STCCCode>
         <planNumber>045</planNumber>
         <powerType>1X</powerType>
         <powerOnlyFlag>false</powerOnlyFlag>
      </purchasedCostTripSegment>
   </purchasedCost>
   <drivers/>
</tmsTrip>
</code>```

This is how much the extracted field I can select:

<tmsTrip xmlns="trip" xmlns:ns2="Common">
PURCHASEDLINEHAUL

2020-05-22T00:53:21.000Z

This is the regex that Splunk creates to select the above xml

```<code>^[^\$\n]*\$\d+\.\w+\s+\w+\s+(?P<xmlMessage><\?\w+\s+\w+="\d+\.\d+"\s+\w+="\w+\-\d+"\?>\s+<\w+\s+\w+="\w+://\w+\.\w+\.\w+/\w+/\w+/\w+"\s+\w+:\w+="\w+://\w+\.\w+\.\w+/\w+/\w+/\w+">\s+<\w+>\w+</\w+>\s+<\w+>\w+</\w+>\s+<\w+>\d+</\w+>\s+<\w+>\d+</\w+>\s+<\w+>\d+</\w+>\s+<\w+>\d+</\w+>\s+<\w+>\d+\-\d+\-\d+\w+:\d+:\d+\.\d+\w+</\w+>\s+<\w+>\s+<\w+:\w+>\d+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>\s+<\w+:\w+>\d+\s+\w+\s+\w+\s+\w+\s+\w+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>\s+<\w+:\w+>\d+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>\s+<\w+:\w+>\d+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>)
</code>```

So can I change the above regex to include the entire xml?

UPDATE
I tried extracting a field from the xmlMessage extracted field.  The xmlMessage field is above. I used the xpath command to extract recordType.  Put the result in a table. This is the command

```<code>| xmlkv | xpath field=xmlMessage
"//tmsTrip/recordType" outfield=Origin | table Origin
</code>```

It returned no results.  This xpath command does not work for the simplest of queries.
What am I doing wrong?

答:
I was able to extract the data from the xml using rex and identify each instance of  the numberCode using max_match and mvindex
Here is an example of anyone who has this problem:

```<code> rex max_match=0 "\<ns2\:numberCode\>(?P<location>[^\<]+)"| eval Segment1_Origin =  mvindex(location, 7)
</code>```

The xml element is ns2:numberCode.  It is renamed to location. max_match=0 means unlimited number of instances.  The mvindex is zero based.  So the 8th instance of the location is set to the variable Segment1_origin

Body:
I am using Splunk to extract a number of fields from xml data this is contained in a log file.  So to limit the search to be MOSTLY the xml file I start the search with this:
sourcetype="name of type here" "RULE"

This returns:

0123459 TripMessage.createMessage MsgSource <?xml version="1.0" encoding="UTF-8"?>
<tmsTrip xmlns="<link to trip" xmlns:ns2="link to common">

...

The file is very large.  This is part of it.

<?xml version="1.0" encoding="UTF-8"?>
<tmsTrip xmlns="trip" xmlns:ns2="Common">
   <recordType>PURCHASEDLINEHAUL</recordType>
   <eventType>APPROVE</eventType>
.... more lines here that are not important
     <purchasedCost>
      <purchasedCostTripSegment>
         <purchCostReference>1587040</purchCostReference>
         <carrier information>
         <origin>
            <contact information>
         </origin>

This query selects the xml part text in the logging file and some of the fields are extracted and I can add to a table. (not including the source and sourcetype..)

| xmlkv | table purchCostReference, eventType, carrier, billingMethod

But need more fields that are child elements within the xml data. One of them is the numberCode. I am trying to use xpath to extract these additional fields.

| xmlkv | xpath
"//tmsTrip/purchasedCost/purchasedCostTripSegment/origin/ns2:numberCode" outfield=Origin | table purchCostReference, eventType, carrier, billingMethod, Origin

But no Origin data is returned when I add the field to the table.  There is no error.  The Origin column is empty.

UPDATE
I think the problem is that I need to add the field parameter.  The xml file is within a log text file.  I limit the search to get the xml file but not only the xml.  So I think xpath is struggling with the other text that is not xml.

UPDATE
I tried creating an extracted field using the wizard of the xml file that is within the logging statement.  The xml is huge and I can only select about 30% of it.  If anyone is good at regex, maybe they can give me some pointers as to how to complete the regex command to get all of the xml.  (I tried updating the props.conf file but do not have permission to add TRUNCATE = 0).
This is the xml file sample:

<?xml version="1.0" encoding="UTF-8"?>
<tmsTrip xmlns="trip" xmlns:ns2="Common">
   <recordType>PURCHASEDLINEHAUL</recordType>
   <eventType>APPROVE</eventType>
   <tripId>143642990</tripId>
   <legId>129014817</legId>
   <tripNumber>129014817</tripNumber>
   <tripLegNumber>1</tripLegNumber>
   <updatedDateGMT>2020-05-22T00:53:21.000Z</updatedDateGMT>
   <origin>
     <contact info>
   </origin>
   <destination>
     <contact info>
   </destination>
   <schedDispatchDateGMT>2020-05-22T13:00:00.000Z</schedDispatchDateGMT>
   <estimatedArrivalDateGMT>2020-05-26T06:00:00.000Z</estimatedArrivalDateGMT>
   <drop/>
   <hook/>
   <actualRoute>
     <info>
   </actualRoute>
   <standardRoute>
    <info>
   </standardRoute>
   <paidRoute>
     <info>
   </paidRoute>
   <settlement>
      <contact info>
               <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
            </ns2:stopOffLocation>
         </stopOff>
         <schedDispatchDate>2020-05-22T05:00:00.000Z</schedDispatchDate>
         <estimatedArrivalDate>2020-05-26T01:00:00.000Z</estimatedArrivalDate>
         <billingMethod>LOCAL</billingMethod>
         <STCCCode>4711110</STCCCode>
         <planNumber>045</planNumber>
         <powerType>1X</powerType>
         <powerOnlyFlag>false</powerOnlyFlag>
      </purchasedCostTripSegment>
   </purchasedCost>
   <drivers/>
</tmsTrip>

This is how much the extracted field I can select:

<tmsTrip xmlns="trip" xmlns:ns2="Common">
PURCHASEDLINEHAUL

2020-05-22T00:53:21.000Z

This is the regex that Splunk creates to select the above xml

^[^\$\n]*\$\d+\.\w+\s+\w+\s+(?P<xmlMessage><\?\w+\s+\w+="\d+\.\d+"\s+\w+="\w+\-\d+"\?>\s+<\w+\s+\w+="\w+://\w+\.\w+\.\w+/\w+/\w+/\w+"\s+\w+:\w+="\w+://\w+\.\w+\.\w+/\w+/\w+/\w+">\s+<\w+>\w+</\w+>\s+<\w+>\w+</\w+>\s+<\w+>\d+</\w+>\s+<\w+>\d+</\w+>\s+<\w+>\d+</\w+>\s+<\w+>\d+</\w+>\s+<\w+>\d+\-\d+\-\d+\w+:\d+:\d+\.\d+\w+</\w+>\s+<\w+>\s+<\w+:\w+>\d+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>\s+<\w+:\w+>\d+\s+\w+\s+\w+\s+\w+\s+\w+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>\s+<\w+:\w+>\d+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>\s+<\w+:\w+>\d+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>\s+<\w+:\w+>\w+</\w+:\w+>)

So can I change the above regex to include the entire xml?

UPDATE
I tried extracting a field from the xmlMessage extracted field.  The xmlMessage field is above. I used the xpath command to extract recordType.  Put the result in a table. This is the command

| xmlkv | xpath field=xmlMessage
"//tmsTrip/recordType" outfield=Origin | table Origin

It returned no results.  This xpath command does not work for the simplest of queries.
What am I doing wrong?

Body:
I was able to extract the data from the xml using rex and identify each instance of  the numberCode using max_match and mvindex
Here is an example of anyone who has this problem:

 rex max_match=0 "\<ns2\:numberCode\>(?P<location>[^\<]+)"| eval Segment1_Origin =  mvindex(location, 7)

The xml element is ns2:numberCode.  It is renamed to location. max_match=0 means unlimited number of instances.  The mvindex is zero based.  So the 8th instance of the location is set to the variable Segment1_origin


问:
I want to go inside a folder and run a command in windows command promt using a single command
C:\node_modules>cd npm (Hit Enter)

C:\node_modules\npm>node connect.js (Hit Enter)

executing connect.js...

The above 2 commands, I want to execute from a single command from the folder location "node_modules". For Example,

C:\node_modules>cd npm/node connect.js

But it doesn't work. whats the right command?

答:
With the current directory already as node_modules, you could use:

Start "" /D npm "%ProgramFiles%\nodejs\node.exe" connect.js
```

<p>or</p>

<pre class="lang-cmd prettyprint-override"><code>Start "" /D npm /Wait "%ProgramFiles%\nodejs\node.exe" connect.js
</code>```

or

PushD npm 2> NUL && "%ProgramFiles%\nodejs\node.exe" connect.js & PopD
```

<p>or</p>

<pre class="lang-cmd prettyprint-override"><code>CD npm 2> NUL && "%ProgramFiles%\nodejs\node.exe" connect.js & CD ..
</code>```

With any directory as current, you could use:

Start "" /D "%ProgramFiles%\nodejs\node_modules\npm" "%ProgramFiles%\nodejs\node.exe" connect.js
```

<p>or</p>

<pre class="lang-cmd prettyprint-override"><code>Start "" /D "%ProgramFiles%\nodejs\node_modules\npm" /Wait "%ProgramFiles%\nodejs\node.exe" connect.js
</code>```

or

PushD "%ProgramFiles%\nodejs\node_modules\npm" 2> NUL && "%ProgramFiles%\nodejs\node.exe" connect.js & PopD
```

<p><HR>
You could shorten those seven examples by omitting the full paths and extensions, if you can guarantee that their locations are set within the environment and the <code>%PATHEXT%</code> variable contains <code>.EXE</code></p>

<pre class="lang-cmd prettyprint-override"><code>Start /D npm node connect.js
</code>```

Start /D npm /W node connect.js
```

<pre class="lang-cmd prettyprint-override"><code>PushD npm 2>NUL&&node connect.js&PopD
</code>```

CD npm 2>NUL&&node connect.js&CD..
```

<pre class="lang-cmd prettyprint-override"><code>Start "" /D "%ProgramFiles%\nodejs\node_modules\npm" node connect.js
</code>```

Start "" /D "%ProgramFiles%\nodejs\node_modules\npm" /W node connect.js
```

<pre class="lang-cmd prettyprint-override"><code>PushD "%ProgramFiles%\nodejs\node_modules\npm" 2>NUL&&node connect.js&PopD
</code>```

I have assumed for the above examples, that the file node.exe, and directory node_modules, are both really located in "%ProgramFiles%\nodejs", usually ("C:\Program Files\nodejs). If one or both of those locations differ on your PC, please modify them accordingly.

Body:
With the current directory already as node_modules, you could use:

Start "" /D npm "%ProgramFiles%\nodejs\node.exe" connect.js

or

Start "" /D npm /Wait "%ProgramFiles%\nodejs\node.exe" connect.js

or

PushD npm 2> NUL && "%ProgramFiles%\nodejs\node.exe" connect.js & PopD

or

CD npm 2> NUL && "%ProgramFiles%\nodejs\node.exe" connect.js & CD ..

With any directory as current, you could use:

Start "" /D "%ProgramFiles%\nodejs\node_modules\npm" "%ProgramFiles%\nodejs\node.exe" connect.js

or

Start "" /D "%ProgramFiles%\nodejs\node_modules\npm" /Wait "%ProgramFiles%\nodejs\node.exe" connect.js

or

PushD "%ProgramFiles%\nodejs\node_modules\npm" 2> NUL && "%ProgramFiles%\nodejs\node.exe" connect.js & PopD

You could shorten those seven examples by omitting the full paths and extensions, if you can guarantee that their locations are set within the environment and the %PATHEXT% variable contains .EXE

Start /D npm node connect.js

Start /D npm /W node connect.js

PushD npm 2>NUL&&node connect.js&PopD

CD npm 2>NUL&&node connect.js&CD..

Start "" /D "%ProgramFiles%\nodejs\node_modules\npm" node connect.js

Start "" /D "%ProgramFiles%\nodejs\node_modules\npm" /W node connect.js

PushD "%ProgramFiles%\nodejs\node_modules\npm" 2>NUL&&node connect.js&PopD

I have assumed for the above examples, that the file node.exe, and directory node_modules, are both really located in "%ProgramFiles%\nodejs", usually ("C:\Program Files\nodejs). If one or both of those locations differ on your PC, please modify them accordingly.


问:
Google Cloud SQL Docker Proxy
I am trying to connect to my Cloud SLQ (Postgres) instance from my local environment (OSX) using the Google Cloud SQL Docker Proxy as documented here. When running the proxy I get:

```<code>google: could not find default credentials.
</code>```

Note that I am running gcloud on my local environment within the right project and having authenticated through the application-default login. I understand that in similar questions this is what solved the issue however this is not my case.

答: Specifying the absolute path of the key file solved my problem.</p>

Title: Google Cloud SQL Docker Proxy

Body:
I am trying to connect to my Cloud SLQ (Postgres) instance from my local environment (OSX) using the Google Cloud SQL Docker Proxy as documented here. When running the proxy I get:

google: could not find default credentials.

Note that I am running gcloud on my local environment within the right project and having authenticated through the application-default login. I understand that in similar questions this is what solved the issue however this is not my case.


问:
Is there a faster way to read, resort and convert a binary file?
I have a binary file that contains a certain number of samples and each sample contains four bytes. The data is acquired via 14 bit ADCs and I have the following bit assignment: b31-b29=Not Used, b28=Digital input, b27-b14=chB(signed), b13-b0=chA(signed). In the end I want to perform a FFT for chA and chB. To get there I use the following Python code:

1. Here the binary data file is opened as a bitstring and the samples, i.e. 516x1024x32x32 bits are read and appended to a bit array. This is done by reading one sample (4 bytes or 32 bits) at a time, inverting the byte order and then putting this bitstring in a bit array. This is repeated for all samples:

```<code>swap = BitArray()

f = ConstBitStream(filename='data.kbin')
f.pos = 0
samples = 516*1024*32
sample_rate = 30517.578125

for i in range(samples):
    data = BitArray()
    g = f.read('bits:32')
    data.append(g)
    data.byteswap(4)
    swap.append(data)

</code>```

2. The newly ordered array is again opened as bitstring:

```<code>data2 = ConstBitStream(swap)
</code>```

3. The bitstring is now read in a way so that the correct bit assignment (as shown above) is applied and each bitstring is converted to a signed integer. Also each integer referring to chA and chB are put into the corresponding list:

```<code>chA = []
chB = []

data2.pos = 0
for i in range(samples):
    a = data2.read('int:3')
    b = data2.read('int:1')
    c = data2.read('int:14')
    d = data2.read('int:14')
    chA.append(d)
    chB.append(c)
</code>```

4. Calculating the FFT:

```<code>dt = 1 / sample_rate

yf_A = fftpack.rfft(chA)
yf_B = fftpack.rfft(chB)
xf = fftpack.rfftfreq(samples, dt)
</code>```

This code works and I get the desired result but it takes really long. The first step takes almost 10 min and the third about 3 min. I am quite new to Python so my knowledge is rather small. How can I speed things up?
Thanks.

答:
I found a much faster way:

```<code># input the path t the data file
file_kbin = input("Path to data file: ")

# initialize two lists where the converted data for chA and chB will be stored

CHA = []
CHB = []

# get the number of samples in the data file

size = 516 * 1024 * 32

# here the binary file is opened and converted following the byte assignment given above
with open(file_kbin, 'rb') as data:

    data.seek(0)                                          # make sure to start at the beginning of the file

    for i in range(size):                                 # loop over the complete file

        sample = data.read(4)                             # read one sample (byte0 byte1 byte2 byte3)
        tmp = int.from_bytes(sample, byteorder='little')  # store the data as integer following the byteorder little (byte3 byte2 byte1 byte0)

        chA = tmp & 0x00003FFF                            # set chA to byte1 byte0 with b15 and b14 = 0
        if (chA & 0x2000):                                # check if chA negative
            chA = chA - 0x4000                            # get the correct negative value

        chB = (tmp & 0x0FFFc000) >> 14                    # set all bits to 0 except for b27-b14 and shift right by 14 bits
        if (chB & 0x2000):                                # check if chB negative
            chB = chB - 0x4000                            # get the correct negative value

        CHA.append(chA)                                   # store the values in the corresponding list
        CHB.append(chB)
</code>```

(Using the corresponding code in C++ would again be a lot faster.)

Body:
I have a binary file that contains a certain number of samples and each sample contains four bytes. The data is acquired via 14 bit ADCs and I have the following bit assignment: b31-b29=Not Used, b28=Digital input, b27-b14=chB(signed), b13-b0=chA(signed). In the end I want to perform a FFT for chA and chB. To get there I use the following Python code:

1. Here the binary data file is opened as a bitstring and the samples, i.e. 516x1024x32x32 bits are read and appended to a bit array. This is done by reading one sample (4 bytes or 32 bits) at a time, inverting the byte order and then putting this bitstring in a bit array. This is repeated for all samples:

swap = BitArray()

f = ConstBitStream(filename='data.kbin')
f.pos = 0
samples = 516*1024*32
sample_rate = 30517.578125

for i in range(samples):
    data = BitArray()
    g = f.read('bits:32')
    data.append(g)
    data.byteswap(4)
    swap.append(data)

2. The newly ordered array is again opened as bitstring:

data2 = ConstBitStream(swap)

3. The bitstring is now read in a way so that the correct bit assignment (as shown above) is applied and each bitstring is converted to a signed integer. Also each integer referring to chA and chB are put into the corresponding list:

chA = []
chB = []

data2.pos = 0
for i in range(samples):
    a = data2.read('int:3')
    b = data2.read('int:1')
    c = data2.read('int:14')
    d = data2.read('int:14')
    chA.append(d)
    chB.append(c)

4. Calculating the FFT:

dt = 1 / sample_rate

yf_A = fftpack.rfft(chA)
yf_B = fftpack.rfft(chB)
xf = fftpack.rfftfreq(samples, dt)

This code works and I get the desired result but it takes really long. The first step takes almost 10 min and the third about 3 min. I am quite new to Python so my knowledge is rather small. How can I speed things up?
Thanks.

Body:
I found a much faster way:

# input the path t the data file
file_kbin = input("Path to data file: ")

# initialize two lists where the converted data for chA and chB will be stored

CHA = []
CHB = []

# get the number of samples in the data file

size = 516 * 1024 * 32

# here the binary file is opened and converted following the byte assignment given above
with open(file_kbin, 'rb') as data:

    data.seek(0)                                          # make sure to start at the beginning of the file

    for i in range(size):                                 # loop over the complete file

        sample = data.read(4)                             # read one sample (byte0 byte1 byte2 byte3)
        tmp = int.from_bytes(sample, byteorder='little')  # store the data as integer following the byteorder little (byte3 byte2 byte1 byte0)

        chA = tmp & 0x00003FFF                            # set chA to byte1 byte0 with b15 and b14 = 0
        if (chA & 0x2000):                                # check if chA negative
            chA = chA - 0x4000                            # get the correct negative value

        chB = (tmp & 0x0FFFc000) >> 14                    # set all bits to 0 except for b27-b14 and shift right by 14 bits
        if (chB & 0x2000):                                # check if chB negative
            chB = chB - 0x4000                            # get the correct negative value

        CHA.append(chA)                                   # store the values in the corresponding list
        CHB.append(chB)

(Using the corresponding code in C++ would again be a lot faster.)


问:
JWT secret to use with ejabberd?
I'm following these:

https://www.process-one.net/blog/ejabberd-19-08/

https://docs.ejabberd.im/admin/configuration/authentication/#jwt-authentication

and have created a secret.key like below using https://mkjwk.org/ to match the example in the first URL above:

According to https://auth0.com/blog/navigating-rs256-and-jwks/ because this is an HS type:

"Simply put HS256 must share a secret with any client or API that
  wants to verify the JWT"

So I naively assumed to use the "k" as the secret to sign the JWT on the server issuing the JWT to use in the password field of any XMPP client (stanza.io and pidgin on the desktop).

What am I misunderstanding? I have confirmed ejabberd starts up correctly with (via ejabberdctl live and loglevel 4):

```<code>auth_method: [jwt, ldap]
jwt_key: /opt/ejabberd/conf/secret.jwk
</code>```

and that I can still authenticate with a password in our Directory Server, but I can't with the JWT. I don't think I'm generating it correctly because I'm just signing it like a normal shared key JWT.

Thanks,
Gavin.

答:
"k" is the secret used to sign the JWTs you generate, you assumed correctly.

However https://mkjwk.org (and jabber) use Base64-url (RFC 4648 §5) encoded secrets.
Please try decoding the value of "k" before signing your JWT as any other libraries (and algorithms) usually do not expect an encoded secret, especialy an url-encoded secret

You can check out https://jwt.io/ to manually create or modify your JWTs and see what is going on with them, with an option to have the secret encoded or not. It however handles base64-url encoding transparently.

Title: JWT secret to use with ejabberd?

Body:
I'm following these:

https://www.process-one.net/blog/ejabberd-19-08/

https://docs.ejabberd.im/admin/configuration/authentication/#jwt-authentication

and have created a secret.key like below using https://mkjwk.org/ to match the example in the first URL above:

According to https://auth0.com/blog/navigating-rs256-and-jwks/ because this is an HS type:

"Simply put HS256 must share a secret with any client or API that
  wants to verify the JWT"

So I naively assumed to use the "k" as the secret to sign the JWT on the server issuing the JWT to use in the password field of any XMPP client (stanza.io and pidgin on the desktop).

What am I misunderstanding? I have confirmed ejabberd starts up correctly with (via ejabberdctl live and loglevel 4):

auth_method: [jwt, ldap]
jwt_key: /opt/ejabberd/conf/secret.jwk

and that I can still authenticate with a password in our Directory Server, but I can't with the JWT. I don't think I'm generating it correctly because I'm just signing it like a normal shared key JWT.

Thanks,
Gavin.