text:
Q: Multi-function MYSQL commands I do not know if piping is the right word.
EDIT below to make the question clearer (ie I show what I am doing in php, and want to do this with a single MYSQL statement).
I know how to do this in php, but am looking on this site and everyone seems to be able to do this kind of stuff with just MYSQL statements alone. Can this be done with just MYSQL statements?
CREATE TABLE `tests` (
 `TestNumber` int(11) NOT NULL AUTO_INCREMENT,
 `InactiveSlotsBitwise` int(11) NOT NULL,
 PRIMARY KEY (`TestNumber`)
) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=latin1

and
CREATE TABLE `testsubject` (
 `UniqueId` int(11) NOT NULL AUTO_INCREMENT,
 `TestNumber` int(11) NOT NULL,
 `UserId` int(11) NOT NULL,
 `Slot` tinyint(4) NOT NULL
 `Time` int(11) NOT NULL,
 PRIMARY KEY (`UniqueId`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1

and
CREATE TABLE `users` (
 `UserId` int(11) NOT NULL AUTO_INCREMENT,
 `Password` varchar(20) NOT NULL,
 `Email` varchar(100) NOT NULL,
 PRIMARY KEY (`UserId`)
) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=latin1

INSERT INTO tests VALUES(1, 0);
INSERT INTO tests VALUES(2, 0);
INSERT INTO tests VALUES(3, 0);
INSERT INTO testsubject VALUES(1, 1, 50, 2, 0);
INSERT INTO testsubject VALUES(2, 2, 51, 5, 0);
INSERT INTO testsubject VALUES(3, 1, 50, 7, 0);
INSERT INTO users VALUES(50, 'abc', 'a@b.com');
INSERT INTO users VALUES(51, 'xyz', 'x@y.com');

What does this all mean? There are two user a@b.com and x@y.com. Our user of focus a@b.com has to withdraw from some of the tests because of illness. There are three tests with TestNumbers 1,2,3. Our subject a@b.com is in only two of them, namely 1 and 3. His test seating position is slot 2 and 7 respectively.
So my aim is to set 'Time' in testsubject to -1 for each of those entries, to show he was in the test but had to withdraw. In test with TestNumber=1 he was in slot 2. So we must show that slot is now free in 'tests'. So in 'tests' with TestNumber=1 the 'InactiveSlotsBitwise' entry must change to InactiveSlotsBitwise = InactiveSlotsBitwise & (1<<2), to show slot 2 is now free. Similarly in test with TestNumber=3 he was in slot 7. So we must show that slot is now free in 'tests'. So in 'tests' with TestNumber=3 the 'InactiveSlotsBitwise' entry must change to InactiveSlotsBitwise = InactiveSlotsBitwise & (1<<7), to show slot 7 is now free.
EDIT:
So I am presently doing the following. I am having to do it in php due to the multi stage:
This gets fills an array of (TestNumber, Slot) combos.
$UserId = 50; // This is sent to the php code

$arrTestNumberSlot = array();
// The Time>=0 requirement is to make sure the person has not already abandoned the test - in which case we do nothing
$stmt = $db->prepare("SELECT TestNumber, Slot FROM testsubject WHERE UserId=:UserId AND Time>=0");
$stmt->execute(array(':UserId' => $UserId));
if($stmt && isset($stmt) && $stmt->rowCount() > 0)
{
    while(($row = $stmt->fetch(PDO::FETCH_ASSOC)))
    {
        array_push($arrTestNumberSlot, array('TestNumber' => intval($row['TestNumber']), 'Slot' => intval($row['Slot'])));
    }
}
$stmt->closeCursor();

Now change the 'Time' in  testsubject to -1
$stmt = $db->prepare("UPDATE testsubject SET Time=-1 WHERE UserId=:UserId AND Time>=0");
$stmt->execute(array(':UserId' => $UserId));

Now go through the TestNumber/Slot array and update the 'tests' table:
$count = count($arrTestNumberSlot);
for($i = 0; $i < $count; $i++)
{
    $stmt = $db->prepare("UPDATE tests SET InactiveSlotsBitwise= (InactiveSlotsBitwise & (1 << :Slot)) WHERE TestNumber=:TestNumber");
    $stmt->execute(array(':Slot' => $arrTestNumberSlot['Slot'], ':TestNumber' => $arrTestNumberSlot['TestNumber']));
}

So the Question is: 'How can this be done all in one with a single MYSQL statement??


text:
Q: How can I output these symbols in c++ I want to output this face
all I see is question mark symbols
void win(){

        cout << "░░░░█▒▒▒▒░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒█" << endl;
        cout << "░░░░█▒▒▄▀▀▀▀▀▄▄▒▒▒▒▒▒▒▒▒▄▄▀▀▀▀▀▀▄" << endl;
        cout << "░░▄▀▒▒▒▄█████▄▒█▒▒▒▒▒▒▒█▒▄█████▄▒█" << endl;
        cout << "░█▒▒▒▒▐██▄████▌▒█▒▒▒▒▒█▒▐██▄████▌▒█" << endl;
        cout << "▀▒▒▒▒▒▒▀█████▀▒▒█▒░▄▒▄█▒▒▀█████▀▒▒▒█" << endl;
        cout << "▒▒▐▒▒▒░░░░▒▒▒▒▒█▒░▒▒▀▒▒█▒▒▒▒▒▒▒▒▒▒▒▒█" << endl;
        cout << "▒▌▒▒▒░░░▒▒▒▒▒▄▀▒░▒▄█▄█▄▒▀▄▒▒▒▒▒▒▒▒▒▒▒▌" << endl;
        cout << "▒▌▒▒▒▒░▒▒▒▒▒▒▀▄▒▒█▌▌▌▌▌█▄▀▒▒▒▒▒▒▒▒▒▒▒▐" << endl;
        cout << "▒▐▒▒▒▒▒▒▒▒▒▒▒▒▒▌▒▒▀███▀▒▌▒▒▒▒▒▒▒▒▒▒▒▒▌" << endl;
        cout << "▀▀▄▒▒▒▒▒▒▒▒▒▒▒▌▒▒▒▒▒▒▒▒▒▐▒▒▒▒▒▒▒▒▒▒▒█" << endl;
        cout << "▀▄▒▀▄▒▒▒▒▒▒▒▒▐▒▒▒▒▒▒▒▒▒▄▄▄▄▒▒▒▒▒▒▄▄▀" << endl;
        cout << "▒▒▀▄▒▀▄▀▀▀▄▀▀▀▀▄▄▄▄▄▄▄▀░░░░▀▀▀▀▀▀" << endl;
    }

A: If you are on Windows, the following code works as long as:

*

*The console font supports the characters.  I'm using Consolas font.

*The source is compiled from source saved in an encoding that supports the characters. Saving as UTF-8 w/ BOM convinces many Windows applications that a file is UTF-8, but also check your compiler for source encoding options.

Note the use of  wcout and wide strings (L"...").  Also, _setmode is used to alter stdout to support UTF-16 output.
#include <iostream>
#include <io.h>
#include <fcntl.h>

using namespace std;

void win(){

    wcout << L"░░░░█▒▒▒▒░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒█" << endl;
    wcout << L"░░░░█▒▒▄▀▀▀▀▀▄▄▒▒▒▒▒▒▒▒▒▄▄▀▀▀▀▀▀▄" << endl;
    wcout << L"░░▄▀▒▒▒▄█████▄▒█▒▒▒▒▒▒▒█▒▄█████▄▒█" << endl;
    wcout << L"░█▒▒▒▒▐██▄████▌▒█▒▒▒▒▒█▒▐██▄████▌▒█" << endl;
    wcout << L"▀▒▒▒▒▒▒▀█████▀▒▒█▒░▄▒▄█▒▒▀█████▀▒▒▒█" << endl;
    wcout << L"▒▒▐▒▒▒░░░░▒▒▒▒▒█▒░▒▒▀▒▒█▒▒▒▒▒▒▒▒▒▒▒▒█" << endl;
    wcout << L"▒▌▒▒▒░░░▒▒▒▒▒▄▀▒░▒▄█▄█▄▒▀▄▒▒▒▒▒▒▒▒▒▒▒▌" << endl;
    wcout << L"▒▌▒▒▒▒░▒▒▒▒▒▒▀▄▒▒█▌▌▌▌▌█▄▀▒▒▒▒▒▒▒▒▒▒▒▐" << endl;
    wcout << L"▒▐▒▒▒▒▒▒▒▒▒▒▒▒▒▌▒▒▀███▀▒▌▒▒▒▒▒▒▒▒▒▒▒▒▌" << endl;
    wcout << L"▀▀▄▒▒▒▒▒▒▒▒▒▒▒▌▒▒▒▒▒▒▒▒▒▐▒▒▒▒▒▒▒▒▒▒▒█" << endl;
    wcout << L"▀▄▒▀▄▒▒▒▒▒▒▒▒▐▒▒▒▒▒▒▒▒▒▄▄▄▄▒▒▒▒▒▒▄▄▀" << endl;
    wcout << L"▒▒▀▄▒▀▄▀▀▀▄▀▀▀▀▄▄▄▄▄▄▄▀░░░░▀▀▀▀▀▀" << endl;
}

int main(){
    _setmode(_fileno(stdout), _O_U16TEXT);
    win();
    return 0;
}

Output:

A: Are you using windows or an unix based system (macos/linux), because windows does not use utf8 by default like macos and linux.
On macos (which i am using) your code compiles an runs completely fine:
#include <iostream>

using namespace std;

void win(){

    cout << "░░░░█▒▒▒▒░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒█" << endl;
    cout << "░░░░█▒▒▄▀▀▀▀▀▄▄▒▒▒▒▒▒▒▒▒▄▄▀▀▀▀▀▀▄" << endl;
    cout << "░░▄▀▒▒▒▄█████▄▒█▒▒▒▒▒▒▒█▒▄█████▄▒█" << endl;
    cout << "░█▒▒▒▒▐██▄████▌▒█▒▒▒▒▒█▒▐██▄████▌▒█" << endl;
    cout << "▀▒▒▒▒▒▒▀█████▀▒▒█▒░▄▒▄█▒▒▀█████▀▒▒▒█" << endl;
    cout << "▒▒▐▒▒▒░░░░▒▒▒▒▒█▒░▒▒▀▒▒█▒▒▒▒▒▒▒▒▒▒▒▒█" << endl;
    cout << "▒▌▒▒▒░░░▒▒▒▒▒▄▀▒░▒▄█▄█▄▒▀▄▒▒▒▒▒▒▒▒▒▒▒▌" << endl;
    cout << "▒▌▒▒▒▒░▒▒▒▒▒▒▀▄▒▒█▌▌▌▌▌█▄▀▒▒▒▒▒▒▒▒▒▒▒▐" << endl;
    cout << "▒▐▒▒▒▒▒▒▒▒▒▒▒▒▒▌▒▒▀███▀▒▌▒▒▒▒▒▒▒▒▒▒▒▒▌" << endl;
    cout << "▀▀▄▒▒▒▒▒▒▒▒▒▒▒▌▒▒▒▒▒▒▒▒▒▐▒▒▒▒▒▒▒▒▒▒▒█" << endl;
    cout << "▀▄▒▀▄▒▒▒▒▒▒▒▒▐▒▒▒▒▒▒▒▒▒▄▄▄▄▒▒▒▒▒▒▄▄▀" << endl;
    cout << "▒▒▀▄▒▀▄▀▀▀▄▀▀▀▀▄▄▄▄▄▄▄▀░░░░▀▀▀▀▀▀" << endl;
}

int main(){
    win();
    return 0;
}

and gives the desired output:
░░░░█▒▒▒▒░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒█
░░░░█▒▒▄▀▀▀▀▀▄▄▒▒▒▒▒▒▒▒▒▄▄▀▀▀▀▀▀▄
░░▄▀▒▒▒▄█████▄▒█▒▒▒▒▒▒▒█▒▄█████▄▒█
░█▒▒▒▒▐██▄████▌▒█▒▒▒▒▒█▒▐██▄████▌▒█
▀▒▒▒▒▒▒▀█████▀▒▒█▒░▄▒▄█▒▒▀█████▀▒▒▒█
▒▒▐▒▒▒░░░░▒▒▒▒▒█▒░▒▒▀▒▒█▒▒▒▒▒▒▒▒▒▒▒▒█
▒▌▒▒▒░░░▒▒▒▒▒▄▀▒░▒▄█▄█▄▒▀▄▒▒▒▒▒▒▒▒▒▒▒▌
▒▌▒▒▒▒░▒▒▒▒▒▒▀▄▒▒█▌▌▌▌▌█▄▀▒▒▒▒▒▒▒▒▒▒▒▐
▒▐▒▒▒▒▒▒▒▒▒▒▒▒▒▌▒▒▀███▀▒▌▒▒▒▒▒▒▒▒▒▒▒▒▌
▀▀▄▒▒▒▒▒▒▒▒▒▒▒▌▒▒▒▒▒▒▒▒▒▐▒▒▒▒▒▒▒▒▒▒▒█
▀▄▒▀▄▒▒▒▒▒▒▒▒▐▒▒▒▒▒▒▒▒▒▄▄▄▄▒▒▒▒▒▒▄▄▀
▒▒▀▄▒▀▄▀▀▀▄▀▀▀▀▄▄▄▄▄▄▄▀░░░░▀▀▀▀▀▀

but on windows it prints:
????????????????????????????
???????????????????????????????
??????????????????????????????????
????????????????????????????????????

and so on.
So i think the problem lies in the fact the machine/terminal you are using does not support unicode.
A solution could be to use std::wcout which is for "wide" characters an example could be this:
std::wcout << L"█" << std::endl;

Or using utf16:
#include <iostream>

using std::cout;
using std::endl;

void win(){
    cout << "\u2591\u2591\u2591\u2591\u2588\u2592\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2588" << endl;
    cout << "\u2591\u2591\u2591\u2591\u2588\u2592\u2592\u2584\u2580\u2580\u2580\u2580\u2580\u2584\u2584\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2584\u2584\u2580\u2580\u2580\u2580\u2580\u2580\u2584" << endl;
    cout << "\u2591\u2591\u2584\u2580\u2592\u2592\u2592\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2592\u2588\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2588\u2592\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2592\u2588" << endl;
    cout << "\u2591\u2588\u2592\u2592\u2592\u2592\u2590\u2588\u2588\u2584\u2588\u2588\u2588\u2588\u258C\u2592\u2588\u2592\u2592\u2592\u2592\u2592\u2588\u2592\u2590\u2588\u2588\u2584\u2588\u2588\u2588\u2588\u258C\u2592\u2588" << endl;
    cout << "\u2580\u2592\u2592\u2592\u2592\u2592\u2592\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2592\u2592\u2588\u2592\u2591\u2584\u2592\u2584\u2588\u2592\u2592\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2592\u2592\u2592\u2588" << endl;
    cout << "\u2592\u2592\u2590\u2592\u2592\u2592\u2591\u2591\u2591\u2591\u2592\u2592\u2592\u2592\u2592\u2588\u2592\u2591\u2592\u2592\u2580\u2592\u2592\u2588\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2588" << endl;
    cout << "\u2592\u258C\u2592\u2592\u2592\u2591\u2591\u2591\u2592\u2592\u2592\u2592\u2592\u2584\u2580\u2592\u2591\u2592\u2584\u2588\u2584\u2588\u2584\u2592\u2580\u2584\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u258C" << endl;
    cout << "\u2592\u258C\u2592\u2592\u2592\u2592\u2591\u2592\u2592\u2592\u2592\u2592\u2592\u2580\u2584\u2592\u2592\u2588\u258C\u258C\u258C\u258C\u258C\u2588\u2584\u2580\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2590" << endl;
    cout << "\u2592\u2590\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u258C\u2592\u2592\u2580\u2588\u2588\u2588\u2580\u2592\u258C\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u258C" << endl;
    cout << "\u2580\u2580\u2584\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u258C\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2590\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2588" << endl;
    cout << "\u2580\u2584\u2592\u2580\u2584\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2590\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2592\u2584\u2584\u2584\u2584\u2592\u2592\u2592\u2592\u2592\u2592\u2584\u2584\u2580" << endl;
    cout << "\u2592\u2592\u2580\u2584\u2592\u2580\u2584\u2580\u2580\u2580\u2584\u2580\u2580\u2580\u2580\u2584\u2584\u2584\u2584\u2584\u2584\u2584\u2580\u2591\u2591\u2591\u2591\u2580\u2580\u2580\u2580\u2580\u2580" << endl;
}

int main(){
    win();
}

But again if your terminal does not support Unicode there is No way to print it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ruby State Machine - After or Before transition I am using the gem state_machines found here https://github.com/state-machines/state_machines
I have it setup so you can dynamically generate state flows via the web browser and also have a few pre determined events.  For example.  You can setup a before or after transition to fire and send and email.
Is there anyway to tell which transition is being fired i.e is it a before or after transition?
Thanks


text:
Q: Spring: Access bean property from another bean I have two beans:
ConfigurationManager:
public class ConfigurationManager
{
    private Configuration configuration;

    public void init() { ... } // Loads a configuration

    // Getters and setters
}

DataCenter:
public class DataCenter
{
    private Configuration configuration;

    ...

    // Getters and setters
}

I would like to get the configuration field of the ConfigurationManager from within my DataCenter bean and I'm not quite sure what the syntax is.
Here's my context file:
<bean id="configurationManager"
      class="com.foo.ConfigurationManager"
      init-method="init">
    <property name="configurationFile" value="etc/configuration.xml"/>
</bean>

<bean id="dataCenter"
      class="com.foo.DataCenter">
    <!-- <property name="storages" ref="configurationManager."/> -->
</bean>

Could somebody please show me how to do this? Thanks in advance!

A: try this
<bean id="dataCenter" class="com.foo.DataCenter">
    <property name="configuration" value="#{configurationManager.configuration}"/>
</bean>

A: You can use Spring Expression Language to refer to other bean properties by name. Here's the example given in the docs
<bean id="numberGuess" class="org.spring.samples.NumberGuess">
    <property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/>

    <!-- other properties -->
</bean>

<bean id="shapeGuess" class="org.spring.samples.ShapeGuess">
    <property name="initialShapeSeed" value="#{ numberGuess.randomNumber }"/>

    <!-- other properties -->
</bean>

In your case, you could use
<bean id="configurationManager"
      class="com.foo.ConfigurationManager"
      init-method="init">
    <property name="configurationFile" value="etc/configuration.xml"/>
</bean>

<bean id="dataCenter"
      class="com.foo.DataCenter">
    <property name="storages" value="#{configurationManager.configuration}"/>
</bean>

In similar fashion, you can use @Value annotation in @Bean methods  or use it in @Autowired methods.


text:
Q: Cannot enter text from class to textbox in form Cannot enter text from class to textbox in form.
We set a keypress event in the MyTreeView class.
The text box cannot contain characters.
What should I do?
*set of textBox1.
*Change Modifiers for textBox1 properties from private to public
*Change keypress event from private to public
*(It didn't work well, so I keep it private now.)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace treeview
{

    public partial class Form1 : System.Windows.Forms.Form
    {

        MyTreeView m_tree_view = new MyTreeView();

        public Form1()
        {
            try
            {
                InitializeComponent();

                System.Windows.Forms.TreeNode[] tree1 = new System.Windows.Forms.TreeNode[2];

                m_tree_view.Location = new System.Drawing.Point(0, 0);
                m_tree_view.Size = ClientSize;
                m_tree_view.AllowDrop = true;

                tree1[0] = new System.Windows.Forms.TreeNode("TreeNode1");
                tree1[1] = new System.Windows.Forms.TreeNode("TreeNode2");

                m_tree_view.Nodes.Add("Node1");

                Controls.Add(m_tree_view);
            }
            catch
            {
            }
        }

        //This is the code I added.
        private void Form1_Load(object sender, EventArgs e)
        {

        }

    }

    public class MyTreeView : System.Windows.Forms.TreeView
    {

        public MyTreeView()
        {
            try
            {
                //This is the code I added.
                KeyPress += MyTreeView_KeyPress;
            }
            catch
            {
            }
        }

        //This is the code I added.
        private void MyTreeView_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            Console.WriteLine("key_press_ok");

            //error code↓
            //textBox1.Text = "sample";
        }

    }
}

A: If you want just to click an button and then print some text i don't understand why you are making another class.
Will be good to make your code efficient and not complicated.
In the main class
private void SendText_Click(object sender, EventArgs e)
    {
        textBox1.Text = "hi";
    }

But if you want to make it complicated and make a class you shuld return i variable and send it to the other class the you can use it.
Learn how to use Public and private first and then use them.
You shuld have a public class which send data and the private to recive and process.

A: add (Exception ex) to your try catch.
so do:
try
{
    // your code
}
catch (Exception ex)
{
    MessageBox.Show(ex, "Error in (add where the error is)");
    Console.WriteLine(ex);
}

So you will get a detailed Exception Message, maybe it helps you or maybe you will post it here, so we can see what the problem is.
And because you have System.Windows.Forms in your Using Directive
using System.Windows.Forms;

so
System.Windows.Forms.TreeNode[] tree1 = new System.Windows.Forms.TreeNode[2];

is redundant and can be shortened to:
TreeNode[] tree1 = new TreeNode[2];


text:
Q: Problems with gulp and ng-annotate I'm using gulp for my project. While saving the changes made in my Controller, it is not getting updated in my app.js(which contains all the .js code that i have used). In my command prompt, I get this as the result while saving the js file.

Suggestions for this problem are invited.


text:
Q: Breadth-first search algorithm Like a previous problem I had earlier, I am trying to create a breadth-first search algorithm that takes a graph and outputs the vertex visit order. It takes an adjacency matrix (representing the graph) as its input and here is what I have so far.
import sys
import Queue

# Input has to be adjacency matrix or list
graphAL2 = {0 : [1,2,3],
        1 : [0,3,4],
        2 : [0,4,5],
        3 : [0,1,5],
        4 : [1,2],
        5 : [2,3] }

# NEED TO FIX:
# - Final graphAL2v print is only displaying key values as 1, not iterating
# through graph and visiting each vertex

def main():
    count = 0
    graphAL2v = {}

    for key, value in graphAL2.items():
        graphAL2v[key] = 0

    print(graphAL2v)

    for key in graphAL2v: # each vertex v in V
        if graphAL2v[key] == 0: # is marked with 0
            bfs(key, count, graphAL2, graphAL2v)
    print(graphAL2v)

def bfs(v, count, graphal, graphv):
    count = count + 1
    print('Visiting', v)

    # Mark v with count and initialize queue with v
    graphv[v] = count
    visited = Queue.Queue()

    while not visited.empty(): #queue not empty:
        print('queue is not empty')
        for element in graphal[v]: # each vertex w in V adjacent to front vertex
            if element == 0:
                count = count + 1
                # mark w with count
                graphal[v] = count
                visited.put()
        visited.get()

if __name__ == '__main__':
    sys.exit(main())

The problem that I am running into is that my output
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
('Visiting', 0)
('Visiting', 1)
('Visiting', 2)
('Visiting', 3)
('Visiting', 4)
('Visiting', 5)
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}

displays the visit order as 1 for all vertices in the list when it should be displaying the visit order as a different number for each vertex as it traverses the "graph." I believe that this error is stemming from within the while loop of the bfs() function. Any suggestions for trying to fix the code so I can achieve the desired output? I'm also not that familiar with queues in Python so any help is appreciated.

A: There are lots of issues in your code -

*

*First of all, you are never putting anything in the Queue that you create, so its always empty, you need to put the v inside the queue before the while loop , that is the starting point.

*Secondly, in the for loop, you are checking element == 0 , which is wrong, you need to check if graphv[element] == 0 , that is whether the element has been already visited or not.

*Thirdly, in the for loop, you need to set graphv[element] = count , that signifies that you vivisted element .

*You are not putting anything inside the queue with - visited.put() , you need to pass the element to put inside the Queue as parameter.

*When getting back the element from the Queue, you need to assign it back to v, otherwise v would never change, v signifies the current element being iterated.
Example code -
import sys
import Queue

# Input has to be adjacency matrix or list
graphAL2 = {0 : [1,2,3],
        1 : [0,3,4],
        2 : [0,4,5],
        3 : [0,1,5],
        4 : [1,2],
        5 : [2,3] }

# NEED TO FIX:
# - Final graphAL2v print is only displaying key values as 1, not iterating
# through graph and visiting each vertex

def main():
    count = 0
    graphAL2v = {}

    for key, value in graphAL2.items():
        graphAL2v[key] = 0

    print(graphAL2v)

    for key in graphAL2v: # each vertex v in V
        if graphAL2v[key] == 0: # is marked with 0
            bfs(key, count, graphAL2, graphAL2v)
    print(graphAL2v)

def bfs(v, count, graphal, graphv):
    count = count + 1
    print('Visiting', v)

    # Mark v with count and initialize queue with v
    graphv[v] = count
    visited = Queue.Queue()
    visited.put(v)
    while not visited.empty(): #queue not empty:
        print('queue is not empty')
        for element in graphal[v]: # each vertex w in V adjacent to front vertex
            if graphv[element] == 0:
                count = count + 1
                # mark w with count
                graphv[element] = count
                visited.put(element)
        v = visited.get()
    return count

if __name__ == '__main__':
    sys.exit(main())

Demo (after above changes) -
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
Visiting 0
queue is not empty
queue is not empty
queue is not empty
queue is not empty
queue is not empty
queue is not empty
{0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6}

A: You can use one of the graph libraries that provide search algorithms, such as NetworkX:
from networkx import *
graphAL2 = {0 : [1,2,3],
        1 : [0,3,4],
        2 : [0,4,5],
        3 : [0,1,5],
        4 : [1,2],
        5 : [2,3] }

g = Graph()

# create graph
for node in graphAL2:
    g.add_node(node)
    for target_node in graphAL2[node]:
        g.add_edge(node, target_node)

print bfs_successors(g, 0)

This will get the successors of each node, exporting the search order from that should be a piece of cake.
Output:
{0: [1, 2, 3], 1: [4], 2: [5]}


text:
Q: How do install C header files in Mac OSX Sierra? I have missing header files like malloc.h and conio.h in my MAC.. how do I install it?

gcc linkedlistmenu.c
  linkedlistmenu.c:2:19: fatal error: malloc.h: No such file or directory

A: First off, malloc.h is deprecated (and not available on your system).  Instead, you should be using stdlib.h.  Furthermore, conio.h is an implementation specific header - and in this case, it is Windows and MS-DOS specific.  It is not available on MacOS.  Both of these are non-standard headers, and therefore are not preferred due to issues with portability.  ncurses (which should already be available on MacOS) provides similar functionality to conio.h; see if that has what you're looking for.
However, your best shot if you really need these header files is to install a virtualization program such as VirtualBox, install Windows, and work from there.


text:
Q: Same xpath works on command line but not in xslt I'm a beginning user of xslt and xpath.  Using an xpath on a command line (Ubuntu 14.04) with a xml file works, but the very same xpath in an xslt file returns nothing.  I'm working with Juniper Junos xml files.  Any suggestions?
Thanks,
George
The xml file begins with:
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:junos="http://xml.juniper.net/junos/12.3R8/junos">
  <interface-information xmlns="http://xml.juniper.net/junos/12.3R8/junos-interface" junos:style="normal">
    <physical-interface>
      <name>fe-0/1/0</name>
      <logical-interface>
        <name>fe-0/1/0.0</name>
          ...

The command line that works in Ubuntu 14.04 is:
xpath -e "/rpc-reply/interface-information/physical-interface/logical-interface/name" interfaces.xml
The xslt file is:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
  version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">

Interfaces

        Name

      <xsl:for-each select="/rpc-reply/interface-information/physical-interface/logical-interface">

          <xsl:value-of select="name"/>

      </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

A: The problem here is quite simple. You are not using namespaces in your XPaths. Apparently your command line utility doesn't care, or evaluates XPaths based on the elements' QNames ignores default namespaces and does some other non-standard handling of namespaces as well.
The solution:
Declare prefixes at the top of your stylesheet:
<xsl:stylesheet
  version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:nbase="urn:ietf:params:xml:ns:netconf:base:1.0"
  xmlns:junosi="http://xml.juniper.net/junos/12.3R8/junos-interface"
>

use those prefixes in your XPaths:
<xsl:for-each select="/nbase:rpc-reply/junosi:interface-information
                        /junosi:physical-interface/junosi:logical-interface">

    <xsl:value-of select="junosi:name"/>

</xsl:for-each>


text:
Q: JavaScript executeScript on tabs.onUpdated In my code I need to execute the same script every time I update a google tab.
I wrote this code;
chrome.tabs.onActivated.addListener((tab) => {
  chrome.tabs.get(tab.tabId, (current_tab_info) => {
    if (
      current_tab_info.url.search("https://") == 0 &&
      current_tab_info.url.search(".instagram.com/p/") > 0
    ) {
      chrome.tabs.executeScript(null, { file: "./foreground.js" });
    } else {
      console.log("You are not in instagram");
    }
  });
});
chrome.tabs.onUpdated.addListener(function (tabID, changeInfo, tab) {
  if (
    tab.url.search("https://") == 0 &&
    tab.url.search(".instagram.com/p/") > 0
  ) {
    chrome.tabs.executeScript(null, { file: "./foreground.js" });
  } else {
    console.log("You are not in instagram");
  }
});

But executeScript(script) only works on the first "Activate". It does not work on any "Activate" or "Update" after. I want it to execute the script everytime I "Update" the instagram tab,
Note: Manifest v2, Chrome extension.
Also this is foreground.js;
const control = document.getElementById("Tasarruflu Downloader");
console.log("control: " + control);
if (control === null) {
  const button = document.createElement("button");
  button.setAttribute("id", "Tasarruflu Downloader");
  button.innerText = "My Button 1";
  document
    .querySelector("._aamu" && "._ae3_" && "._ae47" && "._ae48")
    .appendChild(button);
  button.addEventListener("click", () => {
    console.log("Pressed a Button");
  });
}

How can i execute script in foreground.js file at onActivated and onUpdated events on my main script?

A: You could inject your script once when opening a tab or URL by using manifest.json. There is no need on injecting it over and over again - if code inside the script is not changing.
But you need to modify your script and tabs API handlers code. In both places, you need to use runtime. Things that interest you are:

*

*send method

*onMessage event listener

The steps to do it are simple:

*

*send a message via runtime API when the tab would be updated, refreshed, etc.

*catch it in the content script by registering onMessage listener

*in the callback you could run code shown in the content script example

In order to find what message is sent you could use something like this:
const message = {
name: 'your name for message',
// additional data here
}

Then in the listener callback, you could check if the message has the name you want.


text:
Q: Where can I find third-party components? Where can I find third-party components for the Android?  Components such as dials, meters, graphics of volume controls LED's, etc?

A: What Macarse said: There's no one-stop shop for that. However, code.google.com has a bunch of good projects (http://code.google.com/hosting/search?q=label:Android), and then of course you can just Google for stuff.
What you should do is figure out what you actually need, and google for those things specifically. So if you need a dial component, just google for "android dial component" or something similar.

A: There is no such place.
You should use Google to get some of those.

A: See The Android Arsenal- A categorized directory of free libraries and tools for Android
Contains ~1000 libraries and ~90 sample projects.


text:
Q: Displaying webpage on a iphone 4/4s I have a webpage which I have created a media query for a resolution of 480px in width.
The iphone 4 correctly picks up this version but for some reason it overhangs the page its not using the actual resolution of the iphone 4 which is 640px in width its using a width of 320px. (i read somewhere that it does this for backward compatibility with apps developed for iphone 3)
Is there a way using a viewport or a media query to correct this? Or does someone have an example of how to implement an iphone media query, ive tried this with no luck.
Is there a way to stretch the 480px media query to fit the iphone?
This is my current viewport:
<meta name="viewport" content="width=device-width; initial-scale=1; maximum-scale=5.0; minimum-scale=0.5;" />

Media query - this does nothing and ive tried with just -webkit-device-pixel-ratio: 2 only
@media screen  and (max-width: 480px) and (-webkit-device-pixel-ratio: 2) {}

A: This media query in css3 should detect any iphone or ipod
@media only screen and (max-device-width: 480px), only screen and (min-device-width: 640px) and (max-device-width: 1136px) and (-webkit-min-device-pixel-ratio: 2)

The way I understand it is that retina screens will still act as if they are the normal old screens. you act as if things are still 320px is the width. if you want something to take up the full width of an iphone in portrait then you would use 320px not 640px. Really you should be using percentages and ems though not exact px sizes.
Not sure if this answered anything, but I think you were wanting to know why if you set something to 640px it would hang off the edge and not just take up the width of the retina screen.


text:
Q: Installed Java 7 on Mac OS X but Terminal is still using version 6 I've installed JDK 7u7 downloaded from oracle's website. But after installation, the terminal is still showing java version 6
$java -version
java version "1.6.0_35"
Java(TM) SE Runtime Environment (build 1.6.0_35-b10-428-11M3811)
Java HotSpot(TM) 64-Bit Server VM (build 20.10-b01-428, mixed mode)

any idea why java 7 is not showing up?
Ans:
OK, the problem has been resolved. Here is the answer:
I found that my Terminal has a .bash_profile and the java home variable is set to 1.6
export JAVA_HOME="/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home"

So this is the line causing the problem every time I opened a new terminal window.
Simply remove this line will solve the problem. You still need to follow what @aleroot said, but if that doesn't work for you, check the .bash_profile (or .bashrc) setting file to see if you've previously exported any java version.

A: http://www.java.com/en/download/faq/java_mac.xml is a nice place to understand, while Apple is stopping support to Java, why Java Preferences doesn't exist anymore and rely on System_Preferences => Java => Java if Java 7 from Oracle is installed.

A: May I suggest you to have a look at the tool Jenv
This will allow you to switch at any time between your installed JVMs.
Simply as:
jenv global oracle-1.7

then later for test purpose:
jenv global oracle-1.6

And you have much more commands available.

A: Because you need to enter in Java Preferences pane and flag only the JVM 7 in this way :

To easily and quickly open the Java Preferences pane in Mac OS X you can simply call spotlight with ⌘+SPACE and type System Preferences it will show up in the last row of the window.

A: Hard-coding the JAVA_HOME path might not be the best idea. The /usr/libexec/java_home utility sill works for me on Mac OSX Lion 10.7.5 and JDK 1.7.0_13. According to its man page, it is meant to be used with Apple's old Java Preferences pane, but it appears to be working with the replacement provided by Oracle (Java Control Panel). For example running /usr/libexec/java_home -V lists all installed JDKs (both 1.6.* and 1.7.*) on my machine.
So, as discussed in other threads (e.g. What should I set JAVA_HOME to on OSX), I would still recommend adding the following line to your .bash_profile:
export JAVA_HOME=$(/usr/libexec/java_home)

A: This is nuts! How does Oracle provide an installer that doesn't install anything!?
Anyways for me it was:
sudo rm /usr/bin/java
sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home/jre/bin/java /usr/bin/java

where 1.8.0_31 is your installed java version...

A: In case if you have several Java versions on your machine and you want to choose it dynamically at runtime, i.e, in my case, I have two versions:
ls -la /Library/Java/JavaVirtualMachines
drwxr-xr-x  3 root  wheel    96B Nov 16  2014 jdk1.7.0_71.jdk/
drwxr-xr-x  3 root  wheel    96B Mar  1  2015 jdk1.8.0_31.jdk/

You can change them by modifying the /etc/profile content. Just add (or modify) the following two lines at the end of the file:
export JAVA_HOME=YOUR_JAVA_PATH/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH

In my case, it should be like the following if I want to use:
Java 7:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH

Java 8:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH

After saving the file, please run source /etc/profile and it should work. Here are results when I use the first and second option accordingly:
Java 7:
java -version
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)

