text:
Q: Vue CLI minifies for production, but how can properties and other definitions also be shortened? I looked at an output file (e.g. app.4a7888d9.js) that the Vue CLI generated to see what actually got reduced and I saw that properties declared in the 'data' object, methods declared in the methods object, etc. retain their original name. Same with Vuex state properties.
I'm not trying to obfuscate my code entirely but I do use rather long descriptive names which could benefit of minification. Please don't hate, but an example of a worst case scenario of a property name I have is scheduledTransactionConditionActiveComponent
Is there a better way to achieve minification besides what the cli does by default ? If I should use a different package for this, is there one that's proven for vue?

A: Vue CLI uses terser-webpack-plugin for minification, and property mangling is disabled by default. You could enable it in your Vue config as follows:
// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.optimization.minimizer('terser').tap(args => {
      const opts = args[0]

      opts.terserOptions.mangle = {
        ...opts.terserOptions.mangle,
        properties: true, // mangle all property names
      }

      return args
    })
  }
}

The Terser docs also recommend selective property mangling (e.g., by only applying it to names that match a regexp). For example, you could configure Terser to only mangle properties that end with an underscore:
// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.optimization.minimizer('terser').tap(args => {
      const opts = args[0]

      opts.terserOptions.mangle = {
        ...opts.terserOptions.mangle,
        properties: {
          regex: /_$/, // mangle property names that end with "_"
        },
      }

      return args
    })
  }
}

Note: Although this works well for data props, this mangling does not work for component names (i.e., property names under components).


text:
Q: I have a table similar to the following .i want the individual count of the different status available Table Data
id |name     | status         |location
----------------------------------
 1 |ABCD     |completed       | Delhi
 2 |QWER     |construction    | Mumbai
 3 |RBVF     |To_launch       | Chennai
 4 |POIU     |ready           | Kolkata
 5 |WABCD    |completed       | Delhi
 6 |RQWER    |construction    | Mumbai
 7 |TRBVF    |To_launch       | Chennai
 8 |UPOIU     |ready           | Kolkata
 9 |RBVF      |To_launch       | Chennai
 10|POIU      |ready           | Kolkata
 11|WABCD     |completed       | Delhi

lets say my output should be like
construction status      count
completed                  4
To_launch                  3
ready                      3
construction               2

I have tried something like
select d.status, count(d.status)
from data d
where d.status = 'completed'

but i want all status results to come in a single Query.But iam unable to figure it out.TIA..Please do suggest to improve myself in SQL.

A: use aggregate function count  and group by clause
   select status as `construction status` ,count(*)as Cnt from Yourtable
    group by status

below query also shows total as wanted in your comment
   select status as `construction status`, count(*) as count, total from
   Yourtable,(select count(*) as total from Yourtable) t2
   group by status

http://www.sqlfiddle.com/#!9/8abcce/4

redpajama_set_name: RedPajamaStackExchange


text:
Q: Admin On Rest show Custom Message from server after update After updating a row, I want to show the custom message to the user.
I'm using this code: https://github.com/marmelab/admin-on-rest-demo/blob/master/src/reviews/ApproveButton.js
Admin-on-rest use Material-UI Snackbars to show Message. How can I use this to show Custom Message from Server after an update?

A: If you're also using a custom saga to handle your actions, you can dispatch a notification using the showNotification action creator.
See the reviewSaga which works with this ApproveButton at https://github.com/marmelab/admin-on-rest-demo/blob/master/src/reviews/reviewSaga.js


text:
Q: Generating a sine wave over a big frequency range I want to build a circuit that can generate sine waves at frequencies controlled by a computer or a microcontroller. I would like to go as low as 0.01 Hz (down to 0.05 Hz would probably be acceptable) and as high as 100 kHz; I need at least 10 frequencies per decade, which is a resolution of roughly 12 mHz at the bottom of the scale (or 60 mHz if the bottom is 0.05 Hz). The output voltage doesn't need to be high - I'm going to run it through some op-amps afterwards anyways.
What is the standard way of doing this? Is DDS the way to go (using either a sine lookup table on a uC or an IC like the AD9850)? Is there a simple analog solution that I'm missing?
I would love to stick to through-hole parts if I can.

A: You could easily do a highly flexible DDS on an STM32F4 Discovery board for ~$15 using an internal DAC, DMA, a timer and a sine lookup table.  People have blogged examples of similar things if you look for them.
In order to get the required frequency (the STM32F4xx DAC's can only do 300ksps at full swing, which equates to ~1V/\$\mu\$s) you will need to constrain the range of the DAC.
For a sinusoid, maximum slew rate (in V/s) is \$2 \pi \times f \times A\$.
Inserting the values from the OP's requirements and assuming Vref of the DAC is 3.3V (which if I recall correctly is the case for an STM32F4Disco), a 3.3Vpp sine wave at 100kHz, max slew rate is \$2 \pi \times 10^5 \times 3.3 / 2 = 1036726\$V/s, or \$\approx1.04\$V/\$\mu\$s.
In order to comply with this constraint, the sine wave's amplitude has to be limited, from \$3.3\$V to \$3.3 \times 1 / 1.04 = 3.18\$V.
This now brings in the apparent issue of the 300ksps limit on the STM32F4 DAC.  That limit is a furphy.  I don't know what the actual physical upper limit is, but I suspect it's the APB1 bus speed.  I do know (because I've done it) that you can write at least 2Msps to the DAC and as long as you respect the 1V/us slew rate it will behave predictably.  So, you can do 16 samples per cycle for a 100kHz sine wave, a 1.6Msps update rate, as long as you limit the sine wave amplitude to 3.18V instead of 3.3V.
At some point you're probably going to have to deal with digital pots because the reality is that if you want a smooth, continuous output signal, particularly at low speed, then you're going to have to run your DDS through a filter, and that filter is going to have to be adjustable - you can't just put a 100kHz LPF on it and expect it to be useful at sub-1Hz frequencies.

A: Here's my (RF's) rough summary of the DDS solution, which was initially suggested by Nick Alexeev. I'm marking this as community wiki, so feel free to improve with details etc.
Using AD's calculator, in order to get the desired balance between the 12mHz frequency resolution (which I'll just round to 10mHz) and a resnoably smooth curve at 100KHz output, you need about 10 to 40Mhz DDS clock, with 20Mhz looking like a good middle ground. At lower than 10Mhz clock, the output of the DDS at 100KHz starts to look quite noisy. At higher than 40Mhz clocks, the resolution gets too coarse; at 40Mhz clock you get a little less than 0.01Hz change for every tuning bit, in the low range of course; the tuning word being a clock divider, it produces a non-linear frequency curve.
As for practical solutions, one can find DDS chips already mounted on Arduino-compatible shields (for around $5 it seems); the catch however is that they may come with a fixed (and possibly unsuitably high) clock, but that can be improved upon with some board rework.
Also worth mentioning is that if one is using a microcontroller (uC) that has a built-in and sufficiently speedy DAC, then adding a DDS (which is basically an ASIC sweeping a sine lookup table and sending that indexed value to a DAC) is rather pointless since the sine lookup can be implemented in the uC software. For more details on this integrated-DAC approach see markt's answer.

A: I've used a design for a non-digital oscillator that produced decent sines down to below 0.1Hz and to above 100kHz. Theoretically it was an LC parallel tuned circuit in the feedback path of an amplifier. The L and the C were actually precision gyrator circuits (which is why they were able to be tuned to such ridiculously low resonant frequencies). You'd never build one with real inductors and if you did it would be non-tunable.
Both "C" and "L" were kept tracking by using a precision dual-gang pot and, if I remember correctly, a frequency range of over 50:1 could be got from the pot before changing fixed capacitors in the gyrators.
The pots of course would be better served by digipots these days as these can "track" much better than regular pots. I'm sure with care, it could work down to 0.01Hz.
Inductor gyrator: -

There are higher quality gyrators (better frequency response) and here's another link to a document about a different sort of gyrator. The beauty of the single op-amp gyrator in this application is that the CR network (as normally intended to be parasitic) can be used effectively as the tuning section making the L and C in parallel via small series resistors.

A: One approach would be to clock a 28bit adder/accumulator with a 4 Mhz clock.
A uController driving the low order 20bits with a digital word and the top eight bits feed addresses to an eprom for a 256 entry sine look up table. The data bits from the eprom summed into an R2R ladder would capacitively couple to your op amp gain stage.
Drive a high value from the micro into the adder and the high order bits cycle faster, for a higher frequency sine wave. A low value takes a lot more clock cycle to step make a count occur in the top eight bits driving the eprom.
With a little extra work in the micro software; you can make the eprom table smaller by just storing angles from 0degress through 90. Just read the table forwards for the first 90 degrees (quadrant 1) then backwards for quadrant 2 forward again for quadrant three etc.


text:
Q: How to pass json data to ui autocomplete Can anyone help me with this issue. I use jquery UI autocomplete plugin. Is there a way to pass json data like this

[{'username' : 'user1}, {'username' :
  'user2}, {'username' : 'user3}]

A: You'll need to create an array of usernames. With jQuery, you could do the following:
var jsonData = [{'username' : 'user1'}, {'username' : 'user2'}, {'username' : 'user3'}];
var usernames = $.map(jsonData, function (obj) { return obj.username; });

$("#myInput").autocomplete({source: usernames});

A: Surely the documentation for the plugin must state something about this, however your question is vague at best. Which plugin are you using? Does it have any service methods to put data into?

A: Check out the source option in the Documentation. It can be a local JavaScript array.


text:
Q: Overriding RaisePropertyChanged to execute additional code In my model i have properties which i want to execute some extra code for when the property gets changed. I want to add the new value and the property name to my database. I also want to keep a list of current alarms (value is equal to true).
    public Boolean ActionAlarmLowLow
    {
        get
        {
            return _ActionAlarmLowLow;
        }
        set
        {
            if (value != this._ActionAlarmLowLow)
            {
                Boolean oldValue = _ActionAlarmLowLow;
                _ActionAlarmLowLow = value;
                RaisePropertyChanged("ActionAlarmLowLow", oldValue, value, true);
            }
        }
    }

How can i do this properly?
I am wondering if i should add two lines of code to the property:
DB.Log.addLogItem("ActionAlarmLowLow", value);
AlarmList.UpdateItem("ActionAlarmLowLow", value);

