text:
Q: Intermittent logon failures or lock out failures when under high impersonation load Recently we've been seeing an interesting slew of failures on our cluster where users' jobs will intermittently fail with logon errors, account locked out errors, or file permission errors.
Our cluster is loosely-coupled and coarse-grained, built around 40 16-way Windows 2003 machines. They participate in a corporate domain, with domain controllers locally and on the WAN. Job submission is handled through a 3rd party application (ActiveBatch) and file storage is split between a SAN exported by a Windows 2003 server and a newer CIFS share on an Isilon cluster.
Jobs are directed-acyclic graphs, consisting of 1 to 5,000 processes, scheduled on a head node through ActiveBatch. Most jobs are tiny batch files or Perl scripts which perform environment setup for computational codes written in FORTRAN. Input and output files for these jobs are stored on either the SAN or the Isilon.
What we have been seeing are intermittent failures in authentication, which originally we believed to be isolated on the Isilon. The general failure mode is 100-200 jobs would begin execution, each referencing common configuration data in a file. The majority would succeed, however, multiple jobs on multiple machines would fail on the client side with a file permissions error (either 0x775 'The referenced account is currently locked out...' or 0x52E 'unknown user name or bad password').
Checking the event logs for these time periods reports 0 Security Audit Failures, but multiple Security Audit Successes for the same user! The only event log entry in close proximity is a 6013 event letting us know, "The system uptime is 2199088 seconds."
Recently we've also been seeing the same error when the job scheduling software attempts to create the jobs on the remote machines. ActiveBatch will send the job details to a service running on the machine which then attempts impersonation of the user when it creates the job. As with the file permission failures, we're seeing both account lock outs and unknown user/password when the user's account is neither locked out nor unknown (and in fact processes on the same machine succeeded shortly after these failed attempts).
I'm not familiar enough with domain controllers, nor given sufficient access to explore, to know whether or not this is a client side problem or a server side problem. The lack of client side event log failure entries leads me to believe the failure is perhaps a DC timeout or a network issue. However, a Wireshark interrogation of traffic between a random server and the DC did not reveal any gross inconsistencies beyond the occasional Kerberos Response Too Big messages.
Is this a common problem with domain controller setups where high authentication/impersonation load causes transient failures?

A: It isn't common, unless there is something generating the failure that would result in the lockout.
Enabling Netlogon verbose logging may help track it down.
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters]
"DBFlag"=dword:24401F04

The files created are %systemroot%\debug\netlogon.log and netlogon.bak.
These can roll over quickly in a high-volume environment, so you may need to increase the size of the files, which is 20 MB by default.  To increase it to 50 MB:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters]
"MaximumLogFileSize"=dword:3200000

Enabling debug logging for the Net Logon service
http://support.microsoft.com/kb/109626


text:
Q: Series solution to first order differential equation I need to find a series solution to the following simple differential equation
$$x^2y'=y$$
Assuming the solution to be of the form $y=\sum a_nx^n$  and equating the coefficients on both the sides, all the coefficients turn out to be zero which is definitely wrong.
Please guide me to the correct solution.
Any help is appreciated. Thanks!

A: if you let $y = \sum_{ n = 0}^{\infty} a_nx^n$
$x^2y' = \sum_{ n = 0}^{\infty} a_nnx^{n+1} = \sum_{ n = 0}^{\infty} a_nx^n$
so equating coefficients on each side gives you $a_{0} = 0$ and a relation
$$
a_{n+1} = na_n
$$
which does indeed lead to all coefficients being zero
What if you supposed that $y = \sum_{ -\infty}^{\infty} a_nx^n$
then $a_{-0}$ could equal A say and then you would get $-1a_{-1} = A$
You should then be able to recover the answer that Autolatry found using separation of variables

A: It could be useful to remark that $y(x)=0$ is the only solution of $x^2 y^\prime (x)=y(x)$ which is defined and analytic on the whole real line. In fact, the other solutions of your ODE are of the type:
$$y(x)=C \exp \left( -\frac{1}{x}\right)$$
and none of them is both defined and analytic in $\mathbb{R}$.
Therefore, it is really obvious that the power series method yields only the zero solution.

Moreover, if you let:
$$y(x) := u\left( \frac{1}{x}\right)$$
(for a suitable differentiable $u(t)$) you can reduce your ODE to a simpler one: in fact, you have:
$$y^\prime (x) = -\frac{1}{x^2}\ \dot{u}\left( \frac{1}{x}\right)$$
(where the dot denotes derivation with respect to the $t$ variable) that is:
$$\dot{u} \left( \frac{1}{x}\right) = -x^2\ y^\prime (x)\; .$$
Therefore $y(x)$ solves your ODE away from zero iff $u(t)$ solves:
$$\dot{u}(t) = - u(t)\; .$$
Hence $u(t)=Ce^{-t}$ and $y(x)=Ce^{-1/x}$.

A: Well,
\begin{eqnarray}
\int \frac{dy}{y} &=& \int \frac{dx}{x^{2}}\\
\implies \ln y    &=& -\frac{1}{x}+c
\end{eqnarray}
Hence,
\begin{equation}
y=Ae^{-\frac{1}{x}}
\end{equation}
Is a series solution necessary?

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# Multiple columns individual column sum as a DataRow I have a DataTable of 4 columns A,B,C,D with 4 rows of data all containing integer values.I want to return a DataRow of A,B,C,D columns which contains the sum of individual A,B,C,D column's values. There is no filter, straight up total as do in an excel.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[4] {
                            new DataColumn("A", typeof(int)),
                            new DataColumn("B", typeof(int)),
                            new DataColumn("C", typeof(int)),
                            new DataColumn("D", typeof(int))
                        });
dt.Rows.Add(1,1,1,1);
dt.Rows.Add(2,2,2,2);
dt.Rows.Add(3,3,3,3);
dt.Rows.Add(4,4,4,4);

The output data row must contain 4 columns of 10,10,10,10 values

A: If you want a column (say Total), that has the sum of A,B,C,D of each row, add a computed column, like this,
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] {
                new DataColumn("A", typeof(int)),
                new DataColumn("B", typeof(int)),
                new DataColumn("C", typeof(int)),
                new DataColumn("D", typeof(int)),
                // add computed column in case you want to get sum of each row in a separate column
                new DataColumn("Total", typeof(int),"A+B+C+D")
            });
dt.Rows.Add(1, 1, 1, 1);
dt.Rows.Add(2, 2, 2, 2);
dt.Rows.Add(3, 3, 3, 3);
dt.Rows.Add(4, 4, 4, 4);

If you want the sum of each column in 4 variables (or whatever), use the DataTable.Compute method, like this,
//use DataTable.Compute to calculate sum or each column
var sumA = dt.Compute("SUM(A)", "");
var sumB = dt.Compute("SUM(B)", "");
var sumC = dt.Compute("SUM(C)", "");
var sumD = dt.Compute("SUM(D)", "");

//since you want these added as new row in the datatable...
dt.Rows.Add(sumA, sumB, sumC, sumD);


text:
Q: GitBucket API how to get pull request with base name I try to get pull request with base name like below but looks like "base" query parameter not working(even head query too...).
http://my-gitbucket-server/api/v3/repos/test/test/pulls?state=closed&base=development&head=test:sprint0

How can get pull request data with "base" query parameter.(The purpose is get diff status on the pull request)


text:
Q: Logcat color changed to be Yellow in Jelly Beans I have updated my Google galaxy Nexus (4.0.3 ICS) to Jelly Bean ( offical update thru updates notification on phone).
After updating, my logcat only gives me yellow text ( for all warning, verbose, debug, or error logcat mode).
This is really annoying when you got to many messages to filter.
The filter function on logcat is also disabled.
Did anyone meet this problem, how to solve that?
Thank you for your reading.

A: you should update the ADT. After this all will be as usual