Java 8:
java -version
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)

The process is similar if your java folder is located in different locations.

A: In my case, the issue was that Oracle was installing it to a different location than I was used to.
Download from Oracle: http://java.com/en/download/mac_download.jsp?locale=en

*

*Verify that it's installed properly by looking in System Prefs:

*

*Command-Space to open Spotlight, type 'System Preferences', hit enter.

*Click Java icon in bottom row. After the Java Control Panel opens, click 'Java' tab, 'View...', and verify that your install worked.  You can see a 'Path' there also, which you can sub into the commands below in case they are different than mine.

*Verify that the version is as you expect (sub in your path as needed):
/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java -version

*Create link from /usr/bin/java to your new install
sudo ln -fs /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin/java

*Sanity check your version:
java -version

A: Simple Solution
export PATH="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin:$PATH"

A: I had run into a similar issue with terminal not updating the java version to match the version installed on the mac.
There was no issue with the JAVA_HOME environmental variable being set
I have come up with a temporary and somewhat painful but working solution.
In you .bash_profile add the line:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_11.jdk/Contents/Home"

(This is the path on my machine but may be different on yours, make sure to get yours. The paths should match up to /Library/Java/JavaVirtualMachines/)
the run source ~/.bash_profile
As I mentioned this is a temporary band-aid solution because the java home path is being hard-coded. There is really no way to set the path to get the latest as that is what Apple is supposedly doing for terminal already and the issue is that Apple's java_home environment variable is not getting updated.

