问:
How to fix declaration or statement expected error
I want to append table row with dynamic drop down list but get error declaration or syntax error in jquery code. how to fix it? </p>

```<code>$(".addtable").click(function () {
    debugger;
     $("#fields tbody").append("<tr><td>@Html.DropDownListFor(m => m.MedID, ViewBag.MedicineList as List<SelectListItem>, new { @class = "form-control", placeholder = "Category", id = "manfac", required = "required" })</td><td><input type="number" class="form-control" name=" Quantity" required></td><td><button type="button" class="btn btn-primary addtable">Add More</button><a href="javascript:void(0);" class="btn btn-primary remCF">Remove</a></td></tr>");

});
</code>```

答:
After testing this approach in a dummy project, I've discovered two issues:

You need to wrap your string with single-quotes instead of double-quotes, ie, change .append("...") to .append('...') .

Html.DropDownListFor() produces a string that has a newline character, which causes a line break in the javascript string, which throws a syntax error. So you need to do something like:
.append('@(Html.Raw(Html.DropDownListFor(...).ToString().Replace(System.Environment.NewLine, "")))') , which looks really ugly, but it works in my dummy project.`

So try:

```<code>$(".addtable").click(function () {
debugger;
 $("#fields tbody").append('<tr><td>@(Html.Raw(Html.DropDownListFor(m => m.MedID, ViewBag.MedicineList as List<SelectListItem>, new { @class = "form-control", placeholder = "Category", id = "manfac", required = "required" }).ToString().Replace(System.Environment.NewLine, "")))</td><td><input type="number" class="form-control" name=" Quantity" required></td><td><button type="button" class="btn btn-primary addtable">Add More</button><a href="javascript:void(0);" class="btn btn-primary remCF">Remove</a></td></tr>');
});
</code>```

Body:
I want to append table row with dynamic drop down list but get error declaration or syntax error in jquery code. how to fix it?

$(".addtable").click(function () {
    debugger;
     $("#fields tbody").append("
@Html.DropDownListFor(m => m.MedID, ViewBag.MedicineList as List<SelectListItem>, new { @class = "form-control", placeholder = "Category", id = "manfac", required = "required" })	<input type="number" class="form-control" name=" Quantity" required>	<button type="button" class="btn btn-primary addtable">Add More</button>Remove
");

});

Body:
After testing this approach in a dummy project, I've discovered two issues:

You need to wrap your string with single-quotes instead of double-quotes, ie, change .append("...") to .append('...') .

Html.DropDownListFor() produces a string that has a newline character, which causes a line break in the javascript string, which throws a syntax error. So you need to do something like:
.append('@(Html.Raw(Html.DropDownListFor(...).ToString().Replace(System.Environment.NewLine, "")))') , which looks really ugly, but it works in my dummy project.`

So try:

$(".addtable").click(function () {
debugger;
 $("#fields tbody").append('<tr><td>@(Html.Raw(Html.DropDownListFor(m => m.MedID, ViewBag.MedicineList as List<SelectListItem>, new { @class = "form-control", placeholder = "Category", id = "manfac", required = "required" }).ToString().Replace(System.Environment.NewLine, "")))</td><td><input type="number" class="form-control" name=" Quantity" required></td><td><button type="button" class="btn btn-primary addtable">Add More</button><a href="javascript:void(0);" class="btn btn-primary remCF">Remove</a></td></tr>');
});


来源: stackexchange

问:
Install Packages Onto All Anaconda Environments
I have a large number (~20) of different Anaconda environments and a list of Python packages like dill, csvkit, and so forth that I need to make available on all of those environments.

What's a concise, non-manual way of getting the packages I want onto all of the Anaconda environments?

On this other answer I've seen that making a metapackage out of it and then using a shell script to install that metapackage on each environment iteratively might be an avenue, but I don't see much info online about how to use metapackages for installation purposes.

答:
Put the list of packages you require in a text file, e.g.,

packages.txt

```<code>dill
csvkit
...
</code>```

Note: This file can also include versions, channels, and builds. Basically, anything that you can output with conda list --export.

Then run a loop similar to that found in the other answer,

```<code>for env in $(conda env list | awk '/^[a-zA-Z]/' | cut -d' ' -f1); do
    conda install -n "$env" --file packages.txt;
done
</code>```

Perhaps the -y|--yes and -q|--quiet might also be useful in this context.

ContentLicense: CC BY-SA 4.0

Body:
Put the list of packages you require in a text file, e.g.,

packages.txt

dill
csvkit
...

Note: This file can also include versions, channels, and builds. Basically, anything that you can output with conda list --export.

Then run a loop similar to that found in the other answer,

for env in $(conda env list | awk '/^[a-zA-Z]/' | cut -d' ' -f1); do
    conda install -n "$env" --file packages.txt;
done

Perhaps the -y|--yes and -q|--quiet might also be useful in this context.


问:
audio is out of sync after concat 2 files
i want to show a video, that has 2 movies side by side. each movie is a result of one movie that concat 2 times. the problem is that the audio in the right side is out of sync.

i have 3 commands:
first command concat one movie 2 times

```<code>ffmpeg -i 1.mp4 -i 1.mp4 -filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[concatv][concata]" -map "[concatv]" -map "[concata]" Concat1.mp4
</code>```

second command concat the second movie 2 times

```<code>ffmpeg -i 2.mp4 -i 2.mp4 -filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[concatv][concata]" -map "[concatv]" -map "[concata]" Concat2.mp4
</code>```

at this point the audio is always synced.
the third command takes the 2 results and merge it to one movie side by side with a logo:

```<code>ffmpeg -i Concat1.mp4 -i Concat2.mp4 -i logo.png -filter_complex "[0:v]pad=width=iw+20:height=ih+20:x=10:y=10:color=black[a];[1:v]pad=width=iw+20:height=ih+20:x=10:y=10:color=black[b];nullsrc=size=640x480[base];[a]setpts=PTS-STARTPTS, scale=320x480[left];[b]setpts=PTS-STARTPTS, scale=320x480[right];[base][left]overlay=shortest=1[tmp1];[tmp1][right] overlay=320:0[video];[0:a]apad [apa];[apa][1:a]amerge=inputs=2,pan=stereo|FL<c0+c1|FR<c0+c1[audio];[2:v]scale=120:44 [ovrl];[video][ovrl]overlay=15:25[videoandlogo]" -map "[videoandlogo]" -map "[audio]" output.mp4
</code>```

the problem is that in the output file the audio of the right movie is out of sync in its second time (the second concat). it always the right movie that is out of sync, even when i switch them.

can anyone help?
Thanks.

==============EDIT===================

the problem of the sync has solved by adding apad also to the second file, but after that the command never stops... how can i tell the command to stop when both movies ended if i have apad for both movies?
this is the new command that never stops:

```<code>ffmpeg -i 1.mp4 -i 2.mp4 -i logo.png -filter_complex "[0:v]pad=width=iw+20:height=ih+20:x=10:y=10:color=black[a];[1:v]pad=width=iw+20:height=ih+20:x=10:y=10:color=black[b];nullsrc=size=640x480[base];[a]scale=320x480[left];[b]scale=320x480[right];[base][left]overlay=shortest=1[tmp1];[tmp1][right] overlay=320:0[video];[1:a]apad [apa];[0:a]apad[apa1];[apa][apa1]amix=inputs=2:duration=longest[audio];[2:v]scale=120:44 [ovrl];[video][ovrl]overlay=15:25[videoandlogo]" -map "[videoandlogo]" -map "[audio]" output.mp4
</code>```

答:
Found the answer (hope it will help someone).
for the audio problem, i solved it by putting apad to all of the movies (need to put the apad of the longest movie first). and to fix the never ending movie i put "-t ".
Thanks.</p>

Body:
i want to show a video, that has 2 movies side by side. each movie is a result of one movie that concat 2 times. the problem is that the audio in the right side is out of sync.

i have 3 commands:
first command concat one movie 2 times

ffmpeg -i 1.mp4 -i 1.mp4 -filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[concatv][concata]" -map "[concatv]" -map "[concata]" Concat1.mp4

second command concat the second movie 2 times

ffmpeg -i 2.mp4 -i 2.mp4 -filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]concat=n=2:v=1:a=1[concatv][concata]" -map "[concatv]" -map "[concata]" Concat2.mp4

at this point the audio is always synced.
the third command takes the 2 results and merge it to one movie side by side with a logo:

ffmpeg -i Concat1.mp4 -i Concat2.mp4 -i logo.png -filter_complex "[0:v]pad=width=iw+20:height=ih+20:x=10:y=10:color=black[a];[1:v]pad=width=iw+20:height=ih+20:x=10:y=10:color=black[b];nullsrc=size=640x480[base];[a]setpts=PTS-STARTPTS, scale=320x480[left];[b]setpts=PTS-STARTPTS, scale=320x480[right];[base][left]overlay=shortest=1[tmp1];[tmp1][right] overlay=320:0[video];[0:a]apad [apa];[apa][1:a]amerge=inputs=2,pan=stereo|FL<c0+c1|FR<c0+c1[audio];[2:v]scale=120:44 [ovrl];[video][ovrl]overlay=15:25[videoandlogo]" -map "[videoandlogo]" -map "[audio]" output.mp4

the problem is that in the output file the audio of the right movie is out of sync in its second time (the second concat). it always the right movie that is out of sync, even when i switch them.

can anyone help?
Thanks.

==============EDIT===================

the problem of the sync has solved by adding apad also to the second file, but after that the command never stops... how can i tell the command to stop when both movies ended if i have apad for both movies?
this is the new command that never stops:

ffmpeg -i 1.mp4 -i 2.mp4 -i logo.png -filter_complex "[0:v]pad=width=iw+20:height=ih+20:x=10:y=10:color=black[a];[1:v]pad=width=iw+20:height=ih+20:x=10:y=10:color=black[b];nullsrc=size=640x480[base];[a]scale=320x480[left];[b]scale=320x480[right];[base][left]overlay=shortest=1[tmp1];[tmp1][right] overlay=320:0[video];[1:a]apad [apa];[0:a]apad[apa1];[apa][apa1]amix=inputs=2:duration=longest[audio];[2:v]scale=120:44 [ovrl];[video][ovrl]overlay=15:25[videoandlogo]" -map "[videoandlogo]" -map "[audio]" output.mp4


问:
How to make TypeScript generate a CommonJS valid module?
Let's say I have a module in TypeScript:

```<code>export default function myModule(name: string): void {
  alert(`Hello, ${name}!`)
}
</code>```

When I run tsc to build the above code, and try to import the generated code through Node.js (pure JavaScript):

```<code>const myModule = require('./dist/myModule.js')
myModule('Luiz') // ERROR! `myModule` is `undefined`
</code>```

The only way to make it work is by using .default  after the require(), which is not what I want:

```<code>//                                            ↓↓↓↓↓↓↓↓
const myModule = require('./dist/myModule.js').default
myModule('Luiz') // Now it works.
</code>```