text:
Q: gkSudo Error no matter what I do I don't know why, It wasn't happening yesterday. Was it because I turned the machine off and back on again this morning?
Anyway here's the error. GkSudo won't run anything at all now.
(gksudo:3262): GLib-CRITICAL **: g_str_has_prefix: assertion `str != NULL' failed
This happens no matter what. Funny thing is, gkSudo comes up with the password box, I enter the root password, then the problem happens.
I want my gksudo back  can anyone help? I cannot find documentation for this error at all. I don't know where to look, this is my second ever day using Linux.
I'm on Debian Gnome.


text:
Q: Postgresql trigger set empty string to NULL I have a table with field "mac" of type MACADDR. Now I would like to treat a situation (probably with trigger?) when somebody inserts empty string instead of mac address. I would like to turn this empty string to NULL, so postgresql will not complain: invalid input syntax for type macaddr: ""
What I have now in trigger function is this:
IF CHAR_LENGTH(NEW.mac) = 0 THEN
  NEW.mac := NULL;
END IF;

But it does not seem to work. What would you do, if you want to treat this on DB level?
Thank you very much. -Jan
PS: I am a postgresql newbie. But a fascinated one :)

A: You can't do what you want with a trigger. Your incoming empty string will be parsed and converted to a macaddr (or at least the parsing will be attempted) before the trigger is executed. However, you could write a simple function to convert empty strings to NULL and use that in your INSERT:
create function macaddr_ify(m varchar) returns macaddr as $$
begin
    if m is null or length(m) = 0 then
        return null;
    end if;
    return cast(m as macaddr);
end;
$$ language plpgsql;

And then:
insert into t (addr) values (macaddr_ify(str));

I'd recommend that your client application properly convert empty MAC address strings to NULLs itself though.


text:
Q: High CPU consumption, 33% battery, suddenly MacBook Pro Retina shuts down saying it needs to be plugged in High CPU consumption, 33% battery, suddenly MacBook Pro Retina shuts down saying it needs to be plugged in.
I plug it in and then Mac works fine and battery level is at 33%.
I googled this, found nothing.
Any idea what might be wrong ?
Battery needs replacement ?
Battery looks ok:
Battery Information:

  Model Information:
  Serial Number:    D863016Q037F9Y2A9
  Manufacturer: SMP
  Device Name:  bq20z451
  Pack Lot Code:    0
  PCB Lot Code: 0
  Firmware Version: 511
  Hardware Revision:    000a
  Cell Revision:    1150
  Charge Information:
  Charge Remaining (mAh):   2656
  Fully Charged:    No
  Charging: Yes
  Full Charge Capacity (mAh):   6827
  Health Information:
  Cycle Count:  587
  Condition:    Normal
  Battery Installed:    Yes
  Amperage (mA):    2711
  Voltage (mV): 12002

System Power Settings:

  AC Power:
  System Sleep Timer (Minutes): 0
  Disk Sleep Timer (Minutes):   0
  Display Sleep Timer (Minutes):    5
  Wake on AC Change:    No
  Wake on Clamshell Open:   Yes
  Wake on LAN:  Yes
  AutoPowerOff Delay:   14400
  AutoPowerOff Enabled: 1
  Current Power Source: Yes
  DarkWakeBackgroundTasks:  1
  Display Sleep Uses Dim:   Yes
  GPUSwitch:    2
  Hibernate Mode:   3
  PrioritizeNetworkReachabilityOverSleep:   0
  Standby Delay:    4200
  Standby Enabled:  1
  Battery Power:
  System Sleep Timer (Minutes): 30
  Disk Sleep Timer (Minutes):   0
  Display Sleep Timer (Minutes):    2
  Wake on AC Change:    No
  Wake on Clamshell Open:   Yes
  AutoPowerOff Delay:   14400
  AutoPowerOff Enabled: 1
  DarkWakeBackgroundTasks:  0
  Display Sleep Uses Dim:   Yes
  GPUSwitch:    2
  Hibernate Mode:   3
  Reduce Brightness:    Yes
  Standby Delay:    4200
  Standby Enabled:  1

Hardware Configuration:

  UPS Installed:    No

AC Charger Information:

  Connected:    Yes
  ID:   0x0aa1
  Wattage (W):  85
  Family:   0x0085
  Serial Number:    0x00935697
  Charging: Yes

A: I had the same issue; I did an SMC reset.
Connect the power adapter to the Mac. On the MacBook / Pro's keyboard, hold down the Shift Control Option keys and the Power button at the same time. Release all keys and the power button at the same time – the little light on the MagSafe adapter may change colors briefly to indicate the SMC has reset.


text:
Q: Text isn't anxiously aligned in span The text-align (center) property isn't properly working for my text.
I have the following code:
  i Bla bla.

And the css for the info class is:
 .info {
  font-weight: bold;
  text-align: center;
  background-color: #C73C3C;
  -moz-border-radius: 15px;
  border-radius: 15px;
  text-transform: lowercase;
  letter-spacing: 4px;
  color: #ffffff;
  cursor: pointer;
  font-size: 21px;
}

And the current result is:

A: This could be due to letter-spacing: 4px;
Instead of this and  , you can try using padding instead.

.info {
  font-weight: bold;
  text-align: center;
  background-color: #C73C3C;
  -moz-border-radius: 15px;
  border-radius: 15px;
  text-transform: lowercase;
  /*letter-spacing: 4px;*/
  padding: 0 20px;
  color: #ffffff;
  cursor: pointer;
  font-size: 21px;
}
i

A: You can set div above span tag.Then your text will come in center.

 .info {
  font-weight: bold;
  text-align: center;
  background-color: #C73C3C;
  -moz-border-radius: 15px;
  border-radius: 15px;
  text-transform: lowercase;
  letter-spacing: 4px;
  color: #ffffff;
  cursor: pointer;
  font-size: 21px;
}

div{
text-align:center;
}

  i Bla bla.


text:
Q: C++: I don't understand how this while loop works I was looking at some questions on here that shows you how to read from a txt file, and then assign anything in it to separate variables. The answer used a while loop that looked like this...
ifstream file("file.txt");

int var1;
int var2;
int var3;

while (file >> var1 >> var2 >> var3)
{
    /* do something with name, var1 etc. */
    cout << var1 << var2 << var3 << "\n";
}

My question is, what is happening in that while loop that allows it assign those variables the right value? I know that it works, because I used it, but I just don't understand how it works.
Here's the link I was looking at, just in case anybody wanted to also look at it.
C++: Read from text file and separate into variable
Thanks!

A: Basically, the "expression"(a) file >> var1 >> var2 >> var3 will attempt to read three values from the file stream and place them into the specified variables. It's basically no different than cin >> myVar on it's own (except that it's chanining the input to multiple variables).
The value of that entire expression will be true if and only if all three values are read successfully.
In that case, the loop body will execute, the three values will be printed out, and the loop will go back to the top and try to get the next three values.
At the point where the expression evaluates as false (i.e., three values are not read), the loop will stop.

(a) The actual pathway from someStream >> someVariable to a Boolean value involves a few steps within the stream class (the return value from operator>> being converted to a Boolean with operator bool) but the above explanation should be good enough for most purposes.

A: ifstream overloads operator>>. In your particular case it is:
basic_istream& operator>>( int& value );

as you see it returns reference to itself so you can rewrite:
 while (file >> var1 >> var2 >> var3)

as a function calls:
while (file.operator>>(var1).operator>>(var2).operator>>(var3))

additionally ifstream explicitly converts to bool which gives true if stream is ok, otherwise false. This conversion is done using operator bool, which is marked as explicit (C++11 and up). This specifier applied to conversion operator allows to use ifstream instance in while loop or if statements, but it will not allow you to for example assign it to bool variable:
bool b = file; // results in error

A: The compiler will translate: file >> var1 >> var2 >> var3 as: file.operator>>(var1).operator>>(var2).operator(var3)
The return of basic_istream::operator>>(int&) is basic_istream& hence the extraction operator can be called repeatedly on it's return because it returns a reference to itself.
When you evaluate this as in: while(file >> var1 >> var2 >> var3) the compiler is really doing: while(file.operator>>(var1).operator>>(var2).operator(var3).operator bool()) And we can see that basic_stream provides operator bool() So that will be what is evaluated as the condition for the while loop. And operator bool():

Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().

So the human readable interpretation of this line is: "Insert var1, var2, and var3 into file. If the insertions didn't fail continue the loop."


text:
Q: valid argument forms to deduce the conclusion from the premises, please explain to me , to understand this? $$p \rightarrow q \\
r \lor s \\
\lnot s \rightarrow \lnot t \\
\lnot q \lor s \\
\lnot s \\
\lnot p \land r \rightarrow u \\
w \lor t$$
Is this a valid argument to deduce the conclusion from the premises?
I want to understand the argument above. Can you please explain it to me with reasons for each step? Thank you.

A: 1 p→q
2 r∨s
3 ¬s→¬t
4 ¬q∨s
5 ¬s
6 ¬p∧r→u
7 w∨t
4,5 give not q
not q, 1 give not p
2,5 give r
not p, r, 6 give u
3,5 give not t
not t, 7 give w
ergo u and w


text:
Q: Every sentence in propositional logic can be written in Conjunctive Normal Form While reading through Artificial Intelligence: A Modern Approach by Stuart Russell and Peter Norvig, I came upon the following question:

Any propositional logic sentence is logically equivalent to the
  assertion that each possible world in which it would be false is not
  the case. From this observation, prove that any sentence can be
  written in CNF.

Does anyone have a reference or a proof that Every sentence in propositional logic can also be written in Conjunctive Normal Form?
My (lousy) attempt was that since CNF requires $\forall x\ \mathit{Clauses}(x)$, and propositional logic implies that all sentences it declares must be true for the statement to hold true, then one implies you can convert it?

A: Wikipedia's article on conjunctive normal form gives an idea of why a sentence is logically equivalent to its conjunctive normal form:

Every propositional formula can be converted into an equivalent formula that is in CNF. This transformation is based on rules about logical equivalences: the double negative law, De Morgan's laws, and the distributive law.

I think that what Russell and Norvig are getting at (the question is sort of vague, in my opinion) is that if you have a sentence like
$$ ((A \lor B) \to C) \land \lnot(D \land E) \tag{1}$$
you could then ask "in what cases would this sentence be false?"  In this case, it's when

*

*One side of the conjunction is false, which means that

*
*

*either $(A \lor B) \to C$ is false, which means that

*
*

*
*

*$A$ or $B$ is true and $C$ is false, which means that

*
*

*
*

*
*

*either $A$ is true and $C$ is false

*
*

*
*

*
*

*or $B$ is true and $C$ is false

*
*

*or $\lnot(D \land E)$ is false, which means that

*
*

*
*

*$D$ is true and $E$ is true

From those you can read off a disjunctive normal form:
$$ (A \land \lnot C) \lor (B \land \lnot C) \lor (D \land E) \tag{2} $$
Those are all the cases where $(1)$ is false.  If we negate $(2)$, it is like the "assertion that each possible world in which it would be false is not the case," and we get
$$ \lnot( (A \land \lnot C) \lor (B \land \lnot C) \lor (D \land E) ) \tag{3} $$
which by De Morgan's laws is
$$ \lnot(A \land \lnot C) \land \lnot(B \land \lnot C) \land \lnot(D \land E) \tag{4} $$
and then
$$ (\lnot A \lor C) \land (\lnot B \lor C) \land (\lnot D \lor \lnot E) \tag{6} $$
which is conjunctive normal form for $(1)$.  So, by enumerating all the ways that a sentence could be false, turning that into a single sentence, negating it, and applying De Morgan's laws, we have a logically equivalent sentence in conjunctive normal form.

A: The quote you provided is the essence of the proof. Given a sentence with $n$ propositional variables, there are some (at most $2^{n}$) assignments of truth values ("possible worlds") that evaluate the sentence to FALSE. For each one of these assignments, disjunct the variables that are assigned FALSE and disjunct to those the negation of the variables that are assigned TRUE. Now conjunct all of those disjuncts.

A: Assume we have a fine set of atoms $A = \{ a_1, \dots, a_n \}$ (i.e. think of it as statements that are true or false, like a = "the rocks are made of material". Then what we want to show is:

Given any proposition $p$ (made up of logical connectives, atoms and other propositions) is equivalent to a disjunction $p_1 \lor \dots \lor p_k $ where each disjunct $p_i = a^{\epsilon_1}_1 \land \dots \land a^{\epsilon_n}_n$ and $a^1 := a$ and $a^{-1} := \neg a$.

So given a proposition $p$ we can transform it to another in "disjunctive normal form" as defined above. The idea is to show that there exists a proposition of that form and is equivalent to the original one. To show that its equivalent to the original one we need to show that they return the same truth tables, so with any truth assignment to the atoms they return the same truth value.
Notice that a row of a truth table only containing the atoms is just a truth assuagement $t:A \to \{0,1\}$ ("state of the world" since it assigns values to the atoms/building blocks). This is key because it means that we only have to go through the rows (truth assignments) that set the proposition $p$ true and essentially "encode" that in $p_i = a^{\epsilon_1}_1 \land \dots \land a^{\epsilon_n}_n$.
So list all such truth assignments $t_1, \dots, t_k$. Consider going through them and consider the current one we are considering be $t_j$. With this we will define $p_i = a^{\epsilon_1}_1 \land \dots \land a^{\epsilon_n}_n$ that is true when $t_j$ is true. i.e. $t_j(p_j) = 1$. We do this my setting $\epsilon_i = 1$ if $t_j(a_i) =1$ and $\epsilon_i = -1$ if $t_j(a_i) = 0$. This just picks up the fact that $p_j$ is 1 with the current row of the truth table we are considering. Since $p$ is a disjunction (OR's) then it must be that $t_j(p) = 1 $ since $t_j(p_j) =  1$. So $t(p) = 1 \iff t = t_j$ (its not hard to show it will be zero at the right places since none of these will be true for the remaining rows of the truth table). In fact if you notice you can actually make the notation more compact by doing:
$$ p_j = a^{2t_j(a_1) - 1}_1 \land \dots \land a^{2t_j(a_n) - 1}_n$$
since $\epsilon_i = 2t(a_i) - 1$.
Which completes the proof.
Now note that this argument is not special to atoms. If instead you had propositions instead of atoms, you can still write a (fake) "truth table" with propositions but instead you'd treat those propositions as your "building blocks" for the above algorithm.


text:
Q: iPhone sometimes dims display quickly (a few seconds) even when Automatic Display and Brightness is turned off My iPhone is over 90% charged - and in fact was connected to power. But it was dimming even just a few seconds after accepting a call. I could not look at another app on the phone since the display kept turning off (more than once). The phone call proceeded otherwise normally.
I have looked at this other question that talks about five minutes . That is short but nothing at all like about five seconds:   How to stop iPhone from automatically dimming the brightness?
This does not happen often but when it does it seems to only get resolved by entering into the Settings app and looking around (not necessarily even doing any changes).
What might be happening here - and is there a workaround/fix?   I have an iPhone6S and am on iOS 14.2


text:
Q: PostgresException return null from GCP when call function have an error by constraint FK I am using Google Cloud Platform to host my database postgres 9.6.
I have sent data to force error in FK for an update, in filas = cmd.ExecuteNonQuery() the result is 0 rows, as I hoped. But catch (PostgresException msg_exception) does not recognize the exception and PostgresNotice msg_notice = new PostgresNotice() returns NULL too when try to use the msg_notice.
using(var conn = new NpgsqlConnection(connString)) {
 conn.Open();
 conn.TypeMapper.MapComposite < DTO_Usuario > ("t_usuario");

 using(var transaction = conn.BeginTransaction(IsolationLevel.ReadCommitted)) {
  try {
   using(NpgsqlCommand cmd = new NpgsqlCommand(@ "SELECT ent_usuario_update(@p)", conn)) {
    cmd.Parameters.Add(new NpgsqlParameter {
     ParameterName = "p",
      Value = row_usuario
    });

    PostgresNotice msg_notice = new PostgresNotice();
    try {
     filas = cmd.ExecuteNonQuery();

     transaction.Commit();

     if (filas > 0) {
      row_usuario.Nom_usuario = msg_notice.MessageText;
     } else {
      row_usuario.Nom_usuario = msg_notice.MessageText;
     }

    } catch (PostgresException msg_exception) {
     transaction.Rollback();
     row_usuario.Des_cargo = msg_exception.SqlState;

    }
    return Ok(row_usuario);
   }
  } catch (NpgsqlException) {
   transaction.Rollback();
   return NoContent();
  }
 }
}

My function in Postgres:
CREATE OR REPLACE FUNCTION public.ent_usuario_update(
p_usuario t_usuario)
RETURNS void

update usuario
   set des_cargo=p_usuario.des_cargo,
       nom_usuario = p_usuario.nom_usuario,
       id_organizacion = p_usuario.id_organizacion
 where id_instancia = p_usuario.id_instancia
   and id_mandante = p_usuario.id_mandante
   and id_usuario=p_usuario.id_usuario;

GET DIAGNOSTICS filas = ROW_COUNT;

IF filas == 0 THEN
    RAISE INFO 'No se actualizo usuario % en instancia %', p_usuario.id_usuario,  p_usuario.id_instancia
    using message = 'No actualizo';
ELSE
    RAISE INFO 'Actualización Realizada'
    using message = 'No actualizo';
END IF;

RETURN;

END;

A: PostgreSQL notices aren't raised as exceptions, because they're not errors - so try/catch won't yield anything. It's also not possible to simply instantiate a PostgresNotice and expect it to get automatically filled in when you execute a command.
To receive a PostgreSQL notice, simply subscribe to the Notice event on your connection:
conn.Notice += (sender, args) => Console.WriteLine(args.Notice.MessageText);


text:
Q: Using Treeview as a dropdown template for combo with complex grouping requirments Using the data below as an example...
Id      Name                Type        Sector
12345   GOOG                Eqty        Internet
12346   MSFT                Eqty        Internet
12347   MOBL                Eqty        Oil
12348   XOM                 Eqty        Oil
12349   Wheat               Comdty
12310   Corn                Comdty
12311   Nas 100 eMini       Futures
12312   S&P 500 eMini       Futures

Using the above data i want to build a dropdown combo selector w/ autofiltering that will display a treeview in the format shown below.
Essentially, i want to group by "Type", then by "Sector", then display the Name.  However if Sector is missing, then Name should be grouped under just Type.
+Equities(Eqty)
    +Internet
        Goog
        Msft
    +Oil
        MOBL
        XOM
+Commodities(Comdty)
    Wheat
    Corn
+Futures
    Nas 100 eMini
    S&P 500 eMini

I've tried a number of ways to do this elegantly via just XAML/templating, without much luck.  The complicated part here is that the second grouping is conditional.
Any thoughts on how i might be able to solve this issue would be appreciated

A: If you are intent on working with the now defunct technology called SilverLight and therein use XAML ? Templating look at this link for recursive templating
To do this using linq, what you need is a recursive call... see the answer given here for a nice example.


text:
Q: Unexpected assignment in numpy array I have a somewhat weird problem which is probably derived from how indexing works in numpy. But for some reason I don't seem to understand it, let alone reach the behavior I'm expecting:
>>> a = np.array([['a', 'b'], ['c', 'd']], dtype='<U10')
>>> a
array([['a', 'b'],
       ['c', 'd']], dtype='<U10')
>>> a[0] = ['e']
>>> a
array([['e', 'e'],
       ['c', 'd']], dtype='<U10')

So what I was expecting is to obtain
array([['e'], ['c', 'd']], dtype='<U10)

Can someone give me a hint as of why this is not working as I was expecting, and how to reach the expected behavior?
Also, and in reaction to roganjosh's comment:
>>> a = np.array([np.array(['a', 'b']), np.array(['c', 'd'])])
>>> a[0] = 'e'
>>> a
array([['e', 'e'],['c', 'd']], dtype=object)

However:
>>> a = np.array([np.array(['a', 'b', 'l']), np.array(['c', 'd'])])
>>> a[0] = 'e'
>>> a
array(['c', array(['c', 'd'], dtype='<U1')], dtype=object)

which feels sort of weird.
Thanks in advance!

A: In your last example, you make a 2 element array.  Each element can be anything - a string, a list, or array:
In [113]: a = np.array([np.array(['a', 'b', 'l']), np.array(['c', 'd'])])
<ipython-input-113-3010d1b297e2>:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
  a = np.array([np.array(['a', 'b', 'l']), np.array(['c', 'd'])])

Without the warning:
In [114]: a = np.array([np.array(['a', 'b', 'l']), np.array(['c', 'd'])],object)
     ...:
In [115]: a.shape
Out[115]: (2,)
In [116]: a
Out[116]:
array([array(['a', 'b', 'l'], dtype='<U1'),
       array(['c', 'd'], dtype='<U1')], dtype=object)
In [117]: a[0]
Out[117]: array(['a', 'b', 'l'], dtype='<U1')
In [118]: a[0] = ['foobar']
In [119]: a
Out[119]: array([list(['foobar']), array(['c', 'd'], dtype='<U1')], dtype=object)
In [120]: a[0] = 'foobar'
In [121]: a
Out[121]: array(['foobar', array(['c', 'd'], dtype='<U1')], dtype=object)

This array behaves very much like a 2 element list.  In fact I'd question the value of using such an array instead of a list.
Creating an object dtype array with arrays that are all the same shape can be tricky, because np.array tries to makes multidimensional array where possible (as in your original example).
In [133]: a = np.empty(2,object)     # 'blank' array with desired shape
In [134]: a
Out[134]: array([None, None], dtype=object)
In [135]: a[:] = [['a','b'],['c','d']]    # assign 2 lists to it
In [136]: a
Out[136]: array([list(['a', 'b']), list(['c', 'd'])], dtype=object)
In [137]: a[1] = np.array(['a','b'])     # assign an array to an element
In [138]: a
Out[138]: array([list(['a', 'b']), array(['a', 'b'], dtype='<U1')], dtype=object)

The display gives information about the array elements.
2d array
The original example is 2d array.  The fact that it is string dtype (or object) doesn't make much difference.  It could just as well a numeric array.  You can't change the shape by assignment.
In [122]: b = np.array([['a', 'b'], ['c', 'd']], dtype='<U10')
In [123]: b
Out[123]:
array([['a', 'b'],
       ['c', 'd']], dtype='<U10')
In [124]: b.shape
Out[124]: (2, 2)

The regular multidimensional array indexing rules apply, including broadcasting.
In [125]: b[0]
Out[125]: array(['a', 'b'], dtype='<U10')
In [126]: _.shape
Out[126]: (2,)
In [127]: b[0] = 'd'         # broadcast to the whole row
In [128]: b
Out[128]:
array([['d', 'd'],
       ['c', 'd']], dtype='<U10')

In [129]: b[0] = ['d','e']    # assign separate elements to the row
In [130]: b
Out[130]:
array([['d', 'e'],
       ['c', 'd']], dtype='<U10')

In [131]: b[:,1] = ['x','y']   # assign to a column
In [132]: b
Out[132]:
array([['d', 'x'],
       ['c', 'y']], dtype='<U10')

Look at how these arrays are converted to a list:
In [139]: a.tolist()
Out[139]: [['a', 'b'], array(['a', 'b'], dtype='<U1')]
In [140]: b.tolist()
Out[140]: [['d', 'x'], ['c', 'y']]

numpy is optimized for numeric multidimensional arrays.  All the fast compiled code works on numeric values.  It can store strings and general objects, but the processing is at Python speeds, not fast compiled ones.


text:
Q: Are there any faster way to erase elements from std::vectors? I'm trying to upgrade from C to C++, and I'm having a lot of issues to get used to it. In C, I'm used to work with pointers and linked list, but that is some tiresome job. Then, I was introduced to std::vectors, and the world become prettier. Until I had to work with really huge vectors (a vector of 3 million of small vectors (usually some vector<short>)). Then my nightmare started. The operation is simply (described below).
vector<vector<short>> v;
v = build(); \\create all 3 million of small vectors
for(int i = 0; i < v.size(); i++){
   if(someReallyFastTest(v[i])){
      v.erase(v.begin() + i);
      i--;
   }
}

The program does its purpose, but takes days to finish. I tried to depurate the code and then I notice that the command
v.erase(v.begin() + i);

takes seconds to complete the task. Since in each turn I have to erase thousands of elements, it take hours to complete the task. I don't want to go back and work with pointers and linked list so soon. Is there any faster way to do this task?


text:
Q: Differentiate devices in MPLAB X IDE I have a code that will be used to program a board (using a Pickit3 controller)that contains 2 devices. Within the code contains the initialization for both of these devices in 2 separate functions. How do I use device indices to determine which function to execute? Each of these functions writes to registers that these devices seem to share...

A: You have not provided models so I cannot link to specific datasheets but most devices have a read only DeviceID register that you could read. Although I suspect you wont be able to compile your app in a way that will work for both devices as although they share register names (ex. in C) the memory mapping often changes slightly from one device to the next and the compiled applications relie on memory mapping not register names. Your best bet is probably to setup two project configurations and use conditional compilation to compile ether one config or the other.


text:
Q: Scala types: least upper bounds I am trying to parameterize some methods with very general type parameters.
As an example, in the REPL I first define:
trait Term
case class FunctionalTerm[+T <: Term](t: T) extends Term

Intuitively, the following method takes a Term and a FunctionalTerm, and returns something with type the least upper bound of the type of term passed and the argument type of the FunctionalTerm:
def ex1[T1 <: Term, T3 <: X, FunctionalTerm[T1] <: X, X <: R, R <: Term](t1: FunctionalTerm[T1], s: T3): R = sys.error("TODO")

So far so good in the REPL.
Then I define ex2 as a convenience function that performs the same operation as ex1, but with the input arguments swapped:
def ex2[T2 <: Term, T3 <: X, FunctionalTerm[T2] <: X, X <: R, R <: Term](s: T3, t2: FunctionalTerm[T2]): R = ex1(t2,s)

Attempting to define ex2 in the REPL gives the following error:
error: inferred type arguments [T2,T3,FunctionalTerm,T3,T3] do not conform to method ex1's type parameter bounds [T1 <: Term,T3 <: X,FunctionalTerm[T1] <: X,X <: R,R <: Term]
         ex1(t2,s)
         ^
error: type mismatch;
 found   : FunctionalTerm[T2]
 required: FunctionalTerm[T1]
         ex1(t2,s)
             ^
error: type mismatch;
 found   : T3(in method ex2)
 required: T3(in method ex1)
         ex1(t2,s)
                ^
error: type mismatch;
 found   : R(in method ex1)
 required: R(in method ex2)
         ex1(t2,s)
            ^

I have spent about two days trying to figure out a solution, and am now totally stuck. I cannot find anything more on Google.
Since the type argument list of ex2 is the same as that of ex1 but with T1 and T2 swapped, I don't understand is wrong, or how to fix it.
Any help would be hugely appreciated!
Update
Least upper bounds were a red herring. The example can be distilled further.
The following two functions can be defined in the REPL without error:
def ex1[T1 <: Term, FunctionalTerm[T1] <: Term](t1: FunctionalTerm[T1]): Term = sys.error("TODO: ex1")
def ex2[T2 <: Term, FunctionalTerm[T2] <: Term](t2: FunctionalTerm[T2]): Term = ex1(t2)

Introducing the extra parameter X seems to cause the problem. I can define the following in the REPL:
def ex3[T1 <: Term, FunctionalTerm[T1] <: X, X <: Term](t1: FunctionalTerm[T1]): Term = sys.error("TODO: ex3")

But attempting to subsequently define:
def ex4[T2 <: Term, FunctionalTerm[T2] <: X, X <: Term](t2: FunctionalTerm[T2]): Term = ex3(t2)

gives the error:
error: inferred type arguments [T2,FunctionalTerm,Nothing] do not conform to method ex3's type parameter bounds [T1 <: Term,FunctionalTerm[T1] <: X,X <: Term]
       def ex4[T2 <: Term, FunctionalTerm[T2] <: X, X <: Term](t2: FunctionalTerm[T2]): Term = ex3(t2)
                                                                                ^
error: type mismatch;
 found   : FunctionalTerm[T2]
 required: FunctionalTerm[T1]
       def ex4[T2 <: Term, FunctionalTerm[T2] <: X, X <: Term](t2: FunctionalTerm[T2]): Term = ex3(t2)
                                                                                ^

So, I guess the question becomes: Why does the parameter X unused in the signature have this effect?

A: I'm not sure whether or not you're experiencing a bug, but I am pretty sure you're making your life a lot more difficult that it needs to be. You can rely on covariance and unification to do all the hard work for you,
scala> trait Term
defined trait Term

scala> case class FunctionalTerm[+T <: Term](t: T) extends Term
defined class FunctionalTerm

scala> def ex1[T <: Term](t1 : FunctionalTerm[T], s : T) : T = s
ex1: [T <: Term](t1: FunctionalTerm[T], s: T)T

scala> class A extends Term ; class B extends A ; class C extends A
defined class A
defined class B
defined class C
scala> ex1(new FunctionalTerm(new B), new C)
res0: A = C@4ceeb514

Note the inferred result type (which is equivalent to the R of your original more complex definition) ... it's A which is the LUB of B and C.
Now the flipped version is trivial and Just Works,
scala> def ex2[T <: Term](s : T, t1 : FunctionalTerm[T]) : T = s
ex2: [T <: Term](s: T, t1: FunctionalTerm[T])T

scala> ex2(new C, new FunctionalTerm(new B))
res1: A = C@522ddcec

A: I'm going to simplify your example (I'm using 2.9.1):
scala> trait Term; case class FunctionalTerm[+T <: Term](t: T) extends Term;
defined trait Term
defined class FunctionalTerm

scala> def ex1[T1 <: Term, T3 <: X, FunctionalTerm[T1] <: X, X <: R, R <: Term](t1: FunctionalTerm[T1], s: T3): R = sys.error("TODO")
ex1: [T1 <: Term, T3 <: X, FunctionalTerm[T1] <: X, X <: R, R <: Term](t1: FunctionalTerm[T1], s: T3)R

Now declaring the second method:
scala> def ex2[T2 <: Term, T3 <: X, FunctionalTerm[T2] <: X, X <: R, R <: Term](s: T3, t2: FunctionalTerm[T2]): R = ex1(t2, s)
<console>:11: error: inferred type arguments [T2,T3,FunctionalTerm,T3,T3] do not conform to method ex1's type parameter bounds [T1 <: Term,T3 <: X,FunctionalTerm[T1] <: X,X <: R,R <: Term]
       def ex2[T2 <: Term, T3 <: X, FunctionalTerm[T2] <: X, X <: R, R <: Term](s: T3, t2: FunctionalTerm[T2]): R = ex1(t2, s)
                                                                                ^

The suspicious thing (to me) is the inferred types [T2,T3,FunctionalTerm,T3,T3] - in particular FunctionalTerm. FunctionalTerm is a type constructor * -> *but the method expects a type * in this position.
I would say that this is (presumably) a bug and hence you should submit it to the scala-user mailing list (before raising a ticket) - Adriaan Moors and Miles Sabin are much more likely to have a detailed answer as to whether I'm right.


text:
Q: Find multiple longest words and count how many times they repeat So i made code that finds longest words in two text files and if that is unique word in first text file it writes to file. But i need to find unique words in first text file and then from those unique words find 10 longest words. Then those 10 words sort from longest to shortest and count how many times it appears in first text file.
        string[] LongestWrods(string[] longest1, string[] text2, int longestCount1, out int longestWordText, char[] @char)
    {
        string[] LongestWordsText1 = new string[10];
        longestWordText = 0;
        for (int i = 0; i < longestCount1; i++)
        {
            if (RepeatTimes(text2, longest1[i], @char) == 0)
                LongestWordsText1[longestWordText++] = longest1[i];
        }
        return LongestWordsText1;
    }

A: This way:
class Program
{
    static void Main(string[] args)
    {
        List<string> wordsToCut = File.ReadAllLines("text2.txt").Distinct().ToList();

        List<UniqueWord> uniqueWords = new List<UniqueWord>();

        foreach (string word in File.ReadAllLines("text1.txt"))
        {
            if (wordsToCut.Contains(word) == false)
            {
                UniqueWord uniqueWord = uniqueWords.Where(x => x.Word == word).FirstOrDefault();

                if (uniqueWord != null)
                {
                    uniqueWord.Occurrence++;
                }
                else
                {
                    uniqueWords.Add(new UniqueWord(word));
                }
            }
        }

        uniqueWords = uniqueWords.OrderByDescending(x => x.Word.Length).Take(10).ToList();
    }
}

public class UniqueWord
{
    public string Word { get; set; }
    public int Occurrence { get; set; }

    public UniqueWord(string word)
    {
        Word = word;
        Occurrence = 1;
    }
}

A: Of course not the best option, but fastest one i could get. largestWordsCount contains all the 10 largest unique words and how times it appears in text for each.
var text = "The standard Lorem Ipsum passage, standard used standard since the 1500s \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed";
var splittedText = text.Split(' ');
var uniqueWords = new HashSet<string>(splittedText);
var tenLargestWords = uniqueWords.ToList().OrderByDescending(x => x.Length).Take(10);
var largestWordsCount = tenLargestWords.Select(word => new KeyValuePair<string, int>(word, Regex.Matches(text, word).Count)).ToList();


text:
Q: Using the chain rule on $P \left( Y = y \mid X = x \right)$, with $y \in \mathbb{R}^2$ I have a probability of the form $P \left( Y = y \mid X = x \right)$, with $y \in \mathbb{R}^2$, and want to find a way to express it in terms of $y_1$ and $y_2$ separately. Would the following be correct?
$$\begin{align*}
P \left( Y = y \mid X = x \right) & = P \left( Y_1 = y_1, Y_2 = y_2 \mid X = x \right) \\
& = P \left( Y_2 = y_2 \mid Y_1 = y_1, X = x \right) \cdot P \left( Y_1 = y_1 \mid X = x \right)
\end{align*}$$

A: If $\def\eq{\hspace{0.25ex}{=}\hspace{0.25ex}}\vec Y\eq\langle Y_1,Y_2\rangle$ and $\vec y\eq\langle y_1,y_2\rangle$, then indeed:-
$$\begin{align}\mathsf P(\vec Y\eq\vec y\mid X\eq x)&=\mathsf P(Y_1\eq y_1, Y_2\eq y_2\mid X\eq x)\\[1ex]&=\mathsf P(Y_1\eq y_1\mid X\eq x)\,\mathsf P(Y_2\eq y_2\mid Y_1\eq y_1, X\eq x)\end{align}$$
This is just an application of the Chain Rule for Conditional Probability.


text:
Q: Find all entire functions $f$ satisfying $\Re(f(z))\leq\frac{2}{|z|}$ whenever $|z|>1\iff \frac{1}{|z|}< 1$ I've been working in the following:

Find all the entire function $f$ satisfying $$\Re (f(z))\leq \frac{2}{|z|}\quad\textrm{  whenever } \quad|z|>1\iff \frac{1}{|z|}< 1$$

Solution: Suppose that $f$ is entire with under these conditions. First, $\Re f\leq 2$. Second, consider $g(z)=\exp(f(z))$, then $g$ is entire too and
$$
|g(z)|=|\exp(f(z))|=\exp(\Re(f(z)))\leq e^2.
$$
Hence, by  Liouville's theorem, $g(z)=C$.
Finally, we observe $$g(z)=\exp(f(z))\Longrightarrow g'(z)=f'(z)\exp(f(z))\Longrightarrow 0=f'(z)$$
meaning that $f(z)$ must be a constant.
I just wonder if I miss steps or I'm wrong. Thanks

A: A few corrections . . .

*

*Minor correction:
$$|g(z)|=\exp(|f(z)|)=\; .\;.\;.$$
should be
$$|g(z)|=|\exp(f(z))|= \;.\;.\;.$$

*Also (really minor):$\;$For the inequality
$$|z| > 1\iff \frac{1}{|z|}\leq 1$$
the LHS is strict and the RHS is non-strict.$\\[10pt]$

*Finally, your conclusion needs to be fixed:

Since $f$ is constant, the condition
$$\Re (f(z))\leq \frac{2}{|z|}$$
for all $z$ with $|z| > 1$ implies
$$\Re (f(z))\leq 0$$
hence $f$ must be a constant with nonpositive real part.$\\[10pt]$
Other than that, your argument looks good.


text:
Q: using orWhere in laravel gives an error I am unable to use orWhere and I don't know the reason.
My goal is to pull amount_invoice=0 OR total_mileage=0. My query works if I use WHERE clause only. When I add orWhere, then my query fails.
This query works:
$deliveries = $this->instance->delivery
        ->where('amount_invoice', 0);
        //->where('total_mileage', 0);
        //->where('amount_invoice', 0)->where('total_mileage',0);
        //->where('amount_invoice', 0)->orWhere('total_mileage', 0);
dd($deliveries);

This query works:
$deliveries = $this->instance->delivery
        //->where('amount_invoice', 0);
        ->where('total_mileage', 0);
        //->where('amount_invoice', 0)->where('total_mileage', 0);
        //->where('amount_invoice', 0)->orWhere('total_mileage', 0);
dd($deliveries);

This query works:
$deliveries = $this->instance->delivery
        //->where('amount_invoice', 0);
        //->where('total_mileage', 0);
        ->where('amount_invoice', 0)->where('total_mileage', 0);
        //->where('amount_invoice', 0)->orWhere('total_mileage', 0);
dd($deliveries);

This query DOES NOT WORK:
$deliveries = $this->instance->delivery
        //->where('amount_invoice', 0);
        //->where('total_mileage', 0);
        //->where('amount_invoice', 0)->where('total_mileage', 0);
        ->where('amount_invoice', 0)->orWhere('total_mileage', 0);
dd($deliveries);

I don't know what is the problem but using orWhere fails

A: Without knowing what your model relationships look like, I'm guessing that
$this->instance->delivery

gives you a collection back, since that's what Laravel typically does. And ->where(...) works to filter a collection in Laravel, but ->orWhere(...) doesn't.
If you have
$this->instance->delivery()

instead, you get a query builder back, which you can then use to perform ->where(...) and ->orWhere(...) queries on. Don't forget to add an ->get() call at the end.


text:
Q: ArrowDecorator as default drag connection How to set ArrowDecorator as default connection decorator?
When a new instance is created by the "draw2d.policy.connection.ConnectionCreatePolicy", I want it to be decorated by the ArrowDecorator.
What is the best way to do this without modifying the code base?
Currently I am just changing to code base by setting the target decorator in Connection.js
targetDecorator =  new draw2d.decoration.connection.ArrowDecorator()

A: Found the answer. Use the following code.
     canvas.installEditPolicy(  new draw2d.policy.connection.DragConnectionCreatePolicy({
        createConnection: function() {
            // return my special kind of connection
            var con =  new draw2d.Connection({
                targetDecorator: new draw2d.decoration.connection.ArrowDecorator()
            });
            return con;
        }
     }));   //canvas.add(c);


text:
Q: Unable to display image in JSP page Hi i am getting path of the image in REST API call as below
<hotel-info:thumb-nail-image>/4014/40140/images/Result_tn.jpg</hotel-info:thumb-nail-image>

How to display image in JSP page ?
In JAXB class :
@XmlElement(name = "thumb-nail-image", required = true)
protected String thumbNailImage;

In JSP :

Please help me how to display image in JSP ?

A: STS project explorer drop downs
Firt of all i am using spring tool suite and i now find solution for displaying image in jsp page.
first you need to have a name.xml file in /webapp/WEB-INF/views/name.xml
xml file must be in views folder in WEB-INF and include the content below........
<bean xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
<mvc:resources mapping="/resources/**"
        location="/resources/" /></bean>

........
then place the images folder in the webapp inside the resource folder so that you have access it easily.
if you done it properly then add path to place you want like this

if you have any doubt ...tell me comment


text:
Q: Would like to split a string using a regex pattern I have a string that I would like to split into
var finalQuote = "2012-0001-1";
var quoteNum = "2012-0001";
var revision = "1"

I used something like this
var quoteNum = quoteNum.subString(0,9);
var revision = quoteNum.subString(quoteNum.lastIndexOf("-") + 1);

But can't it be done using regex more efficiently? I come across patterns like this that need to be split into two.
 var finalQuote = "2012-0001-1";
 string pat = @"(\d|[A-Z]){4}-\d{4}";
 Regex r = new Regex(pat, RegexOptions.IgnoreCase);
 Match m = r.Match(text);
 var quoteNum = m.Value;

So far I have reached here. But I feel I am not using the correct method. Please guide me.
EDIT: I wanna edit by the pattern. Splitting with dashes is not an option as the first part of the split contains a dash. ie, "2012-0001"

A: I would simply go with:
var quoteNum = finalQuote.Substring(0,9);
var revision = finalQuote.Substring(10);

quoteNum would consist of the first 9 characters, and revision of the 10th and everything that may follow the 10th, e.g. if the revision is 10 or higher it would still work.
Using complicated regexes or extension methods is very quickly overkill; sometimes the simple methods are efficient enough by itself.

A: I would agree with others that using substring is a better solution than regex for this.
But if you're insisting on using regex you can use something like:
^(\d{4}-\d{4})-(\d)$

Untested since I don't have a C# environment installed:
var finalQuote = "2012-0001-1";
string pat = @"^(\d{4}-\d{4})-(\d)$";
Regex r = new Regex(pat);
Match m = r.Match(finalQuote);
var quoteNum = m.Groups[1].Value;
var revision = m.Groups[2].Value;

Alternatively, if you want a string[] you could try (again, untested):
string[] data = Regex.Split("2012-0001-1",@"-(?=\d$)");

data[0] would be quoteNum and data[1] would be revision.

Update:
Explanation of the Regex.Split:
From the Regex.Split documentation: The Regex.Split methods are similar to the String.Split method, except that Regex.Split splits the string at a delimiter determined by a regular expression instead of a set of characters.
The regex -(?=\d$) matches a single - given it is followed by a digit followed by the end of the string so it would only match the last dash in the string. The last digit is not consumed because we use a zero-width lookahead assertion (?=)

A: sIt would be easier to maintain in the future if you something that the new comer would understand.
you could use:
var finalQuote = "2012-0001-1";
string[] parts = finalQuote.Split("-");
var quoteNum = parts[0] + "-" + parts[1] ;
var revision = parts[3];

However if you insists you need a regEx then
(\d{4}-\d{4})-(\d)

There are two groups in this expression, group 1 capture the first part and the group 2 capture the second part.
var finalQuote = "2012-0001-1";
string pat = @"(\d{4}-\d{4})-(\d)";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(finalQuote);
var quoteNum = m.Groups[1].Value;
var revision = m.Groups[2].Value;


text:
Q: Force compilation to fail if a struct member with a particular name exists Suppose bad_name is a restricted identifier for example that I do not want to be part of the struct. I am looking for a mechanism to force a compilation failure in that case.
example.h
struct example {
  int okay_name;
  int bad_name;
}

main.cc
#include "example.h"

int main() {
  example ex;
  // cause compilation to fail here if bad_name is a member of ex

  return 0;
}

There are probably ways to cause a failure at runtime by simulating reflection, but is there a way to do this at compile time?

A: You can define bad_name to be something that would cause a compile time error. For example, nothing:
#define bad_name

gives on GCC

error: declaration does not declare anything [-fpermissive]
int bad_name;

A: You can simulate static assertions in C like this:
#define bad_name xxx; char static_assertion_bad_name_used[-1];

struct example {
  int okay_name;
  int bad_name;
};

which in GCC gives:
main.c:6: error: size of array 'static_assertion_bad_name_used' is negative

The advantage of this technique is that the error message gives you a reminder of what the problem is (even if slightly obscurely).
Update After reading this I found out that MS Visual Studio does not include the actual variable name in the error message if the array size is negative. Here is an alternative:
#define bad_name xxx; int static_assertion_bad_name_used : 0;

The error message in GCC is then:
main.c:5: error: zero width for bit-field 'static_assertion_bad_name_used'

and apparently something similar in VS.
Also if using a more up to date compiler you can use _Static_assert, which would be a lot cleaner.

A: You may use the following:
#include <cstdint>

#define DEFINE_HAS_SIGNATURE(traitsName, funcName, signature)               \
    template <typename U>                                                   \
    class traitsName                                                        \
    {                                                                       \
    private:                                                                \
        template<typename T, T> struct helper;                              \
        template<typename T>                                                \
        static std::uint8_t check(helper<signature, &funcName>*);           \
        template<typename T> static std::uint16_t check(...);               \
    public:                                                                 \
        static                                                              \
        constexpr bool value = sizeof(check<U>(0)) == sizeof(std::uint8_t); \
    }

DEFINE_HAS_SIGNATURE(has_bad_name, T::bad_name, decltype(&T::bad_name));

Then check with a static_assert (need C++11):
static_assert(!has_bad_name<example>::value, "");

A:
Suppose bad_name is a restricted identifier for example that I do not
  want to be part of the struct. I am looking for a mechanism to force a
  compilation failure in that case.

This is not fully portable, but at least in VC++ and GCC you can mark the identifier as deprecated and, if you want, elevate the warning it gives to an error.


text:
Q: 14.04 cannot output sounds to hdmi audio device My dell XPS 13 2015 with Ubuntu 14.04 is connected to an HDMI device via a displayPort -> HDMI adapter.
The picture appears fine on the HDMI monitor but I cannot select it as my output audio device. It doesn't appear in the system settings sound tab - only built in audio.
What can I do to fix this?

A: First, be aware for that display port to HDMI does not always transfer sound. Everything in your setup must be able to use DP for sound, even the adapter. Not all DP adapters will transfer sound. That being said, try alsamixer in terminal and change the settings there. If that does not work run sudo apt-get install pavucontrol and change your audio settings through there.

A: This helped me in Kubuntu: https://askubuntu.com/a/519113
You can use pavucontrol (pulseaudio volume control, install if necessary). Launch it from multimedia menu, go to the "output devices" tab, and click the green "define as alternative" button that is near HDMI soundcard.
Altho' I had to set the actual HDMI port as a sound device in 'output devices'. I also when to the 'configuration' tab & set it there. Then right-clicked on the speaker icon (KMix in Kubuntu) & selected 'select master channel' & changed it to HDMI there also.
Most likely the last one that fixed it for me (KMix).

A: I have had a similar issue with displayport audio in Ubuntu 20.04, where alsa reloading helped to fix the problem:
$ pulseaudio -k && sudo alsa force-reload

See details here.


text:
Q: How to add classpath resource in application.yml file With spring-boot, in case of application.properties file there is provision to specify classpath in value.
app.templates = classpath:app\mock-templates
How to specify same thing inside application.yml?
When specified like this, value read is not correct -
app:
  templates : 'classpath:app\mock-templates'

Value injection -
@Value("${app.templates}")
private String templateLocation;
// value injected is "classpath:app\mock-templates", it should be <absolute-path>\app\mock-templates

A: I just check that no matter if you use .properties or .yaml file you will have always classpath:app\mock-templates as an injected property value. And that's ok. Spring does not complete classpath: prefix to the real path in a time of reading from properties. That will be done next by ClassPathResource.
P.S. I think quotest also don't make any sense here.

A: I faced the exact same issue and there is a way to solve this. I tried using classpath but it does not work. Then I used this way
app:
  templates: "${PWD}/your/resources/dir/location"

In your application.yml file. It works for me just make sure your PWD will come from the path where your test are running. If you are using git hooks for running tests then mostly it's run from project root dir.

A: Was able to get this working by mentioning
src/test/resources/<file_name> in application.yml
  truststore: src/test/resources/trust.jks


text:
Q: How to share a drive with a network in Windows 7 How can I share a drive with my network, so that I can access the drive form my mobile (any device)  which is connected to the same network (same wireless modem).
I did try it once and when I tried to access the drive from ES File Explorer (Android app) it was asking me user name and password.  I did not have any passwords on my system.
OS : Windows 7

A: Much like the answer provided by Lee, there is one more step that is important for this to work. You will need to go to "Control Panel\Network and Internet\Network and Sharing Center\Advanced sharing settings"
File Sharing you need to go under the "Password protected sharing" section and tick "Turn off password protected sharing" Don't worry other folders you share can still be protected by an account. However without doing this devices like ES File Explorer can't even browse to the folder without some credentials even with it being share with the "Everyone" group.
EDIT: Also check the security tab as well in the general folder settings to ensure the "Everyone" group is also there to read.

A: Sharing a drive with across a network is easy with windows 7. First, hit WindowsKey + E to open an explorer window. Right-click on the drive you want to share, and Share With > Advanced Sharing

Click the Advanced Sharing button, then name the drive as you see fit. You will also need to assign permissions, which can be done granularly, or you can use the user 'Everyone' and its all access for all.

Click OK or Apply to save your changes and your drive should be available on the network by going to \\Your_PC_Name\Shared_Folder_Name
Keep security in mind if you share this network with other people. If you give all access rights to everyone, then anyone can delete/alter files. However if you give named access to individuals, you may not be able to access the share from a device such as a phone.
A final note, if you end the share name with a dollar sign ($), then the share will be hidden from users casually browsing, and they will only find it by explicitly typing in the name of the share.
Also see directions from Microsoft


text:
Q: Unity превращение transform.rotation в Vector2 Когда игрок входит в триггер, идёт проверка на булл, в зависимости от которого, задаётся новый вектор. Сейчас понял, что это можно оптимизировать, но мозга не хватает понять как.
Как, к примеру, сделать, что бы при входе игрока в коллайдер, задавался вектор в зависимости от поворота коллайдера?
        if(DashDR == true)
        {
            PlayerController.dashTime = PlayerController.dashStartTime;
            PlayerController.physics = 1;
            PlayerController.X = 1;
            PlayerController.Y = -1;
        }
        if(DashDL == true)
        {
            PlayerController.dashTime = PlayerController.dashStartTime;
            PlayerController.physics = 1;
            PlayerController.X = -1;
            PlayerController.Y = -1;
        }


text:
Q: socket io - How does it know if a data changed in DB? In my Angular5 / NodeJS web app, we have a dashboard that needs real-time data.
If there is any data change in the DB, we want it to be reflected in the front end immediately. Currently, we are reloading the data at regular intervals (say 30 seconds).
Can socket.io help to achieve this?
Not sure, how does it know if there are any data changes in the DB?

A: You can use SSE (Server Sent Events) a feature in HTML5.
Server-Sent Events (SSE) is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established. They are commonly used to send message updates or continuous data streams to a browser client and designed to enhance native, cross-browser streaming through a JavaScript API called EventSource, through which a client requests a particular URL in order to receive an event stream.
Here is simple example
As the SSE are unidirectional it will save efforts and enhance performance, as you just want to send db updates to frontend i.e. single direction only.
Hope this will help you.


text:
Q: How to restore an object in Silverlight 5 I have created an application by using Silverlight 5. There are many two-way databind in it. I want to retore a change in UI by restoring the object behind. For example:
I have an object behind which contains properties double Left, Right, I inherited it from INotifyPropertyChanged. In UI, I created tow button (ButtonLeft and ButtonRight) and their parent a Canvas Control, ButtonLeft bind Left property in two-way mode and ButtonRight bind Right property in two-way mode. It works very well, if I drag ButtonLeft, then the Left property will be updated with the new Left Value, same for ButtonRight.
Is there any way to restore the old value after the change of UI. Actually, the relation of class in my application is very complicated, I have already knew that retore the value of property in object will restore the UI, so is there any way (more general and loose-coupling) to restore all the objects that need to be restored.
I have thought of creating an interface IRestorable (inside Store(), Restore()) for objects that need to save and restore state. An attribute Restorable for property which need to be restored. For me, the use of AOP could be a good idea, each time when an instance of IRestorable is created, AOP will call a method for saving the current state (properties which is marked an [Restorable]) of object. I don't know if I was on the right way. If not, any advice will be appreciated.

A: Use of memeno design pattern.
http://www.codeproject.com/Articles/18025/Generic-Memento-Pattern-for-Undo-Redo-in-C


text:
Q: While loop for last file in the directories I run this code for getting the list of directories from input file and return last file in each directory
#!/bin/bash
while IFS= read -r line; do
echo "Text read from file: $line"
ls $line -ltrh |tail -1
done < "$1"

but its not working
with this error
[root@localhost /]# ./last_file.sh new2.txt
Text read from file: 17609
 No such file or directory
Text read from file: 17601
: No such file or directory
Text read from file: 17608
: No such file or directory
Text read from file: 17610
: No such file or directory
Text read from file: 12465
: No such file or directory
Text read from file: 12356
: No such file or directory
Text read from file: 34562
: No such file or directory

A: I just inverted ls options and everything works as expected:
#!/bin/bash
while IFS= read -r line; do
        echo "Text read from file: $line"
        ls -ltrh "$line" | tail -1
done < "$1"

Please, tell me what do you get.
 $>  ./last_file.sh new2.txt
 $>  Text read from file: /xxxxxx/xxxxxx/Downloads/
 $>  -rwxr-xr-x   1 xxxxxxx  staff   115B Sep  3 16:49 last_file.sh


text:
Q: If exists then quit VBS Please take this script into context with my question:
If objFSO.FileExists("C:\Windows\Fonts\" & objFile.Name) Then
Wscript.Echo "Font already installed: " & objFile.Name

I want a VBS script to quit/exit/terminate if X file already exists.
Currently, it will instead give a message box saying "Font Already Installed" as expected.
If I remove the Echo I instead get a blank box, where I still have to hit OK.
I want the script to just automatically end if X already exists with 0 user input.
Is this possible? I have wscript.quit and wscript.exit but just get errors.
The full script can be found here:
http://www.cloudtec.ch/blog/tech/install-font-command-line-script-windows-7.html
So again, in context, I want XYZ fonts to install. If they're already installed I want the script to just simply terminate without the need to hit OK. The intention is to deploy fonts accross a network.

A: Try this:
If objFSO.FileExists("C:\Windows\Fonts\" & objFile.Name) Then
  WScript.Quit
End If


text:
Q: Force IOException during file reading I have a piece of code that reads data from a file. I want to force IOException in this code for testing purposes (I want to check if the code throws a correct custom exception in this case).
Is there any way to create a file which is protected from being read, for example? Maybe dealing with some security checks can help?
Please, note that passing the name of a non-existent file cannot help, because FileNotFoundException has a separate catch clause.
Here is the piece of code for better understanding of the question:
    BufferedReader reader = null;
    try {

        reader = new BufferedReader(new FileReader(csvFile));

        String rawLine;
        while ((rawLine = reader.readLine()) != null) {
            // some work is done here
        }

    } catch (FileNotFoundException e) {
        throw new SomeCustomException();
    } catch (IOException e) {
        throw new SomeCustomException();
    } finally {
        // close the input stream
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

A: If you can refactor the code slightly to accept a Reader, rather than a filename, you can use mocks. With EasyMock you can create a mock Reader, and set it to throw IOException upon calling any of its methods you wish. Then you just pass it to the method to be tested, and watch what happens :-)
void readFile(Reader reader) throws SomeCustomException {
    try {
        String rawLine;
        while ((rawLine = reader.readLine()) != null) {
            // some work is done here
        }

    } catch (FileNotFoundException e) {
        throw new SomeCustomException();
    } catch (IOException e) {
        throw new SomeCustomException();
    } finally {
        // close the input stream
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

then the test code:
mockReader = createMock(Reader.class);
expect(mockReader.readLine()).andThrow(
        new IOException("Something terrible happened"));
replay(mockReader);

objectToTest.readFile(reader);

A: You could force an exception by invoking the close method on your BufferedReader:
    reader = new BufferedReader(new FileReader(csvFile));

    // invoke the Close() method.
    reader.Close();

    String rawLine;
    while ((rawLine = reader.readLine()) != null) {
        // some work is done here
    }

I hope that helps.

A: Define in your test an overloaded fileInputStream that throws an exception
FileInputStream s;
try {
    s = new FileInputStream(fileName) {

           @Override
           public int read() throws IOException {
              throw new IOException("Expected as a test");
           }
       };
} catch (FileNotFoundException e) {
   throw new RuntimeException(e.getMessage(), e);
}

A: Late to the party, but I found a way to force an IOException. I am saving/reading a text file using BufferedWriter/Reader and am doing a test that looks like this:
public void testIOException() {
    try {
        int highScore = loadHighScore("/");
        fail("IOException should have been thrown");
    } catch (MissingFileException e) {
        fail("IOException should have been thrown");
    } catch (IOException e) {
        // expected
    }
}

Where "/" is the filename. Inside loadHighScore there's the line:
BufferedWriter bw = new BufferedWriter(new FileWriter(file));

Because my test inputs "file" as "/", it outputs an IOException

A: You could try creating the file as a superuser and then reading it as a standard user.  There should be permissions issues there.  Or just chmod the thing assuming you're on Linux.  You can also try putting it in a hidden / protected directory.

A: You can mock java.nio.file.FileSystem from JDK7. I wrote http://github.com/dernasherbrezon/mockfs specifically for generating IOExceptions during the test.

A: Disclaimer: I have not tested this on a non-Windows platform, so it may have different results on a platform with different file locking characteristics.
If you lock the file beforehand, you can trigger an IOException when something attempts to read from it:
java.io.IOException: The process cannot access the file because another process has locked a portion of the file

This works even if you are in the same thread.
Here's some sample code:
final RandomAccessFile raFile = new RandomAccessFile(csvFile, "rw");
raFile.getChannel().lock();

A: You can use a Mock library like Mockito or Easymock (+classpath) to create a Mock file object (newer libs have classloader extensions that let you mock concrete classes like File), or can cooperate with something like PowerMock (see blog) and have a mock generated for the constructor call, and throw the appropriate exception when called.

A: You can use for example Mockito to emulate that, however you would need to refactor your code so it were better testable. I would also advise to use try-with-resources if you use java 7+. Your code will look much cleaner.
You might extract the reader creation to a separate method so you could then replace an implementation with a mock. Like this
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class SomeClass {

    public static final String IO_EXCEPTION = "IO Exception";
    private String csvFile ="some_path";

    public void someMethod() {
        BufferedReader reader = null;
        try {
            reader = getReader();
            String rawLine;
            while ((rawLine = reader.readLine()) != null) {
                // some work is done here
            }

        } catch (FileNotFoundException e) {
            throw new SomeCustomException("FNF Exception");
        } catch (IOException e) {
            throw new SomeCustomException(IO_EXCEPTION);
        } finally {
            // close the input stream
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    }

    BufferedReader getReader() throws FileNotFoundException {
        return new BufferedReader(new FileReader(csvFile));
    }

    class SomeCustomException extends RuntimeException {

        public SomeCustomException(String message) {
            super(message);
        }
    }
}

The test would look as following
    import static org.assertj.core.api.Assertions.assertThatThrownBy;

import SomeCustomException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;

@RunWith(MockitoJUnitRunner.class)
public class SomeClassTest {

    @Mock
    private BufferedReader bufferedReader;

    @Test
    public void testMethod() throws IOException {
        Mockito.when(bufferedReader.readLine()).thenThrow(new IOException());

        SomeClass someClass = new SomeClass() {
            @Override
            BufferedReader getReader() throws FileNotFoundException {
                return bufferedReader;
            }
        };
        assertThatThrownBy(() -> someClass.someMethod()).isInstanceOf(SomeCustomException.class)
                                                        .hasMessage(SomeClass.IO_EXCEPTION);
    }
}

This is how your someMethod might look like if you use try-with-resource
public void someMethod() {
    try(BufferedReader reader = getReader()) {
        String rawLine;
        while ((rawLine = reader.readLine()) != null) {
            // some work is done here
        }

    } catch (FileNotFoundException e) {
        throw new SomeCustomException("FNF Exception");
    } catch (IOException e) {
        throw new SomeCustomException(IO_EXCEPTION);
    }
}

2 times shorter 20 times more readable
PS as another option for the test, you might extend your SomeClass in the test class and override someMethod in the test class instead of creating an unanimous implementation. But I like the first option more. It is a matter of taste though.
Hope that helps.
PPS: Just realized the question was asked years ago. :) Hopefully it helps somebody to find an answer these days.

A: You could make this exception raise for a file that's too large.

A: I would recommend against using the FileNotFoundException. If you want to throw a specific exception for the file not existing, I would check csvFile.exists().
For example, you can make csvFile a directory. I tested your code and it threw:

File file = new File("actually_a_directory.csv");
file.mkdir();
yourCode(file); // throws FileNotFoundException: "actually_a_directory.csv (Access is denied)"
In my opinion, a file actually being a directory is not the same as FileNotFound, yet it acts the same in java.

A: You can always throw your own IOException:
throw new IOException("Test IOException");


text:
Q: iptables failed with " iptables v1.4.21: Couldn't load match `-d':No such file or directory" message I am running kernel 3.14.18 and using iptables 1.4.21, built with these options --static-enable --disable-shared.
When I run this command:
/sbin/iptables -A PREROUTING  -m -d 127.3.0.2/24 -j DNAT --to-destination 10.0.0.1 -p udp -dport 69