A: I think you can try to install jdk not jre. By installing jdk, the java in /usr/bin/java will be replaced, and all library will work fine.

A: If you have Homebrew installed, you can install java-switcher to change Java default version more quickly
brew tap andycillin/tap
brew install java-switcher

Then you can use just one command to switch your default Java version.
java-switcher 1.7

or
java-switcher 10

A: Oracle's installer puts java inside the /Library/Internet Plug-Ins/JavaAppletPlugin.plugin. And it doesn't overwrite /usr/bin/java. So, if you issue a
whereis java

in the terminal, it'll return /usr/bin/java. (which in turn points to /System/Library/Frameworks/JavaVM.framework/Versions/A/Commands/java, which is Apple's 1.6 version).
So, if you want to use the new java version, replace the /usr/bin/java symlink so that it points to /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java instead:
sudo rm /usr/bin/java
sudo ln -s /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin

A: Since El Capitan, it is difficult to delete the /usr/bin/java symlink, because of the introduction of the new "rootless" policy.
Therefore, I simply added the path to the latest java version (in my case this is /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin) to the PATH in my .bashrc file:
# Use latest java version
export PATH=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin:$PATH

To reload your .bashrc file for the current session, run source ~/.bashrc in the shell. You only have to do this for sessions that had been started before changing the .bashrc file.
Now the latest version is used, when you use java in the shell.