How can I make TypeScript generate an output that I can use later as a Node.js module (as I'm publishing the package into NPM) without that .default property? Just like this:

```<code>const myModule = require('my-module')
</code>```

答:
Short Answer

Use export = to build a CommonJS module that exports a function.

The TypeScript docs say:

TypeScript supports export = to model the traditional CommonJS and AMD workflow... The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.

Full Setup

myModule.ts

export = function myModule(name: string): void {
  console.log(`Hello, ${name}!`)
}
```

<p>tsconfig.json</p>

```{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs"
  }
}
```

<p>myModule.js (output)</p>

```"use strict";
module.exports = function myModule(name) {
    console.log("Hello, " + name + "!");
};
```

<p>demo.js (usage)</p>

```const myModule = require('./my-module');

myModule('Luiz'); // Hello, Luiz!
```

Body:
Let's say I have a module in TypeScript:

export default function myModule(name: string): void {
  alert(`Hello, ${name}!`)
}

When I run tsc to build the above code, and try to import the generated code through Node.js (pure JavaScript):

const myModule = require('./dist/myModule.js')
myModule('Luiz') // ERROR! `myModule` is `undefined`

The only way to make it work is by using .default  after the require(), which is not what I want:

//                                            ↓↓↓↓↓↓↓↓
const myModule = require('./dist/myModule.js').default
myModule('Luiz') // Now it works.

How can I make TypeScript generate an output that I can use later as a Node.js module (as I'm publishing the package into NPM) without that .default property? Just like this:

const myModule = require('my-module')

Body:
Short Answer

Use export = to build a CommonJS module that exports a function.

The TypeScript docs say:

TypeScript supports export = to model the traditional CommonJS and AMD workflow... The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.

Full Setup

myModule.ts

export = function myModule(name: string): void {
  console.log(`Hello, ${name}!`)
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs"
  }
}

myModule.js (output)

"use strict";
module.exports = function myModule(name) {
    console.log("Hello, " + name + "!");
};

demo.js (usage)

const myModule = require('./my-module');

myModule('Luiz'); // Hello, Luiz!


问:
Zend Framework - Add new input element using javascript
I'm working on a project using Zend Framework.

I'm creating a form on which users can add a set of elements by pressing a + sign.

Zend framework uses subforms and decorators to get array of values from a form.

These will show when the page is displayed

How does the new fields created with Javascript integrate in that model?

答:
The best demo of dynamically adding fields on the client to a Zend_Form with which I am familiar comes from Jeremy Kendall:

http://jeremykendall.net/2009/01/19/dynamically-adding-elements-to-zend-form/

The upshot of the technique is to add/call a preValidation() method on the form to check the post for fields missing in the form. If it finds any such fields, then they are added to the form object. By the time isValid() and getValues() are called, all the Zend_Form_Element objects have already been attached to the form, so processing runs as normal.

ContentLicense: CC BY-SA 3.0


问:
Know if image is overzised
I`m creating a function to upload an image. But it won´t over 400px of height and 400px of width, this is part of the code