I get this error message:
iptables v1.4.21: Couldn't load match `-d':No such file or directory

Can anyone help explain what I am missing?

A: I know this is an old post, but for others who come across this via searches....
The -m option is to specify a module to load.  Correcting this and the --dport vs -dport mentioned by Augusto you may want.
/sbin/iptables -A PREROUTING -m udp -d 127.3.0.2/24 -j DNAT --to-destination 10.0.0.1 -p udp --dport 69

A: Try --dport instead -dport (missing one -)


text:
Q: Sample database for exercise I would like to play with a larger database to test my knowledge on SQL.
Is there a huge .sql out there that I can use to play with SQL queries?

A: This is an online database but you can try with the stackoverflow database:
https://data.stackexchange.com/stackoverflow/query/new
You also can download its dumps here:
https://archive.org/download/stackexchange

A: You could try the classic MySQL world database.
The world.sql file is available for download here:
http://dev.mysql.com/doc/index-other.html
Just scroll down to Example Databases and you will find it.

A: Check out CodePlex for Microsoft SQL Server Community Projects & Samples
3rd party edit
On top of the link above you might look at

*

*microsoft sql server samples on github

*the msft db product samples on codeplex

*the new Wide World Importers sample database inludes OLTP and an OLAP for sql server 2016 and later