A: Update
brew tap adoptopenjdk/openjdk
brew cask install adoptopenjdk/openjdk/adoptopenjdk8

https://stackoverflow.com/a/28635465
Old version
For me the easiest and cleanest way to go is to install Java using homebrew like described here:
https://stackoverflow.com/a/28635465
brew update
brew cask install java

A: You can execute following command in your terminal :
export PATH="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin:$PATH"

And this replaces the java old with new one.

A: The basic issue: /usr/bin/java is pointing to one provided by OSX itself initially (/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java)
We need to point this to the one downloaded by the JDK installer. The below steps are for OSX 10.10.4 Yosemite.

*

*Open System Preferences -> select Java. The Java window opens.

*Click on Java tab at the top. Click on 'View' button.

*The Java Runtime Environment Settings tab opens as below:

*Double click on the Path item and copy the path (cmd+c). This is the latest one installed by the JDK installer/updater. In my case, the path was /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java

*Open terminal. In this step, we are going to point (symbolic link, ln -s command) the system java binary to the latest one, which we discovered in the previous step. Run the below command:

sudo ln -s /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin/java
Thats it. To verify, you can just run
java -version
on the terminal. It should output the latest version that you installed/updated to.

A: Install the JDK 7 and this problem will solve itself.
Be sure to get the Java Development Kit (JDK) which includes compilers and stuff like that, rather than just the Java Runtime Environment (JRE) .

A: vi ~/.bash_profile
add
export  JAVA_HOME=`/usr/libexec/java_home -v 1.7`
This tells your /usr/bin/java link target to use the latest Java 7 Package installed in
/Library/Java/JavaVirtualMachines/
So for JDK 1.7.0_17 JAVA_HOME would be:
/Library/Java/JavaVirtualMachines/jdk1.7.0_17.jdk/Contents/Home
Note: There were a lot of change in this area recently to move Mac OS X from Appels own System integrated Java packages to Oracle based Java Packages. The above solution is working fine as of Mac OS X 10.8.2

A: I did
export JAVA_HOME=`/usr/libexec/java_home`

and that fixed my Java 8 issue.
before:
java version "1.6.0_31"
Java(TM) SE Runtime Environment (build 1.6.0_31-b04)
Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01, mixed mode)

after:
java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)

A: It is happening because your .bash_profile is not reflecting changes.To reflect it, just use the following command
$ source .bash_profile

A: You can run this command to find the version of Java that's under /Library/Internet Plugins/:
defaults read /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Info.plist CFBundleVersion

A: Since i have not faced this issue , I am taking a hunch --
Can you please try this :
Where does the soft link "java_home" point to :
ls -lrt /usr/libexec/java_home

Output : (Stunted)
    lrwxr-xr-x java_home ->      /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java_home
**ls -lrt /System/Library/Frameworks/JavaVM.framework/Versions
    My MAC Produces the following :
 lrwxr-xr-x CurrentJDK ->
 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents**

 lrwxr-xr-x   Current -> A
 lrwxr-xr-x  1 root  wheel   10 Oct 18 14:39 1.6.0 -> CurrentJDK
 lrwxr-xr-x  1 root  wheel   10 Oct 18 14:39 1.6 -> CurrentJDK
 lrwxr-xr-x  1 root  wheel   10 Oct 18 14:39 1.5.0 -> CurrentJDK
 lrwxr-xr-x  1 root  wheel   10 Oct 18 14:39 1.5 -> CurrentJDK
 lrwxr-xr-x  1 root  wheel   10 Oct 18 14:39 1.4.2 -> CurrentJDK
 lrwxr-xr-x  1 root  wheel   10 Oct 18 14:39 1.4 -> CurrentJDK

Based on this , we might get a hint to proceed further ?

A: i resolved this issue by re installing Yosemite and then cross check java version on terminal (java -version) and (javac -version) .It work perfectly now.It is not changing to java 7 as version 6 still present on (command + n) libray>java>javavirtualmachine>your javac current version.you need to address to java home .

A: I resolved this issue with
sudo rm /usr/bin/java
And I downloaded and installed the last Java SE Runtime Environment:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home/jre/bin/java /usr/bin/java did not work for me because I got Operation not permitted. El Capitan now protects certain system directories in "rootless" mode (a.k.a. System Integrity Protection). It is applicable to macOS Sierra, and probably new macOS versions for the foreseeable future.

A: Installing through distributed JDK DMG from the Oracle site auto-updates everything for me. I have seen (in El Capitan) updating through System Preferences > Java do updates but that do not reflect to command line. Installing through DMG does the job.

A: Check JDK versions installed:
$ ls  /Library/Java/JavaVirtualMachines/
jdk-11.0.2.jdk  jdk1.8.0_91.jdk

Now in your ~/.bashrc export JAVA_HOME specifying the version:
if [ -e /usr/libexec/java_home ]; then
  export JAVA_HOME=$(/usr/libexec/java_home -v 11)
fi

Source the bashrc file and the Java version will be updated:
$ java -version
java version "11.0.2" 2019-01-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)

A: The latest 100% effective method:

in bash:

vim ~/.bash_profile

add
export PATH="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin:$PATH"

*

*:wq to save

*cmd+q force quit bash

*open bash again, and type in java -version
But actually this path points to jre not jdk.
If you want to point the path to JDK, you need

*

*Make sure you have installed JDK not a single JRE runtime

*replace previous path to PATH="/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk", you can go to /Library/Java/JavaVirtualMachines to make sure you have installed the version of JDK you expected.


text:
Q: Let $p \in \mathbb{N}$ be an odd prime number. Show that $(p − 1)! \equiv p − 1 \pmod{2p}$. The furthest I've gotten on this one is I know I need to apply Wilson's Theorem but I'm confused because I don't understand how the $2p$ affects the Theorem itself.

A: So you know Wilson's theorem, which states that $(p-1)! \equiv -1 \mod p$ for any prime number $p$. What does this mean? Let's be really silly and just say the obvious; it means that $(p-1)!=kp-1$ for some integer $k$.
Lets consider the integer $k$. Can $k$ be even? If it were, then $kp-1$ would be odd, which is impossible since $(p-1)!$ contains a factor of $2$, so long as $p$ itself is greater than 2.
If you require more of a hint, let me know in a comment.


text:
Q: Syntax error before string constant in large header file c++ I want to extract vía SDK a video in format .hik (Hikvision) to MP4. My code is the next:
#include <stdio.h>
#include <stdlib.h>
#include "../SDK/incEn/HCNetSDK.h"
#include "Windows.h"

using namespace std;

int saveRecordFile(int userId, char * srcfile, char * destfile) {
    HINSTANCE hGetProcIDDLL = LoadLibrary("D:\\ExtraccionYConversionArchivos\\c++\\Fuente\\SDK\\HCNetSDK.dll");
    int bRes = 1;
    int hPlayBack = 0;
    if ( (hPlayBack = NET_DVR_GetFileByName(userId, srcfile, destfile)) < 0)
    {
       printf("Error en GetFileByName. Error[$d]\n",NET_DVR_GetLastError());
       bRes = -1;
       return bRes;
    }

    if (!NET_DVR_PlayBackControl(hPlayBack, NET_DVR_PLAYSTART,0,NULL))
    {
       printf("Control de play back fallido [%d]\n", NET_DVR_GetLastError());
       bRes = -1;
       return bRes;
    }
    int nPos = 0;
    for (nPos = 0; nPos < 100 && nPos >= 0; nPos = NET_DVR_GetDownloadPos(hPlayBack))
    {
        Sleep(5000);
    }
    printf("Se obtuvo %d\n", nPos);

    if (!NET_DVR_StopGetFile(hPlayBack))
    {
       printf("Error al detener descarga de archivo [%d]\n",NET_DVR_GetLastError());
       bRes = -1;
       return bRes;
    }
    printf("%s\n",srcfile);

    if (nPos < 0 || nPos > 100)
    {
       printf("Error de descarga [%d]\n", NET_DVR_GetLastError());
       bRes = -1;
       return bRes;
    }
    else
    {
        return 0;
    }
}

int main()
{
    printf("Hello world!\n");
    return 0;
}

