text:
Q: should I write more descriptive function names or add comments? This is a language agnostic question, but I'm wandering what people prefer in terms of readability and maintainability... My hypothetical situation is that I'm writing a function which given a sequence will return a copy with all duplicate element removed and the order reversed.
/*
*This is an extremely well written function to return a sequence containing
*all the unique elements of OriginalSequence with their order reversed
*/
ReturnSequence SequenceFunction(OriginalSequence)
{...}

OR
UniqueAndReversedSequence MakeSequenceUniqueAndReversed(OriginalSequence)
{....}

The above is supposed to be a lucid example of using comments in the first instance or using very verbose function names in the second to describe the actions of the function.
Cheers,
Richard

A: I prefer the verbose function name as it make the call-site more readable. Of course, some function names (like your example) can get really long.
Perhaps a better name for your example function would be ReverseAndDedupe. Uh oh, now it is a little more clear that we have a function with two responsibilities*.  Perhaps it would be even better to split this out into two functions: Reverse and Dedupe.
Now the call-site becomes even more readable:
Reverse(Dedupe(someSequence))

*Note: My rule of thumb is that any function that contains "and" in the name has too many responsibilities and needs to be split up in to separate functions.

A: Personally I prefer the second way - it's easy to see from the function name what it does - and because the code inside the function is well written anyway it'll be easy to work out exactly what happens inside it.
The problem I find with comments is they very quickly go out of date - there's no compile time check to ensure your comment is correct!
Also, you don't get access to the comment in the places where the function is actually called.
Very much a subjective question though!

A: Ideally you would do a combination of the two. Try to keep your method names concise but descriptive enough to get a good idea of what it's going to do. If there is any possibility of lack of clarity in the method name, you should have comments to assist the reader in the logic.

A: Even with descriptive names you should still be concise. I think what you have in the example is overkill. I would have written
UniqueSequence Reverse(Sequence)

A: I'd probably do one of these:

*

*Call it ReverseAndDedupe (or DedupeAndReverse, depending which one it is -- I'd expect Dedupe alone to keep the first occurrence and discard later ones, so the two operations do not commute). All functions make some postcondition true, so Make can certainly go in order to shorten a too-long name. Functions don't generally need to be named for the types they operate on, and if they are then it should be in a consistent format. So Sequence can probably be removed from your proposed name too, or if it can't then I'd probably call it Sequence_ReverseAndDedupe.

*Not create this function at all, make sure that callers can either do Reverse(Dedupe(x)) or Dedupe(Reverse(x)), depending which they actually want. It's no more code for them to write, so only an issue of whether there's some cunning optimization that only applies when you do both at once. Avoiding an intermediate copy might qualify there, but the general point is that if you can't name your function concisely, make sure there's a good reason why it's doing so many different things.

*Call it ReversedAndDeduped if it returns a copy of the original sequence - this is a trick I picked up from Python, where l.sort() sorts the list l in place, and sorted(l) doesn't modify a list l at all.

*Give it a name specific to the domain it's used in, rather than trying to make it so generic. Why am I deduping and reversing this list? There might be some term of art that means a list in that state, or some function which can only be performed on such a list. So I could call it 'Renuberate' (because a reversed, deduped list is known as a list "in Renuberated form", or 'MakeFrobbable' (because Frobbing requires this format).
I'd also comment it (or much better, document it), to explain what type of deduping it guarantees (if any - perhaps the implementation is left free to remove whichever dupes it likes so long as it gets them all).
I wouldn't comment it "extremely well written", although I might comment "highly optimized" to mean "this code is really hard to work with, but goes like the clappers, please don't touch it without running all the performance tests".
I don't think I'd want to go as far as 5-word function names, although I expect I have in the past.

A: I comment where there's an explanation in order that a descriptive name cannot adequately convey.  If there's a peculiarity with a library that forced me to do something that appears non-standard or value in dropping a comment inline, I'll do that but otherwise I rely upon well-named methods and don't comment things a lot - except while I'm writing the code, and those are for myself.  They get removed when it is done, typically.
Generally speaking, function header comments are just more lines to maintain and require the reader to look at both the comment and the code and then decide which is correct if they aren't in correspondence.  Obviously the truth is always in the code.  The comment may say X but comments don't compile to machine code (typically) so...
Comment when necessary and make a habit of naming things well.   That's what I do.


text:
Q: VBA userform to execute selections only after hitting command button I am having a hard time to make vba to execute my selection only after pressing the command button (The GO button in this case). Attached are the picture of the userform, which is not made by activeX control, and the code I am working on. Thanks!

Private Sub MR_Click()

If MR.Value = True Then
Rows(6).Delete
End If

End Sub

Private Sub PMS_Click()

If PMS.Value = True Then
Rows(7).Delete
End If

End Sub

Private Sub VOIDMR_Click()

If VOIDMR.Value = True Then
Rows(13).Delete
End If

End Sub

Private Sub VOIDPMS_Click()

If VOIDPMS.Value = True Then
Rows(14).Delete
End If

End Sub

A: Like this, using a "Go" button's _Click event procedure (presumably GO_Click(), but modify if needed) to check against each of the checkboxes and do the deletion accordingly.
Private Sub GO_Click()
If MR.Value = True Then
    Rows(6).Delete
End If
If PMS.Value = True Then
    Rows(7).Delete
End If
If VOIDMR.Value = True Then
    Rows(13).Delete
End If
If VOIDPMS.Value = True Then
    Rows(14).Delete
End If
End Sub
'These event procedures won't do anything, and can be removed:
Private Sub MR_Click()
End Sub
Private Sub PMS_Click()
End Sub
Private Sub VOIDMR_Click()
End Sub
Private Sub VOIDPMS_Click()
End Sub

The checkboxes' _Click event procedures are no longer needed.
To note about the event procedures, they will fire whenever the event occurs. So for an checkbox with a _Click event, any time the user checks (or unchecks) _Click handler will execute.
As noted, exercise caution when deleting elements from a collection, as this typically needs to be done in reverse order (when you delete row 6, row 7 becomes row 6, so if both MR and PMS are checked, what's in Row 7 initially will not be deleted). This may require some additional code change, but very simply it seems by just re-ordering the commands within GO_Click, should handle this:
Private Sub GO_Click()
If VOIDPMS.Value = True Then
    Rows(14).Delete
End If
If VOIDMR.Value = True Then
    Rows(13).Delete
End If
If PMS.Value = True Then
    Rows(7).Delete
End If
If MR.Value = True Then
    Rows(6).Delete
End If

End Sub

A: just a stylistic variation on @DavidZemens code:
Private Sub GO_Click()
    With Me '<-- reference the userform
        Select Case True
            Case .MR '<-- if MR checkbox control is True
                Rows(6).Delete
            Case .PMS '<-- if PMS checkbox control is True
                Rows(7).Delete
            Case .VOIDMR '<-- if VOIDMR checkbox control is True
                Rows(13).Delete
            Case .VOIDPMS '<-- if VOIPMS checkbox control is True
                Rows(14).Delete
        End Select
    End With
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does a vao know which vbo's/ ibo's are being bound to it? After doing some basic tests, a few things stay unclear to me:

*

*While you're initializing your application does the order in which you bind a vao, vbo and ibo matter? From most tutorials i have seen you generate the vao first then the vbo and then the ibo but in others they changed the order and it seemed to work...

*How does the vao know what is being bind to it? Do you call some special function(behind the scenes) when calling glBindBuffer to the active vao object?
I'm not only asking "how" they work but also "why" they work, I've tried reading some of the openGL specifications but it was too confusing for a novice openGL programmer.

A: Opengl is a state macine : when you call glBindVertexArray, it tells to opengl that it's this vao that is active, and thus, it's to this vao that the vbos will be bound. Then you have to recall glBindVertexArray with another vao index to change the active vao, and then bind another vbo to it.


text:
Q: Ambiguity in composition of functions in MySQL Consider the simple student table,
mysql> select * from student;
+--------------+--------------+-------+
| student_name | joining_date | marks |
+--------------+--------------+-------+
| Anurag       | 2013-06-15   |    50 |
| Chandra      | 2014-07-12   |    65 |
| Dev          | 2014-03-25   |    80 |
| Gopal        | 2015-05-12   |    60 |
| Indra        | 2015-05-20   |    75 |
| Ram          | 2015-01-10   |    75 |
| Shyam        | 2015-01-10   |    50 |
+--------------+--------------+-------+
7 rows in set (0.00 sec)

I need to find:

In which year, did maximum students joined the school?

So, it is similar to max(count()) with a group by. But since SQL does not allow max(count()), I found an alternative to use >= all.
Here is the query and result:
mysql> select extract(year from joining_date) from student group by extract(year from joining_date) having count(student_name) >= all(select count(student_name) from student group by joining_date);
+---------------------------------+
| extract(year from joining_date) |
+---------------------------------+
|                            2014 |
|                            2015 |
+---------------------------------+
2 rows in set (0.00 sec)

I must get only 2015 but it generates two tuples.
When I removed = from >= all, I get the required result. But the maximum must to greater than all the elements right?
Another query for the similar question uses >=.
Consider the account table:
mysql> select * from account;
+----------------+-------------+---------+
| account_number | branch_name | balance |
+----------------+-------------+---------+
| A101           | Downtown    |     500 |
| A102           | Perryridge  |     400 |
| A201           | Brighton    |     900 |
| A215           | Mianus      |     700 |
| A217           | Brighton    |     750 |
| A222           | Redwood     |     700 |
| A305           | Round Hill  |     350 |
+----------------+-------------+---------+
7 rows in set (0.00 sec)

I need to determine the branch that has the highest average balance

mysql> select branch_name from account group by branch_name having avg(balance) >= all(select avg(balance) from account group by branch_name);
+-------------+
| branch_name |
+-------------+
| Brighton    |
+-------------+
1 row in set (0.00 sec)

But when replacing >=' by>' I get,
mysql> select branch_name from account group by branch_name having avg(balance) > all(select avg(balance) from account group by branch_name);
Empty set (0.00 sec)

What is the issue here?

A: Year of max students
Return only the first found year with max students:
SELECT tmp.year
FROM (
   SELECT count(*) AS total, EXTRACT(year FROM joining_date) AS year
   FROM student
   GROUP BY year
   ORDER BY total DESC
) AS tmp
LIMIT 1;

Return all years with equal max students:
SELECT tmp.year
FROM (
   SELECT count(*) AS total, EXTRACT(year FROM joining_date) AS year
   FROM student
   GROUP BY year
) AS tmp
WHERE tmp.total = (
   SELECT MAX(tmp.total)
   FROM (
      SELECT count(*) AS total
      FROM student
      GROUP BY EXTRACT(year FROM joining_date)
   ) AS tmp
);

I looked for ways to optimize this by reusing the subquery but found nothing that didn't make it much larger.
Highest average balance
Return only the first found branch with highest average:
SELECT branch_name
FROM account
GROUP BY branch_name
ORDER BY AVG(balance) DESC
LIMIT 1;

Return all branches with equal highest average:
SELECT branch_name
FROM account
GROUP BY branch_name
HAVING AVG(balance) = (
   SELECT AVG(balance)
   FROM account
   GROUP BY branch_name
   ORDER BY AVG(balance) DESC
   LIMIT 1
);


text:
Q: ConnectionRefusedError in Robot Framework: why does target machine actively refuse it? Say my email address is: geode@blahemail.com. The blahemail is a google mail. I mean, it is powered by Gmail. I am trying to connect to it using Robot Framework in Pycharm and ImapLibrary. So far, I have tried these:
Open Mailbox   host = imap.gmail.com    user = user    password = pass     port = 993

and
Open Mailbox    host = imap.blahemail.com    user = user    password = pass     port = 993

I have also tried ImapLibrary2. In all cases, I get this error:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

What should I do?


text:
Q: Positioning text at node This should be a simple question about positioning text with nodes using pgfplots.
To make a skew node line with text I'd use
\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat = newest}

\begin{document}

\begin{figure}
\begin{tikzpicture}
\begin{axis}[
    title = DPPH,
    xlabel = Applied Magnetic Field (I Guess) / G,
    xmax = 8,
    xmin = -8,
    ymax = 300,
    ymin = -300,
    ytick = \empty,
    xtick pos = left]

    \addplot[black, % Plotting the data
    no marks]
    table[x=xaxis,y=yaxis] {dpph2.dat};

    \node[coordinate,
    pin = {45:g factor = 1.96}
    ] at (0.2,224) {};

\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}