A: Why not download the English Wikipedia? There are compressed SQL files of various sizes, and it should certainly be large enough for you
The main articles are XML, so inserting them into the db is a bit more of a problem, but you might find there are other files there that suit you. For example, the inter-page links SQL file is 2.3GB compressed. Have a look at https://en.wikipedia.org/wiki/Wikipedia:Database_download for more info.
Oskar

A: This is what I am using for learning sql: employees-db

this is a sample database with an integrated test suite, used to test
  your applications and database servers

3rd party edit
According to launchpad.net the database has moved to github.

The database contains about 300,000 employee records with 2.8 million
  salary entries. The export data is 167 MB, which is not huge, but
  heavy enough to be non-trivial for testing.
The data was generated, and as such there are inconsistencies and
  subtle problems. Rather than removing them, we decided to leave the
  contents untouched, and use these issues as data cleaning exercises.

A: If you want a big database of real data to play with, you could sign up for the Netflix Prize contest and get access to their data, which is pretty large (a few gigs of entries).
3rd party edit
The URL above does not contain the dataset anylonger (october 2016). The wikipedia page about the Netflix Prize reports that a law suit was settled regarding privacy concerns.

A: You want huge?
Here's a small table: create table foo (id int not null primary key auto_increment, crap char(2000));
insert into foo(crap) values ('');
-- each time you run the next line, the number of rows in foo doubles.
insert into foo( crap ) select * from foo;
run it twenty more times, you have over a million rows to play with.
Yes, if he's looking for looks of relations to navigate, this is not the answer. But if by huge he  means to test performance and his ability to optimize, this will do it. I did exactly this (and then updated with random values) to test an potential answer I had for another question. (And didn't answer it, because I couldn't come up with better performance than what that asker had.)
Had he asked for "complex", I'd have gien a differnt answer. To me,"huge" implies "lots of rows".
Because you don't need huge to play with tables and relations. Consider a table, by itself, with no nullable columns. How many different kinds of rows can there be? Only one, as all columns must have some value as none can be null.
Every nullable column multiples by two the number of different kinds of rows possible: a row where that column is null, an row where it isn't null.
Now consider the table, not in isolation. Consider a table that is a child table: for every child that has an FK to the parent, that, is a many-to-one, there can be 0, 1 or many children. So we multiply by three times the count we got in the previous step (no rows for zero, one for exactly one, two rows for many). For any grandparent to which the parent is a many, another three.
For many-to-many relations, we can have have no relation, a one-to-one, a one-to-many, many-to-one, or a many-to-many. So for each many-to-many we can reach in a graph from the table, we multiply the rows by nine -- or just like two one-to manys. If the many-to-many also has data, we multiply by the nullability number.
Tables that we can't reach in our graph -- those that we have no direct or indirect FK to, don't multiply the rows in our table.
By recursively multiplying the each table we can reach, we can come up with the number of rows needed to provide one of each "kind", and we need no more than those to test every possible relation in our schema. And we're nowhere near huge.


