问:
Android custom view event listeners not working properly without static reference
I'm creating a custom compound view in android which contains two TextViews within a relative layout. There are two classes, one is BarcodeScannerView which is the compound view and another activity that uses the custom view. The code is as follows.

BarcodeScannerView.java

```<code>    public class BarcodeScannerView extends RelativeLayout implements View.OnClickListener {

    private int boxRadius;
    private String boxText;
    private int boxColor, boxEntityColor;
    private TextView entityName;
    private TextView manualEntry;
    private ImageView scannerReadyImv;
    private RelativeLayout scannerBox;
    private OnClickListener listener;
    private ScannerListener scanner;
    private ScannerState state;
   // private static BarcodeScannerView instance;

    public enum ScannerState {
        IDLE, READY, COMPLETE;
    }

    public interface ScannerListener {

        void onClickScannerBox();
        void scannerIdle();
    }

    public BarcodeScannerView(Context context) {
        super(context);
    }

    public BarcodeScannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {

        View.inflate(context, R.layout.activity_barcode_scanner, this);
        setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS);

        entityName = (TextView) findViewById(R.id.entityNameTV);
        manualEntry = (TextView) findViewById(R.id.manualEntryTV);
        scannerReadyImv = (ImageView) findViewById(R.id.scannerReadyImv);
        scannerBox = (RelativeLayout) findViewById(R.id.scannerBox);

        manualEntry.setOnClickListener(this);
        scannerBox.setOnClickListener(this);

        // Assign custom attributes
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.barcodeviewer, 0, 0);

        try {

            boxEntityColor = a.getInteger(R.styleable.barcodeviewer_boxEntityColor, 0);
            setBoxEntityColor(boxEntityColor);

        } finally {
            a.recycle();
        }

    }

    // Set custom attributes
    private void setBoxEntityColor(int color) {
        this.entityName.setTextColor(color);
    }

    // Set event handlers
    public void setOnClickListener(OnClickListener listener) {
        this.listener = listener;
    }

    public void setOnScannerListener(ScannerListener scanner) {
        this.scanner = scanner;
    }

    // Setters and getters
    public void setScannerState(ScannerState state) {
        this.state = state;
    }

    public ScannerState getScannerState() {
        return this.state;
    }

    private void setScannerReadyState() {
        scannerBox.setBackgroundResource(R.drawable.bc_active_4);
        scannerReadyImv.setVisibility(View.VISIBLE);
    }

    public void onClick(View v) {

        if (v.getId() == R.id.scannerBox) {
            this.scanner.onClickScannerBox();
            if (this.getScannerState() == ScannerState.IDLE) {
                setScannerReadyState();
            }
        }
    }
}
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity implements BarcodeScannerView.ScannerListener {

private BarcodeScannerView barcodeScannerView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    /*barcodeScannerView = BarcodeScannerView.instance(MainActivity.this);
    barcodeScannerView.setOnScannerListener(this);*/
    barcodeScannerView = new BarcodeScannerView(this);
    barcodeScannerView.setOnScannerListener(this);
}

@Override
public void onClickScannerBox() {
    scannerIdle();
}

@Override
public void scannerIdle(){
    barcodeScannerView.setScannerState(BarcodeScannerView.ScannerState.IDLE);
}

}
</code>```

The issue is when I call the onClick() method of the BarcodeScannerView class it gives a null point exception.

java.lang.NullPointerException: Attempt to invoke interface method 'void [packagename]$ScannerListener.onClickScannerBox()' on a null object reference

In debugging I noticed that when the onClickScannerBox() is called, the scanner object get initialized. But after onClickScannerBox() is executed in BarcodeScannerView the scanner object gets null.

According to my observation the reason is when onClickScannerBox() is called one BarcodeScannerView object instance is initialized and when the onClickScannerBox() finishes and comes out of the method since it is in the onClick() method of another BarcodeScannerView object instance the scanner object gets null.

I can simply correct this issue using static scanner object. (The code is not provided here since the gets too long) I don't think having static references is the best approach for this problem. Is there any approach to correct the issue without using any static references? Any suggestions are appreciated.

答:
In your implementation there are two instances of your custom compound view comes into play, one is in the layout (activity layout) and other one is explicitly created one in the activity onCreate method.

```<code>barcodeScannerView = new BarcodeScannerView(this);
barcodeScannerView.setOnScannerListener(this);
</code>```

You have set the listener to the explicitly created one which doesn't have clue about view used in the layout, simply they are two instances. You should use the instance created (inflated) in the xml as follows.

```<code>@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    barcodeScannerView = (BarcodeScannerView) findViewById(R.id.barcode_scanner);
    barcodeScannerView.setOnScannerListener(this);
}
</code>```

barcode_scanner should be the id you have given to the compound view used in the activity layout.

Body:
I'm creating a custom compound view in android which contains two TextViews within a relative layout. There are two classes, one is BarcodeScannerView which is the compound view and another activity that uses the custom view. The code is as follows.

BarcodeScannerView.java

    public class BarcodeScannerView extends RelativeLayout implements View.OnClickListener {

    private int boxRadius;
    private String boxText;
    private int boxColor, boxEntityColor;
    private TextView entityName;
    private TextView manualEntry;
    private ImageView scannerReadyImv;
    private RelativeLayout scannerBox;
    private OnClickListener listener;
    private ScannerListener scanner;
    private ScannerState state;
   // private static BarcodeScannerView instance;

    public enum ScannerState {
        IDLE, READY, COMPLETE;
    }

    public interface ScannerListener {

        void onClickScannerBox();
        void scannerIdle();
    }

    public BarcodeScannerView(Context context) {
        super(context);
    }

    public BarcodeScannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {

        View.inflate(context, R.layout.activity_barcode_scanner, this);
        setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS);

        entityName = (TextView) findViewById(R.id.entityNameTV);
        manualEntry = (TextView) findViewById(R.id.manualEntryTV);
        scannerReadyImv = (ImageView) findViewById(R.id.scannerReadyImv);
        scannerBox = (RelativeLayout) findViewById(R.id.scannerBox);

        manualEntry.setOnClickListener(this);
        scannerBox.setOnClickListener(this);

        // Assign custom attributes
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.barcodeviewer, 0, 0);

        try {

            boxEntityColor = a.getInteger(R.styleable.barcodeviewer_boxEntityColor, 0);
            setBoxEntityColor(boxEntityColor);

        } finally {
            a.recycle();
        }

    }

    // Set custom attributes
    private void setBoxEntityColor(int color) {
        this.entityName.setTextColor(color);
    }

    // Set event handlers
    public void setOnClickListener(OnClickListener listener) {
        this.listener = listener;
    }

    public void setOnScannerListener(ScannerListener scanner) {
        this.scanner = scanner;
    }

    // Setters and getters
    public void setScannerState(ScannerState state) {
        this.state = state;
    }

    public ScannerState getScannerState() {
        return this.state;
    }

    private void setScannerReadyState() {
        scannerBox.setBackgroundResource(R.drawable.bc_active_4);
        scannerReadyImv.setVisibility(View.VISIBLE);
    }

    public void onClick(View v) {

        if (v.getId() == R.id.scannerBox) {
            this.scanner.onClickScannerBox();
            if (this.getScannerState() == ScannerState.IDLE) {
                setScannerReadyState();
            }
        }
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity implements BarcodeScannerView.ScannerListener {

private BarcodeScannerView barcodeScannerView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    /*barcodeScannerView = BarcodeScannerView.instance(MainActivity.this);
    barcodeScannerView.setOnScannerListener(this);*/
    barcodeScannerView = new BarcodeScannerView(this);
    barcodeScannerView.setOnScannerListener(this);
}

@Override
public void onClickScannerBox() {
    scannerIdle();
}

@Override
public void scannerIdle(){
    barcodeScannerView.setScannerState(BarcodeScannerView.ScannerState.IDLE);
}

}

The issue is when I call the onClick() method of the BarcodeScannerView class it gives a null point exception.

java.lang.NullPointerException: Attempt to invoke interface method 'void [packagename]$ScannerListener.onClickScannerBox()' on a null object reference

In debugging I noticed that when the onClickScannerBox() is called, the scanner object get initialized. But after onClickScannerBox() is executed in BarcodeScannerView the scanner object gets null.

According to my observation the reason is when onClickScannerBox() is called one BarcodeScannerView object instance is initialized and when the onClickScannerBox() finishes and comes out of the method since it is in the onClick() method of another BarcodeScannerView object instance the scanner object gets null.

I can simply correct this issue using static scanner object. (The code is not provided here since the gets too long) I don't think having static references is the best approach for this problem. Is there any approach to correct the issue without using any static references? Any suggestions are appreciated.

Body:
In your implementation there are two instances of your custom compound view comes into play, one is in the layout (activity layout) and other one is explicitly created one in the activity onCreate method.

barcodeScannerView = new BarcodeScannerView(this);
barcodeScannerView.setOnScannerListener(this);

You have set the listener to the explicitly created one which doesn't have clue about view used in the layout, simply they are two instances. You should use the instance created (inflated) in the xml as follows.

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    barcodeScannerView = (BarcodeScannerView) findViewById(R.id.barcode_scanner);
    barcodeScannerView.setOnScannerListener(this);
}

barcode_scanner should be the id you have given to the compound view used in the activity layout.


来源: stackexchange

问:
Concatenate two std::vectors in one line using C++11
Is there a way, using C++11, to concatenate two std::vectors in one code line, with the first defined in a local variable, the second returned from a function:

```<code>#include <vector>
#include <iostream>
#include <iterator>

std::vector<int> getNewVector()
{
    return {4,5,6};
}

int main(int argc, char** argv)
{
  std::vector<int> dest;
  std::vector<int> src{1,2,3};

  dest = src + getNewVector(); //Error: no operator "+" matches these operands

  return 0;
}
</code>```

EDIT: differently from this question, that is not using C++11, I would like to know if the new C++11 standard give some useful functionality that would help my task.
As an example, I've used the + operator even if it's not working, but just to give an idea of what I'm looking for.

答:
```<code>namespace named_operator {
  template<class D>struct make_operator{make_operator(){}};

  template<class T, char, class O> struct half_apply { T&& lhs; };

  template<class Lhs, class Op>
  half_apply<Lhs, '+', Op> operator+( Lhs&& lhs, make_operator<Op> ) {
    return {std::forward<Lhs>(lhs)};
  }

  template<class Lhs, class Op, class Rhs>
  auto operator+( half_apply<Lhs, '+', Op>&& lhs, Rhs&& rhs )
  -> decltype( named_invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) ) )
  {
    return named_invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) );
  }
}
</code>```

boilerplate library first, then:

```<code>namespace ops {
  struct concat_t:named_operator::make_operator<concat_t>{};
  static const concat_t concat{};
  template<class T, class A, class A2>
  std::vector<T,A> named_invoke( std::vector<T,A> lhs, concat_t, std::vector<T,A2> const& rhs){
    lhs.insert(lhs.end(), rhs.begin(), rhs.end());
    return std::move(lhs);
  }
}
using ops::concat;
</code>```

writes the +concat+ operator.  End use looks like:

```<code>int main(){
   std::vector<int> a{1,2,3};
   std::vector<int> b{7,8,9};

  for( auto x: a +concat+ a +concat+ b )
    std::cout <<x<<'\n';
}
</code>```

Live example.

Overloading naked + is illegal in std and fragile/dangerous in root namespace.  Fragile due to "in a subnamespace doea not work", dangerous if you make it too greedy.  concat_t tag type avoids both.

And who wants to call a function.  Prefix notation with ()s annoying to chain.

The above copies the left hand side (unless lhs is a temporary), then concatinates the rhs.  Adding move-contents to rhs is juat another named invoke function in namespace ops.  So a+a+b copies a, then extends the copy twice.

An expression template version could avoid hacing to resize more than once, for the usual issues.

ContentLicense: CC BY-SA 3.0

Body:
Is there a way, using C++11, to concatenate two std::vectors in one code line, with the first defined in a local variable, the second returned from a function:

#include <vector>
#include <iostream>
#include <iterator>

std::vector<int> getNewVector()
{
    return {4,5,6};
}

int main(int argc, char** argv)
{
  std::vector<int> dest;
  std::vector<int> src{1,2,3};

  dest = src + getNewVector(); //Error: no operator "+" matches these operands

  return 0;
}

EDIT: differently from this question, that is not using C++11, I would like to know if the new C++11 standard give some useful functionality that would help my task.
As an example, I've used the + operator even if it's not working, but just to give an idea of what I'm looking for.

Body:
namespace named_operator {
  template<class D>struct make_operator{make_operator(){}};

  template<class T, char, class O> struct half_apply { T&& lhs; };

  template<class Lhs, class Op>
  half_apply<Lhs, '+', Op> operator+( Lhs&& lhs, make_operator<Op> ) {
    return {std::forward<Lhs>(lhs)};
  }

  template<class Lhs, class Op, class Rhs>
  auto operator+( half_apply<Lhs, '+', Op>&& lhs, Rhs&& rhs )
  -> decltype( named_invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) ) )
  {
    return named_invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) );
  }
}

boilerplate library first, then:

namespace ops {
  struct concat_t:named_operator::make_operator<concat_t>{};
  static const concat_t concat{};
  template<class T, class A, class A2>
  std::vector<T,A> named_invoke( std::vector<T,A> lhs, concat_t, std::vector<T,A2> const& rhs){
    lhs.insert(lhs.end(), rhs.begin(), rhs.end());
    return std::move(lhs);
  }
}
using ops::concat;

writes the +concat+ operator.  End use looks like:

int main(){
   std::vector<int> a{1,2,3};
   std::vector<int> b{7,8,9};

  for( auto x: a +concat+ a +concat+ b )
    std::cout <<x<<'\n';
}

Live example.

Overloading naked + is illegal in std and fragile/dangerous in root namespace.  Fragile due to "in a subnamespace doea not work", dangerous if you make it too greedy.  concat_t tag type avoids both.

And who wants to call a function.  Prefix notation with ()s annoying to chain.

The above copies the left hand side (unless lhs is a temporary), then concatinates the rhs.  Adding move-contents to rhs is juat another named invoke function in namespace ops.  So a+a+b copies a, then extends the copy twice.

An expression template version could avoid hacing to resize more than once, for the usual issues.


问:
displaying list of dates for loop
i have this code..that will display a list of month for the current year and the first day of first month and second month

```<code>$cur_year = date("Y");
$next_year = $cur_year+1;

for($m=1; $m<=12; ++$m)
{
$monthName=date('F', mktime(0, 0, 0, $m, 1)).'';
$monthNumber=date('m', mktime(0, 0, 0, $m, 1)).'';
$nextmonth=$monthNumber+1;

echo "$monthName<br />";
echo "$cur_year-$monthNumber-01<br />";
echo "$cur_year-$nextmonth-01<br /><br />";
}
</code>```

i would like to be display like this

```<code>January
2017-01-01
2017-02-01

February
2017-02-01
2017-03-01

up to December

December
2017-12-01
2018-01-01
</code>```

current ouput

```<code>January
2017-01-01
2017-2-01

February
2017-02-01
2017-3-01

up to December

December
2017-12-01
2017-13-01
</code>```

答:
Use date() function in PHP

```<code><?php
$cur_year  = date('Y');
$next_year = $cur_year + 1;

for ($m = 1; $m <= 12; ++$m)
{
    $monthName  = date('F', mktime(0, 0, 0, $m, 1));
    $currentMonthText = date('Y-m-d', mktime(0, 0, 0, $m, 1));
    $nextMonthText    = date('Y-m-d', mktime(0, 0, 0, $m + 1, 1));

    echo $monthName, '<br />', PHP_EOL;
    echo $currentMonthText, '<br />' . PHP_EOL;
    echo $nextMonthText, '<br />' . PHP_EOL;
}
</code>```

Title: displaying list of dates for loop

Body:
i have this code..that will display a list of month for the current year and the first day of first month and second month

$cur_year = date("Y");
$next_year = $cur_year+1;

for($m=1; $m<=12; ++$m)
{
$monthName=date('F', mktime(0, 0, 0, $m, 1)).'';
$monthNumber=date('m', mktime(0, 0, 0, $m, 1)).'';
$nextmonth=$monthNumber+1;

echo "$monthName
";
echo "$cur_year-$monthNumber-01
";
echo "$cur_year-$nextmonth-01

";
}

i would like to be display like this

January
2017-01-01
2017-02-01

February
2017-02-01
2017-03-01

up to December

December
2017-12-01
2018-01-01

current ouput

January
2017-01-01
2017-2-01

February
2017-02-01
2017-3-01

up to December

December
2017-12-01
2017-13-01

Body:
Use date() function in PHP

<?php
$cur_year  = date('Y');
$next_year = $cur_year + 1;

for ($m = 1; $m <= 12; ++$m)
{
    $monthName  = date('F', mktime(0, 0, 0, $m, 1));
    $currentMonthText = date('Y-m-d', mktime(0, 0, 0, $m, 1));
    $nextMonthText    = date('Y-m-d', mktime(0, 0, 0, $m + 1, 1));

    echo $monthName, '<br />', PHP_EOL;
    echo $currentMonthText, '<br />' . PHP_EOL;
    echo $nextMonthText, '<br />' . PHP_EOL;
}


问:
Custom processor and backpressuring, throttling
NiFi 1.2.0

There is a custom processor that reads data from db and passes it further. In a recent stress testing, the 'success' relationship queue was clogged and also the later flow as the processor dumped hundred thousands of flow files of several GBs. Obviously, the backpressuring  was not implemented. I also read an informative post about throttling and backpressuring.

What I have figured out is that backpressuring is something we configure in the relationship queue and standard processors like ControlRate can help to regulate the data flow.

Question :

Is additional coding required(e.g: Some interface to be implemented) in the processor to enable it to 'sleep/stop consuming data' for backpressuring or does the NiFi framework handle that, once the 'success' relationship of  the processor is configured for backpressuring

答: No additional coding is required.  The NiFi framework manages backpressure for you and will stop calling your processor when backpressure is applied.</p>


问:
web audio gain node not muting audio completely
I've been trying to either filter, attenuate or mute audio completely in my app. with this code, I've been able to slightly quiet my audio using solutions I found, but setting gainNode.gain.value = 0 doesn't actually set it to 0, and negative integers make it louder. I've thought it possible I have 2 routes for the sound to play through and that the gain node is only one of them, but I don't see how to isolate it. The filter I've added does nothing so far either, but I simply want to be able to cut the sound out.

window.onload = function () {
var volumeBars = {
    mono: document.getElementById("monoFill")
};

document.getElementById("open-file").onchange = function (evt) {
    var file = evt.target.files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        playSound(e.target.result);
    }
    reader.readAsArrayBuffer(file);
}
document.getElementById("open-file1").onchange = function (evt) {
    var file = evt.target.files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        playSound1(e.target.result);
    }
    reader.readAsArrayBuffer(file);
}

var context = new AudioContext();
var context1 = new AudioContext();

