text:
Q: How do I unit test this promptui package written in golang? I am new to golang and I am using an interactive prompt called promptui (https://github.com/manifoldco/promptui) in a project of mine. I have written several unit tests for this project already but I am struggling with how I would unit test this particular package that requires an input.
For example, How would I go about testing the following lines of code (encapsulated in a function):
func setEmail() string {
  prompt := promptui.Prompt{Label: "Input your Email",
     Validate: emailValidations,
  }

  email, err := prompt.Run()
  if err != nil {
    color.red("failed getting email")
    os.exit(3)
  }
  return email
}

I think I need to somehow mock stdin but can't figure out the best way to do that within a test.

A: You should not try to test promptui as it is expected to be tested by its author.
What you can test:

*

*You send correct parameters when you create promptui.Prompt

*You use that promptui.Prompt in your code

*You properly handle promptui.Prompt results

As you can see, all these tests does not verify if promptui.Prompt works correctly inside.
Tests #2 and #3 could be combined. You need to run you code against mock and if you got correct result, you can believe that both #2 and #3 are correct.
Create mock:
type Runner interface {
    Run() (int, string, error)
}

type promptMock struct {
    // t is not required for this test, but it is would be helpful to assert input parameters if we have it in Run()
    t *testing.T
}

func (p promptMock) Run() (int, string, error) {
    // return expected result
    return 1, "", nil
}

You will need separate mock for testing error flow.
Update your code to inject mock:
func setEmail(runner Runner) string {
    email, err := runner.Run()
    if err != nil {
      color.red("failed getting email")
      os.exit(3)
    }
    return email
}

Now it is testable.
Create function that creates prompt:
func getRunner() promptui.Prompt {
  return promptui.Prompt{Label: "Input your Email",
     Validate: emailValidations,
  }
}

Write simple assert test to verify that we create correct structure.
The only not tested line will be setEmail(getRunner()) but it is trivial and can be covered by other types of tests.

A: For whatever reason, they don't export their stdin interface (https://github.com/manifoldco/promptui/blob/master/prompt.go#L49), so you can't mock it out, but you can directly mock os.Stdin and prefill it with whatever you need for testing. Though I agree with @Adrian, it has its own tests, so this shouldn't be necessary.
Extracted and refactored/simplified from source: Fill os.Stdin for function that reads from it
Refactored this way, it can be used for any function that reads from os.Stdin and expects a specific string.
Playground link: https://play.golang.org/p/rjgcGIaftBK
func TestSetEmail(t *testing.T) {
    if err := TestExpectedStdinFunc("email@test.com", setEmail); err != nil {
        t.Error(err)
        return
    }
    fmt.Println("success")
}

func TestExpectedStdinFunc(expected string, f func() string) error {
    content := []byte(expected)
    tmpfile, err := ioutil.TempFile("", "example")
    if err != nil {
        return err
    }

    defer os.Remove(tmpfile.Name()) // clean up

    if _, err := tmpfile.Write(content); err != nil {
        return err
    }

    if _, err := tmpfile.Seek(0, 0); err != nil {
        return err
    }

    oldStdin := os.Stdin
    defer func() { os.Stdin = oldStdin }() // Restore original Stdin

    os.Stdin = tmpfile
    actual := f()
    if actual != expected {
        return errors.New(fmt.Sprintf("test failed, exptected: %s actual: %s", expected, actual))
    }

    if err := tmpfile.Close(); err != nil {
        return err
    }
    return nil
}

A: promptui now has the Stdin property.
There is a fiddle here: https://play.golang.org/p/-mSgjY2kAw-
Here is our function that we will be testing:
func mock(p promptui.Prompt) string {
    p.Label = "[Y/N]"
    user_input, err := p.Run()
    if err != nil {
        fmt.Printf("Prompt failed %v\n", err)
    }

    return user_input
}

We need to create p, which will be an instance of promptui.Prompt and have a custom Stdin.
I got some help here - https://groups.google.com/g/golang-nuts/c/J-Y4LtdGNSw?pli=1 - in how to make a custom Stdin value, which simply has to conform to io.ReadCloser.
type ClosingBuffer struct {
    *bytes.Buffer
}

func (cb ClosingBuffer) Close() error {
    return nil
}

And then you use that as Stdin in the reader:
func TestMock(t *testing.T) {

    reader := ClosingBuffer{
        bytes.NewBufferString("N\n"),
    }

    p := promptui.Prompt{
        Stdin: reader,
    }

    response := mock(p)

    if !strings.EqualFold(response, "N") {
        t.Errorf("nope!")
    }
    //t.Errorf(response)
}

edit: The above doesn't work for multiple prompts within the same function, as discussed here with a solution: https://github.com/manifoldco/promptui/issues/63 - "promptui internally uses a buffer of 4096 bytes. This means that you must pad your buffer or promptui will raise EOF."
I took this pad() function from that exchange - https://github.com/sandokandias/capiroto/blob/master/cmd/capiroto/main.go:
func pad(siz int, buf *bytes.Buffer) {
    pu := make([]byte, 4096-siz)
    for i := 0; i < 4096-siz; i++ {
        pu[i] = 97
    }
    buf.Write(pu)
}

Then the test - - this solution uses ioutil.NopCloser rather than creating a new struct:
func TestMock(t *testing.T) {

    i1 := "N\n"
    i2 := "Y\n"

    b := bytes.NewBuffer([]byte(i1))
    pad(len(i1), b)
    reader := ioutil.NopCloser(
        b,
    )
    b.WriteString(i2)
    pad(len(i2), b)

    p := promptui.Prompt{
        Stdin: reader,
    }

    response := mock(p)

    if !strings.EqualFold(response, "NY") {
        t.Errorf("nope!")
        t.Errorf(response)
    }
}

and the function we are testing:
func mock(p promptui.Prompt) string {
    p.Label = "[Y/N]"
    user_input, err := p.Run()
    if err != nil {
        fmt.Printf("Prompt failed %v\n", err)
    }
    user_input2, err := p.Run()

    return user_input + user_input2
}

The fiddle for multiple prompts is here: https://play.golang.org/p/ElPysYq8aM1


text:
Q: Normed spaces and closed sets. I'm doing a research project for my mathematics class and i need your guys help. I'm almost done but I'm stuck on one proof that i need for the project. The question is as follows:
Let (R^p, ||.||) be a complete normed space. Prove that a closed subset A of R^p is complete.
If anyone could please assist me with this proof, I would greatly appreciate it.
thanks.

A: The key idea is a closed set contains all of its limit points.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magento 2 goes down with 50 concurrent request I am running magento 2 (using magento rest api services only) on aws t2 medium instance with ubuntu16.04, apache 2.4, php7, mysql 5.7.
When I use seige tool for load testing with 50 concurrent request to api. CPU goes up. And server get crash.
Not able to understand why this is happening.
Aws console shows higher mysql connections rate.
How I can handle this situation? Do I need to tune apache or magento2?

A: This is the normal behavior of Magento 2.
There are a couple of things you should do (if not already done) for running Magento in AWS. This answer only covers the infrastructure related issues. I expect that Magento 2 was set up correctly and optimized as described here.
To handle 50 or more users concurrently, you should set up the following resources:

*

*Use an Autoscaling Group

*Use at least an instance_type of m4.large for an "okay" performance

*Use Varnish

*Use Elasticache

*Use a Loadbalancer

Magento itself recommends a Setup that contains 4 Webserver nodes and at least 1 node for the database (source: Magento 2 Whitepaper).


text:
Q: Hacer un efecto de calor en 2D Unity Soy nuevo en esto del lenguaje de shaderlab en Unity sé que necesitaré esto pero no sé que más hacer

    Properties {
        _Background ("Background", 2D) = "" {}            //Textura de fondo
        _BackgroundScrollX ("X Offset", float) = 0        //Cambio de fondo
        _BackgroundScrollY ("Y Offset", float) = 0
        _BackgroundScaleX ("X Scale", float) = 1.0        //Zoom de fondo
        _BackgroundScaleY ("Y Scale", float) = 1.0
        _Refraction ("Refraction", float) = 1.0        //Valor de refracción
        _DistortionMap ("Distortion Map", 2D) = "" {}    //distorsión
        _DistortionScrollX ("X Offset", float) = 0
        _DistortionScrollY ("Y Offset", float) = 0
        _DistortionScaleX ("X Scale", float) = 1.0
        _DistortionScaleY ("Y Scale", float) = 1.0
        _DistortionPower ("Distortion Power", float) = 0.08
    }


text:
Q: iframe's content and visibility based on a user-agent So, I am making my own page (which is going to be an embedded  for other websites later). The page simply is an advertisement banner.
I want the banner to be visible for mobile users only, and the content has to different for Android and/or iOS users (by tracking is it Safari browser for example).
I've never had an experience with the  before, so I don't really understand how the data works with it. Can it be configured on the side of the iframe (my page, the banner's source code)? Or it has to be configured on the website, which is using the ?

A: You'll have to use some feature detection. You'll need to test if the browser is Safari. If it is, then display something. If it's Chrome, display something else. If it's Firefox, display something else.
I don't have a Mac, so I'm doing this based on Chrome.
If it's Chrome, Google.com will display. If it's anything else, Microsoft.com will display.

let ua = navigator.userAgent;
let vendor = navigator.vendor;

let isChrome = /Chrome/.test(ua) && /Google Inc/.test(vendor);

function displayIframe() {
  if (isChrome) {
    console.log(isChrome);
    return `

    `;
  } else {
      return `

      `;
  }
}

iframe.innerHTML = displayIframe();

Once you've tried this in Chrome, move over to Firefox and you'll see the difference.


text:
Q: Prove zero vector is a boundary point of $C_2 - C_1$ of two "distinct" and non-disjoint convex sets $C_1$,$C_2$ Consider $\Bbb R^n$. We say two convex sets are distinct if their intersection are only boundary points of $C_1$ and $C_2$. Prove zero vector is a boundary point of $C_2 - C_1 = \{x_2 - x_1: x_2\in C_2, x_1 \in C_1\}$ of two "distinct" non-disjoint convex sets $C_1$,$C_2$.
My attempt: if $0$ is not an interior point of $C$, then $B_d(0) \subseteq C$ for some $d>0$. Let $\|x\|<d$, then $\exists x_1,x_2,x_1',x_2'$ s.t. $x_2=x_1+x,x_2'=x_1'-x$, implying $0.5x_1+0.5x_1'=0.5x_2+0.5x_2'\in C_1\bigcap C_2$. However, I am not able to show $0.5x_1+0.5x_1'$ or $0.5x_2+0.5x_2'$ are not boundary points of $C_1,C_2$

A: Let $C_1$ and $C_2$ be as above ("distinct", non-disjoint, convex sets in $\mathbb{R}^n$).
Since they are "distinct" and non-disjoint, the intersection is nonempty and consists entirely of boundary points. So there is some $p\in\partial C_1\cap \partial C_2$. This means $p\in C_1$ and $p\in C_2$ so $0=p-p\in C_2-C_1$.
Now suppose for contradiction that $0$ is not a boundary point of $C_2-C_1$. Then there exists an $\epsilon>0$ such that $B_\epsilon(0)\subseteq C_2-C_1$. Let $s:C_1\times C_2\to \mathbb{R}^n$ be the subtraction map given by $s(v,w)=w-v$. This map is continuous so
$$s^{-1}(B_\epsilon(0))\subseteq C_1\times C_2$$
is an open neighborhood of $\{p\}\times\{p\}$. Since it is open, there must exists a $\delta>0$ such that
$$B_\delta(p)\times B_\delta(p)\subseteq s^{-1}(B_\epsilon(0))\subseteq C_1\times C_2$$
Thus $p$ is an interior point of $C_i$ which is a contradiction.
Thus $0$ must be a boundary point of $C_2-C_1$.

A: It is not true.
Consider the following subsets of the plane: $C_1 = [-1,1] \times \{0\}, C_1 =  \{0\} \times [-1,1]$.
Then $C_1 \cap C_2 = \{(0,0)\}$, $C_1 - C_2 = [-1,1]^2$. Hence
$0 \in (C_1-C_2)^\circ$.


text:
Q: issue with bitbucket pull request I create a new branch from master, after push code to this branch when I go to pull request section I create pull request and specified my branch and destination branch when I click on pull request button I recive "unrelated branches" error while I get this branch from master.

A: oh...
I push my codes before pulling destination code, this error comes from here.
for example if you create a branch from master , you should to first pull master to your folder then push all things.


text:
Q: how to get a list of request parameters in ASP.NET I want to use [FromQuery] to get a list (or a map<String, String>) of all request parameters and their values.
we can use in Spring boot this solution:
saveForm(@RequestParam Map<String,String> allParams)

How can I have the same solution in ASP.NET? Can I use something like:
saveForm([FromQuery] Map<String,String> allParams)

A: Here is the solution:
saveForm([FromQuery] Dictionary<String, String> allParams)


text:
Q: Help with understanding this multiple choice question This question was asked in NBHM 2019. It has multiple correct answers.
Let $f$ be a continuous function from the real line $R$ to the closed interval [1,3] such that:
A) $f^{-1}(1)$ and $f^{-1}(3)$ are singletons and B) $f^{-1}(x)$ consists of exactly two real numbers for every $x$ in $(1,2)\cup (2,3)$. Which of the following can be the cardinality of $f^{-1}(2)$? Choose all the correct options:
a) 1 b) 2 c) countable infinity d) uncountable infinity.
I am  having trouble understanding this question. If $f^{-1}$ is to exist, then shouldn't it be that $f$ be bijective. Here B) suggests that $f$ could be many-one function. And $f^{-1}$ looks like one-many function, which can't be true. Any hints are appreciated.