It uses the HCNetSDK.h header, which throw me an error in multiple lines: syntax error before string constant. This header file have more than 41K lines, and most of the error are after typedef:
typedef void (CALLBACK *MSGCallBack)(LONG lCommand, NET_DVR_ALARMER *pAlarmer, char *pAlarmInfo, DWORD dwBufLen, void* pUser);
NET_DVR_API BOOL __stdcall NET_DVR_SetDVRMessageCallBack_V30(MSGCallBack fMessageCallBack, void* pUser);

What could be the problem? Before this lines, there are more than 6K typedef struct like this:
typedef struct  tagNET_DVR_MATRIX_STATUS_V50
{
    DWORD dwSize;
    BYTE  byMainFrameType;
    BYTE  bySoltNum;
    BYTE  byBoardNum;
    BYTE  byLCDPanelStatus;
    NET_DVR_MATRIX_SUBBOARD_V50 struMatrixSubboard[MAX_MATRIX_SUBBOARD_NUM];
    DWORD dwFanSequence;
    DWORD dwFanConnectStatus;
    DWORD dwFanOperationStatus;
    BYTE  byDeviceModel[32];
    BYTE  byRes[32];
}NET_DVR_MATRIX_STATUS_V50, *LPNET_DVR_MATRIX_STATUS_V50;

And even that I make comments over each typedef struct to catch the mistake, I couldn't figure out how.

A: A few things to try:
Look for another file that includes this header. Does it compile? What other headers does it use and which of those come before this header in the list?
Can you copy (duplicate and rename) this code into a C file with a simple hello world main function? It might force the compiler to tell you which line the actual problem is on.
Are you using an old compiler? I used to get problems with an old version of Visual Studio - it wasn't up to date with C99 so it couldn't compile certain data types (that were no problem for GNU compilers). C standards are sometimes updated and you need to use a suitable compiler (or code in an old style!).
Finally, is it possible to extract or convert the data with ffmpeg? If you can do it on a command line, there's no need to compile any code.


text:
Q: Windows batch : find string contains another string inside a for loop I am trying to convert a set of PNG images to WEBP images using cwebp encoder.
I managed to do it using a JAVA program but now I want to write a batch file to do this task.
I already got metal03326's solution after some searching.
But I want one modification in this that 9 patch images should be skipped.
Here is what I did :
pushd %1

set "DOTNINE=.9"

echo %DOTNINE%

for /f "delims=" %%n in ('dir /b /s /a-d-h-s') do (

set MY=%%~nn

set MY=%MY:~-2%

rem IF NOT ".webp" == "%%~xn" IF NOT "MY" == ".9" ("%~dp0cwebp.exe" -q 80 "%%n" -o "%%n.webp") ELSE (echo File already WEBP.)

)

popd

But I'm getting a syntax error. What is wrong in the above code?

A: To re-assign a variable (namely MY) multiple times in a loop you have to use delayed expansion:
setlocal enableDelayedExpansion
pushd "%~1"
for /f "delims=" %%n in ('dir /b /a-d-h-s') do (
    set MY=%%~nn
    set MY=!MY:~-2!
    IF NOT ".webp" == "%%~xn" IF NOT "!MY!" == ".9" ("%~dp0cwebp.exe" -q 80 "%%n" -o "%%n.webp") ELSE (echo File already WEBP.)
)
popd


text:
Q: How can we check channel is subscribed or not in pubnub? I have subscribed channel during object create and unsubscribing it after destroy.But in some events subscribed channels showing blank array.
So how can I check any channel whether it is blank or not? Any method in ruby to check it?

A: PubNub Presence
Please review the Presence Tutorial for Ruby SDK. You would use here_now API to find out who is subscribed to the channel.
For your Ruby server, you could also use Presence Web Hooks to stay updated when clients join or leave any channel.


text:
Q: Having trouble understanding how many arrays are actually created in the merge sort algorithm I've been studying about the merge sort algorithm and I can't conclude how many arrays are actually created as part of the algorithm. Certain literature says that the entire original array is copied into a new array that's sorted. But that means only 2 arrays were created.
As far as I understand, the merge sort algorithm has 2 major steps. Splitting and Merging. I thought if you give merge sort an array of 100 slots, it actually creates new arrays as it splits down the middle from 100 > 50/50 > 25/25 > 12/13 > 6/5 > 3/3 > 1/1. After all those splits at this point it has 12 or 13 arrays in memory. And then when finally it copies all these into new arrays from 1 > 2 > 3 or 4 > 6 > 12 > 25 > 50 > 100.
That's another 8 arrays (roughly speaking).
But in text books I read things like this:

You may wonder where all these subarrays are located in memory. In the
  algorithm, a workspace array of the same size as the original array is
  created. The subarrays are stored in sections of the workspace array.
  This means that subarrays in the original array are copied to
  appropriate places in the workspace array. After each merge, the
  workspace array is copied back into the original array.

-- Data Structures and Algorithms in Java By Robert Lafore

A: Even if you "split" your array you don't have to create 2 new arrays.
You always have the same number of slots (100 here, even if it is 50*2 or 25*4...)
You just move the data at the correct place in the array (after first split the 50 first slots are the first array and the 50 last slots are the second array )
You don't have to store arrays, just indices of where they start in the big array.

A: Consider a pair of final stages of the typical merge sort implementation. We need two arrays - main and auxiliary one, and merge sub-arrays from aux array to the main one.
before some merge stage (| denotes beginning of each array piece (starting index)) - we are merging A subarray with B subarray to fill the first half of destination array, and merging C subarray with D subarray to fill the second half of destination array:
Auxiliary array:  |AAAA|BBBB|CCCC|DDDD
Main array:       ..................

after merge (I use arbitrary ordering)
Auxiliary array:  ...............
Main array:       ABBABBAADCDDCCDC

after copy, before final merge
Auxiliary array:  |ABBABBAA|DCDDCCDC
Main array:      ................

A: The text book is referring to reasonably efficient implementations of merge where a one time allocation of a workspace array the same size as the original is done. After that point, then all of the sub-arrays to be merged are portions of either the workspace array or the original array, accessed via indices (or pointers).
A top down merge sort uses recursion to generate a dynamic stack of pairs of indices to represent the sub-arrays. A bottom up merge sort skips the recursion, and uses iteration to generate the indices, starting with a sub-array size of 1.


text:
Q: Split a string every 5 characters Suppose I have a long string:
"XOVEWVJIEWNIGOIWENVOIWEWVWEW"

How do I split this to get every 5  characters followed by a space?
"XOVEW VJIEW NIGOI WENVO IWEWV WEW"

Note that the last one is shorter.
I can do a loop where I constantly count and build a new string character by character but surely there must be something better no?

A: You can try something like the following:
s <- "XOVEWVJIEWNIGOIWENVOIWEWVWEW" # Original string
l <- seq(from=5, to=nchar(s), by=5) # Calculate the location where to chop

# Add sentinels 0 (beginning of string) and nchar(s) (end of string)
# and take substrings. (Thanks to @flodel for the condense expression)
mapply(substr, list(s), c(0, l) + 1, c(l, nchar(s)))

Output:
[1] "XOVEW" "VJIEW" "NIGOI" "WENVO" "IWEWV" "WEW"

Now you can paste the resulting vector (with collapse=' ') to obtain a single string with spaces.

A: No *apply stringi solution:
x <- "XOVEWVJIEWNIGOIWENVOIWEWVWEW"
stri_sub(x, seq(1, stri_length(x),by=5), length=5)
[1] "XOVEW" "VJIEW" "NIGOI" "WENVO" "IWEWV" "WEW"

This extracts substrings just like in @Jilber answer, but stri_sub function is vectorized se we don't need to use *apply here.

A: Using regular expressions:
gsub("(.{5})", "\\1 ", "XOVEWVJIEWNIGOIWENVOIWEWVWEW")
# [1] "XOVEW VJIEW NIGOI WENVO IWEWV WEW"

A: You can also use a sub-string without a loop.  substring is the vectorized substr
x <- "XOVEWVJIEWNIGOIWENVOIWEWVWEW"
n <- seq(1, nc <- nchar(x), by = 5)
paste(substring(x, n, c(n[-1]-1, nc)), collapse = " ")
# [1] "XOVEW VJIEW NIGOI WENVO IWEWV WEW"

A: Using sapply
> string <- "XOVEWVJIEWNIGOIWENVOIWEWVWEW"
> sapply(seq(from=1, to=nchar(string), by=5), function(i) substr(string, i, i+4))
[1] "XOVEW" "VJIEW" "NIGOI" "WENVO" "IWEWV" "WEW"


text:
Q: Ionic Native HTTP request returns Blob without type I have this piece of Code that grabs the Image string and encodes it as Blob
const reqOptions: any = {
    method: 'get',
    responseType: 'blob',
    headers: {
        accept: 'image/*'
    }
}
ionresp = await this.ionicHttp.sendRequest(url, reqOptions)

if i log the Blob im getting
Blob {size: 15312, type: ""}

The Blob i need has a type of image/png but im not able to convert the Blob afterwards or manipulate the requested data so i get a Blob type set
if i try to fetch the data with a ionicHttp.get() and convert it into a Blob myself the ionresp  is returning an empty Blob
resp.Data = new Blob([ionresp], {type: type})

A: There was no Error with the Blob or returned but the FileReader doesnt work in Capacitor and i had to implement a workaround to get it working.
getFileReader(): FileReader {
    const fileReader = new FileReader();
    const zoneOriginalInstance = (fileReader as any)
    ["__zone_symbol__originalInstance"];
    return zoneOriginalInstance || fileReader;
}

convertBlobToBase64(blob: Blob): Promise<string> {
    return new Promise<string>((resolve, reject) => {
        let reader = this.getFileReader();
        reader.readAsDataURL(blob);
        reader.onload = () => resolve(reader.result.toString());
        reader.onerror = error => reject(error);
    })
}

This is neccesary because Capacitor creates the FileReader in his own Zone and the other code cannot interact with it.


text:
Q: Calculating avg time of activity in the morning I am creating a query to keep track of students' activity at school on MS Acces 2010. And I have a table as follows:
    ID       | Date     |  ActivityCode | Starttime | Endtime | Duration
    ----------------------------------------------------------
    1234     | 1/1/2020 |        a       | AM       | AM      | #(= 3Hours / Total number of AM per person per day)
    1234     | 1/1/2020 |        a       | AM       | AM      | #In this case, Duration = 3/2 = 1.5 hr
    9876     | 1/1/2020 |        a       | AM       | AM      |#(= 3Hours / Total number of AM per person per day)
    9876     | 1/1/2020 |        a       | AM       | AM      | #In this case, Duration = 3/3 = 1 hr
    9876     | 1/1/2020 |        a       | AM       | AM      |  #In this case, Duration = 3/3 = 1 hrs
    9876     | 1/1/2020 |        a       | 1200     | 1500    |  #In this case, Duration = 1500-1200 = 3 hrs

My current attempt on getting the duration
IIF(starttime="AM" or starttime="PM",
#(= 3Hours / Total number of AM per person per day),
CDate(TimeSerial(Val([EndTime])\100,Val([EndTime]) Mod 100,0)-
TimeSerial(Val([starttime])\100,Val([starttime]) Mod 100,0)))
AS Duration,

But I am not sure how to write the #(= 3Hours / Total number of AM per person per day) part in SQL. Any help is appreciated.

A: Try with:
Select ID, [Date], 3/Count(*) As Duration
From YourTable
Group By ID, [Date]

Edit - with time values:
Select
    ID,
    [Date],
    IIF(
        [StartTime] = 'AM' Or [StartTime] = 'PM',
        3/Count(*),
        (TimeSerial(Val([EndTime])\100,Val([EndTime]) Mod 100,0)-TimeSerial(Val([starttime])\100,Val([starttime]) Mod 100,0))*24
        ) As Duration
From
    YourTable
Group By
    ID,
    [Date]

A: Try this query:
SELECT ID, Date, (3/COUNT(*)) as Duration
FROM Table1
WHERE Starttime alike "AM"
GROUP BY ID , Date;

