问:
Finding multiple interpolated x-values from a function that is not invertible
I am trying to find two interpolated x-values of a function found where a threshold is crossed.

I have tried switching the x and y values as proposed in previous answers to similar questions; however, this only returns one of the two x-values I am looking for due to the values having the same x-coordinate when inverted.

.

The red point on each graph shows the point I've already located with the following code:

```<code>interp = interp1d(data[1], data.times)
val = interp(great.middle.iloc[1])
</code>```

Where data is a pandas data frame that contains all the events (so here we are looking at event 1) and a single time column and great is another pandas data frame where the middle value is the greatest value in the event column divided by 2.  Here val is equal to 42.28045192307682 which is the interpolated time at which the middle value is reached (for the second time).

I have tried narrowing the the values for the interpolation function, but the interpolation of a y- value always results in Nan x-values.

The data that I am using is kind of large but here is an output for a voltage and time:
https://drive.google.com/open?id=16xPB5HU_ZJ4qmIdD8icKrDKAAXAO2lH7
https://drive.google.com/open?id=1Yc-_ole-dFAnpTNJhEjKNYU6hQfCSiar

答:
Here's how I solved this:</p>
```<code>#save the event data column as pulse (y-values)
pulse = data[1]
#save the time data as time (x-values)
times = data.times

#resample the zero points of the data (the data - the threshold)
spulse = signal.resample(pulse - np.max(pulse)/2., 10*len(pulse))

#find the place where the data changes signs
crossings = np.where(np.diff(np.sign(spulse)))[0]

#because the data has noise, average the first and second crossings
first = np.mean(crossings[crossings < np.argmax(spulse)])/1000
second = np.mean(crossings[crossings > np.argmax(spulse)])/1000

#print the times that the threshold was crossed
print("First crossing at: " + str(first) + ", Second at: " + str(second))
</code>```

Body:
I am trying to find two interpolated x-values of a function found where a threshold is crossed.

I have tried switching the x and y values as proposed in previous answers to similar questions; however, this only returns one of the two x-values I am looking for due to the values having the same x-coordinate when inverted.

.

The red point on each graph shows the point I've already located with the following code:

interp = interp1d(data[1], data.times)
val = interp(great.middle.iloc[1])

Where data is a pandas data frame that contains all the events (so here we are looking at event 1) and a single time column and great is another pandas data frame where the middle value is the greatest value in the event column divided by 2.  Here val is equal to 42.28045192307682 which is the interpolated time at which the middle value is reached (for the second time).

I have tried narrowing the the values for the interpolation function, but the interpolation of a y- value always results in Nan x-values.

The data that I am using is kind of large but here is an output for a voltage and time:
https://drive.google.com/open?id=16xPB5HU_ZJ4qmIdD8icKrDKAAXAO2lH7
https://drive.google.com/open?id=1Yc-_ole-dFAnpTNJhEjKNYU6hQfCSiar

Body:
Here's how I solved this:

#save the event data column as pulse (y-values)
pulse = data[1]
#save the time data as time (x-values)
times = data.times

#resample the zero points of the data (the data - the threshold)
spulse = signal.resample(pulse - np.max(pulse)/2., 10*len(pulse))

#find the place where the data changes signs
crossings = np.where(np.diff(np.sign(spulse)))[0]

#because the data has noise, average the first and second crossings
first = np.mean(crossings[crossings < np.argmax(spulse)])/1000
second = np.mean(crossings[crossings > np.argmax(spulse)])/1000

#print the times that the threshold was crossed
print("First crossing at: " + str(first) + ", Second at: " + str(second))


来源: stackexchange

问:
How to loop X amount of times in RPG free without creating variables?
I have piece of old code that I am trying to convert

Very simple, just loops 10 times

```<code>C                   DO        10
C* code
C                   ENDDO
</code>```

In order to use for loop in free syntax, a variable needs to be created. For example:

```<code>  FOR I = 1 TO 10;
    // code
  ENDFOR;
</code>```

Any way to accomplish this without the need of creating a new variable?

答:
No, but in RPG IV this is not necessarily as much of a problem. In RPG IV you can use procedures, and procedures can have local variables. RPG 400 and before only allowed global variables. However, if you are using subroutines in your RPG IV programs, you still have to use global variables.

You aren't still using subroutines are you?

Here is the syntax difference:

Subroutines in free:

```<code>exsr mysubroutine;

...

begsr mysubroutine;

   ...

endsr;
</code>```

what it looks like with minimal sub-procedures;

```<code>myProcedure();

...

dcl-proc myProcedure;

   ...

end-proc;
</code>```

You strictly don't need the () after the procedure name if you are not passing parameters, but I do this anyway because it clues me in that it is a procedure and not a random variable or other name sitting alone on a line, or even in an expression.

Advantages of procedures?

You can declare local variables for those loops.

You can still use all the global variables that your subroutines use.

You can pass parameters.

You can return a value and use the procedure in an expression.

Procedures can be called recursively.

Gotchas?

You can still use all the globals that your subroutines use.

You can't call a subroutine from within a procedure unless it is defined within the procedure.

You can't call a subroutine defined inside a procedure from outside that procedure.

Gotchas #2 & #3 mean that it might be best to convert all of your subroutines to procedures. You can do that without any side effects.

ContentLicense: CC BY-SA 4.0

Body:
I have piece of old code that I am trying to convert

Very simple, just loops 10 times

C                   DO        10
C* code
C                   ENDDO

In order to use for loop in free syntax, a variable needs to be created. For example:

  FOR I = 1 TO 10;
    // code
  ENDFOR;

Any way to accomplish this without the need of creating a new variable?

Body:
No, but in RPG IV this is not necessarily as much of a problem. In RPG IV you can use procedures, and procedures can have local variables. RPG 400 and before only allowed global variables. However, if you are using subroutines in your RPG IV programs, you still have to use global variables.

You aren't still using subroutines are you?

Here is the syntax difference:

Subroutines in free:

exsr mysubroutine;

...

begsr mysubroutine;

   ...

endsr;

what it looks like with minimal sub-procedures;

myProcedure();

...

dcl-proc myProcedure;

   ...

end-proc;

You strictly don't need the () after the procedure name if you are not passing parameters, but I do this anyway because it clues me in that it is a procedure and not a random variable or other name sitting alone on a line, or even in an expression.

Advantages of procedures?

You can declare local variables for those loops.

You can still use all the global variables that your subroutines use.

You can pass parameters.

You can return a value and use the procedure in an expression.

Procedures can be called recursively.

Gotchas?

You can still use all the globals that your subroutines use.

You can't call a subroutine from within a procedure unless it is defined within the procedure.

You can't call a subroutine defined inside a procedure from outside that procedure.

Gotchas #2 & #3 mean that it might be best to convert all of your subroutines to procedures. You can do that without any side effects.


问:
Fuzzy match portions of an image
I need to determine the existance of a smaller image inside a larger image.

The match must be fuzzy and preferrably I should know how well it matched (%), but I can calculate the accuracy my self after the match is done if required.

My goal is to match a FFT (Fast Fourier Transfrom) spectrogram (visualization of frequencies in music) with the original music track. The small image I'm matching with is only a subset (both in time and frequency range) of the original track (like a cutout of the image below).

Where should I start? Are the same algorithms used for object recognition suitable for this task?

I am primarily looking for C#/.Net libraries/samples, but also information on implementations and problems/pitfalls.

I am considering using artificual neural networks for training the recognition. Any thoughts?

Example of what the images I want to match may look like:

答:
An Image Correlation may work. Depends on the differences between you full image and the partial one.

Example in Mathematica:

If you post a complete example of a full and partial images, perhaps we can work out more.

Other alternatives also exist: Comparing the FFTs and doing Wavelet Analysis, to name just two more.

Title: Fuzzy match portions of an image

ContentLicense: CC BY-SA 3.0


问:
How to fix Apache Camel WARN about depracated syntax
```<code>
    @Override
    public void configure() {
        from("timer?period=12000&repeatCount=1")
                .log("started")
                .streamCaching()
                .to("sql:select * from TABLE WHERE ROWNUM < 100" +
                        "?dataSource=#dataSource")
                .split()
                .body()
                    .process(new convertToJSON())
                    .setHeader(Exchange.HTTP_METHOD, constant("POST"))
                    .setHeader(Exchange.CONTENT_TYPE, constant("text/html"))
                    .to(url)
                .end()
                .log("Sent");
    }
</code>```

I have this camel route which works fine but I get WARN in console:

```<code>2019-05-30 16:02:51.856  WARN 11284 --- [- timer://timer] o.a.c.language.simple.SimpleLanguage     : Simple language is using deprecated syntax: body. You should migrate to use newer syntax that uses ${xxx} style.
</code>```

How to fix this WARN ??

答:
If you would like to access the exchange body, you should use "${body}" in your simple expression.

For example:

```<code>.log("${body}")
</code>```

The above will log the body of the exchange.

Body:
    @Override
    public void configure() {
        from("timer?period=12000&repeatCount=1")
                .log("started")
                .streamCaching()
                .to("sql:select * from TABLE WHERE ROWNUM < 100" +
                        "?dataSource=#dataSource")
                .split()
                .body()
                    .process(new convertToJSON())
                    .setHeader(Exchange.HTTP_METHOD, constant("POST"))
                    .setHeader(Exchange.CONTENT_TYPE, constant("text/html"))
                    .to(url)
                .end()
                .log("Sent");
    }

I have this camel route which works fine but I get WARN in console:

2019-05-30 16:02:51.856  WARN 11284 --- [- timer://timer] o.a.c.language.simple.SimpleLanguage     : Simple language is using deprecated syntax: body. You should migrate to use newer syntax that uses ${xxx} style.

How to fix this WARN ??

Body:
If you would like to access the exchange body, you should use "${body}" in your simple expression.

For example:

.log("${body}")

The above will log the body of the exchange.


问:
Export Activesheet - values only
I am using this code which works fine but it also copies:

Formulas

Shapes

Macros embedded on Sheet

I am looking for a way to only copy the values of the sheet, whilst retaining their original formatting and then close the newly created workbook as my macro does.

```<code>Sub export_sheet()
Dim sourceWB As Workbook
Dim destWB As Workbook
Dim strSourceSheet As Worksheet
Dim strname As String
Dim path As String

Application.DisplayAlerts = False

path = ThisWorkbook.path & "\"
strname = "test_" & Format(Now, "dd_mmm_yy_hh_mm_ss") & ".xlsx"

Set strSourceSheet = ActiveSheet

ThisWorkbook.Sheets(strSourceSheet).Copy
ActiveWorkbook.SaveAs Filename:=path & strname, FileFormat:=51, CreateBackup:=True
ActiveWorkbook.Close

Application.DisplayAlerts = True
End Sub
</code>```

答:
Try this:

```<code>Sub export_sheet()
    Dim sourceWB As String
    Dim destWB As String
    Dim strSourceSheet As String
    Dim strname As String
    Dim path As String

    Application.DisplayAlerts = False

    path = ThisWorkbook.path & "\"
    strname = "test_" & Format(Now, "dd_mmm_yy_hh_mm_ss") & ".xlsx"

    strSourceSheet = ActiveSheet.Name
    sourceWB = Activeworkbook.Name

    Sheets(strSourceSheet).Copy
     ‘If want to copy yo new wb
    Workbooks.Add
    DestWB = Activeworkbook.Name
     ‘Or if DestWb already exists then
     ‘DestWB = yourdestinationwb.xlsx
     ‘Windows(DestWB).Activate
     ‘Sheets(1).Select
    Activesheet.Range(“A1”).SeLect
    Selection.PasteSpecial Paste:=XlPasteValues
    Selection.PasteSpecial Paste:=XlPasteFormats
    ActiveWorkbook.SaveAs Filename:=path & strname, FileFormat:=51, CreateBackup:=True
    ActiveWorkbook.Close

    Application.DisplayAlerts = True
    End Sub
</code>```

Title: Export Activesheet - values only

Body:
I am using this code which works fine but it also copies:

Formulas

Shapes

Macros embedded on Sheet

I am looking for a way to only copy the values of the sheet, whilst retaining their original formatting and then close the newly created workbook as my macro does.

Sub export_sheet()
Dim sourceWB As Workbook
Dim destWB As Workbook
Dim strSourceSheet As Worksheet
Dim strname As String
Dim path As String

Application.DisplayAlerts = False

path = ThisWorkbook.path & "\"
strname = "test_" & Format(Now, "dd_mmm_yy_hh_mm_ss") & ".xlsx"

Set strSourceSheet = ActiveSheet

ThisWorkbook.Sheets(strSourceSheet).Copy
ActiveWorkbook.SaveAs Filename:=path & strname, FileFormat:=51, CreateBackup:=True
ActiveWorkbook.Close

Application.DisplayAlerts = True
End Sub

Body:
Try this:

Sub export_sheet()
    Dim sourceWB As String
    Dim destWB As String
    Dim strSourceSheet As String
    Dim strname As String
    Dim path As String

    Application.DisplayAlerts = False

    path = ThisWorkbook.path & "\"
    strname = "test_" & Format(Now, "dd_mmm_yy_hh_mm_ss") & ".xlsx"

    strSourceSheet = ActiveSheet.Name
    sourceWB = Activeworkbook.Name

    Sheets(strSourceSheet).Copy
     ‘If want to copy yo new wb
    Workbooks.Add
    DestWB = Activeworkbook.Name
     ‘Or if DestWb already exists then
     ‘DestWB = yourdestinationwb.xlsx
     ‘Windows(DestWB).Activate
     ‘Sheets(1).Select
    Activesheet.Range(“A1”).SeLect
    Selection.PasteSpecial Paste:=XlPasteValues
    Selection.PasteSpecial Paste:=XlPasteFormats
    ActiveWorkbook.SaveAs Filename:=path & strname, FileFormat:=51, CreateBackup:=True
    ActiveWorkbook.Close

    Application.DisplayAlerts = True
    End Sub


问:
How to use jQuery Iris Color Picker on multiple inputs with one function
I'm trying to create a jQuery function that can target iris color picker to multiple inputs using a class.

I need each input iris color picker to work independently.

I am really surprised that $.each(function() does not work as you would expect with Iris. I can't get my head round it.

See fiddle here https://jsfiddle.net/joshmoto/Lmez4oft/

I would appreciate any thoughts on how to get iris working independently by using my .iris-wrapper class as the target.

See my full code below...

// each loop the iris wrapper class elems
$('.iris-wrapper','#form').each(function() {

  // set up current object vars
  $input    = $('INPUT', this);
  $inputGroup   = $('.input-group', this);
  $inputIndicator   = $('.input-group-text', this);

  // set our input color indicator to default color
  $inputIndicator.css('background-color', $input.val());

  // init iris
  $input.iris({
    // on iris change
    change: function(event, ui) {
      // update input value on change
      $input.attr('value', ui.color.toString());
      // load the current value
      $inputIndicator.css('background-color', ui.color.toString());
    }
  });

  // move iris color picker after the input group
  $('.iris-picker', this).insertAfter($inputGroup);

  // input blur function
  $input.blur(function() {
    setTimeout(function() {
      if (!$(document.activeElement).closest(".iris-picker").length)
        $input.iris('hide');
      else
        $input.focus();
    }, 0);
  });

  // when input is focused
  $input.focus(function() {
    // input iris show
    $input.iris('show');
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.input-group-prepend .input-group-text::before  {
  width: 18px;
  content: "";
  display: block;
  height: 1px;
}

.iris-picker {
  position: absolute;
  margin-top: 5px;
}</code>```

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>

  <form id="form">

          <input type="text" id="color_picker" class="form-control form-control-lg" value="#00e4bc" />

          <input type="text" id="color_picker" class="form-control form-control-lg" value="#0084ff" />

  </form>

```

答:
I've just noticed the error of my ways. I was not setting my vars using var.

```<code>// loop the iris wrappers
$('.iris-wrapper','#form').each(function() {

  // set up current object vars
  var $input                    = $('INPUT', this);
  var $inputGroup       = $('.input-group', this);
  var $inputIndicator = $('.input-group-text', this);

  ...

});
</code>```

See working fiddle here https://jsfiddle.net/joshmoto/ucxf7gt8/1/

Working code below..

// each loop the iris wrapper class elems
$('.iris-wrapper','#form').each(function() {

  // set up current object vars
  var $input    = $('INPUT', this);
  var $inputGroup   = $('.input-group', this);
  var $inputIndicator   = $('.input-group-text', this);

  // set our input color indicator to default color
  $inputIndicator.css('background-color', $input.val());

  // init iris
  $input.iris({
    // on iris change
    change: function(event, ui) {
      // update input value on change
      $input.attr('value', ui.color.toString());
      // load the current value
      $inputIndicator.css('background-color', ui.color.toString());
    }
  });

  // move iris color picker after the input group
  $('.iris-picker', this).insertAfter($inputGroup);

  // input blur function
  $input.blur(function() {
    setTimeout(function() {
      if (!$(document.activeElement).closest(".iris-picker").length)
        $input.iris('hide');
      else
        $input.focus();
    }, 0);
  });

  // when input is focused
  $input.focus(function() {
    // input iris show
    $input.iris('show');
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.input-group-prepend .input-group-text::before  {
  width: 18px;
  content: "";
  display: block;
  height: 1px;
}

.iris-picker {
  position: absolute;
  margin-top: 5px;
}</code>```

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>

  <form id="form">

          <input type="text" id="color_picker" class="form-control form-control-lg" value="#00e4bc" />

          <input type="text" id="color_picker" class="form-control form-control-lg" value="#0084ff" />

  </form>

```

Body:
I'm trying to create a jQuery function that can target iris color picker to multiple inputs using a class.

I need each input iris color picker to work independently.

I am really surprised that $.each(function() does not work as you would expect with Iris. I can't get my head round it.

See fiddle here https://jsfiddle.net/joshmoto/Lmez4oft/

I would appreciate any thoughts on how to get iris working independently by using my .iris-wrapper class as the target.

See my full code below...

// each loop the iris wrapper class elems
$('.iris-wrapper','#form').each(function() {

  // set up current object vars
  $input    = $('INPUT', this);
  $inputGroup   = $('.input-group', this);
  $inputIndicator   = $('.input-group-text', this);

  // set our input color indicator to default color
  $inputIndicator.css('background-color', $input.val());

  // init iris
  $input.iris({
    // on iris change
    change: function(event, ui) {
      // update input value on change
      $input.attr('value', ui.color.toString());
      // load the current value
      $inputIndicator.css('background-color', ui.color.toString());
    }
  });

  // move iris color picker after the input group
  $('.iris-picker', this).insertAfter($inputGroup);

  // input blur function
  $input.blur(function() {
    setTimeout(function() {
      if (!$(document.activeElement).closest(".iris-picker").length)
        $input.iris('hide');
      else
        $input.focus();
    }, 0);
  });

  // when input is focused
  $input.focus(function() {
    // input iris show
    $input.iris('show');
  });

});

.input-group-prepend .input-group-text::before  {
  width: 18px;
  content: "";
  display: block;
  height: 1px;
}

.iris-picker {
  position: absolute;
  margin-top: 5px;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>

  <form id="form">

          <input type="text" id="color_picker" class="form-control form-control-lg" value="#00e4bc" />

          <input type="text" id="color_picker" class="form-control form-control-lg" value="#0084ff" />

  </form>

Body:
I've just noticed the error of my ways. I was not setting my vars using var.

// loop the iris wrappers
$('.iris-wrapper','#form').each(function() {

  // set up current object vars
  var $input                    = $('INPUT', this);
  var $inputGroup       = $('.input-group', this);
  var $inputIndicator = $('.input-group-text', this);

  ...

});

See working fiddle here https://jsfiddle.net/joshmoto/ucxf7gt8/1/

Working code below..

// each loop the iris wrapper class elems
$('.iris-wrapper','#form').each(function() {

  // set up current object vars
  var $input    = $('INPUT', this);
  var $inputGroup   = $('.input-group', this);
  var $inputIndicator   = $('.input-group-text', this);

  // set our input color indicator to default color
  $inputIndicator.css('background-color', $input.val());

  // init iris
  $input.iris({
    // on iris change
    change: function(event, ui) {
      // update input value on change
      $input.attr('value', ui.color.toString());
      // load the current value
      $inputIndicator.css('background-color', ui.color.toString());
    }
  });

  // move iris color picker after the input group
  $('.iris-picker', this).insertAfter($inputGroup);

  // input blur function
  $input.blur(function() {
    setTimeout(function() {
      if (!$(document.activeElement).closest(".iris-picker").length)
        $input.iris('hide');
      else
        $input.focus();
    }, 0);
  });

  // when input is focused
  $input.focus(function() {
    // input iris show
    $input.iris('show');
  });

});

.input-group-prepend .input-group-text::before  {
  width: 18px;
  content: "";
  display: block;
  height: 1px;
}

.iris-picker {
  position: absolute;
  margin-top: 5px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://dev.joshmoto.wtf/iris/dist/iris.min.js"></script>

<!-- Gravity forms html mark up below -->

<div class="container pt-3">
  <form id="form">
    <div class="form-row">
      <div class="form-group col-6 iris-wrapper">
        <div class="input-group">
          <div class="input-group-prepend">
            <span class="input-group-text" style="background-color:#00e4bc"></span>
          </div>
          <input type="text" id="color_picker" class="form-control form-control-lg" value="#00e4bc" />
        </div>
      </div>
      <div class="form-group col-6 iris-wrapper">
        <div class="input-group">
          <div class="input-group-prepend">
            <span class="input-group-text" style="background-color:#0084ff"></span>
          </div>
          <input type="text" id="color_picker" class="form-control form-control-lg" value="#0084ff" />
        </div>
      </div>
    </div>
  </form>
</div>


问:
Error in aws-amplify style.css while running the npm test
Had issue while running the npm test

```<code>C:\projects\Test\node_modules\@aws-amplify\ui\dist\style.css:13:root {^
</code>```

error:

```<code>SyntaxError: Unexpected token :

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.<anonymous> (node_modules/aws-amplify-react/src/Amplify-UI/Amplify-UI-Components-React.jsx:5:1)
</code>```

here are my import statements

import Amplify from 'aws-amplify';
import { AuthPiece } from 'aws-amplify-react';
import { Auth, Logger, JS } from 'aws-amplify';

If I comment out the style.css it works without any errors.
But how can I remove this issue so that it doesnt cause issue to others when I commit code.

Had checked all the existing answers provided in different forums.But that doesnt work for me.

答:
I ran into this problem as well, and this thread helped me resolve it. In my case, I needed to install identity-obj-proxy package and map it to the jest config:

npm install --save-dev identity-obj-proxy

package.json

```<code>"jest": {
    "moduleNameMapper": {
      "\\.(css|less)$": "identity-obj-proxy"
    }
  }
</code>```

I hope this helps!

Body:
Had issue while running the npm test

C:\projects\Test\node_modules\@aws-amplify\ui\dist\style.css:13:root {^

error:

SyntaxError: Unexpected token :

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.<anonymous> (node_modules/aws-amplify-react/src/Amplify-UI/Amplify-UI-Components-React.jsx:5:1)

here are my import statements

import Amplify from 'aws-amplify';
import { AuthPiece } from 'aws-amplify-react';
import { Auth, Logger, JS } from 'aws-amplify';

If I comment out the style.css it works without any errors.
But how can I remove this issue so that it doesnt cause issue to others when I commit code.

Had checked all the existing answers provided in different forums.But that doesnt work for me.

Body:
I ran into this problem as well, and this thread helped me resolve it. In my case, I needed to install identity-obj-proxy package and map it to the jest config:

npm install --save-dev identity-obj-proxy

package.json

"jest": {
    "moduleNameMapper": {
      "\\.(css|less)$": "identity-obj-proxy"
    }
  }

I hope this helps!


问:
How can I elegantly implement multiple string replacements in the same file?
Currently I have some code to replace strings in a file that looks like this:

```<code>File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "( " + column.Key + " )",
    " " + column.Value + " "
));
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
));
</code>```

However, each replacement opens and closes the file, and it seems that occasionally they run "too fast" and one replacement will not work because the file did not close yet in a previous string replacement. Is there any code I can reuse that solves this issue, perhaps using the FileStream class (so I can open and close once)? Or suggestions on a better way to do this? Just wondering if there is something simpler I can do than having to create byte arrays of the strings I want to replace and writing code to read, write, and seek through bytes manually. Thanks.

答:
Well, the simlest method would be to ReadAllText, do your replacements and then WriteAllText.

```<code>var text = File.ReadAllText(filePath);
text = Regex.Replace(text,"( " + column.Key + " )"," " + column.Value + " ");
text = Regex.Replace(text,"(\\[\"" + column.Key + "\"\\])","[\"" + column.Value + "\"]");
File.WriteAllText(text,filePath);
</code>```

Body:
Currently I have some code to replace strings in a file that looks like this:

File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "( " + column.Key + " )",
    " " + column.Value + " "
));
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
));

However, each replacement opens and closes the file, and it seems that occasionally they run "too fast" and one replacement will not work because the file did not close yet in a previous string replacement. Is there any code I can reuse that solves this issue, perhaps using the FileStream class (so I can open and close once)? Or suggestions on a better way to do this? Just wondering if there is something simpler I can do than having to create byte arrays of the strings I want to replace and writing code to read, write, and seek through bytes manually. Thanks.

Body:
Well, the simlest method would be to ReadAllText, do your replacements and then WriteAllText.

var text = File.ReadAllText(filePath);
text = Regex.Replace(text,"( " + column.Key + " )"," " + column.Value + " ");
text = Regex.Replace(text,"(\\[\"" + column.Key + "\"\\])","[\"" + column.Value + "\"]");
File.WriteAllText(text,filePath);


问:
getting "Error 411 (Length Required)" when submitting text for translation
I'm just getting started with Google Translate, and I'm using the Python API.  My source language is Simplified Chinese.

For small bits of text (like an article title), it works fine.

When I tried sending an entire article, I got a 413 error saying my request was too big.  According to running len(text), my article is only 2236 characters long, but that's in Unicode, so maybe it gets blown out beyond the 5000 character suggestion/limit when going over the wire.

When I chop off the string at 1000 unicode characters, I get "Error 411, Length Required".

I'm suspecting that my blind chop at 1000 characters is cutting some character in half, but I can't figure out where the content_length is being set (and there's really no exposed parameters in the translate() method that look likely to help)

答:
If anyone is still running into this issue, upgrading to the latest google-cloud-translate client should fix the issue. For more information, the PR here fixed the problem for me, which was that the client was using GET requests instead of POST requests.

Note: This should also fix a related error of getting 413 (Request Entity Too Large) when sending a list of appropriately sized text to translate.


问:
How to stop mysqli_query from adding records with missing info?
I have form that subscribers enter their email address and this gets posted to mysql database. The problem is that if you visit the page, even without subscribing, a record is added to the database even without the required email address. Even worse, it seems to be adding records every three seconds. How can i stop this? Is there something wrong in my code.</p>

```<code><?php

$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
    die("connection error: " . mysqli_connect_error());
}
echo "connected";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST['email'])) {
        $emailErr = "Email required";
    } else {
        $email = post_input($_POST['email']);
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        if (!isset($emailErr)) {
            if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $emailErr = "Invalid email address";
            }
        }
    }
}
// function to clean email
function post_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
    echo "Thank you for subscribing";
} else {
    echo "Error creating record: " . "<br>" . mysqli_error($conn);
}
header('location: index.php');
mysqli_close($conn);
</code>```

答:
Just check with the if statement if there is an email you can save and put saving to database into that if statement as below:</p>

```<code><?php

$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
    die("connection error: " . mysqli_connect_error());
}
echo "connected";

$emailErr = ''; //it is a good practice to initialize variable before its use.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST['email'])) {
        $emailErr = "Email required";
    } else {
        $email = post_input($_POST['email']);
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        if (!isset($emailErr)) {
            if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $emailErr = "Invalid email address";
            }
        }
    }
}
// function to clean email
function post_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");

//if you have an email in $email and there is no
//error in $emailErr
if(!empty($email) && empty($emailErr)) {

    //insert it to the db.

    //THIS IS INSECURE WAY - Check links in comments!

    // query to insert email
    $sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
    if (mysqli_query($conn, $sql)) {
        echo "Thank you for subscribing";
    } else {
        echo "Error creating record: " . "<br>" . mysqli_error($conn);
    }

}

mysqli_close($conn);
header('location: index.php');
exit();
</code>```

Body:
I have form that subscribers enter their email address and this gets posted to mysql database. The problem is that if you visit the page, even without subscribing, a record is added to the database even without the required email address. Even worse, it seems to be adding records every three seconds. How can i stop this? Is there something wrong in my code.

<?php

$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
    die("connection error: " . mysqli_connect_error());
}
echo "connected";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST['email'])) {
        $emailErr = "Email required";
    } else {
        $email = post_input($_POST['email']);
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        if (!isset($emailErr)) {
            if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $emailErr = "Invalid email address";
            }
        }
    }
}
// function to clean email
function post_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
    echo "Thank you for subscribing";
} else {
    echo "Error creating record: " . "
" . mysqli_error($conn);
}
header('location: index.php');
mysqli_close($conn);

Body:
Just check with the if statement if there is an email you can save and put saving to database into that if statement as below:

<?php

$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
    die("connection error: " . mysqli_connect_error());
}
echo "connected";

$emailErr = ''; //it is a good practice to initialize variable before its use.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST['email'])) {
        $emailErr = "Email required";
    } else {
        $email = post_input($_POST['email']);
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        if (!isset($emailErr)) {
            if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $emailErr = "Invalid email address";
            }
        }
    }
}
// function to clean email
function post_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");

//if you have an email in $email and there is no
//error in $emailErr
if(!empty($email) && empty($emailErr)) {

    //insert it to the db.

    //THIS IS INSECURE WAY - Check links in comments!

    // query to insert email
    $sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
    if (mysqli_query($conn, $sql)) {
        echo "Thank you for subscribing";
    } else {
        echo "Error creating record: " . "<br>" . mysqli_error($conn);
    }

}

mysqli_close($conn);
header('location: index.php');
exit();


问:
How do check if a PHP session is empty?
Is this bad practice?

```<code>if ($_SESSION['something'] == '')
{
    echo 'the session is empty';
}
</code>```

Is there a way to check if its empty or it is not set? I'm actualy doing this:

```<code>if (($_SESSION['something'] == '') || (!isset($_SESSION['something'])) {
    echo 'the session is either empty or doesn\'t exist';
}
</code>```

Does !isset just checks if a $_SESSION[''] exist and doesn't check if, is there are values in the array or not

答:
I know this is old, but I ran into an issue where I was running a function after checking if there was a session.  It would throw an error everytime I tried loading the page after logging out, still worked just logged an error page.  Make sure you use exit(); if you are running into the same problem.</p>

```<code>     function sessionexists(){
        if(!empty($_SESSION)){
     return true;
         }else{
     return false;
         }
      }

        if (!sessionexists()){
           redirect("https://www.yoursite.com/");
           exit();
           }else{call_user_func('check_the_page');
         }
</code>```

Title: How do check if a PHP session is empty?

Body:
Is this bad practice?

if ($_SESSION['something'] == '')
{
    echo 'the session is empty';
}

Is there a way to check if its empty or it is not set? I'm actualy doing this:

if (($_SESSION['something'] == '') || (!isset($_SESSION['something'])) {
    echo 'the session is either empty or doesn\'t exist';
}

Does !isset just checks if a $_SESSION[''] exist and doesn't check if, is there are values in the array or not

Body:
I know this is old, but I ran into an issue where I was running a function after checking if there was a session.  It would throw an error everytime I tried loading the page after logging out, still worked just logged an error page.  Make sure you use exit(); if you are running into the same problem.

     function sessionexists(){
        if(!empty($_SESSION)){
     return true;
         }else{
     return false;
         }
      }

        if (!sessionexists()){
           redirect("https://www.yoursite.com/");
           exit();
           }else{call_user_func('check_the_page');
         }


问:
Delphi: PopupMenu doesn't work in my component
English Translation (been a while, so may not be entirely accurate; used google translate for the parts I had trouble with):

I'm working on a Visual Component  in Delphi (it's not a standard Delphi component) which possesses a property called PopupMenu. I associated the property PopupMenu in the component with the PopupMenu, but when I click the right button [of the mouse], I see nothing.

I also tried to force it to display with this code:

```<code>x:= Mouse.CursorPos.X;
y:= Mouse.CursorPos.Y;
// //showmessage(inttostr(x)) PopupMenu1.Popup(x,y);
</code>```

I have two questions:

How do you know that the right click of the mouse is active? Have any of you encountered this type of problem? Thank you for your answers.

Thanks

EDIT

Here is the procedure that I'm using to execute the PopupMenu1: procedure

```<code>TForm6.GeckoBrowser1DOMMouseDown(Sender: TObject; Key: Word);
var x,y:integer;
begin
  if key=VK_RBUTTON then begin
    x:= Mouse.CursorPos.X;
    y:= Mouse.CursorPos.Y;
    //showmessage(inttostr(x)) PopupMenu1.Popup(x,y);
  end;
end;
</code>```

答:
This will never work. You cannot mix code in a form with the component code.

I would suggest something like this:

```<code>interface

type
  TGeckoBrowser = class(....
private
  FPopupmenu: TPopupMenu;
protected
  ...
  procedure MouseUp(Sender: TObject; Key: Word); override;
  ...
published
  property PopupMenu: TPopupMenu read FPopupMenu write FPopupMenu;
end;

implementation

....

procedure TGeckoBrowser.MouseUp(Sender: TObject; Key: Word);
var
  x,y: integer;
begin
  inherited;
  if (key=VK_RBUTTON) and Assigned(PopupMenu) then begin
    x:= Mouse.CursorPos.X;
    y:= Mouse.CursorPos.Y;
    PopupMenu.Popup(x,y);
  end; {if}
end;
</code>```

or if you do not want the OnMouseUp to fire when a popup menu appears do:

```<code>implementation

....

procedure TGeckoBrowser.MouseUp(Sender: TObject; Key: Word);
var
  x,y: integer;
begin
  if (key=VK_RBUTTON) and Assigned(PopupMenu) then begin
    x:= Mouse.CursorPos.X;
    y:= Mouse.CursorPos.Y;
    PopupMenu.Popup(x,y);
  end {if}
  else inherited;
end;
</code>```

See the difference? Popupmenu is now a part (well linked part anyway) of your component and not something that just happens to be on the same form.

Body:
English Translation (been a while, so may not be entirely accurate; used google translate for the parts I had trouble with):

I'm working on a Visual Component  in Delphi (it's not a standard Delphi component) which possesses a property called PopupMenu. I associated the property PopupMenu in the component with the PopupMenu, but when I click the right button [of the mouse], I see nothing.