text:
Q: Disable the inputs when checkbox not checked I have this code and I want to disable all the inputs when the checkbox is not checked.

    <?= ucwords($food_name); ?>

        <input value="<?= $order_food_id; ?>" type="checkbox" name="select_food[]" checked>

        <input value="<?= $order_food_total_members; ?>" type="text" name="total_members[]" class="form-control" placeholder="Total Members">

        <input value="<?= $order_food_date; ?>" type="date" name="food_date" class="form-control">

        <input value="<?= $order_food_time; ?>" type="time" name="food_time" class="form-control">

I have used this code but it is disabling only the first input and I don't know how to taget the remaining two.
$('input[type="checkbox"]').click(function () {
    if(!this.checked) {
        $(this).closest('td').next('td').find('input:text').attr('disabled' , true);
    } else {
        $(this).closest('td').next('td').find('input:text').attr('disabled' , false);
    }
});

A: Whatever you have done is partially correct, what you have done is you have targetted with $(this) so obviously it will take the checkbox input and will find the closest 'td' and disable only the first input tag because it is the one which is closest rather you can do this by targetting the element which has this form-control class and disable the event so it will apply to all the input field which has this class which is indirectly the other three input field.
$('input[type="checkbox"]').click(function () {
    if(!this.checked) {
        $('.form-control').attr('disabled' , true);
    } else {
        $('.form-control').attr('disabled' , false);
    }
});

Or the second choice is you can use this each statement to update the input element.

A: You should be able to do something like this - get all of the elements and then disable. You'll have to do it onclick of the checkbox.
var inputs, index;

inputs = document.getElementsByTagName('input'); // get all of the input elements
for (index = 0; index < inputs.length; ++index) { // loop through them
    inputs[index].disabled = true; // disable them
}

A: The issue is that you are only selecting a single element:
$(this).closest('td').next('td').find('input:text')

This will find the closest  ancestor element to the checkbox, then select the next sibling  element, and finally get the descendants of that  element that matches the selector input:text. This will result in a single element because only one of your inputs is of type "text", and you are only selecting inside of a single .
What you want to do instead is select all of the input elements that are not checkboxes in the table row
 (class .select_tr):
$(this).closest('.select_tr').find('input:not([type=checkbox])')

This will select the parent
 with class .select_tr and then select all input children of it that do not have type=checkbox.
Example:

$('.select_tr input:checkbox').change(function() {
  $(this).closest('.select_tr').find('input:not([type=checkbox])').prop("disabled", !this.checked);
});

      <?= ucwords($food_name); ?>

      <input value="<?= $order_food_id; ?>" type="checkbox" name="select_food[]" checked>

      <input value="<?= $order_food_total_members; ?>" type="text" name="total_members[]" class="form-control" placeholder="Total Members">

      <input value="<?= $order_food_date; ?>" type="date" name="food_date" class="form-control">

      <input value="<?= $order_food_time; ?>" type="time" name="food_time" class="form-control">

A: You can try something like this:
var elemCheckbox = document.querySelectorAll('[type="checkbox"]')[0];
var elemInputs = document.querySelectorAll('.form-control');

function toggleInputs() {
    // https://stackoverflow.com/questions/9887360/check-if-checkbox-is-checked-javascript#answer-9887439
    var shallDisable = !elemCheckbox.checked;
    // https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/
    for (i = 0, len = elemInputs.length; i < len; ++i) {
        // https://stackoverflow.com/questions/7526601/setattributedisabled-false-changes-editable-attribute-to-false#answer-7526666
        elemInputs[i].disabled = shallDisable;
    }
}

elemCheckbox.addEventListener("click", toggleInputs);

Find the explanation in the comments.
This example won't disable the checkbox (if you meant it like that).
I would recommend to add an id to the checkbox. This will guarantee an explicit element selection.
You can then get like document.getElementById("<yourUniqueId>");

A: Your code isn't selecting all the inputs. Use nextAll() for selecting each td after the closest('td').
$('input[type="checkbox"]').click(function(){
 if(!this.checked){
  $(this).closest('td').nextAll('td').find('input').attr('disabled' , true);
 }else{
  $(this).closest('td').nextAll('td').find('input').attr('disabled' , false);
 }
});

JQuery.next() is used for selecting the first matched element after the selected element

So, your code is just affecting the first next only.

JQuery.nextAll() is used for select the next all matched elements after the selected element.

So, using nextAll() instead of next() may solve your problem.


text:
Q: i am getting this error for deleting a record, detail issue is below. " The GET method is not supported for this route. Supported methods: POST. " I am deleting a record and getting the above error but when I go back the record is deleted. Why I am getting an error if the record is deleted when I go back? I tried solving like this: this is my view blade page route
id}}'>

I tried this as well:
form method as well but getting same answer
and this is my web.php
Route::post('/DeleteCandidateID/{CanDelID}', 'CandidateController@DeleteCandidateID')->name('candidate.DeleteCandidateID');

this is my controller :
 public function DeleteCandidateID($CanDelID) {

    $canid = Candidate::findOrFail($CanDelID)->delete();

    return redirect()->back()->with('success', 'candidate deleted successfully');
}

A: FIRST POSSIBILITY :
You added a simple link and in your routes file you indicated that you are waiting a POST request, so you need to add a form in your blade view with the POST method:
<form method="POST" action="{{ route('candidate.DeleteCandidateID', ['CanDelID' => $candidate_id->id]) }}">
   <button type="submit">Delete the candidate</button>
   @csrf
</form>

SECOND POSSIBILITY :
Following this post, if the problem still persists, you can try to keep your link :
id}}'>

And change Route::post(...) to Route::get(...). I think it can fix your problem but it's definilty not the best way.

THIRD POSSIBILITY :
Overide the POST method with method_field :
<form method="POST" action="{{ route('candidate.DeleteCandidateID', ['CanDelID' => $candidate_id->id]) }}">
   <button type="submit">Delete the candidate</button>
   @csrf
   {{ method_field('DELETE') }}
</form>

And change your route to : Route::delete(...)

A: *

*Your route should use delete method. Run php artisan route:list to confirm that.
Route::Delete('/DeleteCandidateID/{CanDelID}','CandidateController@DeleteCandidateID')->name('candidate.DeleteCandidateID');

*Use a form to delete
<form method="POST" action="{{ route('candidate.DeleteCandidateID', $idOfTheCandidate) }}">
          @csrf
          @method('delete')
          <button type="submit">Delete the candidate</button>
      </form>

*That should work and note @method('delete') in the form. Browsers do not understand delete an put methods, so we place it there and it will override post method when the server is hit.


