text:
Q: How do I sort a column from the bottom to the top? I have a table videos with the columns id | position | title now I  want to sort the column position from the end to the bottom in a permanent way with e.g. UPDATE. I could change that manually but there are more than 460 rows I would have to update manually which is really annoying.
I already tried
SELECT position FROM videos ORDER BY position + 0 asc;

which shows the needed result but I don't know how to make it a permanent change. If I use
UPDATE videos SET position = (SELECT position FROM videos ORDER BY position + 0 asc);

which changes the rows of the column to one value.
The table looks like this
Id    | position | title
---------------------------
tz7e  | 3        | title1
-cQ6  | 4        | title2
Q1L3  | 1        | title3
y456  | 2        | title4
V2n4  | 5        | title5
p76b  | 7        | title6
98kN  | 6        | title7

But it want to have it like that
Id    | position | title
---------------------------
tz7e  | 7        | title1
-cQ6  | 6        | title2
Q1L3  | 5        | title3
y456  | 4        | title4
V2n4  | 3        | title5
p76b  | 2        | title6
98kN  | 1        | title7

But with 460 entries in the column position that I want to rerow.

A: Sounds to me like what you want is a Clustered Index. Put it on the column Position and the rows will be physically ordered by that column on the disk. The order ascending or descending does not matter in this case.
CREATE CLUSTERED INDEX name ON videos (position);


text:
Q: Why does my VSIX not install on Visual Studio Professional? I have created a VSIX that is supposed to be installable on either Visual Studio 2013 Professional or higher and/or Visual Studio 2015 Community or higher. When people install with Visual Studio 2013 Professional I get the following error on the log (relevant bits):
SupportedFrameworkVersionRange : [4.5,)
Supported Products : Microsoft.VisualStudio.Community
Version : [12.0,)
References      :
Searching for applicable products...
Found installed product - Microsoft Visual Studio Professional 2013
Found installed product - Microsoft Visual Studio 2013 Shell (Integrated)
Found installed product - Global Location
Found installed product - ssms
VSIXInstaller.NoApplicableSKUsException: This extension is not installable on any currently installed products.
   at VSIXInstaller.App.InitializeInstall()
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()

I have taken out the dates on the left.
I was thinking that 'Microsoft.VisualStudio.Community', Version : [12.0,)
would have supported 'Microsoft Visual Studio Professional 2013', but then I would not expect to get this error.
What are the settings required to allow a vsix extension to target Visual Studio 2013 and Visual Studio 2015 Community?
(I would prefer to allow community for 2013, but my understanding is that version does not support VSIX. If it matters this is a project template with a Wizard.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python List and If Statement issue I have a list called listExitPrice already created with values in it. I was hoping to separate out this list into multiple other lists as you can see below. I wanted to separate it by looking into the what listExitPrice[k] and checking it it is greater than 0, if it is I wanted to follow the path for else. Vise versa. This code yields "list indices must be integers or slices, not tuples" for the first row of the else statement. Any help would be appreciated! Thanks!
countSell = 0
countHold = 0
for k in listExitPrice:
    if k == 0:
        listBuyDateAP[countHold] = listBuyDate[k]
        listStockNameAP[countHold] = listStockName[k]
        listEntryPriceAP[countHold] = listEntryPrice[k]
        listVolumeAP[countHold] = listVolume[k]
        countHold = countHold + 1
    else:
        listBuyDatePT[countSell] = listBuyDate[k]
        listStockNamePT[countSell] = listStockName[k]
        listEntryPricePT[countSell] = listExitPrice[k]
        listVolumePT[countSell] = listVolume[k]
        listExitPricePT[countSell] = listEntryPrice[k]
        listSellDatePT[countSell] = listSellDate[k]
        countSell = countSell + 1

A: Without knowing what your K values look like, I can only guess based on the error that it is not an integer (which can be used to index arrays) but a tuple instead. You probably want to print out listExitPrice to see for yourself.


text:
Q: How to solve for missing angle? (Triangles) I was looking around at geometry questions and came across this
Seemed simple but I got stuck after filling in everything I knew. This is what I couldn't get passed

Only thing I could think of doing is drawing auxiliary lines to fill values but I couldn't think of useful ones.
Help

A: Start by noticing that $ABE$ is a particular triangle. After that, draw the line parallel to $AB$ going through $E$, and the one parallel to $AE$ going through $B$. Once you are done with that, calculate the new angles with the newly formed triangles (very easy given what you already have). Then use what you know about the triangle $ABE$ to draw a very nice line going through $A$ and cutting $[EB]$ in half.
Once you are done with that, observe that the triangle $OED$ (where $O$ is the point formed by the intersection of $DB$ and the line parallel to $AB$ going through $E$) is VERY SIMILAR to a newly formed triangle that you know the angles of...

A: This is a fairly simple problem, here's my approach:

1.) Locate point $C$ on $BD$ and join it with $A$ and $E$ such that $\angle BAC=20$. Now that we know that $\angle BAC=20$ and $\angle ABC=80$, we can infer that $\angle ACB=80$, therefore $AB=AC=AE$.
2.) Since $\angle EAC=60$ and $AE=AC$, we can say that $\triangle AEC$ is equilateral, therefore $AB=AC=AE=EC$. Notice that $\angle DAC=\angle ADC=40$, therefore, $AB=AC=AE=EC=DC$. This proves that $C$ is the circumcenter of $\triangle AED$, therefore via the inscribed angle theorem, $x=30$


text:
Q: Check at least one checkboxlist item is selected in Javascript I want to check that at least one item in asp:checkbox list is selected and if at least one item is selected in checkboxlist then I want to enable button.
Please help

A: Refer the link Validating checkboxList Asp.Net control using javascript for details. Please try:
<script language="javascript" type="text/javascript">
function CheckItem(sender, args){
    var chkControlId = '<%=chkMealPeriod.ClientID%> '
    var options = document.getElementById(chkControlId).getElementsByTagName('input');
    var ischecked=false;
    args.IsValid =false;
    for(i=0;i<options.length;i++)
    {
        var opt = options[i];
        if(opt.type=="checkbox")
        {
            if(opt.checked)
            {
                ischecked= true;
                args.IsValid = true;
            }
        }
    }
}

A: var checkboxs=document.getElementsByName("chkControlId[]");
    var okay=false;
    var l=checkboxs.length;
    for(var i=0;i<l;i++)
    {
        if(checkboxs[i].checked)
        {
            okay=true;
            break;
        }
    }
    if(!okay)
    {
        alert("Please Select atleast one");
    return false;
    }


text:
Q: Minimization randomisation in trial, what to do if dropout or missing data? I have been asked a question on minimization randomisation in a randomised control trial. If the randomisation has allocated thirty participants to sham or treatment, but then subsequently it is discovered that two of the thirty participants only had baseline assessment and did not receive sham or 'treatment'.
How do we ensure that subsequent allocation to treatment or sham is balanced?
Do we remove the individuals and work out if the program can rebalance? (I think this is not possible looking at the documentation).
Alternatively, do we keep them as missing data and allow for this in the analysis?


text:
Q: Is it possible to have an infinite horizontal paging uiscrollview for page control in swift 4? Say I have an array of strings and every time I swipe, I want the text on the screen to be a random string from the array without reaching an end. How would I do that?

A: No, you can't have an infinite scroll view. A UIScrollView is a view onto a rectangular area. That rectangular area can be large, but it has limits.
A UIPageViewController might do what you want. It's been a while since I used one, but looking at the docs it looks like you can either provide an array of view controllers or provide a dataSource that conforms to the UIPageViewControllerDataSource protocol. It sounds like you could use a dataSource to serve up an infinite set of view controllers containing your strings.

A: You can do this with a UIPageViewController.
Here is a simple example (add a UIPageViewController to your storyboard, and set its Class to InfinitePageViewController):
//
//  InfinitePageViewController.swift
//  InfinitePages
//
//  Created by Don Mag on 10/30/18.
//

import UIKit

// simple random color extension
extension UIColor {
    static func randomColor(saturation: CGFloat = 1, brightness: CGFloat = 1, alpha: CGFloat = 1) -> UIColor {
        let hue = CGFloat(arc4random_uniform(361)) / 360.0
        return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
    }
}

class SinglePageViewController: UIViewController {

    var theLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .white
        v.textAlignment = .center
        v.numberOfLines = 0
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.randomColor()

        view.addSubview(theLabel)
        NSLayoutConstraint.activate([
            theLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 40.0),
            theLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -40.0),
            theLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40.0),
            theLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40.0),
            ])

    }

}

class InfinitePageViewController: UIPageViewController, UIPageViewControllerDataSource {

    var stringArray = [
        "1 - Do not consider painful what is good for you.",
        "2 - It is better to look ahead and prepare than to look back and regret.",
        "3 - The easiest thing in the world to be is you. The most difficult thing to be is what other people want you to be. Don't let them put you in that position.",
        "4 - A book is a version of the world. If you do not like it, ignore it; or offer your own version in return.",
        "5 - The scientific name for an animal that doesn't either run from or fight its enemies is lunch.",
        "6 - To love is to receive a glimpse of heaven.",
        "7 - Patriotism is your conviction that this country is superior to all other countries because you were born in it.",
        "8 - There is but one temple in the universe and that is the body of man.",
        "9 - It is easier to get forgiveness than permission.",
        "10 - There is always more misery among the lower classes than there is humanity in the higher.",
        "11 - Success is counted sweetest by those who ne'er succeed.",
        "12 - Indifference and neglect often do much more damage than outright dislike.",
        "13 - For what do we live, but to make sport for our neighbours, and laugh at them in our turn?",
        "14 - Last night somebody broke into my apartment and replaced everything with exact duplicates... When I pointed it out to my roommate, he said, 'Do I know you?'",
        "15 - Do not weep; do not wax indignant. Understand.",
        "16 - Work saves us from three great evils: boredom, vice and need.",
        "17 - You can discover what your enemy fears most by observing the means he uses to frighten you.",
        "18 - Rest satisfied with doing well, and leave others to talk of you as they please.",
        "19 - People want economy and they will pay any price to get it.",
        "20 - On the whole human beings want to be good, but not too good, and not quite all the time.",
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.dataSource = self

        // create the first "page"
        let vc = SinglePageViewController()
        vc.theLabel.text = stringArray[0]

        // set it as the initial page VC
        self.setViewControllers([vc], direction: .forward, animated: false, completion: nil)

    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        // don't allow scrolling backward
        return nil
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        let vc = SinglePageViewController()
        let randomIndex = Int(arc4random_uniform(UInt32(stringArray.count)))
        vc.theLabel.text = stringArray[randomIndex]
        return vc
    }

}

This will scroll infinitely, picking a random string from stringArray for each new page.
Because this is simply getting a random string from the array, it's entirely possible that you will get the same string multiple times - even sequentially. If you don't want that, one approach is to shuffle an array of index numbers, and then step through that array. When you've reached the end, shuffle the numbers again and continue on.


text:
Q: Trying to get MKPolygon overlay working Trying to figure out this MKPolygon working. I've created a whole heap MKMapPoints and placed them into an array. Then I make a Polygon out of them with:
[MKPolygon polygonWithPoints:pointArr count:sqlite3_column_int(countStatement, 0)];