$(() => {
    $(document).on('change', 'input', function (e) {
        let file = event.target.files[0];
        if (!file) {
            e.preventDefault();
            return;
        }else{
            let imageType = /image.*/;
            if (!file.type.match(imageType)) {
                e.preventDefault();
                return;
            }else {
                let reader = new FileReader();
                reader.onload = () => {
                    $('img').attr('src', reader.result);
                }
                reader.readAsDataURL(file);
            }
        }
        //What to do here?
        if ( width > 400 || height > 400) {
            console.log('oversized');

        }
    });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file">
<img src=""></code>```

It is not working, how could I validate if the image and not the img tag
is oversized, I created this code with Jquery to fast problem replication, but, if you can help me with vanilla Javascript, it will be awesome

答:
Try this:

$(() => {
    $(document).on('change', 'input', function (e) {
        let file = event.target.files[0];

        if (!file) {
            e.preventDefault();
            return;
        }else{
            let imageType = /image.*/;
            if (!file.type.match(imageType)) {
                e.preventDefault();
                return;
            }else {
                let reader = new FileReader();
                reader.onload = () => {
                this.imagePreview = new Image();
                this.imagePreview.onload = (imageEvent) => {

                  if (this.imagePreview.width > 400 || this.imagePreview.height > 400) {
   alert(`Allowed dimensions are 400x400 px`);
   return;
    }
  };

                 this.imagePreview.src = reader.result;
                 $('img').attr('src', reader.result);
                }
                reader.readAsDataURL(file);
            }
        }

    });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<input type="file" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
 </code>```

Title: Know if image is overzised

Body:
I`m creating a function to upload an image. But it won´t over 400px of height and 400px of width, this is part of the code

$(() => {
    $(document).on('change', 'input', function (e) {
        let file = event.target.files[0];
        if (!file) {
            e.preventDefault();
            return;
        }else{
            let imageType = /image.*/;
            if (!file.type.match(imageType)) {
                e.preventDefault();
                return;
            }else {
                let reader = new FileReader();
                reader.onload = () => {
                    $('img').attr('src', reader.result);
                }
                reader.readAsDataURL(file);
            }
        }
        //What to do here?
        if ( width > 400 || height > 400) {
            console.log('oversized');

        }
    });
})

<input type="file">

It is not working, how could I validate if the image and not the img tag
is oversized, I created this code with Jquery to fast problem replication, but, if you can help me with vanilla Javascript, it will be awesome

Body:
Try this:

$(() => {
    $(document).on('change', 'input', function (e) {
        let file = event.target.files[0];

        if (!file) {
            e.preventDefault();
            return;
        }else{
            let imageType = /image.*/;
            if (!file.type.match(imageType)) {
                e.preventDefault();
                return;
            }else {
                let reader = new FileReader();
                reader.onload = () => {
                this.imagePreview = new Image();
                this.imagePreview.onload = (imageEvent) => {

                  if (this.imagePreview.width > 400 || this.imagePreview.height > 400) {
   alert(`Allowed dimensions are 400x400 px`);
   return;
    }
  };

                 this.imagePreview.src = reader.result;
                 $('img').attr('src', reader.result);
                }
                reader.readAsDataURL(file);
            }
        }

    });
})

<input type="file" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>


问:
ModelSim simulation outcome doesnt match with the logic of my multiplexer code
I wrote some verilog code about a 7-to-1 Multiplexer with "always" and "case" statements but when I  made a simulation in ModelSim, the outcome seems to not work as expected

Part of multiplexer logic :

```<code>when SW[9:7] = 000, OUT = SW[0]
</code>```

Contradiction :

```<code>In the simulation when SW[0] is changed to 1, the outcome stays at 0.
</code>```

```<code>module SevenToOneMUX(SW, OUT);

    input [9:0] SW;
    output reg OUT;

    always@(SW[9:7])
    begin
        case (SW[9:7])
            3'b000: OUT = SW[0];
            3'b001: OUT = SW[1];
            3'b010: OUT = SW[2];
            3'b011: OUT = SW[3];
            3'b100: OUT = SW[4];
            3'b101: OUT = SW[5];
            3'b110: OUT = SW[6];
        endcase
    end

endmodule
</code>```

答:
The problem is that you only put the 3 most-significant bit of SW in the sensitivity list of your combinational block. This means that the compiler will only execute the always@(SW[9:7]) block if SW[9:7] changes.

If you want to the simulator to update OUT when any of SW's bits changed, change your sensitivity list to the following:

```<code>always@(*)
begin
    /*...*/
end
</code>```

It is also worth to note that always@(*), which was added in Verilog-2001, is usually used when creating synthesizable combinational logic. In hardware, the real logic will be "sensitive" to every right-hand side variable. That means: if any input of the logic you describe changes, the output will also change.

Body:
I wrote some verilog code about a 7-to-1 Multiplexer with "always" and "case" statements but when I  made a simulation in ModelSim, the outcome seems to not work as expected

Part of multiplexer logic :

when SW[9:7] = 000, OUT = SW[0]

Contradiction :

In the simulation when SW[0] is changed to 1, the outcome stays at 0.

module SevenToOneMUX(SW, OUT);

    input [9:0] SW;
    output reg OUT;

    always@(SW[9:7])
    begin
        case (SW[9:7])
            3'b000: OUT = SW[0];
            3'b001: OUT = SW[1];
            3'b010: OUT = SW[2];
            3'b011: OUT = SW[3];
            3'b100: OUT = SW[4];
            3'b101: OUT = SW[5];
            3'b110: OUT = SW[6];
        endcase
    end

endmodule

Body:
The problem is that you only put the 3 most-significant bit of SW in the sensitivity list of your combinational block. This means that the compiler will only execute the always@(SW[9:7]) block if SW[9:7] changes.

If you want to the simulator to update OUT when any of SW's bits changed, change your sensitivity list to the following:

always@(*)
begin
    /*...*/
end

It is also worth to note that always@(*), which was added in Verilog-2001, is usually used when creating synthesizable combinational logic. In hardware, the real logic will be "sensitive" to every right-hand side variable. That means: if any input of the logic you describe changes, the output will also change.


问:
Graphite with powershell
I'm have an instance of graphite configured on one server, and i'm using it to monitor my environment which sadly consists of both linux and windows machines. I want monitor the well-being of my servers so i have opted for collectl on my linux machines which does a nice job collecting system stats.

Sadly for windows there don't seem to be so many solution for getting system stats and sending them to graphite, but i've manage to handle this situation with powershell. I'm using the a script which was suggested here http://josh.behrends.us/2012/07/windows-powershell-graphite-awesome/ for the graphite connection and also for getting metrics out of the computer
i'm using get-counter comandlet which, surprisingly,  can gather a lot of info.

My script looks like this:

```<code>while (1 -eq 1)
{
$carbonServer = "hostname"
$carbonServerPort = 2003
$epochtime = [int][double]::Parse((Get-Date -UFormat %s))

$socket = New-Object System.Net.Sockets.TCPClient
$socket.connect($carbonServer, $carbonServerPort)
$stream = $socket.GetStream()
$writer = new-object System.IO.StreamWriter($stream)
#Write out metric to the stream.

$DiskQue =  [int]((get-counter -Counter "\PhysicalDisk(1 e: f:)\Current Disk Queue Length" ).countersamples | select -property cookedvalue).cookedvalue
$BytesReceived = [int]((get-counter -Counter "\Server\Bytes Received/sec" ).countersamples | select -property cookedvalue).cookedvalue
$BytesSent =  [int]((get-counter -Counter "\Server\Bytes Transmitted/sec").countersamples | select -property cookedvalue).cookedvalue
$MemAvail = ((get-counter -Counter "\Memory\Available Bytes").countersamples | select -property cookedvalue).cookedvalue
$MemCommit = ((get-counter -Counter "\Memory\Committed Bytes").countersamples | select -property cookedvalue).cookedvalue
$ReadOp =  [int]((get-counter -Counter "\System\File Read Operations/sec").countersamples | select -property cookedvalue).cookedvalue
$WriteOp = [int]((get-counter -Counter "\System\File Write Operations/sec").countersamples | select -property cookedvalue).cookedvalue

$metric7 = ("hostname.metrics.WriteOp " + $WriteOp + " " + $epochTime+"`n")
$metric7

$writer.WriteLine($metric7)
$writer.Flush() #Flush and write our metrics.
$writer.Close()
$stream.Close()
sleep 5
}
</code>```

Now this script outputs what it's supposed to at first glance. The output has the format hostname.metrics.name $metric_value $epochTime but there are no graphs being graphed. They apear in the graphite dashboard but they are empty. I've inspected the output sent to the graphite server with wireshark. It seams that in windows the message gets appended with CRLF as opposed to linux where you only have LF. I have added \n by hand and for a small period of time it did the trick but now it stopped working.

My question is am i doing something wrong in the transmission because i've been analysing the trafic and the only difference between traffic coming form linux machines that gets graphed and from windows that doesn't get graphed is the line terminators. In linux its LF(0a) and in windows is CRLF(0d0a), but again i've tried to send from linux LFCRLF(0a0d0a)
hoping the graphite server will read only until the first LF and than interepret the message but still i'm not geting graphs.

Also when I transmit from linux i have only one message, and when i transmit form powershell i have three messages. From what i've saw with strace on the carbon-cache process i have one recvfrom system call with the message i want, and the I have an other one which is empty and the the write syscall(when transmitting from powershell) as opposed yo anly one recvfrom with the message and a write(when transmitting with netcat on linux) ,

答:
I mostly wanted to let you know that you are not alone.  I ran into the same problem where charts showed up, but the data was null.  I was however able to make it past the 0d0a vs 0a problem in this code.  I tried UDP as well but in my case that didn't work either.  Perhaps you will have some luck with TCP using this method.  Cobbled this from various sources.</p>

```<code>$dtmUTC = [int][double]::Parse((Get-Date -UFormat %s))
$CR=""
$carbonServer = "host.domain.com"
[int] $carbonServerPort = 2003

[int]$bufSize = 1472  #MTU on this network

$IP = [System.Net.Dns]::GetHostAddresses($carbonServer)
$Address = [system.net.IPAddress]::Parse($IP)
$EndPoint = New-Object System.Net.IPEndPoint $Address, $carbonServerPort
$Saddrf   = [System.Net.Sockets.AddressFamily]::InterNetwork

#UDP
$Stype    = [System.Net.Sockets.SocketType]::Dgram
$Ptype    = [System.Net.Sockets.ProtocolType]::UDP

#TCP
#$Stype    = [System.Net.Sockets.SocketType]::Stream
#$Ptype    = [System.Net.Sockets.ProtocolType]::TCP

$Sock     = New-Object System.Net.Sockets.Socket $Saddrf, $Stype, $Ptype
$Sock.Connect($EndPoint)

function Send_Graphite
{
    param ($thisFile)
    #encoder object
    $Enc = [System.Text.Encoding]::ASCII

    # Read the entire file
    $bytes = [System.IO.File]::ReadAllText($thisFile)

    $begin=0
    $remain=$bytes.Length
    while ( $begin -lt $bytes.Length)
    {

        if ( $remain -lt $bufsize)
        {
            $bufsize = $remain
        }

        $Chunk = $bytes.Substring($begin, $bufsize)
        $Buffer = $Enc.GetBytes($Chunk)
        $rc=$Sock.Send($Buffer)
        sleep 1
        $begin  += $bufsize
        $remain = $remain - $bufsize
    }
}

$M=""
foreach ($C in "server1","server2")
{
    #echo "polling $C ===================="
    ForEach ( $Drives in Get-WmiObject Win32_LogicalDisk -ComputerName $c -Filter "DriveType=3"  )
    {
        ForEach ( $Drive in $Drives )
        {
            $D=$Drive.DeviceID.Replace(":","")
            $SZ=$Drive.Size
            $FS=$Drive.FreeSpace
            $N=$Drive.VolumeName
            $N=$N.Replace(" ","")

            $U=$SZ-$FS
            $S="itinf.stor.$C"

            if ( $FS -eq "" )
            {
                echo "$N FreeSpace was null"
            }
            if ( $N -eq "" )
            {
                $N="default"
                #echo "$N VolumeName was null"
            }
            if ($SZ -eq "")
            {
                echo "$N Size was null"
            }
            $M = $M + $CR
            $CR="`n"
            $M = $M + "$S.$N.Size $SZ $dtmUTC$CR"
            $M = $M + "$S.$N.Free $FS $dtmUTC$CR"
            $M = $M + "$S.$N.Used $U $dtmUTC$CR"
            $M = $M + "$S.$D.Size $SZ $dtmUTC$CR"
            $M = $M + "$S.$D.Free $FS $dtmUTC$CR"
            $M = $M + "$S.$D.Used $U $dtmUTC"
        }
    }
}

Out-File -NoNewline -FilePath gph.txt -InputObject $M
Send_Graphite gph.txt
sleep .1

if ($Ptype -eq "TCP") { $Sock.Disconnect($EndPoint) }
</code>```

Title: Graphite with powershell

Body:
I'm have an instance of graphite configured on one server, and i'm using it to monitor my environment which sadly consists of both linux and windows machines. I want monitor the well-being of my servers so i have opted for collectl on my linux machines which does a nice job collecting system stats.

Sadly for windows there don't seem to be so many solution for getting system stats and sending them to graphite, but i've manage to handle this situation with powershell. I'm using the a script which was suggested here http://josh.behrends.us/2012/07/windows-powershell-graphite-awesome/ for the graphite connection and also for getting metrics out of the computer
i'm using get-counter comandlet which, surprisingly,  can gather a lot of info.

My script looks like this:

while (1 -eq 1)
{
$carbonServer = "hostname"
$carbonServerPort = 2003
$epochtime = [int][double]::Parse((Get-Date -UFormat %s))

$socket = New-Object System.Net.Sockets.TCPClient
$socket.connect($carbonServer, $carbonServerPort)
$stream = $socket.GetStream()
$writer = new-object System.IO.StreamWriter($stream)
#Write out metric to the stream.

$DiskQue =  [int]((get-counter -Counter "\PhysicalDisk(1 e: f:)\Current Disk Queue Length" ).countersamples | select -property cookedvalue).cookedvalue
$BytesReceived = [int]((get-counter -Counter "\Server\Bytes Received/sec" ).countersamples | select -property cookedvalue).cookedvalue
$BytesSent =  [int]((get-counter -Counter "\Server\Bytes Transmitted/sec").countersamples | select -property cookedvalue).cookedvalue
$MemAvail = ((get-counter -Counter "\Memory\Available Bytes").countersamples | select -property cookedvalue).cookedvalue
$MemCommit = ((get-counter -Counter "\Memory\Committed Bytes").countersamples | select -property cookedvalue).cookedvalue
$ReadOp =  [int]((get-counter -Counter "\System\File Read Operations/sec").countersamples | select -property cookedvalue).cookedvalue
$WriteOp = [int]((get-counter -Counter "\System\File Write Operations/sec").countersamples | select -property cookedvalue).cookedvalue

$metric7 = ("hostname.metrics.WriteOp " + $WriteOp + " " + $epochTime+"`n")
$metric7

$writer.WriteLine($metric7)
$writer.Flush() #Flush and write our metrics.
$writer.Close()
$stream.Close()
sleep 5
}

Now this script outputs what it's supposed to at first glance. The output has the format hostname.metrics.name $metric_value $epochTime but there are no graphs being graphed. They apear in the graphite dashboard but they are empty. I've inspected the output sent to the graphite server with wireshark. It seams that in windows the message gets appended with CRLF as opposed to linux where you only have LF. I have added \n by hand and for a small period of time it did the trick but now it stopped working.

My question is am i doing something wrong in the transmission because i've been analysing the trafic and the only difference between traffic coming form linux machines that gets graphed and from windows that doesn't get graphed is the line terminators. In linux its LF(0a) and in windows is CRLF(0d0a), but again i've tried to send from linux LFCRLF(0a0d0a)
hoping the graphite server will read only until the first LF and than interepret the message but still i'm not geting graphs.

Also when I transmit from linux i have only one message, and when i transmit form powershell i have three messages. From what i've saw with strace on the carbon-cache process i have one recvfrom system call with the message i want, and the I have an other one which is empty and the the write syscall(when transmitting from powershell) as opposed yo anly one recvfrom with the message and a write(when transmitting with netcat on linux) ,

Body:
I mostly wanted to let you know that you are not alone.  I ran into the same problem where charts showed up, but the data was null.  I was however able to make it past the 0d0a vs 0a problem in this code.  I tried UDP as well but in my case that didn't work either.  Perhaps you will have some luck with TCP using this method.  Cobbled this from various sources.

$dtmUTC = [int][double]::Parse((Get-Date -UFormat %s))
$CR=""
$carbonServer = "host.domain.com"
[int] $carbonServerPort = 2003

[int]$bufSize = 1472  #MTU on this network

$IP = [System.Net.Dns]::GetHostAddresses($carbonServer)
$Address = [system.net.IPAddress]::Parse($IP)
$EndPoint = New-Object System.Net.IPEndPoint $Address, $carbonServerPort
$Saddrf   = [System.Net.Sockets.AddressFamily]::InterNetwork

#UDP
$Stype    = [System.Net.Sockets.SocketType]::Dgram
$Ptype    = [System.Net.Sockets.ProtocolType]::UDP

#TCP
#$Stype    = [System.Net.Sockets.SocketType]::Stream
#$Ptype    = [System.Net.Sockets.ProtocolType]::TCP

$Sock     = New-Object System.Net.Sockets.Socket $Saddrf, $Stype, $Ptype
$Sock.Connect($EndPoint)

function Send_Graphite
{
    param ($thisFile)
    #encoder object
    $Enc = [System.Text.Encoding]::ASCII

    # Read the entire file
    $bytes = [System.IO.File]::ReadAllText($thisFile)

    $begin=0
    $remain=$bytes.Length
    while ( $begin -lt $bytes.Length)
    {

        if ( $remain -lt $bufsize)
        {
            $bufsize = $remain
        }

        $Chunk = $bytes.Substring($begin, $bufsize)
        $Buffer = $Enc.GetBytes($Chunk)
        $rc=$Sock.Send($Buffer)
        sleep 1
        $begin  += $bufsize
        $remain = $remain - $bufsize
    }
}

$M=""
foreach ($C in "server1","server2")
{
    #echo "polling $C ===================="
    ForEach ( $Drives in Get-WmiObject Win32_LogicalDisk -ComputerName $c -Filter "DriveType=3"  )
    {
        ForEach ( $Drive in $Drives )
        {
            $D=$Drive.DeviceID.Replace(":","")
            $SZ=$Drive.Size
            $FS=$Drive.FreeSpace
            $N=$Drive.VolumeName
            $N=$N.Replace(" ","")

            $U=$SZ-$FS
            $S="itinf.stor.$C"

            if ( $FS -eq "" )
            {
                echo "$N FreeSpace was null"
            }
            if ( $N -eq "" )
            {
                $N="default"
                #echo "$N VolumeName was null"
            }
            if ($SZ -eq "")
            {
                echo "$N Size was null"
            }
            $M = $M + $CR
            $CR="`n"
            $M = $M + "$S.$N.Size $SZ $dtmUTC$CR"
            $M = $M + "$S.$N.Free $FS $dtmUTC$CR"
            $M = $M + "$S.$N.Used $U $dtmUTC$CR"
            $M = $M + "$S.$D.Size $SZ $dtmUTC$CR"
            $M = $M + "$S.$D.Free $FS $dtmUTC$CR"
            $M = $M + "$S.$D.Used $U $dtmUTC"
        }
    }
}

Out-File -NoNewline -FilePath gph.txt -InputObject $M
Send_Graphite gph.txt
sleep .1

if ($Ptype -eq "TCP") { $Sock.Disconnect($EndPoint) }


问:
mod-rewrite recursive loop
I want to change my website's dynamic urls to Search Engine Friendly URL's

Now the urls like this www.website.com/news.php?id=127591 ,
I want it became this www.website.com/news/127591/this-is-article-subject

I added this

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
</code>```

in my .htaccess file. Everything from /news.php?id=123 change to /new/123/this-is-article-subject

The problem is, now I have two links refer to the same contents. Both /news.php?id=123 and /new/123/this-is-article-subject are the exactly duplicate content

It is said that search engine will punish this if they found duplicated contents.

I check the answers online and found this,

```<code>RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

HTTP 301 permanent redirect from the old URL to the new URL.

But this still have problem. When I put those three lines together, it not works.

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

I guess the reason is the recursive loop. How could I solve this kind of problem?

Thanks!

Update

I changed to this

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

None of the two url work.

答:
Please try this rule in your .htaccess file:

```<code>RewriteEngine on
Options +FollowSymlinks -MultiViews

RewriteCond %{THE_REQUEST} \?id=([0-9]+)\s [NC]
RewriteRule ^news\.php /news/%1? [R=301,L]

RewriteRule ^news/([0-9]+) /news.php?id=$1 [L,NS,NE,QSA,NC]
</code>```

UPDATE:: Based on your comments:

Inside news.php when URL doesn't have /some-title then output this META tag to stop indexing /news/987 type URIs:

```<code><meta name="robots" content="NOINDEX, NOFOLLOW">
</code>```

Once you notice URI of /news/987/some-title inside news.php simply mask above META tag.
I have tested it and seems to be working fine so let me know if doesn't work for you.

Title: mod-rewrite recursive loop

Body:
I want to change my website's dynamic urls to Search Engine Friendly URL's

Now the urls like this www.website.com/news.php?id=127591 ,
I want it became this www.website.com/news/127591/this-is-article-subject

I added this

RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]