text:
Q: finding server uptime from another server using powershell I want to find the server up time of other servers using powershell command from one server. I am using below command to query the other server but could not get the required result.
$lastboottime = (Get-WMIObject -Class Win32_OperatingSystem -ComputerName $server -Credential $altcreds -ErrorAction SilentlyContinue).LastBootUpTime
Write-Host $lastboottime

Can someone share the best way to find the other servers uptime. Is there any way in sqlserver or sqlserver stored procedure

A: You need to convert it to a valid Datetime object, use the ConvertToDateTime method...
$WMI = (Get-WMIObject -Class Win32_OperatingSystem -ComputerName $server -Credential $altcreds -ErrorAction SilentlyContinue)
[datetime]::Now - ($WMI.ConvertToDateTime($WMI.LastBootUpTime))

If you just need the date:
$WMI.ConvertToDateTime($WMI.LastBootUpTime)


text:
Q: Custom fields in Laravel scoping I have an eloquent model with a relationship and a scope for that relationship
<?php

namespace App;
...

class Shift extends Model
{
    public function profession()
    {
        return $this->hasOne(Profession::class, 'id', 'profession');
    }
    ...
    public function scopeWithProfession($query)
    {
        $query->with('profession');
    }
...
}

Then, in my controller, I just call this scope as follows, and it gives me the fields in the professions table:
public function show(Shift $shift)
{
    return Shift::where('id', $shift->id)->withProfession()->first();
}