Or if i can somehow extend/override the RaisePropertyChanged and do some extra stuff elsewhere for specific properties. I.e calling something called
RaisePropertyChangedWriteToDbUpdateAlarmList();`

A: Yes it is quite simple, all you need is to create a base class with INotifyPropertyChanged and call whatever you want inside.
public abstract class NotifyPropertyChangedBase: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged<T>(Expression<Func<T>> expression)
    {
        var memberExpression = (MemberExpression) expression.Body;
        var propertyName = memberExpression.Member.Name;

        var handler = PropertyChanged;
        if (handler != null)
        {
            // Do your common actions here, before property change notification is fired
            handler(this, new PropertyChangedEventArgs(propertyName));
            // Do your common actions here, after property change notification is fired
        }
    }
}

public class MyClass : NotifyPropertyChangedBase
{
    public Boolean ActionAlarmLowLow
    {
       get
       {
           return _ActionAlarmLowLow;
       }
       set
       {
           if (value != this._ActionAlarmLowLow)
           {
               _ActionAlarmLowLow = value;
               OnPropertyChanged(() => this.ActionAlarmLowLow);
           }
       }
   }
}


text:
Q: Annulments in Westeros: What are the laws for annulment and could Robb have his marriage annulled? Update S07E05: Thank you Gilly! Haha

Westeros has annulments right? It's a pretty theocratic place so I guess there's no distinction of legal vs sept.
I mean what's the law with the old gods? The seven? The red god? The Many faced god?
Of course most got marriages are de jure invalid because they're done politically but they're de facto valid. But what about something that's not political? I would think it's also invalid de facto.
Let's take for example someone who could've really benefited from an annulment: Robb Stark. In the books it seems like Robb Stark could get an annulment since he married a girl after having sex with her out of grief.
Could he have his marriage annulled?
If so, why didn't he?
If not, why?
In the show, could Robb Stark have made up some dumb excuse* to annul his marriage for the sake of re-forming an alliance with the Freys?
If so, is it that if he could he didn't want to?
If not, why?

*Actually I think even in modern society there are grounds for annulment.

A: NOTE: This is valid for books only. In the Show, as of Season 7, annulments can be granted regardless to consummation.

Annulments in other faiths
We do not know anything about how annulments work with adherents of Red God, Drowned God, Many Faced God and Old Gods. There is not a single mention of an annulment in followers of those faiths. So the answer, with a heavy heart, would be we do not know yet.
Are Political marriages "De jure" invalid?
Also your assumption that most weddings in Westeros are de-jure invalid because of political nature is wrong. There have been plenty of political marriages in real world as well and none of them are considered "de-jure invalid".
It does not matter whether a marriage is political or not, if both parties said their vows, their marriage is de-jure and de-facto valid and binding.
As evident from your comments, you seem to be viewing Westerosi weddings in light of modern day real world. Marriage of convenience is an idea of modern world and the laws against it are targetted mostly to avoid immigration frauds. In Westeros, most High-born marriages are performed to gain some sort of advantage and there is absolutely no concept of a "Marriage of convenience" in Planetos or any law which declares them invalid. That's your personal idea which has and should not have any impact on the world set in A song of ice and fire.
To clarify, De jure does not mean "Legal according to laws of USA or Italy". De Jure means "Legal according to laws of the land/World concerned". Since there is no law against political marriages in Westeros, They are most definitely valid. I am surprised this actually requires logical proof but think of this logically.
How can something be invalid by law if there is no law making it invalid?
Faith of the Seven
We know of only one faith whose method of annulment is described in canon sources. That's faith of the Seven.
Weddings can be annulled by High Septon or a council of faith if:

*

*Wedding has not been consummated

*At least one party petitions the High Septon or council to annul their marriage. Example would be King Baelor's annulment of his marriage to Daena the Defiant.

As GRRM said:

Tigers14: btw, can a marriage be annulled without both parties
present? and without sansa revealing who she really is?
GRRM: no one needs to be present to annul a marriage
Tigers14: how?
GRRM: but Sansa would need to request it
Tigers14: as sansa?
GRRM: Well, why would a High Septon consider a request from anyone
but the parties involved?

Weddings can also be annulled if:

*

*Wife joins Silent Sisters. Example would be how Ser Quentyn Ball sent his wife to Silent Sisters so that Ball could be eligible for celibate criteria of King's Guard.

*One or both parties were coerced into marriage at sword point as vows sworn on sword-point are considered invalid.

Case of Robb
In Robb's Wedding, Robb followed the old gods while his wife Jeyne Westerling followed the faith of Seven.
As GRRM confirmed that Sansa can petition to High Septon for annulment of her marriage to Tyrion despite following the Old Gods herself, it appears that if one party adheres to faith of Seven (Tyrion did), both parties reserve the right to petition the High Septon to annul the Wedding provided it has not been consummated.
So in theory, Robb could appeal to High Septon for annulment if he had not consummated the marriage.
Then you wonder, why didn't he? Because:

*

*He did not want to. He was apparently head over heels in love with Jeyne Westerling and had absolutely no desire of leaving her.

*He was also too honorable to leave a woman with a bastard/shame of sex outside wedlock.

*He had consummated his marriage numerous times and thus was not eligible to apply.

He sought to rebuild his Frey alliance by offering them hand of his uncle rather than petitioning for an annulment. In any case, Robb's broken betrothal was not the sole cause of Red Wedding. By then, He had lost the North, his heirs and Karstarks. His fate was sealed and Lord Frey did not want to be on the losing side.

A: This doesn't entirely answer the question, but addresses the background: that if Robb could get an annulment, that would appease Walder Frey.
Wrong.
Robb's betrothal to Walder Frey's daughter isn't like a modern decision by two people to marry for the sake of being married. (In fact, it was never even decided who, exactly, Robb would marry, just that it would be a daughter chosen at a later date.) It's a political union: Walder allows Robb to cross the river with his army, and Robb joins their two houses. Having crossed the river, Robb is honor-bound to keep his end of the bargain.
When Robb marries Jeyne Westerling, that is a huge affront to Walder Frey. It's basically a public announcement that Robb lied to Walder just to get what he wanted. It isn' Robb's continuing marriage to Jeyne that insults Walder, it's the fact that he married her in the first place.
Let's say that, for any reason whatsover, his marriage ended: annullment, divorce, death, whatever. Perhaps now Robb goes to the Twins not for his uncle Edmure's wedding, but for his own to Walder's daughter, now that he is available again.
The same thing probably happens: Walder kills Robb for the slight to his honor, although it's possible he does so before Robb is actually his son-in-law. Murdering your guests is one thing; murdering your kin might be a line even Walder Frey avoids crossing if possible. But either way, Walder has his revenge against Robb and House Stark.


text:
Q: Laravel 4: Eloquent::find() doesn't work So I have a simple, empty Eloquent class: class Worker extends Eloquent {}.
Then in the controller I write: Worker::find(1); and I get an exception, saying that the SQL is incorrect:
select * where `id` = ?

Obviously, the from SQL clause is missing.
Oh, I downloaded the Laravel 4 for this app today.

A: In Laravel 4 you have to set a table property
protected $table = 'foo';

A: As already mentioned, you have to specifically set a $table property on the model. Taylor has mentioned here that the old way of doing things (a default table name as the plural of the model's name) may be returning. There just isn't a good composer package for pluralising, so the L3 code may be ported.


text:
Q: Output python into python-readable format We're using a python based application which reads a configuration file containing a couple of arrays:
Example layout of config file:
array1 = [
'bob',
'sue',
'jayne'
]

Currently changes to the configuration are done by hand, but I've written a little interface to streamline the process (mainly to avoid errors).
It currently reads in the existing configuration, using a simple "import". However what I'm not sure how to do, is get my script to write it's output in valid python, so that the main application can read it again.
How can I can dump the array back into the file, but in valid python?
Cheers!

A: I'd suggest JSON or YAML (Less verbose than JSON) for configuration files. That way, the configuration file becomes more readable for the less pythonate ;) It's also easier to throw adequate errors, e.g. if the configuration is incomplete.
To save python objects you can always use pickle.

A: Generally using repr() will create a string that can be re-avaluated. But pprint does a little nicer output.
from pprint import pprint

outf.write("array1 = "); pprint(array1, outf)

A: repr(array1) (and write that into the file) would be a very simple solution, but it should work here.


text:
Q: How can I store different tuples in a list using Python? My code is given below. What I want to accomplish is to add different arrays to my dictionary if score is higher or equals to the best score. For example: [(0.0001, 0.001, "linear"), (1.0, 1.0, "rbf")] etc.
C= [0.0001, 0.001, 0.01,0.1, 1.0, 10.0, 100.0, 1000.0]
gamma=[0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0]
kernel= ["linear","rbf"]
best_score = 0.0
best_C =0.0
best_gamma = 0.0
best_kernel = ""
parameters = {}

for i in C:
    for j in gamma:
        for k in kernel:
            clf = SVC(C=i, gamma=j, kernel=k)
            clf.fit(X_train_std, y_train)
            y_predict_train = clf.predict(X_train_std)
            score = accuracy_score(y_train, y_predict_train)
            if score >= best_score:
                parameters = i, j, k

A: When you write parameters = i, j, k with = you are overwriting the parameter variable with something else, which in this case is the tuple (i, j, k).
In order to add something to the dictionary you need to write
parameters[some_key] = i, j, k

But you don't have a key and it seems what you really want is not a dictionary, but a set or a list.
Initialize parameters as parameters = set() and replace parameters = i, j, k with parameters.add((i, j, k)). If you prefer a list, initialize parameters as parameters = [] and replace parameters = i, j, k with parameters.appendi, j, k)).


text:
Q: Scala object extending Set instance We know in Scala one can initialize the instance of the superclass of a singleton object by calling a constructor after the extends keyword, like so:
class C(val v: Int)
object Obj extends C(1)

Now, collections in the standard library are implemented in quite a peculiar way, delegating their construction methods to companion objects. What if I wanted Obj to extend some instance of Set? At first I was naively tempted to write:
object Obj extends Set[Int](1, 2, 3, 4)

But the compiler complained, bringing my mind to the problem I'm posing here. Am I misconceaving some fundamental Scala hierarchy design rule?
EDIT: I am exposing my use case to clarify why I feel the need to subclass Set.
trait Group[A] extends Set[A] {
    def add(x: A, y: A): A
    val zero: A
    def inverse(x: A): A
}

class CyclicElement(v: Int) {
    val value = v % 4
    override def equals(x: CyclicElement) = value == x.value
}

object CyclicElement {
    def apply(v: Int) = new CyclicElement(v)
}

object CyclicGroup extends Set[CyclicElement](Zero, A, B, C) with Group[CyclicElement] {
    override def add(x: CyclicElement, y: CyclicElement) = CyclicElement(x.value + y.value)
    override val zero = CyclicElement(0)
    override def inverse(x: CyclicElement) = CyclicElement(4 - x.value)
}

A: The compiler complains because an object is a singleton and, by definition of an object, cannot take parameters at construction. On the other hand, Set is an abstract interface, so one has to implement missing methods, whether you want to create an object or a class:
scala> class SI extends Set[Int]{}
<console>:10: error: class SI needs to be abstract, since:
it has 4 unimplemented members.
/** As seen from class SI, the missing signatures are as follows.
 *  For convenience, these are usable as stub implementations.
 */
  // Members declared in scala.collection.GenSetLike
  def iterator: Iterator[Int] = ???

  // Members declared in scala.collection.SetLike
  def -(elem: Int): scala.collection.immutable.Set[Int] = ???
  def +(elem: Int): scala.collection.immutable.Set[Int] = ???
  def contains(elem: Int): Boolean = ???

       class SI extends Set[Int]{}

However, one can make an ugly workaround like this:
scala> object Obj extends Set[Int] {
     | val content = Set[Int](1,2,3,4)
     | def -(elem: Int) = content-elem
     | def +(elem: Int) = content+elem
     | def contains(elem: Int) = content.contains(elem)
     | def iterator: Iterator[Int] = content.iterator
     | }
defined object Obj

scala> Obj + 5
res1: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)

(or you can declare content to be a mutable Set to keep the changes)
UPDATE:
The solution is to derive your Object from one of the concrete implementation of the Set:
scala> object Obj extends scala.collection.mutable.HashSet[Int]
defined object Obj

scala> Obj += 5
res4: Obj.type = Set(5)


text:
Q: Can we explicitly compute this "shift"-quantity over Boolean functions $u:\mathbb{F}_2^n\rightarrow \mathbb{F}_2$? This question is a follow-up of this question.
Let $\mathbb{F}_2=\{0,1\}$ be the field with two elements, and suppose that $n$ is odd.
Question: Can we compute the exact minimum $$A:=
\min_{u:\mathbb{F}_2^n\rightarrow \mathbb{F}_2} \sum_{a\neq 0}\left(\sum_{x}(-1)^{u(x)+u(x+a)}\right)^2 \, \,?
$$
Here is a lower bound, which I don't know if can attained (see derivation below):
$$
A \ge \max\{1,\frac{f^2(n)}{2^n-1}\},
$$
where
$$
f(n):=\min \{\,\, |k| \,\,\, | \,\,\, k+2^n \,\,\,\text{is a square of an integer}\}.
$$
Motivation: This question arose while I was trying to derive a lower bound on the approximate multiplicativity of Boolean functions.

Lower bound derivation:
Set $s(x,a)=(-1)^{u(x)+u(x+a)}$, $g(a):=\sum_xs(x,a)$, $r=\sum_{a \neq 0} g(a)$.
Since $g(0)=2^n$,
$$
\tag{1}
\mathbb{E}_{\mathbf{x},\mathbf{a}}[s(x,a)]=\frac{1}{2^{2n}}\sum_a g(a)=\frac{2^n+r}{2^{2n}}.
$$
Now, we also have
\begin{equation*}
\tag{2}
\left(\mathbb{E}_{\mathbf{x}}[(-1)^{u(\mathbf{x})}]\right)^2=\mathbb{E}_{\mathbf{x}}[(-1)^{u(\mathbf{x})}]\mathbb{E}_{\mathbf{y}}[(-1)^{u(\mathbf{y})}]=\mathbb{E}_{\mathbf{x},\mathbf{y}}[(-1)^{u(\mathbf{x})+u(\mathbf{y})}]=\mathbb{E}_{\mathbf{x},\mathbf{a}}[(-1)^{u(\mathbf{x})+u(\mathbf{x}+\mathbf{a})}]=\mathbb{E}_{\mathbf{x},\mathbf{a}}[s(x,a)],
\end{equation*}
$\mathbb{E}_{\mathbf{x}}[(-1)^{u(\mathbf{x})}]$ is an integer multiple of $1/2^n$, so we may write
$\mathbb{E}_{\mathbf{x}}[(-1)^{u(\mathbf{x})}]=\frac{m}{2^n}$.
Combining this with equations $(1),(2)$, we get
$$
\frac{2^n+r}{2^{2n}}=\frac{m^2}{2^{2n}},
$$
or
$$
2^n+r=m^2.
$$
Thus
$|r| \ge f(n)$, by the definition of $f$.
Now using Cauchy-Schwartz:
$$
f(n) \le |r| = |\sum_{a \neq 0} g(a)| \le \sum_{a \neq 0} |g(a)| \le \sqrt{\sum_{a \neq 0} g^2(a)}\sqrt{2^n-1}.
$$

Equality happens when all the $g(a)=t \in \mathbb{Z}$, and so $$
f(n)=|r|=|\sum_{a \neq 0} g(a)|=(2^n-1)|t|$$
Since $f(n) \le 2^n$, this implies
$$
(2^n-1)|t| \le 2^n,
$$
so $|t|=1$. Is it possible that indeed $|g(a)|=1$ for every $a \neq 0$?

A: Too long for a comment:
A function $u:\mathbb{F}_q^n\rightarrow \mathbb{F}_q^n$ is perfect nonlinear if the derivative
$$
D_au(x)=u(x+a)-u(x)
$$
takes on each value in $\mathbb{F}_q^m$ equally often for any $a\neq 0,$ as $x$ ranges over the domain. Note that here $n$ is odd, $q=2,$ and $m=1.$ In which case we have
$$
D_au(x)=u(x+a)+u(x)
$$
Fix $a,$ and note that for each $x,$ $D_a(x)=D_a(x+a)$ in even characteristic. So we cannot have PN (Perfect Nonlinear) mappings here, but only so called almost PN (APN) mappings [which are 2-to-1].
A natural technique to obtain a function $u:\mathbb{F}_q^n\rightarrow \mathbb{F}_q$ is to use the absolute trace.
Under this approach, a number of monomial power permutations have been shown to be APN and their composition with the absolute trace have also been used.
For example, for $q=2,$ the Gold exponent over $\mathbb{F}_{2^n}$ is defined as
$$
x\mapsto x^{2^k+1}
$$
with $\gcd(2^k+1,n)=1,$ and $n$ odd. So take $u=tr(x^{2^k+1})$ and fix some basis to view $\mathbb{F}_{2^n}$ as $\mathbb{F}_2^n,$ then it turns out that
$$
u(x+a)+u(x)
$$ is balanced for all $a \in \mathbb{F}_2^n\setminus \mathbb{F}_2.$ this will yield
$$
\sum_{a\neq 0}\left(\sum_{x}(-1)^{u(x)+u(x+a)}\right)^2=
\left(\sum_{x}(-1)^{u(x)+u(x+1)}\right)^2=2^{2n}.
$$
So your minimum is upperbounded by this quantity. I don't know of any other examples which give a lower minimum. Perhaps you can do a search and see for small $n$.


text:
Q: ball thrown inside a freely falling box Centre Of Mass I had a thought experiment whose outcome I was unable to understand. It involved a freely falling box with a person inside.The person throws a heavy ball at one wall of the box and the ball keeps bouncing between the two opposite walls(completely elastic collision).The first part is that when the centre of mass of the entire system is traced it is a straight line moving down.That was the first part I found surprising.The second part was "what is the motion of the box to an outside observer?".I know the answers to the first part but don't understand it and can't answere the second. Any answeres will be appreciated. Thanks :)

A: It depends on the mass of the box. If the mass is low, an outside observer will see the box wiggling back and forth a lot. If the mass is high it will wiggle only  little bit. Just because the outer structure of the system (i.e the box) is seen to move by an outside observer, doesn't mean the system is disobeying the rule about the center of mass that you mention. Note also that the person inside the box will also see it wiggle as the ball bounces.

A: The fact that the ball is 'heavy' is probably the main reason you're confused. It could actually have any mass you wanted and (ignoring other effects) would still follow the same path.
Why is this?
The newtonian equation of motion for an object under a force is:
$$F=ma$$
Where $m$ and $a$ are the mass and acceleration of the object and $F$ is the force acting on it. Dividing the whole equation by $m$, you will end up with:
$$a=\frac{F}{m}$$
This is interesting, and we'll see why after looking at the force term.
Forces on objects are the result of the object interacting with a field. The object will have certain charges which will tell us how much it interacts with the field, for example: electric charge $(q)$. The electric field $(E)$ exists without the object being there, and interacts with the object to give us a force $F=qE$
Now, newton's equation of motion gives us an acceleration of the electrically charged object in an electric field to be:
$$a=\frac{q}{m}E$$
So, the interesting thing about gravity is that the charge of an object that interacts with the gravitational field $(G)$ is the mass of the object, which also tells us how much it will accelerate.
The newtonian equation of motion for an object under a gravitational field is then:
$$a=\frac{m}{m}G$$
$$a=G$$
This tells us that no matter what the mass is of an object (as long as $m>0$) it will move the same way under a gravitational field!
Now, back to your original question.
From the point of view of the person in the box throwing the ball, since they are moving under gravity in the same way as the ball and the box, we can completely ignore its effect. They are weightless. Now you can just imagine what would happen if you threw a ball on a spaceship, it would bounce backwards and forwards in a straight line.
For the second part of the question, the observer outside the box is being held up against the gravitational field (eg. by the earth), and so they will not experience the same acceleration. They will therefore observe the box accelerating downwards with the ball bouncing inbetween the walls, but also accelerating downwards.
Edit: Just seen that you were instead asking about the centre of mass of the system, and it wasn't a question about gravity. Whoops.

A: Let's consider the system $S := \{ball + person + box\}$, and let $M_b$ be the mass of the ball and $M$ the mass of the person and the box. The only external force that act on $S$ is gravitation, so with $\textbf{a}$ the acceleration of the center of mass of $S$, the Second Law of Newton says that
$$ M\textbf{a} = M\textbf{g}$$
(Note that the variation of the gravitationnal field are negligeable here, so $\textbf{g} = \textbf{Constant}$). We can say that the trajectory of the center of mass of $S$ will be a parabola.
Now, let's focus on the motion of the ball and the personn and the box. Let $v_{xb}$ be the horizontal speed of the ball in the barycentric frame of reference, $V_0$ its initial velocity and $v_{x}$ the horizontal speed of the box and the person (the person don't move in the box). Since the horizontal momentum of $S$ is conserved ($\textbf{g}$ is vertical) and is null (we are in the barycentric frame of reference), we have
$$ M_b v_{xb} + M v_{x} = 0$$
So $$ v_x = - \frac{M_b}{M} v_{xb}$$
Now, if $M_b << M$, the box's motion will be unnoticeable: it will be as if there was nothing inside it.
Let's focus on the general case. Let $L$ be the width of the box. The energy of the ball is conserved, so the motion has a period of $T:=2L/V_0$. With $x_b$ the abscissa of the ball, and $x$ the one of the box and the person, we then have, with $x_b(t=0)=x(t=0)=0$ and $0 \leqslant t \leqslant T/2$
$$ x_b(2kT+t) = V_0t$$
and $$ x_b((2k+1)T+t) = (\frac{M+M_b}{M}-t)V_0$$
and $$x(2kT+t) = -\frac{M_b}{M}V_0t$$
and $$x((2k+1)T+t) = -(\frac{M+M_b}{M}-t)\frac{M_b}{M}V_0$$


text:
Q: Why on earth is jack showing up in the sequence of alert boxes? Object.prototype.jack = {};

var a = [1,2,3];

for(var number in a){
    alert(number);
}

Could anyone tell me why the word "jack" jumped out of the alert box?
Thank you very much!

A: Simple - arrays are objects in javascript so by adding:
Object.prototype.jack={};

You've added an enumerable property 'jack' to all objects (and by that to all arrays).
once creating your array "a" and looping through all of its properties
for(var number in a)

You are sure to get a 'jack' alert. To avoid it showing up you can use .hasOwnProperty() to make sure all alerted properties are not inherited. or use a regular
for(var i=0; i < a.length; i++)

loop.

A: The for..in loop iterates over properties.  It's only recommended (by Mozilla and other authorities) to be used on Objects, but not Arrays.  If you insist, this is the correct way to iterate over an object and it will work for an array (most of the time).
for (var number in a) {
    if (Object.prototype.hasOwnProperty.call(a, number)) {
        alert(a[number]); // shows 1 then 2 then 3
    }
}

To do it the generally accepted way,
for (var i=0; i<a.length; i++) {
    alert(a[i]);  // same as above
}

My personal preference is:
for (var val, i=0; val = a[i]; i++) {
    alert(val);  // same as above
}

A: Because you're not checking if jack is a property inherited from prototype or not. Try this instead:
Object.prototype.jack={};

var a = [1,2,3];

for (var number in a) {
    if (a.hasOwnProperty(number)) {
        alert(number);
    }
}


text:
Q: Date and Currency validation in Angular (4) I am new to Angular. I am using angular 4 reactive forms and figured out how to perform custom validations. Following is my implementation for numeric
function numberValidator(c: AbstractControl): { [key: string]: boolean } | null {
    if (c.pristine) {
        return null;
    }
    if (c.value.match(/.*[^0-9].*/)) {
        return { 'numeric': true };
    }
    return null;
}

 phoneControl: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(10), numberValidator]],

I am trying to find out how to perform currency (with or without two decimal places) and most importantly Date field.
Forgive me if this was answered elsewhere but I cannot find any samples for angular(4)
Thanks for your time

A: Created a custom validator to handle formats MM/DD/YYYY and MMDDYYYY
function dateValidator(c: AbstractControl): { [key: string]: boolean } | null {
    if (c.pristine) {
        return null;
    }
    if ((c.value !== undefined && c.value !== '' && c.value != null)) {

        var month = null;
        var day = null;
        var year = null;
        var currentTaxYear = Number(new Date().getFullYear() - 1);
        if (c.value.indexOf('/') > -1) {
            var res = c.value.split("/");
            if (res.length > 1) {
                month = res[0];
                day = res[1]
                year = res[2];
            }
        }
        else {
            if (c.value.length == 8) {
                month = c.value.substring(0, 2);
                day = c.value.substring(2, 4);
                year = c.value.substring(4, 8);
            }
        }
        if (isNaN(month) || isNaN(day) || isNaN(year)) {
            return { 'dateInvalid': true };
        }
        month = Number(month);
        day = Number(day);
        year = Number(year);
        if (month < 1 || month > 12) { // check month range
            return { 'dateInvalid': true };
        }
        if (day < 1 || day > 31) {
            return { 'dateInvalid': true };
        }
        if ((month === 4 || month === 6 || month === 9 || month === 11) && day === 31) {
            return { 'dateInvalid': true };
        }
        if (month == 2) { // check for february 29th
            var isleap = (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0));
            if (day > 29 || (day === 29 && !isleap)) {
                return { 'dateInvalid': true };
            }
        }
        if (year !== currentTaxYear) {
            return { 'dateYearGreaterThanTaxYear': true };
        }
    }
    return null;
}

A: If you are using reactive forms, you can write a custom validator,see below
dateValidator(c: AbstractControl): { [key: string]: boolean } {
    let value = c.value;
    if (value && typeof value === "string") {
      let match = value.match(/^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);
      if (!match) {
        return { 'dateInvalid': true };
      } else if (match && match[0] !== value) {
        return { 'dateInvalid': true };
      }
    }
    return null;
  }

While creating control, you need to add this validator along with your other validators as shown below,
const group = this.fb.group({
    DateType: ['', [Validators.required, this.dateValidator]],
  })

A: This solution worked for me and the followings are satisfied

*

*startDate < endDate

*startDate >= today

*endDate >= today

app.component.html
<form [formGroup]="addContract>

              Start Date *
              <input type="date" name="startDate" formControlName="startDate"
               class="form-control" placeholder="Arrival *"
               [ngClass]="{ 'is-invalid': submitted && f.startDate.errors}"/>

                Required

                 Select a date Over today

              End Date*
              <input type="date" name="endDate" formControlName="endDate"
              class="form-control" placeholder="Departure *"
              [class.is-invalid]="endDate.invalid && endDate.touched"/>

                Required

                 choose a date over today

                End Date should be grater than start Date

</form>

app.component.ts
import { DateValidator} from '../shared/date-validator';

export class AppComponent implements OnInit {
  addContract: FormGroup;
  ngOnInit() {
    this.addContract = this.fb.group({
      startDate: ['', [Validators.required]],
      endDate: ['', [Validators.required]]
    }, {validator: DateValidator});

  get f() { return this.addContract.controls; }

  get endDate() {
    return this.addContract.get('endDate');
  }
  get startDate() {
    return this.addContract.get('startDate');
  }

  }

date-validator.ts
import {AbstractControl} from '@angular/forms';

export function DateValidator(control: AbstractControl): { [ key: string]: boolean} | null {

let from = control.get('startDate');
let to = control.get('endDate');
let c= new Date();
if(new Date(from.value)< c )
{
    return {
        invaineFrom:true
    }
}
if(new Date(to.value) < c )
{
    return {
        invaineTo:true
    }
}
if (from.value > to.value ) {
    return {
      dates: true
    };
  }
  return {};
}

A: What kind of date validation do you need? Just that the value is a valid date? If you set the type="date" on the input element the browser will ensure that only a valid date is entered.
Same for your shown number validator and for any currency validator. You should be able to set the type="number" on the input element and you won't need a validator.
If you still do want to perform your own validation, you can use regular expressions just as in your example.
Just look up regular expressions for currency and date. For the date, something like this: Javascript - Regex to validate date format

A: This is another option to using Custom validators
import { FormControl } from '@angular/forms';

export class DateValidator {

   static ptDate(control: FormControl): { [key: string]: any } {
       let ptDatePattern =  /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g;

       if (!control.value.match(ptDatePattern))
           return { "ptDate": true };

       return null;
   }

   static usDate(control: FormControl): { [key: string]: any } {
       let usDatePattern = /^02\/(?:[01]\d|2\d)\/(?:19|20)(?:0[048]|[13579][26]|[2468][048])|(?:0[13578]|10|12)\/(?:[0-2]\d|3[01])\/(?:19|20)\d{2}|(?:0[469]|11)\/(?:[0-2]\d|30)\/(?:19|20)\d{2}|02\/(?:[0-1]\d|2[0-8])\/(?:19|20)\d{2}$/;

       if (!control.value.match(usDatePattern))
           return { "usDate": true };

       return null;
   }
}

and use it this way for "dd/mm/yyyy" format:
this.formDetail = this.formBuilder.group({
   date: ['', DateValidator.ptDate],
});

and use it this way for "mm/dd/yyyy" format:
this.formDetail = this.formBuilder.group({
   date: ['', DateValidator.usDate],
});

I hope this help!

A: If you're using Angular Material, you can use the MatDatepicker integration with Moment.js to validate a custom date format using FormControl as shown here:
https://material.angular.io/components/datepicker/overview#customizing-the-parse-and-display-formats
HTML:
<input matInput [matDatepicker]="dp" placeholder="Verbose datepicker" [formControl]="date">

TS:
export const MY_FORMATS = {
  parse: {
    dateInput: 'LL',
  },
  display: {
    dateInput: 'LL',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

@Component({
  selector: 'datepicker-formats-example',
  templateUrl: 'datepicker-formats-example.html',
  styleUrls: ['datepicker-formats-example.css'],
  providers: [
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],
})
export class DatepickerFormatsExample {
  date = new FormControl(moment());
}

A: Here is (imo) a better date validation function:
function date(c: AbstractControl): { [key: string]: boolean } {
   let value = new Date(c.value);
   return isNaN(value.getTime()) || value <= new Date('01/01/1753') ? {'dateInvalid': true} : undefined;
}

A: This is my solution:
import {AbstractControl} from "@angular/forms";

export class MyValidators {

  // validate MM/DD/YYYY
  static date(c: AbstractControl): { [key: string]: boolean } {
    let value = c.value;
    if (value && typeof value === "string") {
      let match = value.match(/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/);
      if (!match) {
        return {'dateInvalid': true};
      }
      let date = new Date(`${match[3]}-${match[1]}-${match[2]}`);
      if (isNaN(date.getTime())) {
        return {'dateInvalid': true};
      }
    }
    return null;
  }

}

A: Angular mat-datepicker adds matDatepickerParse to a form control error object if it can't parse an input string


text:
Q: Echoing the login script if the user isn't logged in I am receiving an syntax error when using this code, what I want is for the log in script to only display if the user isn't logged in but receiving an error on the line start of  line 4:
<?php
if($_SESSION['loggedin'] != TRUE){

echo "Already a member?
<form id=\"loginform\" method=\"post\" action="$_SERVER['PHP_SELF'];"
 Email Address:
<input type=\"text\" name=\"liusername\"/>

 Password:
<input type=\"text\" name=\"lipassword\" id=\"password\" />

<input name=\"lisubmit\" type=\"submit\" value=\"submit\">

\n";

}else{
 echo
"Log out\n";
?>
}

A: Change the form opening part to the following. That should make the code work:
<form id=\"loginform\" method=\"post\" action='".$_SERVER['PHP_SELF']."'>

And take out the '?>' out of the else {}. Let me know if it doesn't help.

A: Your echo is not correct .
Try this code :
<?php
if($_SESSION['loggedin'] != TRUE){

echo "Already a member?
<form id=\"loginform\" method=\"post\" action=".$_SERVER['PHP_SELF'];"
 Email Address:
<input type=\"text\" name=\"liusername\"/>

 Password:
<input type=\"text\" name=\"lipassword\" id=\"password\" />

<input name=\"lisubmit\" type=\"submit\" value=\"submit\">

\n";

}else{
 echo
"Log out\n";
?>
}

A: Closing bracket not in PHP context:
}else{
echo "Log out\n";
?>
}

should be
    echo "Log out\n";
}
?>

Plus, already mentioned, wrong variable concatenation:
"$_SERVER['PHP_SELF'];"

must be
" . $_SERVER['PHP_SELF'] . "

session not started:
session_start(); // Before http body, before $_SESSION usage

Besides that, you shouldn't put (PHP) logic and (HTML) markup in the same file / context.


text:
Q: Celery to manage java tasks I have a java client that communicates with celery using rabbitmq and sends the task to celery server for adding 2 numbers x and y
String QUEUE_NAME = "celery";
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
String x = "5";
String y = "10";
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
String ID = UUID.randomUUID().toString();
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
String message = "{\"id\":\""+ID+"\", \"task\": \"tasks.add\", \"args\": ["+x+","+y+"], \"kwargs\": {}, \"retries\": 0, \"eta\": \"2009-11-17T12:30:56.527191\"}";
channel.basicPublish("", QUEUE_NAME, new AMQP.BasicProperties.Builder()
        .contentType("application/json").contentEncoding("utf-8")
        .build(), message.getBytes("utf-8"));
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();

We have a python api add to add these number and that is managed by celery.
from celery import Celery

app = Celery('tasks', broker='amqp://guest@localhost//')

@app.task
def add(x, y):
    return x + y

I would like to write this add(x,y) function in java that celery somehow identify a java add(x,y) method and manage it.
Note: I am looking for a solution without webhooks.
Thanks in advance.

A: Check out https://crabhi.github.io/celery-java/
It's a (very alpha at the moment) implementation of Celery client and worker for JVM.
You can annotate your task class:
 import org.sedlakovi.celery.Task;

 @Task
 public class TestTask {

     public int sum(int x, int y) {
         return x + y;
     }
 }

And then call the task like this:
Client client = new Client(rabbitConnectionChannel, rabbitBackend);

Integer result = TestTaskProxy.with(client).sum(1, 7).get();

A: import json

from celery import Celery
from celery import bootsteps
from kombu import Consumer, Exchange, Queue

queue = Queue("input.queue", Exchange("default"), "input.key")

app = Celery(broker="amqp://")

# Decalring the general input message handler
class InputMessageHandler(object):
    def handle(self, body):
        body_json = json.loads(body)
        _type = body_json["type"]
        if _type == "ETL":
            ETLMessageHandler().handle(body_json)

# Declaring the ETL message handler
class ETLMessageHandler(object):
    def handle(self, body):
        print("Working on ETL for message: {0}".format(body))
        # Calling out your Celery tasks here

# Declaring the bootstep for our purposes
class InputMessageConsumerStep(bootsteps.ConsumerStep):
    def get_consumers(self, channel):
        return [Consumer(channel,
                         queues=[queue],
                         callbacks=[self.handle_message],
                         accept=["json"])]

    def handle_message(self, body, message):
        InputMessageHandler().handle(body)
        message.ack()

app.steps["consumer"].add(InputMessageConsumerStep)

if __name__ == "__main__":
    app.start()


text:
Q: Angular: Transform a request result in a observable I started doing my project in a module by module basis, so each one had to access the user.
Now that I'm polishing it, I'm having multiple API requests for the same thing (user info).
Much I found on the internet is deprecated and doesn't work anymore (mostly RxJs stuff).
What I have: the callback from the API with the user info.
What I want: something shareable globally in the project (I only need one request for the API for the user info)
I'm trying right now to turn an observable into another:
@Injectable({
  providedIn: 'root',
})
export class LoginInfoService {
  constructor(private http: HttpClient) {}

  private userURL = `${environment.API}/loginUser`;

  private user$: Observable<LoggedUser>;
  private request = false;

  public retrieveUser(): Observable<LoggedUser> {

    if (!this.request&& !this.user$) {
      console.log("call request");
      this.user$ = this.getUserJson();
    }

    return this.user$;
  }

  private getUserJson() {
    console.log('actual request');
    this.request = true;
    return this.http.get<LoggedUser>(`${this.userURL}?key='123'`);
  }
}

I'm using for testing "json-server" and while I get only one 'actual request' printed, the server shows multiple requests there.
I'm using the latest stable version of Angular.

A: You can use shareReplay, the http request will be executed only once then the result will be cached for any new subscription. Also, you can remove the request variable.
@Injectable({
  providedIn: 'root',
})
export class LoginInfoService {
  constructor(private http: HttpClient) {}

  private userURL = `${environment.API}/loginUser`;

  private user$: Observable<LoggedUser>;

  public retrieveUser(): Observable<LoggedUser> {
    return this.user$.pipe(shareReplay(1));
  }

  private getUserJson() {
    return this.http.get<LoggedUser>(`${this.userURL}?key='123'`);
  }
}

A: Here is a solution with two subscriptions but only one request. Solved with ReplaySubject:
https://stackblitz.com/edit/only-one-request
PS: I used a different API so you have to adjust the userURL.


text:
Q: Why this code is not updating the database & giving exception? I am trying to update the database with a date received from a textfield in date format. But its not working and giving me a java.lang.NumberFormatException: For input string "". Please help.
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
    String date = i5t1.getText();
    try
    {
    i5Date=(Date) formatter.parse(date);
    }
    catch(ParseException p)
    {
    p.printStackTrace();
    }

    PreparedStatement i5ps = i5conn.prepareStatement("Select * from DailyAnalysis");
    i5ps.setDate(1, new java.sql.Date(i5Date.getTime()));
    ResultSet i5rs = i5ps.executeQuery();

EDITS :
I am adding a small program, but this one doesnt compile due to some error, reference to Date is ambiguous, both class java.util.Date in java.util and class java.sql.Date match
Date i5Date1=formatter.parse(date1);
This sql date and util date are very much confusing.
import java.awt.EventQueue;
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Problem {

JFrame frame;
JPanel panel;
JButton saveButton;
JTextField dateField;
JLabel dateLabel;

public Problem() {
    frame = new JFrame();
    panel = new JPanel();
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    dateLabel = new JLabel("Date");
    dateField = new JTextField(20);
    saveButton = new JButton("Save");
    saveButton.addActionListener(new ActionListener()
   {@Override
    public void actionPerformed(ActionEvent ae)
         {
try
{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection i5conn = DriverManager.getConnection("Jdbc:Odbc:TomsJava");
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
    String date1 = dateField.getText();
    try
    {
    Date i5Date1=formatter.parse(date1);
    }
    catch(ParseException p)
    {
    p.printStackTrace();
    }
    String query= "Select * from DailyAnalysis where Date1=?";
    PreparedStatement i5ps = i5conn.prepareStatement(query);

    i5ps.setDate(1, new java.sql.Date(i5Date1.getTime()));

    ResultSet i5rs = i5ps.executeQuery();

                }

catch(SQLException e)
{
    System.out.println(e);
}
catch(ClassNotFoundException z)
{
    System.out.println(z);
}
catch(NumberFormatException n)
{
    System.out.println(n);
}
  }
});

    panel.add(dateLabel);
    panel.add(dateField);
    panel.add(saveButton);
    frame.add(panel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

public static void main(String args[]) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            new Problem();
        }
     });
}
}

A: The issue is with your prepared statement,
PreparedStatement i5ps = i5conn.prepareStatement("Select * from DailyAnalysis");

There is no parameter in your above statement even though you are trying to set some data in your statement as follows:
i5ps.setDate(1, new java.sql.Date(i5Date.getTime()));

It seems you want to get DailyAnalysis based on date value so your PreparedStatement should be as follows (I am assuming your DailyAnalysis table relevant column name is date, change it as per your table column name) :
PreparedStatement i5ps = i5conn.prepareStatement("Select * from DailyAnalysis where date=?");
i5ps.setDate(1, new java.sql.Date(i5Date.getTime()));

Try with above. Hopefully it should work.
Just an advice: Try to learn how to debug your code and how to analyse the exception to find the root cause. It would really help you in long run.


text:
Q: object-reference as string in javascript There is a way to pass a string in a function to other function and this string is a reference to an object in this other function?
function fun1 (structure){
obj = [{"header":{"orderNumber": a, "item": 1}}, {"header":{"orderNumber": b, "item": 1}}]

newObj = obj[0].structure

console.log(newObj)
//first call a
//second call 1

}

//first call
function fun2(){

   structure = 'header.orderNumber'
   fun1(structure)
}

//second call
fun2(){

   structure = 'header.item'
   fun1(structure)
}

What I want is a dynamic way to access an object by creating a string.
For example in the block of code obj.header.item.description and this is valid. I would like to pass a string in this string somehow make a reference to the object so I can get the value.

A: One way you could accomplish this would be by storing all of the object references in a Map (MDN) structure where the key is a string and the value is the object reference in question.
I should say that even though I don't know your exact use case, this is what you would call a "stringly typed" solution which is generally not the best idea.


text:
Q: Question about using selenium+pyautogui to upload file Recently I need to upload my dataset on a website, the first part works fine on selenium.
However, after I click the 'upload' button, a windows file broswer pops-up.
And after searching online, I finally make it work by using pyautogui, code:
pyautogui.write('K:\Github\###\data\global\Global_PM_corT.csv') # enter file with path
pyautogui.press('enter') # click ok

My question is, I want to use above process on Github Action.
So, i changed:
'K:\Github\###\data\global\Global_PM_corT.csv'

to:
'./data/global/Global_PM_corT.csv'

and it's not working.
I think there is some error when using relative path with pyautogui.
So, i was wondering if someone could help me achieve this? Thanks in advance:)
P.S.
its working right now.
I first read the dataset by
pd.read_csv('path')

then write it on github action
to_csv('C:\\Global_PM_corT.csv')

then I can use absolute path with pyautogui:)
However, I still want to know if a better way to achieve this

A: Please try this:
'./data/global/Global_PM_corT.csv'


text:
Q: C# - How to override actions for "Up arrow" and "Down arrow" for a textbox? I have a textbox and below it i have a listbox.
While the user is typing in the textbox if he presses the up or down arrow he should make a selection in the listbox. The textbox detects all the characters (except space) but it seems that it can't detect the arrow presses.
Any solution for this? This is a WPF project btw.
EDIT, Here's the working code thanks to T.Kiley:
    private void searchBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.IsDown && e.Key == Key.Down)
        {
            e.Handled = true;
            //do your action here

        }
        if (e.IsDown && e.Key == Key.Up)
        {
            e.Handled = true;
            //do another action here
        }
    }

A: I just tried this and it works. Add a preview key down event to the textbox
   private void TextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.IsDown && e.Key == Key.Down)
            MessageBox.Show("It works");
    }

A: You can listen to they KeyDown event of the TextBox. In the handler, check whether the arrow key was pressed (you might need to listen to key up to avoid triggering your code multiple times if the user holds down the button for too long).
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Down)
    {
        // Do some code...
    }
}


text:
Q: Add multi-tenancy bean scope in Spring MVC I'm building a multi tenant Spring MVC application. There are Services that cache data based on the current tenant. I have a mechanism that is able to tell me the tenant for the current request (based on the user authentication token). My question is how I can introduce a new scope in Spring MVC that is selected based on the current tenant.
The idea is as follows. In the configuration, some beans have tenant specified as the scope. When a request is authenticated the tenant is known. Based on this tenant I want to select something (a BeanFactory?) that holds the service instances specific to that tenant so that resolving a bean/service in the context of that request return the tenant specific services.


text:
Q: Is there a more dynamic way of adding listener to all components in parent? Right now, I'm overriding JFrame.addKeyListener(KeyListener), checking the components in it's content pane, then adding listeners to all those components (after using super to invoke the original method)
JFrame frame = new JFrame() {
    public void addKeyListener(KeyListener l) {
        super.addKeyListener(l);
        for(Component c : getContentPane().getComponents()) {
            c.addKeyListener(l);
        }
    }
};

I'm not sure if this is the normally practiced way of adding listeners to a hierarchy of components, but it's the only one I can think of. Is there something already built into the standard JDK that is meant for this?

A:
No need to ask why

Sure there is because anytime I see anybody using a KeyListener I know there is almost always a better way to solve the problem.

I want KeyEvents to trigger no matter what has focus

Still not really very clear.
For example, people don't usually listen for KeyEvents on a JButton. An ActionListener is used to handle the keyboard press of a button. Or, a few people have already suggested Key Bindings which would probably be more appropriate.
Or maybe on text components you would use a DocumentListener.
Finally, if you really think you need to listen to all events then you can use an `AWTEventListener'. See Global Event Listeners for more information.
So yes, the why, is important.