var playbackControl = document.querySelector('.playback-rate-control');
    var playbackValue = document.querySelector('.playback-rate-value');
    var panControl = document.querySelector('.panning-control')
    var panValue = document.querySelector('.panning-value');
    var mute = document.querySelector('.mute');
    var gainSlider = document.getElementById("gainSlider");
    var filtControl = document.querySelector(".filter-control")
    var filtValue = document.querySelector(".filter-value");

    function playSound(arraybuffer) {
        context.close();
        context = new AudioContext();

        var source = context.createBufferSource();
        var gainNode = context.createGain();
        var panNode = context.createStereoPanner();
        var filter = context.createBiquadFilter();
        filter.type = 'lowpass';

        source.connect(panNode);
        panNode.connect(context.destination);
        context.decodeAudioData(arraybuffer, function (buffer) {
            source.buffer = buffer;
            source.loop = true;
            source.playbackRate.value = playbackControl.value;

            source.connect(gainNode);

            gainNode.connect(context.destination);
            source.connect(filter);
            filter.connect(gainNode);

            //speed slider
            playbackControl.oninput = function () {
                source.playbackRate.value = playbackControl.value;
                playbackValue.innerHTML = playbackControl.value;
            }
            //pan slider
            panControl.oninput = function () {
                panNode.pan.value = panControl.value;
                //   panValue.innerHTML = panControl.value;
            }
            //filter slider
            filtControl.oninput = function () {
                filter.frequency.value = filtControl.value;
                filtValue.innerHTML = filtControl.value;
            }

            gainSlider.addEventListener('change', function () {
                gainNode.gain = this.value;
            });

            mute.onclick = voiceMute;

            function voiceMute() {
                if (mute.id == "") {
                    gainNode.gain.value = 0;
                    mute.id = "activated";
                    mute.innerHTML = "Unmute";
                } else {
                    gainNode.gain.value = 1;
                    mute.id = "";
                    mute.innerHTML = "Mute";
                }
            }
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <button class="mute">Mute button</button>
</div>
<p><input class="filter-control" type="range" min="0" max="400" step="1" value="400">
<span class="filter-value">1.0</span></p>
<p><input id="gainSlider" type="range" min="0" max="1" step=".05" value="1">Volume</p>
<p><input class="playback-rate-control" type="range" min="0.25" max="3" step="0.01" value="1">
<span class="playback-rate-value">1.0</span></p>
<p><input class="panning-control" type="range" min="-1" max="1" step=".05" value="0">Pan</p></code>```

答:
Add a function to disconnect a node to prevent audio from reaching the destination</p>

```<code>pause=function(){
filter.disconnect();
};
// and to play
var play=function(){
filter.connect(gainNode);
};
</code>```

Body:
I've been trying to either filter, attenuate or mute audio completely in my app. with this code, I've been able to slightly quiet my audio using solutions I found, but setting gainNode.gain.value = 0 doesn't actually set it to 0, and negative integers make it louder. I've thought it possible I have 2 routes for the sound to play through and that the gain node is only one of them, but I don't see how to isolate it. The filter I've added does nothing so far either, but I simply want to be able to cut the sound out.

window.onload = function () {
var volumeBars = {
    mono: document.getElementById("monoFill")
};

document.getElementById("open-file").onchange = function (evt) {
    var file = evt.target.files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        playSound(e.target.result);
    }
    reader.readAsArrayBuffer(file);
}
document.getElementById("open-file1").onchange = function (evt) {
    var file = evt.target.files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        playSound1(e.target.result);
    }
    reader.readAsArrayBuffer(file);
}

var context = new AudioContext();
var context1 = new AudioContext();

var playbackControl = document.querySelector('.playback-rate-control');
    var playbackValue = document.querySelector('.playback-rate-value');
    var panControl = document.querySelector('.panning-control')
    var panValue = document.querySelector('.panning-value');
    var mute = document.querySelector('.mute');
    var gainSlider = document.getElementById("gainSlider");
    var filtControl = document.querySelector(".filter-control")
    var filtValue = document.querySelector(".filter-value");

    function playSound(arraybuffer) {
        context.close();
        context = new AudioContext();

        var source = context.createBufferSource();
        var gainNode = context.createGain();
        var panNode = context.createStereoPanner();
        var filter = context.createBiquadFilter();
        filter.type = 'lowpass';

        source.connect(panNode);
        panNode.connect(context.destination);
        context.decodeAudioData(arraybuffer, function (buffer) {
            source.buffer = buffer;
            source.loop = true;
            source.playbackRate.value = playbackControl.value;

            source.connect(gainNode);

            gainNode.connect(context.destination);
            source.connect(filter);
            filter.connect(gainNode);

            //speed slider
            playbackControl.oninput = function () {
                source.playbackRate.value = playbackControl.value;
                playbackValue.innerHTML = playbackControl.value;
            }
            //pan slider
            panControl.oninput = function () {
                panNode.pan.value = panControl.value;
                //   panValue.innerHTML = panControl.value;
            }
            //filter slider
            filtControl.oninput = function () {
                filter.frequency.value = filtControl.value;
                filtValue.innerHTML = filtControl.value;
            }

            gainSlider.addEventListener('change', function () {
                gainNode.gain = this.value;
            });

            mute.onclick = voiceMute;

            function voiceMute() {
                if (mute.id == "") {
                    gainNode.gain.value = 0;
                    mute.id = "activated";
                    mute.innerHTML = "Unmute";
                } else {
                    gainNode.gain.value = 1;
                    mute.id = "";
                    mute.innerHTML = "Mute";
                }
            }
        });

  <button class="mute">Mute button</button>

<input class="filter-control" type="range" min="0" max="400" step="1" value="400">
1.0

<input id="gainSlider" type="range" min="0" max="1" step=".05" value="1">Volume

<input class="playback-rate-control" type="range" min="0.25" max="3" step="0.01" value="1">
1.0

<input class="panning-control" type="range" min="-1" max="1" step=".05" value="0">Pan

Body:
Add a function to disconnect a node to prevent audio from reaching the destination

pause=function(){
filter.disconnect();
};
// and to play
var play=function(){
filter.connect(gainNode);
};


问:
java regular expression to match file path
I was trying out to create a regular expression to match file path in java like

C:\abc\def\ghi\abc.txt

I tried this ([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\? , like following code

```<code>import java.util.regex.Pattern;

  public class RETester {

public static void main(String arhs[]){

    String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";

    String path = "D:\\directoryname\\testing\\abc.txt";

    Pattern pattern = Pattern.compile(regularExpression);

    boolean isMatched = Pattern.matches(regularExpression,path);
    System.out.println(path);
    System.out.println(pattern.pattern());
    System.out.println(isMatched);

}

}
</code>```

However it's always giving me , false as result .

答:
Java is using backslash-escaping too, you know, so you need to escape your backslashes twice, once for the Java string, and once for the regexp.

```<code>"([a-zA-Z]:)?(\\\\[a-zA-Z0-9_.-]+)+\\\\?"
</code>```

Your regexp matched a literal '[-zA-Z0-9_-' string, and a literal '?' at the end. I also added a period in there to allow 'abc.txt'..

That said, consider using another mechanism for determine valid file names, as there are different schemes (i.e. unix). java.util.File will probably throw an exception if the path is invalid, which might be a good alternative, although I don't like using exceptions for control flow...

ContentLicense: CC BY-SA 4.0

Body:
I was trying out to create a regular expression to match file path in java like

C:\abc\def\ghi\abc.txt

I tried this ([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\? , like following code

import java.util.regex.Pattern;

  public class RETester {

public static void main(String arhs[]){

    String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";

    String path = "D:\\directoryname\\testing\\abc.txt";

    Pattern pattern = Pattern.compile(regularExpression);

    boolean isMatched = Pattern.matches(regularExpression,path);
    System.out.println(path);
    System.out.println(pattern.pattern());
    System.out.println(isMatched);

}

}

However it's always giving me , false as result .

Body:
Java is using backslash-escaping too, you know, so you need to escape your backslashes twice, once for the Java string, and once for the regexp.

"([a-zA-Z]:)?(\\\\[a-zA-Z0-9_.-]+)+\\\\?"

Your regexp matched a literal '[-zA-Z0-9_-' string, and a literal '?' at the end. I also added a period in there to allow 'abc.txt'..

That said, consider using another mechanism for determine valid file names, as there are different schemes (i.e. unix). java.util.File will probably throw an exception if the path is invalid, which might be a good alternative, although I don't like using exceptions for control flow...

ContentLicense: CC BY-SA 2.5


问:
Php making a form entry
I've been working on a PHP project of tours and travels company and I have done adding everything but I am messing up with the buy now form which requires user's name, address, etc.

I cant find any way to get the package name or id from the previous page that is stored in database.

Please help if you can help me figure out this problem.

Thanks in advance!

答:
If you need to save form data in a multistep process, you typically need to insert it with a known value. This can be done with php's uuid() function.

Generate a value with uuid()

Ensure that the value returned by uuid() isn't already used. For a low traffic website the probability is low, but you should definitely still check!

If the value is not unique to your database, loop to step 1. If you have a unique value continue to step 4.

Insert the first part of your records with the uuid.

Insert the rest of your records. The uuid value you generated is now how you'll link the records.

If you don't want to change your DB's foreign key structure, you can use a select statement to pull the primary key that was generated by whatever process you've already setup by selecting the uuid.

Title: Php making a form entry


问:
Number of digits using while true in Python
I'm writing a program on Python 3.6.1 that counts the number of digits of a given number by the user. I'm using the sentence "while True" and not functions or strings because I haven't learned to use them yet. Here is my code:

```<code>number=int(input("Write number: "))
cont=0
while True:
    number=number/10
    cont=cont+1
    if number==0:
        break
print("The number of digits is: ", cont)
</code>```

My problem is the the above code isn't working because when I put, let's say 123, the program gives me the value 326. I don't know what is wrong with my code, so how could I fix this?

答:
Is there a specific reason you don't convert the number to a string and use len(string)?

```<code>len(str(number))
</code>```

Update (thanks to comment):

```<code>len(str(abs(number)))
</code>```

Body:
I'm writing a program on Python 3.6.1 that counts the number of digits of a given number by the user. I'm using the sentence "while True" and not functions or strings because I haven't learned to use them yet. Here is my code:

number=int(input("Write number: "))
cont=0
while True:
    number=number/10
    cont=cont+1
    if number==0:
        break
print("The number of digits is: ", cont)

My problem is the the above code isn't working because when I put, let's say 123, the program gives me the value 326. I don't know what is wrong with my code, so how could I fix this?

Body:
Is there a specific reason you don't convert the number to a string and use len(string)?

len(str(number))

Update (thanks to comment):

len(str(abs(number)))


问:
c# mvc form: how to build view for simple feedback form leveraging the benefit of using html.editorfor?
I have simple input form (basically for feedback) with following fields:
Name, Gender, Mobile-Number, Complaint text. (To simplify I am not mentioning any POST action OR submit button on the form)

Currently, I have created following MVC structure:

```<code>public class ComplaintController
{
    [HttpGet]
    public ActionResult Index()
    {
       return View(); //This view displays the complaint form with all above fields
    }
}
</code>```

I read this and several other links where they suggest to use @Html.EditorFor as it creates UI based on model data-type.

Currently, I am not passing any model to the [HttpGet] view. If I want to use @Html.EditorFor, I need to pass my model to [HttpGet] Index View, how can I do that? What is best pratise to create such MVC forms?

答:
Currently, I am not passing any model to the [HttpGet] view. If I want
  to use @Html.EditorFor, I need to pass my model to [HttpGet] Index
  View, how can I do that?

Hi sahil ,As a first step , create one model class like below

```<code>public class FeedBack
{
   public string  Name{get;set;}
   public string  Gender{get;set;}
   public int  Mobile-Number{get;set;}
   public string  Complaint{get;set;}

  // other additional fields

}
</code>```

And in the controller get method ,pass a model like below

```<code>public class ComplaintController
{
    [HttpGet]
    public ActionResult Index()
    {
      FeedBack OBJFeedback = new FeedBack();
       return View(OBJFeedback);
    }
}
</code>```

And in a view , strongly type this model and post the data as you want to the controller post methods.

Here is the example of strongly typed view : http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/strongly-typed-views-in-mvc/

Important Note : In the get action method , since you dont want to display any values  by default in the view , even if you dont pass model object it will work in the same way.

Hope the above information was useful

Thanks

Karthik

Body:
I have simple input form (basically for feedback) with following fields:
Name, Gender, Mobile-Number, Complaint text. (To simplify I am not mentioning any POST action OR submit button on the form)

Currently, I have created following MVC structure:

public class ComplaintController
{
    [HttpGet]
    public ActionResult Index()
    {
       return View(); //This view displays the complaint form with all above fields
    }
}

I read this and several other links where they suggest to use @Html.EditorFor as it creates UI based on model data-type.

Currently, I am not passing any model to the [HttpGet] view. If I want to use @Html.EditorFor, I need to pass my model to [HttpGet] Index View, how can I do that? What is best pratise to create such MVC forms?

Body:
Currently, I am not passing any model to the [HttpGet] view. If I want
  to use @Html.EditorFor, I need to pass my model to [HttpGet] Index
  View, how can I do that?

Hi sahil ,As a first step , create one model class like below

public class FeedBack
{
   public string  Name{get;set;}
   public string  Gender{get;set;}
   public int  Mobile-Number{get;set;}
   public string  Complaint{get;set;}

  // other additional fields

}

And in the controller get method ,pass a model like below

public class ComplaintController
{
    [HttpGet]
    public ActionResult Index()
    {
      FeedBack OBJFeedback = new FeedBack();
       return View(OBJFeedback);
    }
}

And in a view , strongly type this model and post the data as you want to the controller post methods.

Here is the example of strongly typed view : http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/strongly-typed-views-in-mvc/

Important Note : In the get action method , since you dont want to display any values  by default in the view , even if you dont pass model object it will work in the same way.

Hope the above information was useful

Thanks

Karthik


问:
windows wpf iteratively load Resource files
I am working on a WPF application where I want to display a list of icons that I have embedded as png Images into the Resources folder of my project.
 The images' build action is 'resource', and they are located as follows:

```<code>'NameOfProject'/Resources/Icons/'SomeCategories'/'AllTheIcons'.png
</code>```

Since there are about a thousand I would like to load them into the listview via a foreach-statement like so:

```<code>foreach (imageorwhatever icon in Resources/Icons/Category1) { ... }
foreach (imageorwhatever icon in Resources/Icons/Category2) { ... }
etc.
</code>```

I haven't found a way so far on how I can achieve this. All solutions I have found target every resource individually, or load them from file.

I would prefer loading the images iteratively because I really don't want to define 1000 images in code or xaml

答:
To use them in WPF they need to be part of a ResourceDictionary so they are accessible. Here is some code that works for me:

```<code>using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace ResourceTest
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            var dict = new ResourceDictionary();

            var baseDir = AppDomain.CurrentDomain.BaseDirectory;

            foreach (var file in Directory.GetFiles("Images"))
            {
                dict.Add(file, new BitmapImage(new Uri(Path.Combine(baseDir, file))));
            }

            Application.Current.Resources.MergedDictionaries.Add(dict);

            foreach (var file in Directory.GetFiles("Images"))
            {
                var img = new Image();
                img.Source = (BitmapImage) FindResource(file);

                ListBox.Items.Add(img);
            }
        }
    }
}
</code>```

All you need is the ListBox in your XAML named "ListBox" to run this:

```<code><ListBox x:Name="ListBox"  HorizontalAlignment="Left" Height="238" Margin="23,30,0,0" VerticalAlignment="Top" Width="130"/>
</code>```

I didn't spend long on this and instead of that 2nd loop would be better just to drop the items into a List, then assign to the ResourceDictionary and then the ListBox, but this works.

EDIT: Forgot but the name of the resource I just make the filename as you can see in the above example. Might want to change that or at least remove the extension.

Body:
I am working on a WPF application where I want to display a list of icons that I have embedded as png Images into the Resources folder of my project.
 The images' build action is 'resource', and they are located as follows:

'NameOfProject'/Resources/Icons/'SomeCategories'/'AllTheIcons'.png

Since there are about a thousand I would like to load them into the listview via a foreach-statement like so:

foreach (imageorwhatever icon in Resources/Icons/Category1) { ... }
foreach (imageorwhatever icon in Resources/Icons/Category2) { ... }
etc.

I haven't found a way so far on how I can achieve this. All solutions I have found target every resource individually, or load them from file.

I would prefer loading the images iteratively because I really don't want to define 1000 images in code or xaml

Body:
To use them in WPF they need to be part of a ResourceDictionary so they are accessible. Here is some code that works for me:

using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace ResourceTest
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            var dict = new ResourceDictionary();

            var baseDir = AppDomain.CurrentDomain.BaseDirectory;

            foreach (var file in Directory.GetFiles("Images"))
            {
                dict.Add(file, new BitmapImage(new Uri(Path.Combine(baseDir, file))));
            }

            Application.Current.Resources.MergedDictionaries.Add(dict);

            foreach (var file in Directory.GetFiles("Images"))
            {
                var img = new Image();
                img.Source = (BitmapImage) FindResource(file);

                ListBox.Items.Add(img);
            }
        }
    }
}

All you need is the ListBox in your XAML named "ListBox" to run this:

<ListBox x:Name="ListBox"  HorizontalAlignment="Left" Height="238" Margin="23,30,0,0" VerticalAlignment="Top" Width="130"/>

I didn't spend long on this and instead of that 2nd loop would be better just to drop the items into a List, then assign to the ResourceDictionary and then the ListBox, but this works.

EDIT: Forgot but the name of the resource I just make the filename as you can see in the above example. Might want to change that or at least remove the extension.


问:
How to deploy a connection between two android devices using php host/server
I'm trying to send continuous data (like location) from android device A  to android device B .

Right now android device A sends data to server and server saves data inside database and then device B reads data from server continuously.

1- Is there any way to connect this devices directly or in a way that there is less load on server?

2 Or a way to tell device B to wait until there is new data on server?

3 if I should use push notification  for second question can I make a push notification server of my own and not use google cloud messaging?

4 how does messaging apps like Whatsapp and telegram handle sending data from one phone to another?

答:
Well there are two possibilities that you could go with, the first would be to simply setup a long-polling or websocket connection from Device B to the server, instead of reading the direct data continuously with a new connection each time, you maintain a connection to the server and when new data comes in, the server sends it to you. For more information about this - checkout out this stack Q&A:  What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

The other possibility would be to use push notifications via any number of push services. Personally I like to use the If This Then That (IFTTT) https://ifttt.com maker channel. This is good if it is a personal project, but if you're developing something for an app that you will distribute or as a commercial product you might want to look at some of the paid options. I've also heard that https://pushbots.com/ provides a good service but I haven't used it myself to say so definitely.

If you want to run your own push server check out http://airnotifier.github.io/ for a solution but I think, when it all comes down to it, everything uses the Google Cloud Messaging service, all the push traffic routes through that to get to your Android device as far as I know.


问:
Reading nested tags with sax parser
i am trying to read a xml file with following tag, but the sax parser is unable to read nested tags like

```<code><active-prod-ownership>
  <ActiveProdOwnership>
    <Product code="3N3" component="TRI_SCORE" orderNumber="1-77305469" />
  </ActiveProdOwnership>