Now, my profession item has a self-referencing foreign key that assigns an optional parent object to a profession instance
Schema::create('professions', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('color');
        $table->unsignedBigInteger('parent_id')->nullable();
        $table->timestamps();

        $table->foreign('parent_id')
            ->references('id')
            ->on('professions');
    });

What I want to achieve, is in the call to the withProfession scope, I also want to return a field that references the name of the parent object as an extra to the normal fields in the profession table. This means I essentially need to "add" a custom field to the withProfession scope. How do I do this?

A: there is a simple solution but it load the whole parent:
the base idea is to define a parentProfession relation in Profession Model
then load it in with inside your scope ...
class Profession extends Model
{
    public function parentProfession()
    {
        return $this->hasOne(Profession::class, 'parent_id');
    }

}

class Shift extends Model
{
    public function profession()
    {
        return $this->hasOne(Profession::class, 'id', 'profession');
    }
    ...
    public function scopeWithProfession($query)
    {
        $query->with('profession.parentProfession');
    }
...
}

this should load the Profession with it's parent ...
if you has to get only the name, then you have to a chain of join with 'addSelect'


text:
Q: 2 models in a single view with if condition I have problem with how to and where to add if condition in view which has two models in a single view.
This is view
@foreach (service_provider SP in ViewBag.service_provider) {

        @SP.Sp_email
        @SP.Sp_name
        @SP.city.Cityname

}@foreach (picture img in ViewBag.pictures){

}