This query will get the list of IDs, and group them based on the date. And it will get only records with AM status only.


text:
Q: Leafletjs split polygon I have a polygon and it has circles on it. I drew lines from the intersections of the circles. Actually I want to split this big polygon by lines. I have numbered the polygons to be divided in the figure.
I have uploaded all the code both in the jsfiddle environment and here.
I have a polygon in my codes and there are two circles on it. I created lines from the intersections of the circles. I want to split the polygon according to these lines as shown in the figure
JsFiddle Link:   https://jsfiddle.net/hrnbydgn/et2635hq/2
var map = L.map('map').setView([41.2819587,28.4810230], 18);

    var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '© OpenStreetMap'
    }).addTo(map);

var cor3 = [
        [41.2819587,28.4810230],
        [41.2831258,28.4795746],
        [41.2834906,28.4823748],
        [41.2820716,28.4816051],
        [41.2819587,28.4810230]
    ];

var p3 = L.polyline(cor3, {
  polygon: true,
  fill: true,
  color:'yellow'
});
var ObsCenter = new Array();
var bboxObs = new Array();
var center = [28.480423339203874,41.28301959608716];
ObsCenter.push(center);
var radius = 6;
var options = {steps: 10, units: 'meters'};
var circle = turf.circle(center, radius, options);
var t1 = L.geoJSON(circle).addTo(map);
let bbox = turf.bbox(circle);
bboxObs.push(turf.bboxPolygon(bbox));

var center = [28.480823339215884,41.28261979629536];
ObsCenter.push(center);
var radius = 7;
var options = {steps: 10, units: 'meters'};
var circle = turf.circle(center, radius, options);
var t1 = L.geoJSON(circle).addTo(map);

bbox = turf.bbox(circle);
bboxObs.push(turf.bboxPolygon(bbox));

var polygon = turf.lineToPolygon(p3.toGeoJSON());
L.geoJSON(polygon).addTo(map);

let bbox2 = turf.bbox(polygon);
let bboxPoly = turf.bboxPolygon(bbox2);

var splice = new Array();

for(var sp = 0; sp<bboxObs.length; sp++){
splice.push([
[bboxPoly["bbox"][1],bboxObs[sp]["bbox"][0]],
[bboxPoly["bbox"][3],bboxObs[sp]["bbox"][0]]
]);

splice.push([
[bboxPoly["bbox"][1],bboxObs[sp]["bbox"][2]],
[bboxPoly["bbox"][3],bboxObs[sp]["bbox"][2]]
]);

splice.push([
[bboxObs[sp]["bbox"][1],bboxPoly["bbox"][0]],
[bboxObs[sp]["bbox"][1],bboxPoly["bbox"][2]]
]);

splice.push([
[bboxObs[sp]["bbox"][3],bboxPoly["bbox"][0]],
[bboxObs[sp]["bbox"][3],bboxPoly["bbox"][2]]
]);

}

var spliced = new L.Polyline(splice, {
    color: 'red',
    weight: 2,
    opacity: 0.5,
    smoothFactor: 1
}).addTo(map);

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css" integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ==" crossorigin=""/>


text:
Q: paintComponent method not being called by repaint I'm trying to call my paintComponent method by using repaint but it is never being called. This is my first class:
public class start
{
    public static void main(String[] args){
        Frame f = new Frame();
        f.createFrame();
    }
}

And this is the class that I want the paintComponent method to be called to but all that happens is a blank frame appears:
import javax.swing.JButton;
import javax.swing.JComponent;
import java.awt.Graphics;
import javax.swing.JFrame;
import java.awt.image.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.Timer;

public class Frame implements Runnable,ActionListener
{
JFrame window = new JFrame("Frame");
int i = 0;
Canvas myCanvas = new Canvas();
public void createFrame(){
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 700, 500);
    window.setFocusable(true);
    window.setFocusTraversalKeysEnabled(false);
    window.setVisible(true);
    (new Thread(new Frame())).start();
}

public void run(){
    Timer timer = new Timer (17,this);
    timer.start();
}

public void actionPerformed(ActionEvent e){
    myCanvas.updateGame();
    myCanvas.render();
    window.add(myCanvas);
}
}

class Canvas extends JPanel{
int x = 10;
int y = 10;
public void updateGame(){
    x++;
}

public void render(){
    repaint();
    System.out.println("repaint");
}

@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g.drawString("hi",x,y);
    System.out.println("paint");
}

}
Repaint is called multiple times but paint is never called. Why isn't the paintComponent method being called by repaint?

A: Instead of creating a new frame, pass in the existing frame, I've commented the line below:
public void createFrame(){
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 700, 500);
    window.setFocusable(true);
    window.setFocusTraversalKeysEnabled(false);
    window.setVisible(true);
    (new Thread(new Frame())).start(); <--- instead of creating a new frame, pass in the existing frame
}

You should really consider the following improvements as well:
1) Don't name your class Frame, as it collides with Frame
2) Move the body of createFrame as well as the following three lines:
JFrame window = new JFrame("Frame");
int i = 0;
Canvas myCanvas = new Canvas();

Into a constructor and make these local variables like Canvas into member fields.
3) Remove the last line that creates the thread out of the constructor, and expose it as a method (e.g 'startAnimation') and call it after you've created your object.
EDIT:
Try this:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

    public class Frame implements Runnable, ActionListener
    {
        final JFrame window;
        final Canvas myCanvas;

        public Frame(){
            this.window = new JFrame("Frame");
            this.myCanvas = new Canvas();
            this.window.add(this.myCanvas);
            this.window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.window.setBounds(30, 30, 700, 500);
            this.window.setFocusable(true);
            this.window.setFocusTraversalKeysEnabled(false);
            this.window.setVisible(true);
        }

        public void startApp() {
            final Thread t = new Thread(this);
            t.start();
        }

        public void run(){
            final Timer timer = new Timer (1000,this);
            timer.start();
        }

        public void actionPerformed(ActionEvent e){
            myCanvas.updateGame();
            window.repaint();
        }

        public static void main(String[] args) {
            final Frame f = new Frame();
            f.startApp();
        }
    }

    class Canvas extends JPanel {
        int x = 10;
        int y = 10;
        public void updateGame() {
            x++;
        }

        @Override
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g.drawString("hi", this.x, this.y);
            System.out.println("paint");
        }
    }


text:
Q: Moving SQL Data into Azure SQL PaaS I have a database in the SQL Server installed on Azure VM. DB Size is 2 GB.
How and what is the best approach to move all data into Azure SQL PAAS Service?

A: SQL Migration using data-tier application export/import (BACPAC)
The BACPAC file encapsulates the database schema as well as the data stored in a database application that can be simple imported to an Azure SQL Database.
Workloads using the source database need to be taken offline during the export process to ensure that the exported BACPAC file contains all data in a complete and consistent state.
Export to bacpac file in SQL Server Management Studio (SSMS)
You can follow this post.

*

*Open and connect database file in SQL Server Management Studio (SSMS).

*To export a database file, right click on the name of the database. In the context menu, select Tasks > Export Data-tier Application.

*The option will open the wizard. Click Next> Introduction page and go to the Export Settings.

Import a bacpac file to Azure SQL

*

*After you connect to your Azure sql, go to Object Explorer pane, right click the database, and select Import Data-tier.

*The option will open the wizard. Click Next> Introduction page and go to the Import Settings.

*The Import settings are requested to the bacpac file to import.

A: While the method posted by @Harris Xu is absolutely correct, I am adding the issues which I faced when I migrated my 500+ GB SQL Server DB from Azure VM to PaaS using .bacpac method.
Azure SQL DB is in a away limited when compared to On-prim SQL Server or SQL Server on VM's.
You will not face these issues while creating the .bacpac file but when you try to import, it might give some of the following compatibility issues.

*

*Master Keys , Symmetric Keys, Service Queues and certificates cannot
be migrated to cloud. Drop them before preparing bacpac.

*Drop orphaned Users.

*If you are using XP_CMDSHELL, Trace Flags, DBCC commands or column store indexes, you got to remove them too.

*Cross DB Queries are not allowed on Azure SQL DB. Remove all occurrences of ..

*If you are calling an API from your stored proc then that too is not possible in Azure SQL DB. As a workaround you can use Logic Apps on Azure.
Moreover, Microsoft Migration assistant can help you find compatibility issues before hand too. You can download it here.
NOTE : This no way the full list of issues, I faced them because I was using all above features, if you are not using them you will not face them.


text:
Q: How can i convert my existing mongo db query in to spring boot using aggregation class I wrote mongodb query. And am facing some issue while converting it in spring boot using aggregation class.So, please help me, i want it to convert it in spring boot using aggregation class.
db.api_audit.aggregate([{

  $match: {
      merchant_id: '015994832961',
      request_time: {$gte: ISODate("2017-05-11T00:00:00.0Z"),
          $lt: ISODate("2017-05-12T00:00:00.0Z")}}},
{
   $group:
    {
        _id: {
        SERVICE_NAME: "$service_name",

        STATUS: "$status"
    },
    count: {
        "$sum": 1
    }
}
}, {

 $group: {
    _id: "$_id.SERVICE_NAME",

    STATUSCOUNT: {
        $push: {
            Service_name: "$_id.STATUS",
            count: "$count"
        }
    }
}
 },
 { $sort : { "STATUSCOUNT.count" : -1} }
  ])

Below is the db query response
{
"_id" : "sendOTP",
"STATUSCOUNT" : [
    {
        "status" : "SUCCESS",
        "count" : 2.0
    }
]
}

Thanks in advance.

A: First you create all the required operations and then you add them to an aggregation pipeline. Then you feed it to an autowired mongotemplate.
Something like this:
@Autowired
private final MongoTemplate mongoTemplate;

void aggregate()
{

    Criteria match = where("merchant_id").is("015994832961").andOperator(where("request_time").gte(Date.parse("2017-05-11T00:00:00.0Z")).lt(Date.parse("2017-05-11T00:00:00.0Z")));
    GroupOperation groupOperation1 = group(fields().and("SERVICE_NAME").and("STATUS")).count().as("count");
    GroupOperation groupOperation2 = ...//(not sure how push works here, but it should not be hard to figure out)
    SortOperation sortOperation = sort(DESC, "STATUSCOUNT.count");

    Aggregation aggegation = Aggregation.newAggregation(match, groupOperation1, groupOperation2, sortOperation);

    List<Result> results = mongoTemplate.aggegate(aggregation, ObjectOfCollectionToRunOn.class, Result.class).getMappedResults();
}