</active-prod-ownership>
</code>```

here is the code i am using

```<code>public class LoginConsumerResponseParser extends DefaultHandler {
 // ===========================================================
 // Fields
 // ===========================================================
 static String str="default";
 private boolean in_errorCode=false;
 private boolean in_Ack=false;
 private boolean in_activeProdOwnership= false;
 private boolean in_consumerId= false;
 private boolean in_consumerAccToken=false;

  public void startDocument() throws SAXException {
  Log.e("i am ","in start document");
 }

 public void endDocument() throws SAXException {
  // Nothing to do
  Log.e("doc read", " ends here");
 }

 /** Gets be called on opening tags like:
  * <tag>
  * Can provide attribute(s), when xml was like:
  * <tag attribute="attributeValue">*/

 public void startElement(String namespaceURI, String localName,
   String qName, Attributes atts) throws SAXException {
  if(localName.equals("ack")){
   in_Ack=true;
  }
  if(localName.equals("error-code")){
   in_errorCode=true;
  }
  if(localName.equals("active-prod-ownership")){
   Log.e("in", "active product ownership");
   in_activeProdOwnership=true;
  }
  if(localName.equals("consumer-id")){
   in_consumerId= true;
  }
  if(localName.equals("consumer-access-token"))
  {
   in_consumerAccToken= true;
  }
 }

 /** Gets be called on closing tags like:
  * </tag> */

 public void endElement(String namespaceURI, String localName, String qName)
 throws SAXException {
  if(localName.equals("ack")){
   in_Ack=false;
  }
  if(localName.equals("error-code")){
   in_errorCode=false;
  }
  if(localName.equals("active-prod-ownership")){
   in_activeProdOwnership=false;
  }
  if(localName.equals("consumer-id")){
   in_consumerId= false;
  }
  if(localName.equals("consumer-access-token"))
  {
   in_consumerAccToken= false;
  }
 }

 /** Gets be called on the following structure:
  * <tag>characters</tag> */

 public void characters(char ch[], int start, int length) {

  if(in_Ack){
  str= new String(ch,start,length);
  }
  if(str.equalsIgnoreCase("success")){
  if(in_consumerId){

  }
  if(in_consumerAccToken){

  }
  if(in_activeProdOwnership){
   str= new String(ch,start,length);
   Log.e("active prod",str);
  }
  }
 }
}
</code>```

but on reaching the tag in_activeProdOwnersip read only "<" as the contents of the tag

please help i need to the whole data to be read

答:
The tags in your XML file and parser does not match. I think you are mixing-up tags with attribute names. Here is the code that correctly parses your sample XML:

```<code>public class LoginConsumerResponseParser extends DefaultHandler {
    public void startDocument() throws SAXException {
        System.out.println("startDocument()");
    }

    public void endDocument() throws SAXException {
        System.out.println("endDocument()");
    }

    public void startElement(String namespaceURI, String localName,
                             String qName, Attributes attrs)
        throws SAXException {

        if (qName.equals("ActiveProdOwnership")) {
            inActiveProdOwnership = true;
        } else if (qName.equals("Product")) {
            if (!inActiveProdOwnership) {
                throw new SAXException("Product tag not expected here.");
            }
            int length = attrs.getLength();
            for (int i=0; i<length; i++) {
                String name = attrs.getQName(i);
                System.out.print(name + ": ");
                String value = attrs.getValue(i);
                System.out.println(value);
            }
        }
    }

    public void endElement(String namespaceURI, String localName, String qName)
        throws SAXException {

        if (localName.equals("ActiveProdOwnership"))
            inActiveProdOwnership = false;
    }

    public void characters(char ch[], int start, int length) {
    }

    public static void main(String args[]) throws Exception {
        String xmlFile = args[0];
        File file = new File(xmlFile);
        if (file.exists()) {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            DefaultHandler handler = new Test();
            parser.parse(xmlFile, handler);
        }
        else {
            System.out.println("File not found!");
        }
    }

    private boolean inActiveProdOwnership = false;
}
</code>```

A sample run will produce the following output:

```<code>startDocument()
code: 3N3
component: TRI_SCORE
orderNumber: 1-77305469
endDocument()
</code>```

Title: Reading nested tags with sax parser

Body:
i am trying to read a xml file with following tag, but the sax parser is unable to read nested tags like

<active-prod-ownership>
  <ActiveProdOwnership>
    <Product code="3N3" component="TRI_SCORE" orderNumber="1-77305469" />
  </ActiveProdOwnership>
</active-prod-ownership>

here is the code i am using

public class LoginConsumerResponseParser extends DefaultHandler {
 // ===========================================================
 // Fields
 // ===========================================================
 static String str="default";
 private boolean in_errorCode=false;
 private boolean in_Ack=false;
 private boolean in_activeProdOwnership= false;
 private boolean in_consumerId= false;
 private boolean in_consumerAccToken=false;

  public void startDocument() throws SAXException {
  Log.e("i am ","in start document");
 }

 public void endDocument() throws SAXException {
  // Nothing to do
  Log.e("doc read", " ends here");
 }

 /** Gets be called on opening tags like:
  * <tag>
  * Can provide attribute(s), when xml was like:
  * <tag attribute="attributeValue">*/

 public void startElement(String namespaceURI, String localName,
   String qName, Attributes atts) throws SAXException {
  if(localName.equals("ack")){
   in_Ack=true;
  }
  if(localName.equals("error-code")){
   in_errorCode=true;
  }
  if(localName.equals("active-prod-ownership")){
   Log.e("in", "active product ownership");
   in_activeProdOwnership=true;
  }
  if(localName.equals("consumer-id")){
   in_consumerId= true;
  }
  if(localName.equals("consumer-access-token"))
  {
   in_consumerAccToken= true;
  }
 }

 /** Gets be called on closing tags like:
  * </tag> */

 public void endElement(String namespaceURI, String localName, String qName)
 throws SAXException {
  if(localName.equals("ack")){
   in_Ack=false;
  }
  if(localName.equals("error-code")){
   in_errorCode=false;
  }
  if(localName.equals("active-prod-ownership")){
   in_activeProdOwnership=false;
  }
  if(localName.equals("consumer-id")){
   in_consumerId= false;
  }
  if(localName.equals("consumer-access-token"))
  {
   in_consumerAccToken= false;
  }
 }

 /** Gets be called on the following structure:
  * <tag>characters</tag> */

 public void characters(char ch[], int start, int length) {

  if(in_Ack){
  str= new String(ch,start,length);
  }
  if(str.equalsIgnoreCase("success")){
  if(in_consumerId){

  }
  if(in_consumerAccToken){

  }
  if(in_activeProdOwnership){
   str= new String(ch,start,length);
   Log.e("active prod",str);
  }
  }
 }
}

but on reaching the tag in_activeProdOwnersip read only "<" as the contents of the tag

please help i need to the whole data to be read

Body:
The tags in your XML file and parser does not match. I think you are mixing-up tags with attribute names. Here is the code that correctly parses your sample XML:

public class LoginConsumerResponseParser extends DefaultHandler {
    public void startDocument() throws SAXException {
        System.out.println("startDocument()");
    }

    public void endDocument() throws SAXException {
        System.out.println("endDocument()");
    }

    public void startElement(String namespaceURI, String localName,
                             String qName, Attributes attrs)
        throws SAXException {

        if (qName.equals("ActiveProdOwnership")) {
            inActiveProdOwnership = true;
        } else if (qName.equals("Product")) {
            if (!inActiveProdOwnership) {
                throw new SAXException("Product tag not expected here.");
            }
            int length = attrs.getLength();
            for (int i=0; i<length; i++) {
                String name = attrs.getQName(i);
                System.out.print(name + ": ");
                String value = attrs.getValue(i);
                System.out.println(value);
            }
        }
    }

    public void endElement(String namespaceURI, String localName, String qName)
        throws SAXException {

        if (localName.equals("ActiveProdOwnership"))
            inActiveProdOwnership = false;
    }

    public void characters(char ch[], int start, int length) {
    }

    public static void main(String args[]) throws Exception {
        String xmlFile = args[0];
        File file = new File(xmlFile);
        if (file.exists()) {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            DefaultHandler handler = new Test();
            parser.parse(xmlFile, handler);
        }
        else {
            System.out.println("File not found!");
        }
    }

    private boolean inActiveProdOwnership = false;
}

A sample run will produce the following output:

startDocument()
code: 3N3
component: TRI_SCORE
orderNumber: 1-77305469
endDocument()


问:
why does an array with a property cause an undefined error in JS
This syntax works fine:

```<code>var foo = [];
foo[0] = "do";
foo[1] = "re";
</code>```

I'm trying to do the same using properties, like so.

```<code>var foo = [{
    note: "",
}];
foo[0].note = "do";
foo[1].note = "re";
</code>```

But in this case the last line now generates an undefined variable error. What am doing wrong?

Update:

Just responding to the comment that my question could be clearer. The problem comes up, e.g., when I try to assign values to an array in a for-loop, where i is the index, with something like

```<code>foo[i] = i
</code>```

but when using an array element with a property, like

```<code>foo[i].note = i
</code>```

it won't work because, as nnnnnn says, the element doesn't exist yet as soon as the index hits 1. So is the answer that I just can't assign values to array elements in a for-loop like that and I have to use a variable like fooNote[i] instead?

答:
You need the index 1 as well:

var foo = [{
    note: "",
},
{
    note:"" //note property for foo[1] is now set here
}];
foo[0].note = "do";
foo[1].note = "re";

console.log(foo);```