This is picture model
public int PIC_ID { get; set; }
public string pic_name { get; set; }
public Nullable<int> belong_id { get; set; }
public byte[] pic { get; set; }

This is  service_provider model
public int SPID { get; set; }
public string Sp_email { get; set; }
public string Sp_password { get; set; }
public string Sp_name { get; set; }

This is my controller
public ActionResult Index(){
    ViewBag.service_provider = dc.service_provider;
    ViewBag.pictures = dc.pictures;
    return View();
}

The purpose of the above view is to display details of the service_provider with it's picture by where belong_id in picture equals SPID in service_provider. but I couldn't understand where do I add if condition.I'm using Database first approach

A: It would be much easier if you used a strongly typed model instead of the ViewBag. You can then add logic to your model or your controller. I personally it easier read and test. It also prevents syntax errors.
Models.cs
public class Picture {
    public int PIC_ID { get; set; }
    public string pic_name { get; set; }
    public Nullable<int> belong_id { get; set; }
    public byte[] pic { get; set; }

    // added - your FK pointing back to the corresponding service_provider
    public int SPID { get; set; }
    // added - the corresponding service_provider
    public service_provider ServiceProvider { get; set; }
}

public class service_provider {
    public int SPID { get; set; }
    public string Sp_email { get; set; }
    public string Sp_password { get; set; }
    public string Sp_name { get; set; }

    // added
    public ICollection<Picture> Pictures {get;set;}
}

Controller.cs
public ActionResult Index(){
    var service_provider = dc.service_provider.Inculde(x => x.Pictures);
    // var pictures = dc.pictures;

    // code to add the pictures to the correct service_provider instance
    // ideally this should already be reflected in your model.
    // If you are using EF you should be modeling this using proper data relations
    // that would allow you to execute an .Include statement on the retrieval
    // and pass the model directly into the View without the need for an additional call to pictures as the service_provider would then already contain the relations
    return View(service_provider);
}

View.cshtml
@model IEnumerable<service_provider>
@*This following line indicates that it is a list of service_provider hense the IEnumerable*@
@foreach (service_provider SP in Model){

        @SP.Sp_email
        @SP.Sp_name
        @SP.city.Cityname

    @*Iterate over the pictures on each model.
    You can still split this if you want all service providers and then all pictures.*@
    @foreach (picture img in SP.Pictures){ @*changed to still look at the model*@

    }
}