text:
Q: Variable Name field I have le following fields:
Gigabytes_tier_1__c
Gigabytes_tier_2__c
Gigabytes_tier_3__c
Gigabytes_tier_4__c
I would like write like this:
for (Integer i=1;i<5; i++) {
                     OpportunityLineItem newOpptLineItem = new OpportunityLineItem();
                     newOpptLineItem.Tier__c= opptInserted.Gigabytes_tier_+i+__c;

but it doesn't work.
Do you know how achieve this?
Thanks in advantage for any advice.
BR

A: you can also use the .get method of an sObject with a fieldname.
So something like this
String fieldName = 'Gigabytes_tier_' + i + '__c';
newOpptLineItem.Tier__c = (Decimal)opptInserted.get(fieldName);  //cast the result to the appropriate datatype


text:
Q: ASP.NET WebAPI Service to Service Authentication for services within corp (intranet) What are the best way for ASP.NET WebAPI Service to Service Authentication for services within corp (intranet)? Certificates, JSON Web Token or OAuth?

A: I think the right answer depends.  You may get different answers based on what others use.  But the best advice I've heard is to not create your own.  Use a standard that is well documented and stick to that. OAuth is a good one.
Also as far as just providing for corporate purposes, if you can use a good standard then use that.  Sometimes policies and other software make that difficult.  But if your software ever gets pushed outside the company it would be better off using something in existence.


text:
Q: Can all invited users check every apps uploaded by individual users in google play console? Hi i have a doubt regarding the play console
Can all invited users check every apps uploaded by individual users in play console?
I have multiple users to invite to google play console to upload their individual apps, but the apps uploaded by a user should not be visible to others.


text:
Q: Execution order of global variable destructor and gcc attribute__((destructor)) This is a GCC specific issue. I'm encountering a werid issue in a .so library. The demo code of this .so library could be:
__attribute__((init_priority(101))) std::unique_ptr<object_t> global_object;

__attribute__((constructor)) void entry_constructor() {
    global_object = make_unique<object_t>();
}

__attribute__((destructor)) void entry_destructor() {
    global_object.reset(nullptr);
}

I know the global global_object would be released automatically even without entry_destructor. But I just want to give you an example. For debug building, the entry_destructor runs well. But for release building, it crashed.
I set break points and debugged this issue. In debug build, the entry_destructor is executed firstly, then runs std::unique_ptr::destructor. But in release build, the std::unique_ptr::destructor is run before entry_destructor.
Firstly hit here:
#3  std::unique_ptr<...> >::~unique_ptr (this=<optimized out>, __in_chrg=<optimized out>) at /usr/include/c++/7/bits/unique_ptr.h:263
#4  0x00007ffff5b8c0f1 in __run_exit_handlers (status=0, listp=0x7ffff5f34718 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true, run_dtors=run_dtors@entry=true) at exit.c:108
#5  0x00007ffff5b8c1ea in __GI_exit (status=<optimized out>) at exit.c:139
#6  0x00007ffff5b6ab9e in __libc_start_main (main=0x555555672c51 <main(int, char**)>, argc=1, argv=0x7fffffffe2b8, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffffffe2a8) at ../csu/libc-start.c:344
#7  0x000055555566eb0a in _start ()

Then hit here:
#3  std::unique_ptr<...>::reset (__p=0x555555893ae0, this=0x55555585bc70 <...>) at /usr/include/c++/7/bits/unique_ptr.h:371
#5  0x000055555567b021 in entry_destructor () at ...
#6  0x00007ffff7de5bc3 in _dl_fini () at dl-fini.c:138
#7  0x00007ffff5b8c0f1 in __run_exit_handlers (status=0, listp=0x7ffff5f34718 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true, run_dtors=run_dtors@entry=true) at exit.c:108
#8  0x00007ffff5b8c1ea in __GI_exit (status=<optimized out>) at exit.c:139
#9  0x00007ffff5b6ab9e in __libc_start_main (main=0x555555672c51 <main(int, char**)>, argc=1, argv=0x7fffffffe2b8, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffffffe2a8) at ../csu/libc-start.c:344
#10 0x000055555566eb0a in _start ()

I marked global_object as __attribute__((init_priority(101))) because only by that it can be initialized before entry_construtor, otherwise entry_contructor would crash when accessing global_object.
I also tried to mark global_object as static, but it didn't help either.
I hope all global variables should be destructed after entry_destructor, whether it's debug build or release build. All the documents and discussions I can find are about the construt and destruct order or global variables, but not the order between global variable destruct and __attribute__((destructor)). Is there any GCC rule for that? Or is it an undefined behavior?


text:
Q: Why can I not hide an element on click using jQuery? I want to let a div show and disappaer with jquery and css.
The code does not work:
HTML

            click to show content

                here is content here is content here is content

remove content

            </div

jQuery
$(document).ready(function() {
    $('#b1').click(function() {

        $('.content').css({
            "display": "block"
        });
    });

    $('#b2').click(function() {

        $('.content').css({
            "display": "none"
        });
    });
});

Demo: http://jsfiddle.net/jTgRF/41/

A: The problem is that you don't stop the event from propagating.
When you click the button it actually hide the element at first, but the event propagate up to the parent element, at which you catch the click and show it again. It goes so fast it looks like nothing is happening, but actually when you click on #b2, the elements get hidden, the event then bubble up to the parent #b1, to which you have attached click-event listener to show the content.
Therefor, you need to use .stopPropagation() on #b2.
$(document).ready(function(){
     $('#b1').click(function(){
           $('.content').show();
    });

    $('#b2').on("click", function(e){
           $('.content').hide();
            e.stopPropagation();
    });
});

What you need to do is to pass the click event to the call-backfunction (declared e in my example) and then call stopPropagation() on it to make sure that it doesn't bubble up to the parent element.
Here is a working example: http://jsfiddle.net/jTgRF/64/
Note I use .show() and .hide(), which is exactly the same as what you do with .css(), but is more readable in my opinion.
Edit:
As noted by Venu in his answer, the content will show if you click on the black-area as well, not just the "show content"-text. The easiest way to solve that would be to just move the id="b1" attribute from the div with class content and put it on the a-element instead.
See my updated fiddle: http://jsfiddle.net/jTgRF/65/

A: since, you are attaching an event for an element which is not available in dom, event wont get attached to the element. Use live
$('#b2').live('click', function(){

               $('.content').css({"display":"none"});
        });

Attach an event handler for all elements which match the current selector, now and in the future.
EDIT
1)Use on instead of live as Live is deprecated.
2) There is one more issue with your css. you have set height to 150px for box class. so if you click on black area also, event gets fired.
So move the b2 element outside b1, this would solve the event propagation to the parent-element also.

A: You need to change the button click handler to
$('#b2').click(function(e){
           e.stopPropagation();
           $('.content').css({"display":"none"});
    });

You need to add event.stopPropagation() Or click event will be propagated to the parent div and .content will be hidden immediately again.
Demo: http://jsfiddle.net/joycse06/jTgRF/56/
You should use jQuery .show() and .hide() to show/hide elements.

A: Venu's anwser works but live() is depracated.
You should use on() instead :
jQuery .on function for future elements, as .live is deprecated
Code
$(document).ready(function(){
    $('#b1').click(function(){
        $('.content').css({"display":"block"});
    });

    $(document).on('click', '#b2', function(){
        $('.content').css({"display":"none"});
    });
});

Hope this helps


text:
Q: Can't set default timezone in PHP I've set this in my php.ini file, and restarted php5-fpm process
date.timezone = "UTC"

But phpinfo() script still shows this:
date.timezone   America/New_York    America/New_York

phpinfo() also shows that correct ini file is being used.
I've restarted - but problem persisted. Then I did:
sudo service nginx stop
sudo service apache2 start

and date.timezone is correct when mod-php (apache2) is in use instead of fcgi that is php in nginx.

A: You probably edited the wrong php.ini. See php_info() (or php -i for the cli interpreter) which one is used. For example on ubuntu (and probably other linux distributions) its /etc/php5/cli/php.ini for the cli-interpreter, /etc/php5/apache/php.ini/ for the one used by Apaches mod_php and /etc/php5/cgi/php.ini used by php5-cgi (which is used by nginx).

A: List of supported timezone values: http://php.net/timezones

A: The problem seems to be be with php-fpm processes that lingers around and refers to the old php.ini file settings.
This worked for me:
Get the process ids for php-fpm
root@thiru:/etc/php5/fpm/conf.d# ps aux | head -1 && ps aux | grep php-fpm | grep -v grep
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root     32650  0.0  0.5  86624 17032 ?        Ss   21:44   0:00    php-fpm: master process (/etc/php5/fpm/php-fpm.conf)
www-data 32652  0.0  0.1  86624  4700 ?        S    21:44   0:00 php-fpm: pool www
www-data 32653  0.0  0.1  86624  4704 ?        S    21:44   0:00 php-fpm: pool www

Kill the processes. Starting with the master.
kill -9 32650
kill -9 32652
kill -9 32653

Start php-fpm using the init script
service php5-fpm start or /etc/init.d/php5-fpm start

A: In my installation BY DEFAULT I had realy weird configuration. File /etc/php/7.3/fpm/pool.d/www.conf had such a setting at the end of the file
php_admin_value[date.timezone] = UTC

It lead to timezone setting being ignored in php.ini and default system timezone being ignored.

A: Check your FPM Installation, if you have a pool with a active chroot!
If you have a chroot environment, you need to copy the file /etc/localtime (symlink to /usr/share/zoneinfo/xyz) and the directory /usr/share/zoneinfo to your chroot.
Possible Error-Messages:
Fatal error: phpinfo(): Timezone database is corrupt - this should *never* happen!
Warning: phpinfo(): Invalid date.timezone value 'UTC', we selected the timezone 'UTC' for now.

See https://serverfault.com/questions/413293/php-fpm-chroot-jail-corrupts-timezone-db


text:
Q: Cannot bind list of items in GridView column I'm building an application that show to user the live result of a matches series. I setup the structure of data as follows: Countries->Leagues->Matches
In particular in the ViewModel I've created an observable collection of countries as follows:
private ObservableCollection<Models.Country> _countries = new ObservableCollection<Models.Country>();

public ObservableCollection<Models.Country> Country
{
    get { return _countries; }
}

and the model:
public class Country
{
    public string Name { get; set; }
    public List<League> League { get; set; }
}

public class League
{
    public string Name { get; set; }
    public List<Event> Event { get; set; }
}

the class Event contains the properties of each event, in particular the name of the event, the date and so on..
I valorize this data as follows:
Country country = new Country();
country.Name = "Italy";

League league = new League();
league.Name = "Serie A";
League league2 = new League();
league2.Name = "Serie B";

Event @event = new Event();
@event.MatchHome = "Inter";

Event event2 = new Event();
@event.MatchHome = "Milan";

league.Event = new List<Event>();
league2.Event = new List<Event>();

league.Event.Add(@event);
league2.Event.Add(event2);

country.League = new List<League>();

country.League.Add(league);
country.League.Add(league2);

lsVm.Country.Add(country); //lsVm contains the ViewModel

How you can see I create an object called country (Italy) that will contains in this case two leagues (Serie A) and (Serie B). Each league contains one match actually in playing Serie A -> Inter and Serie B -> Milan
I add the league two the country, and finally the country to the observable collection in the viewmodel. Until here no problem. The problem's come in the xaml.
So I've organized all of this stuff inside of GroupViews, for doing this I'm using a CollectionViewSource, in particular:
<CollectionViewSource Source="{Binding Country}" x:Key="GroupedItems">
       <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="Name" />
            <PropertyGroupDescription PropertyName="League.Name" />
       </CollectionViewSource.GroupDescriptions>

the code above is located in my Window.Resources, and tell to CollectionViewSource to organize for country name and leagues name the respective leagues associated.
I've two ListView as this:
<ListView ItemsSource="{Binding Source={StaticResource GroupedItems}}" Name="Playing">
                    <ListView.View>
                        <GridView>
                            <GridViewColumn Header="Date" Width="150" DisplayMemberBinding="{Binding Path = League.Event.MatchDate}"/>
                            <GridViewColumn Header="Minutes" Width="70" DisplayMemberBinding="{Binding Path = League.Event.MatchMinute}"/>
                            <GridViewColumn Header="Home" Width="150" DisplayMemberBinding="{Binding Path = League.Event.MatchHome}"/>
                            <GridViewColumn Header="Score" Width="100" DisplayMemberBinding="{Binding Path = League.Event.MatchScore}"/>
                            <GridViewColumn Header="Away" Width="150" DisplayMemberBinding="{Binding Path = League.Event.MatchAway}"/>
                        </GridView>
                    </ListView.View>