text:
Q: Where to save data cached in mobile apps? Aim going to develop chat app which must has high security level
what you prefer to save old chat secure in the device ?
use local storage with encoding ?
or using cache in the same app ??
pros of using cache is handling for time period to delete old cache
pros of local storage that I can use more security libraries

A: I Used Hive at least and secured data on it by encrypt it


text:
Q: Small doubt on linearity and $F(\textbf{c}+\textbf{d})=F(\textbf{c})+F(\textbf{d}), F(p\textbf{c})=pF(\textbf{c})$? I'm reading Shafarevich's Linear Algebra and Geometry. Here he proves the following:

I am a bit confused: He proves that $F$ is linear iff $(1.8),(1.9)$ are true. But isn't that already called "linear"? It is as if he is showing that if $F$ is linear, then $F$ is linear. If it's of some use to anyone, the proof is in the following links: 1, 2, 3.

A: The definition of linear in Shafarevich's Linear Algebra and Geometry is

Definition 1.1 A function $F$ on the set of all rows of length $n$ with values in the set of all numbers is said to be linear if there exist numbers $a_1,a_2,\ldots,a_n$ such that $F$ associates to each row $(c_1,c_2,...,c_n)$ the number (1.7).

where (1.7) is the linear combination: $a_1c_1 + a_2c_2 +\cdots+ a_nc_n$.
So from this starting point the theorem you mention is indeed a theorem and needs proof.


