Classifying Group of Order 26 up to Isomorphism

Question: Classify all groups of order 26.
I know that the answer should be the dihedral group of order 13, as well as $Z13XZ2$; however, I'm not sure a good way to show that the dihedral group should be included as well using Sylow theorems without using the semi direct product. Any suggestions?
Comment: Any subgroup of index 2 must be normal, so your $13$-Sylow must be normal. Therefore the group must be some kind of semidirect product of $Z_{13}$ and $Z_2$.
Comment: Yes, if your copy of $Z_2$ is $\{1,a\}$, you just need to check what $axa^{-1}$ must be (in various cases) for each element $x$ of your $13$-Sylow. That way, you can obtain a complete description of the group.
Comment: Thank you! I was actually wondering if there was a way to show without using semi direct product, since we have not covered it in class yet. I've edited the question to reflect this.
Answer: Let $G$ be a group of order $26=2\cdot13$.
If $G$ is abelian, then by the fundamental theorem of finitely generated abelian group. $G\cong \Bbb{Z}_2\times \Bbb{Z}_{13}\cong \Bbb{Z}_{26}$.
Suppose now $G$ is non-abelian. By Cauchy's Theorem, there is a subgroup $H$ of order $13$ and a subgroup $K$ of order $2$. Clearly, $H$ and $K$ are cyclic. Write $H=\langle h\rangle$ and $K=\langle k \rangle$. Since $H$ is of index $2$ in $G$, $H$ is a normal subgroup of $G$. Hence $HK\leq G$. Since $(|H|,|K|)=1$, by product formula, $|G|=|HK|$, so that $G=HK$.
Note that $khk^{-1}\in H$. Hence $khk^{-1}=h^i$ for some $i$. Then $h=k^2hk^{-2}=h^{i^2}$. Hence $i^2\equiv 1\bmod 13$, which means that $i\equiv \pm1 \bmod 13$. Since $G$ is non-abelian, we can only have $khk^{-1}=h^{-1}$. Therefore $G$ is a dihedral group of order $26$.
General case:

If $G$ is a group of order $2p$ where $p$ is a prime, then $G$ is either cyclic or dihedral.


Question in complex numbers from GRE

Question: This is a question motivated from GRE subgect test exam.
if f(x) over the real number has the complex numbers $2+i$ and $1-i$ as roots,then f(x) could be:
a) $x^4+6x^3+10$
b) $x^4+7x^2+10$
c) $x^3-x^2+4x+1$
 d) $x^3+5x^2+4x+1$
 e) $x^4-6x^3+15x^2-18x+10$
What I thought at first was to calculate $(x-2-i)(x-1+i)$ and find the polynomial that is divisible by it.Unfortunately it turns out that $(x-2-i)(x-1+i)$ is complex polynomial which makes thing harder to calculate and since this is a multiple choice question with very limited time there must be an easier way. Then I thought maybe it will be easy if I write the complex numbers in polar form and check explicitly if they are the roots.But I don't think that's a very efficient way as well. Then I noticed that the question ends with "$f(x)$ could be" which may suggest that there is a way eliminate the wrong choices, however I have no idea what to eliminate or not.
Does anyone have any ideas?
Thanks in advance
Answer: I think we should nortice that- in these cases- if $z$ is a root so is $\bar{z}$. And secemdly, I saw a nice practical problem in a book saying that:
If we have $a_0z^n+\cdots+a_n=0$ where $a_0\neq0$ then the sum of all roots and the product of all roots are $$-a_1/a_0$$ and $$(-1)^na_n/a_0$$ respectively. I hope you can solve the problem by yourself.
Comment: Thanks for your answer, but how do we know that if $z$ is a root then it's conjugate is also a root.?
Comment: Y r Welcome! You can show it easily or search this simple fact on the web. It is easy.
Answer: By the complex conjugate root theorem,
en.wikipedia.org/wiki/Complex_conjugate_root_theorem
if 2+i is one root, the other root is its conjugate 2-i, the quadratic would be x^2-4x+5, the other quadratic is x^2-2x+2, multiply them both to get f(x) as option e
Comment: Thanks a lot! I had no idea about that theorem
Answer: 1.
$(x-(2-i))(x-(2+i))$
$x^2-x(2+i)-x(2-i)+(2-i)(2+i)$
$x^2-2x-xi-2x+xi+(4-2i+2i+1)$
$x^2-4x+5$
2.
$(x-(1-i))(x-(1+i))$
$x^2-x(1+i)-x(1-i)+(1-i)(1+i)$
$x^2-x-xi-x+xi+(1+i-i+1)$
$x^2-2x+2$
3.
$(x^2-4x+5)(x^2-2x+2)$
$x^4-2x^3+2x^2-4x^3+8x^2-8x+5x^2-10x+10$
$x^4-6x^3+15x^2-18x+10$

Question in complex numbers from GRE


Different kinds of capos

Question: I recently saw a capo (I think) that had something like teeth(?) that the player changed while he played. I'm not sure what its purpose was. (I'm really not sure how to explain it) -- If I'm not mistaken, you choose what chords to capo and which to leave open.
My question is this: How many different types of capo exist?
(minor addendum) Here is the capo I was talking about:
Answer:
Clamp capo (above called a normal capo) is a spring capo that clamps over the strings. Kysers are my preferred clamp capo these days.
Shubb capo uses a screw and a locking lever to attach the capo to the guitar neck.
Band capo is a capo secured by an elastic or fabric band that clamps over the strings. You can slide an elastic band capo up and down the neck without removing it.
Partial capo fits over a set of strings.  These can be made by cutting chunks of rubber out of a standard clamp capo or by using a clamp capo (such as for banjos) that is narrower than a guitar neck. Shubbs and Kysers are commonly used as partial capos. I have seen in performance up to two partial and one full clamp capo on a guitar neck.
Rail spike capo often used by banjo players for capo-ing the drone 5th string.  It's a small L-shaped nail nailed into the banjo fretboard.  The banjo player tucks the string under the L.
G-band capo is a small plastic clamp that capos outer guitar strings.
Comment: That's good, there's a distinction between the Kyser style, which use a spring (which will squeeze as tight as it's built and might pull the strings sharp, but are easy to take on and off) and a screw (Shubbs being the first to mind) which can be adjusted to squeeze only as tight as needed. I know of a screw-tightened capo that wraps around the neck and is left "tightened" to the nut when not in use.
Comment: Also, band-style capos need not be elastic; my old band-style capo has a non-elastic nylon band and is similar to this: http://www.sweetwater.com/store/detail/ProCapoCurv/
Answer: I think @Tim already answer your first question.
Yes, it's a spider capo, which can grab only selected strings, so you can do some cool stuff.
There are:

Normal capo, obviously which holds all of the strings.
Slider capo or roller capo, it can slide easily from one fret to another fret
without releasing the capo from holding the neck.
Spider capo, I explained that above.

By the way, the normal capo, the back side of it, you can use it as 3-string capo or you can use the front side as banjo capo which holds 5-string.
Answer: Can't answer your question per se, but to enlighten  about that particular capo. It's a SPIDER, and can be used on just about any guitar, including, obviously, bass (Up to 6 string!). The idea is that it can, if so desired, capo as many or few strings as necessary. For instance, if one wanted,say, the E and A on bass to remain as open low notes, but needed to capo 5th fret on D and G, it could be set up thus.Then one could have effectively different tunings. Why, I'm not sure, as if one wanted to play E open and G# and B on the top two strings, one could do it anyway.And if one wants to play high up, one maybe should be on a guitar...  bottom four strings, with a capo should one wish to go even higher.Frets may be too narrow then, though.
The most rudimentary capo for guitar is a pencil and a rubber band. A bendy pencil works best on a cambered fingerboard.Googling 'capo' brings up all sorts, mostly doing the same job, but some in very ingenious ways, like the G7 - how does that work then ?
After listening to the gorgeous playing in the clip, I wonder what the capo was doing. If it moved everything up one fret, why bother. If it was to re-tune a string or two, why not just re-tune a string or two? Or did I miss something? There is a probability that the 'teeth' can be flicked over to produce a different tuning, not sure.
Comment: If you can capo some strings and leave some of them open like you say, it wouldn't be same as retuning. The tuning would stay the same but open strings would sound differently. I can see how it's useful.
Comment: One of the purposes of a capo, on an ordinary guitar, is to take the place of a barre finger. Doing so tends to make the 'open' strings sound 'open'.There's a subtle difference, but there shouldn't be - some of my guitars have a zero fret which theoretically means open, they sound the same as fretted, particularly with a capo.
Comment: Caught it -- right at 1:33 he flips off the "tooth" that was fretting the D string. So he was basically using it as a single-string and instant-cancel capo.
Answer: I highly recommend the following site:
http://www.sternercapo.se/Capomuseum/
I'm sure I didn't expect that there would be a well-curated Capo Museum online. The historical perspective is unmatched.
Enjoy!

Different kinds of capos


curl not redirecting as expected

Question: Any idea why this function is not redirecting to paypal.com and instead I am staying on the same page? curl is activated on the server, safe mode is off and openbasedir is turned off too.
function curl_post($url, array $post = NULL, array $options = array())
{
    $defaults = array(
        CURLOPT_POST => 1,
        CURLOPT_HEADER => 0,
        CURLOPT_URL => $url,
        CURLOPT_FRESH_CONNECT => 1,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FORBID_REUSE => 1,
        CURLOPT_TIMEOUT => 4,
        CURLOPT_POSTFIELDS => http_build_query($post)
    );

    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
}
curl_post("https://www.paypal.com/cgi-bin/webscr",$_POST);

Any idea what am I doing wrong?
Comment: AS far as I know, curl just makes http requests. It doesn't redirect, or act as any kind of web browser.
Answer: After you make curl request:
foreach ($parameters as $key => $value) {
    $requestParams[] = $key . '=' . $value;
}
$requestParams = implode ('&', $requestParams);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestParams);
curl_setopt($ch, CURLOPT_RETURNTRANSFER);
curl_setopt( $ch, CURLOPT_AUTOREFERER, true);
$result = curl_exec($ch);

You should get exact url, to know where you should be redirected:
$location = curl_getinfo($ch)['redirect_url'];

And then redirect:
header('Location: '. $location);

Answer: cURL is just a library for initiating and firing HTTP and FTP requests.
Your code just sends a HTTP POST request to the PayPal server.
In order to redirect the user, send a Location header (before any output!):
header('Location: https://www.paypal.com/...');

Comment: Could I send the post information as well? Could you use it with my code?
Comment: @JimmyHendrikz This is not possible, see here for further information: http://stackoverflow.com/questions/5576619/php-redirect-with-post-data

curl not redirecting as expected


How to delete related data from child table when I delete specific data from parent table in DB using the delete button in windows form c#