for example.
To make a skew node with rotated text, where I can position the text about the node line using above, below, left, right or a combination of those, I'd change the \node part above to
\node[coordinate,
    pin = {[rotate=45]right:g factor = 1.96}
    ] at (-0.3,250) {};

My question: how do I use above, below, right, etc in the first code (without rotating the text as well as the node line)?  I tried things like 45right, 45, right, [45]right, but none of my guesses worked and I can't seem to find an example online.
EDIT
Here's what the first bit of code I put above gives me

and here's what I'd like to be able to do (just move where the text is with respect to the node line)

Thanks.

A: (Ab)using the code from Jake's answer to How can I force TikZ pin angle?, we can define a new style for the pins that uses a label whose anchor we set to label the text, and an empty pin to draw the line. You supply the arguments like [anchor for label]angle:text to make it similar to the default pin usage. Presumably, there is some way to automatically choose the anchor based on the angle, but my TikZ-fu is not strong enough for that :-) Note that the % at the end of the lines are necessary because of how TikZ interprets spaces.
\documentclass{standalone}

\usepackage{pgfplots}
\pgfplotsset{compat = newest}
\tikzset{
    aligned pin/.style args={[#1]#2:#3}{
        pin={[%
            inner sep=0pt,%
            label={[%
                append after command={%
                    node[%
                        inner sep=0pt,%
                        at=(\tikzlastnode.#2),%
                        anchor=#1,%
                    ]{#3}%
                }%
            ]center:{}}%
        ]#2:{}}%
    }
}
\begin{document}

\begin{tikzpicture}
\begin{axis}[
    title = DPPH,
    xlabel = Applied Magnetic Field (I Guess) / G,
    xmax = 8,
    xmin = -8,
    ymax = 300,
    ymin = -300,
    ytick = \empty,
    xtick pos = left
    ]

    \node[coordinate,
    aligned pin={[west]45:g factor=1.96},
    ] at (0,0) {};

\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Why is a Push Engine Required Our Architecture is using a Push Engine to send data to the browser ,
Could anybody please tell me  what is the use of Push Engine ??
(  Why is it required , as the same thing can be achivied  using a normal  AJAX programming )\
Please guide me .

A: AJAX is a pull method - it requires the client to connect to the server. If you have some information that you want to display live - for example a live score in a football game - the AJAX call has to be made at regular intervals - even when there is no data waiting on the server. A Push Engine is the reverse - the client and server maintain a connection and the server pushes data when there is data to be sent.

A: let's say your visiting a website, and the website is updated continuously. Your browser needs to keep updating the data that you're viewing, meaning that the browser needs to keep communicating with the server, and get the updates.
you can use ajax to make requests every few seconds, each time fetch more data from the server. Problem is - you need to make a lot of ajax calls, and you open a connection (a socket) for each, and eventually, it is a very slow process. if the interval between the requests is large, you will have a delay between the updates on the servers, and the updates in your browser.
to solve that, we can manipulate the HTTP calls - keep the request (the connection) open, and continuously send data. that way, when the server wants to send something to the client (browser), there's an open connection, and it doesn't need to way for the next ajax call by the browser.
HTTP servers have a timeout on the requests, so just before request times out, browser will close it and make a new one.
another (better) method is using XMPP protocal, which is used in chats like facebook's and msn.


text:
Q: Sendmail relay authentication I'm trying to set up my sendmail to authenticate against a relay (comcast). I'm not seeing any attempts to authenticate at all. I'm trying to just debug how authentication works, and can't connect all the pieces...
I have, in my .mc file:
define(`RELAY_MAILER_ARGS', `TCP $h 587')dnl
define(`SMART_HOST', `relay:smtp.comcast.net.')dnl
define(`confAUTH_MECHANISMS', `PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/client-info')dnl

And in my /etc/mail/client-info:
AuthInfo:*.comcast.net "U:root" "I:comcast_user" "P:comcast_password"

Now, I know everything is fine with the u/p, as I could authenticate directly through SMTP, using telnet.
There are two things I don't understand.

*

*When AuthInfo records are searched for, they are matched by the target hostname. How? Does it it use the map key (something I would expect), or uses the so-called "Domain" ("R:" parameter that I don't set in my auth-info line)

*What is "U:", really? Sendmail README (http://www.sendmail.org/m4/smtp_auth.html) says it's "user(authoraztion id)", and "I:" is "authentication ID". That suggests that my username should be in "U:", actually, but http://www.sendmail.org/~ca/email/auth.html says that "I:" is your remote user name.
The session looks like this:
[root@manticore]/etc/mail# sendmail -qf -v
Warning: Option: AuthMechanisms requires SASL support (-DSASL)

Running /var/spool/mqueue/p97CgcWq023273 (sequence 1 of 399)
my@email.com... Connecting to smtp.comcast.net. port 587 via relay...
220 omta19.westchester.pa.mail.comcast.net comcast ESMTP server ready
>>> EHLO my.host.name
250-omta19.westchester.pa.mail.comcast.net hello [my.ip.add.res], pleased to meet you
250-HELP
250-AUTH LOGIN PLAIN
250-SIZE 15728640
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-STARTTLS
250 OK
>>> STARTTLS
220 2.0.0 Ready to start TLS
>>> EHLO my.host.name
250-omta19.westchester.pa.mail.comcast.net hello [my.ip.add.res], pleased to meet you
250-HELP
250-AUTH LOGIN PLAIN
250-SIZE 15728640
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 OK
>>> MAIL From:<> SIZE=2183
550 5.1.0 Authentication required
MAILER-DAEMON... aliased to postmaster
postmaster... aliased to root
root... aliased to my@email.com
postmaster... aliased to root
root... aliased to my@email.com
>>> RSET
250 2.0.0 OK

[root@manticore]/etc/mail# sendmail -d0.1
Version 8.14.3
 Compiled with: DNSMAP LOG MAP_REGEX MATCHGECOS MILTER MIME7TO8 MIME8TO7
                NAMED_BIND NETINET NETINET6 NETUNIX NEWDB NIS PIPELINING SCANF
                SOCKETMAP STARTTLS TCPWRAPPERS USERDB XDEBUG

Thanks,
  Pawel.

A:
if FEATURE(`authinfo') is used, then the hostname in the map entry
  must match exactly the hostname of the ISP mailserver

See at your SMART_HOST + client-info

What is "U:", really?

Well, SMTP Authentication states in pure English

U user (authorization) id
I authentication id
...
User or authentication id must exist as well as the password. All
  other entries have default values. If one of user or authentication id
  is missing, the existing value is used for the missing item.

A: My solution was very simple. Default OpenBSD sendmail doesn't have SASL flag set, and can not do any authentication, even plain text. I actually expected that SASL is only used for "advanced" authentication. My -d0.1 output clearly shows no SASL flag.
For those who have the same issue: this page (http://theory14.wordpress.com/2009/06/16/openbsd-smtp-authtls-imaps-proxy/) vaguely (it's not a step-by-step how-to-fix-OpenBSD-sendmail-for-SASL page) explains on the necessary steps to go through. Basically, -- download userland source, and rebuild sendmail with -DSASL flag.
P.S. I think, the "U:" is really the user that runs sendmail, where "I:" is the user to authenticate to the client.


text:
Q: How to unlock password protected MicroSD? Recently I locked a MicroSD memory card from my Nokia 6210 (S60v3) and forgot the password.
It was not much of a problem but today I formatted the phone and it is now asking for password. I tried to connect it to PC but it doesn't show up.
Is there some way I can access its content?

A: I hope the following solutions will help you. From https://sites.google.com/site/way2smarthacker …

It is common knowledge that if the password for the card is lost then
  it will be blocked for further use. In such a situation, the user
  can interface his mobile with the PC using Bluetooth or Infrared and
  make the changes and find the password in the file obtained
  thereafter.....
Solution number one

*

*Go to file manager on your mobile,

*In the "Settings" option,

*Choose system folders,

*In the "System" folder, there's a file called "MMCSTORE",

*Send that to your PC using IR/Bluetooth,

*Then open it in notepad.

*The password you need for your memory card is in that file

  Solution number two:

*

*Insert card into your phone or through card reader but don't access it through phone.

*Run FExplorer and Open the path C:\system.

*You will find a file called mmcstore ,rename the file mmcstore.txt

*Copy that file(mmcstore.txt) to your pc and open that file in notepad.

*You will find your password in that file.(MMC)   you can download FExplorer here
For Micro SD:
Put the card in any E series mobile or N95 etc and format it it will
  not ask for password.


text:
Q: Does $f'(x) → 3$ as $x → 0$ imply $f'(0)$ exists? (Counterexample verification) If $f(x)$ is a real function such that $f'(x) → 3$ as $x → 0$, does that mean $f'(0)$ exists? I ask this because of problem 9 on page 115 of Rudin's Principles of Mathematical Analysis. The actual question is slightly different:

Let $f$ be a continuous real function on $ℝ^1$, of which it is known
  that $f'(x)$ exists for all $x ≠ 0$ and that $f'(x) → 3$ as $x → 0$.
  Does it follow that $f'(0)$ exists?

I believe it does exist because the left and right limits are equal and the function itself is continuous and defined (is there more that must be met than this?). But if continuity is not known, then I think this conclusion is invalid. Would the following counterexample be valid if continuity is not assumed?

Let $f(x) = 3x - 5$, for $x < 0$ and $f(x) = 3x + 5$, for $x ≥ 0$. Then clearly $f'(x) → 3$ as $x → 0$, but $f'(0)$ does not exist because of the jump discontinuity on $f(x)$ at $x=0$.

A: Your counter example when the function is not continuous is right; however, you can directly prove the existence of $f'(0)$ when assuming the continuity by L'Hoptial's theorem for limits as follows
$$\mathop {\lim }\limits_{x \to 0} \frac{{f(x) - f(0)}}{{x - 0}} = \mathop {\lim }\limits_{x \to 0} \frac{{f'(x)}}{1} = \mathop {\lim }\limits_{x \to 0} f'(x) = 3$$


text:
Q: How to get the list of possible operational attributes for an objectClass with python-ldap? With this python snippet, I can get the list of all the available objectClasses in a LDAP server:
import ldap

conn = ldap.initialize("ldap://127.0.0.1:389")
conn.simple_bind_s("cn=admin,dc=mydomain,dc=tld", "mypassword")
res = conn.search_s("cn=subschema", ldap.SCOPE_BASE, "(objectclass=*)", ["*", "+"])
subschema_entry = res[0]
subschema_subentry = ldap.cidict.cidict(subschema_entry[1])

subschema = ldap.schema.SubSchema(subschema_subentry)
object_class_oids = subschema.listall(ldap.schema.models.ObjectClass)
object_classes = [subschema.get_obj(ldap.schema.models.ObjectClass, oid) for oid in object_class_oids]

From this point this is easy to get all the required and optional attributes with object_class.may and object_class.must, but how can I get the list of the operational attributes applicable on a given objectClass? For instance the memberof attribute brought by the memberof OpenLDAP overlay, or the pwdAccountLockedTime attribute brought by the ppolicy overlay.

A: Operational attributes are maintained by the LDAP server. They are not "applicable on a given objectClass". Thus they must not be set by user applications and they are not referenced in object class descriptions.
You can look at the instance attribute AttributeType.usage which contains an Integer indicating its usage.
See also:

*

*RFC 4512 -- Operational Attributes

*ldap.schema.models -- dict AttributeUsage used in AttributeType


text:
Q: Form Validation from service.ts Angular I need to add custom validators to a form from formvalidation.service.ts
form.component.ts
myForm = this.formBuilder.group({
    name: ['', [Validators.required,]]
});

formvalidator.service.ts
passwordValidator(): ValidatorFn {
   return (control: AbstractControl): {[key: string]:any} | null => {
     const year = control.value;
     if (!/[0-9]/.test(year) || !/[A-Z]/.test(year)) {
       return { passwordPattern: true};
     }
     return null;
   }
}

I import it as  FormValidator.passwordValidator(). It can't import this to the component.ts file.
But when the static passwordValidator(): ValidatorFn {} it can do. but my superviser advice me to not to use static methods.

A: You need service class instance in form.component:
export class FormComponent {
  ...
  constructor(private validator: FormValidatorService) {}
  myForm = this.formBuilder.group({
    name: ['', [Validators.required, this.validator.passwordValidator]]
  });
  ...

}

A: You can not import as FormValidator.passwrodValidator, but you can inject the service in the constructor of your component and use
constructor(private formValidator:FormValidator){}
//and use
name:['',this.formValidator.passwordValidator]

The another option is declare the function outside the service (but in the same .ts)
export function passwordValidator(): ValidatorFn {..}

Then you can import {passwordValidator} from './services/service.ts'


text:
Q: TGGoodsinbot v1.1 какие функции добавить? Друзья,
Добавил в магазин оплату товаров Yoomoney.
Используется Aiogram.
Бот развернут в продуктиве на: https://t.me/Goodsinbot
Исходный код выложил сюда:
https://github.com/rashidovich2/TGGoodsInbot
Критика, замечания приветствуются, предложения - очень интересны!


text:
Q: Firebase, como redireccionar luego de iniciar sesión? necesito ayuda con la redirección luego de iniciar sesión en Firebase, lo que quiero es que cuando los datos ingresados sean correctos se redireccione automáticamente a X pagina pero no tengo idea de como hacer. Este es el codigo que estoy usando:
const inputEmail = document.getElementById('inputEmail');
const inputPassword = document.getElementById('inputPassword');
const btnIniciarSesion = document.getElementById('btnIniciarSesion');

btnIniciarSesion.addEventListener('click', e => {
    const email =  inputEmail.value;
    const password = inputPassword.value;
    const auth = firebase.auth();
    const promise = auth.signInWithEmailAndPassword(email, password);
    promise.catch(e => console.log(e.message));
});

Encontre una forma para redireccionar pero lo hace siempre así los datos no sean correctos:
firebase.auth().onAuthStateChanged(user => {
  if(user)
  {
     window.location = 'home.html';
  }
});

Espero me puedan guiar para realizar esto.

A: obtuve ayuda en Stackoverflow en ingles, asi que dejo aquí la solución que me sirvio:
btnIniciarSesion.addEventListener('click', e => {
    const email =  inputEmail.value;
    const password = inputPassword.value;
    const auth = firebase.auth();
    const promise = auth.signInWithEmailAndPassword(email, password)
    .then(user => {
        location = 'home.html' //Url aqui
    }).catch(error => {
        console.error(error);
    })
    promise.catch(e => console.log(e.message));
});

A: usas ahora si el validador del usuario si no esta logueado te devuelve a donde quieras y ya
function observador () {
    firebase.auth().onAuthStateChanged(function(user) {
        const dropdownMenuButton = document.getElementById('dropdownMenuButton')
        if (user) {
          var email = user.email;
          dropdownMenuButton.innerHTML=email
          console.log('el usuario es '+ email')
        } else {
          window.location.href='/index.html'
        }
      });


text:
Q: PFQuery findObjectsInBackgroundWithBlock does not return I copied the example for a PFQuery right out of the docs, put my field and class names in it, but it never hits the completionBlock.
- (void) loadMyWindows {
    PFQuery *query = [PFQuery queryWithClassName:@"RGWindow"];
    [query whereKey:@"creatorID" equalTo:me.facebookID];

    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

        // it never gets here...

        if (!error) {
            NSLog(@"Successfully retrieved %d objects.", objects.count);
        for (PFObject *object in objects) {
            NSLog(@"%@", object.objectId);
        }

        [self gotoMain];
    } else {
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];

I've double checked many times...there are several RGWindow objects in the Data Browser, they have a "creatorID" field, and their ACL's say Public Read.
I'm stumped.

A: I finally found the solution: make SURE that all your objects are instantiated before attempting a call. If you have anything null, it hangs prior to the query and block - it just flat out stops running the code for that particular query. For example:
NSLog(@"test1");
PFQuery *dailyChallengesQuery = [GrowthChallenges query];
NSLog(@"test2");
[dailyChallengesQuery whereKey:kParse_GrowthChallengesGrowthRole equalTo:currentRole];
//When currentVirtue = nil, THIS JUST HANGS - nothing below here is called properly
[dailyChallengesQuery whereKey:kParse_GrowthChallengesGrowthVirtue equalTo:currentVirtue];
NSLog(@"test3");
[dailyChallengesQuery getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
    NSLog(@"test4");
    currentChallenge = (GrowthChallenges *)object;
    [self setupTableView];
}];

When currentVirtue is nil, it logs:
test1
test2
However, when currentVirtue is set properly, it logs:
test1
test2
test3
test4
Check your me.facebookID variable to be sure it is non-nil prior to setting up your query.

A: As it turns out, my PFObject subclass had an init method which is not allowed, an obviously caused havoc in this random place. Maybe I should have read the docs more.


text:
Q: Recording on database the time of a page view i build a site (in PHP) where the users register and then access to reserved Powerpoint presentations. The owner told me to record the time users spend on viewing presentation, but i don't know how to display and record this kind of data. I think that JS and AJAX could help me, but i don't know what script can i use to do that.
Thank you in advice for your opinions and help.

A: basically you should trigger a php script when the user closes the powerpoint presentation, and this can be achieved for example opening the presentation in a modal window and force the user to click on a "close" button to terminate the presentation.
Another solution may be to open the presentation in a new window (even if is not so elegant) and use this script to trigger and action when the window onunload event is triggered:
    Click me!

window.onclick = function() {
    var win = window.open("/");
    win.onload = function() {
        console.log("onload");
        win.onunload = function() {
            alert("onunload");
        }
    }
}

Hope this help.


text:
Q: { Error: [React Intl Error MISSING_DATA] Missing locale data for locale: "th" in Intl.NumberFormat I've checked this source https://formatjs.io/docs/react-intl#runtime-requirements , and tried to add this code
import { NumberFormat } from '@formatjs/intl-numberformat'

NumberFormat.__addLocaleData(
  require('@formatjs/intl-numberformat/dist/locale-data/en.json') // locale-data for en
)

NumberFormat.__addLocaleData(
  require('@formatjs/intl-numberformat/dist/locale-data/th.json') // locale-data for th
)

But it doesn't help, also I've added defaultLocale param :
<IntlProvider defaultLocale={locale}></IntlProvider>

to intl provider , but it also doesn't help. I have 2 languages , for en language I don't get this error , only for th language , what should I do ?

A: Try upgrade your Node Version. I had 10 and moved to 14.x: Issue was gone

A: Issue is with the object being utilized.
Check the object structure of translation content.
IntlProvider should have messages property whose value should be an object which contains property mentioned in id of FormattedMessage


text:
Q: How do I resolve "Type or namespace could not be found" compilation error? I'm concerned that the web hosting that I'm paying for is not configured correctly.  ASP.NET Web Sites which compile and run correctly on my local machine don't work once they're deployed.
The issue I'm dealing with is a compilation error: CS0246, "Type or namespace could not be found (Are you missing a 'using' directive or assembly reference?)
My Web Site contains the following files and folders:
websitedemo/Default.aspx
websitedemo/Default.aspx.cs
websitedemo/App_Code/HelloClass.cs

The compilation error occurs if I attempt to use any code contained in my App Code folder.
I've included the entire /websitedemo/ folder in this archive if it helps troubleshoot the error: http://kivin.ca/websitedemo/source.zip
I've left the folder in debug mode.  The compilation error screen may be viewed at http://kivin.ca/websitedemo/
Best regards.
-- update:
If it helps troubleshoot this error, I've got the behaviour that occurs when I attempt to deploy an ASP.NET WebApplication instead of Website.
In the case that my aspx file includes a @Page direct like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="myproj._Default" Debug="true" %>
The compilation error I get is: 'Parser Error Message: Could not load type 'myproj._Default'.'
The webapps are being deployed via ftp using Build -> Publish -> [X] Replace matching files, [X] Only files needed to run this app. [X] Include App_Data folder.

A: I'd like to thank everyone for their support.  It's most appreciated.  I've been in contact with a specialist at my web hosting company and they've advised me that this isn't a code or server configuration error, but just a missed step in my control panel.
Setting my website working directory as a virtual dir resolved the issue.
Thanks to the stack overflow community and the outstanding support people at Softsys Hosting.

A: If you build your site locally and upload the resulting dll (that will contain HelloClass) to the bin directory, I bet it will work.

A: Try putting your HelloClass.cs in a namespace and put Using  at the top of your default file

A: http://msdn.microsoft.com/en-us/library/54dwfbb7.aspx
i think this may help you... if you have subfolders
also, app_code was introduced in framework 2.0, can you check that the web application on the live box is set to use framework 2.0 ? otherwise the classes wont get compiled in there


text:
Q: Behaviour of group representations under extension of field When studying behaviour of linear representations of finite groups under extension of fields, I came up across two natural questions, which I couldn't solve (Reference: Representations of finite groups: Algebra and Arithmatic by S. Weintraub).
Let $R$ be a ring which is $F$-algebra ($F$ is a field), $E$ be an extension of $F$, set $R'=E\otimes_F R$. If $M$ is an $R$-module, them $M'=E\otimes_F M$ is an $R'$-module.
Definition: If $M'$ is an $R'$ module that is isomorphic to $E\otimes_F M$ for some $R$-module $M$, then $M'$ is said to be defined over $F$.
(If I have understood this definion correctly, then in terms of matrix representations of groups, it says: if $\rho\colon G\rightarrow  GL(n,E)$ is a matrix representation of a finite group $G$, we say that it is defined over $F$ if there is $A\in GL(n,E)$ such that $A\rho(g)A^{-1}\in GL(n,F), \forall g\in G$.)
With this set up, an irreducible representation of $G$ over $F$ may decompose over $E$. Assume $G$ is finite group, and $char(F)>0$, $(char(F),|G|)=1$, $E$ is an extension of $F$.
Question 1: If $\rho_1, \rho_2, \cdots, \rho_r$ is the set of all inequivalent irreducible representations of $G$ over $F$, and if $\rho_i$ decomposes over $E$ as $\rho_{i1}\oplus \rho_{i2} \oplus\cdots \oplus \rho_{it_{i}}$  ($1\leq i\leq r$), is the set $\{ \rho_{ij} \colon 1\leq i\leq r, 1\leq j\leq t_i\}$ is complete set of irreducible representations of $G$ over $E$?
Question 2: If $M'$ is an irreducible $R'$ module, that is not defined over $R$, does some multiple of $M'$, say $dM'$ ($d\in \mathbb{N}$) is defined over $R$?

The second question, I tried, seems to have negative answer; I am not sure:
for example, consider a complex $1$-dimensional representation of $C_4=\langle x\colon x^4\rangle$ given by $x\mapsto [\sqrt -1]$. This representation is clearly not defined over $\mathbb{R}$. Some multiple of this representation (say $d$) will be the map $x\mapsto \sqrt-1 I_d$; still this representation (of dimension $d$) is not defined over $\mathbb{R}$, since this matrix $\sqrt-1 I_d$ is central, its conjugate in $GL(d,\mathbb{C})$ can not be in $GL(d,\mathbb{R})$.
In the paragraph before Prop: 4.17 in the book mentioned above (p.33), author may want to say positive answer to question 2, but I couldn't understood.


text:
Q: Posting photo via Facebook graph no longer working I'm trying to post a photo using the php-sdk - all was working for months successfully but all of the sudden no dice.
Other functions are still working with the same code base (ie: posting messages to wall) - its just the posting of photos that broke on my side.
try {
        $data = $facebook->api('/me/photos', 'post', $args);
      } catch (FacebookApiException $e) {
print_r($e);}

Is dumping:

FacebookApiException Object ( [result:protected] => Array ( [error_code] => 3 [error] => Array ( [message] => No URL set! [type] => CurlException ) ) [message:protected] => No URL set! [string:private] => [code:protected] => 3 [file:protected] => /locationofmy/base_facebook.php [line:protected] => 818 [trace:private] => Array ( [0] => Array [..............]

From the FB php-sdk lines 818:
    if ($result === false) {
      $e = new FacebookApiException(array(
        'error_code' => curl_errno($ch),
        'error' => array(
        'message' => curl_error($ch),
        'type' => 'CurlException',
        ),
      ));
      curl_close($ch);
      throw $e;
    }
    curl_close($ch);
    return $result;
  }

This was working for a long time - has something changed on Facebooks side?
EDIT: php-sdk version: 3.1.1
EDIT 2:
$tag = array(
                'tag_uid' => 'acct_num',
                'x' => 0,
                'y' => 0
            );

        $tags[] = $tag;

        $args = array(
            'message' => $item_description,
            'image'   => '@' . realpath($temp_path . $tempFile),
            'tags'    => $tags,
            );

A: Try changing the image to source. I believe this should fix your issue.
The Facebook API requires a source field but I did not see anything about an image field.
You may also have to pass the actual file contents instead of the real_path (based on the example). Or, alternatively, pass an external URL (based on my understanding of the documentation).
Source: https://developers.facebook.com/docs/reference/api/photo/
Example: https://developers.facebook.com/blog/post/498/

A: Probably that the file doesnt exist, or the file system can't serve it anymore. Can you confirm "$temp_path . $tempFile" - the error is no URL, usually that means no real path to image. I suspect, that the images are missing and/or your servers filled up and no local images are saving. (Yes, this has happened to me before!)


text:
Q: using a list of strings to traverse a dictionary python I have a dictionary in python that represents a directory structure, so something like
dict = {
    "file1.java": {
          "method1": [],
          "method2": []
     },
     "dir1": {
          "file2.java":{
           .
           .
           .
           },
           "dir2": {
                    "file3.java": {
                           "method3": ["hello", "hi"],
                           "method4": []
                    "file4.java": {
            }
     }

}

I also have have a list of strings like
list = ["dir1", "dir2", "file3.java", "method3"]

Is there an easy way to traverse the dictionary to access the data in method3 using the list
So I would like to be able to call
dict[list]

and have it do something like
 dict["dir1"]["dir2"]["file3.java"]["method3"]

and return something like
["hello", "hi"]

but I have no idea how long the list of strings will be  so the list
list = ["file1.java","method1"]

also needs to work

A: You can use the reduce built-in function.
db = {
    "file1.java": {
          "method1": [],
          "method2": []
     },
     "dir1": {
           "dir2": {
                    "file3.java": {
                           "method3": ["hello", "hi"],
                           "method4": []
                    },
                    "file4.java": {
                    }
            }
     }

}

def lookup(db, path):
    return reduce(dict.get, path, db)

print lookup( db, ["dir1", "dir2", "file3.java", "method3"] )

print lookup( db, ["file1.java","method1"] )

A: You can take advantage of the fact that dicts and arrays are reference types to do something like this...
current_entry = dict
for item in list:
    current_entry = current_entry[item]

# The element you want is now in current_entry

Of course, add appropriate error checking to make sure you don't try and select a dict element that doesn't exist.


text:
Q: Why does multiplication does not work with Read-Host value $table_num = Read-Host -Prompt 'Enter the table number you want to get printed'
for ($i=1; $i-lt 11; $i++){
    $ans = ($table_num*$i)
    write "$table_num*$i=$ans"
}

Above is the script which I was trying to execute and I get the result as below:
Enter the table number you want to get printed: 5
5*1=5
5*2=55
5*3=555
5*4=5555
5*5=55555
5*6=555555
5*7=5555555
5*8=55555555
5*9=555555555
5*10=5555555555

I am new to scripting and help me with my code.

A: As you did not point out what is the expected behavior I am not sure if I solve your issue, but I guess you want something like that
$table_num_str = Read-Host -Prompt 'Enter the table number you want to get printed'
$table_num = [int]::Parse($table_num_str)
for ($i=1; $i-lt 11; $i++){
    $ans = ($table_num*$i)
    write "$table_num*$i=$ans"
}

which when entered '5' results in
Enter the table number you want to get printed: 5
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50

So the problem was that Read-Host returns a string which when multiplied with X results in that string repeated X times.

A: The problem lies in type returned by Read-Host cmdlet.
$num = read-host
$num.GetType()

It returns Object[] which is implicitly converted to other types if required. Type is also converted to first argument type when binary operator is used (+, -, *). There are no * operator in object[] type. That's why it's converted to string and THEN multiplied. If first argument is int, PowerShell tries to convert it to int as well. You can tweak your code to use this conversion rules. Take a look at script below:
$table_num = Read-Host -Prompt 'Enter the table number you want to get printed'
1..10 | % { write "$table_num*$_=$($_*$table_num)" }

It also produces:
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50

A: Thanks for the answers!!
Actually I have added the data type int. And the script is good as below.
$table_num = Read-Host -Prompt 'Enter the table number you want to get printed'

        For ($i=1; $i-lt 11; $i++){
        $ans = ([int]$table_num*$i)
            write "$table_num  *  $i =  $ans"
        }

A: do {
    $table_num = read-host "Enter the table number you want to get printed"
    $a = ""
    if( ![int32]::TryParse( $table_num , [ref]$a ) ) {
        Write-Host "Only integers please"
    }
} until ($a -gt 0)

1..10 | % { Write-Host "$table_num*$_=$($_*$table_num)" }

A: To have a working calculation you need a number, not a string.
Multiplying a string gives this kind of result :
"test" * 5 # returns testtesttesttesttest

You could fix your issue like this:
[int]$input_number = $null

$input_string = Read-Host -Prompt 'Enter the table number you want to get printed'

while(-not [int]::TryParse($input_string, [ref]$input_number)) {
    $input_string = Read-Host -Prompt 'Please enter a number'
}

for ($i = 1; $i -lt 11; $i++) {
    $ans = ($input_number * $i)
    Write-Host "$input_number * $i = $ans"
}

[int]::TryParse($input_string, [ref]$input_number) will try to parse the input string as an integer and store the value in $input_number. As long as this fails (because of a bad input), the script will ask for a new input.
See this other question for additional information.


text:
Q: Why Is jQuery Not Submitting This Form? (Or What Have I Done Wrong? :-p) HTML:
<form action="https://live.sagepay.com/gateway/service/vspform-register.vsp" method="POST" id="sagepay_form">
    <input type="hidden" name="navigate" value="" />
    <input type="hidden" name="VPSProtocol" value="2.23">
    <input type="hidden" name="TxType" value="PAYMENT">
    <input type="hidden" name="Vendor" value="******************">
    <input type="hidden" id= "Crypt" name="Crypt" value="">
    <input id="payment_proceed" value="Proceed To Payment" class="mws-button green" type="button">
</form>

JS:
$("#payment_proceed").click(function() {
        $.post('/includes/cart/ajax/sagepay.php', { //This script just echos the base64 "Crypt" string required by sagepay.
                "cart_id": <?php echo $cart_id; ?>,
                "title": $("#title").val(),
                "first_name": $("#first_name").val(),
                "last_name": $("#last_name").val(),
                "telephone": $("#telephone").val(),
                "email": $("#email").val(),
                "line1": $("#line1").val(),
                "line2": $("#line2").val(),
                "line3": $("#line3").val(),
                "town": $("#town").val(),
                "county": $("#county").val(),
                "postcode": $("#postcode").val()
            },
            function(crypt){
                $("#Crypt").val(crypt); //The base64 "Crypt" string is inserted in to the hidden form field here.
                alert($("#Crypt").val()); //I just put this here to make sure it had received the "Crypt" string.
                $("#sagepay_form").submit(); //This doesn't work...
            });
    });

I have no idea why $("#sagepay_form").submit(); does not submit the form. My only guess is it's because the "action" url is a remote server. If this is the case, does anyone know how I can go about what I am trying to achieve?
Thanks, any help would be greatly appreciated.

A: Use  $("#sagepay_form").submit(function() ...instead of $("#payment_proceed").click(function().


text:
Q: Coredata fetch request using NSPredicate I want to do a phone number search in sqlite db. Phone table have a number field which holds a string value (eg: +1 (2-34)56-78 ).
If user enters search text as "234", then I need to fetch the phone numbers with only digits(eliminating all other alphabets or special characters in the string stored) using NSPredicate and compare it with the entered string. Should I do this using a predicate in a fetch request?
I tried with following predicate and it doesn't return me the expected result:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"contactName != null AND SUBQUERY(phoneList, $phone, ANY $phone.number CONTAINS[c] %@).@count > 0",searchText];

IS there any way to get this done? Can I use regular expression with NSPredicate for this?

A: NSPredicate doesn't support that kind of matching. Your Core Data model should include data that your app requires for filtering-- which might mean extra fields that are not normally visible to users. If you need to match numbers without regard to non-numeric characters, you should add a field which contains that data. If the actual string is +1 (2-34)56-78, add a secondary field where you store 12345678. Use this extra field in the predicate.


text:
Q: ¿Cómo convertir XML a Json con asp.net core 3.1? hola comunidad quisiera saber si esto se puede realizar covertir un xml a json he estado buscando por Internet pero vienen ejemplos con cosas desactualizadas si me pudieran proporcionar un link o un ejemplo se los agradecería.
este es un ejemplo que encontré pero creo ya esta obsoleto:
string xml = @"<?xml version='1.0' standalone='no'?>
<root>
  <person id='1'>
  <name>Alan</name>
  <url>http://www.google.com</url>
  </person>
  <person id='2'>
  <name>Louis</name>
  <url>http://www.yahoo.com</url>
  </person>
</root>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

string json = JsonConvert.SerializeXmlNode(doc);

Console.WriteLine(json);

A: Se me ocurre que podrias deserializar el xml a una class y serializar luego esta a json
C# Deserializing XML with namespace in .NET core
entiendo que en net core quizas debas agregar la referencia usando nuget:
System.Xml.Serialization.XmlSerializer

Entonces creas la clase en base al xml
[XmlRoot(ElementName="person")]
public class Person {
    [XmlElement(ElementName="name")]
    public string Name { get; set; }
    [XmlElement(ElementName="url")]
    public string Url { get; set; }
    [XmlAttribute(AttributeName="id")]
    public string Id { get; set; }
}

[XmlRoot(ElementName="root")]
public class Root {
    [XmlElement(ElementName="person")]
    public List<Person> Person { get; set; }
}

quedando la deserializacion
string xmlStr = @"<?xml version='1.0' standalone='no'?>
                    <root>
                      <person id='1'>
                      <name>Alan</name>
                      <url>http://www.google.com</url>
                      </person>
                      <person id='2'>
                      <name>Louis</name>
                      <url>http://www.yahoo.com</url>
                      </person>
                    </root>";

var ms = new MemoryStream(Encoding.UTF8.GetBytes(xmlStr));
XmlSerializer serializer = new XmlSerializer(typeof(Root));
var root = (Root)serializer.Deserialize(ms);

Teniendo la deserializada del xml solo queda serializarla a json
Try the new System.Text.Json APIs
como usas net core 3.1 puedes referenciar a System.Text.Json que es propia del framework no necesitas ninguna libreria de terceros
string jsonString = JsonSerializer.ToString<Root>(root);


text:
Q: Send a response from the serve-side to client-side (Node.js, javascript) Based on the following structure below, I want to send my response (simple array ["Tom", "Bob", "Sam"])  from the server.js to index.js  Is it possible?
server.js
app.get("/*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "frontend", "index.html"));
});

app.post('/settings', function(req, res, next){
res.status(200).json({
                ok: true,
                data: ["Tom", "Bob", "Sam"]
            });
});

app.listen(process.env.PORT || 3000);

frontend/index.html

        Dashboard
        Settings

/frontend/static/js/index.js
document.querySelector("#app").innerHTML = await view.getHtml(); // load page.html
//console.log(data);

/frontend/static/html/page.html
        <button id="btn">Save</button>

A: Thank you for the comment - I believe I understand what you're asking for now.
If you want to retrieve the data in your index.js file, the best way to handle this is probably to move your request code to index.js. Remove the  tag from your page.html file and instead put it in index.js. The code in index.js will run once the page loads, similarly to what is happening in the page script.
You'll need to wait until your fetch completes before doing anything with the resulting data, but if you move the fetch into your index.js you can call other functions in the file with the data, or alternatively declare a variable outside of your fetch call to let other functions in your index.js use it.


text:
Q: Google Analytics Polymer Web Components - Safari Datepicker I am using Google's Polymer Analytics Web Components to build a dashboard. However, these elements seem to rely on HTML 5 (great in most cases), but with Safari (Mac), their is no native HTML 5 datepicker.
How does one go about binding JqueryUI Datpicker (or equivalent) to these components?
for example:
 <google-analytics-date-selector></google-analytics-date-selector>

creates the following shadow code block:
<google-analytics-date-selector class="x-scope google-analytics-date-selector-0">

    Start Date
    <input id="startDate" type="date" class="style-scope google-analytics-date-selector hasDatepicker" max="2016-03-30" min="2005-01-01">

    End Date
    <input id="endDate" type="date" class="style-scope google-analytics-date-selector" min="2016-03-24" max="2016-03-31">

</google-analytics-date-selector>

How can I target the #startDate and #endDate input elements with JQUI Datepicker

A: You could use <paper-date-picker>, which works in multiple browsers, including Safari -- or pick one of the other date pickers from exploring Custom Elements.
The <paper-date-picker> docs show an example snippet:
<paper-dialog class="paper-date-picker-dialog" modal>
  <paper-date-picker date="[[date]]"></paper-date-picker>

    <paper-button dialog-dismiss>Cancel</paper-button>
    <paper-button dialog-confirm>OK</paper-button>

</paper-dialog>

which creates a modal dialog, containing the date-picker, as seen in this Safari screenshot:


text:
Q: Unable to use find -name correctly
*

*Could anyone give some examples how to use find -name "pattern" command, especially with "pattern"s, where is used '?' as part of regular expression. Because my patterns match in online regular expressions, bit doesn't work in 'find' utility.

*Could anyone explain what does this mean in find manual with examples?

The metacharacters (*',?', and []') match a.' at the start of the base name (this is a change in findutils-4.2.2; see section STANDARDS CONFORMANCE below)

*

*How correctly use "?" in find -name "pattern"? Am I correct that "?" means "zero or one symbols"?

A: From the find man page:

-name pattern  Base of file name (the path with the leading directories removed) matches shell pattern pattern.

The answer to your question is the definition of the term shell pattern, which is explained here (you'll also find an explanation looking in the man page of your shell):
*    Matches any zero or more characters.
?    Matches any one character.
[string]
    Matches exactly one character that is a member of the string string. This is called a character class. As a shorthand, string may contain ranges, which consist of two characters with a dash between them. For example, the class '[a-z0-9_]' matches a lowercase letter, a number, or an underscore. You can negate a class by placing a '!' or '^' immediately after the opening bracket. Thus, '[^A-Z@]' matches any character except an uppercase letter or an at sign.
\
    Removes the special meaning of the character that follows it. This works even in character classes.

Examples:
I hope the following examples explain the difference between ? and *.
touch foobar
touch fobar

# * matches the tail (finds 'foobar')
find -name 'foo*'

# * matches the head (finds both files)
find -name '*bar'

# ? matches the 'f' at start (finds 'foobar')
find -name '?oobar'

# ? DON'T matches the whole tail (finds nothing)
find -name 'foo?'

# ? matches the second 'o' (finds 'foobar')
find -name 'fo?bar'

# ? matches one instance of any character after the 'f' (finds 'fobar')
find -name 'f?bar'

# * matches both zero or more characters after 'o' (finds both files)
find -name 'fo*bar'

This example shows how to use the bracket operator [string]:
touch fobar
touch fubar

# matches a single 'o' OR 'u' (finds both files)
find -name 'f[ou]bar'

Of course you are free to mix the various metacharacters:
# Finds every file starting with an 'o' or 'u' (included files named 'o' or 'u')
find -name '[ou]*'

# Finds every file starting with an 'o' or 'u' (excluded files named 'o' or 'u')
find -name '[ou]?*'

A: *

*one example:
[root@v3 ~]# find -name 'op?n*.sh'
./openerp-install.sh
[root@v3 ~]# find -name 'op?en*.sh'
[root@v3 ~]#

*basename is the name of the file without the path, for example if file full path is "/usr/share/pkgconfig/gnome-icon-theme.pc", then the basename of that file will be "gnome-icon-theme.pc"

*"?" in the find pattern means "exactly one symbol", not "zero or one symbol"


text:
Q: Design considerations for an error logging/notification library in C I'm working on several programs right now, and have become frustrated over some of the haphazard ways I'm debugging my programs and logging errors. As such, I've decided to take a couple days to write an error library that I can use across all of my programs. I do most of my development in Windows, making extensive use of the Windows API, but the key here is flexibility: this library ideally needs to remain flexible, offering the programmer notification options in console apps and GUI apps on Windows and Unix-like environments.
My initial idea is to use one library that uses preprocessor conditional inclusion of the headers for windows and unix based on the current environment. For example, in a win32 app, console error message notification (while possible) isn't necessary; instead, a simple
MessageBoxA/W(hWndParent, TEXT("Some error message that makes sense in context"), TEXT("Application Name"), MB_ICONERROR | MB_OK)

would make the most sense. On the other hand, on linux things are a little more complex:
GtkWindow *w;
w = gtk_message_dialog_new(pOwner, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, TEXT("Some error message");
gtk_window_set_title(w, TEXT("Application Name"));

On either operation, simple file logging with more information about the error (function, file, line, etc.) would also be useful in pinpointing the source and tracing the flow.
Moreover, logging should be possible: even when a function requiring error logging/notification is called, it should be possible to show the sequence of function calls in the program, if that level of logging is activated.
Thus, my initial considerations are to have a library that incorporates all of these features, with minimal overhead by dint of preprocessor conditionals. I think it would make the most sense to break this up into a couple structs:

*

*The "main" struct, which is passed to every function in the main program requiring logging, and contains

*

*A bitmask containing the status codes for which file logging is necessary (e.g., NOERROR | WARNING | CRITICALERROR or CRITICALERROR | CRASH)

*A pointer to an "output" struct

*A linked list of "error information" nodes

*The "output" struct, which handles printing to file, displaying message boxes, and printing to the console

*The "error information" struct, which contains information about the error (function, file, line, message, type, etc.)

This is just my initial thoughts about this library. Can any of you think of any more information that I should include? Another major issue for me is atomicity of error addition: it's likely that another thread might create the error than the one logging the error, so I need to make sure that creating and adding an error node is actually an atomic operation. Thus, mutexes would likely be the way I'd go about synchronization.
Thanks for the help!

A: In the case of not CRITICALERROR | CRASH, where the app would be expected to continue after the logging call, it would be better to queue, (thread-safe producer-consumer queue), off each log struct to a logging thread that performs the requested action/s.  The logging thread would normally free the structs after handling them.  Some advantages:
1) The action taken for each logging request is reduced to mallocing the struct, loading it and pushing it onto the queue.  If the disk is temporarily busy, or has high latency because it's on a network, or becomes actually unavailable, the calling thread/s will continue to run almost normally. With this, the set of apps that will fail just because the logging has been turned on is reduced.  A user with some intermittent problem that you cannot reproduce can be instructed to turn on the logger with little chance that the logging will affect normal operations or, worse, introduce delays that cover up the bug.
2) For the same reasons as (1), adding/changing logger functionality, even at runtime, is much easier.  For example, maybee you want to restrict the size of log files or raise a new date/timestamped log file every day.  A 'normal' call would introduce a long delay into the calling thread while the old file was closed and the new one opened. If the logging is queued off, all you get is a temporary increase in the number of queued log structs.
3) Controlling the logging is easier.  In a GUI app, the logger could have its own form where the logging options can be modified.  You could have a 'New log file now' button which, when clicked, queued a 'LOGCONTROL' struct to the logging thread, along with all the other logging messages.  When the thread gets it, it opens a new log file.
4) Forwarding the log messages is fairly easy.  Maybe you want to watch the logged messages, as well as write them to disk - queue up a 'LOGCONTROL' struct that instructs the thread to save a function ptr passed in the struct and henceforth call this function with subsequent logging messages after writing them to disk.  The function passed could queue up the messages to your GUI for display in a 'terminal' type window, (PostMessage on Windows, Qt etc. have a similar functionalities to allow data to be passed to the GUI). Sure, on ***x, you could open a console window and 'tail-f' the log file, but this will not appear particularly elegant to a GUI user, is more difficult to manage for users and is anyway not available as standard on Windows, (how many users know how to copy paste from a console window and email you the error message?).
Another possibility is that the logging thread might be instructed to stream the log text to a remote server - another 'LOGCONTROL' struct could pass the hostname/port to the logger thread. The temporary delays of opening the network connection to the server would not matter because of the queued communications.
5) 'Lazy writing' and other such performance enhancements become easier, but:
Disadvantages:
1) The main one is that when the log call returns to the requestor, the log operation has probably not yet happened.  This is very bad news in the case of CRITICALERROR | CRASH, and can be unacceptable in some cases even with 'ordinary' logging of progress messages etc.  There should be an option to bypass in these cases and a direct disk write/flush made - fOpen/CreateFile a separate 'Direct.log', append, write, flush, close.  Slow - but secure, just in case the app explodes after the log call returns.
2) More complex, so more development, more conditionals, bigger API interface include.
Rgds,
Martin

A: Hi I use this for another language but you could research it and follow its design
http://www.gurock.com/smartinspect/
regards


text:
Q: Design of a Hive pipeline I am trying to find the best way to implement the following pipeline in Hive and HDFS:
I would like to ingest a csv (no problem in there so far) but, I want to the partitions to be made from a field that comes informed into the csv files.
I created an external table that deposits the file on the HDFS and defined the partition field, but with a simple put (which makes sense) the partitions are not made and  I get an exit code 1 when trying to drop the msck repair table.
I would like to know if the following is possible or viable to do:

*

*Load the CSV file into an internal hive table and as a temporal table.

*Do the insert into the "official" table with the partitions
Is this an efficient way to do it? If so, I havent found a lot of information about how to do the first.
Thanks.

A: If it were only one partition per file then you could load directly into target table partition using
hive> LOAD DATA LOCAL INPATH 'yourpath/yourfile.csv' OVERWRITE INTO TABLE your_table PARTITION (key='value');

The worst scenario If there are many partitions per file then you need to load into intermediate table first and then re-partition data using insert-overwrite-select:
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;

insert overwrite official_table partition(partition_key)
 select col1, col2, partition_col --partition is the last one
from intermediate table...

And you need to load (overwrite) all entire partition data at once, if not possible then select should merge data already existing in target partition with incremental load.
See this answer about how to merge incremental updates.
Also INSERT (NOT OVERWRITE) INTO table (partition) select ... is possible solution for inserting incremental data. This statement should load data into additional files in the partition folder, existing data will remain as is.


text:
Q: Why isn't this simple jQuery working? jQuery:

A: There are a fair number of errors.  Corrected and documented inline.

A: You forgot the function() part. And a opening and closing script tag, as others pointed out.

Test your site here: jsfiddle

A: You need to pass a function to ready, and you're passing an object-literal by accident.
You can use this to play around with the example (I love jsfiddle!)
http://jsfiddle.net/hmdrP/
There's also a shortcut, $(function() { ... }) which is equivalent.


text:
Q: Choosing $\delta$ for a given $\varepsilon$ when computing $\lim_{x\to 2}x^2=4$
How does the author come to the conclusion that $\delta$ has to be the $ \min\left\{1,\frac{\epsilon}5\right\}$. Why that $1$? Can it be any number and we get accordingly the value of $\epsilon$? In general, finding $\delta$ for any $\epsilon$ is purely by some guesswork? I can understand why these values work but the 'why' question is troubling me. I'm not very comfortable and unable to convince myself perfectly.

A: I thought I would add some reflections on what exactly is going on with $\min(1,\cdots)$. Most textbooks (and introductory classes) gloss over this entirely, and pretend it is obvious (and it is obvious for the author and anyone else who, like me, have been doing $\epsilon$-$\delta$ arguments for years). This glossing-over is a bad thing, as $\min(1,\cdots)$ is something which stumps most students when they first encounter it. They should be given a thorough reason for why we do it. Here I give something which in my opinion is a bare minimum, but about ten times more than is offered in any textbook or class I have seen (not that I have seen very many).
Note that this applies equally well to the same thing in proofs of continuity.
Limits only care about what happens very close to the point in question. In this case the point $x=2$. It doesn't care what happens at $x=1000$, for instance. Thus we care about small values of $\epsilon$ and $\delta$. So as long as $\epsilon$ is small, choosing $\delta$ to be $\frac{\epsilon}{5}$ works fine, and we're done.
However, while limits only really care about small $\epsilon$, the definition says you should be able to pick a $\delta$ for any epsilon. This is partly in order to be brief, and partly in order to be impartial as to what constitutes "small". The definition may as well have said "For any $\epsilon$ with $0<\epsilon<1$, there is a $\delta>0$ such that ..." and that would've been equivalent.
However, that's a bit longer to write, and it makes $1$ look like some kind of special number in this context, which it is not. Perhaps more importantly, some times you need to specifically use something like $\epsilon=2$ in a proof, and in that case, it's easier if the definition didn't have a limitation on $\epsilon$.
So, with that said, when we pick our $\delta$, we mostly care about small $\epsilon$, but we have to take into account that someone, somewhere, may one day pick $\epsilon=1000$. And in that case $\delta=200$ is way too big.
This can be solved in two ways. One way is to find an expression for $\delta$ which always works. That's complicated and will involve square roots, at the very least. The standard way, which is used here, is to declare that if $\epsilon$ is larger than some bound (in this case $5$), we will use $\delta=1$. If $\epsilon$ is smaller, we will use $\frac\epsilon5$.
There is nothing special about $1$ in this context. It's just that some number must be picked, and $1$ is a nice number most of the time.

A: This is one of the most annoying aspects of teaching a first course in analysis. The author of such a proof has always worked backwards, and has then rewritten the proof (erasing the entire process of coming up with it) so that it looks completely magic.
This kind of proof is generated as follows.

*

*Intuit that the limit is $4$.

*Imagining that the limit is indeed $4$, the proof will look like:

Let $\epsilon > 0$, and choose $\delta = \mathrm{XXX}$. Pick $x$ to be within $\delta$ of $2$. Then $|x^2 - 4| < \epsilon$, which completes the proof.

*Manipulate the final line until we can get something out of it.

Let $\epsilon > 0$, and choose $\delta = \mathrm{XXX}$. Pick $x$ to be within $\delta$ of $2$. Then $|x^2 - 4| = |x+2| |x-2| < \epsilon$, which completes the proof.

*Identify any terms which we can bound uniformly by picking $\delta$. This is where the $1$ comes from, and it only mattered that it was a positive constant.

Let $\epsilon > 0$, and choose $\delta = \min(1, \mathrm{XXX})$. Pick $x$ to be within $\delta$ of $2$. Then $|x^2-4| = |x+2| |x-2| < 5|x-2| < \epsilon$, which completes the proof.

*Repeat by successively refining $\delta$.

Let $\epsilon > 0$, and choose $\delta = \min(1, \frac{\epsilon}{5})$. Pick $x$ to be within $\delta$ of $2$. Then $|x^2-4| = |x+2| |x-2| < 5 \cdot \frac{\epsilon}{5} = \epsilon$, which completes the proof.

*Pretend that none of the above happened, and just write down the proof in its final form.

(Thanks to Dr Paul Russell for giving almost exactly this answer in his course Analysis II.)

A: I can relate to your difficulties. Before I answer your question, I would like to emphasize that in $\varepsilon-\delta$ proof, you need to do the "calculation" in advance.
Now, here is the thing... The concept of limit is probably best explained as moving closer and closer to a certain value. In your problem, $x$ is moving closer and closer to $2$. How close? That depends on the choice of your $\varepsilon>0$ in the first place. Now, understand that $x$ moves closer to $2$ means you can "bound" $x$. In this case, I can bound $x$ with any number (usually $1$ for simplicity and easy calculation). If you are in doubt, you can try to use another number such as $\sqrt{2}$ but maybe the calculation will be not as good sometimes.
Also, "guess work" as you mention is not entirely wrong. However, you need to be "smart" to guess the correct answer. In this case, do "rough" calculation in advance.
So, let's think in different perspective. This is our goal :
$$|x^{2} - 4| < \varepsilon$$
and this is our starting point :
$$ |x- 2| < \delta$$
Now, consider our goal as starting point :
\begin{align*}
&|x^2 - 4| = |x-2|\,|x+2| < \varepsilon \\
&|x-2| < \frac{\varepsilon}{|x+2|}
\end{align*}
Now, we want to bound $x$. So, let's use different number, for example $\frac{1}{2}$. Assume $|x-2|<\frac{1}{2}$ then we have $\frac{5}{2}< x+ 2 <\frac{7}{2}$ which means $\frac{5}{2}< |x+2| < \frac{7}{2}$ and now we know that $\frac{2}{7} < \frac{1}{|x+4|} < \frac{2}{5}$
Going back to the previous inequality, we obtain
$$|x-2| < \frac{\varepsilon}{|x+2|}<\frac{2}{5}\varepsilon$$
Now, we can find $\delta = \min \{\frac{1}{2}, \frac{2}{5}\varepsilon\}$ as our bound and start the proof. What I want to demonstrate here is for you to realize that "guess work" needs to be smartly done and there are a lot of answers to prove.

A: What @arthur points out is spot on I would just like to add a couple things to it.
The reason we often choose some "maximal" delta to begin with is to make it easier to work with the piece of the function that's left. For $x^2$ at $2$ this can be nicely seen graphically.
Notice that the in the region bounded by the blue and red lines (that's between $2-1=1$ and $2+1=3$ the function $x^2$ is particularly well behaved. It is strictly increasing it is defined everywhere and so will be easy to work with. That is why we want to make sure no matter how big an $\epsilon$ someone gives us we always work in this nice region.
Doing this lets us assume nice things in our proof later on. For example $|x+2|\leq 5$ and also $x>0$. When we later try to bound $|x^2-4|$ this information can (and does) come in handy.
This is even more important when our functions are less well behaved than a quadratic. You might have functions that are not defined everywhere or behave very badly at some points. Compare to a function like $\frac{sin(1/x)}{100}$

This function is continuous everywhere except at $0$ and consequently has a limit everywhere. But if you want to prove that it has a limit somewhere other than $0$ you really want to bound yourself away from that nasty oscillation so you can work with a function that behaves nicely at the place you're taking your limit.


text:
Q: Explanation for tail(?) recursion when calling the method twice Let's have the following code:
import time

def rec1(len):
    if( len < 2): return 1;
    return 2*rec1(len-1);

def rec2(len):
    if( len < 2): return 1;
    return rec2(len-1) + rec2(len-1);

def callAndReport(len, method):
    time1 = time.time()
    answer = method(len)
    time2 = time.time()
    print("{0} with {1}:{2} in {3:.0f} ms".format(len,method.__name__,answer, (time2-time1)*1000))

if __name__ == '__main__':
   callAndReport(20,rec1)
   callAndReport(20,rec2)
   print('')
   callAndReport(23,rec1)
   callAndReport(23,rec2)

This code produces the following output:
20 with rec1:524288 in 0 ms
20 with rec2:524288 in 642 ms

23 with rec1:4194304 in 0 ms
23 with rec2:4194304 in 4613 ms

Could someone explain the execution time difference? I have few ideas but I would like to be sure.
For completeness, the original problem I had was the method below (which can be easily express as a for loop, but that's not the point here):
def find11s_rec(len):
    if len<2: return 0
    if len== 2: return 1;
    return find11s_rec(len-2)+find11s_rec(len-1)+2**(len-2)

.

A: That's because while rec1 only uses rec1 once, rec2 uses rec2 twice. And then those inner rec2 calls will each call rec2 twice. The number of function calls will rise exponentially. While rec1 might use x calls, rec2 would use 2^x calls. In computer science terms, rec1 is O(x) while rec2 is O(2^x). In more complicated cases, dangerous recursion might inobvious; so use a debugger to find out what is actually being done.

A: The complexity of rec1 is O(n) and the complexity of rec2 is O(2^n). That's a big performance difference.
rec2(n) = rec2(n-1) + rec2(n-1)
        = (rec2(n-2) + rec2(n-2)) + (rec2(n-2) + rec2(n-2)) = 4 * rec2(n-2)
          ...

rec2(n) = (2^n)*rec2(1)
        = O(2^n)


text:
Q: Markov Process From Semi-group Let $(\Omega,\mathcal{F},\mathbb{P})$ be a complete probability space.
Suppose that $(T_t)_{t\geq 0}$ is a continuous semi-group on $L^2(\mathcal{F},\mathbb{P})$; that is:

*

*$T_0(f)=f$ for every $f \in L^2(\mathcal{F},\mathbb{P})$,

*$T_{s+t}=T_s\circ T_t$,

*$t\mapsto T_t(f)$ is continuous for every $f \in L^2(\mathcal{F},\mathbb{P})$,

and $T_t=e^{tA}$ for some closed operator $A:L^2\rightarrow L^2$.  Upong rescaling $A$, can we necessarily find a Markov process $X_t$ on $\mathbb{R}$ whose law is determined by $T_t$?


text:
Q: Getting different results while computing md5 for Serializable object vs string I want to compute md5 of any Serilizable object, which is done by following function.
public static String getMd5Hash(Serializable object) {
        try {
            return getChecksum(object, "MD5");
        } catch (Exception e) {
            throw new RmsException("Exception while generating md5 hash", e);
        }
    }

public static String getMd5Hash(Serializable object) {
            try {
                return getChecksum(object, "MD5");
            } catch (Exception e) {
                throw new RuntimeException("Exception while generating md5 hash", e);
            }
        }

    private static String getChecksum(Serializable object, String algorithm)
        throws IOException, NoSuchAlgorithmException {
        try (
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos)
        ) {
            oos.writeObject(object);
            MessageDigest md = MessageDigest.getInstance(algorithm);
            byte[] theDigest = md.digest(baos.toByteArray());
            return DatatypeConverter.printHexBinary(theDigest);
        }
    }

Test
@Test
 public void getMd5Hash() {
        String actual = CryptoUtils.getMd5Hash("water");

        Assert.assertEquals("9460370bb0ca1c98a779b1bcc6861c2c", actual);
}

OP
Expected :9460370bb0ca1c98a779b1bcc6861c2c (actual md5 for string water)
Actual   :37F7DBD142DABF05ACAA6759C4D9E96C (Why the diff?)

A: The ObjectOutputStream adds a header, so the Serializable you are passing does not actually represent "water" when you get the byte array. Print out baos.toString() to verify. You can either extend ObjectOutputStream and override the writeStreamHeader method, or call md.digest with the substring of the data, ie md.digest(baos.substring(7).getBytes()) (or something thereabouts). Once the actual data digested is "water", the hash will be correct.

A: As Terje says,
ObjectOutPutStream adds a header, you can verify that using
public static String getChecksum(Serializable object, String algorithm)
            throws IOException, NoSuchAlgorithmException {

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos)) {

            oos.writeObject(object);
            oos.flush();
            MessageDigest md = MessageDigest.getInstance(algorithm);
            md.update(object.toString().getBytes());
            byte[] theDigest = md.digest();
            System.out.println("Without Object output stream="+DatatypeConverter.printHexBinary(theDigest));

            md.reset();
            System.out.println("object="+object+ " Written to ByteArray is="+baos.toString());
            md.update(baos.toByteArray());
            theDigest = md.digest();
            return DatatypeConverter.printHexBinary(theDigest);
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
        System.out.println(getChecksum("water", "MD5"));

    }

Instead of creating all ByteArrayOutputStream and ObjectOutputStream, you can simple use
md.update(object.toString().getBytes());

To write byte array to MessageDigest.
Thanks


text:
Q: Random generator for CSMA/CD collisions? I don't know if this is the right place to post this question, but here it goes: I was wondering how a random time is generated when a collision is detected in CSMA/CD?

A: CSMA/CD is defined in IEEE Standard 802.3. These Standards are free to download:
http://standards.ieee.org/about/get/802/802.3.html
EDIT: I think Section One Page 67 is what you are looking for.

A: The Ethernet standard doesn't specify which random number generator to use, only that one should be used. It specifies that the random number generator should have a uniform output distribution but, beyond that, it doesn't specify any specific algorithm to use.
Stop and think about it for a moment. As long as the output of the random number generator is uniformly distributed it doesn't matter what the algorithm is, from an operational perspective. If I showed you the output of two random number generators, both of which produced uniformly distributed output, you wouldn't be able to tell if they were generated by the same algorithm or different algorithms.
Protocol standards are concerned with specifying the operational characteristics of the protocol in great detail. The functional specifications necessary to implement the protocol are typically left up to the implementor. As long as your implementation of a protocol has the correct operational characteristics, per the standard, the implementation is irrelevant. Further I would argue that a protocol that requires a particular implementation in order to produce the correct operational result is a flawed protocol.

A: Maybe its not mentioned so that manufacturers can choose one at random?


text:
Q: Problem on Linux NAND Root Filesystem I'm have a JFFS2 root filesystem running on a large NAND device.  Every once in a while, when I restart the computer, I get error messages about invalid ELF headers when /sbin/init or /bin/login try to load dynamically linked shared libraries from the /lib folder
The errors cause a kernel panic and I'm stuck reflashing the NAND to get the computer up and running again.
Example:
/sbin/init: error while loading shared libraries: /lib/libc.so.6: invalid ELF header
Kernel panic - not syncing: Attempted to kill init!
Call Trace:
[dffc1d20] [c0007c74]  (unreliable)
[dffc1d60] [c0020d68]
[dffc1db0] [c0025074]
[dffc1e80] [c00250bc]
[dffc1f40] [c000f340]

It seems that somehow the dynamically linked libraries in the /lib folder are becoming corrupted.  I don't think that dynamically linked libraries are even written to disk during normal operation (unless you're doing an update).  So that rules out a partial write with a loss of power causing the corruption.
So the only other causes I can think of are that either JFFS2 has some sort of terrible bug that is corrupting files that aren't even being written to?  Or the NAND itself is being corrupted?
Does anyone have any other ideas?  Or am I way off base?

A: Are you mounting the root partition, or whatever partition your libraries exist on with the "noatime" option?  If not, every access is causing a write.


text:
Q: Replace line in config file with batch afterward start exe With a batch file, I want to change a value in a configuration file:
"title.connectionString" : "ServerIP",

ServerIP is the variable to be changed. So the batch file has to give people who use it an option to choose from 4 prefixed IPs. After they selected one of the 4 the IP, the config file has to be saved with new value and the batch file should run an executable.
Has anyone got an idea how I can do this with a batch file?

A: Easy, try this code:
@echo off
:start
Echo Select Ip:
Echo.
Echo     1. 10.0.0.0
Echo     2. 10.0.0.1
Echo     3. 10.0.0.2
Echo     4. 10.0.0.1
Echo.
Choice /c 1234 /m "Ip: " /n
set choice=%errorlevel%
set ip=
if %choice%==1 set ip=10.0.0.0
if %choice%==2 set ip=10.0.0.1
if %choice%==3 set ip=10.0.0.2
if %choice%==4 set ip=10.0.0.3
if "%ip%"=="" (Echo Error, null variable & goto :start)

ren config.txt config.tmp
setlocal Enabledelayedexpansion
for /f "tokens=*" %%a in (config.tmp) do (
set line=%%a
Echo !line:ServerIP=%ip%! >> config.txt
)
del config.tmp

And that should do what you want.
Mona

A: @echo off

    setlocal enableextensions

    call :replaceKeyValue "file.config" "title.connectionString" "123456789"

    endlocal

exit /b

:replaceKeyValue file key value
    setlocal enableextensions disabledelayedexpansion
    ren "%~f1" "%~nx1.tmp" >nul && (
        (for /f tokens^=1^,*^ delims^=^:^ eol^= %%k in ('findstr /n "^" ^<"%~f1.tmp"') do (
            echo(%%l|findstr /c:"\"%~2\"" >nul && (
                for /f "tokens=1 delims=:" %%v in ("%%l") do echo(%%~v : "%~3",
            ) || (
                echo(%%l
            )
        )) > "%~f1"
        del "%~f1.tmp" > nul
    )
    endlocal

This will handle the replacement of the value in the file. Monacraft answer shows a perfect way of selecting the required ip.
This will rename the file to file.tmp and for each line in the file (findstr /n is used to avoid lost of empty lines) it is tested agains the passed key. When required line is found, it is split using the colon (to keep the indentation) and value replaced with supplied value. All the non matching lines are echoed as is. All the output of the process is send to the original file and at end, the .tmp file is deleted.


text:
Q: Update the contents of a file in Python I am trying to update the contents of the file swimmerpoints.txt. My current code is as follows:
def update():
  swimmerid = []
  name = []
  points = []
  files = open('swimmerpoints.txt', 'a+')
  for info in files:
    info = info.strip()
    lists = info.split(',')
    swimmerid.append(lists[0].strip())
    name.append(lists[1].strip())
    points.append(lists[2].strip())

  x = int(input("Swimmer ID to update points: "))
  index = swimmerid.index(x)
  print(name[index] + "'s", "point total is:", points[index])
  changes = int(input("Enter the new point value: "))
  files.write(f"{changes}")
  files.close()
update()

The contents of swimmerpoints.txt are this list: 1, JOHNNY, 492. When I get the prompt to enter the Swimmer ID, which in this case is 1, I get this error:
Traceback (most recent call last):
  File "main.py", line 29, in <module>
    update()
  File "main.py", line 24, in update
    index = swimmerid.index(x)
ValueError: 1 is not in list

1 is in the spot of swimmerid
JOHNNY is in the spot of name
492 is in the spot of points
What is the proper way to read my file and match with the proper ID?


text:
Q: WindowBeforeRightClick doesn't work I am using the Microsoft Ax framer control to view the word document in the Visual C# Form.
After hosting (open) the Word document in the Ax framer control.
While right-click on the Word document, MS Word context menu is appearing.
I want to hide this pop up menu.
I set
`Word.Document wddoc = (Word.Document)axFramerControl1.ActiveDocument;
Word.Application wordApp = wddoc.Application;
wordApp.WindowBeforeRightClick += new ApplicationEvents4_WindowBeforeRightClickEventHandler(wordApp_WindowBeforeRightClick);`

to handle RightClick of Microsoft Word.
But the application doesn't run the WindowBeforeRightClick event.
What's the problem?

A: This was bug that was fixed with March 2016 update for Word 2016.
MS16-029: Description of the security update for Word 2016: March 8, 2016
https://support.microsoft.com/en-us/kb/3114855


text:
Q: Does this sort have a name? I had to find what that mystery algorithm does. Now I know it's a sort, but I can't find an official name for it.
Here is its Java code:
for (int i = 0 ; i < myListSize; i++) {
    min = Collections.min(myList.subList(i, myListSize));
    minIndex = myList.indexOf(min);
    Collections.reverse(myList.subList(minIndex, myListSize));
    Collections.reverse(myList.subList(i, myListSize));
}

Take this array:
   [G,E,D,A,F,C,H,I,B]

It 1) searches for the min. element, 2) reverses the subarray from there and 3) reverses the whole thing again:
1) [G,E,D,[A,F,C,H,I,B]]
2) [G,E,D,[B,I,H,C,F,A]]
3) [[A,F,C,H,I,B],D,E,G]

Now the min. element is on the left. Repeat for the remainder of the array:
1) [A] [F,C,H,I,[B,D,E,G]]
2) [A] [F,C,H,I,[G,E,D,B]]
3) [A] [[B,D,E,G],I,H,C,F]

1) [A,B] [D,E,G,I,H,[C,F]]
2) ...

and voilà! Sorted. Do you have a name for it, please ?

A: It's called Pancake sorting.

Here's a code golf puzzle about it: Flipping pancakes


text:
Q: Get deployments counts on Ansible Tower How to get deployment counts on Ansible Tower? Is there any way to get deployment counts using ansible tower REST API?

A: In respect of your question and comment

... or last jobs history list ...

you could use according the Ansible Tower REST API and Jobs - List jobs something like
curl --silent -u "${ACCOUNT}:${PASSWORD}" https://${TOWER_URL}/api/v2/jobs/ | jq .

which provides also a Sorting and Searching option, in example ?order_by=name.


text:
Q: why the progress dialog doesn't disappear on some page? this is my mainactivity, when i load some page the progress dialog doesn't disappear onpagefinished...where is the problem?
if you want to try the problem are with the page "accedi" or on the payment of the order
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WebView webView = new WebView(this);

    webView.setClickable(true);
    webView.setFocusableInTouchMode(true);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.loadUrl("http://www.alldrink.it");
    WebClientClass webViewClient = new WebClientClass();
    webView.setWebViewClient(webViewClient);
    WebChromeClient webChromeClient=new WebChromeClient();
    webView.setWebChromeClient(webChromeClient);
    setContentView(webView);
    webView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                WebView webView = (WebView) v;

                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        if (webView.canGoBack()) {
                            webView.goBack();
                            return true;
                        }
                        break;
                }
            }

            return false;
        }
    });

}

public class WebClientClass extends WebViewClient {
    ProgressDialog pd = null;

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        pd = new ProgressDialog(MainActivity.this);
        pd.setTitle("Attendere");
        pd.setMessage("Caricamento in corso..");
        pd.show();
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (pd.isShowing()) {
            pd.dismiss();

        }
    }

}

public class WebChromeClass extends WebChromeClient{

}

}

A: the dismiss() function is working, but your onPageStarted() has run two times, making dialog recreate again and look like it never disappear. Try changing your onPageStarted as:
@Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);

        if(!pd.isShowing())
        {
            pd.setTitle("Attendere");
            pd.setMessage("Caricamento in corso..");
            pd.show();
        }
    }


text:
Q: Corrupt an image with noise given the noise's distribution? I am developing a test bed in OpenCV and I would like to know how can I create a corrupted image given the image and a specific Probability Density Function of the required noise? In Digital Image Processing by Gonzalez and Woods Chapter 5 of this book they give the PDF but I really can't seem to figure out how to calculate generate the noise in an image given the PDF. If someone can point me in the correct direction as to how I might start with the implementation I would be grateful. Even if the information is not in C\C++ I would appreciate any help thanks.

A: One approach here is to try to simulate a histogram matching from uniform noise to the desired PDF.
1.) Calculate the CDF of the desired noise from your PDF.
2.) Generate a uniform random number 0-1.
3.) Find the value in the CDF that is closest to the random number.
4.) The index of the closest value in the CDF is the digital count in the noise image.
After doing this for each pixel, you should have a noise image with the desired PDF.