I also tried to force it to display with this code:

x:= Mouse.CursorPos.X;
y:= Mouse.CursorPos.Y;
// //showmessage(inttostr(x)) PopupMenu1.Popup(x,y);

I have two questions:

How do you know that the right click of the mouse is active? Have any of you encountered this type of problem? Thank you for your answers.

Thanks

EDIT

Here is the procedure that I'm using to execute the PopupMenu1: procedure

TForm6.GeckoBrowser1DOMMouseDown(Sender: TObject; Key: Word);
var x,y:integer;
begin
  if key=VK_RBUTTON then begin
    x:= Mouse.CursorPos.X;
    y:= Mouse.CursorPos.Y;
    //showmessage(inttostr(x)) PopupMenu1.Popup(x,y);
  end;
end;

Body:
This will never work. You cannot mix code in a form with the component code.

I would suggest something like this:

interface

type
  TGeckoBrowser = class(....
private
  FPopupmenu: TPopupMenu;
protected
  ...
  procedure MouseUp(Sender: TObject; Key: Word); override;
  ...
published
  property PopupMenu: TPopupMenu read FPopupMenu write FPopupMenu;
end;

implementation

....

procedure TGeckoBrowser.MouseUp(Sender: TObject; Key: Word);
var
  x,y: integer;
begin
  inherited;
  if (key=VK_RBUTTON) and Assigned(PopupMenu) then begin
    x:= Mouse.CursorPos.X;
    y:= Mouse.CursorPos.Y;
    PopupMenu.Popup(x,y);
  end; {if}
end;

or if you do not want the OnMouseUp to fire when a popup menu appears do:

implementation

....

procedure TGeckoBrowser.MouseUp(Sender: TObject; Key: Word);
var
  x,y: integer;
begin
  if (key=VK_RBUTTON) and Assigned(PopupMenu) then begin
    x:= Mouse.CursorPos.X;
    y:= Mouse.CursorPos.Y;
    PopupMenu.Popup(x,y);
  end {if}
  else inherited;
end;

See the difference? Popupmenu is now a part (well linked part anyway) of your component and not something that just happens to be on the same form.


问:
How can I get the root of my project in ASP.NET and not the location of IIS Express using .CurrentDirectory()?
I have an ASP.NET Core project that I'm developing and I'm making use of LiteDB as a database solution. In order to instantiate my database I need to provide a URI so that the program knows where to create the database.

Usually I'd do something like System.Environment.CurrentDirectory() to find the current directory I'm in and modify that, however the result of this command turns out to be C:\program files\IIS Express or something similar. Basically the current directory points to the location of IIS Express.

Instead I want to get the root of my ASP.NET project, the location that contains my controllers folder, appsettings.json, bin and obj folders.

What command do I need to use to get a string representing this location? I don't want to use a hard coded string for obvious reasons.

答:
You may be better served by using a dedicated location (such as a network share) rather than the folder that contains the executable code. Having user data mixed into deployed code comes with a lot of headaches:

Deployments become more complex as they need to account for the presence of user data. This is especially true if you need to delete pre-existing code during a deployment.

If the user data is sensitive, developers may be denied access to read the deployed code. This can make troubleshooting issues much harder.

Backups of deployed code will contain user data, which means they will always appear to be different even if nothing (code-wise) has changed.

Of course, this all assumes that the production environment is configured differently from developers' local machines.


问:
How can I $match on everything in an if...else?
I'm setting up a MongoDB aggregation pipeline and part of it is using a $match if a parameter is provided, or else trying to $match everything.

There's a method, self.products(), which returns a list of every product I'd like to query if no parameter is provided but I can't figure out how ti either integrate that or use $match with a wildcard for everything.

```<code>    self.pipeline = [
        {
            '$lookup':
                {
                    'from': 'timeseries',
                    'localField': '_id',
                    'foreignField': '_id',
                    'as': 'everything'
                }
        },
        {
            '$unwind': '$everything'
        },
        {
            '$project': {
                '_id': 1,
                'header': 1,
                'item': 1,
                'data': '$everything.data'
            }
        },
        {
            '$match': {
                'product.real': product if product else self.products()
            }
        }

    ]
</code>```

答:
Solved it with:</p>

```<code>{
    '$match': {
        'product.real': product if product else {'$exists': True}
    }
}
</code>```

Body:
I'm setting up a MongoDB aggregation pipeline and part of it is using a $match if a parameter is provided, or else trying to $match everything.

There's a method, self.products(), which returns a list of every product I'd like to query if no parameter is provided but I can't figure out how ti either integrate that or use $match with a wildcard for everything.

    self.pipeline = [
        {
            '$lookup':
                {
                    'from': 'timeseries',
                    'localField': '_id',
                    'foreignField': '_id',
                    'as': 'everything'
                }
        },
        {
            '$unwind': '$everything'
        },
        {
            '$project': {
                '_id': 1,
                'header': 1,
                'item': 1,
                'data': '$everything.data'
            }
        },
        {
            '$match': {
                'product.real': product if product else self.products()
            }
        }

    ]

Body:
Solved it with:

{
    '$match': {
        'product.real': product if product else {'$exists': True}
    }
}


问:
Using stored procedure to produce excel file
I am trying to use this stored procedure below to create a list which I can then export as an Excel file. I have been using Entity Framework thus far, but I am unsure how to go about this in my controller:</p>

```<code>CREATE PROCEDURE [dbo].[spFlugReport]
(
   @AccNo INTEGER,
   @DateFrom DATE,
   @DateTo DATE
)
AS
BEGIN
    SELECT *
    FROM [dbo].[KIRData]
    WHERE AccNo = @AccNo
      AND StartDate >= @DateFrom
      AND EndDate <= @DateTo
      AND Prod = 'Air'
END
</code>```

答:
That sounds like a combination of 2 questions:

How to call a stored procedure, and

How to create an Excel document

For calling a stored procedure, there is a good thread here that should be useful to you, it explains how to use Entity to call a stored procedure
How to call Stored Procedure in Entity Framework 6 (Code-First)?

Second, to create an Excel document I'd suggest you have a look at ClosedXML, it's pretty straight forward to use and has proven reliable at producing Excel docs https://github.com/closedxml/closedxml and https://www.nuget.org/packages/ClosedXML

Hope that helps.

Body:
I am trying to use this stored procedure below to create a list which I can then export as an Excel file. I have been using Entity Framework thus far, but I am unsure how to go about this in my controller:

CREATE PROCEDURE [dbo].[spFlugReport]
(
   @AccNo INTEGER,
   @DateFrom DATE,
   @DateTo DATE
)
AS
BEGIN
    SELECT *
    FROM [dbo].[KIRData]
    WHERE AccNo = @AccNo
      AND StartDate >= @DateFrom
      AND EndDate <= @DateTo
      AND Prod = 'Air'
END


问:
What is the need of SMTP AUTH?
I want to write an application which can receive emails locally and can response with successful and error responses.

After reading some tutorials about how SMTP works I was trying to send an email using telnet to my locally running SMTP server.

Connect to SMTP server

HELO/EHLO command

AUTH ...

MAIL from command

RCPT to command

DATA command

write somedata

QUITE

What I couldn't understand is step 3. Why do I need to be authenticated to send an email to localhost. I mean if I am yahoo user and I have to send an email to gmail user, how can I be authenticated to gmail SMTP server?

答:
SMTP AUTH protects the server from unauthorized use.  For example, Google doesn't allow people to send email from Google's email servers unless they have an account.  You prove that you have an account (or that you are somehow authorized to use their servers) by authenticating with the AUTH command.

Maybe an example where the email service isn't free would be more clear.  If you are trying to send email using GoDaddy's email servers, but you don't have an account, they will prevent you from doing it.  GoDaddy charges people to use their services.

If you are running a company called mycompany.com, and you run your own mail servers, you don't want every spammer in the world using your servers to send email out of your company.  You require senders to authenticate using AUTH in order to protect your servers from unauthorized use.

Title: What is the need of SMTP AUTH?


问:
How do I write a Tensorflow custom op containing a persistent C++ object?
I'm developing a Tensorflow sequence model that uses a beam search through an OpenFST decoding graph (loaded from a binary file) over the logits output from a Tensorflow sequence model.

I've written a custom op that allows me to perform decoding over the logits, but each time, I'm having the op call fst::Read(BINARY_FILE) before performing the decoding. This might be fine as long as it stays small but I'd like to avoid the I/O overhead.

I've read through the Tensorflow custom op and tried to find similar examples but I'm still lost. Basically, what I want to do in the graph is:

FstDecodingOp.Initialize('BINARY_FILE.bin') #loads the BINARY_FILE.bin into memory
...
for o in output:
    FstDecodingOp.decode(o) # uses BINARY_FILE.bin to decode

```

<p>This would of course be straightforward in Python outside of the tensorflow graph, but I need to eventually move this into a vanilla TF-Serving environment, so it needs to get frozen into an export graph. Has anyone encountered a similar problem before? </p>

<p><strong>Solution:</strong></p>

<p>Didn't realize that you could set private attributes using the "OpKernel(context)". Just initialized it using that function.</p>

<p><strong>Edit: more detail on how I did it. Have yet to try serving.</strong></p>

<pre class="lang-cpp prettyprint-override"><code>REGISTER_OP("FstDecoder")
    .Input("log_likelihoods: float")
    .Attr("fst_decoder_path: string")
    ....

...

template <typename Device, typename T>
class FstDecoderOp : public OpKernel {

private:
   fst::Fst<fst::StdArc>* fst_;
   float beam_;

public:
  explicit FstDecoderOp(OpKernelConstruction* context) : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("beam", &beam_));

    std::string fst_path;
    OP_REQUIRES_OK(context, context->GetAttr("fst_decoder_path", &fst_path));

    fst_ = fst::Fst<fst::StdArc>::Read(fst_path);
  }

  void Compute(OpKernelContext* context) override {
    // do some compute
    const Tensor* log_likelihoods;

    OP_REQUIRES_OK(context, context->input("log_likelihoods",
     &log_likelihoods));

    // simplified
    compute_op(_fst, log_likelihoods);

  }
};
</code>```

In python:

sess = tf.Session()
mat = tf.placeholder(tf.float32, shape=test_npy.shape)
res_ = decoder_op.fst_decoder(beam=30, fst_decoder_path="decoder_path.fst", log_likelihoods=mat)
res = sess.run(res_, {mat : test_npy} )

```

答:
Solution:

Didn't realize that you could set private attributes using the "OpKernel(context)". Just initialized it using that function.

Edit: more detail on how I did it. Have yet to try serving.

REGISTER_OP("FstDecoder")
    .Input("log_likelihoods: float")
    .Attr("fst_decoder_path: string")
    ....

...

template <typename Device, typename T>
class FstDecoderOp : public OpKernel {

private:
   fst::Fst<fst::StdArc>* fst_;
   float beam_;

public:
  explicit FstDecoderOp(OpKernelConstruction* context) : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("beam", &beam_));

    std::string fst_path;
    OP_REQUIRES_OK(context, context->GetAttr("fst_decoder_path", &fst_path));

    fst_ = fst::Fst<fst::StdArc>::Read(fst_path);
  }

  void Compute(OpKernelContext* context) override {
    // do some compute
    const Tensor* log_likelihoods;

    OP_REQUIRES_OK(context, context->input("log_likelihoods",
     &log_likelihoods));

    // simplified
    compute_op(_fst, log_likelihoods);

  }
};
```

<p>In python:</p>

<pre class="lang-py prettyprint-override"><code>
sess = tf.Session()
mat = tf.placeholder(tf.float32, shape=test_npy.shape)
res_ = decoder_op.fst_decoder(beam=30, fst_decoder_path="decoder_path.fst", log_likelihoods=mat)
res = sess.run(res_, {mat : test_npy} )

</code>```

Body:
I'm developing a Tensorflow sequence model that uses a beam search through an OpenFST decoding graph (loaded from a binary file) over the logits output from a Tensorflow sequence model.

I've written a custom op that allows me to perform decoding over the logits, but each time, I'm having the op call fst::Read(BINARY_FILE) before performing the decoding. This might be fine as long as it stays small but I'd like to avoid the I/O overhead.

I've read through the Tensorflow custom op and tried to find similar examples but I'm still lost. Basically, what I want to do in the graph is:

FstDecodingOp.Initialize('BINARY_FILE.bin') #loads the BINARY_FILE.bin into memory
...
for o in output:
    FstDecodingOp.decode(o) # uses BINARY_FILE.bin to decode

This would of course be straightforward in Python outside of the tensorflow graph, but I need to eventually move this into a vanilla TF-Serving environment, so it needs to get frozen into an export graph. Has anyone encountered a similar problem before?

Solution:

Didn't realize that you could set private attributes using the "OpKernel(context)". Just initialized it using that function.

Edit: more detail on how I did it. Have yet to try serving.

REGISTER_OP("FstDecoder")
    .Input("log_likelihoods: float")
    .Attr("fst_decoder_path: string")
    ....

...

template <typename Device, typename T>
class FstDecoderOp : public OpKernel {

private:
   fst::Fst<fst::StdArc>* fst_;
   float beam_;

public:
  explicit FstDecoderOp(OpKernelConstruction* context) : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("beam", &beam_));

    std::string fst_path;
    OP_REQUIRES_OK(context, context->GetAttr("fst_decoder_path", &fst_path));

    fst_ = fst::Fst<fst::StdArc>::Read(fst_path);
  }

  void Compute(OpKernelContext* context) override {
    // do some compute
    const Tensor* log_likelihoods;

    OP_REQUIRES_OK(context, context->input("log_likelihoods",
     &log_likelihoods));

    // simplified
    compute_op(_fst, log_likelihoods);

  }
};

In python:

sess = tf.Session()
mat = tf.placeholder(tf.float32, shape=test_npy.shape)
res_ = decoder_op.fst_decoder(beam=30, fst_decoder_path="decoder_path.fst", log_likelihoods=mat)
res = sess.run(res_, {mat : test_npy} )


问:
React js. How to make a component with this structure: <Component> description of the component </Component>
I have the following code. And I am having trouble understanding how the ProjectCardDescription component should be implemented in order to be able to pass its description within the ProjectCard component

I've tried this, but got an empty component:

```<code>import React, { Component } from 'react';

class ProjectCardDescription extends Component {
    render () {
        return (
            <span>
                {this.props.description}
            </span>
        );
    }
}

export default ProjectCardDescription;
</code>```

This is how my ProjectCard component looks like:

```<code>import React, { Component } from 'react';
import ProjectCardIcon from './ProjectCardIcon/ProjectCardIcon';
import './ProjectCard.css';
import ProjectCardDescription from './ProjectCardDescription/ProjectCardDescription';

class ProjectCard extends Component {
    render() {
        return(
            <div className="project-card project-card-medium">
                <a href="https://www.linkedin.com/in/florovarelaa/" target="_blank" rel="noopener noreferrer">
                    <ProjectCardIcon icon='react'/>
                    <ProjectCardDescription>
                        Una descripcion de un projecto hecho en react. Que contiene dos oraciones.
                    </ProjectCardDescription>
                </a>
            </div>
        );
    };
}
export default ProjectCard;
</code>```

I would like to get the ProjectCardDescription Component with its propper
inside html. Should I pass it as props?

答:
You didn't pass the component a description prop. This is done via (what look like) HTML attributes, as follows:

```<code><ProjectCardDescription description="my description here" />
</code>```

Note also that this is all you need, you don't need (or want) a closing tag and content inside. The render method of that component tells it how to convert the props to its internal content.

Body:
I have the following code. And I am having trouble understanding how the ProjectCardDescription component should be implemented in order to be able to pass its description within the ProjectCard component

I've tried this, but got an empty component:

import React, { Component } from 'react';

class ProjectCardDescription extends Component {
    render () {
        return (

                {this.props.description}

        );
    }
}

export default ProjectCardDescription;

This is how my ProjectCard component looks like:

import React, { Component } from 'react';
import ProjectCardIcon from './ProjectCardIcon/ProjectCardIcon';
import './ProjectCard.css';
import ProjectCardDescription from './ProjectCardDescription/ProjectCardDescription';

class ProjectCard extends Component {
    render() {
        return(

                    <ProjectCardIcon icon='react'/>
                    <ProjectCardDescription>
                        Una descripcion de un projecto hecho en react. Que contiene dos oraciones.
                    </ProjectCardDescription>

        );
    };
}
export default ProjectCard;

I would like to get the ProjectCardDescription Component with its propper
inside html. Should I pass it as props?

Body:
You didn't pass the component a description prop. This is done via (what look like) HTML attributes, as follows:

<ProjectCardDescription description="my description here" />

Note also that this is all you need, you don't need (or want) a closing tag and content inside. The render method of that component tells it how to convert the props to its internal content.


问:
Trim Values existing in Mongo Database
The data in my collection may have white spaces in the front and at the back what I want to do is trim all white spaces and make a == comparison to get the appropriate record my code below:

```<code>var test = await _dataStore.FindMostRecentAsync(x => x.Barcodes.PrimaryBarcode.Trim() == barcode.Trim());
</code>```

When I run this code it gives me an error .Trim() not supported (it works only when I trim the barcode string variable that I pass in.

What is the best way to trim the data in my collection so I can have an exact comparison.

Stack Trace

at
  MongoDB.Driver.Linq.Translators.PredicateTranslator.GetFieldExpression(Expression
  expression)    at
  MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateComparison(Expression
  variableExpression, ExpressionType operatorType, ConstantExpression
  constantExpression)    at
  MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression
  node)    at
  MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression
  node, IBsonSerializerRegistry serializerRegistry)    at
  MongoDB.Driver.MongoCollectionImpl1.CreateFindOperation[TProjection](FilterDefinition1
  filter, FindOptions2 options)    at
  MongoDB.Driver.MongoCollectionImpl1.FindAsync[TProjection](IClientSessionHandle
  session, FilterDefinition1 filter, FindOptions2 options,
  CancellationToken cancellationToken)    at
  MongoDB.Driver.MongoCollectionImpl1.<>c__DisplayClass37_01.b__0(IClientSessionHandle
  session)    at
  MongoDB.Driver.MongoCollectionImpl1.UsingImplicitSessionAsync[TResult](Func2
  funcAsync, CancellationToken cancellationToken)

答:
The solution I came up for this was to do the following:

```<code>var test = await _dataStore.FindMostRecentAsync(x => x.Barcodes.PrimaryBarcode.Contains(barcode.Trim()));
</code>```

Instead of trying to trim the values that existed in the database I will trim the variable and then do a Contains that way I will get all the values that match my barcode, later on with that array of objects I can go ahead and filter by date or what not.

I have not found any way in which we can pass in the Trim() method for the collection object using the C# MongoDriver

Title: Trim Values existing in Mongo Database

Body:
The data in my collection may have white spaces in the front and at the back what I want to do is trim all white spaces and make a == comparison to get the appropriate record my code below:

var test = await _dataStore.FindMostRecentAsync(x => x.Barcodes.PrimaryBarcode.Trim() == barcode.Trim());

When I run this code it gives me an error .Trim() not supported (it works only when I trim the barcode string variable that I pass in.

What is the best way to trim the data in my collection so I can have an exact comparison.

Stack Trace

at
  MongoDB.Driver.Linq.Translators.PredicateTranslator.GetFieldExpression(Expression
  expression)    at
  MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateComparison(Expression
  variableExpression, ExpressionType operatorType, ConstantExpression
  constantExpression)    at
  MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression
  node)    at
  MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression
  node, IBsonSerializerRegistry serializerRegistry)    at
  MongoDB.Driver.MongoCollectionImpl1.CreateFindOperation[TProjection](FilterDefinition1
  filter, FindOptions2 options)    at
  MongoDB.Driver.MongoCollectionImpl1.FindAsync[TProjection](IClientSessionHandle
  session, FilterDefinition1 filter, FindOptions2 options,
  CancellationToken cancellationToken)    at
  MongoDB.Driver.MongoCollectionImpl1.<>c__DisplayClass37_01.b__0(IClientSessionHandle
  session)    at
  MongoDB.Driver.MongoCollectionImpl1.UsingImplicitSessionAsync[TResult](Func2
  funcAsync, CancellationToken cancellationToken)

Body:
The solution I came up for this was to do the following:

var test = await _dataStore.FindMostRecentAsync(x => x.Barcodes.PrimaryBarcode.Contains(barcode.Trim()));

Instead of trying to trim the values that existed in the database I will trim the variable and then do a Contains that way I will get all the values that match my barcode, later on with that array of objects I can go ahead and filter by date or what not.

I have not found any way in which we can pass in the Trim() method for the collection object using the C# MongoDriver


问:
Is there a way to modify the page title with React-Router v4+?
I'm looking for a way to modify the page title when React-Router v4+ changes locations. I used to listen for a location change action in Redux and check that route against a metaData object.

When using React-Router v4+, there's no fixed routes list. In fact, various components around the site could use Route with the same path string. That means old method I used won't work anymore.

Is there a way I can update the page title by calling actions when certain major routes are changed or is there a better a better method to update the site's metadata?

答:
Using a functional component on your main routing page, you can have the title change on each route change with useEffect.

For example,

```<code>const Routes = () => {
    useEffect(() => {
      let title = history.location.pathname
      document.title = title;
    });

    return (
      <Switch>
        <Route path='/a' />
        <Route path='/b' />
        <Route path='/c' />
      </Switch>
    );
}
</code>```

Body:
Using a functional component on your main routing page, you can have the title change on each route change with useEffect.

For example,

const Routes = () => {
    useEffect(() => {
      let title = history.location.pathname
      document.title = title;
    });

    return (
      <Switch>
        <Route path='/a' />
        <Route path='/b' />
        <Route path='/c' />
      </Switch>
    );
}


问:
Creating API versioning for my php application (Social App)
I'm currently working on a Social Application.

I would like to have a versioning system on my PHP backend, but I don't know where to start: I have looked up a bunch of articles online, but I couldn't really understand what I've found.

Let's say my application is v1.0. Then I create a new version v2.0 and of course I update the PHP files too. After this, if someone hasn't updated their app from v1.0, I would like them to reach myapp.com/v1.0/ so that the app doesn't crash.

What would you recommend?

A typical PHP file of mine looks like this, for example:

```<code><?php

// Include files

include_once ('../../config.php');

include_once (ROOT_DIR . '/config/includes.php');

$_USERDATA = Validator::validateUser($_POST["userId"], $_POST["session"]);

// Valid session

$qry = $db->prepare('SELECT n.id, n.type, n.time, n.isRead, n.postId, n.commentId, n.text, n.inReplyToCommentId, u.id as byUserId,
    ( SELECT COUNT(nu.id)
    FROM notificationUsers AS nu
    WHERE nu.notificationId = n.id ) as detail1,
    ( SELECT nu2.userId
    FROM notificationUsers AS nu2
    WHERE nu2.notificationId = n.id ORDER BY nu2.id DESC LIMIT 1 ) as latestUserId FROM notifications AS n LEFT JOIN userData AS u ON n.byUserId = u.id
    WHERE n.userId = :userId ORDER BY n.time DESC');
$qry->bindParam(':userId', $_USERDATA["userId"], PDO::PARAM_INT);
$qry->execute();

$notificationsArray = $qry->fetchAll(PDO::FETCH_ASSOC);

$returnValue = array();
$returnValue["status"] = "1";
$returnValue["title"] = "Success";
$returnValue["message"] = "Downloaded notifications";
$returnValue["data_notifications"] = $notificationsArray;
exit(json_encode($returnValue));

?>
</code>```

...

UPDATE 1

So I decided to do the following:

Placing every not shared file inside a folder like so:

```<code>/api/v1.0/file.php
</code>```

But every resource for example (images) is outside the API

```<code>/resources/images/profilepictures/image.jpg
</code>```

If I make a minor change, I just update the files within the api/v1.0/ folder.

Then, all the users that are using the Application v1.1, they are requesting myapp.com/api/v1.1/, but I redirect them to api/v1.0/ where I can present the users the right data (depending on if the request was from v1.0 or v1.1)

If the versions add up and I release a bigger update, I'll create a new folder with the name v2.0, and so it goes...

Or what do you think? How should I do it?

答:
You're defining your architecture to future proof your design, which is good first step.

If you use a framework like Laravel or Symfony, you may keep your Models and Helpers directory common while making Controllers directory versioned with sub-directory like v1.x, v2.x etc.

It can make your life easy if you use a routing mechanism so let us say for example your v1.0 has 50 API endpoints and you're planning to modify 5 of them for v1.2 w/o backwards compatibility, in that case all rest of the 45 API endpoints would still be identical to v1.0 and you don't want to duplicate them in your v1.2 directory.

```<code><?php

$versions = ["v1.0", "v1.2"];

route("/api/v1.0/foobar", "Controllers/v1.0/FoobarController@doSomething");
route("/api/v1.0/footar", "Controllers/v1.0/FoobarController@doTar");

route("/api/v1.2/foobar", "Controllers/v1.2/FoobarController@doSomething");

function route($endpoint, $controller)
{
    // Logic to call function of a respective class/file
    // and call previous version of an API if function/endpoint is not redefined in current version
}
?>
</code>```

So in above case, when client calls /api/v1.2/footar, it should execute /api/v1.0/footar for API consumer.

I hope it helps.

Body:
I'm currently working on a Social Application.

I would like to have a versioning system on my PHP backend, but I don't know where to start: I have looked up a bunch of articles online, but I couldn't really understand what I've found.

Let's say my application is v1.0. Then I create a new version v2.0 and of course I update the PHP files too. After this, if someone hasn't updated their app from v1.0, I would like them to reach myapp.com/v1.0/ so that the app doesn't crash.

What would you recommend?

A typical PHP file of mine looks like this, for example:

<?php

// Include files

include_once ('../../config.php');

include_once (ROOT_DIR . '/config/includes.php');

$_USERDATA = Validator::validateUser($_POST["userId"], $_POST["session"]);

// Valid session

$qry = $db->prepare('SELECT n.id, n.type, n.time, n.isRead, n.postId, n.commentId, n.text, n.inReplyToCommentId, u.id as byUserId,
    ( SELECT COUNT(nu.id)
    FROM notificationUsers AS nu
    WHERE nu.notificationId = n.id ) as detail1,
    ( SELECT nu2.userId
    FROM notificationUsers AS nu2
    WHERE nu2.notificationId = n.id ORDER BY nu2.id DESC LIMIT 1 ) as latestUserId FROM notifications AS n LEFT JOIN userData AS u ON n.byUserId = u.id
    WHERE n.userId = :userId ORDER BY n.time DESC');
$qry->bindParam(':userId', $_USERDATA["userId"], PDO::PARAM_INT);
$qry->execute();

$notificationsArray = $qry->fetchAll(PDO::FETCH_ASSOC);

$returnValue = array();
$returnValue["status"] = "1";
$returnValue["title"] = "Success";
$returnValue["message"] = "Downloaded notifications";
$returnValue["data_notifications"] = $notificationsArray;
exit(json_encode($returnValue));

?>

...

UPDATE 1

So I decided to do the following:

Placing every not shared file inside a folder like so:

/api/v1.0/file.php

But every resource for example (images) is outside the API

/resources/images/profilepictures/image.jpg

If I make a minor change, I just update the files within the api/v1.0/ folder.

Then, all the users that are using the Application v1.1, they are requesting myapp.com/api/v1.1/, but I redirect them to api/v1.0/ where I can present the users the right data (depending on if the request was from v1.0 or v1.1)

If the versions add up and I release a bigger update, I'll create a new folder with the name v2.0, and so it goes...

Or what do you think? How should I do it?

Body:
You're defining your architecture to future proof your design, which is good first step.

If you use a framework like Laravel or Symfony, you may keep your Models and Helpers directory common while making Controllers directory versioned with sub-directory like v1.x, v2.x etc.

It can make your life easy if you use a routing mechanism so let us say for example your v1.0 has 50 API endpoints and you're planning to modify 5 of them for v1.2 w/o backwards compatibility, in that case all rest of the 45 API endpoints would still be identical to v1.0 and you don't want to duplicate them in your v1.2 directory.

<?php

$versions = ["v1.0", "v1.2"];

route("/api/v1.0/foobar", "Controllers/v1.0/FoobarController@doSomething");
route("/api/v1.0/footar", "Controllers/v1.0/FoobarController@doTar");

route("/api/v1.2/foobar", "Controllers/v1.2/FoobarController@doSomething");

function route($endpoint, $controller)
{
    // Logic to call function of a respective class/file
    // and call previous version of an API if function/endpoint is not redefined in current version
}
?>

So in above case, when client calls /api/v1.2/footar, it should execute /api/v1.0/footar for API consumer.

I hope it helps.


问:
Sendgrid brand link with nginx proxy
We try to set a brand link with custom ssl with this doc https://sendgrid.com/docs/ui/account-and-settings/custom-ssl-configurations/.

We follow it, and now we have a proxy, with certificat, and that's redirect to sendgrid.net.

Support tell us that their test say "FAIL: We did not get a 200 response back from the test 'https' click tracking link." And tell us also that certificat wildcard on proxy is not supported.

I don't understand the wildcard reason, and the proxy send not a 200, because sendgrid.net send a 404

So I don't understand what to do.

We use nginx and this example to implement our proxy : https://gist.github.com/jjhiew/cbbd26da313fc550467e303a6c6f8177

答:
Thanks for the reminder. We do have it working, but I forgot to post it here. The general idea is to
have branded click requests go to our own server, which has the TLS certifiate. I.e. link.mysite.com
goes to our own server instead of SendGrid. Our server accepts those requests, makes the identical
request to SendGrid. Whatever SendGrid replies to our server, we send back to the browser.

I'm not sure but I think the SendGrid support folks had to flip some switch. But that might be wrong. I do remember I talked to them, and I remember they didn't understand this proxy situation. Did I finally get someone who did, or did I get it working without them, I'm not sure.

Below is the code we use for this (Ruby on Rails):

```<code># Allow SendGrid Click Tracking to use HTTPS
#
# SendGrid click tracking uses the host 'link.example.com' but HSTS requires that host
# respond to HTTPS. However SendGrid does not have our certificate. So instead point
# link.example.com to this proxy, and we make the same request to sendgrid.
#
# see: https://sendgrid.com/docs/ui/account-and-settings/custom-ssl-configurations/
#
# Configuring SendGrid, Heroku, and DNSimple for Click Tracking and unsubscribes
# ------------------------------------------------------------------------------
#   Sendgrid > Sender Authentication > Link Branding
#     Create branded link for example.com
#     Advanced Settings > Custom link subdomain: link
#
#   DNS > make the CNAME records they mention
#   Sendgrid >
#     verify branded links so they are activated.
#     Make link the default.
#
#   Heroku > configure subdomain for link.example.com
#   DNS > change CNAME record so link.example.com points to Heroku, e.g. blah.blah.herokudns.com
#
#   Test:
#       Unsubscribe links that start with link.example.com/___ should work now.
#
#   Sendgrid > Tracking > Click Tracking > ON
#
#   Test:
#     Send a test Frisky Friday.
#     Follow link to article--it should start with link.example.com
#     SendGrid increments the Click Tracking counter
class SendgridLinkProxyController < ActionController::Base
  SENDGRID_CLICK_TRACKING_URL = 'https://sendgrid.net'.freeze

  def index
    # Make matching request to SendGrid
    sendgrid_url = URI.parse("#{SENDGRID_CLICK_TRACKING_URL}#{request.env['ORIGINAL_FULLPATH']}").to_s
    sendgrid_headers = { 'Host' => CFG.SENDGRID_PROXY_HOSTNAME }

    Rails.logger.info("sendgrid_link_proxy_controller.rb: fetching #{sendgrid_url}, headers: #{sendgrid_headers}")
    sendgrid_response = HTTParty.get(sendgrid_url, headers: sendgrid_headers, follow_redirects: false) # , debug_output: STDOUT)

    # Make matching response to browser
    user_response_status = sendgrid_response.code
    response.set_header('location', sendgrid_response.headers['location'])
    Rails.logger.info("sendgrid_link_proxy_controller.rb: responding status_code: #{user_response_status}, location header: #{response.header['location']}")
    render html: sendgrid_response.body.html_safe, # We are trusting SendGrid. Winston think's that's OK. [Winston Dec 2018]
           status: user_response_status
  end
end
</code>```

And here's an RSpec file to go with it:

```<code>require 'spec_helper'

describe SendgridLinkProxyController do

  describe '#index' do
    before do
      @sendgrid_response = {
        headers: {},
        body: '<html>SENDGRID BODY</html>',
        code: 200
      }
      request.env['ORIGINAL_FULLPATH'] = '/wf/click?upn=BLAH'
      CFG.SENDGRID_PROXY_HOSTNAME = 'link.example.com'
    end

    subject do
      allow(HTTParty)
        .to receive(:get)
        .and_return(double('Mock Sendgrid Response', @sendgrid_response))
      get :index, params: {a: 'click'}
    end

    it 'requests page from sendgrid with same path and with Host header' do
      expect(HTTParty).to receive(:get)
        .with('https://sendgrid.net/wf/click?upn=BLAH',
              headers: { 'Host' => 'link.example.com' },
              follow_redirects: false
             )

      subject
    end

    context 'when receiving a click-tracking redirect link' do
      before do
        @sendgrid_response[:code] = 302
        @sendgrid_response[:headers]['location'] = 'https://example.com/TARGET'
      end

      it 'redirects browser to target link' do
        subject

        expect(response.status).to eq(302)
        expect(response.headers['location']).to eq('https://example.com/TARGET')
      end
    end

    context 'when receiving an unsubcribe link' do
      before do
        request.env['ORIGINAL_FULLPATH'] = '/wf/unsubscribe?upn=BLAH'
      end

      it 'renders sendgrid\'s unsubscribe page' do
        subject

        expect(response.body).to eq('<html>SENDGRID BODY</html>')
      end
    end
  end
end
</code>```

Title: Sendgrid brand link with nginx proxy

Body:
Thanks for the reminder. We do have it working, but I forgot to post it here. The general idea is to
have branded click requests go to our own server, which has the TLS certifiate. I.e. link.mysite.com
goes to our own server instead of SendGrid. Our server accepts those requests, makes the identical
request to SendGrid. Whatever SendGrid replies to our server, we send back to the browser.

I'm not sure but I think the SendGrid support folks had to flip some switch. But that might be wrong. I do remember I talked to them, and I remember they didn't understand this proxy situation. Did I finally get someone who did, or did I get it working without them, I'm not sure.

Below is the code we use for this (Ruby on Rails):

# Allow SendGrid Click Tracking to use HTTPS
#
# SendGrid click tracking uses the host 'link.example.com' but HSTS requires that host
# respond to HTTPS. However SendGrid does not have our certificate. So instead point
# link.example.com to this proxy, and we make the same request to sendgrid.
#
# see: https://sendgrid.com/docs/ui/account-and-settings/custom-ssl-configurations/
#
# Configuring SendGrid, Heroku, and DNSimple for Click Tracking and unsubscribes
# ------------------------------------------------------------------------------
#   Sendgrid > Sender Authentication > Link Branding
#     Create branded link for example.com
#     Advanced Settings > Custom link subdomain: link
#
#   DNS > make the CNAME records they mention
#   Sendgrid >
#     verify branded links so they are activated.
#     Make link the default.
#
#   Heroku > configure subdomain for link.example.com
#   DNS > change CNAME record so link.example.com points to Heroku, e.g. blah.blah.herokudns.com
#
#   Test:
#       Unsubscribe links that start with link.example.com/___ should work now.
#
#   Sendgrid > Tracking > Click Tracking > ON
#
#   Test:
#     Send a test Frisky Friday.
#     Follow link to article--it should start with link.example.com
#     SendGrid increments the Click Tracking counter
class SendgridLinkProxyController < ActionController::Base
  SENDGRID_CLICK_TRACKING_URL = 'https://sendgrid.net'.freeze

  def index
    # Make matching request to SendGrid
    sendgrid_url = URI.parse("#{SENDGRID_CLICK_TRACKING_URL}#{request.env['ORIGINAL_FULLPATH']}").to_s
    sendgrid_headers = { 'Host' => CFG.SENDGRID_PROXY_HOSTNAME }

    Rails.logger.info("sendgrid_link_proxy_controller.rb: fetching #{sendgrid_url}, headers: #{sendgrid_headers}")
    sendgrid_response = HTTParty.get(sendgrid_url, headers: sendgrid_headers, follow_redirects: false) # , debug_output: STDOUT)

    # Make matching response to browser
    user_response_status = sendgrid_response.code
    response.set_header('location', sendgrid_response.headers['location'])
    Rails.logger.info("sendgrid_link_proxy_controller.rb: responding status_code: #{user_response_status}, location header: #{response.header['location']}")
    render html: sendgrid_response.body.html_safe, # We are trusting SendGrid. Winston think's that's OK. [Winston Dec 2018]
           status: user_response_status
  end
end

And here's an RSpec file to go with it:

require 'spec_helper'

describe SendgridLinkProxyController do

  describe '#index' do
    before do
      @sendgrid_response = {
        headers: {},
        body: '<html>SENDGRID BODY</html>',
        code: 200
      }
      request.env['ORIGINAL_FULLPATH'] = '/wf/click?upn=BLAH'
      CFG.SENDGRID_PROXY_HOSTNAME = 'link.example.com'
    end

    subject do
      allow(HTTParty)
        .to receive(:get)
        .and_return(double('Mock Sendgrid Response', @sendgrid_response))
      get :index, params: {a: 'click'}
    end

    it 'requests page from sendgrid with same path and with Host header' do
      expect(HTTParty).to receive(:get)
        .with('https://sendgrid.net/wf/click?upn=BLAH',
              headers: { 'Host' => 'link.example.com' },
              follow_redirects: false
             )

      subject
    end

    context 'when receiving a click-tracking redirect link' do
      before do
        @sendgrid_response[:code] = 302
        @sendgrid_response[:headers]['location'] = 'https://example.com/TARGET'
      end

      it 'redirects browser to target link' do
        subject

        expect(response.status).to eq(302)
        expect(response.headers['location']).to eq('https://example.com/TARGET')
      end
    end

    context 'when receiving an unsubcribe link' do
      before do
        request.env['ORIGINAL_FULLPATH'] = '/wf/unsubscribe?upn=BLAH'
      end

      it 'renders sendgrid\'s unsubscribe page' do
        subject

        expect(response.body).to eq('<html>SENDGRID BODY</html>')
      end
    end
  end
end


问:
Pass hashed password from $request->validated in Laravel?
Is there a way I can create the user with the hashed password, not plain password?</p>

```<code>public function post(StoreUserRequest $request) {
    User::create($request->validated());
    return redirect()->route('frontend.login')->with('message', 'Your account has been created!');
}
</code>```

答:
What are you using to Hash your password? But also you can, because a hash in just a string. Your field password in DB, probably is a string too. You can use Laravel Auth too. This provide a full authentication system with one line on terminal

php artisan make:auth

Body:
Is there a way I can create the user with the hashed password, not plain password?

public function post(StoreUserRequest $request) {
    User::create($request->validated());
    return redirect()->route('frontend.login')->with('message', 'Your account has been created!');
}


问:
How does Keycloak use the LDAP attributes defined in User Federation?
In setting up User Federation from an LDAP provider, there are three LDAP attributes:

Username LDAP attribute

RDN LDAP attribute

UUID LDAP attribute

How does the value of each of these impact Keycloak or the sync process?

For instance, if the directory ensures unique email addresses, are there any negatives to using mail as the UUID LDAP attribute?

Where can I find details on each of these attributes--specific to Keycloak?

答:
In Keycloak admin console, you may hover over the tooltip - a tiny question mark - next to the LDAP attribute label if you want as much info as possible about it. I checked this on Keycloak v6.0.1 but I assume it applies to most recent versions. Such tooltip will often give more info than you can find on the Keycloak documentation website. More details about these attributes:

Username LDAP attribute: Name of LDAP attribute which is mapped as Keycloak username. For many LDAP server vendors it can be 'uid'. For Active Directory it can be 'sAMAccountName' or 'cn'. The attribute should be filled for all LDAP user records you want to import from LDAP to Keycloak. So there you could use the mail attribute if you want this as username in Keycloak. Then users would log on to Keycloak with their email address. If you enable LDAP synchronization to Keycloak local database (switch on Import Users), this will be recorded there as username.

RDN LDAP attribute: Name of LDAP attribute which is used as RDN (top attribute) of typical user DN. Usually it's the same as Username LDAP attribute, however it's not required. For example for Active directory it's common to use 'cn' as RDN attribute when username attribute might be 'sAMAccountName'. For example with a conventional LDAP directory (not Active Directory) where user DNs are typically uid=XXX,ou=people,dc=example,dc=com, you would use 'uid' there.

[EDIT 2019-05-31] The RDN attribute is actually used for instance when you create a new user in Keycloak. If you have the Edit Mode option set to WRITABLE in the settings, Keycloak synchronizes it back to the LDAP directory, i.e. creates the new user entry in LDAP. For that, it needs (among other things) the RDN and the Users DN (another option below the RDN) to make the full DN of the new user LDAP entry.

UUID LDAP attribute: Name of LDAP attribute which is used as unique object identifier (UUID) for objects in LDAP. For many LDAP server vendors, it's 'entryUUID' however some are different. For example for Active Directory it should be 'objectGUID'. If your LDAP server really doesn't support the notion of UUID, you can use any other attribute, which is supposed to be unique among LDAP users in tree. For example 'uid' or 'entryDN'. Any standard LDAP v3 directory should use entryUUID (OpenLDAP, OpenDJ...).

Regarding best practices on UUID in LDAP directories, you may look at the RFC 4530 standard.

In general, I would advise against using 'mail' as UUID, because a user's 'mail' may change (see reasons down below), whereas an entry UUID - whether it is a user entry or not - is meant to be a globally uniquely generated number (or at least contain such a number), usually generated on server side, and fixed once and for all for the entry. (Furthermore, it shall not be reused ever, even after the entry is deleted, as UUIDs should be unique in time and space.) In particular, it should be independent from any of the user's variable attributes, like email address.

Indeed, a user's email address may change during his/her lifetime in the organization for various reasons, just to name a few:

Users - women typically - may get married or divorced, and therefore may change their last name.

Top management decides to rebrand the company and therefore change the mail domain.

The company is going through a merger or an acquisition with/by another company and therefore the mail domain changes again.

...


问:
Coding in Objective-C 2.0 screencasts?
Has anyone used the Pragmatic Programmers screencast series Coding in Objective-C 2.0?

They look good, but I don't know if I could get just as much value out of a text book or other web links.

答:
I bought both screen casts. I'm neither a starving student nor a starving out of work developer, so $5 is effectively free.

A screen cast can cover material fairly quickly because there's no need to stop and describe what's going on; the viewer gets to watch every step. There's none of the awkwardness you find in books that have to use words to describe every step in great detail.

So yes, I found them to be worth the $5 and I'll buy any more that come out.

OwnerDisplayName: Steven Behnke

ContentLicense: CC BY-SA 2.5

Title: Coding in Objective-C 2.0 screencasts?

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: Terry Wilcox


问:
Jackson annotation to convert BigDecimal value and set scale to 2
I have POJO like where I have a BigDecimal field:

```<code>public class Foo implements Serializable {

   private BigDecimal amount;
}
</code>```

I want to have the BigDecimal value up to 2 decimal place only. Is there any annotation exist using which I can directly change it's value at the field level itself? I cannot change it's type as well.

Though it can be done with getter and ObjectMapper within the application.

答:
When you want to set scale you need to take care about rounding. You have some options such as ROUND_HALF_EVEN and you need to decide which rounding mode to use.

To intercept BigDecimal deserialisation you can write custom deserialiser. Below example shows how to do that, we can extend default one and set scale after deserialzation:

```<code>import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.NumberDeserializers;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();

        Foo person = mapper.readValue(jsonFile, Foo.class);
        System.out.println(person);
    }
}