Question: I have many tables in this database. Two of them being Student and StudentAttendance.
In Student table, Id is the primary key which is auto-generated and in the StudentAttendance table
AttendanceId is the primary key and StudentId is foreign key. Now the requirement is that If I delete any student by giving its registration number in the textbox and then clicking the delete button then student record with this id should also get deleted from the StudentAttendance table.
I cannot do this with CASCADE DELETE. I have to do this with a query.
I am trying this code but this is giving me error and not working.
private void studentDeleteButton_Click(object sender, EventArgs e)
        {
            var con = Configuration.getInstance().getConnection();
            SqlCommand cmd = new SqlCommand("Delete from Student Where RegistrationNumber = @RegistrationNumber", con);
            cmd.Parameters.AddWithValue("@RegistrationNumber", addStudentRegTextbox.Text);
            cmd.ExecuteNonQuery();
            SqlCommand cmd1 = new SqlCommand("Delete from StudentAttendance Where StudentId = id", con);
            cmd1.ExecuteNonQuery();
            MessageBox.Show("Record has been Deleted successfully!");

}
Comment: You can both together with a stored procedure, or a trigger, or a session from your client that executes both DML statements itself in a transaction (all of these should be in a transaction) of a CASCADE DELETE.  Note: it's generally *easier* to delete the children *first* and then the parent (in part because of typical foreign key constraints), but you can do it either way.
Answer: yur code should work fine but you are missing the "@" for the id in the second delete and you can add parametrised to your sql to avoid sql injection
 private void studentDeleteButton_Click(object sender, EventArgs e)
                {
                    var con = Configuration.getInstance().getConnection();
                    SqlCommand cmd = new SqlCommand("Delete from Student Where RegistrationNumber = @RegistrationNumber", con);
                    cmd.Parameters.AddWithValue("@RegistrationNumber", addStudentRegTextbox.Text);
                    cmd.ExecuteNonQuery();
                    SqlCommand cmd1 = new SqlCommand("Delete from StudentAttendance Where StudentId = @id", con);
                    cmd1.Parameters.AddWithValue("@id", addStudentRegTextbox.Text);
                    cmd1.ExecuteNonQuery();
                    MessageBox.Show("Record has been Deleted successfully!");

Comment: But i am not taking id in textbox as Ive mentioned it is auto-generated
Comment: you can delete based on any giving values,first try to delete record with the foreign key then delete it from wherever it is primary key
Answer:
Firstly, check and make sure your mysql database uses InnoDB engine;
Then, check if you have set the physical foreign-key relation. Theoretically you should add this sql sentence when you create your child table:

ADD CONSTRAINT `atten_stu_fk` FOREIGN KEY (`StudentId`) REFERENCES `student` (`id`) ON DELETE CASCADE;

Maintain the foreign key relation by the code:
private void studentDeleteButton_Click(object sender, EventArgs e) {
            var con = Configuration.getInstance().getConnection();
            SqlCommand cmd = new SqlCommand("Delete from StudentAttendance Where StudentId = id", con);
            cmd.ExecuteNonQuery();
            SqlCommand cmd1 = new SqlCommand("Delete from Student Where RegistrationNumber = @RegistrationNumber", con);
            cmd1.Parameters.AddWithValue("@RegistrationNumber", addStudentRegTextbox.Text);
            cmd1.ExecuteNonQuery();
            MessageBox.Show("Record has been Deleted successfully!");
  }

Comment: Sorry, I think I just misunderstood your words. It's easy to solve the problem——Switch the order of the two lines of query code.
Comment: You cannot delete any record of the parent table if its primary key is referenced by its child table as foreign key. Or you will break the consistency of the relation.
Comment: I cannot make any changes in the design of the tables


Cannot Convert DC to single DC

Question: Windows 2016 Server environment with 3 DCs, single domain.
All DCs are also GCs.
Server 1 holds all 5 FSMO roles.
Now I want to export the VM of server 1 and put onto a different environment on a separate virtual host server, network completely separated from the actual domain. Shutdown VM, export, then re-import on the other host.
The VM works. Can ping it from a PC connected to the new separate network.
What I would expect is that AD should work just as usual, with this DC now being a lonely DC. Of course replications won't work, but since that server is a GC and holds all FSMO roles, it should have all it needs, right?
However, what happens is following:

Cannot connect to Active Directory, not even locally from server 1
dcdiag passes connectivity test but fails advertising test with error 1355 (the locator cannot find the server).
another error in dcdiag is unable to connect to NetLogon share.
nslookup query for _ldap._tcp.dc._msdcs.domain.com yields the proper reply, just as it did in the original domain network. This is supposed to be the query to locate a DC, so why does it not find it although DNS can locate it?
On the DC itself, in the new domain environment, the sysvol folder no longer contains "Policy" and "Scripts" folder, but instead there is a folder called something like "Ntfrs_Previous_SeeEventLog".

I am at a loss to understand why this happens.
Is that expected to happen, or did I do something wrong? What could it be?
Answer: Microsoft explicitly says to not do what you're doing (1). "replication won't work" will definitely (eventually) lead to "my AD broke". A DC with badly-broken replication will indeed stop acting like a DC, stop servicing logins, etc.
They even left you a breadcrumb that you found! Ntfrs_Previous_SeeEventLog - That's NT File Replication Service. It broke (expected), the DC removed its shares (expected), thus breaking logins, and left you a message to look up the event logs. Go do that.
If you insist on going down this path, you'll need to fix replication, cleanup this machine's view of AD now that you've cut it off from other DCs, and then you might have a working isolated test domain.
Update per your comment - yes, of course you can have a domain with a single DC. But you took a (copy of) a DC that was NOT solo, and cut it off from the replication partners that it knows about, so it thinks it's broken. You have to fix it. End of story.
(1) - There used to be a TechNet KB article stating this. Microsoft memory-holed a lot of that, so I don't have an easy source. It was about unsupported scenarios for AD migrations during corporate splits and divestitures; a "please don't do this" scenario was simply partitioning the network and then cleaning up each half's AD. Obviously, on paper there's no reason it shouldn't work, but if you miss something or do it wrong or cleanup the wrong stuff, you've made a HELL of a headache and MS didn't want to support it.
Comment: Can you provide info where Microsoft says so? Obviously I can have a domain with a single DC so replication is not required. What seems not supported then is "downgrading" a DC without demoting all other DCs first (which is not what I want to do)
Comment: But isn't that exactly what replication with a 2nd DC is supposed to handle? Imagine domain with 2 DCs - disastrous outage - after recovery only 1 DC comes back up - exactly same situation as I have, so the single DC will not function? But that situation is exactly why one would have 2 DCs - so that one can fail, and in any way imaginable.  - So does this then mean minimum nbr of DCs is 2? So one should really always have 3 so one can fail, leaving 2? This would be a disastrously stupid setup - I cannot believe this to be true.
Comment: No, loss of a single DC in a 2-DC environment will not immediately cause the domain to die, you're correct. The design is not disastrously stupid. It usually takes a while. So perhaps you took too long to recreate the isolated environment. Maybe there was some weirdness with the time service during the isolation/recreation.
Regardless, Windows already told you the problem - NTFRS had a hiccup so the DC protected itself. Figure out the problem, fix it, and keep going.

Cannot Convert DC to single DC


Laracasts/flash not showing in laravel 5.4

Question: I have recently upgraded my project from Laravel 5.1 to 5.4. Everything is working fine except for flash messages which are not displaying. I have perform the following checks to make sure I am not doing something wrong:

RouteServiceProvider.php

The web middleware group is added automatically to my routes by mapWebRoutes function
+--------+----------+-----+--------+------------------------------------------+--------------+
| Domain | Method   | URI | Name   | Action                                   | Middleware   |
+--------+----------+-----+---------------------------------------------------+--------------+
|        | GET|HEAD | /   |        | App\Http\Controllers\HomeController@index| web,auth     |

Kernel.php

Below is the content of the middleware groups in Kernel.php
 'web' => [
                \App\Http\Middleware\EncryptCookies::class,
                \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
                \Illuminate\Session\Middleware\StartSession::class,
                // \Illuminate\Session\Middleware\AuthenticateSession::class,
                \Illuminate\View\Middleware\ShareErrorsFromSession::class,
                \App\Http\Middleware\VerifyCsrfToken::class,
                \Illuminate\Routing\Middleware\SubstituteBindings::class,
            ],

flash() is placed before redirects
flash()->success('Bob stone Added Successfully');
$target_location = 'cia_agent/' . $agent_id .'/profile';
return redirect($target_location);

Just one 302 reponse is returned in Network in Chrome developer tool.
The above code works in Laravel 5.1, what are my missing here?
Comment: Which version of the package are you using? have you tried updating the flash package to the latest version?
Comment: I am using laracasts/flash 3.0
Comment: There was a change to view partial used to display the messages. If you had published and used it, you need to manually change it. https://github.com/laracasts/flash/blob/master/src/views/message.blade.php This is from the release changelog https://github.com/laracasts/flash/releases/tag/3.0.0
Comment: I do have the correct view. that is done with `@include('flash::message')`
Answer: After digging, I found the solution. In /resources/views/vendor/flash/message.blade.php, I had the following code which was working for Laravel 5.1
@if (Session::has('flash_notification.message'))
    @if (Session::has('flash_notification.overlay'))
        @include('flash::modal', ['modalClass' => 'flash-modal', 'title' => Session::get('flash_notification.title'), 'body' => Session::get('flash_notification.message')])
    @else

            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

            {{ Session::get('flash_notification.message') }}

    @endif
@endif

But since there is been a change with Laracasts/flash view partial used to display messages, I put the new code in the file:
@foreach ((array) session('flash_notification') as $message)
    @if ($message['overlay'])
        @include('flash::modal', [
            'modalClass' => 'flash-modal',
            'title'      => $message['title'],
            'body'       => $message['message']
        ])
    @else

            @if ($message['important'])
                <button type="button"
                        class="close"
                        data-dismiss="alert"
                        aria-hidden="true"
                        >×</button>
            @endif

            {!! $message['message'] !!}

    @endif
@endforeach

{{ session()->forget('flash_notification') }}

It's working perfectly now.


How to encoding a string into a bytearray using utf-8?

Question: I want to encode a string in a byte array using utf-8. For example, for the string "CD" I want to obtain b"\x43\x44". I have tried this, but it's not working:
def toTab(strMessage):
    return strMessage.encode('utf-8')

and I get b'CD', which is not the result I want.
Comment: `b'\x43\x44'` and `b'CD'` are the same byte string, just written differently. Check this expression: `b'\x43\x44' == b'CD'`. It's like writing `3.0` or `3.00000` or `3e0` for all the same number.
Answer: One of the major changes from Python 2 to 3 was with the str data type. More about that here. Basically, they try their hardest to be human readable at all times, which can lead to some interesting and frustrating things when trying to keep hex values in a string. The b in front of a string tells python that it is encoded, so your function actually is working, but it is displayed as human readable. To show this, simply try:
b'CD'.hex()

or, more specifically:
'CD'.encode().hex()

which gives:
'4344'

EDIT: To clarify, a python str will always represent ASCII as ASCII. This can be shown by entering the following into a console:
"résumé".encode("utf-8")

which will yield:
b'r\xc3\xa9sum\xc3\xa9'

Notice that all ASCII is rendered as such and non-ASCI is represented by bytes. Also notice something key, UTF-8 characters can be represented with anything form 1 to 4 bytes (where a byte is 8 bits). The entire ASCII set on the other hand can be represented with only 7 bits, leaving all ASCII bytes zero padded.
So again, your output is b'\x43\x44', it is just visually represented as b'CD'. If you passed this to a c program to, say, exploit a buffer overflow, it recognizes the string as b'\x43\x44' as you desire.
To show this, try:
if b'\x43\x44' == b'CD':
    print(True, b'\x43\x44')
else:
    print(False)

Which will print: True b'CD'
Comment: Thanks a lot ! I get what you say. Actually I wanted to get b"\x43\x44", but it's okay. The most important is that i understand what Python is doing.
Answer: You could get what you want by combining and formatting each byte of the bytearray manually.
def toTab(strMessage):
    return 'b"{}"'.format(''.join(r'\x{:0x}'.format(b) for b in strMessage))

msg = b"\x43\x44"
print(toTab(msg))  # -> b"\x43\x44"

Comment: But this does not do what the OP wants, as you are putting in a byte array. If you already have the byte array, why not just use it, rather than putting in a function to get the same thing out?
Comment: @jacob: Perhaps I misunderstood what the OP meant by "I want to obtain `b"\x43\x44"` — which I took to mean literally a string with exactly those characters in it.


Does anyone know of any application of mathematical induction in Complex Analysis?

Question: I know some applications of mathematical induction, such as D'moivre's theorem and triangular inequality, but I wanted something more, like derivatives, limits or some complex identities to which I could apply mathematical induction.
If anyone knows any material, please indicate :)
Comment: One of the most useful theorems about that if a complex function is differentiable at a point, then it is infinitely differentiable at a point is proven using mathematical induction
Answer: How about this one?
Consider a Taylor series
$$ f(x) = \sum_{n=0}^\infty \frac{a_n}{n!} x^n $$
Then for all natural numbers $k$, the $k$'th derivative of $f$ is
$$ f^{(k)}(x) = \sum_{n=0}^\infty \frac{a_{n+k}}{n!} x^n $$
with the same radius of convergence.