text:
Q: How to find all hostnames in DNS attached to one IP? If I have multiple hosts configured on one machine (a la apache's VirtualHosts), how can I do a lookup on the IP and find all domains configured to reach it?
For example, I have several web and email domains hooked-to my server. How can I find all domains that point to it?
Is it even possible?
I have DNS A entries for all the domains I own, plus I know some friends' domains point to my server. What I'd like to see is if folks I don't know about are pointing there, too. (Or if someone has repointed their domain elsewhere, and I can delete their 'old' website from my server.)

A: The only way to do this, is to have content data of domain name you want to inspect.
With this content you can devellop a recursive script to search hostname relative to your IP (recursive because of eventual CNAME to check).
To get data of some domain name partner, you can ask to be secondary and get DATA with a dig -t axfr.

A: Not really, no. This is all about the difference between forward and reverse DNS lookups.
A forward lookup is the standard name->IP lookup. So, you would have to know all the names in advance.
What you want is to do an IP->name lookup, but somehow get all the names you've applied in your Apache config and in DNS as A records (or CNAMES or whatever).
What you will probably find is that doing a reverse lookup (e.g. dig @nameserver $ip -x) will return the hostname given to that IP by the people who own that netblock, which could be your ISP. It might have a name like 45-23-45-231.big-isp.com, which doesn't mean a whole lot to you. And crucially, there is only one reverse record, but potentially many forward ones.
I suppose it boils down to the question - how does the reverse zone know about any of the records in the forward zone? In most setups, the forward zone is made available to the customer to make changes to, but the reverse zone is maintained by the owners of the netblock. The two systems don't need to know anything about each other to function.

A: I think you're coming at this from the wrong direction. Aside from either a) querying every DNS server in existence for every possible domain name and then storing the result or b) getting zone transfers from the DNS servers you're interested in, there's no way to do this with DNS.
Well, if you're running Apache name-based vhosts, you already have a list of domains that will reach your server. Aside from the default vhost, a name-based vhost will only answer for its' name. So if I point foobar.com at my box, and don't have a foobar.com vhost, it'll either be served by the default or not get answered (if you don't have a default server).
Apache has some very powerful logging features. It shouldn't be a problem to define a custom log format with the request lines you want. Also, there's always the referrer field.
Mail, on the other hand, is a bit more of a pain. About the best thing I can think of is to pick what you can from the server logs and, if you really need to know, setup a packet capture for SMTP.

A: You should check for RobTex
Not the best web design, but very useful ! You can find out all the DNS associated to an IP.
Of course, as explained Alnitak,

It's not possible to do it with the DNS protocol itself

That means that this website is just a huge database of most DNS/IP servers. That's pretty efficient but not 100% exhaustive.

A: It's not possible to do it with the DNS protocol itself, because typically there's only one PTR record for each IP address, even though there may be many A records pointing at that IP address.
However some companies (e.g. http://www.ip-adress.com/) have managed to compile databases containing what you're after by storing the results of a whole load of DNS lookups and then offering a reverse-query into their own databases.
Those databases can't be definitive though, they can't guarantee to know about every possible domain that might happen to point at that IP - they can only record the DNS details for the domain names that they've actually looked up.


text:
Q: Html table - row highlight on mouse hover for specific column Let's take example table:

        header
        12
        13
        14

        header
        22
        23
        24

        header
        32
        33
        34

        header
        42
        43
        44
    </tr

In this example, complete row is highlighted on any column mouse hover.
Is it possible to highlight complete row only on mouse hover for 1st column using just css? Like this.

A: Edited answer. Try this!

A: Use the ~ selector with :first-child. Like this:
table tr td:first-child:hover ~ td {
    background-color: #8888FF;
}
  table tr td:first-child:hover {
    background-color: #8888FF;
}

P.S. Maybe this is not the best approach, but I don't know any others.

A: you can use this code:
    table tr td:nth-child(1):hover{
                                    background-color: #8888FF;
                                  }

A:   td:first-child:hover ~ td, td:first-child:hover{
        background-color: #8888FF;
    }

I think that this is what you are looking for


text:
Q: How can I passively examine the contents of a ZFS send stream? I have some stored ZFS "send streams" (i.e., they were created by redirecting the output of zfs send to a file). I would like to examine the contents of these streams without receiving and writing them into a filesystem — for example, I'd like to view a list of filenames inside the stream. Is there any way to do this?
I've done some reading and searching, but haven't found anything that looks like what I'm talking about. I'm using both the FreeBSD and the ZFS on Linux implementations of ZFS.

A: You can obtain some info by piping them into zstreamdump -d, but that will not give any info on file names directly because there are no files in the stream. The stream is a sheer difference between two trees described in blocks. However the code is public, so if you manage to add ZFS structure detection and parsing you can get more from it.
ZFS internal structure is a tree internally and all operations are done over that tree. Files, directories, filenames, attributes and everything else is just a data in that tree. Snapshots, volumes and FS are the tree roots, and when you take another snapshot you are just storing the current root somewhere. Live systems are generating new roots for each transaction constantly drifting away from the older roots, while keeping a lot of data "leaves" from the previous tree intact. The stream represents a list of operations that should be performed on tree A to become B.
I'm just trying to say that you may not see the data you are looking for in the stream because they are not required to be there. When the file is dropped the corresponding blocks are just freed so you can't tell what was the file name or contents. When the file is changed it's referenced by the object id so you wouldn't get anything from the stream even if the file was rewritten from the scratch but the directory entry hasn't been updated.
You will be lucky if the stream is not a differential stream or if you have some data over it's previous state. But that's just because a full stream transforms empty root to the target tree thus containing all required data. Hence you can add the block parsing code to the zstreamdump to detect and process ZFS internal data.

A: Short answer:
I do not believe there is any way to usefully catalog the contents of a send stream that is any lighter weight than piping it to zfs receive to recreate it as a dataset.
Much longer answer:
A send stream is a storage block level collection of data, not a filesystem level collection of data. A send stream does not know or care about individual files; it's designed to replicate what are essentially raw block devices. While one user might exclusively use zfs send to replicate ZFS datasets with files stored directly on them, another might use it to replicate ZVOLs formatted with ext4, ntfs, or even an encrypted system like LUKS - in these cases, ZFS has absolutely no knowledge of what the contents of the volume are, it merely stores the raw blocks for them.
zfs send works exactly the same whether you're replicating a dataset, or a raw zvol, because it simply doesn't care about anything below the raw block storage level. It doesn't know about filenames, file sizes, paths, or anything else - it knows which blocks belong in a given snapshot of a zvol or snapshot, but it does not know how any of those blocks relate to one another.
So, there's no lightweight way to catalog the file contents of a zfs send stream, because there is no internal catalog of the files in one. Even if you know conclusively that this particular stream happens to be a full (not incremental) replication of an unencrypted ZFS dataset, you'd have to parse every block of it line by line to try to figure out which blocks of it contained filenames.
Essentially, in order to extract the filenames from a send stream, you'd be doing all the same work that zfs receive is doing by applying that stream to a dataset in the first place.


text:
Q: SignalR not calling client methods from the server I'm adding all my client methods before I call .start().
What I'm doing is loading wiring up all the client methods and I've got a setTimeout for 5 seconds to actually call .start(), so I know all my client script is wired up.
For some reason the scripted gets wired up but will not be called be the server.
Now, I'm able to call the server methods with no problems, I just need the server to relay that message back to the clients, via the client script.
Is it OK to put client script inside named function objects?
I've removed a lot of the code so it is readable.
This works, because I'm calling the server.
$.connection.hub.proxies.collaboratorhub.server.sendMsg

-
This does not work because I'm waiting on the server to send the client it's message
 $.connection.hub.proxies.collaboratorhub.client.receiveMsg

=
On the server side when I debug I am receiving the sentMsg from the client to the server and the receiveMsg is being called from the server, but it never makes it to the client.
    function ChatBox(collaboratorMenuItem) {

    var
        sendMsg = function (ev) {
            // If the user has pressed enter

            if (ev.keyCode === 13) {

                if (this.value.trim() === '') { return false; };

                var avatar = attendees.querySelector('.' + meAttendee.profile.UserID);
                if (avatar) {

                    chats.appendChild(
                           docCreateAttrs('div', { 'class': 'collabChat', innerHTML: this.value }).addChild(avatar.cloneNode(true))
                           );
                } else {
                    chats.appendChild(
                          docCreateAttrs('div', { 'class': 'collabChat', innerHTML: this.value })
                          );
                };

                $.connection.hub.proxies.collaboratorhub.server.sendMsg({ msg: this.value });

                this.value = '';
                return false;
            } else { return true; };
        },

    debugger
    //Callbacks that are called from the server. Not intended for local function calls
    $.connection.hub.proxies.collaboratorhub.client.receiveMsg = function (cmsg) {

        var avatar = attendees.querySelector('.' + cmsg.uid);
        if (avatar) {

            chats.appendChild(
                   docCreateAttrs('div', { 'class': 'collabChat', innerHTML: cmsg.msg }).addChild(avatar.cloneNode(true))
                   );
        } else {
            chats.appendChild(
                  docCreateAttrs('div', { 'class': 'collabChat', innerHTML: cmsg.msg })
                  );
        };
    };
    $.connection.hub.proxies.collaboratorhub.client.addCurrAttendee = function (attendee) {

        debugger
        addAttendee(attendee);
    };
    $.connection.hub.proxies.collaboratorhub.client.joined = function (attendee) {
        debugger
        addAttendee(attendee);

        //let the new attendee know about you
        if (attendee.cnnid !== meAttendee.cnnid) {
            meAttendee.newbieid = attendee.cnnid;
            //
            this.server.addMeNewbie(meAttendee);
        };
    };
    $.connection.hub.proxies.collaboratorhub.client.rejoined = function (attendee) {
        debugger
        //console.log('Re joined : ' + attendee.cnnid);
        addAttendee(attendee);

        //let the new attendee know about you
        if (attendee.cnnid !== meAttendee.cnnid) {

            meAttendee.newbieid = attendee.cnnid;
            this.server.addMeNewbie(meAttendee);
        };
    };
    $.connection.hub.proxies.collaboratorhub.client.gone = function (attendee) {
        // console.log('gone : ' + attendee.cnnid);
        removeAttendee(attendee);
    };

    collaboratorMenuItem.onclick = function (e) {
        //debugger
        if (!chatBox.parentNode) {
            var xy = e.target.getBoundingClientRect();

            document.body.appendChild(chatBox.setGX(null, xy.left).setGY(null, xy.height));
            $(chatBox).draggable({ handle: chatHead, cursor: "move" }).css('position', 'absolute').resizable();
        } else {
            removeChat();
        };
    };

    return {
        chatBox: chatBox,
        attendLk: attendLk,
        addAttendee: addAttendee,
        removeAttendee: removeAttendee,
        removeChat: removeChat
    };
};

--This is how I create a name function called collaborateManager that when instantiated has a property call this.chatBox and this is where all the client script is loaded up, with-in the ChatBox.
The collaboratorMenuItem is just a div that the ChatBox is placed next to.
  function collaborateManager(collaboratorMenuItem) {

                this.chatBox = new ChatBox(collaboratorMenuItem);

    }

    return {
        hideCollaborator: hideCollaborator,
        showCollaborator: showCollaborator,
        getCollaborator: getCollaborator,
        removeCollaboratorCollaborators: removeCollaborator
    };

And in another Global JS File I start the connect in five seconds.
document.bindReady(function () {

setTimeout(function () {

    //Global SignalR Connections State

    var cnnStateChanged = function (change) {

        if (change.newState === $.signalR.connectionState.reconnecting) {
            console.log('Re-connecting');
        }
        else if (change.newState === $.signalR.connectionState.connected) {

            console.log('The server is online');
        }
        else if (change.newState === $.signalR.connectionState.disconnected) {

            console.log('The server is offline');
        };
    },
     cnnReconnected = function (change) {

         if (change && change.newState === $.signalR.connectionState.reconnected) {

         };
         console.log('The server is re-connected');
     };
    //------------------------------------------------------------------------------------------------------------
    //Global start SignalR connectio

    $.connection.hub.stateChanged(cnnStateChanged);
    $.connection.hub.reconnected(cnnReconnected);

    if ($.connection.hub && $.connection.hub.state === $.signalR.connectionState.disconnected) {
        $.connection.hub.start().done(function () {

            //debugger
            // onConnected();
        });
    } else {
        //debugger
        // onConnected();
    };

},5000);

});

The connection is starting correctly each time, that is not the issue, I can send server messages as well, I need to be able to receive those messages.
Here is my server side sendMsg that gets called, but no clients ever receive the receiveMsg()
  public Task sendMsg(Cmsg cmsg)
    {
        string pid = this.Context.QueryString["pid"],
               uid = this.Context.QueryString["uid"];
        //
        cmsg.cnnid = Context.ConnectionId;
        cmsg.uid = uid;
        //614

        return Clients.OthersInGroup(pid).receiveMsg(cmsg);
    }

Any suggestions? Am I doing this wrong?

A: Try Changing your server side code to:
public Task sendMsg(Cmsg cmsg)
{
   string pid = this.Context.QueryString["pid"],
   uid = this.Context.QueryString["uid"];
   //
   cmsg.cnnid = Context.ConnectionId;
   cmsg.uid = uid;
   //614
   return Clients.Caller.OthersInGroup(pid).receiveMsg(cmsg);
}

Adding the Caller in:  return Clients.Caller.OthersInGroup(pid).receiveMsg(cmsg);


text:
Q: Why do Sitecore standard values not get propagated? I have some items in the content tree that are currently just being used as data items. However, I want to add a layout and various sublayouts to them and I don't want to have to do it manually. Currently these items don't have any presentation details set.
So, I've added the presentation details to the standard values of the template that these items are using. I thought that the items would start using these sublayouts straight away. I know that if a default value is put in after the template has started to be used and the item already has a value the standard values will not overwrite this value, but since the items don't currently have any presentation details (and I've tried resetting them) I thought this would work.
It's probably worth noting that the reason I'm doing this is for previewing purposes so although these can be published, it doesn't necessarily have to happen.

A: Unfortunately I do not know why your solution isn't working but you could see if reseting the fields back to the standard values sorts the problem.
In the content editor select a data item, then from the ribbon select the version tab and click the reset button (make sure standard fields are visible).
Select the layouts field and reset it to standard values.
This will at least indicate if you have values setup on the standard values correctly.

A: You may have to reset the Layout on the items (Not the standard values). It could be that you have changed the layouts on the data items, or some other random thing that may have happened, and it needs to be reset.


text:
Q: Netflix doesn't work since installing Ubuntu 18.04 I installed Ubuntu 18.04 64-bit and enabled DRM in Firefox. When trying to watch Netflix, I get the following errors:
Oops, something went wrong...

Netflix video player unavailable

We're having trouble playing Netflix in your browser. Please make sure you're on an official version of Firefox.

Error Code: F7355-1204

I'm using the version of Firefox that came installed with Ubuntu. How do I play Netflix videos on 18.04?

A: In order to watch netflix with firefox under Ubuntu 18.04, you need to make sure that you have DRM enabled in your firefox settings (Go to settings, scroll down, check play drm-controlled content). Also make sure you have the libavcodec-extra package (from the universe repository) installed. In order to install libavcodec-extra you should have the universe repository enabled:
sudo add-apt-repository universe

Then install the libavcodec-extra package:
sudo apt install libavcodec-extra

A: I found this fix at Netflix support site. I have the HTML 5 theme enabled and Silverlight theme was also added but not enabled.
I also have the following plugins enabled, OpenH264 Video Codec, shockwave flash, and Widevine Content Decryption Module.
Netflix is now working perfectly from Firefox browser in Ubuntu 18.04.


text:
Q: Ubuntu 20.04 Reading package lists... Error I am beginner with ubuntu. I've got stuck with an error. I can't install application. Any ideas what may be wrong?
usic@hosttt:~$ sudo apt-get install /myprogram/program.deb
Reading package lists... Error!
E: read, still have 59 to read but none left
E: Error reading archive member header
E: Could not read meta data from /myprogram/program.deb
E: The package lists or status file could not be parsed or opened.

A: When installing local DEB packages, you should use dpkg instead of apt, since apt is designed for installing packages from the remote repositories. To install your package with dpkg, use the following command:
sudo dpkg -i /path/to/my/package.deb

Replace /path/to/my/package.deb with the actual path of your own package.
In some cases, this command may fail with missing dependency errors. If this is the case, issue the following command:
sudo apt --fix-broken install

This will install the dependencies. After that, re-run the first dpkg command to install your package.
Alternatively, the program gdebi can be used instead of dpkg, since it has better resolution of dependencies without needing to apt --fix-broken install. To install gdebi, run this command:
sudo apt install gdebi-core

Now you can install your program directly using:
sudo gdebi /path/to/my/package.deb

A: If the myprogram directory is in you Home, then the path is wrong.
Run
sudo apt install ~/myprogram/program.deb


text:
Q: 'Run' or 'Operate' for a business related sentence I am trying to decide between two sentences but not sure which one fits the most. I am going to use this sentence inside the 'About Us' section of the company.
Option 1

Company A also runs two hotels.

Option 2

Company A also operates two hotels.

A: Either sentence is fine, I'd say, although "operates" might be a touch more formal.

A: Choose 'Run'.
While both are ok, I would say that 'operate' has come to imply a more physical interaction - using your hands to make something function in a certain way. Thus, one might operate a machine.
'Run' is more often used to imply a less physical involvement. For this context, 'run' and 'manage' are more likely to be considered synonymous than 'run' and 'operate', given common usage.
I say again, a dictionary will tell you that both of these sentences are fine and I agree that you could choose either. I recommend using 'run' based solely on common usage.
Hope that helps.


text:
Q: Play framework: Store connections after onStart? I'm writing a RESTful API using the Play Framework and I have some bootstrap operations on application start;
Client transClient = new TransportClient(settings)
            .addTransportAddress(new InetSocketTransportAddress(ESHost, 9300));

Which is quite basic, I establish a connection to an ElasticSearch cluster. Now, I want transClient to be accessible across packages/controllers/etc, and one workaround could be to Cache.set("ES", transClient), which ofcourse doesn't seem right.
I cannot find any documentation about this online. What's the best way to go about this?

A: The simplest way is a singleton. You don't even have to bootstrap it in the global onStart method.
public class ConnectionHolder {

    private static ConnectionHolder holder;
    private Client transClient = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress(ESHost, 9300));

    private ConnectionHolder() {   }

    static ConnectionHolder getInstance() {
        return holder == null ? holder = new ConnectionHolder() : holder;
    }

    public Client getClient() {
        return transClient;
    }

}

tl;dr
In my current project we use the Guice singleton scope for this kind of problems. So we can easily inject anything to controllers or services. There's a lot advantages of this solution especially during tests. If you don't have any dependency injection framework in your project a simple singleton will do the job. Solving thread safe problems is up to you.


text:
Q: Google Publisher Tag Reward Ad reloads Mithril SPA unexpectedly When I run this code in my localhost server and I click the Show Ad button in the #!/reward page, the reward ad shows but sends me back to the #!/ page. However, in this online code editor this SPA (single page app) works as intended: it plays the ad but leaves you on the reward page. Obviously this must have something to do with the fact that the application is running in an iframe on the editor, but why am I getting the "unexpected" behavior on my localhost and "expected" behavior in these online editors (I've also tested in jsbin and jsfiddle and same result).

<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

UPDATE (2022.08.03 11:16)
I can confirm that by placing this code into a subdirectory and then running it inside an iframe I get the expected behavior. I still need to understand why it doesn't work without the iframe. Here's a Glitch page that illustrates both scenarios. Click the View button on the preview pane to view it in its own window and note the difference.

A: The specific code for a rewarded ad appends #goog_rewarded to the end of the page's URL. This is what forces the unexpected behaviour to return to the default route of Mithril's router when using the default #! strategy. The added # triggers a hashchange event and Mithril cannot resolve the route. Setting the m.route.prefix to a different strategy (in my case m.route.prefix = '?') resolves the problem as it prevents the lookup from taking place.


text:
Q: rolling back version on whole s3 bucket I have an s3 bucket on aws with versioning enabled. I need to "rollback" to the previous version. Not file by file but the whole bucket. Is there any software i can use? or any command on the console that i can run? it's an emergency and time sensitive.
Thanks you!

A: There is no concept of "rollback to the previous version" for a bucket.
Each object maintains a version history, and each historical version of each object is maintained and accessible.
If you wish to abandon the most recent version of each object, you would need to write a script/program that would:

*

*Obtain a list of all objects

*For each object:

*

*Obtain a list of versions

*Delete the most recent version

The prior version of each object would then become the current version.
Alternatively, you could obtain the previous version of each object without removing the current version. This would involve a similar script/program, without the delete step.


text:
Q: generating random primary id in rails 3 I have different models like Customer, User, Admin etc in my rails app. I would like to make the primary id as string and prepend it with a character. so for customers, the id would be something like C1, C2, C3. For Users it will be U1, U2, U3 etc..

A: If you really need this info, you could just define a method called string_id or something that returns the numerical id prepended with a custom prefix that you define?
Comparison of non-numerical primary keys (when finding records in your DB) is only going to slow down your app, and I'm not sure why you would want to do this since you can simply do a .class.name call on the model of your choice to get the class name back, or the first character of the class, or whatever. I think you need to justify and explain the technical need for this in your question a bit more, otherwise it just looks like a really bad idea.
Also, your question title specifies "random" - but where's the random part? What is it you're trying to do exactly?
Basically there are multiple, better ways to do this than trying to use a String as your primary key, at least based on what information you've provided in your question thus far.

A: Unless you have a really, very, super good reason for doing this, just don't. Generating your own keys seems like a great idea until it causes a malfunction.
Instead, create an auxiliary key with a unique index and use it for this purpose.

A: You can declare an alternative id column or you can define your own key.
for example:
class Customer < ActiveRecord::Base
  self.primary_key = "C_"+ #your column
end

see http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/PrimaryKey/ClassMethods.html#method-i-primary_key-3D


text:
Q: Dragging divs from one window to another I have window with some divs that are draggable. I also have  a second window that I created with window.open() that has divs that are draggable.  Is it possible now to drag a div from one window to the other?
Thanks

A: Take a look at this tutorial for the DnD part.
To achieve this, it's possible to pass a temp value that both sending and receiving window can read. It could be a cookie, or a better idea could be to use localStorage if it's available, as some people voluntarily block cookies for more privacy.
Using the Modernizr's fallback test, it could goes like this:
if (Modernizr.draganddrop) {
    // add drag and drop support
} else {
    // custom drag and drop support or suggest the user to get a real browser (if possible)
}

Whenever a drag is started :
if (Modernizr.localstorage) {
    window.localStorage['item_1_drag_started'] = true;
} else {
    document.cookie = "item_1_drag_started=1";
}

Then, when drag is over / mouse is up :
if (Modernizr.localstorage) {
    delete window.localStorage['item_1_drag_started'];
} else {
    document.cookie = "item_1_drag_started=0";
}

Now, when the mouse enters the other window, you may check if the item was still being dragged by accessing localStorage (or the dirty cookie if it's unavailable).
The only issue I can think of is when the user releases the mouse button while between those windows. That could be a problem, since the item will be considered dragging but you can't release a button that isn't pressed. Does anyone know about a trick to check if the mouse button is still pressed when entering a window even if it doesn't fired the event ?
In the meantime, the click event in the receiving window could simply check if it's still dragging then drop the item and remove the flag.

UPDATE: Concerning the mentionned issue, after digging a little and doing some test with events it seems that neither mouseover or mousemove is fired when a mouse button is still pressed (at least in Chrome where my tests have been made).
With that in mind, I think that the best approach to Drag and Drop between two windows is to toggle it:
  Click --> Drag is started

  Click again --> Drop the item

A: From the answers provided I can see now that dragging between windows is really ugly. You have to basically transfer the mouse state from one window to the other and inject the element being dragged into the DOM of the destination window.  I was hoping there was some jQuery around that you could run in both windows that would smooth all that over, but I guess not.  I just won't do the drag in this project.  I can just allow the user to click an element in the second window and have it appear immediately in the first window.  Good enough.  Thanks for looking at the question.

A: I guess you could set a variable "drag item = true" and store the item content somewhere. Then drop it on the mouse up in your popup.

A: What you could do is on drag being, set a cookie and on mouse over the target window, check for the cookie and simulate the drag.


text:
Q: We need better spam detection and blocking tools With popularity comes spam, and Stack Exchange is popular. It sometimes takes a few repeats before you start to recognize the same URL or product name, and blacklisting frequently spammed URLs is a non-trivial process which moderators can't even do ourselves.
For one-time drive-by spammers, the community tends to be pretty good about dispatching bad posts. Repeat offenders though are not always easy to catch, and result in a lot of work for both moderators and the community at large. We need better tools to combat this.
I would like to request the following tools, kind of in order of complexity to implement:
The relatively easy to add things...

*

*A search function for posts marked and deleted as spam, similar to deleted:1. Something like spam:1 would do. This would help in finding trends.

*A listing in the moderator tools of posts recently marked as spam. (This could probably even be a 10k or 20k tool). Recently deleted posts are already listed, but a lot of deleted posts aren't spam. Having this tool would help us to find repeat offenders, enabling a more appropriate response.

*Automatic listing of URLs found in posts flagged and deleted as spam. Any URL appearing in more than 3-5 spam-flagged posts (perhaps have a menu, or just filter by # occurances) would show up on the list, with a link to view all posts with that URL.
The more complicated things...

*

*Automated blocking of repeatedly spammed URLs. If a given URL is present in more than, say, 15 posts marked as spam, it will automatically be added to the blacklist. To avoid false positives, perhaps there should be an exception for URLs that appear at least twice as many times in non-spam posts with positive vote counts.

*Auto-flag from Community when the same URL gets posted x or more times in n or fewer days, if the URL has never previously been seen on the site. This would help to raise attention for URLs which are being spammed but might not be caught right away by the community.
There are probably other things that would be helpful too, these are just some of my initial ideas of things that would help us to catch and stop spam more easily. Feel free to add other suggestions in the comments.

A: Note: most of the following tools are currently available to our developers; not as moderator tools.
Yes, indeed... if only we could look over all sites, checking all posts flagged as spam/offensive that have been deleted and marked as successfully resolved, extract the links, and aggregate those by domain... if only those tools already existed (cough)

I'm a bit reluctant to do too much by way of automated blacklisting, as without sanity checks it could perhaps be exploited in nefarious ways - maybe that's overly paranoid. However! We also have other more manual tools available to developers, including:

*

*manual blacklisting of content

*automated analysis of posts by a user and blacklisting of common hosts

I'm open to thoughts on how much of a common problem it is when we get a spate of spam for a single host that we should take prompt action on. From what I've seen, it hasn't usually been big enough (except for very rare and isolated events) to get too excited about. Open to thoughts, though.
Finally, yes, we could perhaps do better with better network-wide rather than per-site blacklisting. That said, I don't want the blacklist to be enormous...

A: To avoid confusion: please only upvote if you think automatic deletion of associated accounts is helpful, and downvote if you think it's making things worse... I know how voting works here.

Yesterday I was about to post the following as a question, but while typing I realized that automatic removal of associated accounts might also delete valuable content or might be problematic for hacked accounts, and hence be a bad idea. Or is it?
A spam account was deleted from Stack Overflow (at least 5 spam posts from May 8th to May 16th),  while its associated account on Super User was involved in the same spamming too (at least one spam post, but also a nice non-spam answer).
Some time later, the Super User moderators also deleted the spam, and warned:

If you spam this product again, you will be suspended.

That's fine with me, but still just curious: would it make life easier for moderators to automatically delete associated accounts (and their content), if an account is deleted for spamming on one site?
(That would also remove any subscriptions such spammer might have configured to find future spammable posts, but I guess such subscriptions could also be maintained using a puppet, so not a lot we can do there. Also note that this specific user has associated a new SE account to their remaining other accounts. But I don't think that having a few "old" associated accounts would fool other users into giving a spammer the benefit of the doubt if spamming again.)

A: It would be nice if a user get's deleted or suspended for something like spam elsewhere on the network, to have his latest posts on other sites automatically be flagged.
Simply put them in the queue of the moderator flags like you do with low quality posts or put them there on /review. So in a way, it's just another trigger for an already existing mechanism. If the post(s) look suspicious, users can flag the user for moderator attention and they can be dealt with like any other problem user.
Like you said, it doesn't happen that frequently, so having some peer review would be good to prevent nasty side effects. But being deleted/suspended elsewhere on the network seems a pretty good marker for being a problem user


text:
Q: Preferred method of accessing MS SQL with PHP 5.3+ on Linux What is the preferred method of accessing a Microsoft SQL Server database with PHP 5.3+ on Linux?
Given the different extension options now available I'm unsure which method is preferred based on reliability and performance. Right now I am using the mssql extension with FreeTDS, but I'd like to know if this isn't the best way.
I've heard some recommend using php-odbc/EasySoft because the mssql extension has been abandoned - yet others have said going the ODBC route isn't worth the performance hit.
The response to this stackoverflow question seems to touch on what I'm asking, however it's Windows centric.
Thank you!

A: I've had good results using PHP's PDO (PHP Data Objects) library for this sort of thing.  There's an excellent tutorial at http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/. Just make sure you use the following template to initialize your database connection:
$dbh = new PDO("dblib:host=$host;dbname=$dbname", $user, $pass);

A: I use FreeTDS. It's far from satisfactory. In fact, I found your question because I live in hope that there must be a better solution and I keep looking for one. Unfortunately, FreeTDS seems to be the best option at the moment, if you're developing in a Linux environment.
If you were on Windows, you could obviously use the Microsoft SQL Server drivers for PHP which would be better, but even then there are missing features, like support for PDO lastInsertId().


text:
Q: Django Form Wizard, how to reset/clear wizard when I'm not done yet? I have a working Form Wizard. To get to the wizard the user will click a button from the home page.
If I finish the wizard (three steps) and go back to the home page and click the button again, there's no problem. The wizard is good as new again and all the forms are empty which is what we want.
However if you didn't finish the wizard, like say I'm on the second step and I went back to the home page, click the button there, I'll be back to the second page. That's not what we want. We want a brand new wizard.
I want to implement a "cancel" or "reset" button that if clicked, the user will be redirected to the home page and when the user clicks the button they will be go to the first step of the wizard with all forms empty.

A: I got it. Apparently I only have to add a reset query param to the url that points to the wizard.
So my
becomes
and the session will reset and I will go to step 1 of the wizard. Found it after looking at the source code (Hint: line 647).


text:
Q: C# SHA-1 vs. PHP SHA-1...Different Results? I am trying to calculate a SHA-1 Hash from a string, but when I calculate the string using php's sha1 function I get something different than when I try it in C#. I need C# to calculate the same string as PHP (since the string from php is calculated by a 3rd party that I cannot modify). How can I get C# to generate the same hash as PHP? Thanks!!!
String = s934kladfklada@a.com
C# Code (Generates d32954053ee93985f5c3ca2583145668bb7ade86)
        string encode = secretkey + email;
        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] HashValue, MessageBytes = UE.GetBytes(encode);
        SHA1Managed SHhash = new SHA1Managed();
        string strHex = "";

        HashValue = SHhash.ComputeHash(MessageBytes);
        foreach(byte b in HashValue) {
            strHex += String.Format("{0:x2}", b);
        }

PHP Code (Generates a9410edeaf75222d7b576c1b23ca0a9af0dffa98)
sha1();

A: This method in .NET is equivalent to sha1 in php:
string sha1Hash(string password)
{
    return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(password)).Select(x => x.ToString("x2")));
}

A: I had this problem also.  The following code will work.
string dataString = "string to hash";
SHA1 hash = SHA1CryptoServiceProvider.Create();
byte[] plainTextBytes = Encoding.ASCII.GetBytes(dataString);
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
string localChecksum = BitConverter.ToString(hashBytes)
.Replace("-", "").ToLowerInvariant();

A: Use ASCIIEncoding instead of UnicodeEncoding. PHP uses ASCII charset for hash calculations.

A: Had the same problem. This code worked for me:
string encode = secretkey + email;
SHA1 sha1 = SHA1CryptoServiceProvider.Create();
byte[] encodeBytes = Encoding.ASCII.GetBytes(encode);
byte[] encodeHashedBytes = sha1.ComputeHash(passwordBytes);
string pencodeHashed = BitConverter.
ToString(encode HashedBytes).Replace("-", "").ToLowerInvariant();

A: FWIW, I had a similar issue in Java. It turned out that I had to use "UTF-8" encoding to produce the same SHA1 hashes in Java as the sha1 function produces in PHP 5.3.1 (running on XAMPP Vista).
    private static String SHA1(final String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        final MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(text.getBytes("UTF-8"));
        return new String(org.apache.commons.codec.binary.Hex.encodeHex(md.digest()));
    }

A: Try The following! I think it will work great:
public static string SHA1Encodeb64(string toEncrypt)
    {
        //Produce an array of bytes which is the SHA1 hash
        byte[] sha1Signature = new byte[40];

        byte[] sha = System.Text.Encoding.Default.GetBytes(toEncrypt);
        SHA1 sha1 = SHA1Managed.Create();
        sha1Signature = sha1.ComputeHash(sha);

        /**
        * The BASE64 encoding standard's 6-bit alphabet, from RFC 1521,
        * plus the padding character at the end.
        */
        char[] Base64Chars = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '+', '/',
            '='
            };
        //Algorithm to encode the SHA1 hash using Base64
        StringBuilder sb = new StringBuilder();
        int len = sha1Signature.Length;
        int i = 0;
        int ival;
        while (len >= 3)
        {
            ival = ((int)sha1Signature[i++] + 256) & 0xff;
            ival <<= 8;
            ival += ((int)sha1Signature[i++] + 256) & 0xff;
            ival <<= 8;
            ival += ((int)sha1Signature[i++] + 256) & 0xff;
            len -= 3;
            sb.Append(Base64Chars[(ival >> 18) & 63]);
            sb.Append(Base64Chars[(ival >> 12) & 63]);
            sb.Append(Base64Chars[(ival >> 6) & 63]);
            sb.Append(Base64Chars[ival & 63]);
        }
        switch (len)
        {
            case 0: // No pads needed.
                break;
            case 1: // Two more output bytes and two pads.
                ival = ((int)sha1Signature[i++] + 256) & 0xff;
                ival <<= 16;
                sb.Append(Base64Chars[(ival >> 18) & 63]);
                sb.Append(Base64Chars[(ival >> 12) & 63]);
                sb.Append(Base64Chars[64]);
                sb.Append(Base64Chars[64]);
                break;
            case 2: // Three more output bytes and one pad.
                ival = ((int)sha1Signature[i++] + 256) & 0xff;
                ival <<= 8;
                ival += ((int)sha1Signature[i] + 256) & 0xff;
                ival <<= 8;
                sb.Append(Base64Chars[(ival >> 18) & 63]);
                sb.Append(Base64Chars[(ival >> 12) & 63]);
                sb.Append(Base64Chars[(ival >> 6) & 63]);
                sb.Append(Base64Chars[64]);
                break;
        }
        //Encode the signature using Base64
        string base64Sha1Signature = sb.ToString();
        return base64Sha1Signature;
    }


text:
Q: Restrict directory listing to only logged in users I am using directory listing with http://adamwhitcroft.com/apaxy/ theme. Which is obviously not part of WordPress. I am looking for a way to allow only registered subscribers to access + download content from those directories.
I have looked into <?php auth_redirect(); ?> but it seems like it only works if the page/post is already part of WordPress ecosystem.
Is there any way to solve this problem?

A: You could try configuring your server to pass or "proxy" all requests to your directory through a php script that can check if the user is logged-in.
Check out the following answer for an example of how to do this:
https://wordpress.stackexchange.com/a/37743/48165


text:
Q: How to manipulate general output (not numbers or variables) in C? Ok so I am doing this assignment in C and I was wondering if C has output manipulators like setw from c++? I know how to manipulate numbers and stuff but I don't know how to manipulate general output. E.g
I want to output "process" and "count" with a width of 5:
printf("Process") and then printf("count") with a width of 5 in between them. How can I do this?

A: I'm not sure setw(n) works like you think it does. If you compile and run this C++ code . . .
#include <sstream>
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << "Process"
              << std::setw(5) << "count" << '\n';
}

then you'll get this output.

Processcount

Use setw(10) instead, and you'll get this output.

Process     count

In C, printf() lets you specify the column width.
/* File: code/c/test.c */
#include <stdio.h>

int main(void) {
  printf("%s", "Process");
  printf("%10s\n", "count");

  return 0;
}

That will print "Process" first, then print "count" in a field that's 10 characters wide. The string "count" itself is five characters. That leaves five blanks between the two strings.
$ gcc -Wall code/c/test.c
$ ./a.out

Process     count

Embedding a tab like this printf("Process\tcount\n"); won't give you five blanks between the two words.

Process count

A: By adding a \t between "process" and "count" will put a tab between the two string.
printf("Process\tcount\n");


text:
Q: clarification on db2 optimiser - Runstas I had a complicated table which has only 7 columns but in production it will have many rows say more than 100,000 rows..
so for this i execute RUNSTATS for two columns one is PK and another is FK..
RUNSTATS ON TABLE WEBSS.P0029_LOCATION  WITH DISTRIBUTION ON COLUMNS (LOC_ID, OUTLET_ID);

after this when i run
SELECT * FROM SYSCAT.COLDIST WHERE TABSCHEMA = 'WEBSS' AND TABNAME = 'P0029_LOCATION'

In result i had 60 rows.. 30 rows each for two columns..
in that i had type is Q and F.. Quantile and Frequeency..
But i need little more input on this.. on what basis they(Q and F) are defined..
on what basis do we need to optimise.
Please pour your suggestions.

A: There are two type of column statistics on DB2, simple ones where you just get the column cardinality and the number of nulls, and distribution stats as you have collected above.
I found simple statistics are better for most applications unless you do literal searches on highly skewed data.
If you have indexes defined on you PKs and FKs you get simple stats with
RUNSTATS ON MYTABLE ON KEY COLUMNS

or
RUNSTATS ON MYTABLE ON ALL COLUMNS

The quantiles are histogram data, and you get by default I think 20 histogram values for each, and the F are the most popular values in your column, and I then you get 10 by default.   You don't need distributions on a PK, as it's unique, and it's unlikely you need them on an FK as well.  Stick to the simple ones first.


text:
Q: ESLint indent rule with tsx file. Set indent rule for HTML node attributes Is there a method to tell the indent rule of ESLint to accept that? What I want
    <BottomNavigation
       showLabels
       value={value}
       onChange= {(…) => {
          …
       }}
    >
       <BottomNavigationAction component={Link} to="/contacts"…
                               icon={<ContactsIcon/>}/>
       <BottomNavigationAction … />
       <BottomNavigationAction
          component={Link} to="/groups" … icon={<GroupIcon/>}/>
    </BottomNavigation>

What it forces me to do: What it forces me
    <BottomNavigation
       showLabels
       value={value}
       onChange= {(…) => {
          …
       }}
    >
       <BottomNavigationAction component={Link} to="/contacts"…
          icon={<ContactsIcon/>}/>
       <BottomNavigationAction … />
       <BottomNavigationAction component={Link} to="/groups" …
          icon={<GroupIcon/>}/>
    </BottomNavigation>

My indent rule values: Indent rule
    "indent: [
      "error",
      4
     ],