<GroupStyle>
                            <GroupStyle.ContainerStyle>
                                <Style TargetType="{x:Type GroupItem}">
                                    <Setter Property="Template">
                                        <Setter.Value>
                                            <ControlTemplate>
                                                <Expander IsExpanded="True" Background="#4F4F4F" >
                                                    <Expander.Header>
                                                        <StackPanel Orientation="Horizontal" Height="22">
                                                            <TextBlock Text="{Binding Name}" FontWeight="Bold" Foreground="White" FontSize="22" VerticalAlignment="Bottom" />
                                                            <TextBlock Text="{Binding ItemCount}" FontSize="22" Foreground="Orange" FontWeight="Bold" FontStyle="Italic" Margin="10,0,0,0" VerticalAlignment="Bottom" />
                                                            <TextBlock Text=" Leagues" FontSize="22" Foreground="White" FontStyle="Italic" VerticalAlignment="Bottom" />
                                                        </StackPanel>
                                                    </Expander.Header>
                                                    <ItemsPresenter />
                                                </Expander>
                                            </ControlTemplate>
                                        </Setter.Value>
                                    </Setter>
                                </Style>
                            </GroupStyle.ContainerStyle>
                        </GroupStyle>

The GroupStyle contains the leagues that will contains each match, now the problem is that I can't see any league and any match 'cause this item are inside of a list. So for display them I should write in the xaml this code:
<PropertyGroupDescription PropertyName="League[0].Name" />

this fix the bug of the league name displayed into GroupStyle
and in the GridView:
<GridViewColumn Header="Casa" Width="150" DisplayMemberBinding="{Binding Path = League[0].Event[0].MatchHome}"/>

but this of course will display only the specific item.. not the list of items. I need help to fix this situation, I cannot figure out. Thanks.

A: If you want to use the ListView's grouping abilities, you have to provide it a flat list of the items you want to group (in your case, the leagues), not the header items. The CollectionView does the grouping for you by specifying GroupDescriptions.
For example, assuming the League class has a Country property:
class ViewModel
{
    public ObservableCollection<Models.Country> Country { get; }

    public IEnumerable<League> AllLeagues => Country.SelectMany(c => c.Leagues);
}

public class League
{
    public string Name { get; set; }
    public List<Event> Event { get; set; }
    // add Country here
    public Country Country { get; set; }
}

class

<CollectionViewSource Source="{Binding AllLeagues}" x:Key="GroupedItems">
   <CollectionViewSource.GroupDescriptions>
        <PropertyGroupDescription PropertyName="Country" />
   </CollectionViewSource.GroupDescriptions>

Then when you bind the columns, you bind directly to League properties, e.g.:
<GridViewColumn Header="Date" DisplayMemberBinding="{Binding Path=Event.MatchDate}"/>

And in the group style you can bind to Country properties, as you've done.
Alternative solution
If you want to display any hierarchical data in WPF you can either use a control that was built for it (such as the Xceed data grid) or hack it together with the built-in WPF data grid's row details.
Here's a sample XAML for this (note it uses your original data structures without the modifications I suggested above). These are essentially 3 data grids nested within each other. Each grid has its own set of columns, so you can define anything you want for each level (Country, League, Event).
<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        xmlns:app="clr-namespace:WpfApp"
        d:DataContext="{d:DesignData ViewModel}">
    <FrameworkElement.Resources>
        <app:VisibilityToBooleanConverter x:Key="VisibilityToBooleanConverter" />
        <DataTemplate x:Key="HeaderTemplate">
            <Expander IsExpanded="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGridRow}, Path=DetailsVisibility, Converter={StaticResource VisibilityToBooleanConverter}}" />
        </DataTemplate>
        <Style x:Key="DataGridStyle"
               TargetType="DataGrid">
            <Setter Property="RowHeaderTemplate"
                    Value="{StaticResource HeaderTemplate}" />
            <Setter Property="RowDetailsVisibilityMode"
                    Value="Collapsed" />
            <Setter Property="AutoGenerateColumns"
                    Value="False" />
            <Setter Property="IsReadOnly"
                    Value="True" />
        </Style>
    </FrameworkElement.Resources>
    <Grid>
        <DataGrid ItemsSource="{Binding Country}"
                  Style="{StaticResource DataGridStyle}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name"
                                    Binding="{Binding Name}" />
            </DataGrid.Columns>
            <DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <DataGrid ItemsSource="{Binding League}"
                              Style="{StaticResource DataGridStyle}">
                        <DataGrid.Columns>
                            <DataGridTextColumn Header="Name"
                                                Binding="{Binding Name}" />
                        </DataGrid.Columns>
                        <DataGrid.RowDetailsTemplate>
                            <DataTemplate>
                                <DataGrid ItemsSource="{Binding Event}"
                                          AutoGenerateColumns="False"
                                          IsReadOnly="True">
                                    <DataGrid.Columns>
                                        <DataGridTextColumn Header="Match Home"
                                                            Binding="{Binding MatchHome}" />
                                    </DataGrid.Columns>
                                </DataGrid>
                            </DataTemplate>
                        </DataGrid.RowDetailsTemplate>
                    </DataGrid>
                </DataTemplate>
            </DataGrid.RowDetailsTemplate>
        </DataGrid>
    </Grid>
</Window>

You'll also need the code for the converter I used:
public class VisibilityToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        => value as Visibility? == Visibility.Visible;

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        => value as bool? == true ? Visibility.Visible : Visibility.Collapsed;
}


text:
Q: Problem with Tailwind and NexJS render, with some props avatar is hidden have problem with avatar, when I change size (28, 18, 16) - everything is fine.
But when I change size to 24, 22, 20 and other - image is hidden.
Here is my screenshots and code:
Img Component:
import Image from "next/image";

function Img(props) {
  return (
    <>
      <div className={`relative flex h-[${props.size}px] w-[${props.size}px]`}>
        <Image
          src={
            "https://images.unsplash.com/photo-1509967419530-da38b4704bc6?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2095&q=80"
          }
          alt="image"
          fill
          style={{
            objectFit: "cover",
            borderRadius: "999px",
          }}
        />

    </>
  );
}

export { Img };

import { Img } from "../../elements/common/Img";

export default function AvatarPage() {
  return (
    <>

    </>
  );
}

Example 1
Example 2
What I do wrong?
Example 3 - if I change size to 38px the image will appear

A: That is simply not how Tailwind works.
Tailwind just-in-time basically scrapes all of your files (that matches paths in your content from tailwind.config.js) for existing classes and add them to the final distributed CSS. It is totally impossible to create Tailwind dynamic classes via props. You should use  style= to add Height.
As a little tip, in the case the possible classes to be generated would be predictable (not [] values, but Tailwind classes), you can make usage of safelist which you can find the documentation here.


text:
Q: How to fix "Type 'Promise<{}>' is missing the following properties from type 'Observable'" in angular Here's the code:
 const reportModules = [
      { url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } },
      {
        url: 'application1',
        params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() }
      },
      {
        url: 'application2',
        params: {
          to: format(endOfWeek(TODAY), DATE_FORMAT).toString(),
          from: format(startOfWeek(TODAY), DATE_FORMAT).toString()
        }
      },
      {
        url: 'application3',
        params: {
          to: format(endOfWeek(TODAY), DATE_FORMAT).toString(),
          from: format(startOfWeek(TODAY), DATE_FORMAT).toString()
        }
      }
    ];

    const promises = reportModules.map(
  target =>
    new Promise(resolve => {
      this.notificationService
        .getSummary(target.url, target.params)
        .pipe(take(1))
        .subscribe(
          (result: Response) => {
            resolve({ target, result });
          },
          (err: Error) => {
            // return reject(err);
          }
        );
    })
);
        const observables: Observable<any>[] = promises;

        merge(...observables).subscribe((results) => { ... }

how to fix the error let observables: Observable<any>[]
'observables' is declared but its value is never read.ts(6133)
Type 'Promise<{}>[]' is not assignable to type 'Observable<any>[]'.
  Type 'Promise<{}>' is missing the following properties from type 'Observable<any>': _isScalar, source, operator, lift, and 6 more.ts(2322).
What I'm trying to do here to load the first call then second until the end of the promise.
for example it will call the first which is the application1 after that the application2, it should call it one by one.

A: The error is in the last two lines of your code. You're assigning a list of promises to a list of observables. They're not the same type of object.
The simplest fix would be to just stick to Promises and use Promise.all() instead of merge().


text:
Q: Is there a free product configurator/ designer extension for Magento? I'am recently building a eShop with the help of Magento and my fellow students for a university seminar. Since the business idea we had to think of resolves around customizable furniture I wanted to know whether or not there are any free or demo versions of these extensions for Magento to be found.
Alternatively we would have to explain the way we would've implemented and configured the plugin but I'd prefer to show them the real thing, integrated into our shop system.
The main feature I would be looking for is the overlay of images according to the given feature options to show the new product, anything else would be a bonus.


text:
Q: I can't validate response with jsonSchema for anyOf objects in postman I want to validate coming response with schema in Postman. I'm using jsonSchema. But I can't use anyOf parameters in schema. For example I have an object in schema
"rmState":{
    "anyOf": [
        {
            "type": "string",
            "enum": [
                "REGISTERED",
                "DEREGISTERED"
            ]
        },
        {
            "type": "string"
        }
    ]
}

I expect that rmState can only have this enum parameters. But when I validate response with
pm.response.to.have.jsonSchema(schema); validation passes even rmState got any other string from enum.Validation fails only if I change rmState to int. What am I missing for this validation? Thanks for helps.

A: You are checking if it is a string with any of the enum values OR a string. So it matches for all strings. I do not see why you need the anyOf


text:
Q: jQuery Infinite Carousel with Thumbnail I'm making a slider and I got some problem with my thumbnail, they animate faster then the fade of the main image, (After a couple of thumb animate, they are asyncrone with the animate of the main slide... they need to be at the same moment) they have the same speed, so I don't understand why that producing this error...
jQuery(document).ready(function(){
    speed = 8000;
    max_slide = jQuery(".slides_control div.fps-slide").size();
    val_x = 0;
    run = setInterval('rotate()', speed);

    jQuery("#slider").hover(
        function () { clearInterval(run); },
        function () { run = setInterval('rotate()', speed); }
    );

});

function rotate() {
    thumbFirst = jQuery(".fps-pagination li:first-child");
    thumbContainer = jQuery(".fps-pagination");
    animationSpeed = 800;
    if (val_x > max_slide) { val_x = 0 }

    thumbFirst.clone().appendTo(jQuery(".fps-pagination"));

    jQuery(".slides_control div.fps-slide:eq("+val_x+")").animate({"opacity":"0"}, { queue: false, duration: animationSpeed });
    val_x++;
    jQuery(".slides_control div.fps-slide:eq("+val_x+")").animate({"opacity":"1"}, { queue: false, duration: animationSpeed });

    thumbContainer.animate(
        {"top":"-137px"},
        {queue:false, duration: animationSpeed,
        complete: function() {
            thumbFirst.remove();
            thumbContainer.css({"top": "0px"})
        }
    });
}

jsFiddle : http://jsfiddle.net/AY3y2/1/ (Not working well in this environement)
Live code: http://webserver.lewebsimple.ca/~tempcode/

A: can you make a short jsfiddle example???
Edit
use this rotate function, your problem was in if val_x > maxSlide
it must be >= and after the val_X ++, but try it
function rotate() {
    thumbFirst = jQuery(".fps-pagination li:first-child");
    thumbContainer = jQuery(".fps-pagination");
    animationSpeed = 800;

    thumbFirst.clone().appendTo(jQuery(".fps-pagination"));

    jQuery(".slides_control div.fps-slide:eq(" + val_x + ")").animate({ "opacity": "0" }, { queue: false, duration: animationSpeed });
    val_x++;
    if (val_x >= max_slide) { val_x = 0 }
    jQuery(".slides_control div.fps-slide:eq(" + val_x + ")").animate({ "opacity": "1" }, { queue: false, duration: animationSpeed });

    console.log(jQuery(".slides_control div.fps-slide:eq(" + val_x + ")").length + "valor x " + val_x);

    thumbContainer.animate({ "top": "-137px" }, { queue: false, duration: animationSpeed, complete: function () { thumbFirst.remove(); thumbContainer.css({ "top": "0px" }) } });
}