class BigDecimal2JsonDeserializer extends NumberDeserializers.BigDecimalDeserializer {

    @Override
    public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        BigDecimal value = super.deserialize(p, ctxt);

        // set scale
        value = value.setScale(2, BigDecimal.ROUND_HALF_EVEN);

        return value;
    }
}

class Foo {

    @JsonDeserialize(using = BigDecimal2JsonDeserializer.class)
    private BigDecimal amount;

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    @Override
    public String toString() {
        return "Foo{" +
                "amount=" + amount +
                '}';
    }
}
</code>```

For below JSON payload:

```<code>{
  "amount": 16.127
}
</code>```

above app prints:

```<code>Foo{amount=16.13}
</code>```

Body:
I have POJO like where I have a BigDecimal field:

public class Foo implements Serializable {

   private BigDecimal amount;
}

I want to have the BigDecimal value up to 2 decimal place only. Is there any annotation exist using which I can directly change it's value at the field level itself? I cannot change it's type as well.

Though it can be done with getter and ObjectMapper within the application.

Body:
When you want to set scale you need to take care about rounding. You have some options such as ROUND_HALF_EVEN and you need to decide which rounding mode to use.

To intercept BigDecimal deserialisation you can write custom deserialiser. Below example shows how to do that, we can extend default one and set scale after deserialzation:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.NumberDeserializers;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();

        Foo person = mapper.readValue(jsonFile, Foo.class);
        System.out.println(person);
    }
}

class BigDecimal2JsonDeserializer extends NumberDeserializers.BigDecimalDeserializer {

    @Override
    public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        BigDecimal value = super.deserialize(p, ctxt);

        // set scale
        value = value.setScale(2, BigDecimal.ROUND_HALF_EVEN);

        return value;
    }
}

class Foo {

    @JsonDeserialize(using = BigDecimal2JsonDeserializer.class)
    private BigDecimal amount;

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    @Override
    public String toString() {
        return "Foo{" +
                "amount=" + amount +
                '}';
    }
}

For below JSON payload:

{
  "amount": 16.127
}

above app prints:

Foo{amount=16.13}


问:
I can't understand "String.format() function in this example any help ?"
this an example to get mac address form my machine but i can't understand the syntax of sting.format function
here is the example.

public String getMACIdentifier(NetworkInterface network)
{
    StringBuilder identifier = new StringBuilder();
    try {
        byte[] macBuffer = network.getHardwareAddress();
        if (macBuffer != null) {
            for (int i = 0; i < macBuffer.length; i++) {
                identifier.append(
                    String.format("%02X%s",macBuffer[i],
                    (i < macBuffer.length - 1) ? "-" : ""));
            }
        } else {
            return "---";
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }

    return identifier.toString();
}
```