in my .htaccess file. Everything from /news.php?id=123 change to /new/123/this-is-article-subject

The problem is, now I have two links refer to the same contents. Both /news.php?id=123 and /new/123/this-is-article-subject are the exactly duplicate content

It is said that search engine will punish this if they found duplicated contents.

I check the answers online and found this,

RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

HTTP 301 permanent redirect from the old URL to the new URL.

But this still have problem. When I put those three lines together, it not works.

RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

I guess the reason is the recursive loop. How could I solve this kind of problem?

Thanks!

Update

I changed to this

RewriteRule ^news/([0-9]+) /news.php?id=$1 [L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

None of the two url work.

Body:
Please try this rule in your .htaccess file:

RewriteEngine on
Options +FollowSymlinks -MultiViews

RewriteCond %{THE_REQUEST} \?id=([0-9]+)\s [NC]
RewriteRule ^news\.php /news/%1? [R=301,L]

RewriteRule ^news/([0-9]+) /news.php?id=$1 [L,NS,NE,QSA,NC]

UPDATE:: Based on your comments:

Inside news.php when URL doesn't have /some-title then output this META tag to stop indexing /news/987 type URIs:

<meta name="robots" content="NOINDEX, NOFOLLOW">

Once you notice URI of /news/987/some-title inside news.php simply mask above META tag.
I have tested it and seems to be working fine so let me know if doesn't work for you.


问:
How to add a unique id to first of kind
ok.  Building out a employee directory.  At the top of the directory is the alphabet so you can click on a letter an arrive at the first person who has that letter as first letter of last name.  How can i loop through the all of the employees and add an id of the letter to the first of each.  I haven't built out the markup, yet, but for now it could be as simple as </p>

```<code><h3><span class="fname">Johnny</span><span class="lname">Willis</span></h3>
</div> ```

Where I would target the last name and add an ID to the card
I am pulling all of the content in from a hubspot hubdb.  Unsure if that is relevant, but wanted to add that.
</code>```

答:
I think you don't need to add an ID to each of the last names from your list. If you just want to scroll down to the first item when clicking the alphabet index, try this:

HTML

```<code><!-- A container for the alphabet letters -->
<div id="alphabet">
  <span id="letter-a">A</span>
  <span id="letter-b">B</span>
  <span id="letter-c">C</span>
  <span id="letter-d">D</span>
</div>

<!-- A container for each last name -->
<div id="employee-a" style="height:500px">
  <p>A</p>
  <p>Adams Mike</p>
  <p>Addison John</p>
  <p>Adkins Smith</p>
</div>
<div id="employee-b" style="height:500px">
  <p>B</p>
  <p>Bain Chris</p>
  <p>Barker Travis</p>
  <p>Banner Brock</p>
</div>
<div id="employee-c" style="height:500px">
  <p>C</p>
  <p>Carl Steve</p>
  <p>Carter Aaron</p>
  <p>Castle Vania</p>
</div>
<div id="employee-d" style="height:500px">
  <p>D</p>
  <p>Daenerys Targaryen</p>
  <p>Dale Denton</p>
  <p>Daniels Jack</p>
</div>
</code>```

JAVASCRIPT

```<code><script>
  // Wait until DOM is fully loaded
  $(document).ready(function() {
    // Get the ID name from the letter you clicked
    $('#alphabet > span').on('click', function() {
      // Pass this ID name to a variable
      var letter = $(this).attr('id');
      var goTo = letter.split('-').pop();
      // Use it to smooth scroll to the position of the first last name with the letter you clicked
      $('html, body').animate({
        scrollTop : $('#employee-' + goTo).offset().top
      }, 500);
    })
  });
</script>
</code>```

Hope this helps.

Enjoy!

Title: How to add a unique id to first of kind

Body:
ok.  Building out a employee directory.  At the top of the directory is the alphabet so you can click on a letter an arrive at the first person who has that letter as first letter of last name.  How can i loop through the all of the employees and add an id of the letter to the first of each.  I haven't built out the markup, yet, but for now it could be as simple as

JohnnyWillis

 ```

Where I would target the last name and add an ID to the card
I am pulling all of the content in from a hubspot hubdb.  Unsure if that is relevant, but wanted to add that.

Body:
I think you don't need to add an ID to each of the last names from your list. If you just want to scroll down to the first item when clicking the alphabet index, try this:

HTML

<!-- A container for the alphabet letters -->
<div id="alphabet">
  <span id="letter-a">A</span>
  <span id="letter-b">B</span>
  <span id="letter-c">C</span>
  <span id="letter-d">D</span>
</div>

<!-- A container for each last name -->
<div id="employee-a" style="height:500px">
  <p>A</p>
  <p>Adams Mike</p>
  <p>Addison John</p>
  <p>Adkins Smith</p>
</div>
<div id="employee-b" style="height:500px">
  <p>B</p>
  <p>Bain Chris</p>
  <p>Barker Travis</p>
  <p>Banner Brock</p>
</div>
<div id="employee-c" style="height:500px">
  <p>C</p>
  <p>Carl Steve</p>
  <p>Carter Aaron</p>
  <p>Castle Vania</p>
</div>
<div id="employee-d" style="height:500px">
  <p>D</p>
  <p>Daenerys Targaryen</p>
  <p>Dale Denton</p>
  <p>Daniels Jack</p>
</div>

JAVASCRIPT

<script>
  // Wait until DOM is fully loaded
  $(document).ready(function() {
    // Get the ID name from the letter you clicked
    $('#alphabet > span').on('click', function() {
      // Pass this ID name to a variable
      var letter = $(this).attr('id');
      var goTo = letter.split('-').pop();
      // Use it to smooth scroll to the position of the first last name with the letter you clicked
      $('html, body').animate({
        scrollTop : $('#employee-' + goTo).offset().top
      }, 500);
    })
  });
</script>

Hope this helps.

Enjoy!


问:
Is there a speed difference in MySQL operations?
I was discussing speed of MySQL statements and someone asked me: Between SELECT, INSERT, UPDATE, and DELETE, which is faster and why?

I didn't know the answer. Does anyone know if one is faster than the other, and if so, why? Or are they all generally the same speed?

答:
Mostly "it depends".

For example, if the database is serving a lot of concurrent users then the amount of time the table is locked is going to matter more than the amount of time the query takes in total.

As a rule of thumb, I would say:

INSERT is usually fastest, as it only adds data and doesn't need to lock the table because no existing data is modified.  Lots of indexes could slow it down a little though.

SELECT can potentially be very fast or very slow.  It depends on the query.  It has the potential to be the fastest, and it doesn't lock the table.  But SELECT operations are often a lot more complex than the others, fetching data from multiple tables, or sorting or using indexes more comprehensively.

DELETE is relatively slow.  The table (or depending on the storage engine, the affected rows) needs to be locked.  Indexes need updating.

UPDATE is usually the slowest.  The table (or depending on the storage engine, the affected rows) need to be locked, indexes need updating, and it is slightly more involved than DELETE.

But as I said, this is all a rule of thumb, and it really depends a lot on circumstances.

OwnerDisplayName: rocket

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: trr


问:
Why this sprintf statement crashing?
```<code>char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here
</code>```

If I format only current, then it is ok.

```<code>sprintf(filebuf,"%s",current);
</code>```

Output:

```<code>CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release
</code>```

答: The reason of the crash has already been explained - I can only add one piece of advice - just ditch sprintf if possible and use string streams. It will make your code better. You will not have to worry about the length of the buffer or other errors like the one you encountered.</p>

Title: Why this sprintf statement crashing?

Body:
char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here

If I format only current, then it is ok.

sprintf(filebuf,"%s",current);

Output:

CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release


问:
Explanation for logical operators example in Eloquent JS
I have problems understanding following example from Eloquent JS book :

console.log(
  1 + 1 == 2 && 10 * 10 > 50 // true
);```

Can someone explain it to me, step by step.

Body:
I have problems understanding following example from Eloquent JS book :

console.log(
  1 + 1 == 2 && 10 * 10 > 50 // true
);

Can someone explain it to me, step by step.

Body:
Operator precedence
:

+ has precedence of 13

== has precedence of 10

* has precedence of 14

> has precedence of 11

&& has precedence of 6

So, the code is equivalent to:

1 + 1 == 2 && (10 * 10) > 50 // group * (precedence 14)
(1 + 1) == 2 && (10 * 10) > 50 // group + (precedence 13)
(1 + 1) == 2 && ((10 * 10) > 50) // group > (precedence 11)
((1 + 1) == 2) && ((10 * 10) > 50) // group == (precedence 10)

Then simplify:

((1 + 1) == 2) && ((10 * 10) > 50)
((2) == 2) && ((10 * 10) > 50)
(true) && ((10 * 10) > 50)
(true) && ((100) > 50)
(true) && (true)
true


问:
Show only posts that user has access
I have this 3 tables, one post can be viewed by more than one user:

users

posts

user_posts

How I can do with Eloquent to show to the users only the posts that he has access?

Thanks

答:
I assume you have the models set up correctly, something like this on the User Model:

```<code>public function posts(){
    return $this->belongsToMany("App\Post");
}
</code>```

To get only those posts that a single user has created, try this in your controller (uses eager loading to limit the database queries):

```<code> $user = \App\User::with('posts')->find($someInputUserId_orAuthUserId);

 $posts = $user->posts;
</code>```

Title: Show only posts that user has access

Body:
I assume you have the models set up correctly, something like this on the User Model:

public function posts(){
    return $this->belongsToMany("App\Post");
}

To get only those posts that a single user has created, try this in your controller (uses eager loading to limit the database queries):

 $user = \App\User::with('posts')->find($someInputUserId_orAuthUserId);

 $posts = $user->posts;


答:
First off, we have one plus one, and we're checking if that's equal to two (it is).

```<code>1 + 1 == 2
</code>```

Then we have a logical AND operator (&&) which checks if the statements on both sides of it are true. So far, the above is true, so processing continues.

Finally we are multiplying ten and ten (100) and checking if it's greater than 50 (it is).

```<code>10 * 10 > 50
</code>```

And finally the AND operator sees that both arguments are true, and gives our result:

console.log(1 + 1 == 2 && 10 * 10 > 50);```

Title: Explanation for logical operators example in Eloquent JS

Body:
First off, we have one plus one, and we're checking if that's equal to two (it is).

1 + 1 == 2

Then we have a logical AND operator (&&) which checks if the statements on both sides of it are true. So far, the above is true, so processing continues.

Finally we are multiplying ten and ten (100) and checking if it's greater than 50 (it is).

10 * 10 > 50

And finally the AND operator sees that both arguments are true, and gives our result:

console.log(1 + 1 == 2 && 10 * 10 > 50);


问:
How to redirect http:// to https:// like firebase hosting
Firebase hosting already had https:// redirects, in the firebase.json. I have an Angular app, and to prepare for SSR, I migrated from firebase hosting to Cloud Run. At first I didn't know whether I was supposed to mess with Angular Universal or something to do this, I seen a similar question on here but it was answered with Nginx, which is not what I need.

I tried to do really dumb things with the server.ts file and that was not the answer at all. I honestly do not know exactly where to start. I have scoured google for the answer, including of google cloud run docs here:

https://cloud.google.com/run/docs/authenticating/public

but I have no idea where to go from here.

答:
If you are happy with Firebase hosting, you can keep using it together with Cloud Run: https://firebase.google.com/docs/hosting/cloud-run

This lets you keep the nice features of Firebase hosting, like forcing HTTPS, rewriting URLs, and pointing some URLs to static content.


问:
RTMP Stream Input to an OpenTok session
So I've created a streaming app in my community website using OpenTok.  It's really great, but there are a few use cases where some of my community currently stream via YouTube and have a setup that uses RTMP.  They don't necessarily want to use YouTube, but have invested in hardware and software that streams using RTMP.  Is there a way to set OpenTok up so that it can take RTPM as an input and convert it to a Stream?

(I know that OpenTok can broadcast to RTMP - I'm not interested in output - I need RTMP as an input)

答:
Tokbox developer here

There is no REST API call to do this. You would have to do it programatically, as follows:

You can pipe a RTMP receiver with the Linux SDK (beta) or one of the officials SDK (ios, android, windows), using the custom audio and video capturer.

The idea is the following:
---> RTMP Stream --> [ RTMP receiver & media decoder ] --> Raw media -->
[ ios/android/windows/linux SDK ] --> [ Opentok ]

If you want to get the linux SDK, please email support@tokbox.com

Title: RTMP Stream Input to an OpenTok session


问:
How to insert a new element under another with xmlstarlet?
```<code>$ vim test.xml

<?xml version="1.0" encoding="UTF-8" ?>
<config>
</config>
$ xmlstarlet ed -i "/config" -t elem -n "sub" -v "" test.xml
<?xml version="1.0" encoding="UTF-8"?>
<sub></sub>
<config>
</config>
</code>```

But I wanted sub to be a child of config. How should I change the xpath parameter of -i?

BONUS:
Is it possible to insert the child directly with an attribute and even have it set to a value?
Something like:

```<code>$ xmlstarlet ed -i "/config" -t elem -n "sub" -v ""  -a attr -n "class" -v "com.foo" test.xml
</code>```

答: The example did not work until I wrapped <GlobalNamingResources> into a <Server> element.

Body:
$ vim test.xml

<?xml version="1.0" encoding="UTF-8" ?>
<config>
</config>
$ xmlstarlet ed -i "/config" -t elem -n "sub" -v "" test.xml
<?xml version="1.0" encoding="UTF-8"?>

<config>
</config>

But I wanted sub to be a child of config. How should I change the xpath parameter of -i?

BONUS:
Is it possible to insert the child directly with an attribute and even have it set to a value?
Something like:

$ xmlstarlet ed -i "/config" -t elem -n "sub" -v ""  -a attr -n "class" -v "com.foo" test.xml


问:
Java get a group of user names
I've coded a program where there is like 5 people "killing" a monster, and i need a piece of code to get all of the members "nickname" (getName() ) and display them with a coma beetwen, how could I do that?

I guess I could do a for loop but ye, not sure how to add the comas beetwen then..

答:
http://snippets.dzone.com/posts/show/91

Or if you can use Google Guava (highly recommended as a tool in your belt anyway):

```<code>String nickname = Joiner.on(",").join(listOfMembers);
</code>```

Title: Java get a group of user names

Body:
http://snippets.dzone.com/posts/show/91

Or if you can use Google Guava (highly recommended as a tool in your belt anyway):

String nickname = Joiner.on(",").join(listOfMembers);


问:
Pass data through two activities using interface
I have to pass a lot of data from 'Activity 1' to a 'Activity 2'. This data is condensed on a POJO with a lot of subclass on itself.

So, I figured I need to pass this data with an interface, this because I need use previous data to call a web service. But at the moment of reach the web service, the data is null.

Actually this is my code, but is not working:

```<code>public class FirstActivity extends AppCompatActivity {
  protected void onCreate(Bundle savedInstanceState) {
      ....
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
        case R.id.continue_button:
            continueToNewScreen();
            break;
    }
  }

  private void continueToNewScreen() {
    if (infoResult != null && infoResult.size() > 0) {
        eventsListener = new SecondActivity();
        eventsListener.callback(myObjectToSend);
        //send data to the next activity and start it.
        Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
        startActivity(intent);
    }
  }
}

public class SecondActivity extends AppCompatActivity implements EventsListener {
      protected void onCreate(Bundle savedInstanceState) {
          configurateView();
          manageEvent();
      }

    @Override
    public void callback(InfoEvent event) {
        Log.d("callback", "callback: ");
        //here the object is informed
        infoEvent = event;

    }

  private void manageEvent() {
    //call web service with the info from the last activity
    //here the object is null
  }
}
</code>```

答:
You need to use intent putExtra() method and Serializable or Parcelable in order to send some data from one activity to another.
Actually in your case you must make your myObjectToSend class to implements Serializable or Parcelable and then pass it with help of putExtra() method.

In FirstActivity:

```<code>intent.putExtra("KEY", myObjectToSend);
</code>```

which KEY can be a constant for getting this object in SecondActivity.

In SecondActivity onCreate() method:

```<code>if (savedInstanceState == null) {
    Bundle extras = getIntent().getExtras();
    if(extras == null) {
        yourObjectToReceive = null;
    } else {
        yourObjectToReceive = (YourObjectToReceiveClass) extras.getSerializable("KEY");
    }
} else {
    yourObjectToReceive = (YourObjectToReceiveClass)savedInstanceState.getSerializable("KEY");
}
</code>```

Body:
I have to pass a lot of data from 'Activity 1' to a 'Activity 2'. This data is condensed on a POJO with a lot of subclass on itself.

So, I figured I need to pass this data with an interface, this because I need use previous data to call a web service. But at the moment of reach the web service, the data is null.

Actually this is my code, but is not working:

public class FirstActivity extends AppCompatActivity {
  protected void onCreate(Bundle savedInstanceState) {
      ....
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
        case R.id.continue_button:
            continueToNewScreen();
            break;
    }
  }

  private void continueToNewScreen() {
    if (infoResult != null && infoResult.size() > 0) {
        eventsListener = new SecondActivity();
        eventsListener.callback(myObjectToSend);
        //send data to the next activity and start it.
        Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
        startActivity(intent);
    }
  }
}

public class SecondActivity extends AppCompatActivity implements EventsListener {
      protected void onCreate(Bundle savedInstanceState) {
          configurateView();
          manageEvent();
      }

    @Override
    public void callback(InfoEvent event) {
        Log.d("callback", "callback: ");
        //here the object is informed
        infoEvent = event;

    }

  private void manageEvent() {
    //call web service with the info from the last activity
    //here the object is null
  }
}

Body:
You need to use intent putExtra() method and Serializable or Parcelable in order to send some data from one activity to another.
Actually in your case you must make your myObjectToSend class to implements Serializable or Parcelable and then pass it with help of putExtra() method.

In FirstActivity:

intent.putExtra("KEY", myObjectToSend);

which KEY can be a constant for getting this object in SecondActivity.

In SecondActivity onCreate() method:

if (savedInstanceState == null) {
    Bundle extras = getIntent().getExtras();
    if(extras == null) {
        yourObjectToReceive = null;
    } else {
        yourObjectToReceive = (YourObjectToReceiveClass) extras.getSerializable("KEY");
    }
} else {
    yourObjectToReceive = (YourObjectToReceiveClass)savedInstanceState.getSerializable("KEY");
}


问:
How to get all elements in nested collection with streams
I have a class which contains different nested collections, now I want to receive all the elements of the nested collections, concrete I want to collect all the StrokePoints of the collections. I can solve it with "old" java but how to do it with streams?

```<code>    int strokesCounter = 0;
    List<StrokePoint> pointList = new ArrayList<>();
    if (!strokesData.getListOfSessions().isEmpty()) {
        for (SessionStrokes session : strokesData.getListOfSessions()) {
            List<Strokes> strokes = session.getListOfStrokes();
            for (Strokes stroke : strokes) {
                strokesCounter++;
                List<StrokePoint> points = stroke.getListOfStrokePoints();
                pointList.addAll(stroke.getListOfStrokePoints());
            }
        }
    }
</code>```

I am looking for a way to fill the pointList with the stream functionality.

答:
Flattening the nested data is pretty simple:

```<code>List<StrokePoint> pointList = strokesData.getListOfSessions()
        .streams()
        .map(SessionStrokes::getListOfStrokes)
        .flatMap(List::stream)
        .map(Strokes::getListOfStrokePoints)
        .flatMap(List::stream)
        .collect(Collectors.toList());
</code>```

Collecting the stroke count along the way is more tricky, and somewhat controversial. You could create a

```<code>AtomicInteger strokesCounter = new AtomicInteger();
</code>```

and increment it just after the first flatMap:

```<code>.peek(strokesCounter::incrementAndGet)
</code>```

Body:
I have a class which contains different nested collections, now I want to receive all the elements of the nested collections, concrete I want to collect all the StrokePoints of the collections. I can solve it with "old" java but how to do it with streams?

    int strokesCounter = 0;
    List<StrokePoint> pointList = new ArrayList<>();
    if (!strokesData.getListOfSessions().isEmpty()) {
        for (SessionStrokes session : strokesData.getListOfSessions()) {
            List<Strokes> strokes = session.getListOfStrokes();
            for (Strokes stroke : strokes) {
                strokesCounter++;
                List<StrokePoint> points = stroke.getListOfStrokePoints();
                pointList.addAll(stroke.getListOfStrokePoints());
            }
        }
    }

I am looking for a way to fill the pointList with the stream functionality.

Body:
Flattening the nested data is pretty simple:

List<StrokePoint> pointList = strokesData.getListOfSessions()
        .streams()
        .map(SessionStrokes::getListOfStrokes)
        .flatMap(List::stream)
        .map(Strokes::getListOfStrokePoints)
        .flatMap(List::stream)
        .collect(Collectors.toList());

Collecting the stroke count along the way is more tricky, and somewhat controversial. You could create a

AtomicInteger strokesCounter = new AtomicInteger();

and increment it just after the first flatMap:

.peek(strokesCounter::incrementAndGet)


问:
Best practice to avoid N+1 when listing objects retrieved by a method in an associated object
I'm trying to figure the best way to fix a N+1 problem in my rails app.

Let's say I have a model Student, which has a many association of terms.

```<code>student = Student.find_by_name('John')
student.terms
# [{term: 1}, {term: 2}, {term: 3}]
</code>```

So, I need to be able to show the list of student terms but also need to show the previous term in the same view. Currently, for this I have a method that gets the previous term by the attribute start_at which is a DateTime value equivalent to the first  day of the term.

```<code># Term.rb
def previous_term
  Term.where("start_at < ?", start_at).order(start_at: :desc).first&.start_at
end
</code>```

But using this method in the terms list makes a query for each term for each Student

```<code>- @terms.each do |term|
  %td= term.start_at # list current term start_at
  %td= term.previous_term # show previous term start_at - N+1 is here
</code>```

I've thought about loading all student terms in the controller and creating a class method in model Term, this method would detect the previous Term from a ordered collection of Terms.

```<code># Term.rb
def self.get_previous(term_collection, term_id)
  term_collection.detect do |term|
    # logic to filter and get the previous term
  end
end
</code>```

This way it would be filtering the objects in memory instead of making database connections, buuuuut I know there is a better and smarter way to do it (maybe best practice?).

答:
From your ordered terms student.terms.order(start_at: :desc), you can create a ruby array loop with index in your view

```<code>- @terms.each_with_index do |term, index|
  %td= term.start_at
  - if index > 0
    %td= @terms[0..index-1].pluck(:name)
</code>```

Hope this can help

Body:
I'm trying to figure the best way to fix a N+1 problem in my rails app.

Let's say I have a model Student, which has a many association of terms.

student = Student.find_by_name('John')
student.terms
# [{term: 1}, {term: 2}, {term: 3}]

So, I need to be able to show the list of student terms but also need to show the previous term in the same view. Currently, for this I have a method that gets the previous term by the attribute start_at which is a DateTime value equivalent to the first  day of the term.

# Term.rb
def previous_term
  Term.where("start_at < ?", start_at).order(start_at: :desc).first&.start_at
end

But using this method in the terms list makes a query for each term for each Student

- @terms.each do |term|
  %td= term.start_at # list current term start_at
  %td= term.previous_term # show previous term start_at - N+1 is here

I've thought about loading all student terms in the controller and creating a class method in model Term, this method would detect the previous Term from a ordered collection of Terms.

# Term.rb
def self.get_previous(term_collection, term_id)
  term_collection.detect do |term|
    # logic to filter and get the previous term
  end
end

This way it would be filtering the objects in memory instead of making database connections, buuuuut I know there is a better and smarter way to do it (maybe best practice?).

Body:
From your ordered terms student.terms.order(start_at: :desc), you can create a ruby array loop with index in your view

- @terms.each_with_index do |term, index|
  %td= term.start_at
  - if index > 0
    %td= @terms[0..index-1].pluck(:name)

Hope this can help


答:
You can just use Stream.flatMap() twice:

```<code>List<StrokePoint> pointList = strokesData.getListOfSessions().stream()
        .flatMap(session -> session.getListOfStrokes().stream())
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());
</code>```

If you need to count the strokes list you can split this into two parts and use List.size():

```<code>List<Strokes> strokesList = strokesData.getListOfSessions().stream()
        .flatMap(session -> session.getListOfStrokes().stream())
        .collect(Collectors.toList());
int strokesCounter = strokesList.size();
List<StrokePoint> pointList = strokesList.stream()
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());
</code>```

Alternatively you can increment an AtomicInteger in flatMap():

```<code>final AtomicInteger strokesCounter = new AtomicInteger();
List<StrokePoint> pointList = strokesData.getListOfSessions().stream()
        .flatMap(session -> {
            List<Strokes> strokes = session.getListOfStrokes();
            strokesCounter.addAndGet(strokes.size());
            return strokes.stream();
        })
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());
</code>```

Or with peek():

```<code>final AtomicInteger strokesCounter = new AtomicInteger();
List<StrokePoint> pointList = strokesData.getListOfSessions().stream()
        .flatMap(session -> session.getListOfStrokes().stream())
        .peek(i -> strokesCounter.incrementAndGet())
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());
</code>```

Title: How to get all elements in nested collection with streams

Body:
You can just use Stream.flatMap() twice:

List<StrokePoint> pointList = strokesData.getListOfSessions().stream()
        .flatMap(session -> session.getListOfStrokes().stream())
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());