and add that to an Array for retrieval later.
Later I loop through the array and add each object (MKPolygon) to the map with:
[mapView addOverlay:[overlays objectAtIndex:i]];

And this according to logs works fine.
I then implement mapView: viewForOverlay: like so
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
MKOverlayView *theOverlayView = nil;
for (MKPolygon *theOverlay in overlays) {
    if (theOverlay == overlay) {
        MKPolygonView *thePolygonView = [[[MKPolygonView alloc] initWithPolygon:theOverlay] autorelease];
        theOverlayView = thePolygonView;

    }
}
return theOverlayView;
}

As far as I can see this should technically work. But it doesn't, the App just crashes when it gets to the region of the map that I think its on (points may be wrong because of lat long mixup or conversion mistake but thats another thing)
Am I missing some property I need to set or could the incorrect points be causing the crash? Or am I missing it entirely?
Cheers for any help.

A: This was actually correct but I made a mistake putting more than I remembered into overlays - it was actually and array of dictionaries which stored the MKPolygon and a string. Correcting this got it working.


text:
Q: mongodb $or in JAVA I am trying to execute the following query in java but it returns no results at all even though on command line it works fine! they are identical queries but different results!
    BasicDBObject m_query = new BasicDBObject();
    BasicDBObject cid = new BasicDBObject();
    BasicDBList in = new BasicDBList();
    in.add("56eea58b013693083806ab92");
    cid.append("client_id", new BasicDBObject("$in", in));
    BasicDBObject pcid = new BasicDBObject();
    pcid.append("parent_client_id", new BasicDBObject("$in", in));
    BasicDBList or = new BasicDBList();
    or.add(cid);
    or.add(pcid);
    m_query.append("$or", or);
    System.out.println(m_query);
    System.out.println(mongoTemplate().getCollection(datatType).count(m_query));

The printed results are:
>{ "$or" : [ { "client_id" : { "$in" : [ "578ac9492c1ae71f2958d2c2"]}} , { "parent_client_id" : { "$in" : [ "578ac9492c1ae71f2958d2c2"]}}]}

> 0

When I execute the following on mongo cmd I get "5" as result for count:
> db.collection.count({$or : [ {client_id: {$in : ["578ac9492c1ae71f2958d2c2"]}}, {parent_client_id: {$in : ["578ac9492c1ae71f2958d2c2"]}} ]})

> {
    "client_id": "56eea58b013693083806ab92",
    "activity_type": "client",
    "geo_tag": {
        "type": "Point",
        "coordinates": [
            35.83278446,
            31.97517983
        ]
    },
    "cell_phone": "",
    "_platform": "web",
    "client_status": "lead",
    "phone": "",
    "name": "client 2",
    "comment": "undefined",
    "zip_extension": "",
    "contact_title": "",
    "user": "Representative"
}


text:
Q: Can unitary evolution produce a superposition of wavefunctions, or do wave functions have to be 'created' in a superposition before evolution? A quantum superposition is a wave function such as :
$$
|\psi\rangle = \alpha |\psi_1\rangle + \beta  |\psi_2 \rangle
$$
Unitary evolution will transfer these states to $|\psi'\rangle \to U|\psi\rangle$
My question is can unitary evolution transform a wave function psi to a 'greater' superposition of states, for instance
$$
\alpha |\psi_1\rangle + \beta  |\psi_2 \rangle+ \kappa |\psi_3\rangle=U(\alpha |\psi_1\rangle + \beta  |\psi_2 \rangle)
$$
If this is not possible, then how does one create (in real life) a superposition of wave-functions if no unitary operator exists to create it from a simpler wave function ?

A: Well, I see no reason why the action of some arbitrary unitary operator should keep a vector in some subspace. A trivial way to see this is to realise that rotations in two dimensions are unitary, and you can certainly rotate the $\hat{\mathbf{x}}$ vector to some combination of $\mathbf{\hat{x}}$ and $\mathbf{\hat{y}}$ using a rotation!
It's very easy to construct an equivalent quantum example of this. A "physical" example of this is neutrino oscillations: neutrinos are created (and detected) as one of their flavour eigenstates ("electron", "muon", or "tau" neutrinos), but these are not eigenstates of the system's Hamiltonian (which are the so-called "mass" eigenstates). Thus, if an "electron" neutrino is created in the sun and travels to the Earth, it evolves unitarily into a superposition of the other states and so you could well say that: $$\hat{U}(t) |\psi_e\rangle = \alpha(t)\, |\psi_e\rangle + \beta(t) \,|\psi_\mu\rangle + \gamma(t) \,|\psi_\tau\rangle.$$
So even though the system was created as a pure "electron" neutrino, since this state was not an eigenstate of the Hamiltonian, it  evolved into a superposition of other orthogonal states.
As to the second part of your question, I don't know how such states are created experimentally, but unitary operations are just one of many types of allowed linear operations, but not all quantum operations need to be unitary: the most notable example being measurements, which cause the wavefunction to collapse to some eigenstate of the observable being measured, and which are certainly not unitary! Only symmetry operations need to be unitary (or anti-unitary, see Wigner's theorem) in order to conserve probability.

A: Vector spaces don't have some elements that are superpositions and others that are not superpositions. Such a distinction depends on a choice of basis, which is a choice, not something built in to the vector space.
So your question would need to be changed somehow in order to make it a question that makes sense. One way to do so would be to change it to a question about density matrices.

A: Part of this question is what you consider to be a superposition of states. The word "state" in that phrase is ambiguous. It usually refers to the eigenstates of some observable that we want to measure, while the state of the system can be any linear combination of these. If we were interested in a different observable, that also means a different set of eigenstates and therefore a different kind of linear combination of them. In essence, a system state may be an eigenstate with respect to one observable, making it not a superposition in this eigenbasis, while the same state can be considered as a superposition when changing the observable and with it the eigenbasis.
As a simple example, in Schrödinger QM, the evolution operator is the exponential map of the Hamiltonian, i.e. energy operator, $U(t) = e^{-iHt/\hbar}$. If your initial state is an eigenstate of the Hamiltonian to an eigenvalue $\hbar\omega$, then time evolution will just add phase factors,
$$|\psi(t)\rangle = e^{-iHt/\hbar} |\psi(0)\rangle = e^{-i\omega t} |\psi(0)\rangle.$$
If you measure the energy of this, you wouldn't consider the state to be in a superposition. But if you measure the position, your state is not a position eigenstate and you could describe it as a superposition of position eigenstates. After that measurement, you are in a position eigenstate, which is not an energy eigenstate, and unitary evolution will do more to this state than just add a phase factor.


text:
Q: How prove this $\cot(\pi/15)-4\sin(\pi/15)=\sqrt{15}$ I need some help with this demonstration, please
I have tried with some identities but nothing.
I wanted to use this $$\sin(\pi/15)\cdot \sin(2\pi/15)\cdots\sin(7\pi/15)=\sqrt{15}$$

A: We may prove:
$$ \cos\frac{\pi}{15}-4\sin^2\frac{\pi}{15}=\sqrt{15}\sin\frac{\pi}{15} $$
by squaring both sides. By setting $\theta=\frac{\pi}{15}$, that leads to:
$$ \frac{13}{2}-2\cos(\theta)-\frac{15}{2}\cos(2\theta)+2\cos(3\theta)+2\cos(4\theta) = \frac{15}{2}-\frac{15}{2}\cos(2\theta)$$
or to:
$$ -\cos(\theta)+\cos(3\theta)+\cos(4\theta) = \frac{1}{2} $$
so we just have to prove that $\cos(\theta)$ is a root of:
$$ p(x) = 16x^4+8x^3-16x^2-8x+1.$$
That easily follows from:
$$ \Phi_{30}(x) = x^8+x^7-x^5-x^4-x^3+x+1.$$

A: Consider the equation $$\tan5\theta=\tan\dfrac{\pi}{3}$$ which has $5$ principle solutions $$\theta=\dfrac{n\pi}{5}+\dfrac{\pi}{15}\,\,\,\,\,\,\,\,n=0, 1, 2, 3, 4.$$ Therefore $\tan\dfrac{\pi}{15}$ is a root of the equation $$t^5-5\sqrt3t^4-10t^3+10\sqrt3t^2+5t-\sqrt3=0.$$ If we can find $\tan\dfrac{\pi}{15}$ using above equation we just have to show that $$\dfrac{1}{t}-\dfrac{4t}{\sqrt{t^2+1}}=\sqrt{15}.$$ After solve the above equation, I got  that $$\color{Green}{\tan\dfrac{\pi}{15}=\sqrt{23-10\sqrt5-2\sqrt{255-114\sqrt5}}=\dfrac{3\sqrt3}{2}-\dfrac{\sqrt{15}}{2}-\dfrac{\sqrt{50-22\sqrt5}}{2}}.$$

A: If $\cot A-4\sin A=\pm\sqrt{15}$
Multiplying both sides by $\sin A$ which is clearly $\ne0,$
$\pm\sqrt{15}\sin A=\cos A-4\sin^2A=\cos A-4(1-\cos^2A)$
$\pm\sqrt{15}\sin A=4\cos^2A+\cos A-4$
Squaring both sides, $15(1-\cos^2A)=(4\cos^2A+\cos A-4)^2$
$\iff16\cos^4A+8\cos^3A-16\cos^2A-8\cos A+1=0\  \ \ \  (1)$
$\dfrac\pi{15}=12^\circ$ and as $\cos5\cdot\left(12^\circ\right)=\dfrac12$
and $\cos5y=16\cos^5y-20\cos^3y+5\cos y$
and $\cos5y=\dfrac12=\cos60^\circ$
$\implies5y=360^\circ m\pm60^\circ\iff y=72^\circ m\pm12^\circ$ where $m$ is any integer
So, the roots of $16\cos^5y-20\cos^3y+5\cos y=\dfrac12\iff32\cos^5y-40\cos^3y+10\cos y-1=0$
are $\cos y$ where $y=72^\circ m+12^\circ$ where $m\equiv0,1,2,3,4\pmod5$
But $\cos\left[72^\circ\cdot4+12^\circ\right]=\cdots=\dfrac12$
Now $\dfrac{32\cos^5y-40\cos^3y+10\cos y-1}{2\cos y-1}=16\cos^4y+8\cos^3y-16\cos^2y-8\cos y+1$
So, the roots of $16\cos^4y+8\cos^3y-16\cos^2y-8\cos y+1=0\ \ \ \  (2)$ (which is same as $(1)$)
are $\cos y$ where $y=72^\circ m+12^\circ$ where $m\equiv0,1,2,3\pmod5$
Now $\sin\left[72^\circ\cdot1+12^\circ\right]>0$ and
 $\cot\left[72^\circ\cdot1+12^\circ\right]<\cot60^\circ<\sqrt{15}$
$\sin\left[72^\circ\cdot2+12^\circ\right]=\cdots=\sin24^\circ$ and
 $\cot\left[72^\circ\cdot1+12^\circ\right]=\cdots=-\cot24^\circ<0$