Your original array didn't have the index 1 set.

Body:
This syntax works fine:

var foo = [];
foo[0] = "do";
foo[1] = "re";

I'm trying to do the same using properties, like so.

var foo = [{
    note: "",
}];
foo[0].note = "do";
foo[1].note = "re";

But in this case the last line now generates an undefined variable error. What am doing wrong?

Update:

Just responding to the comment that my question could be clearer. The problem comes up, e.g., when I try to assign values to an array in a for-loop, where i is the index, with something like

foo[i] = i

but when using an array element with a property, like

foo[i].note = i

it won't work because, as nnnnnn says, the element doesn't exist yet as soon as the index hits 1. So is the answer that I just can't assign values to array elements in a for-loop like that and I have to use a variable like fooNote[i] instead?

Body:
You need the index 1 as well:

var foo = [{
    note: "",
},
{
    note:"" //note property for foo[1] is now set here
}];
foo[0].note = "do";
foo[1].note = "re";

console.log(foo);

Your original array didn't have the index 1 set.


问:
How to run tensorboard automatically when training my model?
I am using tensorflow on windows and I know that I can run tensorboard manually:

Open an anaconda prompt

Activate the tensorflow environment

Enter the Log directory of the logdir of my tensorflow running in the anaconda prompt

Enter the command ‘tensorboard –logdir=mylogdir’

Open google chrome then enter http://localhost:6006/

I hope to run these 5 steps automatically and hope tensorboard run together when I am traning the model so that I can monitor the training process. I can add the following system call before entering the training process

os.system('C:/CodingSoftware/Anaconda3_py3.5/envs/tensorflow-gpu/python -m tensorflow.tensorboard --logdir='+tf_log_dir)

However the code stop at showing "Starting TensorBoard b'47' at http://0.0.0.0:6006"

Thank you Ayushya below. With your first method, it does not run in parallel. If I start P1 first, it still requires Press CTRL+C before entering the rest of the code

```<code>log_dir='E:/PythonCode/BayesianLinearStrategy/LOG'
p1 = Process(target=startTensorboard(log_dir))
p1.start()
p2 = Process(target=RunTFCode)
p2.start()
</code>```

答:
I believe that you are trying to run tensorboard in parallel with training.

You could use threading or multiprocessing. Here is a modified example from source:

```<code>from multiprocessing import Process

def startTensorboard(tf_log_dir):
  os.system('C:/CodingSoftware/Anaconda3_py3.5/envs/tensorflow-gpu/python -m tensorflow.tensorboard --logdir='+tf_log_dir)

if __name__ == '__main__':
  log_dir='E:/PythonCode/BayesianLinearStrategy/LOG'
  p1 = Process(target=startTensorboard(log_dir))
  p2 = Process(target=RunTFCode)
  p1.start()
  p2.start()
  p1.join()
  p2.join()
  ...rest of your code
</code>```

OR

You can use create a bash script which executes those steps you specified in question and simultaneously start the training session. You can run two commands using:

```<code>prog1 & prog2 && fg
</code>```

This will:

Start prog1.

Send it to background, but keep printing its output.

Start prog2, and keep it in foreground, so you can close it with ctrl-c.

When you close prog2, you'll return to prog1's foreground, so you can also close it with ctrl-c.

Edit: Modified python code by adding p1.join() and p2.join().

Body:
I am using tensorflow on windows and I know that I can run tensorboard manually:

Open an anaconda prompt

Activate the tensorflow environment

Enter the Log directory of the logdir of my tensorflow running in the anaconda prompt

Enter the command ‘tensorboard –logdir=mylogdir’

Open google chrome then enter http://localhost:6006/

I hope to run these 5 steps automatically and hope tensorboard run together when I am traning the model so that I can monitor the training process. I can add the following system call before entering the training process

os.system('C:/CodingSoftware/Anaconda3_py3.5/envs/tensorflow-gpu/python -m tensorflow.tensorboard --logdir='+tf_log_dir)

However the code stop at showing "Starting TensorBoard b'47' at http://0.0.0.0:6006"

Thank you Ayushya below. With your first method, it does not run in parallel. If I start P1 first, it still requires Press CTRL+C before entering the rest of the code

log_dir='E:/PythonCode/BayesianLinearStrategy/LOG'
p1 = Process(target=startTensorboard(log_dir))
p1.start()
p2 = Process(target=RunTFCode)
p2.start()

Body:
I believe that you are trying to run tensorboard in parallel with training.

You could use threading or multiprocessing. Here is a modified example from source:

from multiprocessing import Process

def startTensorboard(tf_log_dir):
  os.system('C:/CodingSoftware/Anaconda3_py3.5/envs/tensorflow-gpu/python -m tensorflow.tensorboard --logdir='+tf_log_dir)

if __name__ == '__main__':
  log_dir='E:/PythonCode/BayesianLinearStrategy/LOG'
  p1 = Process(target=startTensorboard(log_dir))
  p2 = Process(target=RunTFCode)
  p1.start()
  p2.start()
  p1.join()
  p2.join()
  ...rest of your code

OR

You can use create a bash script which executes those steps you specified in question and simultaneously start the training session. You can run two commands using:

prog1 & prog2 && fg

This will:

Start prog1.

Send it to background, but keep printing its output.

Start prog2, and keep it in foreground, so you can close it with ctrl-c.

When you close prog2, you'll return to prog1's foreground, so you can also close it with ctrl-c.

Edit: Modified python code by adding p1.join() and p2.join().


问:
React, is there a way to avoid needing to wrap a div inside a div?
I have the following:

```<code>const errorMessage = ({meta}) =>
  <div>
    {meta.error && meta.touched && <div className="alert alert-info" role="alert">{meta.error}</div>}
  </div>
</code>```