Set a Macro before sending log over network with syslog-ng

Question: I have created a syslog server and client. I want to set client serial number in SOURCE macro in all logs being sent to server so that on server side I can retrieve the macro and can create the log file based on client serial number. Following is my rewrite rule:
rewrite set_host{
    set("DEVICE_SERIAL_NO", value("SOURCE"));

};
log { source(s_src); rewrite(set_host); destination(d_net); };
On server side I have written following configuration for log file:
destination d_host-specific {
    file("/var/log/testlogs/$SOURCE/$YEAR/$MONTH/$HOST-$YEAR-$MONTH-$DAY.log");

};
But on server side I get value of $SOURCE as s_net. Seems like SOURCE macro is over-written on server side. How to sustain a macro from client to server and use it on server side?
Answer: $SOURCE is a local value, it is not forwarded to the server by default. Every destination has an on-wire format, for example, the network() source/destination uses the BSD (RFC 3164) or IETF (RFC 5424) syslog protocol. The default template of these protocols contains $PROGRAM, $MSG, $HOST, $ISODATE, etc., but $SOURCE is not a standard field.
You have multiple options:

You can specify a destination template() manually and then parse the message on the server side. This can be done, for example, in JSON format ($(format-json) and json-parser()).
You can use the structured-data section of a RFC 5424 syslog message:

# client

rewrite set_host {
  set("DEVICE_SERIAL_NO", value(".firstname.lastname@example.com"));
};

destination d_net {
  syslog("server.address");
};

# server

source s_net {
  syslog();
};

destination d_host_specific {
  file("/firstname.lastname@example.com}/$YEAR/$MONTH/$HOST-$YEAR-$MONTH-$DAY.log");
};

The syslog() and the network(flags(syslog-protocol)) destinations forward messages using the IETF syslog protocol. All subkeys under .SDATA will be serialized automatically into the forwarded message.

syslog-ng >= v3.17 has a dedicated source/destination plugin that transfers messages "in whole" between syslog-ng instances (containing all name-value pairs) in a special format. Both the source and destination objects are called ewmm() (enterprise wide message model).
As an alternative, you can use $HOST with (keep-hostname(yes) on the server side), which is part of the message header.
Comment: I tried setting HOST parameter too. It gets changed when I receive the message on server.
Comment: Also, the solution provided above didn't work. I am using syslog-ng 3.13.
Comment: If you want to keep the original hostname, set `keep-hostname(yes)` in the server config.
Comment: What do you mean by "didn't work"?
Comment: By "didn't work" I mean that on server side I get .firstname.lastname@example.com as empty.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/101206/discussion-between-mranno-and-darshan-prajapati).
Comment: Having keep-hostname(yes) on server side and setting HOST on client side it worked. @MrAnno just change the answer with this and I will mark it as accepted answer.


accuracy and precision in regression vs classification

Question: Are accuracy and precision the same things in regression and classification?
In regression: accuracy is bias, and precision is inverse of variance.
In classification: accuracy is correct prediction over number of samples, and precision is true positives over all predicted positives.
Answer: As you've pointed out, they are not the same, and sometimes refer to wildly different things (i.e., precision is a property of the model in classification, and refers to a measure of variance in regression). Unfortunately, in statistics and i'm sure other disciplines, we tend to abuse notation and use the same word to denote different things. You've pointed out a great example.
Precision and Accuracy
Precision in the context of regression, more specifically linear regression and the normal distribution refers to the Precision matrix, where X is a multivariate, normally distributed variable
$X \sim MVN(\mu, \Sigma), \hspace{4mm} \text{where } \Sigma^{-1} = \text{Precision Matrix} $.
In the context of classification, Precision is also known as PPV (or positive predictive value), and that refers to how "good" your model is at idnetifying true cases among the predictions.
$PPV = \text{Precision} = \frac{TP}{TP + FP}$
where TP/FP = True and False positives, respectively. Some communities use PPV, and some communities use precision. They mean the same.
Similarly, with Recall and Sensitivity, you measure how good you are at "catching" all the positive cases.
I think the best thing is to follow Bane's lead above, and create a cheat-sheet or notecards with these terms to not confuse them since they can easily get mixed up and be referred to constantly in ambiguous settings.
Answer:
Accuracy is the overall accuracy of the model.
It is the ratio of
(total number of correct predictions) / (total population)

Precision (Positive Prediction Value) on the other hand is the ratio of
(correctly predicted as positive) / (total number of positive predictions)


How to keep navigation bar when push to subpages and back to main page?

Question: screentshot
In my app there are some features in home page,what I want is when direct to their sub pages and still keep the buttom navigation bar.
Code for navigation bar Below the answer
Code for parts of home page
@override
Widget build(BuildContext context) {
return new MaterialApp(
    home: new Scaffold( resizeToAvoidBottomInset:false,
    body: SlidingUpPanel(
        body: Center(
          child:Container(
            constraints: BoxConstraints.expand(),
            margin: const EdgeInsets.only(top:23),
            child: Column(
              children: [
             .....
             Container(
              width: 730,
              height: 190,
              alignment:Alignment.center,
              child:Wrap(
                 children: <Widget>[
                 //...otherFiveFeatures...//
                    OutlinedButton(
                    onPressed:()async{
                        var nav = await Navigator.of(context).pushNamed('/routerMobileScannerPage');
                        if(nav==true||nav==null)
                        {Navigator.of(context).pushNamedAndRemoveUntil('/routerHomePage',(Route<dynamic>route)=>false);
                        }
                      },

                    ),

                ],
              ),
            )

              ],
            ),
          ),
        ),
      collapsed: Container(),
      panel: Center(),
      ),

   )
 );

}
Answer: To achieve this, you need to manage multiple widgets for a single selection index. For example, from Home Screen you want to navigate to Details screen keeping the Home tab selected, you need to manage a flag for that selection. Something like this.
Code to get widget based on selection
  Widget _getBodyWidget() {
    switch (currentIndex) {
      case 0:
        return shouldShowDetails ? DetailsView() : HomeView();
      case 1:
        return CategoriesView();
      default:
        return HomeView();
    }
  }

In the code above, there is a flag shouldShowDetails which will be assigned as true when user taps on the Details button. When user wants to come to HomeScreen, change to false.
For such scenarios, I would suggest you to use the Provider plugin. It provides us an easy way to update the widget state based on such flags.
Answer: Code for buttom navigation bar
class PageCTRLWidget extends State<statePageCTRLWidget> with AutomaticKeepAliveClientMixin{
  @override
 bool get wantKeepAlive => true;
 int currentIndex=0;
 final screens=[
 stateHomePageWidget(),
 Center(child: Text('Categories',style: TextStyle(fontSize: 45),),),
 Center(child: Text('Assistant',style: TextStyle(fontSize: 45),),),
 stateMemberPageWidget()
];
@override
Widget build(BuildContext context) {
return Scaffold(

  body: IndexedStack(
    index: currentIndex,
    children: screens,
  ),

  bottomNavigationBar: BottomNavigationBar(
    type: BottomNavigationBarType.fixed,
    selectedItemColor: Colors.orange,
    currentIndex: currentIndex,
    onTap:(tappedIndex)=>setState(()=>currentIndex=tappedIndex),
    items: [
      BottomNavigationBarItem(
        icon: Icon(Icons.home),
        label: 'Home',
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.menu_book_rounded),
        label: 'Categories',
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.add_location_alt_rounded),
        label: 'Assistant',
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.account_box_rounded),
        label: 'Member',
      )
    ],
  ),
);
}
}


What's the difference between CREATED and DTSTAMP in the iCalendar format?

Question: In the iCalendar spec I find the following about DTSTAMP:

This property is different than the "CREATED" and "LAST-MODIFIED"
properties. These two properties are used to specify when the
particular calendar data in the calendar store was created and last
modified. This is different than when the iCalendar object
representation of the calendar service information was created or
last modified.