text:
Q: android notification log history Hi there is there any way I could view history of the notification log file. I tried using andriod sdk ( db shell logcat > log.txt ) but does not get the log i wanted.
For example, if a contact join viber. You will receive a notification of the contact joining viber. Im trying to get the history of this log.
Many many thanks.

A: You can observe notification with AccessibilityService.
But you can´t go to history, you have to observe, save to your database and then you have to use own history...


text:
Q: How to create a shell script to create a folder by using the today's date to take backup using rsync command on every evening around 7 pm 1] I want to create a script which matches the today's date >> with server's date format.
2] If it matches then, it will create the folder named "$date" itself in the mentioned path "/tmp/test/files/testing/".
3] Moreover, it will search for the files which are created by today's date with the help of "find" command from "/var/www/path" and take the back up with the help of the rsync command of those files into /mnt/ folder.
I'm kinda new shell scripter however, kindly help me with the script.
________________________________________________________________________________
What I've did until now is :>>>>>>>
##!/bin/bash
now=$(date +"%m_%d_%Y")

mkdir /tmp/test/files/testing/"date +%b%Y%m%d"/$now &&

find . -type f -newermt 2019-06-10 -ls -exec rsync -avzh {} /mnt/Data/exes/10-June-2019/ \;  &&

mysqldump -h localhost -u username -ppassword production > /mnt/Data/date +%b%Y%m%d/productionDate.sql