If I remove the outer div wrapper in the above I get an error... Is there a way to get errorMessage to work without the extra DIV?

Thanks

答:
You can write like this :

```<code>const errorMessage = ({meta}) => {
return (meta.error && meta.touched) ? `<div className='alert alert-info' role='alert'>${meta.error}</div>` : null
}
</code>```

Body:
I have the following:

const errorMessage = ({meta}) =>

    {meta.error && meta.touched &&
{meta.error}
}

If I remove the outer div wrapper in the above I get an error... Is there a way to get errorMessage to work without the extra DIV?

Thanks

Body:
You can write like this :

const errorMessage = ({meta}) => {
return (meta.error && meta.touched) ? `<div className='alert alert-info' role='alert'>${meta.error}</div>` : null
}


问:
php random generate id like a32-jn3-sdf3
with the current code i'm getting are in5v6wyio0er5isu9rv4, so how do i get more number and less alphabets in the id?

below is the code which i have done

```<code>    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';

    for ($i = 0; $i < 20; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    echo $randomString;
</code>```

i would like to get the id in this format 6437270e-c2d4-4524-8a26-ad311c4ca55e.

答:
If you want more number, get them higher priority by duplicate them in available strings:

$characters = '012345678901234567890123456789abcdefghijklmnopqrstuvwxyz';

And the number format, just pre-format them by yourself:

```<code> $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';

    for ($i = 0; $i < 24; $i++) {
         if($i % 5 == 0){
             // Add "-" each 5 characters
             $randomString .= "-";
         }else{
             $randomString .= $characters[rand(0, strlen($characters) - 1)];
         }

    }

    echo $randomString;
</code>```

Body:
with the current code i'm getting are in5v6wyio0er5isu9rv4, so how do i get more number and less alphabets in the id?

below is the code which i have done

    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';

    for ($i = 0; $i < 20; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    echo $randomString;

i would like to get the id in this format 6437270e-c2d4-4524-8a26-ad311c4ca55e.

Body:
If you want more number, get them higher priority by duplicate them in available strings:

$characters = '012345678901234567890123456789abcdefghijklmnopqrstuvwxyz';

And the number format, just pre-format them by yourself:

 $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';

    for ($i = 0; $i < 24; $i++) {
         if($i % 5 == 0){
             // Add "-" each 5 characters
             $randomString .= "-";
         }else{
             $randomString .= $characters[rand(0, strlen($characters) - 1)];
         }

    }

    echo $randomString;


问:
A solution that uses EntityFramework source projects instead its assemblies, could not start successfully
I have a WinForms project that uses EntityFramework 6.1.2-beta with .NET4, it worked fine, till I decided to replace EF assemblies with their source codes, for some tracing goals, so I removed EntityFramework.dll and EntityFramework.SqlServer.dll from my project references and get their source codes from CodePlex and add them to my solution.

I changed these new project configuration to DebugNet40(because my project works with .NET 4, but EntityFramework and EntityFramework.SqlServer projects work with .NET 4.5).

It compile successfully, but now when I want to run my project I get following error:

An unhandled exception of type 'System.IO.FileLoadException' occurred in Microsoft.VisualStudio.HostingProcess.Utilities.dll

Additional information: Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0x8013141A)

It is my app.config file:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
     <section name="entityFramework"
              type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
              EntityFramework, Version=6.0.0.0, Culture=neutral,
              PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
     <defaultConnectionFactory
          type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,
                EntityFramework">
          <parameters>
             <parameter value="mssqllocaldb" />
          </parameters>
     </defaultConnectionFactory>
     <providers>
     <provider invariantName="System.Data.SqlClient"
               type="System.Data.Entity.SqlServer.SqlProviderServices,
               EntityFramework.SqlServer" />
     </providers>
  </entityFramework>
  <connectionStrings>
     <add name="ERPContext"
                connectionString="Data Source=.;Initial Catalog=MyDb;
                Persist Security Info=True;User ID=sa;password=*****"
                providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>
</code>```

I removed PublicKeyToken=b77a5c561934e089" from app.config too, but the problem exists yet.

Is there any Idea?

答: You can right click the project in Visual Studio solution explorer, and Signing on the left and uncheck sign assembly. In your web config you will also need to remove the public key token. </p>

Body:
I have a WinForms project that uses EntityFramework 6.1.2-beta with .NET4, it worked fine, till I decided to replace EF assemblies with their source codes, for some tracing goals, so I removed EntityFramework.dll and EntityFramework.SqlServer.dll from my project references and get their source codes from CodePlex and add them to my solution.

I changed these new project configuration to DebugNet40(because my project works with .NET 4, but EntityFramework and EntityFramework.SqlServer projects work with .NET 4.5).

It compile successfully, but now when I want to run my project I get following error:

An unhandled exception of type 'System.IO.FileLoadException' occurred in Microsoft.VisualStudio.HostingProcess.Utilities.dll

Additional information: Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0x8013141A)

It is my app.config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

  </configSections>
  <entityFramework>
     <defaultConnectionFactory
          type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,
                EntityFramework">
          <parameters>
             <parameter value="mssqllocaldb" />
          </parameters>
     </defaultConnectionFactory>
     <providers>
     <provider invariantName="System.Data.SqlClient"
               type="System.Data.Entity.SqlServer.SqlProviderServices,
               EntityFramework.SqlServer" />
     </providers>
  </entityFramework>
  <connectionStrings>
     <add name="ERPContext"
                connectionString="Data Source=.;Initial Catalog=MyDb;
                Persist Security Info=True;User ID=sa;password=*****"
                providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

I removed PublicKeyToken=b77a5c561934e089" from app.config too, but the problem exists yet.

Is there any Idea?


问:
D3: Can I have an svg transition based on items in a list?
I would like to take a list...

```<code>var data = [100, 200, 300] // arbitrarily long
</code>```

... and transition an element across the screen based on each list item. For example, I would like to send a dot first to [100,100], [200,100], [300,100]. Is there a way to do this with data joining?

Right now, I have have a solution that works, but it works in what seems to be a very un-D3-ish way: using a counter to iterate through a list, and using no data-binding. Excluding the CSS, here's the code:

```<code><svg>
  <circle/>
</svg>

<script>

var data = [100,200,300]

var circle = d3.selectAll("circle")
    .attr("r",20)
    .attr("cy",100)
    .attr("cx",0)

var count = 0

repeat()

function repeat() {
  var run = circle
    .transition()
    .duration(1000)
    .attr("cx", function (d) {return data[count]});

    count++

  if (count < data.length){
    run
      .each("end", repeat);
  }
}

</script>
</code>```

Shouldn't there be a way to do this with data binding? I'd love to do this the right way, but for now this is all I can figure out just to make it work.

答:
Yes, you could enter/append circles based on the data in the array, and then set cx based on it's data. Also, you can achieve the staggering by basing the transition delay on the data point's index, eg https://jsfiddle.net/65aeo5q5/ :</p>

```<code>var circle = svg.selectAll("circle")
  .data(data)
  .enter()
  .append("circle")
    .attr("r",20)
    .attr("cy",100)
    .attr("cx",0)
    .style("fill", "red")

var delay = 1000;

circle
    .transition()
    .duration(delay)
    .delay(function (d, i) {return i * delay;})
    .attr("cx", function (d) {return d;});
</code>```

Body:
I would like to take a list...

var data = [100, 200, 300] // arbitrarily long

... and transition an element across the screen based on each list item. For example, I would like to send a dot first to [100,100], [200,100], [300,100]. Is there a way to do this with data joining?

Right now, I have have a solution that works, but it works in what seems to be a very un-D3-ish way: using a counter to iterate through a list, and using no data-binding. Excluding the CSS, here's the code:

<svg>
  <circle/>
</svg>

Shouldn't there be a way to do this with data binding? I'd love to do this the right way, but for now this is all I can figure out just to make it work.

Body:
Yes, you could enter/append circles based on the data in the array, and then set cx based on it's data. Also, you can achieve the staggering by basing the transition delay on the data point's index, eg https://jsfiddle.net/65aeo5q5/ :

var circle = svg.selectAll("circle")
  .data(data)
  .enter()
  .append("circle")
    .attr("r",20)
    .attr("cy",100)
    .attr("cx",0)
    .style("fill", "red")

var delay = 1000;

circle
    .transition()
    .duration(delay)
    .delay(function (d, i) {return i * delay;})
    .attr("cx", function (d) {return d;});


问:
Auto Populate CTE in SQL Server
How can I auto populate a CTE to contain the first day of every month
Eg:

1-1-2010

2-1-2010

3-1-2010

4-1-2010

and so on. I looking for a query to do so, rather than using UNION operator.

答:
```<code>WITH CTEDates AS
(
SELECT CAST('20100101' AS DATETIME) AS DateVal
UNION ALL
SELECT DATEADD(mm, 1, DateVal)
FROM CTEDates
WHERE DateVal < '20101201'
)

SELECT * FROM CTEDates
</code>```

Title: Auto Populate CTE in SQL Server


问:
Why can't I find control using sap.ui.getCore().byId()?
I'm trying to access an input control in the controller but I'm not able to fetch it.

I'm using

sap.ui.getCore().byId("id of the input");
```

答:
https://openui5.hana.ondemand.com/#docs/guide/91f28be26f4d1014b6dd926db0e91070.html Hope this doc will help you.

You should use relative navigation(this.getView().byId('myId')). Absolute Navigation(sap.ui.getcore().byId('myId')) is not recommended, since that will not work anymore if you change like local project to FioriLaunchpad.

I think the source code of byId of Controller and createId of View explains a lot.


问:
Scale div to browser height vh troubles
I want the content inside of my div to scale with the browser vertically to prevent the need for scrolling The images will be different orientations so the width will be different. I know this can be achieved horizontally with width:100%; but max-height:100%; or height:auto; both still extend past the browser window for me and I'm not sure why.

EDIT: Had a lot of additional modal code in here, and simplified it down to the html/css and switched from simple width:100% height: 100% to vh and vw.

Fiddle :https://jsfiddle.net/duckyduck/6soe8zs0/

What's happening:

How I want it to look:

```<code><body>
<style>

.modal {
  display: block;
  position: fixed;
  z-index: 1;
  box-sizing:border-box;

  left: 0;
  top: 0;
height: 100%;
width:100%;

  overflow:auto;
  background-color:#D81E21;
}

.modal-content {
  position: relative;/*modal x button */
  width: auto;
  height: auto;
  background-color: #7E7DE1;
  max-height: 50vh;
  max-width:70vw;
  margin: auto;
  }

.mySlides{
    max-height:100%;
    max-width: 100%;
    height:auto;
    width:auto;
}

.roll-img {
display:flex;
flex-wrap:wrap;
}

.column {
flex:1;
}

.caption-container {
  text-align: center;
  background-color: black;
  padding: 2px 16px;
  color: white;
}

</style>

<div id="myModal" class="modal">

    <div class="modal-content">

        <div class="mySlides">
          <img src="images/5_2.jpg">
        </div>

        <div class="caption-container">
          <p id="caption"></p>
        </div>

      <div class="roll-img">
        <div class="column">
            <img class="demo cursor" src="images/5_2.jpg">
        </div>
      </div> <!--roll-img-->

  </div> <!--modal-content-->
</div> <!--myModal-->

</body>
</code>```