I checked the documentation of the indent rule but they never mention HTML nodes. So I'm a bit lost there. (ESLint documentation on indent)


text:
Q: How can I answer this," How is life on work front?" I mean work front is just confusing me .

A: It is a frequently-used metaphor, which breaks down one's life into a series of military "fronts" e.g. home front, work front, leisure front, etc. It is often used where a person is known to be going through difficult times - so they may be looking at life in terms of a military campaign.
So "How's life on the work front?" simply means "How is life for you at work right now?"

A: Well work front can Also be used/called things such as the following. Job, used in phrases such as *Time to get back to reality of 'making that money!!" Or can be used like this, "I am so not looking forward to getting back to Adulting tomorrow!!" Adulting (v): to do grown up things and hold responsibilities such as, a 9-5 job, a mortgage/rent, a car payment, or anything else that makes one think of grown ups. Or here is other words in relation to working. Career structure, function, labor, livelihood, occupation, position, service, slot, walk of life, working life, work load. Hope I was somewhat of a assistance to your question.


text:
Q: Repository not extending JpaRepository I'm new to using JPA, I am reading tutorials online and all of them extend from JPARespository like below
from this page
https://www.callicoder.com/spring-boot-jpa-hibernate-postgresql-restful-crud-api-example/
package com.example.postgresdemo.repository;