If you need to count the strokes list you can split this into two parts and use List.size():

List<Strokes> strokesList = strokesData.getListOfSessions().stream()
        .flatMap(session -> session.getListOfStrokes().stream())
        .collect(Collectors.toList());
int strokesCounter = strokesList.size();
List<StrokePoint> pointList = strokesList.stream()
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());

Alternatively you can increment an AtomicInteger in flatMap():

final AtomicInteger strokesCounter = new AtomicInteger();
List<StrokePoint> pointList = strokesData.getListOfSessions().stream()
        .flatMap(session -> {
            List<Strokes> strokes = session.getListOfStrokes();
            strokesCounter.addAndGet(strokes.size());
            return strokes.stream();
        })
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());

Or with peek():

final AtomicInteger strokesCounter = new AtomicInteger();
List<StrokePoint> pointList = strokesData.getListOfSessions().stream()
        .flatMap(session -> session.getListOfStrokes().stream())
        .peek(i -> strokesCounter.incrementAndGet())
        .flatMap(strokes -> strokes.getListOfStrokePoints().stream())
        .collect(Collectors.toList());


问:
Collapse div element based on screen size
I was just wondering how, based on screen size, could you use bootstraps accordion, so for example lets say i have a div I want to display regularly on everything but when in mobile view I want it to collapse.