________________________________________________________________________________
Thanks,
Bakula


text:
Q: Extract multiple 7z files with auto rename I have a bunch of 7z files, some of which contain files that have the same name. Therefore, I would like to do auto rename.
I can do something like
find ./all -exec 7z x -pabc123 -oall/xml {} \;

to extract all the files, but this asks me for each archive whether or not I want to auto rename them. Is there a way I can just have it ask me once? Or better yet, pass that in as a command line option?
(Note that I have to use seven zip because it has a password.)

A: From the p7zip manual:

-ao (Overwrite mode) switch
Specifies the overwrite mode during extraction, to overwrite files
  already present on disk.
Syntax
-ao[a | s | t | u ]

Switch    Description
-aoa    Overwrite All existing files without prompt.
-aos    Skip extracting of existing files.
-aou    aUto rename extracting file (for example, name.txt will be renamed to name_1.txt).
-aot    auto rename existing file (for example, name.txt will be renamed to name_1.txt).
Examples
7z x test.zip -aoa

extracts all files from test.zip archive and overwrites existing files without any prompt.
Commands that can be used with this switch
e (Extract),
  x (Extract with full paths)
See also
Switches: -y (assume Yes on all
  queries)

Looks like either the -aou or the -aot switch on the 7z command will do what you want, e. g.:
find all -exec 7z x -aou [OPTIONS...] {} \;