import com.example.postgresdemo.model.Answer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public interface AnswerRepository extends JpaRepository<Answer, Long> {
    List<Answer> findByQuestionId(Long questionId);
}

But in my project Eclipse complains with the following
The type JpaRepository<Property,Long> cannot be the superclass of PropertyRepository; a superclass must be a class

Below is my class
package realestate.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import realestate.model.Property;

import java.util.List;

@Repository
public class PropertyRepository extends JpaRepository<Property, Long> {

}

A: Basically JPA Repositories are interfaces.
In your code you declared a class and extending it with an interface.
A Class can implement an interface, but not extends it.
So please change Class declaration to an interface as below.
@Repository
public class PropertyRepository extends JpaRepository<Property, Long> {

}

to
@Repository
public interface PropertyRepository extends JpaRepository<Property, Long> {

}


text:
Q: Angular 2 Conditional Template? I have a conditional template for a webpage that may use a different grid component depending on the id that was passed in
The webpages are setup like this
www.mywebpage.com/referenceGrid/85
or
www.mywebpage.com/referencePage/75
Im listening to the page change id through params service
ngOnInit(): void {
  this.route.params.subscribe(
    (params: Params) => {
      this.pageid = params['id'];
      this.gridData = [];
    }
  );
}

They both share the same component.ts file. Lets call it base.component.ts.
@Component({
  selector: 'app-griddata',
  template: `
      <div [ngSwitch]="isCertainId">
        <template [ngSwitchCase]="true"> ${require('./specialId.component.html')} </template>
        <template ngSwitchDefault> ${require('./default.component.html')} </template>
      </div>`
      ],
})