Any suggestions?

答:
In Bootstrap-4 things are much easier:

```<code><div className="container-fluid text-center d-none d-lg-block">
      <div className="row">
        <div className="mx-auto col-lg-2">
          <p className="text-uppercase">products</p>
        </div>
      </div>
    </div>
</code>```

We will see "PRODUCTS" on the screen only in large screen and it will be centered(text-center) and will take up only 2 columns wide

Body:
In Bootstrap-4 things are much easier:

<div className="container-fluid text-center d-none d-lg-block">
      <div className="row">
        <div className="mx-auto col-lg-2">
          <p className="text-uppercase">products</p>
        </div>
      </div>
    </div>

We will see "PRODUCTS" on the screen only in large screen and it will be centered(text-center) and will take up only 2 columns wide


问:
How to Hide Code cells When converting a Jupyter Notebook into Sphinx Doc using nbsphinx
I'm new to Sphinx documentation, and I am trying to convert a Jupyter Notebook into Sphinx docs using Nbsphinx. Especially, I want to hide the code cells (not their outputs), but I could not make it using templates that I found for Jupyter Nbconvert.

I expect the outputs from converted notebook on the Sphinx documentation, but no input.

答:
I added the following code to the first cell and it works well.</p>

```<code>import IPython.core.display as di # Example: di.display_html('<h3>%s:</h3>' % str, raw=True)
di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)'
</code>```

Body:
I added the following code to the first cell and it works well.

import IPython.core.display as di # Example: di.display_html('<h3>%s:</h3>' % str, raw=True)
di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)'


问:
Modbus TCP/IP to BACnet
Firstly I am new to this and I have tried googling for answer but figured it is best ask the experts.

There is a building management system (BMS) that is using BACnet protocol but my equipment logger only has Modbus TCP/IP. I understand that the market has a converter for this but I will like to know the concept.

Modbus TCP/IP has registry values (e.g 40135) which is dedicated to a specific parameter reading. How does the converter read this registry value in the BACnet BMS? Do you have to specific this registry value in the converter software for the output at BACnet?

In general, what should be input at the BACnet end to read the equipment parameter such as power received?

In this situation, is the BACnet BMS consider the MASTER and the equipment as SLAVE?

I hope someone can take some time to clear my doubts on this. Will really appreciate it.

Thank you.

答:
Just to add to what's already been said; a lot of the time - out in the field, there are gateway devices, that encompass the conversion process for you, so unless you're the one setting-up the BMS, you generally don't have to concern yourself with the conversion specifics.

If the device's 'Max(imum) ADPU Length' is set to 480, then the device is probably a Modbus device (/a Modbus device is probably sitting behind the gateway's/converter's (object) point).

Title: Modbus TCP/IP to BACnet


问:
How to get intellij to offer a text diff comparison on failed tests
I'm writing a Scala test with some ScalaTest matchers.

When my test fails, intellij says something like