What does that mean? I'm storing events in a database and want to generate an iCal file. I assume CREATED should be set to whenever the event was created, but what should I set DTSTAMP to?
Answer: VEVENT vs. an event in a calendar application
A *.ical or *.ics file, or another comparable data stream contains messages sent from one calendar application to another one. The calendar applications store events as objects.
You can enter an event in your calendar by clicking and typing, but another way is to import an ical file with VEVENT messages. Don't think of those VEVENT messages as duplicates of the application's event-objects. Think of it as duplicates of your clicking and typing.
With this idea in mind, it is easy to understand, that a VEVENT not only can create an event. It also can change an existing event, and it even can delete an event from the application.
And now let's have a look on some fields that are important in this context:

CREATED
This is the timestamp of when an event-object was created in a calendar application. Each event-object can be identified by a unique Identifier (UID).

DTSTAMP
This is the timestamp of the creation of a VEVENT-message in an ical or ics file. There are different types of such VEVENT-message, creating a new event-object is just one of them. You also can change existing events and even cancel events if you add the correct UID to the VEVENT-message to identify which event-object it belongs to. So for one event-object in your calendar application (identified by its UID) you can receive many VEVENT-events, each with its own DTSTAMP, but all referring to an event with just one CREATED date.

SEQUENCE
This is not a timestamp but a number (an integer). If you omit a sequence number, it is treated as SEQUENCE:0. If you have more than one VEVENTs (received in one or more files) for the same event-object (same UID), then they will be processed by increasing sequence numbers. DTSTAMP just tells you when the VEVENT was created, but it does not influence the order of execution, which is defined by the field SEQUENCE. So make sure, that every change in your callendar application sets a new DTSTAMP for VEVENT together with an incremented SEQUENCE number.

LAST-MODIFIED
This again is a timestamp of an object in a calendar application. When you receive an ical-file with a VEVENT-message who's DTSTAMP is today, 9 a.m., and you feed it into you application at 10 a.m., then 10 a.m. is the value of LAST-MODIFIED.

How can CREATED and LAST-MODIFIED make sense in VEVENT?
As shown before, CREATED and LAST-MODIFIED are properties of an object in a calendar application, while VEVENT is a message that contains properties, from which a calendar application can create, modify or delete its objects. The message can't know when you will import it into your application, so it can't know when you will create or modify the object. Or can it know? Why should those object-properties be part of the message?
The answer is: To be able to export and import the objects of a calendar application. You have two devices (lets say a mobile phone and a desktop computer) and want to keep the calendars on both devices synchronized? Then you need messages from one device sent to the other one containing all relevant data, including the timestamps for CREATED and LAST-MODIFIED.
Since VEVENT-messages are not only used to mimic clicking and typing as described above, but also to synchronized event-objects across different instances of calendar-applications, you sometimes also need CREATED and LAST-MODIFIED in VEVENT-messages.
Answer: DTSTAMP should be set to when you create the actual ical file from the information in your database
Comment: That seems to be what makes the most sense. Thanks!
Comment: Then why does it belong to an event and not to the calendar itself?
Answer: I was looking for an answer to this question, and although the answers here helped me to understand, i also found the information in the iCalendar.org site helpful.

In short: Created states when the event was created, DTStamp is the timestamp of a modification both when "Method" property is specified or not, and LastModified is the timestamp of a modification of an event. See that LastModified is same as DTStamp plus this last one also changes in case of "Method" property set.

I just share the original here:
Created:

This property specifies the date and time that the calendar information was created by the calendar user agent in the calendar store.

DTStamp:

In the case of an iCalendar object that specifies a "METHOD" property, this property specifies the date and time that the instance of the iCalendar object was created. In the case of an iCalendar object that doesn't specify a "METHOD" property, this property specifies the date and time that the information associated with the calendar component was last revised in the calendar store.

LastModified:

This property specifies the date and time that the information associated with the calendar component was last revised in the calendar store.


Parsing JFormattedTextField, manipulating data and parsing back to String

Question: I am working on a project at work and having some problems with parsing a number. I'm not sure why I am getting the odd results I am.
To start I have a JFormattedText field that holds a 12-digit number, like so:
referenceNumberField = new JFormattedTextField(nf);
        referenceNumberField.setText("371260062101009");
        referenceNumberField.setColumns(12);
        panel5.add(referenceNumberField);

There is a loop further in my program that causes this number to be written an indefinite amount of times. I have been asked to ensure that the number is different each time it is written without changing the amount of digits. To do this I decided to add the current counter value to the number each run, thus it will always be different but remain 12 digits.
To start I attempted to parse the JFormattedTextField into a String.
String referenceStartingString = referenceNumberField.getText();

This part works correctly. Next I want to turn it into a double so I can manipulate it.
double referenceNumberDouble = Double.parseDouble(referenceStartingString);
                    System.out.println("Reference Number Double: "+referenceNumberDouble);

The problem I'm having really lies here. The result I get from runtime is this:
Reference Number Double: 3.71260062101009E14

I'm not sure why the decimal has been added nor am I sure why exactly the "E" is in the number. I thought that stood for exponent and only shows up if the number exceeds the limit for double (Which I do not think this does)..
Just to clarify the next stages are
Turning my counter into a double
double countDouble = (double) j;

Adding the two together:
double referenceTotal = referenceNumberDouble + countDouble;

and turning back into a String..
String referenceString = String.valueOf(referenceTotal);

Without being able to turn the string into a double I can't go any further, I appreciate any help!
Answer: The E means *10^. This is because int has a maximal value of about 2000000000. Try parsing to long instead of int.
Long.parselong()
Comment: Thanks! I should have thought of that but I thought that Double could hold an extremely large number.. I will switch to long and go from there.

I'll accept your answer after the 10 minute mandatory wait.


IIS7 / FTP 7.5 - how to access outside FTP root directory

Question: Is it possible to set access any directories outside the FTP root with Windows Server 2008 and FTP 7.5 server? I have FTP User Isolation set to 'User name directory' and have created a virtual directory under the LocalUser directory with the same name of the user which links to an external directory. But this isn't working so I guess it's not the right way to do it.
Any ideas anyone?
Answer: There are 2 possible solutions for you.  In IIS 7(.5), you can click on the FTP Directory Browsing icon and turn on Directory Listing Options: "Virtual Directories" which will display it for you.
The other option is to create a blank folder with the same name, where the vdir is.  Then it will show up in the listing, although if you navigate to it with FTP the vdir will 'catch' instead and direct you to where you want to go.
Answer: It looks like adding a virtual directory does work - it just doesn't show up in the FTP directory listing. You have to type in it's address manually to get to it.


Problema ao alternar entre gráficos usando CardLayout

Question: Olá, estou tendo problemas ao utilizar CardLayout para exibir os gráficos de duas classes. Eu pretendia mostrar cada gráfico de uma vez e exibir o outro ao apertar um botão, no entanto quando eu aperto o botão o primeiro gráfico continua desenhado e o segundo aparece sobre escrevendo o primeiro, fazendo com que os dois gráficos apareçam ao mesmo tempo.
Classe principal
public class MainFrame extends JFrame{
    JPanel mainCard;
    JButton jb1, jb2;
    CardLayout cards;
    NRZL card1 = new NRZL();
    NRZI card2 = new NRZI();

    public MainFrame(){
        setSize(900,900);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setTitle("Tela de escolha");

        jb1 = new JButton("Vá para NRZI");
        jb2 = new JButton("Vá para NRZL");

        jb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cards = (CardLayout) mainCard.getLayout();
                cards.show(mainCard, "card 2");
            }
        });

        jb2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cards = (CardLayout) mainCard.getLayout();
                cards.show(mainCard, "card 1");
            }
        });

        card1.add(jb1);
        card2.add(jb2);

        mainCard = new JPanel(new CardLayout());
        mainCard.add(card1, "card 1");
        mainCard.add(card2, "card 2");

        getContentPane().add(mainCard);
        setVisible(true);
    }

    public static void main(String[] args){
        MainFrame mainFrame = new MainFrame();
    }
}

Classe gráfico 1
public class NRZL extends JPanel{

    @Override
    public void paintComponent(Graphics g){
        super.repaint();
        g.drawOval(200, 200, 200, 200);
    }
}

Classe gráfico 2
public class NRZI extends JPanel{

    @Override
    public void paintComponent(Graphics g){
        super.repaint();
        g.drawRect(300, 200, 200, 200);
    }

}

Desde já agradeço por qualquer ajuda.
Answer: vc pode colocar um repaint
jb1.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
          repaint();
          cards = (CardLayout) mainCard.getLayout();
          cards.show(mainCard, "card 2");

      }
  });

  jb2.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        repaint();
        cards = (CardLayout) mainCard.getLayout();
        cards.show(mainCard, "card 1");

      }
  });

Comment: Muito obrigado, esse era o detalhe que faltava.


Por que não consigo chamar objeto cta1 instanciado em btnCriarConta_Click?

Question: Por que não consigo chamar objeto cta1 instanciado em btnCriarConta_Click?
namespace proj3 {
   public partial class conta : System.Web.UI.Page {
      protected void Page_Load(object sender, EventArgs e) {
      }
      protected void btnCriarConta_Click(object sender, EventArgs e) {
         try {
            decimal saldo = decimal.Parse(txtSaldo.Text);
            ContaBancaria cta1 = new ContaBancaria(1, saldo);
            Session.Add("conta", cta1);
            msgGeral.Text = "Conta criada com sucesso.";
         }catch (Exception ex){
         }
      }
      protected void btnDebitar_Click(object sender, EventArgs e) {
         try {
            cta1.debitar(decimal.Parse(txtSaldo.Text));
         } catch (Exception ex) {
         }
      }
      protected void btnCreditar_Click(object sender, EventArgs e)
      {
         try {
         }catch (Exception ex) {
         }
      }
   }
}

Comment: Onde está o JavaScript nesse código?
Answer: O trecho que código que você adicionou não é javascript, eu acho que é c#.
Você não consegue acessar cta1 por causa do escopo, a variável só existe dentro do corpo do método btnCriarConta_Click.
Para poder utilizar o objeto dentro de btnDebitar_Click você pode obter ele através do Session utilizando a chave "conta" já que após criar a ContaBancaria você salva ela na sessão do usuário.
Uma outra solução que não tenho certeza se atende seu caso seria definir a conta como um propriedade da classe conta e acessar essa propriedade em btnCriarConta_Click e btnDebitar_Click.
Answer: Porque a variável foi criada (portanto, está limitada) ao escopo da função.
Ou seja, a variável cta1 é criada em btnCriarConta_Click e somente acessível a partir desta função (após sua declaração).
Por outro lado, você está salvando o objeto (conteúdo da variável) no estado da sessão.
Basicamente, o que falta é declarar uma variável de mesmo tipo na função desejada para obter o objeto salvo na sessão, e então chamar o método desejado.
protected void btnDebitar_Click(object sender, EventArgs e)
{
     try
     {
        ContaBancaria cta1 = (ContaBancaria) Session["conta"]; // Aqui!
        cta1.debitar(decimal.Parse(txtSaldo.Text));
     }
     catch (Exception ex)
     {
     }
}