答:
I am able to get the desired result by applying 4 things:

max-width: 90vw; ensures that the object will never exceed 90% of the screen width.

max-height: 90vh; ensures that the object will never exceed 90% of the screen height.

width: auto; adjusts the width to maintain the original aspect ratio

height: auto; adjusts the width to maintain the original aspect ratio

With these four combined, the object will always be fully in view and you will not need to scroll the screen.

Working example:
(open in full screen and resize vertically or horizontally to see the effect)

body {
  background: #131418;
  margin: auto;
  padding: 0;
  text-align: center;
}

.adjust {
  width: auto;
  height: auto;
  max-width: 90vw;
  max-height: 90vh;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="adjust" src="https://unsplash.it/3000/3000"></code>```

Title: Scale div to browser height vh troubles

Body:
I am able to get the desired result by applying 4 things:

max-width: 90vw; ensures that the object will never exceed 90% of the screen width.

max-height: 90vh; ensures that the object will never exceed 90% of the screen height.

width: auto; adjusts the width to maintain the original aspect ratio

height: auto; adjusts the width to maintain the original aspect ratio

With these four combined, the object will always be fully in view and you will not need to scroll the screen.

Working example:
(open in full screen and resize vertically or horizontally to see the effect)

body {
  background: #131418;
  margin: auto;
  padding: 0;
  text-align: center;
}

.adjust {
  width: auto;
  height: auto;
  max-width: 90vw;
  max-height: 90vh;
  margin: 0 auto;
}

<img class="adjust" src="https://unsplash.it/3000/3000">


问:
displaying list of dates for loop
i have this code..that will display a list of month for the current year and the first day of first month and second month

```<code>$cur_year = date("Y");
$next_year = $cur_year+1;

for($m=1; $m<=12; ++$m)
{
$monthName=date('F', mktime(0, 0, 0, $m, 1)).'';
$monthNumber=date('m', mktime(0, 0, 0, $m, 1)).'';
$nextmonth=$monthNumber+1;

echo "$monthName<br />";
echo "$cur_year-$monthNumber-01<br />";
echo "$cur_year-$nextmonth-01<br /><br />";
}
</code>```

i would like to be display like this

```<code>January
2017-01-01
2017-02-01

February
2017-02-01
2017-03-01

up to December

December
2017-12-01
2018-01-01
</code>```

current ouput

```<code>January
2017-01-01
2017-2-01

February
2017-02-01
2017-3-01

up to December

December
2017-12-01
2017-13-01
</code>```

答:
Try this code:</p>

```<code><?php

 $cur_year = date("Y");
 $next_year = $cur_year+1;

for($m=1; $m<=12; ++$m)
 {
$monthName=date('F', mktime(0, 0, 0, $m, 1)).'';
$monthNumber=date('m', mktime(0, 0, 0, $m, 1)).'';
$nextmonth=$monthNumber+1;

if($nextmonth<10)
  $nextmonth="0".$nextmonth; //will add 0 as prefix to the numbers below 10

echo "$monthName<br>";
echo "$cur_year-$monthNumber-01<br>";
if($nextmonth > 12)
 {
   $cur_year++; //current year +1 2017 to 2018
  $nextmonth="01"; //start the month back to 01 or january
 }
 echo "$cur_year-$nextmonth-01<br><br>";
 }
</code>```

Title: displaying list of dates for loop

Body:
i have this code..that will display a list of month for the current year and the first day of first month and second month

$cur_year = date("Y");
$next_year = $cur_year+1;

for($m=1; $m<=12; ++$m)
{
$monthName=date('F', mktime(0, 0, 0, $m, 1)).'';
$monthNumber=date('m', mktime(0, 0, 0, $m, 1)).'';
$nextmonth=$monthNumber+1;

echo "$monthName
";
echo "$cur_year-$monthNumber-01
";
echo "$cur_year-$nextmonth-01

";
}

i would like to be display like this

January
2017-01-01
2017-02-01

February
2017-02-01
2017-03-01

up to December

December
2017-12-01
2018-01-01

current ouput

January
2017-01-01
2017-2-01

February
2017-02-01
2017-3-01

up to December

December
2017-12-01
2017-13-01

Body:
Try this code:

<?php

 $cur_year = date("Y");
 $next_year = $cur_year+1;

for($m=1; $m<=12; ++$m)
 {
$monthName=date('F', mktime(0, 0, 0, $m, 1)).'';
$monthNumber=date('m', mktime(0, 0, 0, $m, 1)).'';
$nextmonth=$monthNumber+1;

if($nextmonth<10)
  $nextmonth="0".$nextmonth; //will add 0 as prefix to the numbers below 10

echo "$monthName<br>";
echo "$cur_year-$monthNumber-01<br>";
if($nextmonth > 12)
 {
   $cur_year++; //current year +1 2017 to 2018
  $nextmonth="01"; //start the month back to 01 or january
 }
 echo "$cur_year-$nextmonth-01<br><br>";
 }


问:
undefined method _path for
I'm running into a problem when I open a new register view.
Take a look at the error:

```<code>undefined method `operadors_path' for #<#
<Class:0x0055dc5dc2ce48>:0x0055dc5dc177a0>
Did you mean?  operadores_path
operadore_path
</code>```

And Rails complains about these line form's code:

```<code><%= form_for(@operador) do |f| %>
    <% if @operador.errors.any? %>
         <div id="error_explanation">
             <h2>Descobrimos <%= pluralize(@operador.errors.count, "erro") %> no preenchimento do formulário :(</h2>
</code>```

I don't understant this error because I'm not using any route like operador_path on the form's code.

Can someone help me?

My routes:

```<code>resources :operadores
</code>```

My form:

```<code><%= form_for(@operador) do |f| %>
    <% if @operador.errors.any? %>
            <div id="error_explanation">
                <h2>Descobrimos <%= pluralize(@operador.errors.count, "erro") %> no preenchimento do formulário :(</h2>

                <ul>
                <% @operador.errors.full_messages.each do |message| %>
                    <li><%= message %></li>
                <% end %>
                </ul>
            </div>
    <% end %>

    <div class="field">
        <%= f.label :user %>
        <%= f.text_field :user %>
    </div>
    </br>

    <div class="field">
        <%= f.label :senha %>
        <%= f.text_field :senha %>
    </div>
    </br>

    <div class="field">
        <%= f.label :operador_tipo_id %>
        <%= f.collection_select(:operador_tipo_id, @tipos_opstions_for_select, :id, :tipo) %>
    </div>
    </br>

    <div class="actions">
        <%= f.submit %>
    </div>
<% end %>
</code>```

Edit 2 Model and Controller.

My Model:

```<code>class Operador < ApplicationRecord

    attr_accessor :password

    #Relacionamento com o tipo de operador
    belongs_to :operador_tipo, optional: true

    #Validações
    validates_confirmation_of :password
    validates_length_of :password, :is => 8
    validates_presence_of :password, :if => :password_required?
    validates_presence_of :operador_tipo_id

    #Callback para encriptação de senha antes de salvar no banco
    before_save :encrypt_new_password

    #Autenticação
    #Procura e retorna o usuário se o usuario e senha estão corretos
    def self.authenticate(user, password)
        user = find_by_user(user)
        return user if user && user.authenticated?(password)
    end

    #Verifica se a senha esta correta
    def authenticated?(password)
        self.hashed_password == encrypt(password)
    end

    ######################### Bloco abaixo é protegido e só pode ser visto pela própria classe
    protected

    #Solicita a encriptação se a senha não estiver em branco
    def encrypt_new_password
        return if password.blank?
        self.hashed_password = encrypt(password)
    end

    #Verifica se a senha esta em branco
    def password_required?
        hashed_password.blank? || password.present?
    end

    #Efetua a encriptação
    def encrypt(string)
        Digest::SHA1.hexdigest(string)
    end
end
</code>```

My Controller:

```<code>class OperadoresController < ApplicationController

before_action :find, only: [:edit, :update, :destroy]
before_action :set_options_for_select, only: [:new, :edit, :update, :create]

  def show
    @operador = Operador.find(params[:user])

  end

  # GET /operadors/new
  def new
    @operador = Operador.new
  end

  def index
    @operadores = Operador.all
  end

  # GET /operadors/1/edit
  def edit
  end

  # POST /operadors
  # POST /operadors.json
  def create
    @operador = Operador.new(operador_params)

    @operador.valid?

    respond_to do |format|
      if @operador.save
        format.html { redirect_to @operador, notice: 'Operador cadastrado com sucesso.' }
        format.json { render :show, status: :created, location: @operador }
      else
        format.html { render :new }
        format.json { render json: @operador.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /operadors/1
  # PATCH/PUT /operadors/1.json
  def update
    respond_to do |format|
      if @operador.update(operador_params)
        format.html { redirect_to @operador, notice: 'Operador atualizado com sucesso.' }
        format.json { render :show, status: :ok, location: @operador }
      else
        format.html { render :edit }
        format.json { render json: @operador.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /operadors/1
  # DELETE /operadors/1.json
  def destroy
    @operador.destroy
    respond_to do |format|
      format.html { redirect_to operadors_url, notice: 'Operador removido com sucesso.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
  def find
      @operador = Operador.find(params[:id])
   end

   def set_options_for_select
    @tipos_opstions_for_select = OperadorTipo.all
   end

    # Never trust parameters from the scary internet, only allow the white list through.
  def operador_params
      params.require(:operador).permit(:user, :password, :operador_tipo_id)
  end
end
</code>```

答:
Adding to @Gerry's answer, If you wish not to change the routes and controller, you can just force Rails to use which you are defined. You can do that with the help of inflections. Put the below line in config/initializers/inflections.rb

```<code>inflect.irregular 'operador', 'operadores'
</code>```

and restart the server.

Title: undefined method _path for

Body:
I'm running into a problem when I open a new register view.
Take a look at the error:

undefined method `operadors_path' for #<#
<Class:0x0055dc5dc2ce48>:0x0055dc5dc177a0>
Did you mean?  operadores_path
operadore_path

And Rails complains about these line form's code:

<%= form_for(@operador) do |f| %>
    <% if @operador.errors.any? %>

Descobrimos <%= pluralize(@operador.errors.count, "erro") %> no preenchimento do formulário :(

I don't understant this error because I'm not using any route like operador_path on the form's code.

Can someone help me?

My routes:

resources :operadores

My form:

<%= form_for(@operador) do |f| %>
    <% if @operador.errors.any? %>

Descobrimos <%= pluralize(@operador.errors.count, "erro") %> no preenchimento do formulário :(

                <% @operador.errors.full_messages.each do |message| %>

<%= message %>

                <% end %>

    <% end %>

        <%= f.label :user %>
        <%= f.text_field :user %>

        <%= f.label :senha %>
        <%= f.text_field :senha %>

        <%= f.label :operador_tipo_id %>
        <%= f.collection_select(:operador_tipo_id, @tipos_opstions_for_select, :id, :tipo) %>

        <%= f.submit %>

<% end %>

Edit 2 Model and Controller.

My Model:

class Operador < ApplicationRecord

    attr_accessor :password

    #Relacionamento com o tipo de operador
    belongs_to :operador_tipo, optional: true

    #Validações
    validates_confirmation_of :password
    validates_length_of :password, :is => 8
    validates_presence_of :password, :if => :password_required?
    validates_presence_of :operador_tipo_id

    #Callback para encriptação de senha antes de salvar no banco
    before_save :encrypt_new_password

    #Autenticação
    #Procura e retorna o usuário se o usuario e senha estão corretos
    def self.authenticate(user, password)
        user = find_by_user(user)
        return user if user && user.authenticated?(password)
    end

    #Verifica se a senha esta correta
    def authenticated?(password)
        self.hashed_password == encrypt(password)
    end

    ######################### Bloco abaixo é protegido e só pode ser visto pela própria classe
    protected

    #Solicita a encriptação se a senha não estiver em branco
    def encrypt_new_password
        return if password.blank?
        self.hashed_password = encrypt(password)
    end

    #Verifica se a senha esta em branco
    def password_required?
        hashed_password.blank? || password.present?
    end

    #Efetua a encriptação
    def encrypt(string)
        Digest::SHA1.hexdigest(string)
    end
end

My Controller:

class OperadoresController < ApplicationController

before_action :find, only: [:edit, :update, :destroy]
before_action :set_options_for_select, only: [:new, :edit, :update, :create]

  def show
    @operador = Operador.find(params[:user])

  end

  # GET /operadors/new
  def new
    @operador = Operador.new
  end

  def index
    @operadores = Operador.all
  end

  # GET /operadors/1/edit
  def edit
  end

  # POST /operadors
  # POST /operadors.json
  def create
    @operador = Operador.new(operador_params)

    @operador.valid?

    respond_to do |format|
      if @operador.save
        format.html { redirect_to @operador, notice: 'Operador cadastrado com sucesso.' }
        format.json { render :show, status: :created, location: @operador }
      else
        format.html { render :new }
        format.json { render json: @operador.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /operadors/1
  # PATCH/PUT /operadors/1.json
  def update
    respond_to do |format|
      if @operador.update(operador_params)
        format.html { redirect_to @operador, notice: 'Operador atualizado com sucesso.' }
        format.json { render :show, status: :ok, location: @operador }
      else
        format.html { render :edit }
        format.json { render json: @operador.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /operadors/1
  # DELETE /operadors/1.json
  def destroy
    @operador.destroy
    respond_to do |format|
      format.html { redirect_to operadors_url, notice: 'Operador removido com sucesso.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
  def find
      @operador = Operador.find(params[:id])
   end

   def set_options_for_select
    @tipos_opstions_for_select = OperadorTipo.all
   end

    # Never trust parameters from the scary internet, only allow the white list through.
  def operador_params
      params.require(:operador).permit(:user, :password, :operador_tipo_id)
  end
end

Body:
Adding to @Gerry's answer, If you wish not to change the routes and controller, you can just force Rails to use which you are defined. You can do that with the help of inflections. Put the below line in config/initializers/inflections.rb

inflect.irregular 'operador', 'operadores'

and restart the server.


答:
You need to fix the for-loop. You're telling PHP to add a random character from $characters 20 times, so it will never print something like XXXX-XXXX-XXX etc. because the "-" character is not even in $characters. I see two possible answers:

 Add conditionals:

```<code>for ($i = 0; $i < 20; $i++) {
  if (i === 8) { // at the 9th position, add an "-"
    $randomString .= "-";
  }
  else {
  $randomString .= $characters[rand(0, strlen($characters) - 1)];
  }
}
</code>```

Do this for all "-" that you want to insert.

Separate your for-loops. That is, make first a for-loop for the first sequence of character, then add "-", then a second for-loop for the second sequence of characters, and so on. (at its face, this seems to be bad coding practice; the egregious WET approach)

As for the wish to include more numbers than letters, make two different strings: $numbers = '0123456789'; $letters = 'abcd...' , or simply start your random number from $characters after the numbers (that is, rand(10, strlen($characters) - 1)) to get a letter or end it before 10 to get a number, if you want letters in certain places of the $randomString and numbers in others.

If you want to increase the odds of getting a number, use Huy Trịnh's brilliant suggestion: you can add more numbers or characters to $characters to increase the odds of getting a random character/number.

Title: php random generate id like a32-jn3-sdf3

Body:
You need to fix the for-loop. You're telling PHP to add a random character from $characters 20 times, so it will never print something like XXXX-XXXX-XXX etc. because the "-" character is not even in $characters. I see two possible answers:

 Add conditionals:

for ($i = 0; $i < 20; $i++) {
  if (i === 8) { // at the 9th position, add an "-"
    $randomString .= "-";
  }
  else {
  $randomString .= $characters[rand(0, strlen($characters) - 1)];
  }
}

Do this for all "-" that you want to insert.

Separate your for-loops. That is, make first a for-loop for the first sequence of character, then add "-", then a second for-loop for the second sequence of characters, and so on. (at its face, this seems to be bad coding practice; the egregious WET approach)

As for the wish to include more numbers than letters, make two different strings: $numbers = '0123456789'; $letters = 'abcd...' , or simply start your random number from $characters after the numbers (that is, rand(10, strlen($characters) - 1)) to get a letter or end it before 10 to get a number, if you want letters in certain places of the $randomString and numbers in others.

If you want to increase the odds of getting a number, use Huy Trịnh's brilliant suggestion: you can add more numbers or characters to $characters to increase the odds of getting a random character/number.


问:
Resize my Android application when I call ssoftkeyboard
I have a problem with the softkeyboard in my application. When I press the edit text the soft keyboard appears over the edit text. I read the documentation from Android and I put in AndroidManifest.xml android:windowSoftInputMode="adjustResize"> but it's not working.

答: I would suggest making the root view a ScrollView?</p>


问:
Getting a certain class from an element using wildcard
I am wanting to get the class starting with logo, only example item is:

jQuery(document).ready(function($) {

  // add classes to tab items
  var listItems = $(".vc_tta-tab a");
  // loop through all tab items
  listItems.each(function(idx, item) {
    var listItem = $(item);
    var tabID = listItem.attr("href");
    console.log(tabID);
    var matchCard = $(tabID).find('[class^="logo-"]');
    var tabClass = $(tabID).attr("class");
    console.log(tabClass);
    console.log(matchCard);

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="vc_general vc_tta vc_tta-tabs vc_tta-color-grey vc_tta-style-classic vc_tta-shape-rounded vc_tta-spacing-1 vc_tta-tabs-position-top vc_tta-controls-align-left">
  <div class="vc_tta-tabs-container">
    <ul class="vc_tta-tabs-list">
      <li class="vc_tta-tab vc_active" data-vc-tab=""><span class="vc_tta-title-text">Symantec SSL/TLS Certificates</span></li>
      <li class="vc_tta-tab" data-vc-tab=""><span class="vc_tta-title-text">GeoTrust SSL Certificates</span></li>
      <li class="vc_tta-tab" data-vc-tab=""><span class="vc_tta-title-text">RapidSSL Certificates</span></li>
      <li class="vc_tta-tab" data-vc-tab=""><span class="vc_tta-title-text">Thawte SSL Certificates</span></li>
      <li class="vc_tta-tab" data-vc-tab=""><span class="vc_tta-title-text">Certum SSL Certificates</span></li>
      <li class="vc_tta-tab" data-vc-tab=""><span class="vc_tta-title-text">Comodo SSL Certificates</span></li>
    </ul>
  </div>
  <div class="vc_tta-panels-container">
    <div class="vc_tta-panels">
      <div class="vc_tta-panel vc_active logo-ssl-symantec" id="ssl-brand-symantec" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">Symantec SSL/TLS Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
      <div class="vc_tta-panel logo-ssl-geotrust" id="ssl-brand-geotrust" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">GeoTrust SSL Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
      <div class="vc_tta-panel logo-ssl-rapidssl" id="ssl-brand-rapidssl" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">RapidSSL Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
      <div class="vc_tta-panel logo-ssl-thawte" id="ssl-brand-thawte" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">Thawte SSL Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
      <div class="vc_tta-panel logo-ssl-certum" id="ssl-brand-certum" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">Certum SSL Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
      <div class="vc_tta-panel logo-ssl-comodo" id="ssl-brand-comodo" data-vc-content=".vc_tta-panel-body">
        <div class="vc_tta-panel-heading">
          <h4 class="vc_tta-panel-title"><span class="vc_tta-title-text">Comodo SSL Certificates</span></h4>
        </div>
        <div class="vc_tta-panel-body"></div>
      </div>
    </div>
  </div>
</div></code>```

It is working by finding ID and matching that but can't get it to select that class I am wanting.

Also, I then want to take that class and set to the parent element of the initial href.

答:
You can check for the current item class using the jQuery is method as follows:

if($(item).is('[class^="logo-"]'))

Find a simple working example in here: https://codepen.io/jpgcode/pen/GEdQRp

Body:
I am wanting to get the class starting with logo, only example item is:

jQuery(document).ready(function($) {

  // add classes to tab items
  var listItems = $(".vc_tta-tab a");
  // loop through all tab items
  listItems.each(function(idx, item) {
    var listItem = $(item);
    var tabID = listItem.attr("href");
    console.log(tabID);
    var matchCard = $(tabID).find('[class^="logo-"]');
    var tabClass = $(tabID).attr("class");
    console.log(tabClass);
    console.log(matchCard);

  });
});

Symantec SSL/TLS Certificates

GeoTrust SSL Certificates

RapidSSL Certificates

Thawte SSL Certificates

Certum SSL Certificates

Comodo SSL Certificates

Symantec SSL/TLS Certificates

GeoTrust SSL Certificates

RapidSSL Certificates

Thawte SSL Certificates

Certum SSL Certificates

Comodo SSL Certificates

It is working by finding ID and matching that but can't get it to select that class I am wanting.

Also, I then want to take that class and set to the parent element of the initial href.