```<code>{"count":3,"pagination":{"offset":0,"limit":100},"content":{"uri":"http://locahost.com/catalogue/content?order=Query&id=18,20,19"},"list":[{"id":"18","position":27},{"id":"20","position":341},{"id":"19","position":33}]} was not equal to {"count":3,"pagination":{"offset":0,"limit":100},"content":{"uri":"http://locahost.com/catalogue/content?order=Query&id=18,20,19"},"list":[{"id":"18","timestamp":"2015-01-28T11:55:44.494Z","content":"Episode","position":27},{"id":"20","timestamp":"2015-01-19T11:55:44.494Z","content":"Program","position":341},{"id":"19","timestamp":"2015-01-17T11:55:44.494Z","content":"Episode","position":33}]}
org.scalatest.exceptions.TestFailedException: {"count":3,"pagination":{"offset":0,"limit":100},"content":{"uri":"http://locahost.com/catalogue/content?order=Query&id=18,20,19"},"list":[{"id":"18","position":27},{"id":"20","position":341},{"id":"19","position":33}]} was not equal to {"count":3,"pagination":{"offset":0,"limit":100},"content":{"uri":"http://locahost.com/catalogue/content?order=Query&id=18,20,19"},"list":[{"id":"18","timestamp":"2015-01-28T11:55:44.494Z","content":"Episode","position":27},{"id":"20","timestamp":"2015-01-19T11:55:44.494Z","content":"Program","position":341},{"id":"19","timestamp":"2015-01-17T11:55:44.494Z","content":"Episode","position":33}]}
at    org.scalatest.MatchersHelper$.newTestFailedException(MatchersHelper.scala:160)
at org.scalatest.Matchers$ShouldMethodHelper$.shouldMatcher(Matchers.scala:6231)
at org.scalatest.Matchers$AnyShouldWrapper.should(Matchers.scala:6265)
...
</code>```

However, intellij does not give me the handy see difference in the text feature.

I thought it might be because I'm comparing 2 objects

```<code>  val responseBody = responseAs[JsValue]
  responseBody should be(viewingByAccountIdResponseJson)
</code>```

but changing it to

```<code>assert(responseBody.toString() === viewingByAccountIdResponseJson.toString())
</code>```

Does not allow me to do a text comparison either.

Is there any way to configure intellij to do this?

(I'm currently using a FlatSpec with Matchers)

Note: This is related to this question
Formatting output so that Intellij Idea shows diffs for two texts

However, even using the syntax recommended that intellij might pick up, it does not work.

答:
As intellij feature request mentioned by Bruce celebrates it's 7th birthday, some of us have lost their hope (still don't forget to +1 it). Here's an ugly script which allows you to mitigate the issue a bit. Just copy This was not equal to That line and feed it to the stdin of this script:

```<code>| scalatest-diff
</code>```

```<code>cat > ~/bin/scalatest-diff
#!/usr/bin/perl

my $in = join("", <STDIN>);
if( $in =~ m/[^:]+\: (.+?) was not equal to (.+)/so ) {
    my $this = $1;
    my $that = $2;
    $this =~ s/,/,\n/g;
    $that =~ s/,/,\n/g;
    open(thisFile, ">", "/tmp/this");
    open(thatFile, ">", "/tmp/that");
    print thisFile $this; close thisFile;
    print thatFile $that; close thatFile;
    exec("vimdiff /tmp/this /tmp/that");
}
<Ctrl-D>
chmod a+x ~/bin/scalatest-diff
</code>```

P.S. feel free to change vimdiff to your favorite differ.

Body:
I'm writing a Scala test with some ScalaTest matchers.

When my test fails, intellij says something like

{"count":3,"pagination":{"offset":0,"limit":100},"content":{"uri":"http://locahost.com/catalogue/content?order=Query&id=18,20,19"},"list":[{"id":"18","position":27},{"id":"20","position":341},{"id":"19","position":33}]} was not equal to {"count":3,"pagination":{"offset":0,"limit":100},"content":{"uri":"http://locahost.com/catalogue/content?order=Query&id=18,20,19"},"list":[{"id":"18","timestamp":"2015-01-28T11:55:44.494Z","content":"Episode","position":27},{"id":"20","timestamp":"2015-01-19T11:55:44.494Z","content":"Program","position":341},{"id":"19","timestamp":"2015-01-17T11:55:44.494Z","content":"Episode","position":33}]}
org.scalatest.exceptions.TestFailedException: {"count":3,"pagination":{"offset":0,"limit":100},"content":{"uri":"http://locahost.com/catalogue/content?order=Query&id=18,20,19"},"list":[{"id":"18","position":27},{"id":"20","position":341},{"id":"19","position":33}]} was not equal to {"count":3,"pagination":{"offset":0,"limit":100},"content":{"uri":"http://locahost.com/catalogue/content?order=Query&id=18,20,19"},"list":[{"id":"18","timestamp":"2015-01-28T11:55:44.494Z","content":"Episode","position":27},{"id":"20","timestamp":"2015-01-19T11:55:44.494Z","content":"Program","position":341},{"id":"19","timestamp":"2015-01-17T11:55:44.494Z","content":"Episode","position":33}]}
at    org.scalatest.MatchersHelper$.newTestFailedException(MatchersHelper.scala:160)
at org.scalatest.Matchers$ShouldMethodHelper$.shouldMatcher(Matchers.scala:6231)
at org.scalatest.Matchers$AnyShouldWrapper.should(Matchers.scala:6265)
...

However, intellij does not give me the handy see difference in the text feature.

I thought it might be because I'm comparing 2 objects

  val responseBody = responseAs[JsValue]
  responseBody should be(viewingByAccountIdResponseJson)

but changing it to

assert(responseBody.toString() === viewingByAccountIdResponseJson.toString())

Does not allow me to do a text comparison either.

Is there any way to configure intellij to do this?

(I'm currently using a FlatSpec with Matchers)

Note: This is related to this question
Formatting output so that Intellij Idea shows diffs for two texts

However, even using the syntax recommended that intellij might pick up, it does not work.

Body:
As intellij feature request mentioned by Bruce celebrates it's 7th birthday, some of us have lost their hope (still don't forget to +1 it). Here's an ugly script which allows you to mitigate the issue a bit. Just copy This was not equal to That line and feed it to the stdin of this script:

| scalatest-diff

cat > ~/bin/scalatest-diff
#!/usr/bin/perl

my $in = join("", <STDIN>);
if( $in =~ m/[^:]+\: (.+?) was not equal to (.+)/so ) {
    my $this = $1;
    my $that = $2;
    $this =~ s/,/,\n/g;
    $that =~ s/,/,\n/g;
    open(thisFile, ">", "/tmp/this");
    open(thatFile, ">", "/tmp/that");
    print thisFile $this; close thisFile;
    print thatFile $that; close thatFile;
    exec("vimdiff /tmp/this /tmp/that");
}
<Ctrl-D>
chmod a+x ~/bin/scalatest-diff

P.S. feel free to change vimdiff to your favorite differ.


问:
Get list of all loaded python packages & versions, and variables
I'm coming from an R background where it was quite easy to figure out for me all of the loaded packages that I was using.  I could look to my rstudio tab 'packages' and see checkmarks next to package names and versions for what I had loaded / available.

I could run:

```<code>library(dplyr)
x=3;
y=4;
</code>```