A: Try:
@foreach (picture img in ViewBag.pictures)
{
     if(img.PIC_ID == ViewBag.service_provider.SPID)
{

}
}

BTW - Maybe better way - is check in server side and return ONLY pics that you need??


text:
Q: Default value for missing attributes in xpath expression I'm retrieving with cURL an XML that get parsed with libxml2 and xpath. Results (keyword) fill my 2D array (myarray). It works great!
But the XML I get (current weather data for a specified City based on openweathermap.org), depending on weather condition, have sometimes missing attributes:
Ex.
If sky is clear XML is like:
<current>
<city id="4219762" name="Rome">
<coord lon="-85.164673" lat="34.257038"/>
<country>US</country>
<sun rise="2013-06-18T10:28:40" set="2013-06-19T00:55:19"/>
</city>
<temperature value="21.59" min="21" max="22" unit="celsius"/>
<humidity value="88" unit="%"/>
<pressure value="1014" unit="hPa"/>
<wind>
<speed value="1.03" name="Calm"/>
<direction value="87.001" code="E" name="East"/>
</wind>
<clouds value="75" name="broken clouds"/>
<precipitation mode="no"/>
<weather number="701" value="mist" icon="50n"/>
<lastupdate value="2013-06-18T05:35:00"/>
</current>

while if it's rainy is like:
//same as above
<precipitation value="0.125" mode="rain" unit="3h"/>
//same as above

The problem is that in the first case myarray get 9 lines:
id: 0 string: 3171168
id: 1 string: Pescara
id: 2 string: IT
id: 3 string: 24.646
id: 4 string: 92
id: 5 string: 5.7
id: 6 string: Moderate breeze
id: 7 string: no
id: 8 string: Sky is Clear

while in the second get 10 lines:
id: 0 string: 3171168
id: 1 string: Pescara
id: 2 string: IT
id: 3 string: 24.646
id: 4 string: 92
id: 5 string: 5.7
id: 6 string: Moderate breeze
id: 7 string: 0.125
id: 8 string: rain
id: 9 string: broken clouds

so when I print myarray in main function
printf("Cloudiness:%s",myarray[8]);

if sky is clear i get correct vuales, but if it's rainy I get inconsistent data (cause now Cloudiness is in line 9). The same behavior could be applied if other nodes/attributes are missing for some specific server side issues.
Is there a way to specific a default value (Ex. N/A) for missing nodes/attributes so myarray get always consistent data (and lines get respectively the same type of information)? Have someone had the same issue? Is there a workaround?
Thanks for helping,
Best,
Giovanni.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>

    struct MemoryStruct {
    char *memory;
    size_t size;
};

    static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    struct MemoryStruct *mem = (struct MemoryStruct *)userp;
    mem->memory = realloc(mem->memory, mem->size + realsize + 1);
    if (mem->memory == NULL) {  /* out of memory! */
        printf("not enough memory (realloc returned NULL)\n");
        exit(EXIT_FAILURE); }
    memcpy(&(mem->memory[mem->size]), contents, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;
    return realsize;
}

    xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath) {
    xmlXPathContextPtr context;
    xmlXPathObjectPtr result;
    context = xmlXPathNewContext(doc);
    if (context == NULL) {
        printf("Error in xmlXPathNewContext\n");
        return NULL;    }
    result = xmlXPathEvalExpression(xpath, context);
    xmlXPathFreeContext(context);
    if (result == NULL) {
        printf("Error in xmlXPathEvalExpression\n");
        return NULL;    }
    if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
        xmlXPathFreeObject(result);
        printf("No result\n");
        return NULL;    }
    return result;
}

    int xmlretrive(char* myurl, char* myxpath, char*** myarray) {
    CURL *curl_handle;
    xmlDocPtr doc;
    xmlChar *xpath = (xmlChar*) myxpath;
    xmlNodeSetPtr nodeset;
    xmlXPathObjectPtr result;
    int i;
    xmlChar *keyword;
    struct MemoryStruct chunk;
    chunk.memory = malloc(1);
    chunk.size = 0;
    curl_global_init(CURL_GLOBAL_ALL);
    curl_handle = curl_easy_init();
    curl_easy_setopt(curl_handle, CURLOPT_URL, myurl);
    curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
    curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
    curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
    curl_easy_perform(curl_handle);
    curl_easy_cleanup(curl_handle);
        //printf("%s\n", chunk.memory);
    doc = xmlParseDoc(chunk.memory);
    if (doc == NULL ) {
            fprintf(stderr,"Document not parsed successfully. \n");
            return NULL;    }
    result = getnodeset (doc, xpath);
    if (result) {
        nodeset = result->nodesetval;
        *myarray = malloc((nodeset->nodeNr + 1) * sizeof(*myarray));
        for (i=0; i < nodeset->nodeNr; i++) {
            keyword = xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode, 1);
            (*myarray)[i] = malloc(strlen(keyword)+1);
            if ((*myarray)[i] == NULL) {
            // out of memory.  print error msg then exit
            }
            strcpy((*myarray)[i], keyword);
            xmlFree(keyword);
        }
        xmlXPathFreeObject (result);
    }
    xmlFreeDoc(doc);
    xmlCleanupParser();
    if(chunk.memory)
    free(chunk.memory);
    curl_global_cleanup();
    return i-1;
}

    int main(void)  {
char thisxpath[300];
char thisurl[200];
char** myarray = NULL;
char output[900] = "";
int arr_rows;
strcpy (thisurl,"http://api.openweathermap.org/data/2.5/weather?q=Rome&mode=xml&units=metric");
strcpy (thisxpath,"//city/@*[name()='name' or name()='id'] | //country | //weather/@value | //temperature/@value | //precipitation/@*[name()='value' or name()='mode'] | //humidity/@value | //speed/@*[name()='name' or name()='value']");
arr_rows = xmlretrive (thisurl, thisxpath, &myarray);

    // for cycle to print myarray with some great layout

free(myarray);
return 0;
}

A: If you were using XPath 2.0 the following construction would work:
(/precipitation/@value, "NA")[1]

However, since you're using libxml2, I believe you're stuck with XPath 1, in which that won't work.
In either case, I'd suggest a different approach. Rather than using one big complex XPath to select a bunch of nodes and then assuming that the ones you care about will be both present exactly once and in the right order, I'd put the logic into c code. Loop over the nodes you're interested in and make one call to getnodeset() for each with a specific XPath. Then you can investigate the return value to determine whether the value is there or not and insert either that value, or some placeholder into your array at the desired location.
The way I'd do it would be to put the individual XPath expressions into an array and loop over it; then simply use the index in the XPath array as the index in the output array; that way the output values are always in a predictable location, but without the c code needing to know anything about the actual XPath, or what values are going where.


text:
Q: iframe cross-domain access I have an HTML page with an iframe included from a cross domain that doesn't belong to me.
I need to do some basic javascript modifications in the iframe (write value and fire up an event -> form processing).
Because of the same origin policy I'm not allowed to do this. However, I need to do it, so I'm searching for a workaround.
The solution is just important that I can run a script for myself. It is enough if it works in one browser and I don't need security for myself.
On my research I have found a lot of ways to break the same origin policy like document.location (in FF only with similar locations), JSONP/sendMessage (I need to be the owner of both domains) and so on, nothing that works with an iframe of a page that doesn't belong to me.

A: The only "workaround", if you can't make the other site include the relevant CORS headers, would be to fetch the iframe content server side and serve it as coming from your own domain.
The reason there isn't simpler workaround is due to why there is this same origin policy : to protect users.


text:
Q: How do I write a synchronous function with parameters as an asynchronous function (Javascript)? Suppose I have the following code:
Synchronous Version:
    var waitingToGetValue = heavyProcessingFunc (para1, para2);
    response.send(waitingToGetValue);

I tried looking around but all I got were functions without parameter.
Asynchronous Attempt:
    heavyProcessingFunc(para1, para2, (function(waitingToGetValue){
       response.send(waitingToGetValue);
    });

I need to send the two parameters to the function. The function returns a value that I need to use to then send it to the response.
Does it even matter if I put it in a asynchronous format? Can anyone recommend me a video/source that easily explains the difference synchronous vs asynchronous: I read many material for the past few days and it just keep getting more confusing with promises, callbacks, and trying to access the values outside those functions.

A:

    function heavyProcessingFunc(para1, para2, callback){
     console.log('We have two params to work with', para1, para2);
     setTimeout(function(){// Simulating a long request
      callback("Now we send the response by calling the callback"); // This is waitingToGetValue
     },3000);
    }

    heavyProcessingFunc("para1", "para2", function(waitingToGetValue){
       console.log(waitingToGetValue);
       // response.send(waitingToGetValue);
    });


text:
Q: What is the correlation between ECMAScript 5 and JavaScript 1.8.5 in terms of language features? I've been reading up on Mozilla's continuing development of JavaScript, up through version 1.8.5: https://developer.mozilla.org/en/JavaScript.
My question is: What is the correlation between JavaScript 1.8.5+ and ECMAScript 5+ in terms of language features? Any chance Mozilla's new JavaScript features (like generators, array comprehensions, etc.) will become part of ECMAScript?
I just want to get a handle on whether it's worth learning JavaScript 1.8.5 features (and working to shim them into non-supporting browsers) or whether I should forget JS 1.8.5 and focus on learning/shimming the new ECMAScript 5 features.
FYI: Mozilla talks about how they're planning to bring JavaScript into compliance with ECMAScript 5 here: https://developer.mozilla.org/En/JavaScript/ECMAScript_5_support_in_Mozilla

A: Defiantly focus on ES5. The issue with 1.7 & 1.8 features is that they change the syntax of the language so you can't shim them into other code.
You can emulate all the properties of the Object with ES5 but you can't emulate the let keyword. In other browsers the various expression are just not valid javascript.
You must distinquish between making addition to native code which is what most of ES5 is doing and changing the syntax of javascript which is what 1.7 & 1.8 are doing.
There is a use for 1.7 & 1.8 which is to develop for the RHINO platform. But for browser javascript stick to the spec.
Admittedly the multiple value returns is a pretty neat feature. Having an array assignment like that would be nice
function() f {
     return [1,2,3];
}

[a,b,c] = f()

But the other features are quite major changes to the syntax and you just can't push them through ecmascript they just won't deal with it. Small changes like above you might be able to get into ES6 but your going to have to wait at least a year.
So realistically don't expect the learning to pay off for a year or two if at all. Most likely it won't pay off. Do look at libraries such as underscore.js which can define common functional utility methods for you.

A: JavaScript 1.8.5 is Mozilla's implementation of ECMAScript with added features. It's a superset of the ECMAScript specification (and of current implementations like IE, Chrome and Opera). Mozilla pushes for the features it adds to its own browser, they may or may not make it into ECMA. Note that Mozilla is a member of the W3C and has some say, but my guess is that most features won't make it.
Bottom Line Don't use it unless you're coding something specific to firefox, FF extensions, XUL apps, Rhino (Added Rhino thanks to @Raynos)

A: I think ECMAScript is the "standard", like a blueprint, and javascript is the actual language it is based off of.  Kind of like how w3c has their standards and then people make (or don't) make rendering engines based off it.
So basically to answer your question, look at ECMAScript to see what the consensus is, how javascript is "supposed" to work, but you should focus on javascript, because that's what you will actually be coding with.