$\implies\cot\left[72^\circ\cdot m+12^\circ\right]-4\sin\left[72^\circ\cdot m+12^\circ\right]=-\sqrt{15}$ for $m\equiv1,2$
$\sin\left[72^\circ\cdot3+12^\circ\right]=\cdots=-\sin48^\circ<0$ and
 $\cot\left[72^\circ\cdot3+12^\circ\right]=\cot48^\circ>0$
$\implies\cot\left[72^\circ\cdot m+12^\circ\right]-4\sin\left[72^\circ\cdot m+12^\circ\right]=\sqrt{15}$ for $m\equiv0,3$


text:
Q: Как настроить автоматическое форматирование кода в vs code? Чтобы не нажимать каждый раз SHIFT+ALT+F. А при редактировании кода он сам автоматически форматировался. У меня уже такое было, но у vscode слетели настройки и плагины, забыл как настроить.
PS    Settings->
    editor.formatOnType - Format после ввода строки
    editor.formatOnSave - Format на сохранении
    editor.formatOnPaste - Format на вставку.

не помогает

A: Найболее популярная штука - Prettier.  его можно настроить форматировать по сохранению документа.
prettier
Добавляешь в  корень проекта файл .prettierrc
с нужными параметрами, например:
{
  "printWidth": 80,
  "tabWidth": 4,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "all",
  "bracketSpacing": true,
  "jsxBracketSameLine": false,
  "arrowParens": "always"
}


text:
Q: Dynamically Add Fields in Access Saved Query I have a ComboBox named ComboBox_Calculations in my program that is filled with calculations (ex. Current_Ratio, Total_Debt_To_Assets_Ratio).  ComboBox_Calculations is actually populated by using the contents of a field in a tabled called Criteria in my Access Database.
I need to create a saved query called Calculations_Quarterly.  The query needs to have fields of Ticker, [Year], Period and then one field for every item in ComboBox_Calculations.  So for this example I would also need fields named Current_Ratio and Total_Debt_To_Assets_Ratio.
Here is what my tables look like so far:
Criteria

Calculations_Quarterly

Here is the code I have that adds one field at a time (in this case Current_Ratio.  But I do not know how add a column for every item in ComboBox_Calculations
con.Open()
    Dim dr As OleDbDataReader
    Dim cmd6 As New OleDb.OleDbCommand("SELECT Calculation, [Interval], Formula FROM Criteria", con)
    dr = cmd6.ExecuteReader
    dr.Read()
    Dim Calculation = dr("Calculation").ToString
    Dim Interval = dr("Interval").ToString
    Dim Formula = dr("Formula").ToString
    Dim Where_Statement As String
    If Interval = "Daily" Then
        Where_Statement = "WHERE Historical_Stock_Prices.[Date] < " & DateTime.Now.Date & ""
    ElseIf Interval = "MRQ" Then
        Where_Statement = "WHERE Income_Statements.Period < 5"
    ElseIf Interval = "TTM" Then
        Where_Statement = "WHERE Income_Statements.Period < 5"
    ElseIf Interval = "5 Year" Then
        Where_Statement = "WHERE Income_Statements.Period = 5"
    Else
        Where_Statement = ""
    End If

    Try
        Dim cmd2 As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)
        cmd2.ExecuteNonQuery()
    Catch ex As Exception
    Finally
        Dim cmd2a As OleDbCommand = New OleDbCommand("DROP PROCEDURE " & Calculation & "", con)
        cmd2a.ExecuteNonQuery()
        Dim cmd2b As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)
        cmd2b.ExecuteNonQuery()
    End Try
con.Close

A: I couldnt find the name of you combobox or how it is filled so assuming it is named Combo1, and you filled it using Combo1.Items.Add("..."), you would want something like this:
Dim sb as new System.Text.StringBuilder("")
For each s as string in Combo1.Items
  sb.Append("," & s)
Next

And then in your SQL:
Dim cmd2 As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & sb.ToString & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)


text:
Q: PowerShell About files, format to print I want to print the "about" files of PowerShell (official  online here). the text does not wrap, but lines are separated manually. It's hard work to deal with it.
There any source where data appears in the design "normal" for Print / Web?


text:
Q: Image fromarray is showing a greyed out image I am taking an array from a camera, thresholding the values and want to save the new image. I am using PIL.Image.fromarry() to turn an array into an image but I am only seeing greyed out images. The image is there because when I import into another program I can see what I want. When I show the image with plt.show(data) that is how I would like to see the image. How can I change the color values?
from flirpy.camera.lepton import Lepton
import matplotlib.pyplot as plt
import numpy as np
import cv2
from PIL import Image as im

camera = Lepton()

for i in range(5):
    image = camera.grab()
    cimage = np.around(image/100 - 273.15, 2)
    cimage = np.where(cimage < 20, 20, cimage)
    cimage = np.where(cimage > 30, 30, cimage)

    data = im.fromarray(cimage.astype(np.uint8),'L')
    data.save(f'test_{i:04}.png')
    plt.imshow(data)
    plt.show()

camera.close()

Matplotlib:

PIL:

A: Matplotlib applies a colormap to your image and, under certain circumstances also scales the values to the full colour range. PIL doesn't do that, so if you give it a greyscale image (single channel) with all the values in the range 20..30, it will come out black, because it really expects values in the range 0..255 and it doesn't colorise the grey for you either.
Here's how you can convert a Matplotlib cmap into a palette and push it into a PIL Image:
#!/usr/bin/env python3

import matplotlib.pyplot as plt
from PIL import Image, ImageMath

def cmap2palette(cmapName='viridis'):
    """Convert a Matplotlib colormap to a PIL Palette"""
    cmap = plt.get_cmap(cmapName)
    palette = [int(x*255) for entry in cmap.colors for x in entry]
    return palette

# Generate a linear ramp
im = Image.linear_gradient('L')
im.save('DEBUG-ramp.png')            # just debug, not required

# Generate the viridis Matplotlib colourmap push into our PIL Image
pal = cmap2palette('viridis')
im.putpalette(pal)
im.save('DEBUG-viridis.png')

# Just for fun...

# Generate the inferno Matplotlib colourmap push into our PIL Image
pal = cmap2palette('inferno')
im.putpalette(pal)
im.save('DEBUG-inferno.png')

# Now with your image
im = Image.open('w9jUR.png')

# Contrast-stretch to full range
gMin, gMax = im.getextrema()
print(F'Greyscale min: {gMin}, greyscale max: {gMax}')
im = ImageMath.eval('int(255*(g-gMin)/(gMax-gMin))', g=im, gMin=gMin, gMax=gMax).convert('L')

# Generate the viridis Matplotlib colourmap push into our PIL Image
pal = cmap2palette('viridis')
im.putpalette(pal)
im.save('DEBUG-result.png')

That gives this as the input greyscale image:

and this as the result with the viridis and inferno colormaps:

Note also that you don't need to make 2 passes over your image to clip it to the range 20..30 like this:
cimage = np.where(cimage < 20, 20, cimage)
cimage = np.where(cimage > 30, 30, cimage)

You should be able to use np.clip():
np.clip(cimage, 20, 30, out=cimage)

If we apply the code above to your image:


text:
Q: JavaScript Build Arrays from Array I currently have an array that has 2 levels. I am attempting to build two new arrays from the initial array but seem to be stuck with the method to use. I have attempted a forEach(), while loop, as well as push to no avail.
My current array structure:
[
  {
    "attributes": {
      "Summary": 10,
      "class": "Blue"
    }
  },
  {
    "attributes": {
      "Summary": 63,
      "class":"Red"
    }
  }
]

I am looking to build two arrays, namely one for summary values, and one for class values.
Are my approaches of a forEach or while loop on the correct path?

A: If you have an array and want to transform that into another array, the simplest way is to use map (which basically creates a new array containing the results of running each element through a function):
const arr = [
  {
    "attributes": {
      "Summary": 10,
      "class": "Blue"
    }
  },
  {
    "attributes": {
      "Summary": 63,
      "class":"Red"
    }
  }
];
const summaries = arr.map(e => e.attributes.Summary);
const classes = arr.map(e => e.attributes.class);

A: If you want to accomplish this using forEach, here's one way to do it:

const aryInitial = [
  {
    "attributes": {
      "Summary": 10,
      "class": "Blue"
    }
  },
  {
    "attributes": {
      "Summary": 63,
      "class":"Red"
    }
  }
];
let arySummary = [];
let aryClass = [];

aryInitial.forEach((obj)=>
{
  arySummary.push(obj.attributes.Summary);
  aryClass.push(obj.attributes.class);
});
console.log("Summary Array:",arySummary);
console.log("Class Array:",aryClass);


text:
Q: ASP.Net MVC 5 when changing the class data annotations it gives exception error? I created one Model class Employee
public class Employee
{

    public int ID { get; set; }
    [DisplayName("Employee Name")]
    [Required(ErrorMessage = "Employee Name Is Required") ]
    public string Name { get; set; }
    public int Email { get; set; }
    public double Salary { get; set; }
    public int Address { get; set; }

}

when I run the application it worked fine after that when I saw that field Address is Int so I
changed it to String or :
public class Employee
{

    public int ID { get; set; }
    [DisplayName("Employee Name")]
    [Required(ErrorMessage = "Employee Name Is Required") ]
    public string Name { get; set; }
    public string Email { get; set; }
    public double Salary { get; set; }
    public string Address { get; set; }

}

when I run the application it gives the following error:
An exception of type 'System.InvalidOperationException' occurred in ProductApps.dll but was not  handled in user code