text:
Q: Navigation controller in landscape, pop scrolls up my app use a navigation controller and i'm trying to insert the landscape support!
I have my NavigationController and a view, that is called with an IBAction (connected at a UIButton) with this code:
view *myview = [[view alloc] initWithNibName:@"view" bundle:[NSBundle mainBundle]];
[self pushViewController:myview animated:YES];

Of course, i've imported "myview.h" in my NavigationController_Class
So, for the landscape, i've inserted this code in "myview.m" and in "NavigationController_Class.m"
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 return ((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) || (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
 }

What's the problem?
It works, but when you touch the button for the pop of the view from the stack, this scrolls not from the right to the left, but from up to down!
Do you know what could be the problem?
thanks!

A: im guessing you have a UINavigationController inside a UITabBarController?
the solution is to override the shouldAutorotateToInterfaceOrientation: method of each view controller in a navigation stack (the last one is not necessary) and return YES for supported Orientations


text:
Q: Jenkins DSL generic multiple promotions I've written most of our project's jobs/pipelines in DSL without any previous groovy experience but now I'm stuck at more advanced problem that I can't figure out.
I'm trying to implement a method that would add 1,2,n promotions to a job.
Below you can see a fully-working method that can add one promotion, and I expected it to work in such way that I'd just call the method twice if I needed another one but then I ran into my problem - only promotion that was created the latest would be generated.
/**
    * @param job           DSL job object
    * @param promotionName Name of the promotion
    * @param nextJobs      Comma seperated string of jobs to trigger when promotion is executed
    * @param deployers     Comma seperated string IDs that can execute promotion
    * @param params        Array of parameters to pass to the next job [0] = key, [1] = value.
*/
static void addPromotion(def job, String promotionName, String nextJobs, String deployers, String[][] params){
        job.properties {
            promotions {
                promotion {
                    name(promotionName)
                    icon("star-gold")
                    conditions {
                        manual(deployers)
                    }
                    actions {
                        downstreamParameterized {
                            trigger(nextJobs) {
                                parameters {
                                    for (String[] param : params){
                                        predefinedProp(param[0]+"=",param[1])
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

The way it would work, however, if I added another 'promotion' closure like this, however, this example would generate almost identical(name and name-1) promotions:
static void addPromotion(def job, String promotionName, String nextJobs, String deployers, String[][] params){
        job.properties {
            promotions {
                promotion {
                    name(promotionName)
                    icon("star-gold")
                    conditions {
                        manual(deployers)
                    }
                    actions {
                        downstreamParameterized {
                            trigger(nextJobs) {
                                parameters {
                                    for (String[] param : params){
                                        predefinedProp(param[0]+"=",param[1])
                                    }
                                }
                            }
                        }
                    }
                }
                promotion {
                    name("${promotionName}-1")
                    icon("star-gold")
                    conditions {
                        manual(deployers)
                    }
                    actions {
                        downstreamParameterized {
                            trigger(nextJobs) {
                                parameters {
                                    for (String[] param : params){
                                        predefinedProp(param[0]+"=",param[1])
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

Is it possible to re-use closures in some way and populate the variables from a different method maybe? Or any other ideas?

A: This is how I solved it.
Generic promotion object part:
/**
* Adds 'promoted-builds' plugin configuration to job
**/
class Promotions {

    public def    job
    public String promotionName
    public String nextJobs
    public String deployers
    public String [][] params

     /**
    * @param job           DSL job object
    * @param promotionName Name of the promotion
    * @param nextJobs      Comma seperated string of jobs to trigger when promotion is executed
    * @param deployers     Comma seperated string IDs that can execute promotion
    * @param params        Array of parameters to pass to the next job [0] = key, [1] = value.
    */

    public Promotions(Object jobName, String promotionName, String nextJobs, String deployers, String[][] params){
        this.job = jobName
        this.promotionName = promotionName
        this.nextJobs = nextJobs
        this.deployers = deployers
        this.params = params
    }

    static void addPromotions(Promotions ... jobPromotions){
        // Assuming the same job is provided as arguments
        jobPromotions[0].job.properties {
            promotions {
                for (Promotions jobPromotion : jobPromotions){
                    promotion {
                        name(jobPromotion.promotionName)
                        // star-gold, star-silver
                        icon("star-gold")
                        conditions {
                            manual(jobPromotion.deployers)
                        }
                        actions {
                            downstreamParameterized {
                                trigger(jobPromotion.nextJobs) {
                                    parameters {
                                        for (String[] param : jobPromotion.params){
                                            predefinedProp(param[0],param[1])
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

And then I prepare my params and pass them to the promotion constructor, and in the end I call addPromotions() and pass all my constructed objects to it:
    def nextJobs   = "${Configuration.repoName}-${branchName}-deploy-to-perf"
    def deployers  = "developer"
    def params     = [["VERSION", "\${VERSION}"],
                     ["SOURCE_GIT_COMMIT", "\${SOURCE_GIT_COMMIT}"]] as String[][]
    def promo1 = new Promotions(job, "Promote to PERF", nextJobs, deployers, params)

    def nextJobs2   = "../master/${Configuration.repoName}-${branchName}-to-prod-dtr"
    def deployers2  = "admin"
    def params2     = [["VERSION", "\${VERSION}"],
                      ["SOURCE_GIT_COMMIT", "\${SOURCE_GIT_COMMIT}"]] as String[][]
    def promo2 = new Promotions(job, "Promote to PROD", nextJobs2, deployers2, params2)

    Promotions.addPromotions(promo1, promo2)


text:
Q: Jquery inside Facebox I have facebox setup and it works.  when I load an external page with a tab based navigation (JQuery too) the modal works but the nav doesnt.  If it isnt clear I actually want the tabs to be inside the lightbox.  And I also have php/mysql running inside the lightbox if that can change anything.
Thanks for any help.
Edit=>  Sorry about the lack of code here is the code on the page that gets loaded into the facebox:

Informations

Factures en attente

Marché en cours

I saw that maybe using Jquery live might help but am unsure as to whether its what I need.

A: I think i understand, but i don't know enough about facebox. if it loads via AJAX then you will need to use the .live function of jQuery inside of your document ready like this: (on your main page, not the modal page):
$(document).ready(function () {
    $('.modal_box').live('load', function () {
        $('#tabs').tabs();
    });
});

If it loads by iFrame, then you will not need to use .live, however you may consider wrapping the tabs call inside of a document ready like this (inside of the modal page):
$(document).ready(function () {
    $('#tabs').tabs();
});


text:
Q: Extjs 4. combobox in grid. using index to get data I need my controller to load a grid with comboboxes.
The status field (number) in the 'equipment data' should load the status field of possible states from 'equipment states' and display these in the combobox.
When selecting a new option, the id should be saved in 'equipment data', status field. As a number.
// for store 'equipment'
<?php
header("Content-type: application/json");
?>
{
    "success": true,
    "data": [
        {
            "equipment_id": 1,
            "name": "screwdriver",
            "status": 1
        }
    ]
}

// store 'equipmentStatus'
<?php
header("Content-type: application/json");
?>
{
    "success": true,
    "data": [
        {
            "id": 1,
            "status": "available"
        },
        {
            "id": 2,
            "status": "out of stock"
        },
        {
            "id": 3,
            "status": "not available"
        }
    ]
}

// -----------------------------

Ext.define('Equipment.view.EquipmentGrid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.EquipmentGrid',

    title: 'Equipment manager',

    requires: [
        'Ext.form.field.ComboBox',
        'Ext.grid.column.CheckColumn',
        'Ext.grid.plugin.CellEditing'
    ],

    initComponent: function () {

        // enable quicktips
        Ext.tip.QuickTipManager.init();

        this.cellEditing = new Ext.grid.plugin.CellEditing({
            clicksToEdit: 1
        });

        Ext.apply(this, {

                plugins: [this.cellEditing],

                // connect store to grid
                store: 'Equipments',

                    columns: [
                    {
                        header: 'Status',
                        dataIndex: 'status',
                        editor: new Ext.form.field.ComboBox({
                            typeAhead: true,
                            triggerAction: 'all',
                            store: 'EquipmentStatus'
                        })
                    }
                ]
    });

        this.callParent(arguments);
    }

});

A: I don't understand your question clearly, but if you want to display status in the combobox and save the option you choose from the combobox with id as a number you should add two displayField and valueField in the combobox config.
    Ext.define('Equipment.view.EquipmentGrid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.EquipmentGrid',

    title: 'Equipment manager',

    requires: [
        'Ext.form.field.ComboBox',
        'Ext.grid.column.CheckColumn',
        'Ext.grid.plugin.CellEditing'
    ],

    initComponent: function () {

        // enable quicktips
        Ext.tip.QuickTipManager.init();

        this.cellEditing = new Ext.grid.plugin.CellEditing({
            clicksToEdit: 1
        });

        Ext.apply(this, {

                plugins: [this.cellEditing],

                // connect store to grid
                store: 'Equipments',

                    columns: [
                    {
                        header: 'Status',
                        dataIndex: 'status',
                        editor: new Ext.form.field.ComboBox({
                            typeAhead: true,
                            triggerAction: 'all',
                            store: 'EquipmentStatus',
                            // status field will be displayed in combobox
                            displayField: 'status',
                            // id field will be the value of selected status
                            valueField: 'id'
                        })
                    }
                ]
    });

        this.callParent(arguments);
    }

 });

If it is not you wanted, please explain your question in more details. Hope that helps.


text:
Q: C# HttpClient tracing stuck I want to log my request/response but I'm having a problem.
My request stuck at some point which I have no idea why.
Inside my controller I've this code
var log = new LoggingHandler();

using (var client = new HttpClient(log))// <-- problem here
{

    string baseUrl = ConfigurationManager.AppSettings["apiBaseAddress"];
    client.BaseAddress = new Uri(baseUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    foreach (var website in websitesList)
    {
        string stringtime = TimeHandler.GetCurrentDateTime();

        var userModel = new RegisterModel()
        {
           // my user model
        };

        var content = new FormUrlEncodedContent(new[]
       {
              //encoding model
        });

        try
        {
            HttpResponseMessage response = client.PostAsync("api/UserDetails/Register", content).Result;

            //tResult.URL = response.RequestMessage.RequestUri.OriginalString;
            tResult.URL = website.URL;
            tResult.Result = response.ReasonPhrase;

            var statusCode = response.StatusCode.ToString();

           .
           .
           .
           .
        }

        tResult.TestLog = log.GetLog();//*****

        resultList.Add(tResult);
    }
}

and my LoggingHandler
public class LoggingHandler : DelegatingHandler
{
    StringBuilder sb = new StringBuilder();

    public LoggingHandler()
        : base(new HttpClientHandler())
    {
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {

        sb.AppendLine("Request:");
        sb.AppendLine(request.ToString());
        if (request.Content != null)
        {
            sb.AppendLine(await request.Content.ReadAsStringAsync());
        }
        sb.AppendLine();

        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

        sb.AppendLine("Response:");
        sb.AppendLine(response.ToString());
        if (response.Content != null)
        {
            sb.AppendLine(await response.Content.ReadAsStringAsync());
        }
        sb.AppendLine();

        return response;
    }

    public string GetLog()
    {
        return sb.ToString();
    }
}

My debug stuck at:
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

Can someone please put some light and explain me why it's stuck?
Appreciate any help :)

A: You are mixing synchronous and asynchronous call when you use .Result.
HttpResponseMessage response = client.PostAsync("api/UserDetails/Register", content).Result;

That is what is causing deadlock.
Either go async all the way or not at all.
var response = await client.PostAsync("api/UserDetails/Register", content);


text:
Q: re.sub not recognizing spaces in set of values from Excel I'm trying to use python to automatically replace spaces with commas from a set of numbers I am pasting from Excel as a string. However when I try to use re.sub, it doesn't recognize the spaces. I've also tried a simple string sentence and the spaces are replaced with commas as expected. Is there some additional formatting I need to do to the x?
x = '28 23  35  36  35  39  38  34  34  38  38  29  31  34  35  31  38  35  30  35  34  24  30  35  38  35  35  35  38  39  30  35  36  23  23  23  35  35  38  36  28  35  34  31  24  34  36  29  38'
print(re.sub("[\s+]", ",", x))

y = 'hello there sir'
print(re.sub("[\s+]", ",", y))

A: Installed Remove tabs and it resolved itself.


text:
Q: how can i disable save button for a form of field with same label but different ng-model angular js I'm a newbie. I have code something like this in  which has multiple same label(AGE) field (Though form has many other files too)but with different ng-model and name attribute. All i want is to keep the save button disabled until all the Age fields are entered.

    Age

   <input type="text" default="0" id="_AGE_1_" name="AGE_1" ng-model="AGE_1">

    Age

   <input type="text" default="0" id="AGE_2_" name="_AGE_2" ng-model="AGE_2">

    Age

   <input type="text" default="0" id="AGE_3_" name="_AGE_3" ng-model="AGE_3">

How can i achieve that? Please Help

A: Something like this using a simple counter?
activateSave() {
    return this.counter==3;
}

<button [disabled]="activateSave()" (click)="doSomething()">Save</button>


text:
Q: Details are not shown for Internal Server Error [500] even after setting the IncludeErrorDetailPolicy to Always I am not seeing the error details even after the IncludeErrorDetailPolicy to Always
I have the below code in Startup.cs.
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always

Is there anything else I need to do? I can get the whole error information in my local machine, but not in the DEV server after it is deployed.
I logged into the server and made the customError mode set to "On". Also, I set the httpErrors set to "Detailed".
<system.web>
    <customErrors mode="On"/>
</system.web>

<system.webServer>
    <httpErrors errorMode="Detailed"/>
</system.webServer>

It did not show after those changes as well. Is there anything else need to be done in IIS?

A: First of all this is not an answer. It is a workaround:
I removed the below code from Startup.cs
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always

Added the below in web.config in system.webServer section:
<httpErrors existingResponse="PassThrough" errorMode="Detailed" />

Also, I used the ResponseMessage(HttpResponseMessage) instead of InternalServerError(Exception) as below:
private IHttpActionResult CustomHttpActionResult(string message)
{
   return ResponseMessage(new HttpResponseMessage
   {
      Content = new StringContent(message),
      StatusCode = HttpStatusCode.InternalServerError
   });
}


text:
Q: EC2 Unable to install composer "Unable to write keys.dev.pub to: /home/ec2-user/.composer" I have a Linux AMI EC2 server that I'm trying to install composer on. Usually the process is pretty simple but in this case I just can't get it to work.
$ cd /home/ec2-user/
$ rm composer-setup.php
$ php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
$ php composer-setup.php
All settings correct for using Composer
Unable to write keys.dev.pub to: /home/ec2-user/.composer

I tried chmod 777 /home/ec2-user and then php composer-setup.php but I get the same error.
I tried this too:
$ sudo curl -sS https://getcomposer.org/installer | sudo php
All settings correct for using Composer
Unable to write keys.dev.pub to: /root/.composer

I also tried going into my project directory on the server and doing the following:
$ sudo su
$ curl -sS https://getcomposer.org/installer | php
All settings correct for using Composer
Unable to write keys.dev.pub to: /root/.composer

I confirmed that the .composer directory does not exist in my users's home directory
$ ls -la ~ | grep composer
-rw-rw-r-- 1 ec2-user ec2-user 305459 Feb 27 17:27 composer-setup.php

I'm really stomped here. Would really appreciate any hints or suggestions.

A: After a very long time, I figured out that composer installation was failing because the file_put_contents function was disabled on my server. Unfortunately when the install failed, it didn't indicate what was causing the problem and did not write anything into my PHP error log (I confirmed that PHP error logging was set up & working correctly). After re-enabling the file_put_contents method, the install worked like a charm. I just wish it gave me more details upon failing. If anyone knows a way to get additional failure details during installation, please let me know.


text:
Q: Implementing stale-while-revalidate with service worker, behaves like cache-only on mobile I'm currently implementing a simple service worker to improve the performance of a website, the website serves the cached assets and then once the page has loaded quietly checks the ETAG to see if it has changed since the last visit, if it has it downloads the resource in the background and caches it for the next time.
I tried changing an image on the server, on desktop chrome updated the resource after 20 minutes while on android the cache has never been updated since the moment the sw was installed, which is 16 hours ago. I can't seem to understand what's the issue, maybe you guys can help. It's worth mentioning this is my first time writing a service worker and with asyncronous javascript in general.
This is my code:
 const staticAssets = [
    //Resources I want to be served using stale-while-revalidate
];

self.addEventListener('install', async event =>{
    const cache = await caches.open('rmi');
    cache.addAll(staticAssets);
});

self.addEventListener('fetch',event =>{
    const req = event.request;
    event.respondWith(cacheFirst(req));
});

async function cacheFirst(req){
    try{
        const cachedResponse = await caches.match(req)
        if  (cachedResponse == null)
            throw "Not In Cache";

        const cache = await caches.open('rmi');
        try{
            return  cachedResponse;
        } finally {
            addToCache(req.url,cache);
        }

    } catch(error) {
        const res = await fetch(req);
        return res;
    }
};

function addToCache(req,cache){

    fetch(req,{cache:'no-cache'}).then(function(response) {
    if (!response.ok) {
      throw new TypeError('Bad Response Status');
    }
    return cache.put(req, response);
    })

}


text:
Q: Storing User Time Zone in Amazon SimpleDB I'm looking to store some information about the the timezone that the user is in. However, i'm not sure what the best practice is to store the timezone in the database as, I'm using Amazon SimpleDB so the type will be of a string. Is there a easy way to store this and reuse TimeZone or TimeZoneInfo that is provided within the .net framework?
Thanks

A: Hey, you can store time zone id as string and then when reading value from SimpleDB use TimeZoneInfo.FindSystemTimeZoneById method to get CLR instance.
// Id for storage in SimpleDB.
var exampleTimeZone = TimeZoneInfo.GetSystemTimeZones()[0].Id;
// CLR instance to use in .NET from stored Id.
var timeZoneInstance = TimeZoneInfo.FindSystemTimeZoneById(exampleTimeZone);


text:
Q: Convert Objects from Query to other Class in Hibernate? I have following problem: I am using Spring + Hibernate and am currently trying to select an id + amount of its id and return a list with each id and its corresponding amount. Now the problem is, that apperently the converter has a problem as I get following exception :

ConverterNotFoundException: No converter found capable of converting
  from type [java.lang.Long] to type [...entity.E_Amount]] with root
  cause

E_Amount creates Obejects with an id and an amount. And My Query:
 @Query("select t.e.id, count(t.id) from...")

returns a perfectly fine result of a long and an integer e.g. {9,101}
I am simply not completely sure how to start tackling this converting problem. Any ideas would be greatly appreciated!

A: Try the result class strategy:
1) Create a new class ResultClass with constructor accepting your query results:
public class ResultClass{

    public ResultClass(Integer id, Long count){..}
}

2) Amend the query a bit:
@Query("select new com.mypackage.ResultClass(t.e.id, count(t.id)) from...")
public List<ResultClass> query(..);

Just make sure that constructor arguments are in the same order as column in the select statement.


text:
Q: Deadbolt 2 playframwork 2.5 getting issue with Annotations? When i am using anotations like Subject Present it giving me the error
[ConfigurationException: Guice configuration errors:
1) No implementation for be.objectify.deadbolt.java.cache.HandlerCache was bound.
  while locating be.objectify.deadbolt.java.cache.HandlerCache
    for parameter 0 at be.objectify.deadbolt.java.actions.SubjectNotPresentAction.(SubjectNotPresentAction.java:45)
  while locating be.objectify.deadbolt.java.actions.SubjectNotPresentAction
2) No implementation for be.objectify.deadbolt.java.cache.PatternCache was bound.
  while locating be.objectify.deadbolt.java.cache.PatternCache
    for parameter 2 at be.objectify.deadbolt.java.ConstraintLogic.(ConstraintLogic.java:43)
  while locating be.objectify.deadbolt.java.ConstraintLogic
    for parameter 3 at be.objectify.deadbolt.java.actions.SubjectNotPresentAction.(SubjectNotPresentAction.java:45)
  while locating be.objectify.deadbolt.java.actions.SubjectNotPresentAction
3) No implementation for be.objectify.deadbolt.java.cache.SubjectCache was bound.
  while locating be.objectify.deadbolt.java.cache.SubjectCache
    for parameter 1 at be.objectify.deadbolt.java.ConstraintLogic.(ConstraintLogic.java:43)
  while locating be.objectify.deadbolt.java.ConstraintLogic
    for parameter 3 at be.objectify.deadbolt.java.actions.SubjectNotPresentAction.(SubjectNotPresentAction.java:45)
  while locating be.objectify.deadbolt.java.actions.SubjectNotPresentAction
3 errors]
I have i already implemented the Subject , Role and Permission and also implemented HandlerCache and DeadboltHandler and DeadboltHook also.
everythings work but when i am using annotation its gives error.

A: play {
  modules {
    enabled += "be.objectify.deadbolt.java.DeadboltModule",
    enabled += "modules.CustomDeadboltHook"
  }
}

put this code in your application.conf file. istead of
modules {
    enabled += "be.objectify.deadbolt.java.DeadboltModule",
    enabled += "modules.CustomDeadboltHook"
  }

it fix your issue.


text:
Q: CSS image-orientation: from-image; Not working My images orientation on my website are not the same as the actual image, I tried using: image-orientation: from-image; to fix my issue and it did not work, the images orientations are wrong and when I inspect the element, image-orientation: from-image; is crossed out....is there another way to do this?

A: The question is very technical, we need to read the image as raw binary data.
I hope that this answer will help you.


text:
Q: What is the enterprise use of the Jetty plugin in Maven? Since I learn from some maven tutorials we can import Jetty as a maven plugin like this.

<plugin>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>maven-jetty-plugin</artifactId>
  <version>6.1.10</version>
  <configuration>
    <scanIntervalSeconds>5</scanIntervalSeconds>
  </configuration>
</plugin>

And can run the plugin like this.
$ mvn jetty:run

Also we can change the port and context path and lots of stuff in this plugin.

As I understood that we can use Jetty as a server like tomcat, and we can deploy an application through it.
But the thing I don't understand is what is the actual enterprise use of Jetty in maven..

A: From the official documentation:

The Jetty Maven plugin is useful for rapid development and testing. You can add it to any webapp project that is structured according to the Maven defaults. The plugin can then periodically scan your project for changes and automatically redeploy the webapp if any are found. This makes the development cycle more productive by eliminating the build and deploy steps: you use your IDE to make changes to the project, and the running web container automatically picks them up, allowing you to test them straight away.

However (and maybe this addresses what you call "enterprise use"):

While the Jetty Maven Plugin can be very useful for development we do not recommend its use in a production capacity. In order for the plugin to work it needs to leverage many internal Maven apis and Maven itself it not a production deployment tool. We recommend either the traditional distribution deployment approach or using embedded Jetty.

A: I don't know exactly what you mean by enterprise use, but let's say you're developing a web application and it's a Maven project.
Each time you want to test whether the web application works correctly, you need to deploy the web archive (WAR) on a web server, e.g. Jetty or Tomcat. Usually this involves a couple of manual steps like:

*

*Start the web server

*Deploy the WAR on it

Where the Maven plugin comes in handy is that it allows you to just execute
mvn jetty:run-war

and it does all these steps automatically for you in a single command, saving you lots of time. The plugin is even able to redeploy the application once it notices changes have been made.

A: The main usage is for testing, Jetty can also be started programmatically (see this example Java code) which means you can start server directly from your code and interact with your REST API for instance.
You can also use it for easier deployment of small applications, just package everything into the JAR which runs server from main method when executed via java -jar your-app.jar. You don't need any dependencies installed except Java then.
As a side note, I currently work in Clojure (JVM language based on Lisp) and many people deploys their application as JAR which internally runs embedded Jetty because this way it's also starts REPL which you can connect to remotely and debug your application when it's running.


text:
Q: Bernoulli numbers [A classical introduction to modern number theory] I'm struggling with following exercise (Ex.9) from the book in the corresponding chapter.

Using Lemma 1 show the radius of convergence of $\sum B_nt^n/n!$ is $2\pi$. As a consequence show that for any $C,k>0$ there are infinitely many $n$ such that $|B_n|>Cn^k$.

Lemma 1 simply says that $$\frac{t}{e^t-1}=\sum_{n=0}^\infty B_nt^n/n!$$
I managed to show
$$\limsup_{n\to\infty}\sqrt[n]{\frac{|B_n|}{n!}}=2\pi$$ using identity $2(2m)!\zeta(2m)=(-1)^{m+1}(2\pi)^{2m}B_{2m},$ which does not solves the problem (I mean I'm using stronger fact).
So how can I compute the $\limsup$ using only the Lemma?
I have a problem with the second part as well. From the $\limsup$ for every $\varepsilon>0$ there is $N$ such that $|B_n|/n!<2\pi+\varepsilon$ for every $n>N$. Let us assume $n$ even and fix $\varepsilon.$ Then we have bound $$|B_n|<n!(2\pi+\varepsilon).$$
We know $\forall C,k>0$ there is $M$ such that $Cn^k<n!$ for every $n>M$, so an obvious necessary condition is $n>\max\{N,M\}$. But what else?


text:
Q: Dark L before semi-vowels Not sure if this is the right place to ask on, but it's been bothering me for a while now. Do you still make a dark L before consonants like W, Y.
For example - I'm all yours tonight. Will the L in "all" be a dark L?

A: Before /w/, the "dark l" allophone will certainly be used
Before /w/, I can't imagine a native speaker who has "dark" and "light" allophones of /l/ using anything but dark l. The sequence /lw/ cannot occur within a single syllable in English, so the /l/ must be in a syllable coda, which is a position that strongly conditions the use of "dark l". I can't think of anything that would counteract this tendency before /w/.
Some speakers actually vocalize coda /l/ to something like [w], [ɰ] or [ɤ̯].
Also, some speakers who don't generally vocalize coda /l/ may elide it in some common words such as "always". I've also heard of this happening in other words with /lw/ such as "railway".
Jack Windsor Lewis wrote in "The General American and General British Pronunciations of English"

In GB [General British (English)] loss of an /l/ is very common in
  almost, always, railway, vulnerable, wholly (rendering it homophonous
  with holy) etc and syllable-finally some speakers vocalise /l/ to a
  weak /u/ in forms like /`veɪu/ veil, /`reɪueɪ/ railway etc mainly in
  markedly southeastern types of accent.

Before /j/, I'm not sure but I doubt "light l" would be used
Before /j/, I've read that some native speakers will drop /l/ in some words, such as "billion".
While it's true that front vowels or front semivowels tend to condition brighter realizations of adjacent consonants, I've never read of this occurring in English for /l/ before /j/. I don't know enough phonetics to say if this happens or not.