答:
Have you try it?

```<code>public static void main(String[] args) {
    StringBuilder identifier = new StringBuilder();
    byte[] macBuffer = new byte[5];

    macBuffer[0] = 0x10;
    macBuffer[1] = 0x1;
    macBuffer[2] = 0x02;
    macBuffer[3] = 0x30;

    for (int i = 0; i < macBuffer.length; i++) {
        identifier.append(
                String.format("%02X%s", macBuffer[i],
                        (i < macBuffer.length - 1) ? "-" : ""));
    }

    System.out.println(identifier.toString());
}
</code>```

Output

```<code>10-01-02-30-00
</code>```

"%02X%s"

%02X this is for hexadecimal format and the 02 refer to the minimum number of chars (0x1 is printed as 0x01)

%s this is for string format

Body:
Have you try it?

public static void main(String[] args) {
    StringBuilder identifier = new StringBuilder();
    byte[] macBuffer = new byte[5];

    macBuffer[0] = 0x10;
    macBuffer[1] = 0x1;
    macBuffer[2] = 0x02;
    macBuffer[3] = 0x30;

    for (int i = 0; i < macBuffer.length; i++) {
        identifier.append(
                String.format("%02X%s", macBuffer[i],
                        (i < macBuffer.length - 1) ? "-" : ""));
    }

    System.out.println(identifier.toString());
}

Output

10-01-02-30-00

"%02X%s"

%02X this is for hexadecimal format and the 02 refer to the minimum number of chars (0x1 is printed as 0x01)

%s this is for string format