I use ViewChildren to find the grid. They are both called #grid
public isCertainId: boolean = false;
@ViewChildren('grid')
public childrenComponent: QueryList<GridComponent>;
  private grid: GridComponent;

The child cant be found until ngAfterViewInit so I call it here
public ngAfterViewInit(): void {
  this.isCertainId = (this.pageid === '85' || this.pageid === '16');
  this.childrenComponent.changes.subscribe((comps: QueryList<GridComponent>) => {
    this.grid = comps.first;
  }
 });
}

This works fine on initial screen load, however if the user selects a different webpage( pageid 85 to pageid 75) the template conditional statement doesn't get hit again as both pages use the same component.ts
How can I get that [ngSwitch] to be hit on a different page load?


text:
Q: Overfull \hbox when typing inline Math equations. Can we make it adaptive to go to the next line? Hey guys so below is my Tex command:
\subsection{Bicubic Interpolation}
This is an extension of the cubic interpolation method in a two dimensional regular grid.
Given the function values $f$ and the derivatives $f_x$, $f_y$ and $f_{xy}$ are known at the four corners
around the four corners $(0,0), (0,1), (1,0), (1,1)$ of the unit square.
The interpolated surface can then be expressed as:

A: Inline math just beaks at infix binary operators (like +) or relations (like =) or explicit linebreak penalties added by \linebreak[2] or similar commands.
But here the list of coordinates is part of the sentence structure not mathematics so just as the comma after $f_x$ you can mark it up with text commas so you get normal sentence comman spaces and line break possibilities:
$(0,0)$, $(0,1)$, $(1,0)$, $(1,1)$