then run to find out the packages I had loaded('dplyr):
 sessionInfo()
and to find out which variables were in my environment if I didn't want to look at the loaded variable pain (x, y)

```<code>ls()
</code>```

I'm trying to figure out a way to do this in python.  For example, is there a command that will:

Show me everything available python package I can import & corresponding versions?

Show me the packages I have already loaded thus far in my session and their corresponding versions?

Show me all my defined variables that I have made and their type (such as pandas data frames, lists, dictionaries, functions, etc)

I'm sure this is pretty easy, but I can't seem to find how to do this coming from R where it was very simple.

答:
1. Not possible in general. Import statements are handled dynamically at the time the line is executed, and so the result depends on whatever is lying around on your filesystem at that time.

You can get a decent idea of what's available by looking in the site-packages dir, the location of which is platform dependent but can be found with the code snippet below:

```<code>>>> import sysconfig
>>> sysconfig.get_path("purelib")
'/usr/local/lib/python3.7/site-packages'
</code>```

The standard library is always available. A comprehensive list of stdlib modules is in the library docs here: https://docs.python.org/3/library/

There is a helper function in pkgutil.walk_packages() which will essentially walks the sys path and looks for accessible modules.  I believe pydoc's help("modules") listed in the other answer actually uses this helper internally.

pip freeze will show distributions installed in a virtual environment.

2. Just look in sys.modules. A version number for a module is not required, and might not even exist, but a common convention is for the top-level module to have a __version__ attribute.

3. This is built-in function vars. Just call vars() with no arguments, it will return a mapping of names and objects. The types of the objects you will just have to see with type(obj).

Body:
I'm coming from an R background where it was quite easy to figure out for me all of the loaded packages that I was using.  I could look to my rstudio tab 'packages' and see checkmarks next to package names and versions for what I had loaded / available.

I could run:

library(dplyr)
x=3;
y=4;

then run to find out the packages I had loaded('dplyr):
 sessionInfo()
and to find out which variables were in my environment if I didn't want to look at the loaded variable pain (x, y)

ls()

I'm trying to figure out a way to do this in python.  For example, is there a command that will:

Show me everything available python package I can import & corresponding versions?

Show me the packages I have already loaded thus far in my session and their corresponding versions?

Show me all my defined variables that I have made and their type (such as pandas data frames, lists, dictionaries, functions, etc)

I'm sure this is pretty easy, but I can't seem to find how to do this coming from R where it was very simple.

Body:
1. Not possible in general. Import statements are handled dynamically at the time the line is executed, and so the result depends on whatever is lying around on your filesystem at that time.

You can get a decent idea of what's available by looking in the site-packages dir, the location of which is platform dependent but can be found with the code snippet below:

>>> import sysconfig
>>> sysconfig.get_path("purelib")
'/usr/local/lib/python3.7/site-packages'

The standard library is always available. A comprehensive list of stdlib modules is in the library docs here: https://docs.python.org/3/library/

There is a helper function in pkgutil.walk_packages() which will essentially walks the sys path and looks for accessible modules.  I believe pydoc's help("modules") listed in the other answer actually uses this helper internally.

pip freeze will show distributions installed in a virtual environment.

2. Just look in sys.modules. A version number for a module is not required, and might not even exist, but a common convention is for the top-level module to have a __version__ attribute.

3. This is built-in function vars. Just call vars() with no arguments, it will return a mapping of names and objects. The types of the objects you will just have to see with type(obj).


问:
How to bind css class in vue js template within a v-for loop?
How do I name my td class the name of the step in this example?

```<code><td v-for="steps in item.steps" v:bind:class="item.steps.name">
 {{ item.steps.name }}
</td>
</code>```

In this example, my class gets literally named items.steps.name rather than the return value.  Everything else works.

答:
That's cause you are looping over item.steps with each iteration named steps and you use the variable you are looping over in the class-binding.

Try steps.name instead.

Body:
How do I name my td class the name of the step in this example?

 {{ item.steps.name }}

In this example, my class gets literally named items.steps.name rather than the return value.  Everything else works.


问:
Is it possible to include a C# variable in a string variable without using a concatenator?
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

```<code>DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);
</code>```

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

```<code>string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>
    <html>
    <head>
        <title>$title</title>
    </head>
    <body>
    <div>Hello StackO</div>
    <div>The date is $date</div>
    </body>
    </html>
    ";

}
</code>```

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.

答: The short and simple answer is: No!</p>

Body:
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>

        <title>$title</title>

Hello StackO

The date is $date

    ";

}

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.

Body: The short and simple answer is: No!


问:
getting the total count of search results in wordpress
How to get the total count of results, in the search results page in wordpress ... i think my question is clear .i need the total number of search results that displayed in  the search results page .And also need to find the count of results from page and post separately

what i have tried is

```<code>    <?php echo count($posts); ?>
</code>```

by using this i got the total number of search results . but i also need the count of pages and posts in the search results

答:
Once you are already in a search query, you can as well use the global $wp_query.

See example below:

```<code><?php
   global $wp_query;
   $not_singular = $wp_query->found_posts > 1 ? 'results' : 'result'; // if found posts is greater than one echo results(plural) else echo result (singular)
   echo $wp_query->found_posts . " $not_singular found";
?>
</code>```

Body:
How to get the total count of results, in the search results page in wordpress ... i think my question is clear .i need the total number of search results that displayed in  the search results page .And also need to find the count of results from page and post separately

what i have tried is

    <?php echo count($posts); ?>

by using this i got the total number of search results . but i also need the count of pages and posts in the search results

Body:
Once you are already in a search query, you can as well use the global $wp_query.

See example below:

<?php
   global $wp_query;
   $not_singular = $wp_query->found_posts > 1 ? 'results' : 'result'; // if found posts is greater than one echo results(plural) else echo result (singular)
   echo $wp_query->found_posts . " $not_singular found";
?>


问:
INVALID_REQUEST when I'm using page_token
I try to capture the info in a list on r when I'm using page_token in google_places

In general the short code is functional, but I can see in google.maps 65 results, and my code just return me 60 results.

```<code>key_word = 'McDonalds Bogota'
res <- google_places(search_string = key_word)
  info <- list(res)
  while (res$status == 'OK') {
    Sys.sleep(1.5)
    res <- google_places(search_string = '',
                         page_token = res$next_page_token)
    info <- c(info,list(res))
  }
</code>```

I obtain a list with complete information in info[[1]], info[[2]] and info[[3]], but when I see info[[4]] I get status INVALID_REQUEST, so I want to see the final 5 observations in info[[4]] but I could not to do this

答:
info[[3]] does not have a $next_page_token since the number of results caps at 60. So the following loop for info[[4]] will not have a valid token to request more results.

next_page_token contains a token that can be used to return up to 20
  additional results. A next_page_token will not be returned if there
  are no additional results to display. The maximum number of results
  that can be returned is 60.

https://developers.google.com/places/web-service/search

Body:
I try to capture the info in a list on r when I'm using page_token in google_places

In general the short code is functional, but I can see in google.maps 65 results, and my code just return me 60 results.

key_word = 'McDonalds Bogota'
res <- google_places(search_string = key_word)
  info <- list(res)
  while (res$status == 'OK') {
    Sys.sleep(1.5)
    res <- google_places(search_string = '',
                         page_token = res$next_page_token)
    info <- c(info,list(res))
  }

I obtain a list with complete information in info[[1]], info[[2]] and info[[3]], but when I see info[[4]] I get status INVALID_REQUEST, so I want to see the final 5 observations in info[[4]] but I could not to do this


问:
How can a scrollbar be included in a legend?
It would be nice to see more than 18 lines of a legend.

Wrapping the output in a wellPanel( style = 'overflow-y:scroll;' ) appears like it would be the correct function, but did not work.

```<code>library(shiny)

shinyApp(
  ui     <- fluidPage(
    splitLayout(cellWidths = c('20%', '30%', '50%'),
      sliderInput('mySldr'  , value = 4   , min =  1 ,
               label = 'how many groups ?', max = 44 ),     # max 52 > 44
      plotOutput( 'myLgnd' ),
      plotOutput( 'myPlt'  )
     )
   ),
  server          <- function(input, output, session) {
    n             <- reactive({   input$mySldr                       })
    theD          <- reactive({ matrix(runif( 5*n() ), nrow = 5,
                  dimnames = (list( 1:5, rep(letters,2)[ 1:n() ] ))) })
    output$myLgnd <- renderPlot({
                  legend(  x = 'center',   legend = colnames( theD() ),
                                             fill = rainbow( n() ) ) })
    output$myPlt  <- renderPlot({
          matplot( x = c(2001:2005), type = 'o', xlab = '', ylab = '',
                           y = theD()      , col  = rainbow( n() ) ) })
   }
 )
</code>```

Any help towards a scrollable legend would be appreciated.  Thank you.

答:
Not very robust but this works for your example:

```<code>            div(
              style = "overflow-y: auto; overflow-x: hidden",
              plotOutput( 'myLgnd' )
            ),
</code>```

and

```<code>output$myLgnd <- renderPlot({
  par(mar = c(0,0,0,0))
  legend(  x = 'center',   legend = colnames( theD() ),
           fill = rainbow( n() ) ) }, height = function(){170+10*ncol(theD())})
</code>```

I've found the values 170 and 10 after many trials-errors. Maybe there are better values.

It would be better to do the graphic with plotly.

Body:
It would be nice to see more than 18 lines of a legend.

Wrapping the output in a wellPanel( style = 'overflow-y:scroll;' ) appears like it would be the correct function, but did not work.

library(shiny)

shinyApp(
  ui     <- fluidPage(
    splitLayout(cellWidths = c('20%', '30%', '50%'),
      sliderInput('mySldr'  , value = 4   , min =  1 ,
               label = 'how many groups ?', max = 44 ),     # max 52 > 44
      plotOutput( 'myLgnd' ),
      plotOutput( 'myPlt'  )
     )
   ),
  server          <- function(input, output, session) {
    n             <- reactive({   input$mySldr                       })
    theD          <- reactive({ matrix(runif( 5*n() ), nrow = 5,
                  dimnames = (list( 1:5, rep(letters,2)[ 1:n() ] ))) })
    output$myLgnd <- renderPlot({
                  legend(  x = 'center',   legend = colnames( theD() ),
                                             fill = rainbow( n() ) ) })
    output$myPlt  <- renderPlot({
          matplot( x = c(2001:2005), type = 'o', xlab = '', ylab = '',
                           y = theD()      , col  = rainbow( n() ) ) })
   }
 )

Any help towards a scrollable legend would be appreciated.  Thank you.

Body:
Not very robust but this works for your example:

            div(
              style = "overflow-y: auto; overflow-x: hidden",
              plotOutput( 'myLgnd' )
            ),

and

output$myLgnd <- renderPlot({
  par(mar = c(0,0,0,0))
  legend(  x = 'center',   legend = colnames( theD() ),
           fill = rainbow( n() ) ) }, height = function(){170+10*ncol(theD())})

I've found the values 170 and 10 after many trials-errors. Maybe there are better values.

It would be better to do the graphic with plotly.


问:
laravel post data and redirect to the same post url without form submit
I need to post data to a payment service(payment.com), and redirect to payment.com(to fill credit card number etc.)

The traditional way to do it is like this:

<form id="form" action="payment.com" method="POST">
</form>

```

<blockquote>
  <p>But I want to do it through a <code>controller</code>, not submit by a form, so no
  data could be changed.</p>
</blockquote>

<hr>

<p>This is my controller method, and I've tried two ways:<code>redirect()</code> and <code>Guzzle</code></p>

<ol>
<li>I tried to <code>redirect()</code> to the url with post data, but I got <strong>"The GET method is not supported for this route. Supported methods: POST."</strong></li>
</ol>

<pre class="lang-php prettyprint-override"><code>public function postToPaymentServer(Request $request)
{
    $amount=$request['amount'];
    $payment=[
        'amount'=>$amount,
        'auth-id'=>config('auth-id')
    ];
    return redirect(url('api/payment/server'))->with(compact('payment'));
}
</code>```

ps. Here I made a local route to simulate the payment.com in routes/api.php

Route::post('payment/server','PaymentController@server');
```

<hr>

<ol start="2">
<li>I tried to use <code>Guzzle</code>, but it <strong>wouldn't redirect to the post url</strong>.</li>
</ol>

<pre class="lang-php prettyprint-override"><code>public function postToPaymentServer(Request $request)
{
    $amount=$request['amount'];
    $payment=[
        'amount'=>$amount,
        'auth-id'=>config('auth-id')
    ];
    $client = new Client();
    $response = $client->post('payment.com',[
        'body'=>[
            'payment'=>$payment,
            'allow_redirects' => true
        ],
    ]);
    return $response;
}
</code>```

Any suggestions would be greatly appreciated!

答:
You need to retrieve last location from redirect history and redirect to this location.

Look at the track_redirects option:

```<code>use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'http://payment.com',
    [
        RequestOptions::ALLOW_REDIRECTS => [
            'max' => 5,
            'track_redirects' => true,
        ],
        RequestOptions::FORM_PARAMS => [
            'payment' => $payment,
        ],
    ]
);

$lastLocation = end($response->getHeaders()['X-Guzzle-Redirect-History']);

return redirect($lastLocation);
</code>```

Body:
I need to post data to a payment service(payment.com), and redirect to payment.com(to fill credit card number etc.)

The traditional way to do it is like this:

<form id="form" action="payment.com" method="POST">
</form>

But I want to do it through a controller, not submit by a form, so no
  data could be changed.

This is my controller method, and I've tried two ways:redirect() and Guzzle

I tried to redirect() to the url with post data, but I got "The GET method is not supported for this route. Supported methods: POST."

public function postToPaymentServer(Request $request)
{
    $amount=$request['amount'];
    $payment=[
        'amount'=>$amount,
        'auth-id'=>config('auth-id')
    ];
    return redirect(url('api/payment/server'))->with(compact('payment'));
}

ps. Here I made a local route to simulate the payment.com in routes/api.php

Route::post('payment/server','PaymentController@server');

I tried to use Guzzle, but it wouldn't redirect to the post url.

public function postToPaymentServer(Request $request)
{
    $amount=$request['amount'];
    $payment=[
        'amount'=>$amount,
        'auth-id'=>config('auth-id')
    ];
    $client = new Client();
    $response = $client->post('payment.com',[
        'body'=>[
            'payment'=>$payment,
            'allow_redirects' => true
        ],
    ]);
    return $response;
}

Any suggestions would be greatly appreciated!

Body:
You need to retrieve last location from redirect history and redirect to this location.

Look at the track_redirects option:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'http://payment.com',
    [
        RequestOptions::ALLOW_REDIRECTS => [
            'max' => 5,
            'track_redirects' => true,
        ],
        RequestOptions::FORM_PARAMS => [
            'payment' => $payment,
        ],
    ]
);

$lastLocation = end($response->getHeaders()['X-Guzzle-Redirect-History']);

return redirect($lastLocation);