Additional information: The model backing the 'ProductContext' context has changed since the  database was created. Consider using Code First Migrations to update the database    (http://go.microsoft.com/fwlink/?LinkId=238269).

A: The reason you're experiencing this exception is because by making a change to the property type within your entity, Entity Framework needs to update the database to reflect your changes.
In this instance it needs to update the Email column within the Employee table to be of type int instead of string. And in order to force Entity Framework to do this you need to run the necessary console commands.
To run a console command go to Tools > Nuget Package Manager > Package Manager Console and run the following:
Add-Migration UpdatedEmailType followed by Update-Database. If you experience an error saying that migrations isn't enabled then you'll need to run the following command to enable the database migriations: Enable-Migrations.
Note:
Whilst Database Migrations can be a great help in creating a database schema, at times it can be hard work. If you're still experiencing issues then you can always disable migrations and update the database manually within SQL Server Management Studio or Visual Studio's database manager tool.


text:
Q: C++98: Compile Time Detect floating point type So you can make a fake is_integral in C++98 with the following:
template <typename T>
struct is_integral
{
  static const bool value;
};

template <typename T>
const bool is_integral<T>::value = std::numeric_limits<T>::is_integer;

easy enough...is there anything similar you can do for floating point (without getting a boost dependency?)

A: The C++ standard* states:

Specializations shall be provided for each fundamental type, both floating point and integer, including bool.

(*- I am having trouble finding an earlier draft of the standard. If someone can lend a hand here, it'd be much appreciated.)
Since std::numeric_limits provides definitions for is_integer and is_specialized, you can combine the information to deduce whether or not a type is a floating point type.
For example:
template <typename T>
struct is_floating_point
{
    static const bool value;
};

template <typename T>
const bool is_floating_point<T>::value =
    std::numeric_limits<T>::is_specialized &&  // Is fundamental arithmetic type...
    !std::numeric_limits<T>::is_integer;       // ...that is not an integer

A: Since there are only three floating point types (per C++98 §3.9.1/8), it's not hard to enumerate them:
template <typename T>
struct is_floating_point {
  enum { value = 0 };
};

template <>
struct is_floating_point<float> {
  enum { value = 1 };
};

template <>
struct is_floating_point<double> {
  enum { value = 1 };
};

template <>
struct is_floating_point<long double> {
  enum { value = 1 };
};

A: Something along the lines of your is_integral trick:
#include <limits>
#include <iostream>

template <typename T>
struct is_floating_point
{
  static const bool value;
};

// is a fundamental type (i.e. not a user defined type) but not an integer
template <typename T>
const bool is_floating_point<T>::value =
!std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_bounded;

struct Obj
{
};

int main()
{
    std::cout << is_floating_point<float>::value << std::endl;        // 1
    std::cout << is_floating_point<int>::value << std::endl;          // 0
    std::cout << is_floating_point<Obj>::value << std::endl;          // 0
    std::cout << is_floating_point<bool>::value << std::endl;         // 0
    std::cout << is_floating_point<double>::value << std::endl;       // 1
    std::cout << is_floating_point<long double>::value << std::endl;  // 1

    // this would compile since it's an array of size 1
    int Y[is_floating_point<float>::value] = { };
    // this wouldn't compile since it's an array of size 0
    int N[is_floating_point<int>::value] = { };
}


text:
Q: Injective and Surjective Function (Mapping) I had a question about mapping, for example:
what do they mean by $R \times R \to R$? is that not just $R \to R$?

A: When we write $f: \mathbb{R} \times \mathbb{R} \to \mathbb{R}$ we mean that $f$ takes pairs $(x,y)$ to $\mathbb{R}$ where $x,y \in \mathbb{R}$. For example, consider the map $f(x,y) = x$ then $f:\mathbb{R} \times \mathbb{R} \to \mathbb{R}$.


text:
Q: Axon query maximum size returning I have an Axon Query that collects List of Objects from a repository.
I worry about a case when I have too big data returning.
Is there some restrictions on it? And how to handle extra data ?

A: The answer is knowing maximum gRPC message size, which is 4,2 mB
To increase maximum gRPC message size: AxonServer configuration axon.axonserver.max-message-size in the client configuration
And maximum query timeout is 5 minutes You can increase this timeout by setting the property axoniq.axonserver.default-command-timeout. The value of the property is the timeout in milliseconds.


text:
Q: Looking for an alternative SQL statement Given the following table with 2 columns:
c1      c2
------------
a1   |  b1
a1   |  b1
a2   |  b2
a2   |  b3
a3   |  b3

I want to return those values from column c2 where the value of c2 column appears multiple times for the same c1 value. I am doing the following SQL query to return the required result:
SELECT DISTINCT ( c2 ) AS c
  FROM ( SELECT c1 , c2 , COUNT (*) AS rowcount
           FROM table
          GROUP BY c1 , c2 HAVING rowcount > 1 )

Result:
 c
---
 b1

Is there any alternative SQL statement of the above query?

A: Based on your description, you can use:
select distinct c1
from (select t.*, count(*) over (partition by c2) as cnt
      from t
     ) t
where cnt >= 2;

Based on your sample results:
select c1
from t
group by c1
having count(*) >= 2;

And based on the revised question:
select c2
from t
group by c2
having count(*) >= 2;

A: Use count in having clause instead of using subquery:-
select c1
from table
group by c1
having count(c2) > 1

A: Most answers above will work if you want all the values in c1 that appear more than once in the table (even with the same value on c2).
If you want to measure only values of c1 that may have multiple DISTINCT values on c2 you can use:
SELECT c1
FROM table
GROUP BY c1
HAVING COUNT(DISTINCT c2) > 1


text:
Q: How should I start a new Activity, after the application is done fetching and passing the fetched data to it? In my app, I use a Contacts database and display those contacts using a RecyclerView . When I click on a contact, I want to fetch its data from the tables in the DB, and load them in a new Activity, ContactCard. I have an AsyncTask() which fetches the PhoneNumber objects that match the selected contactId, but I will also need to retrieve the Address and Email objects from the other tables.
I would like to be able to start the activity after all the relevant data is fetched, and I tried doing this in the activity with the Contacts RecyclerView, but the application crashes as the data has not been fetched yet.
I can call the new activity using an intent, but how can I ensure data from different tables is fetched first, before I start the new activity (which effectively displays this data)?
Some of my code:
public class PhoneNumberRepository {

    private WorksideDatabase worksideDatabase;
    private List<PhoneNumber> returnedNumbers;
    private Context mContext;

    public PhoneNumberRepository(Context context) {
        String DB_NAME = "workside_database";
        worksideDatabase = Room.databaseBuilder(context, WorksideDatabase.class, DB_NAME).build();
        mContext = context;
    }

    public List<PhoneNumber> fetchPhoneNumbers(final int id) {

        new AsyncTask<Integer, Void, List<PhoneNumber>>() {
            @Override
            protected List<PhoneNumber> doInBackground(Integer... ids) {

                returnedNumbers = worksideDatabase.phoneNumberDao().getPhoneNumbersById(id);

                System.out.println(returnedNumbers);

                for (PhoneNumber pn : returnedNumbers) {
                    System.out.println("Number: " + pn.getPhoneNumber());
                }

                return returnedNumbers;
            }

            // This runs in UI when background thread finishes
            @Override
            protected void onPostExecute(List<PhoneNumber> result) {
                super.onPostExecute(result);

                System.out.println("Entered onPostExecute of fetchPhoneNumbers");

                //                for (PhoneNumber pn : result) {
                //                    Toast.makeText(mContext, pn + "", Toast.LENGTH_SHORT).show();
                //                }
            }
        }.execute();

        return returnedNumbers;
    }

    public List<PhoneNumber> getPhoneNumbers(int id) {
        return fetchPhoneNumbers(id);
    }
}

ContactsFragment:
     adapter.setOnItemClickListener(
                contact -> {
     Intent viewContact = new Intent(getActivity(), WorksideContactCard.class);
     viewContact.putExtra(WORKSIDE_CONTACT, contact);

     PhoneNumberRepository phoneNumberRepository =
         new PhoneNumberRepository(getActivity().getApplicationContext());

     List<PhoneNumber> phoneNumberList;

     phoneNumberList = phoneNumberRepository.getPhoneNumbers(contact.getId());

     ArrayList<PhoneNumber> arrlistPhoneNumbers =
                                new ArrayList<>(phoneNumberList);
                        viewContact.putParcelableArrayListExtra(
                                WORKSIDE_CONTACT_PHONE_NO, arrlistPhoneNumbers);

      startActivity(viewContact);
}

A: You can do this when you click on an item start the asyntask like this
 adapter.setOnItemClickListener(
                contact -> {
     PhoneNumberRepository phoneNumberRepository =
     new PhoneNumberRepository(getActivity().getApplicationContext());

 List<PhoneNumber> phoneNumberList;

 phoneNumberRepository.getPhoneNumbers(contact.getId());

}

and change your PhoneNumberRepository to this class
public class PhoneNumberRepository {

        private WorksideDatabase worksideDatabase;
        private List<PhoneNumber> returnedNumbers;
        private Context mContext;

        public PhoneNumberRepository(Context context) {
            String DB_NAME = "workside_database";
            worksideDatabase = Room.databaseBuilder(context, WorksideDatabase.class, DB_NAME).build();
            mContext = context;
        }

        public void fetchPhoneNumbers(final int id) {

            new AsyncTask<Integer, Void, List<PhoneNumber>>() {
                @Override
                protected List<PhoneNumber> doInBackground(Integer... ids) {

                    returnedNumbers = worksideDatabase.phoneNumberDao().getPhoneNumbersById(id);

                    System.out.println(returnedNumbers);

                    for (PhoneNumber pn : returnedNumbers) {
                        System.out.println("Number: " + pn.getPhoneNumber());
                    }

                    return returnedNumbers;
                }

                // This runs in UI when background thread finishes
                @Override
                protected void onPostExecute(List<PhoneNumber> result) {
                    super.onPostExecute(result);
 Intent viewContact = new Intent(context, WorksideContactCard.class);
    ArrayList<PhoneNumber> arrlistPhoneNumbers =
                                new ArrayList<>(result);
                        viewContact.putParcelableArrayListExtra(
                                WORKSIDE_CONTACT_PHONE_NO, arrlistPhoneNumbers);

      context.startActivity(viewContact);
                    System.out.println("Entered onPostExecute of fetchPhoneNumbers");

                }
            }.execute();

        }

        public void getPhoneNumbers(int id) {
            return fetchPhoneNumbers(id);
        }
    }

A: store the contacts in a list in the doInBackground() method and start an intent to the new activity in the onPostExecute() method and with this intent pass the list of contacts as intent.extra() variables, retrieve and use them in the called activity.

A: Change your repository class to something like this
public class PhoneNumberRepository {

    private WorksideDatabase worksideDatabase;
    private List<PhoneNumber> returnedNumbers;
    private Context mContext;
    private boolean dataDownloaded;

    public PhoneNumberRepository(Context context) {
        String DB_NAME = "workside_database";
        worksideDatabase = Room.databaseBuilder(context, WorksideDatabase.class, DB_NAME).build();
        mContext = context;
    }

    public List<PhoneNumber> fetchPhoneNumbers(final int id) {

        new AsyncTask<Integer, Void, List<PhoneNumber>>() {
            @Override
            protected List<PhoneNumber> doInBackground(Integer... ids) {

                returnedNumbers = worksideDatabase.phoneNumberDao().getPhoneNumbersById(id);

                System.out.println(returnedNumbers);

                for (PhoneNumber pn : returnedNumbers) {
                    System.out.println("Number: " + pn.getPhoneNumber());
                }

                return returnedNumbers;
            }

            // This runs in UI when background thread finishes
            @Override
            protected void onPreExecute(List<PhoneNumber> result) {
                //set flag to false when download starts
               dataDownloaded = false;
            }

            // This runs in UI when background thread finishes
            @Override
            protected void onPostExecute(Object obj) {
                super.onPostExecute(result);

                //set flag to true once download completes, you can also check if response is null and update it accordingly
                dataDownloaded = true;

                System.out.println("Entered onPostExecute of fetchPhoneNumbers");

                //                for (PhoneNumber pn : result) {
                //                    Toast.makeText(mContext, pn + "", Toast.LENGTH_SHORT).show();
                //                }
            }
        }.execute();

        return returnedNumbers;
    }

    public List<PhoneNumber> getPhoneNumbers(int id) {
        return fetchPhoneNumbers(id);
    }

    public boolean isDataDownloaded(int id) {
        return dataDownloaded;
    }
}

Use this function in onItemClick() whether your data is downloaded or not
if(phoneNumberRepository.isDataDownloaded()) {
   //code to fetch data from phonenumberrepo and start activity
}


text:
Q: How to make users select their friends and post on their wall in facebook I know this has been asked several times before, but Facebook changes its api often so comes the necessity to ask this question again.
I have an iframe application, how to make users select their friends and post on their wall the message which comes out of my application in facebook using FB.ui ? or some other better method.

A: The simplest way to do this is via the "send" widget. http://developers.facebook.com/docs/reference/plugins/send/
If you have the stream_publish right from the user, you can also fetch his friends, let the user selects the friends he wishes to post to, and than in a loop you post to this users via graph api on the wall. (without the stream_publish right, you would have to open a fb.ui for EACH of the friends the user wants to post to.

A: for share to friend:
            FB.ui({
                method: "apprequests",
                display: "iframe",
                message: 'take a tour to my app',
                data: '123'
            });

for post to wall:
        FB.ui({
            method: 'feed',
            link: 'http://myapp.com',
            display: 'iframe',
            message: 'take a tour to my app',
            name: 'Click to view my app',
            caption: 'Hello my app'

        });


text:
Q: How to get rid of "project/app_name/src/public-api" path of an Angular dependency in the VSCode intellisense? I created a new Angular project with one application project and a library project. When I tried to import dependencies/components of the library project into the main application project using VSCode's intellisense, it's including the path *project/app_name/src/public-api" instead of just the name of the library/project.

How do I configure it in the angular.json so that it only shows the library name? Here's my angular.json config. I didn't do anything to it, it's just the default generated by the Angular CLI.

A: You can use path mapping by configuring your tsconfig.json as follows:
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "public-api/*": ["../projects/app_name/src/public-api/*"],
    }
  }
}


text:
Q: swagger-codegen-maven-plugin generating @Schema annotation for generated request models class fields instead fo @JsonProperty Using:
<build>
<plugins>
  <plugin>
    <groupId>io.swagger.codegen.v3</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <executions>
      <execution>
        <id>client-w</id>
        <goals>
          <goal>generate</goal>
        </goals>
        <configuration>
          <inputSpec>${project.basedir}/src/main/resources/api/w/w-swagger.yml</inputSpec>
          <output>${project.build.directory}/generated-sources/swagger</output>
          <language>jaxrs-cxf-client</language>
          <apiPackage>com.w.w.swagger.api</apiPackage>
          <modelPackage>com.w.w.swagger.model</modelPackage>
          <generateApiTests>false</generateApiTests>
          <generateModelTests>false</generateModelTests>
          <generateModelDocumentation>false</generateModelDocumentation>
          <skipOverwrite>true</skipOverwrite>
          <configOptions>
            <dateLibrary>java8-localdatetime</dateLibrary>
            <java8>true</java8>
          <sourceFolder>swagger</sourceFolder>
          </configOptions>
        </configuration>
      </execution>
    </executions>
  </plugin>
</plugins>

generates...
  @Schema(required = true, description = "")
  private CreateAlarmReq createAlarmReq = null;
 /**
   * Get createAlarmReq
   * @return createAlarmReq
  **/
  @JsonProperty("CreateAlarmReq")
  public CreateAlarmReq getCreateAlarmReq() {
    return createAlarmReq;

The thing is, if I create & use at the controller a custom model with all request body json properties as @JsonProperty instead of @Schema (I mean the class fields instead of getters), it works. Otherwise, with swagger pluggin generated models, @RequestBody fails to parse json body thworing a 415 Unsupported Media Type.
THIS WORKS (done manually):
  @JsonProperty("CreateAlarmReq"))
  private CreateAlarmReq createAlarmReq = null;

THIS DOES NOT WORK (generated by swagger-codegen-maven-plugin):
  @Schema(required = true, description = "")
  private CreateAlarmReq createAlarmReq = null;

  @JsonProperty("CreateAlarmReq")
  public CreateAlarmReq getCreateAlarmReq() {
    return createAlarmReq;

YML (fields changed for privacy):
swagger: '2.0'
info:
  title: ManageBrie
  description: This interface manages creation and modification of Brie
  version: '1.0'
host: api.host.com
basePath: /rest/ManageBrie
schemes:
  - http
consumes:
  - application/json
produces:
  - application/json
securityDefinitions:
  basicAuth:
    type: basic
    description: HTTP Basic Authentication. Works over `HTTP` and `HTTPS`
paths:
  /createBrie:
    post:
      tags:
        - ManageBrie
      security:
        - basicAuth: []
      operationId: createBrieResponseMessage
      summary: This operation creates one or several Brie
      description: ''
      deprecated: false
      parameters:
        - name: createBrie
          in: body
          required: true
          description: ''
          schema:
            $ref: '#/definitions/CreateBrieMessage'
      responses:
        '200':
          description: success
          schema:
            $ref: '#/definitions/CreateBrieResponseMessage'
        '400':
          description: bad request
          schema:
            $ref: '#/definitions/FaultResponseMessage'
        '500':
          description: internal server error
          schema:
            $ref: '#/definitions/FaultResponseMessage'
  /updateBrie:
    post:
      tags:
        - ManageBrie
      security:
        - basicAuth: []
      operationId: updateBrieResponseMessage
      summary: This operation update one or several Brie
      description: ''
      deprecated: false
      parameters:
        - name: updateBrie
          in: body
          required: true
          description: ''
          schema:
            $ref: '#/definitions/UpdateBrieMessage'
      responses:
        '200':
          description: Success
          schema:
            $ref: '#/definitions/UpdateBrieResponseMessage'
        '400':
          description: Success
          schema:
            $ref: '#/definitions/FaultResponseMessage'
        '500':
          description: Success
          schema:
            $ref: '#/definitions/FaultResponseMessage'
definitions:
  CreateBrieMessage:
    description: ''
    required:
      - CreateBrieReq
    type: object
    properties:
      CreateBrieReq:
        $ref: '#/definitions/CreateBrieReq'
  CreateBrieResponseMessage:
    description: ''
    required:
      - CreateBrieReq
    type: object
    properties:
      CreateBrieReq:
        $ref: '#/definitions/CreateBrieRes'
  UpdateBrieMessage:
    description: ''
    required:
      - UpdateBrieReq
    type: object
    properties:
      UpdateBrieReq:
        $ref: '#/definitions/UpdateBrieReq'
  UpdateBrieResponseMessage:
    description: ''
    required:
      - UpdateBrieReq
    type: object
    properties:
      UpdateBrieReq:
        $ref: '#/definitions/UpdateBrieRes'
  CreateBrieReq:
    description: ''
    required:
      - technicalCamembert
      - Brie
    type: object
    properties:
      technicalCamembert:
        description: 'technical context'
        $ref: '#/definitions/technicalCamembert'
      Brie:
        description: 'list of Brie to create'
        type: array
        minItems: 1
        items:
          $ref: '#/definitions/BrieCreate'
  CreateBrieRes:
    description: ''
    required:
      - results
    type: object
    properties:
      results:
        description: 'results'
        type: string
  UpdateBrieReq:
    description: ''
    required:
      - technicalCamembert
      - Brie
    type: object
    properties:
      technicalCamembert:
        description: 'technical context'
        $ref: '#/definitions/technicalCamembert'
      Brie:
        description: 'list of Brie to update'
        type: array
        minItems: 1
        items:
          $ref: '#/definitions/BrieUpdate'
  UpdateBrieRes:
    description: ''
    required:
      - results
    type: object
    properties:
      results:
        description: 'results'
        type: string
  technicalCamembert:
    description: 'technical context'
    required:
      - sender
      - recipient
      - flowId
      - flowName
      - flowVersion
      - sendDate
      - BrieCount
    type: object
    properties:
      sender:
        description: 'sender name = USA'
        type: string
      recipient:
        description: 'recipient name = VXZK'
        type: string
      flowId:
        description: 'flowId is used when a flow is sent twice'
        type: string
      flowName:
        description: 'flow name = Création Briees'
        type: string
      flowVersion:
        description: 'flow version = 1.0'
        type: string
      ackFlag:
        description: 'acknowledgement flag'
        type: boolean
      ackMode:
        description: 'acknowledgement send mode (mail, ...)'
        type: string
      sendDate:
        description: 'send date, format DD/MM/AAAA HH:MM:SS'
        type: string
      BrieCount:
        description: 'number of Brie'
        type: string
  BrieCreate:
    description: 'Brie creation'
    required:
      - idBrie
      - dateBrie
      - sourceBrie
      - typeBrie
      - typeBastille
      - croissantTurcs
      - regionalDirectionPapirus
      - etatSoleil
      - foiegras
      - Turc
      - login
      - seR
    type: object
    properties:
      idBrie:
        description: 'unique identifier for the Brie'
        type: string
      dateBrie:
        description: "Brie's detection date (precision : 15min)"
        type: string
      sourceBrie:
        description: "Brie's source (PPP disconnection or DHCP session)"
        type: string
      typeBrie:
        description: "Brie's type (network failure or deterioration)"
        type: string
      idGroupBrie:
        description: "Brie's USA group id"
        type: string
      typeBastille:
        description: "Brie's USA group id"
        type: string
      croissantTurcs:
        description: 'main impacting Turc'
        type: string
      regionalDirectionPapirus:
        description: "impacting Turc's regional direction Papirus"
        type: string
      center:
        description: "impacting Turc's center Papirus"
        type: string
      reign:
        description: 'name of the reign impacted'
        type: string
      etatSoleil:
        description: 'etatSoleil Papirus of the impacted reign'
        type: string
      reignInseePapirus:
        description: "impacted reign's insee Papirus"
        type: string
      foiegras:
        description: 'adsf site'
        type: string
      Turc:
        description: 'list of Turcs concerned by the Brie'
        type: array
        minItems: 1
        items:
          $ref: '#/definitions/TurcCreate'
      login:
        description: 'list of customers ND having RossetaPiramid = 1'
        type: array
        minItems: 1
        items:
          $ref: '#/definitions/Login'
      seR:
        description: "Brie's sequential number"
        type: string
  TurcCreate:
    description: 'Turc creation'
    required:
      - name
      - type
    type: object
    properties:
      name:
        description: 'Turc name'
        type: string
      type:
        description: 'Turc type (Fripouille, ...)'
        type: string
      impacting:
        description: 'whether the Turc is impacting'
        type: boolean
      tourLouvre:
        description: 'whether the Turc is secondary impacting'
        type: boolean
      letempsdesfleurs:
        description: 'number of customers with issue at the time of the Brie'
        type: string
      louismoins16:
        description: 'number of customers connected to the Turc at the time of the Brie'
        type: string
      daleatucuerpoalegriamacarena:
        description: 'number of customers connected to the Turc during the last 7 days'
        type: string
  Login:
    description: 'login'
    required:
      - loginTest
    type: object
    properties:
      loginTest:
        description: 'customer sadf for a customer with RossetaPiramid=1'
        type: string
  BrieUpdate:
    description: 'Brie update'
    required:
      - idBrie
      - dateUpdateBrie
      - Turc
      - seR
    type: object
    properties:
      idBrie:
        description: 'unique identifier for the Brie'
        type: string
      dateUpdateBrie:
        description: "Brie's update date (precision : 15min)"
        type: string
      typeBrie:
        description: "Brie's type (network failure or deterioration)"
        type: string
      idGroupBrie:
        description: "Brie's USA group id"
        type: string
      statusClosed:
        description: "closing type (administrative or normal)"
        type: string
      idBrieMaster:
        description: "substituting id for a closed Brie"
        type: string
      Turc:
        description: 'list of Turcs concerned by the Brie'
        type: array
        minItems: 1
        items:
          $ref: '#/definitions/TurcUpdate'
      seR:
        description: "Brie's sequential number"
        type: string
  TurcUpdate:
    description: 'Turc update'
    required:
      - name
      - type
    type: object
    properties:
      name:
        description: 'Turc name'
        type: string
      type:
        description: 'Turc type (Fripouille, ...)'
        type: string
      impacting:
        description: 'impacting Turc indicator'
        type: boolean
      tourLouvre:
        description: 'impacting secondary Turc indicator'
        type: boolean
      letempsdesfleurs:
        description: 'number of customers with issue at the time of the Brie'
        type: string
      louismoins16:
        description: 'number of customers connected to the Turc at the time of the Brie'
        type: string
      daleatucuerpoalegriamacarena:
        description: 'number of customers connected to the Turc during the last 7 days'
        type: string
      restore:
        description: "Turc's State (f -> not restore t-> restore)"
        type: string
      dateRestore:
        description: "Turc's restore date (precision : 15min)"
        type: string
  FaultResponseMessage:
    description: 'fault response message'
    required:
      - fault
    type: object
    properties:
      fault:
        description: 'fault'
        type: array
        minItems: 0
        items:
          $ref: '#/definitions/Fault'
  Fault:
    description: 'fault'
    required:
      - idBrie
      - faultLabel
    type: object
    properties:
      idBrie:
        description: 'unique identifier for the Brie'
        type: string
      faultLabel:
        description: 'litteral description of the fault name'
        type: string

I thought it was 'swagger: 2.0' in .yml clashing with io.swagger.codegen.v3 maven plugin but after converting to openapi3 at https://editor.swagger.io/ the same result happened:
HTTP Status 415 – Unsupported Media Type

What is going on? Any idea? Thanks.


text:
Q: wp - all the pages by title - not just the first one How can I get all pages that meet the criteria?
get_page_by_title()
The above only brings the first one. Is it possible for get_page_by_title to return an array of pages?

A: Here is the code to loop all pages with title:
<?php
 $args = array(
    'sort_order' => 'asc',
    'sort_column' => 'post_title',
    'hierarchical' => 1,
    'exclude' => '',
    'include' => '',
    'meta_key' => '',
    'meta_value' => '',
    'authors' => '',
    'child_of' => 0,
    'parent' => -1,
    'exclude_tree' => '',
    'number' => '',
    'offset' => 0,
    'post_type' => 'page',
    'post_status' => 'publish'
);
$pages = get_pages( $args);
    foreach ($pages as $page_data) {
         $title = $page_data->post_title;
         echo $title;
    }
?>

You can change args to filter pages.


text:
Q: Layout bug manifest on new Area51 home page I opened up the new Area51 home page and saw a small layout bug:

I'm using Chrome 9.0.597.83 beta on Ubuntu 10.10 64-bit. (But this is not a Chrome beta bug - I tried it in FF too.)

A: This is fixed now. Thanks for the report.


text:
Q: Powershell IE Automation- Can't specify textbox by ID or TagName I am trying to use powershell to enter text into two text boxes. I can enter a value into the first box, but not the second. This is due to the fact that I don't know how to isolate the second textbox as it has the same code as the first text box including things such as ID, Class, TagName, etc.
Below is my code with the URL taken out (due to work). I had initially thought to isolate the second textbox by using -ne on the value of the first since by inputting a value it differentiated the code, however this doesn't seem to work. I am new to coding so my apologies if I'm expressing myself poorly, but any help you could provide would be appreciated.
Here are two text boxes, I can enter a value into the first one using powershell but I am unable to isolate the second text box to enter a value into it. This is due to the two lines of code being identical- See second image
As you can see the two lines of code for input are identical and as such I cannot use GetElementById/TagName/Name to identify which text box I want powershell to enter the value into.
$Web = "URL"
$Internet = New-Object -ComObject InternetExplorer.Application
$Internet.visible = $true
$Internet.Navigate($web)

While($Internet.Busy -eq $true){
Start-Sleep -Seconds 1
}

$Internet.document.getElementById("filterValue").value="Number"
$link = $Internet.Document.getElementsByTagName('a') | where-object {$_.innerText -eq 'Next Prompt'}
$link.click()

While($Internet.Busy -eq $true){
Start-Sleep -Seconds 1
}
**#Question about coding starts here**

$Input = $Internet.Document.IHTMLDocument3_getElementById("filterValue")
$Input.value = "1/1/2020"

While($Internet.Busy -eq $true){
Start-Sleep -Seconds 1
}

$Input2 = $Internet.Document.IHTMLDocument3_getElementById("filterValue") | ? {$_.value -ne "1/1/2020"}
Start-Sleep -Seconds 4
$Input2.value = "1/2/2020"

A: I checked the image of HTML code and looks like there are some issues with the HTML code.

*

*The ID of the HTML element should be unique. That means there cannot be more than one element that has the same ID on a single web page.

*I also notice that the input element has / at the end of it for closing it. There are 2 more closing input tags after it. In HTML, there is no end tag for the Input element. So this is invalid HTML code.

*Verify and confirm that you are referring to the correct code for those 2 textboxes. Try to use developer tools to view the HTML for those 2 textboxes.
I suggest you contact the developer of the website and inform them about this issue.


text:
Q: macro in function declaration I'm looking at the v4l header files and I found function definitions with the following structure.
#define SOME_VAR

SOME_VAR int somefunc(int i,....);

What is the purpose of using the #define directive in such a way?
Thanks in advance

A: You can specify a calling convention or a import/export tag. For example Visual Studio you build a DLL and have some functions to export, you can reuse your header file. For compiling the export you use
#define SOME_VAR __declspec(dllexport)

on the import site you write
#define SOME_VAR __declspec(dllimport)

using only one include in both situations reduce the possible errors during updating and bug fixing of the code.
In the case you mentioned above it seems to be for future use as some platforms have other calling conventions (e.g. the pascal calling convention) than others.
Visual Studio uses a similar stub, the macro WINAPI, which is also empty.


text:
Q: Java/J2EE Internal Server Error I have a DaoHibernateImpl file which is breaking my application. Here is the code for this and its xml.
    public class OfferBankDaoHibernateImpl extends GenericDaoHibernateImpl<OfferBank, Long> implements OfferBankDao {

        static Logger log = Logger.getLogger(OfferBankDaoHibernateImpl.class);
        private ResourceManager rMgr = new ResourceManager(this);

        public List<OfferBank> findOfferBankByName(String offerBankNm) throws AppException {
            List<OfferBank> offerBanks = new ArrayList<OfferBank>();
            try {
                // offerBanks =
                // sessionFactory.getCurrentSession().createCriteria(OfferBank.class)
                // .add( Restrictions.eq("offerBankNm", offerBankNm))
                // .list();

                offerBanks = sessionFactory.getCurrentSession().createQuery("from OfferBank ob where ob.offerBankNm = '" + offerBankNm + "'").list();
            } catch (GenericJDBCException e) {
                log.error(e.getMessage(), e);
                throw new AppException(e.getMessage(), e);
            } catch (HibernateException e) {
                log.error(e.getMessage(), e);
                throw new AppException(e.getMessage(), e);
            }
            return offerBanks;
        }

        public Object[] getOfferBanks(List<String> offerBankTypes, int startPos, int endPos, List<Long> statusIds) {
            int totalRowCount = 1000000;
            try {
                if (endPos == 0) {
                    endPos = totalRowCount;
                }
                String dataSql = rMgr.get("sql.offer_bank_get_banks");
                dataSql += " " + rMgr.get("sql.offer_bank_get_banks_types_where");
                if (!statusIds.isEmpty()) {
                    dataSql += " " + rMgr.get("sql.offer_bank_get_banks_status_where");
                }
                dataSql += " " + rMgr.get("sql.offer_banks_get_banks_group_by");

                log.debug("query : " + dataSql);
                SQLQuery dataQuery = this.sessionFactory.getCurrentSession().createSQLQuery(dataSql);
                if (!statusIds.isEmpty()) {
                    dataQuery.setParameterList("offerBankStatusIds", statusIds);
                }
                dataQuery.setParameterList("offerBankTypes", offerBankTypes).setParameter("start", startPos).setParameter("end", endPos);
                List offerBankList = dataQuery.list();
                return makeOfferBankTO(offerBankList);
            } catch (RuntimeException e) {
                log.error("Error getOfferBanks(List<Long> offerBankTypes ,int startPos, int endPos, List<Long> statusIds)");
                throw e;
            }
        }

        public Object[] getOfferBanksByBanner(List<String> offerBankTypes, int startPos, int endPos, List<Long> statusIds) {
            int totalRowCount = 1000000;
            try {
                if (endPos == 0) {
                    endPos = totalRowCount;
                }
                String dataSql = rMgr.get("sql.offer_bank_get_banks_by_banner");
                dataSql += " " + rMgr.get("sql.offer_bank_get_banks_types_where");
                if (!statusIds.isEmpty()) {
                    dataSql += " " + rMgr.get("sql.offer_bank_get_banks_status_where");
                }
                dataSql += " " + rMgr.get("sql.offer_banks_get_banks_by_banner_group_by");

                log.debug("query : " + dataSql);
                SQLQuery dataQuery = this.sessionFactory.getCurrentSession().createSQLQuery(dataSql);
                if (!statusIds.isEmpty()) {
                    dataQuery.setParameterList("offerBankStatusIds", statusIds);
                }
                dataQuery.setParameterList("offerBankTypes", offerBankTypes).setParameter("start", startPos).setParameter("end", endPos);
                List offerBankList = dataQuery.list();
                return makeOfferBankTO(offerBankList);
            } catch (RuntimeException e) {
                log.error("Error getOfferBanksByBanner(List<Long> offerBankTypes ,int startPos, int endPos, List<Long> statusIds)");
                throw e;
            }
        }

        public Object[] getOfferBankById(List<Long> offerBankIds) {
            int startPos = 1;
            int endPos = 100000;
            String dataSql = rMgr.get("sql.offer_bank_get_banks");
            dataSql += " " + rMgr.get("sql.offer_bank_get_banks_ids_where");
            dataSql += " " + rMgr.get("sql.offer_banks_get_banks_group_by");
            log.debug("sql= " + dataSql);
            SQLQuery dataQuery = this.sessionFactory.getCurrentSession().createSQLQuery(dataSql);
            dataQuery.setParameterList("offerBankIds", offerBankIds).setParameter("start", startPos).setParameter("end", endPos);
            List offerBankList = dataQuery.list();
            return makeOfferBankTO(offerBankList);
        }

        private Object[] makeOfferBankTO(List offerBankList) {
            int totalRowCount = 0;
            List<OfferBankTO> offerBankTOs = new ArrayList<OfferBankTO>();
            Iterator iter = offerBankList.iterator();
            while (iter.hasNext()) {
                Object[] row = (Object[]) iter.next();
                OfferBankTO ob = new OfferBankTO();
                ob.setOfferBankId(((BigDecimal) row[0]).longValue());
                ob.setPromotionalPeriodId(((BigDecimal) row[1]).longValue());
                ob.setOfferBankName(row[2].toString());
                ob.setOfferBankStatusDesc(row[3].toString());
                if (row[4] != null) {
                    ob.setStartDate(DateFormats.dateFmt.format((Date) row[4]));
                }
                if (row[5] != null) {
                    ob.setEndDate(DateFormats.dateFmt.format((Date) row[5]));
                }
                ob.setOfferBankTypeDesc(row[6].toString());
                ob.setOfferBankTypeCd(row[7].toString());
                ob.setPromotionalPeriodNm(row[8].toString());
                ob.setTotalCount(((Integer) row[9]).intValue());
                ob.setEditingCount(((Integer) row[10]).intValue());
                ob.setFailedDeactiveCount(((Integer) row[11]).intValue());
                ob.setFailedProductionCount(((Integer) row[12]).intValue());
                ob.setFailedPreviewCount(((Integer) row[13]).intValue());
                ob.setLoadedCount(((Integer) row[14]).intValue());
                ob.setPendingCount(((Integer) row[15]).intValue());
                ob.setParkedCount(((Integer) row[16]).intValue());
                ob.setSuccessDeactivatedCount(((Integer) row[17]).intValue());
                ob.setSuccessLoadedProdCount(((Integer) row[18]).intValue());
                ob.setSuccessLoadedPreviewCount(((Integer) row[19]).intValue());
                ob.setTotalPendingCount(((Integer) row[20]).intValue());
                ob.setTotalFailedCount(((Integer) row[21]).intValue());
                totalRowCount = ((Integer) row[22]).intValue();
                if (row[24] != null)
                    ob.setMaxOfferEffectiveEndDt(DateFormats.dateFmt.format((Date) row[24]));
                if (row[25] != null)
                    ob.setMinOfferEffectiveStartDt(DateFormats.dateFmt.format((Date) row[25]));

                ob.setEndedCount(((Integer) row[26]).intValue());
                ob.setCopientDelayCount(((Integer) row[27]).intValue());
                ob.setRejectedCount(((Integer) row[28]).intValue());
                ob.setProcessingCount(((Integer) row[29]).intValue());

                if (row.length > 30) {
                    if (row[30] != null) {
                        ob.setRegionId(row[30].toString());
                    }
                    if (row[31] != null) {
                        ob.setRegionNm(row[31].toString());
                    }
                }

                offerBankTOs.add(ob);
            }
            return new Object[] { totalRowCount, offerBankTOs };
        }

        public Object[] getBankTypes() {
            List<OfferBankTypeTO> offerBankTypes = new ArrayList<OfferBankTypeTO>();
            try {
                String sql = rMgr.get("sql.offer_bank_types");
                SQLQuery query = this.sessionFactory.getCurrentSession().createSQLQuery(sql);

                List typeList = query.list();

                Iterator iter = typeList.iterator();
                while (iter.hasNext()) {
                    Object[] row = (Object[]) iter.next();
                    OfferBankTypeTO type = new OfferBankTypeTO();
                    type.setOfferBankTypeCd(row[0].toString());
                    type.setOfferBankTypeDesc(row[1].toString());
                    offerBankTypes.add(type);
                }

            } catch (RuntimeException e) {
                log.error("Error List<OfferBankType> getBankTypes()");
                throw e;
            }
            return new Object[] { offerBankTypes };
        }

        public void updateOfferBank(OfferBank offerBank, Context ctx) {

            String user = (ctx != null && ((UserContext) ctx).getUserName() != null && ((UserContext) ctx).getUserName().length() > 0) ? ((UserContext) ctx)
                    .getUserName() : SharedMessages.getString("user.default");

            offerBank.setLastUpdtTs(new Date(System.currentTimeMillis()));
            offerBank.setLastUpdtUserId(user);

            this.makePersistent(offerBank);
        }

        public OfferBank addOfferBank(OfferBank offerBank, Context ctx) {
            String user = (ctx != null && ((UserContext) ctx).getUserName() != null && ((UserContext) ctx).getUserName().length() > 0) ? ((UserContext) ctx)
                    .getUserName() : SharedMessages.getString("user.default");
            Date now = new Date(System.currentTimeMillis());
            offerBank.setLastUpdtTs(now);
            offerBank.setLastUpdtUserId(user);
            offerBank.setCreationUserId(user);
            offerBank.setCreationTs(now);

            return this.insert(offerBank);
        }

        public int updateCurrentBankStatus(OfferBank offerBank, Context ctx) {
            String sql = rMgr.get("sql.update_current_bank_status");
            SQLQuery query = this.sessionFactory.getCurrentSession().createSQLQuery(sql);
            query.setParameter("offer_bank_id", offerBank.getOfferBankId());
            return query.executeUpdate();
        }

        public void insertBankStatus(OfferBank offerBank, short newStatusId, Context ctx) {
            String user = (ctx != null && ((UserContext) ctx).getUserName() != null && ((UserContext) ctx).getUserName().length() > 0) ? ((UserContext) ctx)
                    .getUserName() : SharedMessages.getString("user.default");
            OfferBankStatus offerBankStatus = new OfferBankStatus();
            OfferBankStatusId offerBankStatusId = new OfferBankStatusId();
            Date now = new Date(System.currentTimeMillis());
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

            offerBankStatusId.setOfferBankId(offerBank.getOfferBankId());
            offerBankStatusId.setEffectiveStartDt(now);
            offerBankStatus.setId(offerBankStatusId);
            offerBankStatus.setCreationTs(now);
            offerBankStatus.setCreationUserId(user);
            offerBankStatus.setEffectiveEndDt(null);
            offerBankStatus.setLastUpdtTs(now);
            offerBankStatus.setLastUpdtUserId(user);

            this.sessionFactory.getCurrentSession().save(offerBankStatus);
        }

        /*public void addOfferBankRegions(List<OfferBankCluster> obRegionList, Context ctx) {
            String user = (ctx != null && ((UserContext) ctx).getUserName() != null && ((UserContext) ctx).getUserName().length() > 0) ? ((UserContext) ctx)
                    .getUserName() : SharedMessages.getString("user.default");
            Date now = new Date(System.currentTimeMillis());

            for (OfferBankCluster obc : obRegionList) {
                obc.setCreationUserId(user);
                obc.setCreationTs(now);
                obc.setLastUpdtTs(now);
                obc.setLastUpdtUserId(user);

                this.sessionFactory.getCurrentSession().save(obc);
            }
        }*/
    }

and the xml file is:
    <?xml version="1.0" encoding="UTF-8"?>
<properties>
    <sql>

        <offer_bank_get_banks>
            select * from (
                select
                    ob.offer_bank_id
                    , ob.promotional_period_id
                    , ob.offer_bank_nm
                    , obst.offer_bank_status_type_dsc
                    , ob.effective_start_dt
                    , ob.effective_end_dt
                    , obt.offer_bank_type_dsc
                    , obt.offer_bank_type_cd
                    , pp.promotional_period_nm
                    , SUM(CASE WHEN a.offer_id IS NOT NULL THEN 1 ELSE 0 END) as total_count
                    , SUM(CASE WHEN a.offer_status_type_cd = 'ED' THEN 1 ELSE 0 END) as editing_count
                    , SUM(CASE WHEN a.offer_status_type_cd = 'FD' THEN 1 ELSE 0 END) as failed_deactive_count
                    , SUM(CASE WHEN a.offer_status_type_cd in ('FP', 'FI') THEN 1 ELSE 0 END) as failed_production_count
                    , SUM(CASE WHEN a.offer_status_type_cd = 'FV' THEN 1 ELSE 0 END) as failed_preview_count
                    , SUM(CASE WHEN a.offer_status_type_cd = 'LD' THEN 1 ELSE 0 END) as loaded_count
                    , SUM(CASE WHEN a.offer_status_type_cd in ('PE', 'PS') THEN 1 ELSE 0 END) as pending_count
                    , SUM(CASE WHEN a.offer_status_type_cd = 'PK' THEN 1 ELSE 0 END) as parked_count
                    , SUM(CASE WHEN a.offer_status_type_cd = 'SD' THEN 1 ELSE 0 END) as successfully_deactivated_count
                    , SUM(CASE WHEN a.offer_status_type_cd in ('SP','PI') THEN 1 ELSE 0 END) as successfully_loaded_to_prod_count
                    , SUM(CASE WHEN a.offer_status_type_cd = 'SV' THEN 1 ELSE 0 END) as successfully_loaded_to_preview_count
                    , SUM(CASE WHEN a.offer_status_type_cd in ('LD','PE','PS') THEN 1 ELSE 0 END) as total_pending_count
                    , SUM(CASE WHEN a.offer_status_type_cd in ('FD','FP','FV','FR','FI') THEN 1 ELSE 0 END) as failed_count
                    , COUNT(1) OVER(PARTITION BY 1) as total_rows
                    , ROW_NUMBER() OVER (ORDER BY ob.effective_end_dt desc) as row_nbr
                    , MAX(a.offer_effective_end_dt)as max_offer_effective_end_dt
                    , MIN(a.offer_effective_start_dt)as min_offer_effective_start_dt
                    , SUM(CASE WHEN a.offer_status_type_cd in('AR','SR','SD') THEN 1 ELSE 0 END) as ended_count
                    , SUM(CASE WHEN a.offer_status_type_cd in('CD') THEN 1 ELSE 0 END) as copient_delay_count
                    , SUM(CASE WHEN a.offer_status_type_cd in('SR') THEN 1 ELSE 0 END) as rejected_count
                    , SUM(CASE WHEN a.offer_status_type_cd in('LV', 'GV', 'CD', 'GA', 'GC', 'GD', 'GI', 'GP', 'GR', 'LA', 'LI', 'LP', 'LR', 'LV', 'LE')
                        THEN 1 ELSE 0 END) as processing_count
                from
                    ${sql.database}.offer_bank ob
                    INNER JOIN ${sql.database}.offer_bank_status obs
                    ON ob.offer_bank_id = obs.offer_bank_id
                    INNER JOIN ${sql.database}.offer_bank_status_type obst
                    ON obs.offer_bank_status_type_cd = obst.offer_bank_status_type_cd
                    INNER JOIN ${sql.database}.promotional_period pp
                    ON ob.promotional_period_id = pp.promotional_period_id
                    INNER JOIN ${sql.database}.offer_bank_type obt
                    ON ob.offer_bank_type_cd = obt.offer_bank_type_cd
                    LEFT OUTER JOIN
                        (Select
                            o.offer_id
                            , o.offer_bank_id
                            , ost.offer_status_type_cd
                            , o.offer_effective_end_dt
                            , o.offer_effective_start_dt
                         from
                            ${sql.database}.offer o
                            INNER JOIN ${sql.database}.offer_status os
                            ON o.offer_id = os.offer_id
                            INNER JOIN ${sql.database}.offer_status_type ost
                            ON os.offer_status_type_cd = ost.offer_status_type_cd
                            AND os.effective_end_dt is null
                        ) a
                    ON ob.offer_bank_id = a.offer_bank_id
                where
                    obs.effective_end_dt is null
         </offer_bank_get_banks>

and error stack being:
20:52:16,069 ERROR JDBCExceptionReporter:101 - ORA-00972: identifier is too long

20:52:16,070 ERROR OfferBankDaoHibernateImpl:77 - Error getOfferBanks(List<Long> offerBankTypes ,int startPos, int endPos, List<Long> statusIds)
Jul 19, 2013 8:52:16 PM org.restlet.resource.UniformResource doCatch
WARNING: Exception or error caught in resource

My code is breaking at OfferBankDaoHibernateImpl. To me it seems the method getOfferBanks(List offerBankTypes ,int startPos, int endPos, List statusIds) is breaking. If anyone has come across a similar situation, it will help?

A: ORA-00972: identifier is too long tells you what the issue is. The max length of an identifier is 30 characters in Oracle, and you have a couple aliases that are longer than 30 characters. For example, successfully_loaded_to_prod_count is 33 characters.


text:
Q: Wrap ostream in class and templatize << operator I want to wrap C++ streams in a template class such that all << operations that are defined for the streams are already available for the wrapper class.
Can you change the following code such that it compiles without altering the overall intention too much?
#include <iostream>
class Foo
{
private:

    std::ostream& os;

public:

    explicit Foo( std::ostream& os ) : os( os ) {};

    template<class T>
    Foo& operator<<( const T& t )
    {
        os << t << '!';
        return *this;
    }

};

int main()
{

    Foo( std::cout ) << "test" << '\n'; // works fine
    Foo( std::cout ) << "test" << std::endl; // compilation error

    return 0;
}

I assumed that std::endl has some type and hence is 'caught' by the templated method.

A: As suggested by kmdreko, you need to add an overload for template functions
(std::endl is a template function, not a class or simple type)
Like this :
#include <iostream>
class Foo
{
private:

    std::ostream& os;

public:

    explicit Foo(std::ostream& os) : os(os) {};

    // for classes
    template<class T>
    Foo& operator<<(const T& t)
    {
        os << t << '!';
        return *this;
    }

    // for endl
    Foo& operator<<(std::ostream& (*pf) (std::ostream&)) {
        os << pf;
        return *this;
    }
};

A: You should probably guard it with SFINAE and perfect-forward the argument.
    template<class T> auto operator<<(T &&t)
         -> decltype(os << std::forward<T>(t) << '!', *this)
    {
            return os << std::forward<T>(t) << '!', *this;
    }

Now this should accept every argument std::ostream can print and fail to compile with everything else.


text:
Q: How To Remove Ugly Header Material From Bioinfo Class? I am trying to write a report using the bioinformatics class, a template for which has been provided here: https://www.overleaf.com/latex/templates/template-for-oxford-bioinformatics-journal-new-version/zjrmbrmtrytg
If you look at the template PDF on the Overleaf page, you see that it prints a whole bunch of info at the top of the page e.g.

"main"-2017/4/20-3:38-page 1-#1

I think this is really ugly and would like to remove it. However, I cannot find the part of the style file that actually produces it. Can anyone help?

A: Class bioinfo loads package crop and puts crop marks on the page and page information in the header. The page information is in the top edge that will be cut off.
To remove the information from header add class option noinfo:
\documentclass[noinfo]{bioinfo}


text:
Q: Get index of Pandas Dataframe where some columns are zero This is probably very simple but I can't seem to make it work for some reason. Let's say I have a dataframe:
    A   B   C   D   E  ... Z
1   0   2   3   0   5  ... 0
2   5   0   0   0   4  ... 1
3   0   0   3   0   10 ... 12
4   4   0   0   0   0  ... 0

and a list col that has certain columns of the dataframe
How can I return a list of the index of the rows for which columns of col are all 0? For example if col = ['B', 'C', 'D'] I would like it to return idx = [2, 4]
I tried doing idx = df.index[df.loc[col].sum() == 0].tolist() but I get a ValueError even though all the columns exist in the dataframe.
Any help is much appreciated!

A: You can use all. sum is not a good option as it's probably more expensive to compute the sum and you would potentially have false positives if there are negative values:
col = ['B', 'C', 'D']

df.index[df[col].eq(0).all(axis=1)].to_list()

output: [2, 4]


text:
Q: How to get location x,y on selection of each object in 2d diagram using Viewer api? Using Viewer API, I displaying the 2d diagram. Is that possible to get the location x,y values on the selection of each value?
I am getting some properties of the object.  But it doesn't contain any properties related to X, Y of it? Is any way to get the position?

Edit


text:
Q: Use spaces in smbclient mkdir I'm trying to use smbclient in a bash script to make a directory on a remote windows server.
Whilst this works:
smbclient -U "DOMAIN/$username" "//remoteserver/folder with spaces" --directory "Another folder with spaces/" -c "mkdir /newfolder/"

This doesn't:
smbclient -U "DOMAIN/$username" "//remoteserver/folder with spaces" --directory "Another folder with spaces/" -c "mkdir /folder to create with spaces/"

Instead a folder simply called 'folder' is created.
I've tried many variations like the following:
"mkdir /folder\ to\ create\ with\ spaces/"
"mkdir '/folder to create with spaces/'"
'mkdir '/folder to create with spaces/''

but can't seem to find the magic combination.

A: These options should work:

*

*-c 'mkdir "folder to create with spaces"'

*-c "mkdir \"folder to create with spaces\""


text:
Q: how to remove cookies from browser in asp.net c#, SO answers NOT working I'm trying to remove cookies using C# when a user logs out. The code suggestions listed here: remove cookies from browser do not work. I put several of them together in desperation and they are not working.
if (Request.Cookies["loginidcookie"] != null)
{
    HttpCookie myCookie = new HttpCookie("loginidcookie");
    myCookie.Value = String.Empty;
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
    Response.Cookies.Remove("loginidcookie");
}
Response.Redirect("logout.aspx");

So not only am I overwriting the value of the cookie with an empty string, I am setting it to expire yesterday AND removing it from the list of cookies. Yet when I run this code then hit the back button and reload, the cookie is still there with its original value. So how do I get rid of it?
Thank you

A: Try this instead:
string cookieName = "loginidcookie";
if (Request.Cookies[cookieName ] != null)
{
    var myCookie = new HttpCookie(cookieName);
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}
Response.Redirect("logout.aspx", false);

Note (from here):

You cannot directly delete a cookie on a user's computer. However, you
  can direct the user's browser to delete the cookie by setting the
  cookie's expiration date to a past date. The next time a user makes a
  request to a page within the domain or path that set the cookie, the
  browser will determine that the cookie has expired and remove it.

A: You are adding the Cookie and then Removing it from the collection before the response is sent so you are effectively doing nothing.
HttpCookie myCookie = new HttpCookie("loginidcookie");
... and then below
Response.Cookies.Add(myCookie);
Response.Cookies.Remove("loginidcookie");

If you change the cookie to expire yesterday, you need to leave the cookie in the collection so that the browser takes care of deleting it once it sees the cookie has been updated with an expiration date in the past. In other words, don't call Response.Cookies.Remove("loginidcookie");

A: Try RedFilter's solution but use Server.Transfer() or Server.TransferRequest() instead of Response.Redirect() which it seems doesn't always let those cookie responses happen due to a possible bug.

A: Are you checking the cookie after closing the browser? Or reloading the page in the same browser?
If you are opening the page in the same browser you will see the cookie which is expired, but if you opened the new browser and try to access the page again, you would not get the cookie.


text:
Q: A space in JSON value causes "unexpected token END OF FILE at position 11" exception when parsing in Java When I use the parser from org.json.simple.parser.* I get an exception whenever one of the values in JSON contains a space. For example:
{"name":"Adam"}

would parse correctly, but
{"name":"Ad am"}

would cause "unexpected token END OF FILE at position 11" exception
Here is the code that I use to convert a JSON string into a JSONObject.
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringJSON);

A: Try to get through this below example and each value contains space except integer one and giving this example just because of you don't have shared your source code.
JSON File(personal_detail.json):
{
    "name":"arif mustafa",
    "age":26,
    "address":["district is Korba","state is Chhattisgarh","country is India"]
}

Java source to read the JSON file format:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JSONExample {

    public static void main(String[] args) {

        JSONParser parser = new JSONParser();

        try {

            Object obj = parser.parse(new FileReader("src/resources/personal_detail.json"));

            JSONObject jsonObject = (JSONObject) obj;
            System.out.println(jsonObject + "\n");

            String name = (String) jsonObject.get("name");
            System.out.println("name : " + name);

            long age = (Long) jsonObject.get("age");
            System.out.println("age : " + age);

            //get Object loop array
            JSONArray address = (JSONArray) jsonObject.get("address");
            System.out.println("address is : ");

            Iterator<String> iterator = address.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
}


text:
Q: SQL Server switching live database A client has one of my company's applications which points to a specific database and tables within the database on their server.  We need to update the data several times a day.  We don't want to update the tables that the users are looking at in live sessions.  We want to refresh the data on the side and then flip which database/tables the users are accessing.
What is the accepted way of doing this?  Do we have two databases and rename the databases?  Do we put the data into separate tables, then rename the tables?  Are there other approaches that we can take?

A: I think I understand what you're saying: if the user is on a screen you don't want the screen updating with new information while they're viewing it, only update when they pull a new screen after the new data has been loaded? Correct me if I'm wrong. And Mike's question is also a good one, how is this data being fed to the users? Possibly there's a way to pause that or something while the new data is being loaded. There are more elegant ways to load data like possibly partitioning the table, using a staging table, replication, have the users view snapshots, etc. But we need to know what you mean by 'live sessions'.
Edit: with the additional information you've given me, partition switching could be the answer. The process takes virtually no time, it just changes the pointers from the old records to the new ones. Only issue is you have to partition on something patitionable, like a date or timestamp, to differentiate old and new data. It's also an Enterprise-Edition feature and I'm not sure what version you're running.
Possibly a better thing to look at is Read Committed Snapshot Isolation. It will ensure that your users only look at the new data after it's committed; it provides a transaction-level consistent view of the data and has minimal concurrency issues, though there is more overhead in TempDB. Here are some resources for more research:
http://www.databasejournal.com/features/mssql/snapshot-isolation-level-in-sql-server-what-why-and-how-part-1.html
https://msdn.microsoft.com/en-us/library/tcbchxcb(v=vs.110).aspx
Hope this helps and good luck!

A: Based on the information you have provided, I believe your best bet would be partition switching. I've included a couple links for you to check out because it's much easier to direct you to a source that already explains it well.  There are several approaches with partition switching you can take.
Links: Microsoft and Catherin Wilhelmsen blog
Hope this helps!

A: The question details are a little vague so to clarify:
What is a live session? Is it a session in the application itself (with app code managing it's own connections to the database) or is it a low level connection per user/session situation? Are users just running reports or active reading/writing from the database during the session? When is a session over and how do you know?
Some options:
1) Pull all the data into the client for the entire session.
2) Use read committed or partitions as mentioned in other answers (however requires careful setup for your queries and increases requirements for the database)
3) Use replica database for all queries, pause/resume replication when necessary (updating data should be faster than your process but it still might take a while depending on volume and complexity)
4) Use replica database and automate a backup/restore from the master (this might be the quickest depending on the overall size of your database)
5) Use multiple replica databases with replication or backup/restore and then switch the connection string (this allows you to update the master constantly and then update a replica and switch over at a certain predictable time)