text:
Q: Why is Python Preinstalled on Ubuntu? Why is Python Preinstalled on Ubuntu?

*

*Does the operating system depend on Python?

A: Try running:
apt-cache rdepends python | grep -v python | wc -l

Since Ubuntu 20.04 uses python3 for default, run:
apt-cache rdepends python3 | grep -v python | wc -l

This basically says "Count the number of packages that depend on Python, NOT counting python specific packages". On my system it's well over 1000 other packages - safe to say Ubuntu depends pretty heavily on Python.

A: Looking at 20.04, the technical reason is that ubuntu-minimal depends on python3.  It would be tough to run Ubuntu without ubuntu-minimal as its description is

This package depends on all of the packages in the Ubuntu minimal
system, that is a functional command-line system with the following
capabilities:

*

*Boot

*Detect hardware

*Connect to a network

*Install packages

*Perform basic diagnostics

It is also used to help ensure proper upgrades, so it is recommended
that it not be removed.

While I expect most of the core Linux programs don't require python, I believe a lot of software that Ubuntu (Canonical) writes is done in python.  Things like ubuntu-advantage, landscape, cloud-init, and netplan.
Another common dependency is that there are python apt libraries used by a number of packages.  For example, unattended-upgrades is written in python

A: Ubuntu works with python, and without python Ubuntu won't work (actually, I never tested it, but I think it won't work). That's why it's already installed when you load Ubuntu.


text:
Q: What is a good term to describe different ways to view the same data? Software gives us different ways to view the exact same data with each "view" targeted at a specific task.
For example, in Stack Exchange, questions can be viewed in

*

*The review queue where you only see questions listed which need to be reviewed

*The main question list where everything is listed

*Edit history pages where you can see and compare every version of a question

*Mods have access to vote fraud tools

*etc

Every one of those "views" is highly customized for the task at hand showing only those pieces of the data that matter at that moment.
Is there a good term to describe this feature without all the long winded explanation?

A: View strikes me as being the usual term. Other possibilities are view(ing) mode, display mode or window, depending on the exact context.

A: I would just say the data is in a different format.  Techies and non-techies can understand this.

the way in which something is arranged or set out.

A: The term "perspective" comes to mind.

A: "Layout" or "Perspective" or perhaps just "View"

A: Perhaps something like "polyview" or "polyperspective"? Poly meaning multiple, and then slapping any synonym for angle/viewpoint/dimension you like.

A: Perhaps "viewpoint"?
It uses the customary word "view" but like "perspective" it emphasizes that there is a whence, a position from which one is looking.

A: One could say that the services you have enumerated are all abstractions of the single underlying relational database.

*

*The quality of dealing with ideas rather than events

*The process of considering something independently of its associations or attributes

The word also has special meaning in the context of computer systems/programming.

In computer science, abstraction is the process of separating ideas from specific instances of those ideas at work


text:
Q: Docker log without new line I'd like to have a container outputting dots like a progress bar. Like this:
....... done!
dots are produced with echo -n '.' and done with echo " done!"
The problem is that docker logs appears to only output whole lines. So all dots will appear at once along with the done part.
I tried stdbuf -o0 echo -n '.' and docker run myimage stdbuf -o0 myscript.sh, but to no luck.
Is there a way to achieve this?


text:
Q: Any suggestion on the best way to build a serial port script? I need to configure daily dozens of devices through serial port. The config is at it follows:

*

*Wait for boot (i.e. a specific line appears).

*Enter a sequence of commands.

*Do a 'print' to check everything is right.

*Move to next device.

It doesn't seem complicated, and I really need to automate it. I'm not an expert programmer, but I find my ways.
What can you suggest me to get started? Where should I look on? In particular, any great API out there that would do the dirty job for me? I'm using Windows, but I could get Linux too if really needed.
The one language that I've studied is C. But I'm open to something new as long as it can be done fast.
Thank you in advance.

A: That looks like a task for expect:
#!/usr/bin/expect
set timeout 20
spawn "terminal-program"
expect "a specific line"
send "sequence_of_commands"
expect "prompt >"
send "print"

and put that in a bash-loop.


text:
Q: PHP / HTML - re organize array I have a array with ID values like this [2,34,7,46,16,19 ...] etc
each ID points to more data which I display with html like:

    content from 2
    content from 34
    content from 7

    content from 46
    content from 16
    content from 19

  ...

notice that in this case there are 3 entries into each list item.
How can share entries from the array to each
 in a such way that there are always exactly 5 list items?
for eg, if the array has 15 items, each
 has 3 items, or if array has 9 items, each
 has at least 1 entry (4 of them will have 2)

A: array_chunk($myArray, count($myArray) / 5) should work. You might need to tweak it a little, such as a ceil or floor on the count/5, but that's the right direction.
http://php.net/manual/en/function.array-chunk.php


text:
Q: how to get from parameters more than one word in each paramater (discord.py) my question is simple ,and i don't know if it has been answered before because i couldn't find an answer.So i'm trying this idea about when someone types a word the bot would automatically reply with a specific reply, i'm making a command to add these things, but i'm having a problem, which is that each parameter gets only the first and the second input,and i want to split them from each other, here's a small example:
@client.command()
async def areply(ctx,word, info):

A: You can add * which will take every word after the second parameter as user input, for example:
@client.command()
async def areply(ctx, word, *, info):
    await ctx.send(f"The word provided was: `{word}` and the information provided was: `{info}`")

Lets say a user typed !areply Example This is test info, the bot will output the following:

The word provided was: Example and the information provided was: This is test info


text:
Q: Различия между Action Script и Flash Поясните разницу между этими двумя языками, какой где применяется?
A: ИМХО: Flash - это не язык, ближайшее слово для описания - платформа, набор средств для создания медиа контента, игр, приложений, и их доставки потребителю.
А ActionScript (3), да язык, для создания приложений/программ исполняемых на Flash платформе. От баннеров до игр и тяжелых насыщенных корпоративных приложений (Flex).
Как платформа (Flash а следовательно и ас3) может применяться/запускаться практически везде, веб/соц приложения, desktop (win/mac), мобильные (android/ios).
Думаю что в связи с приходом приставок последнего поколения на х86/х64 архитектуру (слава богу), следует скоро ждать появления средств разработки Flash контента и для этих систем. (вернее средства и среды есть, нужен проигрыватель / вирт машина)
A: Flash - это не язык, это технология, которая позволяет на веб страница в интернете размещать различный контент(от игр, до видео).
AS3 - это язык с помощью, которого можно создавать такой контент.
.swf - это формат(особая структура) файла, который и есть тот самый контент, который подкладывается.

A: ActionScript — объектно-ориентированный язык программирования, один из диалектов ECMAScript, который добавляет интерактивность, обработку данных и многое другое в содержимое Flash-приложений. ActionScript исполняется виртуальной машиной (ActionScript Virtual Machine), которая является составной частью Flash Player. ActionScript компилируется в байт-код, который включается в SWF-файл.
Ссылка на wiki >>>
Ide поддерживающие action script 3.0: Flash Builder, Flash Develop, Eclipse, Astella и др.


text:
Q: Make SQL Server 2005 accessible via Internet I have an application that runs on a client's server built on a SQL Server 2005 database.
We have now developed an ASP.NET v2 application which connects to this database.  This web application will be hosted on an ISP's server but needs to access the SQL Server database on the client's server.
The client's server has a firewall and so forth so I assume it should be possible to make the SQL Server accessible via the Internet but of course I am woriied about security.  Can someone point me to some best practices to achieve this.

A: can you develop a web service to run on the client's server? you probably want to avoid opening SQL Server to the world.

A: Best practice: DO NOT DO IT. Lets leave security concerns aside - the ip delay will significantly slow you down. Try it out first, but the large ping times MAY be terrible for you.
THat said, all you noramlly have to do (not assuming reconfiguration) is to allow:
* The server somehow to be reached
* On Port 1433 (default port).
Use A VPN or IPSEC to secure traffic and make sure that "accessible through the internet" is not "accessible for every idiot out there". The ISP admin should be able to help you, or the customers admins. But I would not do it - the performance may not be to your liking. Test performance out first.


text:
Q: python scapy dns sniff есть задача, сделать на python scapy мониторинг dns запросов на локальной машине.
Что бы просто записывать в файл домены сайтов куда обращалась локальная машина.
В интернете не нашел такого, там все про атаки и подмены пакетов, а мне нужно просто мониторить куда обращается машина.
Т.е. если я локально запускаю этот скрипт и через браузер захожу в google, то в файле должно появится time - google.ru

A: Изначально нужно установить scapy командой:pip install --pre scapy[basic]
А затем, можно попробовать так:
import subprocess

from scapy.all import sniff

def ip_iface():
    com_run = subprocess.check_output('ip -h -br a | grep UP', shell=True).decode()
    default_interface = com_run.split()[0].strip()
    local_ipv4 = com_run.split()[2].strip().split("/")[0]
    local_ipv6 = com_run.split()[3].strip().split("/")[0]
    return default_interface, local_ipv4, local_ipv6

def packet_sniff(packet):
    qname = packet['DNS Question Record'].qname.decode()
    print(f'Запрос: {qname[0:-1]}')

def main():
    from os import getuid
    if not getuid() == 0:
        print('\n[+] Запустите скрипт с правами суперпользователя!\n')
        return
    print(f'[+] Анализ пакетов... \n')
    sniff(iface=ip_iface()[0], filter='dst port 53', count=0, store=False, prn=packet_sniff)

if __name__ == "__main__":
    main()

у меня Linux, потому скрипт писал под него. Но, если у вас Windows, скрипт будет работать и под ним. Нужно просто из main() удалить все, оставить только sniff.
Из sniff удалить iface, так как это фильтр, который фильтрует запросы только к активной сетевой карте. Ну и соответственно, уберите функцию ip_iface().
В Linux скрипт нужно запускать с повышенными правами, то есть от суперпользователя, так как scapy работает с повышенными правами. А под Windows, если не ошибаюсь, запускать от имени администратора не обязательно. Единственное, что под Windows нужно будет для scapy, чтобы он работал, установить Npcap, в дополнение к scapy.
Ну и скрипт, с учетом всего удаленного будет выглядеть так:
from scapy.all import sniff