Setting event date in views

Question: i have events page on my Drupal and it is showing events until the relative date (is greater than) "now" which means the event disappears from the table on the starting date of the event.
Can you please help me with setting that date to the last day of the event - so that the event stays on the table until the last day. I have multiple events, so i really dont know how to do this. I checked other relative formats, but i am no developer, so i am puzzled.
Thank you in advance.
Answer: If your node contains Date field than you can set start and end date (you can turn on/off end date field in field settings). Both are available in Views so instead of building your Views filter on start date, build it on end date.
Comment: Thank you for very this logical answer. Solved my problem.

Setting event date in views


How to move the heavy sorting work away from UI thread

Question: I have a sort of numeric keypad and a list. When the user chooses the keypad, I call a function to sort the list. The user can press the button to show the list at any time.
But that list can be pretty large, 500+, so I was thinking about doing the sorting no longer on the UI thread.
What is the best way to do this ?
Should I use a regular thread, asynctask?
My only worry is that the user can also click the button to show the list while the asynctask is not finished yet. How should I handle that ?
Thx
Comment: use mutli-threading  in android [see this post][1], i hope it helps

  [1]: http://stackoverflow.com/questions/5517197/how-to-create-multi-thread-in-android
Answer: Definitely go for AsyncTask which is designed for heavy work outside UI. Concerning your last question, make button disabled and enable it in AsyncTask's onPostExecute(). Cheers.
Answer: Definitely you need a asynctask. In your onCreate method hide all of your buttons and textviews. Before you do something in the background you need to show user a load bar or a spinner so that user can't click any of the buttons you have created. Here is a sample:
class LoadAllProducts extends AsyncTask<String, String, String> {
    protected void onPreExecute() {
         super.onPreExecute();
         pDialog = new ProgressDialog(Academic.this);
         pDialog.setMessage("Loading. Please wait...");
         pDialog.setIndeterminate(false);
         pDialog.setCancelable(false);
         pDialog.show();
}

protected String doInBackground(String... args) {
       //Do something
       return null;
}

protected void onPostExecute(String file_url) {
    // dismiss the dialog after getting all products
    pDialog.dismiss();
    // updating UI from Background Thread
    runOnUiThread(new Runnable() {
           public void run() {
             //finally show your button
          }
    });
}

Before using this code make sure you have declared the pDialog. In my program I had used spinner.
Answer: AsyncTask looks good for this... task. You can also make some sort of state-member to check whether the sort task is running and depending on it start the task or do nothing when the user presses the button. As an alternative, if something has changed, you can also cancel the task and start a new one.
Answer: Go  for Async Task and you can show some progress bar in onPreExecute() and stop it in onPostExecute().
User wont be able to clcik anything till progress bar is running on screen.
Answer: You can use AsyncTask as other have told or you can create a thread and run long running operations and update UI accordingly with handlers. Have a look at this link http://www.vogella.com/articles/AndroidPerformance/article.html


How can I update an user field via JSON:API?

Question: How do I update user field via JSON API with D8?
EndPoint:https://domainname.com/jsonapi/user/user/

Method:PATCH

Request Header;
Accept:application/vnd.api+json
Content-Type:application/vnd.api+json
X-CSRF-Token:xxxxxxxxxx

Body:
"data": {
        "type": "user--user",
        "id": "xxxxxx-7798-45e5-a16c-xxxxxxxxxxxx",
        "attributes": {
            "field_test1": [
                "data1",
                "dara2"
            ]
        }
    }

But below error
        "title": "Method Not Allowed",
        "status": "405",
        "detail": "No route found for \"PATCH /jsonapi/user/user/\": Method
        Not Allowed (Allow: POST, GET, HEAD)",

Answer: You need to also put UUID in your request URL, so it should look like
EndPoint:https://domainname.com/jsonapi/user/user/xxxxxx-7798-45e5-a16c-xxxxxxxxxxxx


Sum of Functions with Incommensurable Periods

Question: I am trying, essentially, to prove that for incommensurable numbers $a, b \in \mathbb{R}$, and some $\epsilon > 0$, there exist integers $n, m \in \mathbb{Z}$ such that $|na + mb| < \epsilon$.
There are several other problems equivalent or very closely related to this. For example, a ray with irrational slopes under the quotient map $\mathbb{R}^n \longrightarrow \mathbb{R}^n / \mathbb{Z}^n$ is dense, or the fact that $(-n, n) \subseteq Im(\sin a_1x + \dots + \sin a_nx)$ where $a_1 \dots a_n$ all incommensurable. I have seen similar questions posted in the following StackOverflow entries, but they are always solved without justification. I am trying to actually prove that these facts are true (they will mostly imply each other).
Minimum of sum of incommensurable functions
Period of the sum/product of two functions
Range of a sum of sine waves
It seems like the result is well known, so I assume I'm missing something obvious.
Comment: Note that the inequality holds trivially when $n=m=0$, so you have to say $0<|na+mb| <\epsilon$.
Answer: Suppose $b$ is irrational. I will first prove the result when $a=1$. For each positive integer $m$ there exists a unique integer $n_m$ in the interval $[-mb,-mb+1)$. Let $x_m=n_m+mb$ so $x_m \in [0,1)$ for each $m$. Choose a positive integer $k$ such that $\frac 1 k <\epsilon$. Consider the number $x_1,x_2,...,x_{k+1}$ in $[0,1)$. If any two of these differ by $\frac 1 k$ or more then the difference between the largest and the smallest of them would exceed $1$ which is a contradiction. In other words there exist $i,j$ such that $0<|x_i-x_j| <\frac 1 k <\epsilon$.  Thus $0<|(n_i+ib)-(n_j+jb)| <\epsilon$. [The fact that $b$ is irrational is required to say that $(n_i+ib)-(n_j+jb) \neq 0]$.  This proves the result when $a=1$. A simple modification gives the result for any $a$.
Comment: Perfect, thank you very much.


Array.filter returns an empty array

Question: I am trying to solve a Kata in codewars. The goal of the kata is:
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.
It should remove all values from list a, which are present in list b.
arrayDiff([1,2],[1]) == [2]
I decided to solve the problem using the array.filter method. when I run this code below it returns an empty array.
function arrayDiff(a, b) {

    let filtered = a.filter(inventa =>{
        b.filter(inventb =>{
            inventa !== inventb
        })
    })

    return filtered;
}

arrayDiff([1,2],[1])

i have tried researching what could possibly be the cause. i would love an explanation on why it does so.
PS: I am a beginner
Comment: None of your `.filter()` callbacks returns anything. This won't produce the requested result, but it would be a first step in the right direction.
Comment: You might want to read: [When should I use \`return\` in es6 Arrow Functions?](https://stackoverflow.com/q/28889450)
Answer: try:
function arrayDiff(arr1, arr2){
  return arr1
    .filter(x => !arr2.includes(x))
    .concat(arr2.filter(x => !arr1.includes(x)));
}

Edit: Explanation
This Code is first filteringthe first Array, to remove all items that are in the second. Then the first Array is put together with the second Array, which is filtered to remove all Elements that are already in the first Array.
Comment: While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation.
Comment: ok, i'm sorry and thanks for the hint!
Answer: One line answer:
const arrayDiff = (a, b) => a.filter(r => !b.includes(r));

Then arrayDiff([1,2],[1]) gives [2].

It should remove all values from list a, which are present in list b.

It only works for this scenario, not the other way around.

Array.filter returns an empty array


VBA script not affecting first cell in a table

Question: I have a VBA script designed to strip non-breaking spaces out of a table in Microsoft Word by searching for NBSPS and then replacing them with regular spaces and then using trim to clean up spaces before and after text. As it stand, the code will work for everything except trimming the first cell in a table (it does however, replace the spaces in the first cell). I was hoping to find out if there are any unique behaviors to Word/VBA that might cause this as I will be making several macros for tables in MS Word.
Sub nbsbCleanupQuick()
' use find and replace to replace all nbsp in the table with regular spaces
' use trim to clean up unwanted spaces
' For some reason this macro will replace nbsp with regular spaces but will not trim in the first cell of a table

' vars for counting
Dim numRows, numCells As Integer
Dim rindex, cindex As Integer

'container for cell contents
Dim container As String

Selection.Tables(1).Select
numRows = Selection.Rows.Count

For rindex = 1 To numRows
numCells = Selection.Tables(1).Rows(rindex).Cells.Count
For cindex = 1 To numCells
    container = ""
    Selection.Tables(1).Rows(rindex).Cells(cindex).Range.Select
    With Selection.Find
        .Text = Chr(160)
        .Replacement.Text = Chr(32)
        .Execute Replace:=wdReplaceAll, Wrap:=wdFindContinue
    End With
    If (Len(Selection.Text) - 2 > 0) Then
        container = Left(Selection.Text, Len(Selection.Text) - 2)
    End If
    Selection.Text = Trim(container)
Next
Next

End Sub

Any help would be appreciated :)
Comment: what text you have in your first cell? type it here exactly as it is. The thing is that your code is working fine for me...
Comment: Different texts, in fact the first cell is often empty with only 1 nbsp and the macro replaces the nbsp with a regular space but does not remove the empty space from the first cell. Honestly, for what I need that is perfectly fine... for now. I'd just like to know what could cause it to only perform half of the operations on that first cell.
Answer: Because you are at the beginning of bigger project I'll give you some advices with some more changes of your code. See proposed solution below with some comments explaining reasons for changes inside the code. Obviously this solves the problem you described in your question.
Sub nbsbCleanupQuick()
' use find and replace to replace all nbsp in the table with regular spaces
' use trim to clean up unwanted spaces
' For some reason this macro will replace nbsp with regular spaces but will not trim in the first cell of a table

' vars for counting
Dim numRows, numCells As Integer
Dim rindex, cindex As Integer

'container for cell contents
Dim container As String

Selection.Tables(1).Select
numRows = Selection.Rows.Count

'do replacement once, at the beginning
'it will be more efficient option
    ActiveDocument.Tables(1).Select
    With Selection.Find
        .Text = Chr(160)
        .Replacement.Text = Chr(32)
        .Execute Replace:=wdReplaceAll ', Wrap:=wdFindContinue
        'keep wrap parameter switch off to do replacement only within table 1
    End With

'to iterate through all cells in table use this kind of loop
Dim tblCell As Cell
For Each tblCell In ActiveDocument.Tables(1).Range.Cells

        'it's not necessary to select but I didn't want to
        'change your solution completly
        tblCell.Select

    'this check is easier to understand
    If (Len(Selection.Text) > 2) Then
        container = Left(Selection.Text, Len(Selection.Text) - 2)
    End If
    Selection.Text = Trim(container)

Next

End Sub

Comment: This is interesting in deed. I didn't realize that the with block would execute on the entire table without the wrap::continue. The "activedocument.tables(1)" line to me implies it grabs the first table in the document. My documents have upwards of 30 tables which is why I had it set up to force the user to select a table rather than reference a specific table. If the warp::continue line affects all tables in a document that explains why the macro could take several minutes to work sometimes. This gives me much to consider. Thank you.


Urllib2, tratamento de exceções

Question: Sou um iniciante na arte da programação. Estou aprendendo a programar em Python através de um livro,

Aprenda a Programar: A arte de ensinar o computador (Cesar Brod - Novatec Editora)

Em um dos exercícios, devo utilizar a biblioteca de funções Urllib2 para buscar uma determinada página web e verificar se existe uma determinada palavra ou expressão dentro dessa página (a ideia é utilizar esse processo num conjugador de verbos, verificando num dicionário online se o verbo digitado pelo usuário é regular).
Basicamente, isso é o que deveria acontecer:
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2
>>> verbo = 'amar'
>>> pagina = urllib2.urlopen('http://pt.wiktionary.org/wiki/' + verbo)
>>> pagina = pagina.read()
>>> "Verbo regular" in pagina
True
>>>

Até aí, tudo bem. Porém, caso não exista uma página correspondente à palavra digitada pelo usuário, o seguinte erro aparece:
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2
>>> verbo = '123ar'
>>> pagina = urllib2.urlopen('http://pt.wiktionary.org/wiki/' + verbo)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 437, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 550, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 475, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 558, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found
>>> pagina = pagina.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'pagina' is not defined
>>>

Bem, como a página em questão (http://pt.wiktionary.org/wiki/123ar) possui um código-fonte, eu imaginei que o programa o leria e faria a verificação da mesma forma, entretanto isso não acontece. Alguém poderia me sugerir uma solução?
P.S.: Caso eu não tenha sido muito claro, ou tenha deixado alguma informação importante de fora, por favor, me avisem. Outra coisa, eu costumo utilizar um Linux para programar, mas estou usando um Windows no momento, no entanto, o erro ocorre nos dois sistemas.
P.S.2: Perdoem-me por qualquer erro conceitual, como disse anteriormente, ainda sou um inciante na arte da programação. Falando nisso, estou aberto a dicas também =)
Comment: @ErlonCharles Valeu aí pela edição! =)
Comment: Por nda, tudo para melhorar a cominidade
:D
Answer: Você deve tratar este erro num bloco try...except, quando a função urlopen não consegue abrir uma página, uma exceção HTTPError é lançada (é uma subclasse de URLError), portanto para tratá-la faça o seguinte:
import urllib2

try:
    verbo = '123ar'
    pagina = urllib2.urlopen('http://pt.wiktionary.org/wiki/{0}'.format(verbo)).read()
    print ("Verbo regular" in pagina)
except urllib2.HTTPError as e:
    print ("Nao foi possivel abrir a pagina. Erro {0}".format(e.code))

Bem, como a página em questão (http://pt.wiktionary.org/wiki/123ar)
  possui um código-fonte, eu imaginei que o programa o leria e faria a
  verificação da mesma forma, entretanto isso não acontece. Alguém
  poderia me sugerir uma solução?

Isso acontece porque a urllib2 trabalha de modo diferente que urllib, a documentação cita o seguinte:

Para os códigos de erros diferentes de 200, o trabalho passa para o método manipulador protocol_error_code, via OpenerDirector.error(). Eventualmente, urllib2.HTTPDefaultErrorHandler irá gerar um HTTPError se nenhum outro manipulador lida com o erro.

Para contornar isto, existe duas maneiras, a primeira é pegar o código fonte no bloco except:
try:
    verbo = '123ar'
    pagina = urllib2.urlopen('http://pt.wiktionary.org/wiki/{0}'.format(verbo)).read()
except urllib2.HTTPError as e:
    pagina = e.fp.read()

E a segunda é usar a urllib:
import urllib

verbo = '123ar'
pagina = urllib.urlopen('http://pt.wiktionary.org/wiki/{0}'.format(verbo)).read()
print ("Verbo regular" in pagina)

Comment: Ah, tudo bem. A outra resposta já me ajudou muito, mas a nova facilitou ainda mais o meu trabalho, além de me ensinar ainda mais coisas. Novamente, obrigado.
Comment: Resolveu o meu problema. Muito obrigado, @qmechanik
Comment: @PedroA. Disponha. Atualizei a resposta, eu não tinha visto a segunda parte da sua pergunta.

Urllib2, tratamento de exceções


What distribution would be expected for number rapists ( vs number of victims)?

Question: This is a horrible question to ask. But it would be useful to know (rather than someone spouting an opinion that 99.999% are/are not.).
It has been estimated that 18.3% of women will be raped at some point in their life time (CDC: Sexual Violence, Facts at a glance).
So to answer "how many men are (likely to be) rapists", more info is required.
There would be an upper bound of 18.3%, however some men would rape more than one woman.
So to make an estimate the percentage of men that may have committed rape on one or more women, you would need to know that type of distribution there would be.
So what would likely be the distribution for rapist like behaviour?
(One tailed normal, Pareto, something else?)
*To make things simple lets assume only for the M -> F case.
This rather subjective, so I am more than happy to rephrase if someone has suggestions how.
Also links to actual research would be ideal.
Comment: "There would be an upper bound of 18.3%" <- One woman could be raped by multiple (possibly all) men, so the rapist ratio might be anything from 1/(male population) to 100%.
Comment: There's a problem in that its not clear how to define rape. A survey a few years ago came out with a statistic that X% of women had been raped, where X was a surprisingly large number. But it turned out that the question asked was (something like)  "Have you ever had sex when you didn't really want to".
Comment: @cardinal Ok. I have deleted the other one.
Comment: Due to the intimate connection between the probability model and the answer, and the near-complete lack of information that could be employed to select any probability model over any other, this question seems tantamount to asking respondents to give their opinions about the proportion of men who are rapists. These opinions would be uninformed by essential data such as the population in question and the time period referenced. As such I am leery about keeping this thread open, but perhaps some thoughtful respondents will show how statistical ideas might be appropriately used.
Comment: Darcy, thank you for acknowledging your cross-post, but please instead choose *one* site to post on in the SE network at a time. If you don't get a suitable answer after some time, then you can flag the question and ask that it be migrated.
Comment: @jona Ah true. Will need to factor that in to the final calculation.
Comment: You're suggesting continuous distributions, but you're talking about a (scaled) count. It's not likely to be any named distribution.
Answer: How about a zero-inflated model?
It seems reasonable to assume that the population contains a (hopefully large) number of good folks who never rape anyone, mixed together with a subpopulation of rapists that attack people according to some other as-of-yet-unspecified distribution.
Fortunately for me, I know nothing about rapists, but it might be reasonable to start by imagining that for the rapists, the rapes are "generated" by a Possion process. The underlying model--rapists attack new victims at a fixed rate-- isn't quite right, but it's probably reasonably close enough that a zero-inflated poisson model would work reasonably well.
Since the Poisson model only has one parameter ($\lambda$ controls both the mean and variance), you may  want to consider a zero-inflated negative bionomial instead, since it can handle over-dispersed (variance > mean) data too.


Obter linha de um ficheiro

Question: Estou a ler um ficheiro txt em PHP, e pretendo obter a primeira linha e a ultima linha para poder escrever. Utilizei este codigo para ler todo o ficheiro linha a linha. Mas o que pretendo é so umas linhas.
$fp = fopen($fichier,"r");

if ($fp) {

    while (!feof($fp)) {
        $texte = fgets($fp);

        if(strpos($texte,"--") === false )
        {}
        else {
            $titre = $texte; /
            echo $titre."
";
        }

    }
fclose($fp);}

Comment: O quer apenas obter a primeria e a última linha para escrever onde?
Answer: A 1a linha é fácil, basta usar fgets como vc já está usando. Pra pegar a última linha sem ter que ler todo o arquivo use a classe ReverseFile desta resposta do Stackoverflow em inglês aqui:
https://stackoverflow.com/questions/3234580/read-a-file-backwards-line-by-line-using-fseek
Answer: Use a função file.
Ex:
<?php
$linhas = file('arquivo.txt');

Essa função te retorna o conteúdo do arquivo com uma linha por entrada do array. A partir daí é só manipular a linha que você quiser por meio do índice do array e depois reescrever o arquivo com o conteúdo do array (se for o caso):
<?php
file_put_contents('arquivo.txt', implode(PHP_EOL, $linhas));

Comment: Em questão de desempenho do SERVIDOR este método não é muito bom pois pode consumir mais memória que o necessário.
Comment: @GuilhermeNascimento sim. se for um arquivo grande, o procedimento pode ser custoso.
Comment: O que eu quero dizer é que se ele deseja a primeira e última linha, o melhor procedimento seria `feof` combinado `fgets` mais um incremento `++$i` para detectar a linha ao qual o usuário solicitou. Assim o gasto seria o mínimo possível.
Comment: Guilherme Nascimento, se o arquivo for pequeno, exemplo, umas 5 linhas, o uso do file() é melhor e o uso do fgets torna-se mais pesado.. Portanto, o que é "certo" ou "errado", depende do caso.
Answer: Seguindo o seu próprio exemplo, uma maneira de se fazer o processo seria criar uma função e pegar a linha especifica configurando os argumentos da função.
No caso usei um array para definir as linhas que você necessita capturar.
A função retorna um array, pois é melhor para você poder organizar.
Descrição:
array getLines ( mixed $handle , array $lines)

$handle Pode ser uma string com o caminho do arquivo ou um resource retornado de um fopen
$lines Deve ser um array com as linhas especificadas

A função:
function getLines($context, $lines) {
    $isResource = false;

    if (is_resource($context)) {
        //Você pode definir um resource ao invés de um "path"
        $fp = $context;
        $isResource = true;
    } else if (is_file($context)) {
        $fp = fopen($context, 'r');
    } else {
        return false;
    }

    $i = 0;
    $result = array();

    if ($fp) {
        while (false === feof($fp)) {
            ++$i;
            $data = fgets($fp);
            if (in_array($i, $lines)) {
                $result[] = $data;
            }
        }
    }

    //Pega última linha
    if ($i !== 1 && in_array('last', $lines)) {
        $result[] = $data;
    }

    if ($isResource === true) {
        //Não fecha se for resource, pois pode estar sendo usada em outro lugar
        $fp = null;
    } else {
        fclose($fp);
    }
    $fp = null;

    return $result;
}

Exemplos:
Lendo linhas 1 e 2 de um arquivo:
print_r(getLines('/home/user/test.txt', array(1, 2)));

Lendo linhas 3, 6, 11, 12 e 13 de um resource:
$res = fopen('data.txt', 'r');
print_r(getLines($res, array(3, 6, 11, 12, 13)));
...
fclose($res);

Lendo a primeira e a ultima linha:
print_r(getLines('/home/user/test.txt', array(1, 'last')));

Obter linha de um ficheiro


Reading GPIO on imx6 wandboard quad

Question: I'm writing a driver to control GPIO pins. I have identified JP4 connector and added a LED on gpio91 (JP4.06 => /sys/class/gpio/gpio91). After reading many tutorials I have written a simple kernel module. This module receives an input from user space and based on input I am setting gpio like gpio_set_value(91,true). Before calling gpio_set_value, I am calling one more function i.e gpio_direction_output. And thus led is glowing. On the other hand when I am getting other command from user space to get status of PIN (for this I am relying on gpio_get_value(91) and for this also setting direction to input), here I am not getting proper value.
Am I missing any step to get desired value? How should I attempt doing this?
Comment: The first things to check for issues like that: 1. Are clocks enabled for your module (GPIO)?  2. Are pins you are using are muxed to GPIO (and not some other module)? Check your device tree file for pin muxes first.
Comment: Also, be sure to call `gpio_request()` (before calling any other GPIO specific functions) and check `dmesg` output: the chances are someone else already uses your GPIO. `gpio_request()` is gonna help you debug this.
Comment: Also, provide us with kernel version you are using and whether it uses board files or device tree for your device. It would be nice to have link to your kernel's git repo as well.
Comment: @SamProtsenko I am not sure how to check clock is enabled or not ,but the our kernel module is happily inserted .even I am not sure my pin are muxed or not however when I am setting the pin the led is lights up.
Comment: @SamProtsenko I am using this kernel version:
_3.10.17-1.0.1-wandboard+ga6e7fc5_

This image is core-image-minimal version.
Comment: So if you can light your LED via sysfs, it means your pin is already muxed. Try to call `gpio_request()` first (in your module) and then look for `dmesg` output, if it says anything about your GPIO.
Answer: From https://github.com/wandboard-org/linux/blob/wandboard_imx_3.10.17_1.0.0_ga/arch/arm/boot/dts/imx6qdl-wandboard.dtsi#L390
EIM_D27 is properly muxed as a gpio, its padconf is 0x1B880 which means:

Slow Slew Rate
Drive Strength HIZ
Speed: 100 MHz
Output is open drain
Pull/Keeper Enabled
Pull Enabled
100K Ohm Pull Up
Schmitt trigger input

If you are always reading 1, maybe you could try to remove the pull up by using 0x18880

Reading GPIO on imx6 wandboard quad


glDrawElements is called with VERTEX_ARRAY client state disabled

Question: I'm trying to draw a sphere in OpenGL ES 2.0+ on Android, and I'm seeing the following error in Logcat:

glDrawElements is called with VERTEX_ARRAY client state disabled!

I looked at the documentation for this call and I can't see anything I might be doing wrong. From the error it sounds like I'm missing some setup somewhere.
Here's my VertexBuffer class where I'm doing the setup:
public class VertexBuffer {

    private final int mBufferId;

    public VertexBuffer(float[] vertexData) {
        // Allocate a buffer
        final int[] buffers = new int[1];
        glGenBuffers(buffers.length, buffers, 0);
        if (buffers[0] == 0) {
            throw new RuntimeException("Could not create a new VBO");
        }
        mBufferId = buffers[0];

        // Bind to the buffer
        glBindBuffer(GL_ARRAY_BUFFER, mBufferId);

        // Transfer data to native memory
        FloatBuffer vertexArray = ByteBuffer
            .allocateDirect(vertexData.length * BYTES_PER_FLOAT)
            .order(ByteOrder.nativeOrder())
            .asFloatBuffer()
            .put(vertexData);
        vertexArray.position(0);

        // Transfer data from native memory to the GPU buffer
        glBufferData(GL_ARRAY_BUFFER, vertexArray.capacity() * BYTES_PER_FLOAT, vertexArray, GL_STATIC_DRAW);

        // IMPORTANT: Unbind from the buffer when we are done with it
        glBindBuffer(GL_ARRAY_BUFFER, 0);
    }

    public void setVertexAttribPointer(int dataOffset, int attributeLocation, int componentCount, int stride) {
        glBindBuffer(GL_ARRAY_BUFFER, mBufferId);
        glVertexAttribPointer(attributeLocation, componentCount, GL_FLOAT, false, stride, dataOffset);
        glEnableVertexAttribArray(attributeLocation);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
    }
}

Comment: The `GL_VERTEX_ARRAY` client state is not even part of GLES 2.0, it is only present in the fixed function pipeline of GLES 1.x. If you are using an ES 2.0 context, this error does not make any sense at all - your driver may be confused.
Comment: Could you please show the code where you draw?
Comment: You are absolutely right. I forgot to set the context to ES 2.0 on my surface. I set it and now the error went away.
Answer: Add:
setEGLContextClientVersion(2);


textbox dynamic autocomplete

Question: My form has a textBox and i want to add autocomplete while typing.
My autocomplete values are loaded dynamically via a json api.
I applied the "update" function on the "TextChanged" Event of the textBox.
Everytime it is triggered, the autocomplete opens for 0.5 sec and the textBox's value changes to the first autocomplete entry. After that the autocomplete menu disappears.
I cannot choose any suggestions manuelly...
How to fix?
onload Event:
AutoCompleteStringCollection colValues = new AutoCompleteStringCollection();
private void StellenUebersicht_Load(object sender, EventArgs e)
{
        TextBox textBoxExample = textBox1;
        textBoxExample.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        textBoxExample.AutoCompleteSource = AutoCompleteSource.CustomSource;
        textBoxExample.AutoCompleteCustomSource = colValues;
        doAutoCompleteListExample();
}

doAutoCompleteListExample():
private void doAutoCompleteListExample()
    {
        if (textBox1.Text.Length >= 1)
        {
            string w = Web.get("MY JSON API URL");

            JObject o = JObject.Parse(w);
            List<string> ac = new List<string>();
            foreach (JObject item in o["items"])
            {
                string name = item["name"].ToString();
                ac.Add(name);
            }
            colValues.AddRange(ac.ToArray());
        }

    }

Comment: possible duplicate of [AutoComplete TextBox Control](http://stackoverflow.com/questions/1357853/autocomplete-textbox-control)
Answer: i fixed it.
Solution:
change
textBoxExample.AutoCompleteMode = AutoCompleteMode.SuggestAppend;

to
textBoxExample.AutoCompleteMode = AutoCompleteMode.Suggest;

Answer: just delete your If,no need If... do this if you not sure
 // if (textBox1.Text.Length >= 1)
    //    {
            string w = Web.get("MY JSON API URL");

            JObject o = JObject.Parse(w);
            List<string> ac = new List<string>();
            foreach (JObject item in o["items"])
            {
                string name = item["name"].ToString();
                ac.Add(name);
            }
            colValues.AddRange(ac.ToArray());
   //     }

maybe this help you
Answer: The properties like AutoCompleteCustomSource, AutoCompleteMode and AutoCompleteSource to perform a TextBox that automatically completes user input strings by comparing the prefix letters being entered to the prefixes of all strings in a data source.
        textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
        textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
        AutoCompleteStringCollection DataCollection = new AutoCompleteStringCollection();
        addItems("Add your Data here");
        textBox1.AutoCompleteCustomSource = DataCollection;

Full source here.

textbox dynamic autocomplete


Vaadin Flow DateTimePicker dirty inside CRUD

Question: I am adding a com.vaadin.flow.component.datetimepicker.DateTimePicker to a com.vaadin.flow.component.crud.Crud. This appears to always mark the CRUD dirty. I noticed that things are all good when using a com.vaadin.flow.component.datepicker.DatePicker. This problem only shows for DateTimePicker. How should I cope with this?
DateTimePicker dtp = new DateTimePicker("When");
dtp.setStep(Duration.ofMillis(1));
// ...
binder.bind(dtp, new ValueProvider<MyEvent, LocalDateTime>() {
    @Override
    public LocalDateTime apply(final MyEvent source) {
        return source.getWhen();
    }
}, ...

So, DateTimePicker with millis step, provided with a LocalDateTime value.
Later Edit:
I have looked further into the DateTimePicker.setPresentationValue(LocalDateTime) implementation and found that some JavaScript is being executed:
datePicker.getElement().executeJs("this.dispatchEvent(new CustomEvent('change', { bubbles: true }));");

Could this be it? Unfortunately, I am not familiar to Vaadin's internals, so unsure why is that required there.
Comment: Which version of Vaadin are you using? Because the DateTimePicker had some packages in the most recent version
Comment: Using Vaadin 14.7.0
Comment: Can you please try it with 14.7.2?
Comment: Yes, I did switch to `14.7.2` in my `pom.xml`, but nothing has changed.
Answer: I have experienced the same behavior on other components as well (e.g.: EnhancedDateTimePicker and Autocomplete). In some situation there is a ValueChangeEvent that is fired from the client even if the value is not changed at all. This makes the field dirty and using binder this produces that binder.hasChanges() returns true.
I have made a workaround creating a custom component that contains two instances of the component. One is hidden (not visible) and gets updated only when the value of the visible one actually changes. From the binder (and any other external) perspective, it is the hidden component that provides value and events.
Here it is for the EnhancedDateTimePicker:
public class DateTimeSelection extends HorizontalLayout implements
        HasValue<AbstractField.ComponentValueChangeEvent<EnhancedDateTimePicker, LocalDateTime>, LocalDateTime> {

    private EnhancedDateTimeField hiddenDateTimeField = new EnhancedDateTimeField("");
    private EnhancedDateTimeField visibleDateTimeField = new EnhancedDateTimeField("");

    public DateTimeSelection() {
        visibleDateTimeField.addValueChangeListener(event -> {
            if (!ObjUtils.eq(event.getValue(), hiddenDateTimeField.getValue())) {
                hiddenDateTimeField.setValue(event.getValue());
            }
        });
        visibleDateTimeField.setWidthFull();
        add(visibleDateTimeField);
    }

    public DateTimeSelection(String label) {
        this();
        setLabel(label);
    }

    public String getLabel() {
        return visibleDateTimeField.getLabel();
    }

    public void setLabel(String label) {
        visibleDateTimeField.setLabel(label);
    }

    @Override
    public void setValue(LocalDateTime localDateTime) {
        hiddenDateTimeField.setValue(localDateTime);
        visibleDateTimeField.setValue(localDateTime);
    }

    @Override
    public LocalDateTime getValue() {
        return hiddenDateTimeField.getValue();
    }

    @Override
    public LocalDateTime getEmptyValue() {
        return hiddenDateTimeField.getEmptyValue();
    }

    @Override
    public Optional<LocalDateTime> getOptionalValue() {
        return hiddenDateTimeField.getOptionalValue();
    }

    @Override
    public boolean isEmpty() {
        return hiddenDateTimeField.isEmpty();
    }

    @Override
    public void clear() {
        hiddenDateTimeField.clear();
        visibleDateTimeField.clear();
    }

    @Override
    public void setReadOnly(boolean b) {
        visibleDateTimeField.setReadOnly(b);
    }

    @Override
    public boolean isReadOnly() {
        return visibleDateTimeField.isReadOnly();
    }

    @Override
    public void setRequiredIndicatorVisible(boolean b) {
        visibleDateTimeField.setRequiredIndicatorVisible(b);
    }

    @Override
    public boolean isRequiredIndicatorVisible() {
        return visibleDateTimeField.isRequiredIndicatorVisible();
    }

    @Override
    public Registration addValueChangeListener(ValueChangeListener<? super AbstractField.ComponentValueChangeEvent<EnhancedDateTimePicker, LocalDateTime>> valueChangeListener) {
        return hiddenDateTimeField.addValueChangeListener(valueChangeListener);
    }
}

Comment: Thanks, CT Liv! I thought that Vaadin's major versions are (more) mature, but as I explore it I realize that it's not the case. I don't understand why are we having Vaadin Flow 21 and now 22 (alpha), when 14 is missing lots of basic functionality and requires dirty fixes every here and there. I find myself more and more in the position to consider using Vaadin 8 instead.
Answer: Please see https://github.com/vaadin/flow-components/issues/1043 . You should be able to change your project's pom.xml to pick-up the v 14.7.1 version of the timepicker flow component with the appropriate fix.


Can I use WCF for communicating (sending message) between 2 applications?

Question: I have a problem regarding WCF .Can i do that:-
I want to create WCF service,window service & Silverlight Application.And I want to send message(data) from  window service to silverlight application through wcf service.
and vice-versa.Is it possible.
Thanks & Regards,
Vipin Kumar
Answer: It is only possible, if the receiving side has a listener that listen for messages then reply as needed to those messages. I think what you are really looking for is a Pub/Sub solution to communicated between two different processes.


What are different types of string/int as in data types that can be input by the person playing a game in python. (I am using pycharm)

Question: How to input an integer data type as a user playing a game? I have tried many things but they don't work. I have tried inputing numbers but they still are strings not integers.
Answer: In python3 use:
x = int(input(3))

and in python2 use:
input(3)


Calling C dll code from C#?

Question:
Possible Duplicate:
How do I call unmanaged C/C++ code from a C# ASP.NET webpage

is there a way to link the two?
Comment: http://stackoverflow.com/questions/720004/how-do-i-call-unmanaged-c-c-code-from-a-c-asp-net-webpage
Comment: many examples Windows® API Code Pack for Microsoft® .NET Framework(http://code.msdn.microsoft.com/WindowsAPICodePack/Release/ProjectReleases.aspx?ReleaseId=3574)
Answer: P/Invoke is the approach you want
Answer: Search for PInvoke in C#
you will find plenty of resources. Like this one:
http://msdn.microsoft.com/en-us/magazine/cc164123.aspx
Answer: Yes, PInvoke is the way. This site/wiki will be a great help likely.

Calling C dll code from C#?


Example of Symplectic fibration

Question: Can you give a example of manifold $M$ such that $\pi:M\longrightarrow T^2 $ be a Symplectic fibration?
Answer: Let $X$ be any symplectic manifold. Then there is a symplectic fibration given by $M = X \times T^{2}$ with the map $f: X \times T^{2} \rightarrow T^{2}$ given by projection to the second factor.

Example of Symplectic fibration


Recharts show tooltip on ALL charts on hover

Question: I'm using recharts/ react to visualize some simple data, and running into a wall. I want to show the line + tooltip on ALL the graphs whenever a user hovers over any of the graphs. Been trying to use state or dispatch but running into a wall.
I've attached code snippets for my chart and dashboard files with the attempt at using dispatcher. I dont't know where in chart.js to actually call showTooltip. The functionality I want is to show the tooltips for all charts whenever a user hovers over any single chart. If one tooltip = active, I want all tooltips=active. Any guidance would be super helpful!
chart.js snippet
export default function Chart(props) {

  const {state, dispatch} = useContext(AppContext);

  const showTooltip = (newValue) => {

    dispatch({ type: 'HOVER', data: newValue,});
  };

  const theme = createMuiTheme({
    palette: {
      primary: {
          main: '#041f35'
      },
      secondary: {
        main: '#5dc5e7'
      }
    }
  });

  return (
    <React.Fragment>
      <MuiThemeProvider theme={theme}>
      <Title>{props.title}</Title>
      <ResponsiveContainer width="100%" height="100%">
        <LineChart
          width={500}
          height={300}
          data={data}
          margin={{
            top: 5,
            right: 5,
            left: -35,
            bottom: 5,
          }}
        >
          <XAxis dataKey="time" />
          <YAxis axisLine={false} tickLine={false}/>
          <Tooltip  />
          <CartesianGrid vertical={false} stroke="#d3d3d3"/>
          <Line type="monotone" dataKey="mktplace1" stroke={theme.palette.primary.main} activeDot={{ r: 8 }} />
          <Line type="monotone" dataKey="mktplace2" stroke={theme.palette.secondary.main}  />
        </LineChart>
      </ResponsiveContainer>
    </MuiThemeProvider>
    </React.Fragment>
  );
}

dashboard.js file snippet
export const AppContext = React.createContext();

// Set up Initial State
const initialState = {

  active: new Boolean(false),

};

function reducer(state, action) {
  switch (action.type) {
      case 'HOVER':
          return {
              active: new Boolean(true)
          };

      default:
          return initialState;
  }
}

export default function Dashboard() {

  const [state, dispatch] = useReducer(reducer, initialState);

  return (

      <CssBaseline />

        <Container maxWidth="lg" className={classes.container}>
          <Grid container spacing={2}>
            {/* Chart */}
            <Grid item xs={12} sm={12} md={6} lg={6} xl={6}>
              <Paper className={fixedHeightPaper}>
                <AppContext.Provider value={{ state, dispatch }}>
                  <Chart title="Sales by Marketplace"/>
                </AppContext.Provider>
              </Paper>
            </Grid>
            <Grid item xs={12} sm={12} md={6} lg={6} xl={6}>
              <Paper className={fixedHeightPaper}>
              <AppContext.Provider value={{ state, dispatch }}>
                  <Chart title="Sales by Marketplace"/>
                </AppContext.Provider>
              </Paper>
            </Grid>
            <Grid item xs={12} sm={12} md={6} lg={6} xl={6}>
              <Paper className={fixedHeightPaper}>
              <AppContext.Provider value={{ state, dispatch }}>
                  <Chart title="Sales by Marketplace"/>
                </AppContext.Provider>
              </Paper>
            </Grid>
            <Grid item xs={12} sm={12} md={6} lg={6} xl={6}>
              <Paper className={fixedHeightPaper}>
              <AppContext.Provider value={{ state, dispatch }}>
                  <Chart title="Sales by Marketplace"/>
                </AppContext.Provider>
              </Paper>
            </Grid>
          </Grid>
        </Container>

  );
}

Answer: I know this was a long time ago, but there is a "syncId" property to put on your chart. All charts with the same syncId will show tooltips at the same time.
Comment: Perfect: https://recharts.org/en-US/examples/SynchronizedAreaChart is an example


How update a value of a HashMap that is an object?

Question: If the value is a class called Hand
public class Hand implements Iterable<Card>{
    protected List<Card> cards;
    .....
    .....
}

and my HashMap is
HashMap<Integer, Hand> hashMap;

If I want to add a Card object to the instance field of Hand i.e cards, do I need to do
hashMap.get(i).cards.add(Card Object)

or do I need to do
hashMap.put(i, hashMap.get(i).cards.add(Card Object))

Comment: Did you try both options to see what happens?
Comment: `add(Card Object)` won't compile.
Answer: Assuming the Hand instance already exists, you would want to retrieve the instance:
Hand hand = hashMap.get(i);

Once you have the instance, you want to access its cards list and add another card to it:
Card card = ...;
hand.cards.add(card); //consider using a getMethod to get the cards

Or in your own code:
hashMap.get(i).cards.add(card);

You don't need to remap the hand element in the hashmap because you aren't replacing the actual Hand object, so the reference to it in the map remains the same. All you are doing is modifying one of its properties by adding an item in the Hands's cards.
Answer: Use a getter for cards within Hand class like
protected List<Card> getCards() {
    return this.cards;
}

and then update as follows -
hashMap.get(i).getCards().add(new Card())

Attempting
hashMap.put(i, hashMap.get(i).getCards().add(new Card()))

is trying to put a boolean returned from add at index i instead and wouldn't work good with your logic.


'The specified invariant name 'System.Data.SqlClient' wasn't found in the list of registered .NET Data Providers.' on a .netCore project

Question: I am getting the error above on a .netCore API project that's referencing .netCore library that connects to a SQL database. Can anyone help me here?
I have already referenced the System.Data.SQLClient or Microsoft.Data.SqlClient and still no luck.
Thanks
Answer: There is no global configuration (commonly known as GAC) in .NET Core. As a result, the provider is not registered by default. You will have to manually register the provider. You can register it as
<code>DbProviderFactories.RegisterFactory("System.Data.SqlClient", System.Data.SqlClient.SqlClientFactory.Instance);

//for Connection
var factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
DbConnection connection = factory.CreateConnection();
</code>
Comment: Thanks. How about if the library was build in .net framework? is the a 'DbProviderFactories.RegisterFactory()' for a .net framework or it's equivalent?
Comment: We have a .Net Framework 4.6.1 assembly and included it on a .Net Core 3.1 api, so we needed to include 'Microsoft.Data.SqlClient' on both, the library and the main api project.
Change code from Systems.Data.SqlClient to Microsoft.Data.SqlClient Also require to add this line at Startup constructor:

`public Startup(IConfiguration configuration)
{
    Configuration = configuration;

    // Chesare. Requerido para .net Core
    DbProviderFactories.RegisterFactory("Microsoft.Data.SqlClient", Microsoft.Data.SqlClient.SqlClientFactory.Instance);
}`
Comment: I am not exactly sure, but the library might search in `machine.config`. If you want to overwrite the `DbProviderFactories`, then you might have to update your `app.config` file. Something like  `     `
Comment: see [Could not load file or assembly 'System.Data.SqlClient](https://stackoverflow.com/questions/53159316/could-not-load-file-or-assembly-system-data-sqlclient-version-4-4-0-0)
Answer: Just changing Systems.Data.SqlClient to Microsoft.Data.SqlClient in Nuget already worked for me