def packet_sniff(packet):
    qname = packet['DNS Question Record'].qname.decode()
    print(f'Запрос: {qname[0:-1]}')

def main():
    sniff(filter='dst port 53', count=0, store=False, prn=packet_sniff)

if __name__ == "__main__":
    main()

Я тут немного "поиздевался" над скриптом )). В итоге получилось примерно это:


text:
Q: Moments of an exponential random variable
If $X$ is an exponential random variable with mean $\frac{1}{γ}$, show that $\\E[X^k]=\frac{k!}{γ^k},\,\,$ for $\, \, \, k=1,2,3$...

How would I go about proving this?

A: The induction step uses integration by parts.
$$E[X^{k+1}] = \int_0^\infty x^{k+1} \gamma e^{-\gamma x} \mathop{dx}
= (k+1)\int x^k e^{-\gamma x} \mathop{dx} = \frac{k+1}{\gamma} E[X^k].$$

A: Moment generating function of the exponential RV is $$\frac{1}{1-t\gamma^{-1}},\,t<\gamma$$ So $$M_X(t)=\mathsf{E}\{e^{tX}\}=1+t\mathsf{E}\{X\}+\frac{t^2\mathsf{E}\{X^2\}}{2!}+\frac{t^3\mathsf{E}\{X^3\}}{3!}+\cdots=\sum_{k=0}^{\infty} t^k\frac{\mathsf{E}\{X^k\}}{k!}=\frac{1}{1-t\gamma^{-1}}$$
Expanding the RHS using
$\frac{1}{1-x}=\sum_{n=0}^{\infty}x^n,\,|x|<1$ for $x=t\gamma^{-1}$
$$\frac{1}{1-t\gamma^{-1}}=1+t\gamma^{-1}+(t\gamma^{-1})^2+\cdots=\sum_{k=0}^{\infty} t^k(\gamma^{-k})$$
and the coefficients of $t^k$ should be identical.  That is
$$\gamma^{-k}=\frac{\mathsf{E}\{X^k\}}{k!}\Rightarrow \mathsf{E}\{X^k\}=\gamma^{-k}k!$$


text:
Q: SmartyStreets jQuery.liveaddress plugin, how to unbind events I'm using smarty streets jquery.liveaddress plugin in an angular single page app.  I need to unbind all of the event listeners from the liveaddress instance when I transition to next page. Right now, if I come back to the page, all events are fired twice, then the next time on page, three times.
I've tried everything i can think of. My last solution was to unbind all of the event names from the $(document) because it looks like that is where the plugin is attaching all of the events to. but even that didn't work.
jQuery(document).unbind("AddressChanged");
        jQuery(document).unbind("AutocompleteUsed");
        jQuery(document).unbind("VerificationInvoked");
        jQuery(document).unbind("RequestSubmitted");
        jQuery(document).unbind("ResponseReceived");
        jQuery(document).unbind("RequestTimedOut");
        jQuery(document).unbind("AddressWasValid");
        jQuery(document).unbind("AddressWasAmbiguous");
        jQuery(document).unbind("AddressWasInvalid");
        jQuery(document).unbind("AddressWasMissingSecondary");
        jQuery(document).unbind("OriginalInputSelected");
        jQuery(document).unbind("UsedSuggestedAddress");
        jQuery(document).unbind("InvalidAddressRejected");
        jQuery(document).unbind("AddressAccepted");
        jQuery(document).unbind("Completed");

A: Ok for anyone trying to implement SmartyStreets jquery.liveaddress plugin in an angular application.
The trick was to not register anonymous event handlers.
In my case I was instantiating SmartyStreets in a directive, so put all the eventHandlers on scope and call liveAddress.deactivate() upon $destroy. No more duplicate events.

A: In jQuery, event handler functions are stored in an array. Therefore, unbind() function looks just for the function in the aforementioned array. It further means that you can only unbind() event handlers which are already added with bind().
Check out jQuery documentation on .bind()


text:
Q: Formalisation of a given sentence using quantiifiers The question is:

Minesweeper is a single-player computer game invented by Robert Donner in 1989. A unary predicate mine is defined, where $mine(x)$ means that the cell $x$ contains a mine
Consider the statement: $$\exists x_1, \dots , \exists x_n \left(\bigwedge_{i=1}^{n} \text{mine}(x_i) \wedge \forall y \left( \text{mine}(y) \to \bigvee_{i=1}^{n} y = x_i\right) \right)$$
Which of the following statements is the correct interpretation of the above formula?
a.There are exactly n mines in the game
b.There are at least n mines in the game
c. There are at most n mines in the game

The way I did this was that the first inner predicate means that are $n$ mines present, implying that there are at least $n$ mines. The second part of the predicate says that if it is a mine, it has be present in one of the $n$ cells, thus implying that there are at most $n$ mines. Hence, the answer should be that there are exactly $n$ mines.
However, the answer given is C i.e there can be at most $n$ mines. One possible reasoning I could think for this is that the second predicate doesn't mean all the $x_i$s have to be different, so there can be less than $n$ mines. However, I don't know why this should be true.
Is my solution correct or is it possible that two of the $x_i$s can refer to the same cell?

A: The mines are precisely the $x_i$, so there are at most $n$ of them (with exactly $n$ iff the $x_i$ are pairwise distinct, which isn't given).


text:
Q: Keeps getting EOF expected error I have this problem with SOAP that I can't seem to solve.
No matter what I try, then I keep getting this error:

500 - Internal server error. There is a problem with the resource you
  are looking for, and it cannot be displayed.

When digging further down the error code I'm told there is a EOF expected error?
Hope that some of you might be able to help me
<%
On Error Resume Next
Dim objXMLHTTP : set objXMLHTTP = Server.CreateObject("Msxml2.XMLHTTP.3.0")
Dim strFunction
Dim strRequest
Dim strResult
Dim strName
Dim strFirstName
Dim strLastname
Dim strAddress
Dim strZipCode
Dim strCity
Dim strTelephone
Dim strTelephone2
Dim strTelephone3
Dim strTelephone4
Dim strEmail
Dim strExtFields
Dim strStdFields
Dim CampaignID
Dim Page

Page = Request.Form("Page")
CampaignID = Request.Form("CampaignID")
StrName = Request.Form("Name")
StrTelephone = Request.Form("Phone")

strRequest = ""
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"">
<Body>
<InsertNewCustomer xmlns=""http://api.ivocall.dk/ivocallservice.asmx"">
<Login>Loginname</Login>
<Password>Password</Password>
<ClientID>1323</ClientID>
<IDPassword>ag4bghsitm8gatddbpt34qjndjrbsla</IDPassword>
<CampaignID>"& campaignid &"</CampaignID>
<Name>"& StrName &"</Name>
<Firstname></Firstname>
<Lastname></Lastname>
<Address></Address>
<City></City>
<ZipCode></ZipCode>
<Telephone>"& StrTelephone &"</Telephone>
<Telephone2></Telephone2>
<Telephone3></Telephone3>
<Telephone4></Telephone4>
<email></email>
<ExtFields>landingpage="& page &"</ExtFields>
<StdFields></StdFields>
<UserName></UserName>
</InsertNewCustomer>
</Body>
</Envelope>"

objXMLHTTP.open "post", "" & "http://api.ivocall.dk/ivocallservice.asmx" & "", False
objXMLHTTP.setRequestHeader "Content-Type", "text/xml; charset=UTF-8"
objXMLHTTP.setRequestHeader "Content-Length", Len(strRequest)
objXMLHTTP.setRequestHeader "SOAPAction", "http://www.ivocall.dk/ivocallservice/InsertNewCustomer"

'send the request and capture the result
Call objXMLHTTP.send(strRequest)
strResult = objXMLHTTP.responseText

'display the XML
response.write strResult
response.write strRequest

If Err.Number <> 0 Then
        Response.Write (Err.Description)
ELSE
        Response.Write ("task done")
        Response.End
End If
%>

I really hope some of you can help me out her?

A: You use inline code-tags.
<%

They do not contain any imported namespaces.
Additionally, you seem to want to copying XML into strRequest, but you're not properly escaping it, plus VB.NET (which is what you're using, not C#) doesn't support multiline strings.
And why do you use
Server.CreateObject("Msxml2.XMLHTTP.3.0")

You can use the normal WebRequest class, instead of an ActiveX-Object. And if you want to do it client-side, you need to use JavaScript (AJAX).
If you're doing a cross-domain request, you need to use CORs (and a browser supporting CORs), or you need to write a proxy that does the request for you.
Additionally, did you try adding a web-reference to your project ?
Visual Studio will automagically download the WSDL and generate the wrapper classes. Why do you want to do it by hand ? ...
Additionally, if you want to embed code in the ASPX page, do it in a "script"-tag using runat="server":
<%@ Register TagPrefix="RS" Namespace="Microsoft.ReportingServices.WebServer" Assembly="ReportingServicesWebServer" %>
<%@ Page Language="C#" AutoEventWireup="true" Inherits="Microsoft.ReportingServices.WebServer.ReportViewerPage" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<script type="text/C#" runat="server">

    protected void SetDocumentMode()
    {
        if(System.Web.HttpContext.Current == null || System.Web.HttpContext.Current.Request == null || System.Web.HttpContext.Current.Request.Browser == null || System.Web.HttpContext.Current.Request.Browser.Browser == null)
            // return "<null>";
            return;

        if (!StringComparer.OrdinalIgnoreCase.Equals(System.Web.HttpContext.Current.Request.HttpMethod, "GET"))
            // return "<notget>";
            return;

        // fu IE 11
        if(System.Web.HttpContext.Current.Request.Browser.Browser == "IE" || System.Web.HttpContext.Current.Request.Browser.Browser == "InternetExplorer")
        {
            if(System.Globalization.CultureInfo.InvariantCulture.CompareInfo.IndexOf(System.Convert.ToString(System.Web.HttpContext.Current.Request.QueryString), "stylesheet", System.Globalization.CompareOptions.IgnoreCase) == -1 )
            {
                System.Web.HttpContext.Current.Response.Write(@"<meta http-equiv='X-UA-Compatible' content='IE=5'>
");
                //return "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=5\">"; // IE5-Quirks when no custom stylesheet (=not in iframe)
            }
            else
                System.Web.HttpContext.Current.Response.Write("<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>");
                // return "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">"; // Switch to Standards mode when a custom stylesheet is set(=in iframe)
        }

        // return "<not ie: " + System.Web.HttpContext.Current.Request.Browser.Browser + ">";
        //return "";
    }
</script>

[...]
<%SetDocumentMode(); %>

Are you actually using ASP instead of ASP.NET ?