text:
Q: How to put a label on the are inside the circle in a JFrame? I am designing a DFA related program.. so I want to put stuffs like Q0 or Q1 inside the circles but I don't know how.. Can someone please look at my code and tell me how? If its possible to directly put a name that will appear inside the circles, it would be great because I think its hard to set location for a JLabel.. here's my code:
    import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class midterm extends JFrame
{
    JPanel mainpanel;
    JPanel gamepanel;
    JPanel controls;

    ExitButtonListener end=new ExitButtonListener();

    public midterm()
    {
        super("My DFA Design");
        setSize(700,700);
        setLocation(400,100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);

        panel();
        this.getContentPane().add(mainpanel);
        this.pack();
        setVisible(true);
        setSize(400,400);
    }

    public static void main(String[] args)
    {
        midterm frame=new midterm();
    }

    void panel()
    {
        mainpanel=new JPanel();
        mainpanel.setLayout(new BorderLayout());

        gamepanel=new JPanel();
        gamepanel.setBorder(BorderFactory.createTitledBorder("Deterministic Finite Automata"));
        gamepanel.setLayout(new GridLayout(2,3));

        controls = new JPanel();
        controls.setLayout(new BorderLayout());
        controls.setBorder(BorderFactory.createTitledBorder("Control"));

        JButton newGame = new JButton("Reset");
        newGame.addActionListener(new NewButtonListener());
        controls.add(newGame, BorderLayout.NORTH);

        JButton exitGame = new JButton("Exit");
        exitGame.addActionListener(end);
        controls.add(exitGame, BorderLayout.SOUTH);

        mainpanel.add(gamepanel, BorderLayout.CENTER);
        mainpanel.add(controls, BorderLayout.EAST);

        mainpanel.setVisible(true);

        q1 c1=new q1();
        q2 c2=new q2();
        q3 c3=new q3();
        gamepanel.add(c1);
        gamepanel.add(c2);
        gamepanel.add(c3);

    }

    class ExitButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            System.exit(0);
        }
    }

    class NewButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {

        }
    }

    class q1 extends JPanel
    {
        final int radius=25;
        public void paint(Graphics gr)
        {
            setBackground(Color.black);
            gr.drawOval((100/2-radius),(100/2-radius), radius*2, radius*2);
        }
    }

    class q2 extends JPanel
    {
        final int radius=25;
        public void paint(Graphics gr)
        {
            setBackground(Color.black);
            gr.drawOval((95/2-radius),(100/2-radius), radius*2, radius*2);
        }
    }

    class q3 extends JPanel
    {
        final int radius=25;
        public void paint(Graphics gr)
        {
            setBackground(Color.black);
            gr.drawOval((250/2-radius),(50/2-radius), radius*2, radius*2);
        }
    }

}

A: Possible, yes, recommended, maybe not...

public class TestLabel {

    public static void main(String[] args) {
        new TestLabel();
    }

    public TestLabel() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            add(new CircleLable("1"));
            add(new JLabel("What is the capital of SegWay?"));
        }

    }

    public class CircleLable extends JLabel {

        public CircleLable() {
            init();
        }

        public CircleLable(String text) {
            super(text);
            init();
        }

        protected void init() {
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
            setBorder(new EmptyBorder(2, 2, 2, 2));
        }

        @Override
        public Dimension getPreferredSize() {
            Dimension size = super.getPreferredSize();
            size.width = Math.max(size.width, size.height);
            size.height = size.width;
            return size;
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            Insets insets = getInsets();
            int width = (getWidth() - (insets.left + insets.right));
            int height = getHeight() - (insets.top + insets.bottom);
            int radius = Math.max(width, height);

            int x = insets.left + ((width - radius) / 2);
            int y = insets.top + ((height - radius) / 2);

            g2d.drawOval(x, y, radius, radius);

            super.paintComponent(g2d);

            g2d.dispose();
        }

    }

}

The problem I have with this solution is there is to much that can go wrong.  Adding a Icon, changing the text alignment ect could through it off.
Personally, I would simply use a custom JPanel and render the text my self (making sure that the component was transparent first), but that's just me...

A: @MadProgrammer idea is better, but you can use dingbats for circled numbers: ➀, ➁, ➂, …


text:
Q: Redirect to log in page if user is not authenticated with Devise I'm using Devise with Ruby on Rails.
What is the recommended way to redirect unauthenticated users to the sessions#new page if they attempt to access a page that requires authentication?
Right now I get an error that says no route matches the one they attempt to access (leading to a 404 error in production).

A: Just simple add this method to application_controller.rb
  protected
  def authenticate_user!
    if user_signed_in?
      super
    else
      redirect_to login_path, :notice => 'if you want to add a notice'
      ## if you want render 404 page
      ## render :file => File.join(Rails.root, 'public/404'), :formats => [:html], :status => 404, :layout => false
    end
  end

And you can call this method on before_filter another controllers you want.
e.g :
class HomesController < ApplicationController
  before_filter :authenticate_user!
  ## if you want spesific action for require authentication
  ## before_filter :authenticate_user!, :only => [:action1, :action2]
end

Don't forget add login_path into routes.rb
devise_scope :user do
  match '/sign-in' => "devise/sessions#new", :as => :login
end

note : I always use this way when play with devise for my apps authentication.. (rails 3.2 and rails 4.0.1)

A: I thought you could just add:
  before_action :authenticate_user!
to each controller that required the user to be logged in.
I'm a Rails beginner but I found this in my own searches and it works well in my application.

A: You can do just like GeekTol wrote, or just put
before_action :authenticate_user!

in your controller.
In this case, devise uses the default authenticate_user! method, that will redirect to the "user_session_path" and use the default flash message.
It's not necessary to rewrite authenticate_user! method, unless you want to customize it.

A: You should refer to Devise's own How To: How To: Redirect to a specific page when the user can not be authenticated.
Another alternative I can think of is creating a routing Constraint wrapping your protected routes. You'd better stick to Devise's way, but here is an example:
#On your routes.rb
constraints(Constraints::LoginRequired) do
  get '/example'
end

#Somewhere like lib/constraints/login_required.rb
module Constraints
  class LoginRequired
    def self.matches?(request)
      #some devise code that checks if the user is logged in
    end
  end
end

A: Add this code in your config/routes.rb devise_for :users and resources :users and you can generate devise in views.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CheckBox to get Y or N in c#? I have corpflag check box when ever it is TRUE or FALSE i will get 1 or 0.How can i use CheckBox to get Y or N.
Code for Corp_flag Checkbox:
 this.chk_CorpFlag = new System.Windows.Forms.CheckBox();

if (dtGridNwBrandModel.Rows[e.RowIndex].Cells[10].Value.ToString().ToLower() == "false")
  {
     chk_CorpFlag.Checked = false;
  }
   else
  {
     chk_CorpFlag.Checked = true;
  }

A: You could use the Tag
//I took the chance to make code more readable
using System.Windows.Forms;

var cellValue = dtGridNwBrandModel.Rows[e.RowIndex].Cells[10].Value;

// I suggest checking for true instead...
var isChecked = !(cellValue.ToString().ToLower() == "false");

this.chk_CorpFlag = new CheckBox
{
    Checked = isChecked,
    Tag = isChecked ? 'Y' : 'N'
};

and then you have 'Y' and 'N' available through chk_CorpFlag.Tag.

A: Edited: I guess it doesn't accept 'Y' and 'N'. If you want this to be in variable then you can use ternary operator like this
var result = chk_CorpFlag.Checked == true? 'Y' : 'N';

A: Do not quite understand what you want ... Was that it?
char Y_or_N = (hk_CorpFlag.Checked) ? 'Y' : 'N';


text:
Q: adding check box dynamically to gridview <asp:GridView ID="SearchGrid" runat="server" GridLines="Both" AutoGenerateColumns="false">
                        <Columns>
                            <asp:BoundField DataField="Q" HeaderText="Q" />
                            <asp:TemplateField HeaderText="C">
                                <ItemTemplate>
                                    <asp:CheckBox ID="CCheckbox" runat="server" AutoPostBack="true" OnCheckedChanged="CCheckbox_CheckedChanged" />
                                </ItemTemplate>
                            </asp:TemplateField>
                             <asp:TemplateField HeaderText="R">
                                <ItemTemplate>
                                    <asp:CheckBox ID="RCheckbox" runat="server" AutoPostBack="true" OnCheckedChanged="RCheckbox_CheckedChanged" />
                                </ItemTemplate>
                            </asp:TemplateField>
                             <asp:TemplateField HeaderText="E">
                                <ItemTemplate>
                                    <asp:CheckBox ID="ECheckbox" runat="server" AutoPostBack="true" OnCheckedChanged="ECheckbox_CheckedChanged" />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>

This is my Aspx code for the GridView
if (ViewState["SearchGrid"] == null)
            {
                SearchTable.Columns.Add(new DataColumn("Q", typeof(string)));
                SearchTable.Columns.Add(new DataColumn("C", typeof(bool)));
                SearchTable.Columns.Add(new DataColumn("R", typeof(bool)));
                SearchTable.Columns.Add(new DataColumn("E", typeof(bool)));
                ViewState["SearchGrid"] = SearchTable;
            }
            SearchTable =(DataTable) ViewState["SearchGrid"];
            DataRow dr = null;
            dr = SearchTable.NewRow();
            dr["Q"] = MySearchTextBox.Text;
            switch (SearchType)
            {
                case "Contains": dr["C"] =true;
                    break;
                case "Related": dr["R"] = true;
                    break;
                case "Exact": dr["E"] = true;
                    break;
            }

and my code behind.
At the time of adding the row I have to check a paticular check box.
I have been trying to check the checkbox by giving its values as true but it does not seem to work. Can someone tell me what I am doing wrong here?

A: You can bind in the markup to the value: Checked='<%# Eval("C") %>'
<asp:GridView ID="SearchGrid" runat="server" GridLines="Both" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Q" HeaderText="Q" />
        <asp:TemplateField HeaderText="C">
            <ItemTemplate>
                <asp:CheckBox ID="CCheckbox" runat="server" AutoPostBack="true" OnCheckedChanged="CCheckbox_CheckedChanged" Checked='<%# Eval("C") %>' />
            </ItemTemplate>
        </asp:TemplateField>
            <asp:TemplateField HeaderText="R">
            <ItemTemplate>
                <asp:CheckBox ID="RCheckbox" runat="server" AutoPostBack="true" OnCheckedChanged="RCheckbox_CheckedChanged" Checked='<%# Eval("E") %>' />
            </ItemTemplate>
        </asp:TemplateField>
            <asp:TemplateField HeaderText="E">
            <ItemTemplate>
                <asp:CheckBox ID="ECheckbox" runat="server" AutoPostBack="true" OnCheckedChanged="ECheckbox_CheckedChanged" Checked='<%# Eval("R") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Or you can use rowdatabound event: OnRowDataBound="SearchGrid_RowDataBound"
MarkUP Change:
<asp:GridView ID="SearchGrid" runat="server" GridLines="Both" AutoGenerateColumns="false" OnRowDataBound="SearchGrid_RowDataBound">

Codebehind: Note i used a list object instead of a datatable.
public class TestObject
{
    public string Q { get; set; }
    public bool C { get; set; }
    public bool R { get; set; }
    public bool E { get; set; }
}
public partial class Default : System.Web.UI.Page
{
    public List<TestObject> Values { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //NEED SOME DATA TO TEST THE RESULT
            Values = new List<TestObject>();

            Values.Add(new TestObject() { Q = "test 1", C = true, E = true, R = true });
            Values.Add(new TestObject() { Q = "test 1", C = true, E = false, R = true });
            Values.Add(new TestObject() { Q = "test 1", C = true, E = true, R = false });
            Values.Add(new TestObject() { Q = "test 1", C = false, E = true, R = true });
            //BIND TO THE GRID
            SearchGrid.DataSource = Values;
            SearchGrid.DataBind();
        }
    }

    //FIRES FOR EVERY ROW IN THE GRID
    protected void SearchGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //WE ONLY CARE ABOUT THE DATAROW NOT HEADER ETC
        if (e.Row.RowType != DataControlRowType.DataRow)
            return;
        //GET THE BOUND INDIVIDUAL ITEM
        TestObject obj = (TestObject)e.Row.DataItem; //IN YOUR CASE THIS WOULD BE: DataRow row = (DataRow)e.Row.DataItem

        //FIND ALL THE CHECKBOXES
        CheckBox cchk = e.Row.FindControl("CCheckBox") as CheckBox;
        CheckBox echk = e.Row.FindControl("ECheckBox") as CheckBox;
        CheckBox rchk = e.Row.FindControl("RCheckBox") as CheckBox;

        //CHECK IT OR NOT BASED ON THE DATATITEMS VALUE
        if (cchk != null)
            cchk.Checked = obj.C; //IN YOUR CASE THIS WOULD BE: bool c = (bool)row["C"];

        if (echk != null)
            echk.Checked = obj.E;

        if (rchk != null)
            rchk.Checked = obj.R;
    }
}

A: You can try to check out the functionality of GridView.RowDataBound. Use this event to capture the row when it has data bound to it and then you should be able to access the CheckBox item and assign its .Checked value.
Link: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx


text:
Q: Is transaction isolation level 100% reliable in SQL Server? I'm doing some test about the isolation level in SQL Server.
First I create a table called test with this structure:

Then I run the test code with 2 threads at the same time:
use test-db;
go
declare @count int = 0;
while @count<5000
begin
  set transaction isolation level read committed;
  begin transaction;

  declare @max int;
  select @max = coalesce(max(sequence_no),0) from test;
  print @max;
  insert into test (prefix, sequence_no, thread) values ('AAA', @max+1, 1);

  commit transaction;
  set @count = @count+1;
end;

The second thread just change the thread number:
use test-db;
go
declare @count int = 0;
while @count<5000
begin
  set transaction isolation level read committed;
  begin transaction;

  declare @max int;
  select @max = coalesce(max(sequence_no),0) from test;
  print @max;
  insert into test (prefix, sequence_no, thread) values ('AAA', @max+1, 2);

  commit transaction;
  set @count = @count+1;
end;

Under read committed mode, the code should wait for read the max number of sequence when the other thread is not commit, which means they won't generate a same sequence_no.
But it often give me a error:

Violation of PRIMARY KEY constraint 'PK_test'. Cannot insert duplicate key in object 'dbo.test-db'. The duplicate key value is (AAA, 2402).

I test it in repeatable read mode again, and it's the same.
Can someone explain why the reading query between transaction will get crash?
Does it means that isolation level isn't 100% reliable?

A: You need to use SERIALIZABLE isolation and an UPDLOCK is also required to avoid deadlocks:
SELECT @max = coalesce(max(sequence_no),0)
FROM dbo.test WITH (UPDLOCK, SERIALIZABLE);

This is awful for concurrency so you should really use an identity or a sequence.


text:
Q: how to filter and display the table view and collection view values based on the bool value in my json I have the json list of :
 [
     {

         "title": "Languages",
         "name_list": [
             {

                 "title": "Hindi",
                 "locked": true
             },
             {
                 "title": "Hindi1",
                 "locked": true
             },
             {
                 "title": "Hindi2",
                 "locked": false
             },
             {
                 "title": "Hindi3",
                 "locked": true
             },
             {
                 "title": "Hindi4",
                 "locked": false
             }],
     },
     {

         "title": "Subject",
         "name_list": [
             {
                 "title": "Hindi4",
                 "locked": false
             },
             {
                 "title": "Hindi4",
                 "locked": true
             },
             {
                 "title": "Hindi4",
                 "locked": true
             }]
     }
 ]

I am using table view and inside table view i have collection view.
Now in my table view i will show the title .And in my collection view i will show the name_list title on each collection view cell. Now it's working fine.
What i needs is, as you can see in the json, that have many locked =  true and false.
So,  In my table view- which object have less locked == false. that title i needs to show as first. For example.
In my above json, title = subject have only one locked = false, but title = language have 2 locked = false. So in my table view first subject have to display and language.
Same in each collection view, which object have locked = false that needs to display first in my collection view cell.
Any help please.
Here is my code of table view :
cellTitleLabel.text = jsonData?["title"] as? String ?? ""
in my collection view :
if let gamesList = jsonData?["name_list"]  as? [[String: Any]] {
   let Info = nameList[indexPath.item]
   collectionCell.cellTitleLabel.text = Info["title"] as? String ?? ""
}

   var Info: [String: Any]?{
        didSet {

            cellTitleLabel.text = jsonData?["title"] as? String ?? ""
            collectionView.reloadData();

            guard let gamesList = jsonData?["name_list"]  as? [[String: Any]] else {
                return
            }
        }
    }

A: I used this below json for dummy
[
    {
        "title": "Languages",
        "name_list": [
            {
                "title": "Sub 1",
                "locked": true
            },
            {
                "title": "Sub 2",
                "locked": true
            },
            {
                "title": "Sub 3",
                "locked": false
            },
            {
                "title": "Sub 4",
                "locked": true
            },
            {
                "title": "Sub 5",
                "locked": false
            }
        ]
    },
    {
        "title": "Subject",
        "name_list": [
            {
                "title": "Sub 6",
                "locked": false
            },
            {
                "title": "Sub 7",
                "locked": false
            },
            {
                "title": "Sub 8",
                "locked": false
            }
        ]
    }
]

Model Struct for this json :
public struct TestModel {

    public var nameList : [NameList]
    public var title : String
}

public struct NameList {

    public var locked : Bool
    public var title : String

}

My json is in local project, so I use this below func to
func getLocalData(){
    let url = Bundle.main.url(forResource: "testjson", withExtension: "json")!
    do {
        let jsonData = try Data(contentsOf: url)
        let json = try JSONSerialization.jsonObject(with: jsonData) as! [Any]
       self.arrData = self.createDataModel(json)
    }
    catch {
        print(error)
    }
}

Func to bind the json into model struct
func createDataModel (_ json : [Any]) -> [TestModel] {
    var arr = [TestModel]()

    for adata in json {
        let aDictItems = adata as! [String : Any]
        let aNameListData = aDictItems["name_list"] as! [Any]
        var arrNameList = [NameList]()

        for aName in aNameListData {
            let adictname = aName as! [String : Any]
            arrNameList.append(NameList.init(locked: adictname["locked"] as! Bool, title: adictname["title"] as! String ))
        }

        arr.append(TestModel.init(nameList: arrNameList, title: aDictItems["title"] as! String))

    }
    return arr
}

And in last, func that sort your list into the number of locked count (false) and return back filtered data.
func filterData (_ searchText : String) -> [TestModel] {
    if searchText == "" { return arrData }

    let s = arrData.sorted { (res1, res2) -> Bool in
        var count1 = 0, count2 = 0
        for r in res1.nameList {
            if !r.locked {
                count1 += 1
            }
        }
        for r in res2.nameList {
            if !r.locked {
                count2 += 1
            }
        }
        return count1 > count2
    }

    let f = s.filter {
        $0.nameList.contains(where: { (aNameRes) -> Bool in
          aNameRes.title.contains(searchText)
        })
    }
    return f
}

Edit : To Show data in cell

tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return filtered.Count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    :
    // filtered[indexPath.row].title // your tableview cell title
    // filtered[indexPath.item].nameList // your collectView Data, Use this array to show data in collectionview
}

Note: Your API json Data and filtered data is always be same. When there is no string in the search bar then you need to toggle filtered data with api original data.

If something change in your requirement then let me know.

A: My solution here is to create a function in your tableview cell and call it at cellForRowAt indexPath with the corresponding array. And you can call the function simply by cell. fillCollectionView(array).
class ExampleTableViewCell: UITableViewCell {

@IBOutlet weak var exampleCollectionView: UICollectionView!

var array = [[String:Any]]()

func fillCollectionView(with array: [[String:Any]]) {
    self.array = array
    exampleCollectionView()
}

A: In this case, If you want to display locked == false as first then you need to rearrange your dictionary of array(sort by locked). and then load data into UItableview and UIcollectionview

A: Just use this function and it will work for you without creating any models.
func sortArr(array : [[String:Any]]) -> [[String:Any]]{
var arr = array
for i in 0...arr.count - 1 {
    var dict = arr[i]
    let name_list = dict["name_list"] as! [[String:Any]]
    let lockedItems = name_list.filter { (item) -> Bool in
        let locked = item["locked"] as! Bool
        if locked == false {
            return true
        }
        return false
    }
    print(lockedItems.count)
    dict["lockedItems"] = lockedItems.count
    arr[i] = dict
}
arr = arr.sorted(by: { (item1, item2) -> Bool in
    let lockedcount1 = item1["lockedItems"] as! Int
    let lockedcount2 = item2["lockedItems"] as! Int
    return lockedcount1 < lockedcount2
})
return arr
}

EDITED
import UIKit
var arr = [
[

"title": "Languages",
"name_list": [
[
"title": "Hindi",
"locked": true
],
[
"title": "Hindi1",
"locked": true
],
[
"title": "Hindi2",
"locked": false
],
[
"title": "Hindi3",
"locked": true
],
[
"title": "Hindi4",
"locked": false
]],
],

[
"title": "Subject",
"name_list": [
[
"title": "Hindi4",
"locked": false
],
[
"title": "Hindi4",
"locked": true
],
[
"title": "Hindi4",
"locked": true
]]
]

]
func sortArr(array : [[String:Any]]) -> [[String:Any]]{
    var arr = array
    for i in 0...arr.count - 1 {
        var dict = arr[i]
        let name_list = dict["name_list"] as! [[String:Any]]
        let lockedItems = name_list.filter { (item) -> Bool in
            let locked = item["locked"] as! Bool
            if locked == false {
                return true
            }
            return false
        }
        print(lockedItems.count)
        dict["lockedItems"] = lockedItems.count
        arr[i] = dict
    }
    arr = arr.sorted(by: { (item1, item2) -> Bool in
        let lockedcount1 = item1["lockedItems"] as! Int
        let lockedcount2 = item2["lockedItems"] as! Int
        return lockedcount1 < lockedcount2
    })
    return arr
}

var array = sortArr(array: arr)
print(array)

A: struct Root {
    let nameList: [NameList]
    let title : String
    init(dictionary: [String: Any]) {
        self.title = dictionary["title"] as? String ?? ""
        self.nameList = (dictionary["name_list"] as? [[String:Any]] ?? []).map(NameList.init)
    }
}

struct NameList {
    let locked: Bool
    let title: String
    init(dictionary: [String: Any]) {
        self.locked =  dictionary["locked"] as? Bool == true
        self.title = dictionary["title"] as? String ?? ""
    }
}

let jsonData = Data("""
[
  {
    "title" : "Languages",
    "name_list" : [
      {
        "title" : "Hindi",
        "locked" : true
      },
      {
        "title" : "Hindi1",
        "locked" : true
      },
      {
        "title" : "Hindi2",
        "locked" : false
      },
      {
        "title" : "Hindi3",
        "locked" : true
      },
      {
        "title" : "Hindi4",
        "locked" : false
      }
    ]
  },
  {
    "title" : "Subject",
    "name_list" : [
      {
        "title" : "Hindi4",
        "locked" : false
      },
      {
        "title" : "Hindi4",
        "locked" : true
      },
      {
        "title" : "Hindi4",
        "locked" : true
      }
    ]
  }
]
""".utf8)

let dictionaries = (try? JSONSerialization.jsonObject(with: jsonData)) as? [[String:Any]] ?? []

print("\nAll Models", terminator: "\n============\n")
let models = dictionaries.map(Root.init)
for model in models {
    print(model.title)
    for name in model.nameList {
        print(name.title)
     }
}
print("\nunlockedModels", terminator: "\n============\n")
let unlockedDictionary: [String: [NameList]] = models.reduce(into: [:]) {
    $0[$1.title] = $1.nameList.filter{ $0.locked}
}
for (title, nameList) in unlockedDictionary {
    print(title)
    for name in nameList {
        print(name.title)
    }
}


text:
Q: Algorithm review for time complexity
*

*I would like to know whether this works in worst case as Θ(n+m)?

n is size of i_StringForSearch, m is size of i_SubStringToFind.
2.Is there any program which is recommended to check time complexity of a given code, I prefer a free tool which is well recognized.
Thank you
public static boolean isSubstring(String i_StringForSearch, String i_SubStringToFind)
    {
        int strForSearchIndex = 0;
        int subStrToFindIndex = 0;
        boolean endOfStringToSearch = false;
        boolean foundSubString = false;
        boolean isThereASequenceOfMatching = false;

        while(!endOfStringToSearch && !foundSubString)
        {
            if(strForSearchIndex == i_StringForSearch.length())
            {
                endOfStringToSearch = true;
            }

            else if(i_StringForSearch.charAt(strForSearchIndex) == i_SubStringToFind.charAt(subStrToFindIndex))
            {
                isThereASequenceOfMatching = true;
                if(subStrToFindIndex == i_SubStringToFind.length() -1 )
                {
                    foundSubString = true;
                }
                subStrToFindIndex++;
                strForSearchIndex++;
            }

            else if(i_StringForSearch.charAt(strForSearchIndex) != i_SubStringToFind.charAt(subStrToFindIndex))
            {
                if(isThereASequenceOfMatching)
                {
                    subStrToFindIndex = 0;
                    isThereASequenceOfMatching = false;
                }
                strForSearchIndex++;
            }
        }

       return foundSubString;
    }

A: *

*Answering your question: yes, the algorithm is O(n+m). Each
iteration increases strForSearchIndex, so there are at most n
iterations. [this is assuming i_StringForSearch.length() is done
in O(1), which is usually true].

*The algorithm is wrong with the counter example of isSubstring("aaab","aab") == false.

*You might want to have a look on Knuth Morris Pratt algorithm and/or Rabin-Karp algorithm and/or Aho-Corasick Algorithm


text:
Q: Understanding the fundamental theorem of calculus via squeeze theorem I was just taught "integration is the opposite of differentation, this will give the area"
While I can integrate, I am not sure why it works and the "anti derivate" magically is the area. I really need some help getting this idea in my head. I am using https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus for reference.
If we want A(x), I am not sure how adding an extra red section helps. I think I understand the red area is defined as approximateley A(x)-A(x-h), which equals f(x)h.
Then I have read, this is between
hf(x)< RED AREA < f(x+h).
I then see we divide by h, and are left with the defintion of differentation when h>>0.
However I have 2 questions'
1) Surely we are not concerned with the red area, we want the blue area
2) When we take the limit as h>>0 this leaves an infitesimal slice (I understand that integration is the summation of an infinate amount of infiniately small sliced) but the concept of adding +h to the area (thus creating a red area) only to remove it doesn't seem to have any effect on the blue area.
Thanks a lot for your help. Hopefully its something easy I missed, and I can get there!

A: I have the feeling that a part of your confusion comes from the fact that you're reading a paragraph of the Wikipedia-page with an expectation that's different from its goal. They don't define the integral in that paragraph.

2) When we take the limit as h>>0 this leaves an infitesimal slice (I understand that integration is the summation of an infinate amount of infiniately small sliced) but the concept of adding +h to the area (thus creating a red area) only to remove it doesn't seem to have any effect on the blue area.

You are right: you don't need the red part to understand what the integral does, where it comes from, how it is defined. As you say: you divide the interval into subintervals and you build rectangles whose length you let go to 0. Adding the areas of the rectangles gives an approximation of the area under the curve and we get (or: define!) the real area by taking the limit of $h \to 0$ (I'm omitting details here). This is done in many books, websites and partly also in the Wikipedia article.
However, you're referring to the picture and the reasoning in the paragraph Geometrical meaning and there, they are trying to explain what the relation is between actually calculating this area and the concept of derivatives and anti-derivatives. More precisely: it gives you the relation between $f$ and the area function $A$, and they're connected as one being the derivative of the other one.

Thanks, I can see that if I differentiate A(x), I will get f(x), but may I ask why you want to differentiate A to get the area, when A is the area? What is the logic or intuition in this?

So what they achieved in that paragraph is showing that you can obtain a formula for the area under the graph of $f$, if you can find a function $A$ that satisfies $A'(x) = f(x)$, what we call an anti-derivative (or primitive function) of $f$. Note that you don't necessarily "discover" this relation if you only define the integral as the limit of a sum of areas of rectangles.


text:
Q: remove exif from all files in directory I would like to remove the exif/metadata from all .JPG files in a directory. Here's what I have so far, but part of me doesn't think this will work, so...help?
import os
from gi.repository import GExiv2

rootdir = "c:\directory\subdirectory\subdirectory2"

def noMeta(file):
    exif = GExiv2.Metadata(file + ".jpg")
    exif.clear_exif()
    exif.clear_xmp()
    exif.save_file()

for root, dir, files in os.walk(rootdir):
    for file in files:
        if file.lower().endswith(".jpg"):
            noMeta(file)

A: Do you really want ...Metadata(file + ".jpg") because file already has .jpg on it.
I don't know anything about GExiv2. FWIW, the piexif library seems to be maintained:
import os
import piexif

rootdir = "c:\directory\subdirectory\subdirectory2"

def noMeta(file):
  print("gutting exif data from {}".format(file))
  piexif.remove(file)

for root, dir, files in os.walk(rootdir):
  for file in files:
    if file.lower().endswith(".jpg"):
      noMeta(os.path.join(root, file))


text:
Q: How can you get script name in BSD process accounting file? I'm trying to write a program to process the BSD-style process accounting file under Linux (/var/account/pacct).
When we start a script with either ./script_name or bash script_name, the process accounting record actually gets written out the the command bash. Presumably because that's the actual program doing the running.
What we'd like to see is the command script_name. Does anyone know of a way to get the script name written to the accounting file rather than the bash executable?

A: Linux: Eternal Bash History with Snoopy.
Edit:
As a hack alternative, you can periodically run ps -eo args
Edit by questioner (so I can accept the answer from the only SO'er who helped out :-):
I found that if you actually added "'#!bin/bash" to the file, it started showing up in pacct with the script name (tst) instead of the interpreter (bash).
My script was originally devoid of the hash-bang marker and it may be that bash had to re-exec itself or something like that. Anyway, it's fixed now.


text:
Q: Login screen on macOS Sierra suddenly with gray background yesterday after waking my Macbook Air (Early 2015) with macOS Sierra from sleep I was greeted with gray login screen. Now I have gray every time I wake up my Mac.
First time I had the same color as background on dock for some reason but that went away after I disabled "Reduce transparency" in Accessibility settings.
I did some googling and found that this may be related to FileVault (since everything is encrypted OS presents gray background) however I had FileVault turned on since I got my Macbook and never encountered this gray thing.
What is the cause? My main worry is that it might indicate some problems with my computer. Thanks.

A: When your machine restarts with FileVault enabled, the gray screen login is to unlock FileVault. There are no problems with your machine.


text:
Q: iOS Unique Identifier How are we supposed to uniquely identify devices now that the UDID has been deprecated? I need to be able to uniquely identify a device even if the user uninstalls my app and then reinstall it. The new identifierForVendor doesn't work for this purpose because it will randomly generate again once the user uninstalls the app. I also can't use the MAC address to identify the device because it doesn't work in iOS 7.
The advertisingIdentifier seems to work for my purposes but I heard that if you're not actually using it for advertising Apple will reject your app?
Does anyone know of a way to reliably identify a device?

A: According to Apple, you should be using the vendor or advertising identifiers.  Vendor doesn't work for you obviously, but you are fine to use advertisingIdentifier.

A:
The advertisingIdentifier seems to work for my purposes but I heard that if you're not actually using it for advertising Apple will reject your app?

They are not currently rejecting apps for using avertisingIdentifier in place of uniqueIdentifier as a device ID. I just had a version of my app approved that uses advertisingIdentifier for purposes other than advertising. A bigger negative is that users can change this identifier any time they like, which is guaranteed to mess up your reporting.


text:
Q: What does the exclusive lock on storage for OrientDB entail exactly? Having read the following statement from the official documentation of OrientDB:

In order to guarantee atomicity and consistency, OrientDB acquire an
  exclusive lock on the storage during transaction commit.

I am wondering if my understanding of the situation is correct. Here is how I assume this will work:

*

*Thread 1 opens a transaction, and reads records #1:100 to #1:200, some from class A, and some from class B (something which cannot be determined without the transaction coming to a close).

*Thread 1 massages the data, maybe even inserting a few records.

*Thread 1 starts to commit the data. As the database does not have any way to know which parts of the data might be effected by the open transaction, it will blindly block the whole storage unit and verify the @version to enforce optimistic locking on all possibly affected records.

*Thread 2 tries to read record #1:1 (or any other record from the whole database) and is blocked by the commit process, which is aligned, AFAIK with exclusive locking on the storage unit. This block occurs, if I'm not off, regardless of the cluster the original data resides on, since we have multi-master datasets.

*Thread 1 ends the commit process and the database becomes consistent, effectively lifting the lock.

*At this point, any thread can operate on the dataset, transactionally or otherwise, and will not be bound by the exclusive locking mechanism.

If this is the case, during the exchange highlighted in point 3 the data store, in its entirety is in an effective trance state and cannot be reached to, read from, or interacted with in any meaningful way.
I do so hope that I am missing my guess.
Disclaimer: I have not had the chance to dig into the underlying code from the rather rich OrientDB codebase. As such, this is, at its best, an educated guess and should not be taken as any sort of reference as to how OrientDB actually operates.
Possible Workarounds:
Should worse come to worse and this happens to be the way OrientDB actually works, I would dearly welcome any workarounds to this conundrum. We are looking for meaningful ways that will still keep OrientDB as a viable option for an enterprise, scalable high-end application.

A: In current release of OrientDB, transactions lock the storage in exclusive mode. Fortunately OrientDB works in optimistic way and this is done "only" at commit() time. So no matter when the transaction is begun.
If this is a showstopper for your use case, you could consider to:

*

*don't use transactions. In this case you'll go in parallel with no locks, but consider using indexes requires the usage of lock at index level. In case the index is a bottleneck, the most common workaround is to create X sub-classes with an index on each. OrientDB will use the index of sub-classes if needed and on CRUD operation only the specific index will be locked

*wait for OrientDB 3.0 where this limitation will be removed with real parallel transaction execution


text:
Q: Multiple Table Inheritance in Rails 4/Devise setting the current_user So I have decided to use MTI for different users of my app. The users have different enough info to where I don't think i should use STI and I wanted it more robust down the road. I have an app built in rails 4 using devise that has a polymorphic association for the users, made like this
class User < ActiveRecord::Base

  belongs_to :rolable, :polymorphic => true

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable

  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable, :confirmable, :timeoutable
end

with the other classes looking like
class User1 < ActiveRecord::Base
  has_one :user, :as => :rolable
end

This is all fine and dandy but I am asking how I will set the devise's "current_user" to be an instance of User1? is that possible or recommended? I can make a new User1 and update the :rolable attribute of a user to include a reference to a specific User1 in the console, but I am not sure where to put this in my code.
I want the sign-in information to be the same for all users but I want the user to be able to change user specific info upon login. I was thinking I would modify the user controller to add the User1 model on creation and then in the application controller I would set the current_user to be an instance of User1.
Is this advised or is there a better way to make the current_user?
A second thought i had was setting another variable and getting the type using the columns in the User class. (rolable_id and rolable_type)
Which would be the best way? (I am not the most experienced Rails Developer)

A: For my project I did not change the current_user from Devise's instance of current_user. instead I created new objects for each user when i needed them and used the current_user's id field as the foreign key for the specific Users. Changing the current_user probably wasn't the best idea because then i lose the reference to the User table and the info in that table. It worked just fine to create an object for each User


text:
Q: Allow only certain strings obtained with autocomplete in input box I basically want to make an input box behave like the tags field of StackOverflow, or for example the input field of https://gitignore.io, except that only a single tag is allowed.
Is there any existing library for doing this?

A: Please check select2. This may help you.
https://select2.github.io

A: These might help
https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/
Or
http://mbenford.github.io/ngTagsInput/
Depends on what Tech you are using.


text:
Q: Apache Tomcat Server 8.0.32 and a blue color default Favicon I have deployed abc.war file on Apache Tomcat 8.0.32. Everything works fine except the favicon.ico. Even on index.html I have defined like :
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
 <link rel="icon" href="favicon.ico" type="image/x-icon">

It shows icon like this :

Not sure from where this icon is coming ?
EDIT:
I also tried to see via developer tools of chrome , but didn't get the info of this blue icon.As checked all images retrieved from the network.


text:
Q: replacing strings in ASP.NET hidden field via JavaScript how can I replace strings in ASP.NET hidden field using JavaScript?
var s = document.getElementById('HF').value;

where HF is my hidden field, I want to replace some strings in HF value, but s doesn't display replace function, should I convert s to ToString?
thanks

A: You mean this?
var s = document.getElementById('HF').value;
document.getElementById('HF').value = s.replace(/oldstring/g, "newstring");

Live example: http://jsfiddle.net/2tzGH/


text:
Q: How to scrape location from list of websites I have a list of URLs in a csv file and I would like to scrape locations for each website. I am really new in scraping, so I do not know what tool or language is better. Is there some method to make it? Any help would be appreciated.

A: Web scraping can be done in several ways. There are many tools online and it also depends on your selection of language that suits you. I worked on Python and can suggest you to try Beautiful Soup, Requests and other API's. You also need to understand DOM structure of the webpage you want to scrape.
You may like to see documentation of Beautiful Soup: https://www.crummy.com/software/BeautifulSoup/bs4/doc/
Note that in a webpage, you need to understand DOM structure to search its location and extract location data accordingly.


text:
Q: Koszul Homology vs Koszul Cohomology Let $R$ be a ring and $x \in R$. The Koszul complex $K_\bullet(x)$ is then $0 \rightarrow R \stackrel{x}{\rightarrow} R \rightarrow 0$. Given $x_1,\dots,x_n \in R$ the Koszul complex $K_\bullet(x_1,\dots,x_n)$ is defined to be $K_\bullet(x_1) \otimes \cdots \otimes K_\bullet(x_n)$, where $\otimes$ is the tensor product of complexes. Then the Koszul homology of an $R$-module $M$ is the homology of the complex $K_\bullet(x_1,\dots,x_n) \otimes M$.
In his notes, Craig Huneke is defining a different Koszul complex $K^\bullet(x)$ by $0 \rightarrow R \rightarrow R_x \rightarrow 0$, where the middle arrow is the canonical map of localization. As above, he defines $K^\bullet(x_1,\dots,x_n) = K^\bullet(x_1) \otimes \cdots \otimes K^\bullet(x_n)$ and the Koszul cohomology of an $R$-module $M$ is the cohomology of the complex $K^\bullet(x_1,\dots,x_n) \otimes M$. In these notes it is then shown that the local cohomology $H^i_I(M)$ of $M$ with respect to an ideal $I=(x_1,\dots,x_n)$ is in fact the Koszul cohomology of $M$.
Question: I have seen before the Koszul homology in Matsumura and Bruns and Herzog, but Koszul cohomology is new to me. The dual denominations Koszul homology-cohomology suggest that the two Koszul complexes $K_\bullet(x_1,\dots,x_n)$ and
$K^\bullet(x_1,\dots,x_n)$ described above are in some sense dual. Is this the case and in what sense?

A: As Youngsu says, what you have written as Koszul cohomology is sometimes called Cech cohomology instead (geometrically, the terms of degree $> 0$ are exactly those of the Cech complex for the open sets $D(x_i)$ - I will not comment on Huneke's use of the term though).
Here is a way to relate Cech cohomology with Koszul homology: given the Koszul complex $K^\bullet(x) : 0 \to R \xrightarrow{x} R \to 0$, one can form a direct limit of complexes
$$\require{AMScd}
\begin{CD}
0 @. 0 @. 0\\
@VVV @VVV @VVV\\
R @>=>> R @>=>> R @>=>> ...\\
@VVxV @VVx^2V @VVx^3V\\
R @>x>> R @>x>> R @>x>> ...\\
@VVV @VVV @VVV\\
0 @. 0 @. 0
\end{CD}
\qquad \implies \qquad
\begin{CD}
0 \\
@VVV \\
R \\
@VVV \\
R_x \\
@VVV \\
0
\end{CD}$$
where the vertical columns are $K^\bullet(x^j)$, and the limit is the Cech complex, which I will call $C^\bullet(x) = \varinjlim K^\bullet(x^j)$. Tensoring such sequences together gives (since $\varinjlim$ and $\otimes$ commute) $C^\bullet(x_1, \ldots, x_n; M) \cong \varinjlim K^\bullet(x_1^j, \ldots, x_n^j; M)$. One can show that the cohomology of this complex computes local cohomology, i.e. if $I := (x_1, \ldots, x_n)$, then $H^i_I(M) \cong H^i(C^\bullet(x_1, \ldots, x_n; M))$, and since $\varinjlim$ is exact, this is $\varinjlim H^i(K^\bullet(x_1^j, \ldots, x_n^j; M))$ (in the case that $x_1, \ldots, x_n$ is a regular sequence, one can see this directly by noting that the Koszul complex on $(x_1^j, \ldots, x_n^j)$ is a free resolution of $R/(x_1^j, \ldots, x_n^j)$, thus can be used to compute $\text{Ext}$, and local cohomology is a limit of $\text{Ext}$'s.
For more information on this (such as the relation to sheaf cohomology), see e.g. Appendix 4 in Eisenbud.


text:
Q: Accessing original field in Parse.com Cloud Code beforeSave function The ultimate goal is to detect changes between an existing Parse object and the incoming update using the beforeSave function in Cloud Code.
From the Cloud Code log available through parse.com, one can see the input to beforeSave contains a field called original and another one called update.
Cloud Code log:
Input: {"original": { ... }, "update":{...}

I wonder if, and how, we can access the original field in order to detect changing fields before saving.
Note that I've already tried several approaches for solving this without success:

*

*using (object).changedAttributes()

*using (object).previousAttributes()

*fetching the existing object, before updating it with the new data

Note on request.object.changedAttributes():
returns false when using in beforeSave and afterSave -- see below for more details:
Log for before_save -- summarised for readability:
Input: { original: {units: '10'}, update: {units: '11'} }
Result: Update changed to { units: '11' }
[timestamp] false <--- console.log(request.object.changedAttributes())

Log for corresponding after_save:
[timestamp] false <--- console.log(request.object.changedAttributes())

A: There is a problem with changedAttributes().  It seems to answer false all the time -- or at least in beforeSave, where it would reasonably be needed. (See here, as well as other similar posts)
Here's a general purpose work-around to do what changedAttributes ought to do.
// use underscore for _.map() since its great to have underscore anyway
// or use JS map if you prefer...

var _ = require('underscore');

function changesOn(object, klass) {
    var query = new Parse.Query(klass);
    return query.get(object.id).then(function(savedObject) {
        return _.map(object.dirtyKeys(), function(key) {
            return { oldValue: savedObject.get(key), newValue: object.get(key) }
        });
    });
}

// my mre beforeSave looks like this
Parse.Cloud.beforeSave("Dummy", function(request, response) {
    var object = request.object;
    var changedAttributes = object.changedAttributes();
    console.log("changed attributes = " + JSON.stringify(changedAttributes));  // null indeed!

    changesOn(object, "Dummy").then(function(changes) {
        console.log("DIY changed attributes = " + JSON.stringify(changes));
        response.success();
    }, function(error) {
        response.error(error);
    });
});

When I change someAttribute (a number column on a Dummy instance) from 32 to 1222 via client code or data browser, the log shows this:

I2015-06-30T20:22:39.886Z]changed attributes = false
I2015-06-30T20:22:39.988Z]DIY changed attributes =
  [{"oldValue":32,"newValue":1222}]


text:
Q: Trying to connect node with firebase, "Expected first argument to collection()" Getting this "Expected first argument to collection() to be a CollectionReference, ' +" after trying to run this code
import { initializeApp } from "firebase/app"
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite'

const firebaseConfig = {
    //Config info...
}
console.log(firebaseConfig)
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

async function getUsers(db) {
  const usersCol = collection(db, 'Users');
  const usersSnapshot = await getDocs(usersCol);
  const usersList = usersSnapshot.docs.map(doc => doc.data());
  return usersList;
}
export default getUsers()
console.log(getUsers(db))


text:
Q: Number of circular seating arrangements if each person can't sit next to two other people There are 30 people sitting around a round table, and those 30 people all arrived to the event in 10 groups of 3. How many different ways can those people sit around the table if no-one is allowed to sit next to anyone else who arrived with them (ie was with them in a triplet, so for each person there are two other people they are not allowed to be seated next to).
Hope that explanation makes sense!
I am really stumped with this question, completely lost and no idea where to start. My train of thought was as follows, however: If you seat the first person down, then there are 29 people yet to be seated. Additionally, there are 2 people you can't sit in the next seat, adjacent to the first person you sat. So there are 27 people who can be seated in the second seat. Then in the third, there are 28 people remaining, as two have been seated. Again, two people can't sit there, for there are 26 people who can sit in the third chair.
Now, if my thinking is even correct up to this point, things start to get particularly foggy in my mind. So 27 people remain, and a maximum of two people may not be able to sit in the seat next to the third person. So it seems reasonable to suggest that 25 people can sit there. But if one of those two people has already sat earlier, then actually there are actually 26 of the remaining 27 who are allowed to sit in this seat. It is here that I am finding myself at a complete loss.
It occurred to me that I could calculate the total possible number of seating arrangements without conditions, and then subtract the arrangements where the given condition is broken....but that would be a lot of different illegitimate conditions to calculate.
Any help would be much appreciated. I have a few questions other like this to wrangle with afterwards aswell, so I don't mind if you help, just give hints, or solve the entire thing.

A: You can do this via inclusion-exclusion, but I don't see how to find a closed form. Let's generalize from $10$ to $n$ groups of $3$. There are $3n$ conditions, one for each of the three pairs in each of the $n$ groups. To form all possible conjunctions of conditions, we can select $k$ groups in which $2$ conditions are fulfilled and $l$ groups in which $1$ condition is fulfilled. For each of the $k$ groups, there are $3$ ways to select the $2$ out of $3$ conditions, and for each of the $l$ groups, there are $3$ ways to select the $1$ out of $3$ conditions; in both cases there are $2$ orders for the group member fulfilling the conditions. Given the fulfilled conditions, there remain $(3n-2k-l-1)!$ possible orders of the $3n-2k-l$ blocks of people, where subtracting $1$ accounts for the cyclical symmetry. If you want to count cyclically equivalent configurations as distinct, you need to multiply the entire result by $3n$. Thus, inclusion-exclusion yields as the number of configuration that don't fulfill any of the conditions (and thus fulfill the given restrictions):
$$
\sum_{k=0}^{10}\sum_{l=0}^{10-k}(-1)^l6^k6^l\binom n{k,l,n-k-l}(3n-2k-l-1)!\;.
$$
I don't see how to get a closed form for this. For $n=10$, we can evaluate the double sum, e.g. in Sage; the result is $1038433851912064897405414932480$.


text:
Q: Exercises about Hausdorff spaces two problems from Dugundji's book page $156$. (I don't know why the system deletes the word hi in this sentence)
$1$. Let $X$ be a Hausdorff space. Show that:
a) $\bigcap \{F: x \in F , F \ \textrm{closed}\}  = \{x\}$.
b) $\bigcap \{U : x \in U, U \ \textrm{open}\} = \{x\}$.
c) The above properties are not equivalent to being Hausdorff.
$2$. Prove every infinite Hausdorff space contains a countably infinite discrete subspace.
My work:

*

*(a) So let $y \not \in \{x\}$ then $x \neq y$. Since $X$ is Hausdorff we can find disjoint open sets $U_{x}$, $V_{y}$. Define $F = X \setminus V_{y}$ then $x \in F$, $F$ is closed and $y \not \in F$, so $y \not \in \bigcap \{F: x \in F , F \ \textrm{closed}\}$.

(b) Same as above, just note that $y \not \in U_{x}$, hence not in the intersection.
(c) Not sure here, can we take $X$ any infinite set endowed with the cofinite topology?
Claim:  $\bigcap \{F: x \in F , F \ \textrm{closed}\}  = \{x\}$. Suppose $y \not \in \{x\}$ then $y \neq x$, that is: $y \not \in \{x\}$. Note that since $X$ is a $T_{1}$ space then $F=\{x\}$ is closed and contains $x$, so $y$ is not in the intersection.
Similarly for $(b)$. But $X$ is not Hausdorff since any two non-empty open sets intersect.
2) How do you prove this one?

A: Some style comments on 1(a): As user6312 says, you should just begin by supposing that $y \ne x$; starting with $y \notin \{x\}$ is an unnecessary complication. More important, what Hausdorffness gives you is not just disjoint open sets $U_x$ and $V_y$, but disjoint open sets $U_x$ and $V_y$ such that $x \in U_x$ and $y \in V_y$, and for clarity you should say so. (Minor point: if you use different letters for the sets, there's no reason to use subscripts: just call them $U$ and $V$. If you use the subscripts, you might as well use a single basic name, e.g., $U_x$ and $U_y$.)
1(c): Just a brief expansion of what user 6312 said: $\{x\}$ is finite, so by definition its complement is open, and $\{x\}$ is therefore one of the closed sets containing $x$, and you don't need to look further to see that $\{x\}$ is the intersection of the closed sets containing $x$. Alternatively, if you've already proved that (a) is true in any $T_1$ space, you merely observe that if $x \ne y$, then $X \setminus \{y\}$ is an open set containing $x$ but not $y$, so $X$ is $T_1$. (But in that case you could have done (a) simply by noting that every Hausdorff space is $T_1$.) For the second part of (c) you do need the argument that $x$ is the intersection of the open sets $X \setminus \{y\}$ for $y \ne x$.
(2) If $x \in X$ has a finite open nbhd, then $\{x\}$ is open (i.e., $x$ is an isolated point). (Why?) Let $I$ be the set of isolated points of $X$; clearly $I$ is discrete, so if $I$ is infinite, just pick any countably infinite subset of it. That's the easy case; you have to work harder when $I$ is finite.
In that case let $Y = X \setminus I$. Note that if $y \in Y$, every open nbhd $V$ of $y$ is infinite. Now build the desired discrete set recursively. Start by choosing distinct points $y_0,y_1 \in Y$, and let $W_0,V_1$ be disjoint open sets with $y_0 \in W_0$ and $y_1 \in V_1$. (Here there's a reason for using different letters: the $V_n$'s are needed temporarily for the construction, but it's the $W_n$'s that we really want.) $V_1 \cap Y$ is infinite (why?), so we can pick a point $y_2 \in V_1 \setminus \{y_1\}$. Now let $W_1$ and $V_2$ be disjoint open subsets of $V_1$ such that $y_1 \in W_1$ and $y_2 \in V_2$. Now $V_2 \cap Y$ is infinite, so we can pick a point $y_3 \in V_2 \setminus \{y_2\}$ and let $W_2$ and $V_3$ be disjoint open subsets of $V_2$ such that $y_2 \in W_2$ and $y_3 \in V_3$. Continue in this fashion to get points $y_n$ and open sets $W_n$ for each $n \in \omega$. Clearly $y_n \in W_n$ for each $n$, and with a little thought you should be able to see that if $m \ne n$, $y_m \notin W_n$. (It's probably best to consider the cases $m<n$ and $m>n$ separately. It may also help to make a sketch of the first few steps of the construction.)

A: a) Hausdorff implies $T_1$ which implies singletons are closed. Note that closure of $\{x\}$ is defined: $\bigcap\{F:x\in F\}$, and this must equal $\{x\}$ by the aforementioned property of $T_1$ spaces.
b) Choose a point $y \not= x$. We note that there is an open set containing $x$, that does not contain $y$ by choosing 2 open sets, one containing $x$, the other containing $y$, such that the sets are disjoint. The result follows - if $y$ is not in one open set containing $x$, it is certainly not in every open set containing $x$.
c) a: Use the cofinite topology on the set of reals. Singletons are again closed. The fact that every open set intersects every other open set (except $\emptyset$) shows that this topology is not Hausdorff.
b: Use the cofinite topology on the reals. Consider open sets of the form $\{r\}^c$ where $r$ is a real number different from $\{x\}$. The intersection of all these sets is {x} but again, the space is not Hausdorff.
Part 2:
Edit: This construction doesn't work, I can't think of a way to fix it sorry.
Let $H$ be a Hausdorff space. Let's construct the discrete space inductively.
Induction
Suppose we have the set of points $\{x_i : 1\le i \le n\}$ and a corresponding collection of open sets $O_i$ such that
1.$x_i \in O_i$
2. $x_j \not \in O_i$ where $j \not= i$
3. $\bigcup_{i=1} ^n O_i$ does not cover $H$.
Choose points $x_{n+1}$ and $y$ in $[\bigcup_{i=1}^n O_i]^c$. Choose an open set $O_{n+1}$ around $x_{n+1}$ that does not contain $y$ or $x_i : 1\le i \le n$. (We can find this set by intersecting $n+1$ open sets that contain $x_{n+1}$ which are disjoint from the $x_i : 1\le i \le n$, and $y$. Now we have set of points $\{x_i : 1\le i \le n+1\}$ and a corresponding collection of open sets $O_i$ such that
1. $x_i \in O_i$
2. $x_j \not \in O_i$ where $j \not= i$
3. $\bigcup_{i=1} ^{n+1} O_i$ does not cover $H$.
Base Case
Chose $x_1$ and $y$ in $H$, and choose $O_1$ which contains $x_1$ but not $y$.
Conclusion
Now we have shown the existence of an increasing sequence of subspaces $S_n = \{x_i: 0 \le i \le n\}$ which are discrete. Just consider that $\{x_i\} = S_n \cap O_i \Rightarrow \{x_i\} $ is open in the subspace topology. (By increasing sequence I mean $S_n \subset S_{n+1}$) It remains to be shown that the limit is discrete.
Let $S_{\infty} = \bigcup_n S_n = \{x_i : 1\le i\}$. Choose any point $x_i$ in $S_{\infty}$. Note that, by construction, $O_i \cap S_{\infty} = \{x_i\}$ so all singletons are open and therefore $S_{\infty}$ is a discrete subspace which is countable and infinite.

A: Your answer to 1(a) is too complicated.  Note that $\{x\}$ is in the collection whereof you are taking the intersection.
Also, your answer to 1(c) is too complicated:  The natural numbers under the cofinite topology provides a counterexample.
For 2, I haven't thought through the details, but I think this works:  First show that any infinite Hausdorff space must have a nonempty open set whose complement is infinite.  Then apply the Axiom of Choice inductively to carve out neighborhoods of points.


text:
Q: What is Iused in df -kg on UNIX? What is Iused column when running df -kg command on AIX server?
@:/logs #df -kg
Filesystem    GB blocks      Free %Used    Iused %Iused Mounted on
/dev/hd4           1.00      0.61   39%     6103     4% /
/dev/hd2           3.00      0.56   82%    53834    28% /usr

A: Iused means Inodes space used. Each file in Unix-like systems has an associated data structure called Inode which stores the information about the file (sometimes called file metadata). In the output of the df command the Iused column indicated the space used by the Inodes of the files and the %Iused column indicates how much percentage of the total allocated Inodes space has been used so far.
One implication is that you have a realistic limits on how many files you can have on the filesystem regardless of the space.


text:
Q: Vertical and horizontal align in multicolumn and multirow I have big issues with alllign in multicolumn and multirow. In I need vertical allign in multicolumn with content 'a' and 'b'. Also I need horizontal and vertical allign in multirow. Is there way to do it? I will be grateful if someone help.
\documentclass{article}
\usepackage{geometry}                 % customize page layout
\usepackage{array}
\usepackage{multirow}                 % multirow for table (rowspan)

\geometry{paper=a4paper, landscape,hmargin=28.5mm,vmargin=20mm}

\setlength\parindent{0cm}   % no indent for whole document
\setlength{\tabcolsep}{0cm}   % padding either side of each column (only horizontal)

% document start
\begin{document}

\newcolumntype{M}[1]{>{\centering\arraybackslash}m{\dimexpr#1-\arrayrulewidth\relax}}
\newcolumntype{P}[1]{>{\centering\arraybackslash}p{\dimexpr#1-\arrayrulewidth\relax}}

  \begin{tabular}{
  | P{1.4cm}
  | M{1.4cm}
  | M{1.4cm}
  | P{7.6cm}
  | P{6.4cm}
  | P{1.2cm}
  | P{1.2cm}
  | P{1.2cm}
  | P{2.2cm}
  |
}

\hline
\multicolumn{4}{|c|}{\rule[-0.8cm]{0cm}{1cm} a} & \multicolumn{5}{c|}{b} \\

\hline
0 & 1 \par \footnotesize{(1)} & 2 & 3 & 4 & 5 & 6 & 7 &  \\\cline{1-8}

\rule[-0.8cm]{0cm}{1cm} & & &
\multirow{3}{7.6cm}{%
Question \hfill $\bigcirc$ \strut  Yes  $\bigcirc$ No \newline
Question \hfill $\bigcirc$ \strut  Yes  $\bigcirc$ No \newline
Question \hfill $\bigcirc$ \strut  Yes  $\bigcirc$ No \newline
Question \hfill $\bigcirc$ \strut  Yes  $\bigcirc$ No \newline
Question \hfill $\bigcirc$ \strut  Yes  $\bigcirc$ No \newline
Question \hfill $\bigcirc$ \strut  Yes  $\bigcirc$ No%  <--- % needed
}
  & & & & & \\
\cline{1-3}\cline{5-8}
\rule[-0.8cm]{0cm}{1cm} & s & & & & & & & \\\cline{1-3}\cline{5-8}
\multicolumn{2}{|P{2.8cm}}{\rule{0cm}{1cm}}  & & & & \multicolumn{3}{P{2.8cm}}{\rule{0cm}{1cm}}  &\\
\hline

\end{tabular}

% document end
\end{document}

A: Here is a slightly simpler code, and the use of \multirowcell from the makecell package. Everything has been vertically centred:
\documentclass{article}
\usepackage{geometry} % customize page layout
\usepackage{array}
\usepackage{multirow} % multirow for table (rowspan)
\geometry{paper=a4paper, landscape,hmargin=28.5mm,vmargin=20mm}

\usepackage{etoolbox}
\usepackage{makecell}
\renewcommand\cellalign{{p{\dimexpr7.6cm-10pt\relax}}c}
\patchcmd\cellset{\def\arraystretch{1}}{\def\arraystretch{1.12}}{}{}

\setlength\parindent{0cm} % no indent for whole document
\setlength{\tabcolsep}{0cm} % padding either side of each column (only horizontal)

\newcolumntype{M}[1]{>{\centering\arraybackslash}m{\dimexpr#1-\arrayrulewidth\relax}}
\newcolumntype{P}[1]{>{\centering\arraybackslash}p{\dimexpr#1-\arrayrulewidth\relax}}

\newcommand\YesNo{\hfill$\bigcirc$ \strut Yes\hskip0.5em$\bigcirc$ No }

% document start
\begin{document}

\begin{tabular}{%
    | P{1.4cm}
    | M{1.4cm}
    | M{1.4cm}
    | P{7.6cm}
    | P{6.4cm}
    | P{1.2cm}
    | P{1.2cm}
    | P{1.2cm}
    | P{2.2cm}
    |
    }%

    \hline
    \multicolumn{4}{|c|}{\rule[-0.45cm]{0pt}{1cm} a} & \multicolumn{5}{c|}{b} \\

    \hline
    0 & \thead{1 & & & & & & & \\ \footnotesize(1)}& 2 & 3 & 4 & 5 & 6 & 7 & \\
    \cline{1-8}
    \rule[-0.45cm]{0pt}{1cm} & & &
    \multirowcell{3}[4pt]{%
    Question \YesNo\\
    Question \YesNo\\%
    Question \YesNo\\%
    Question \YesNo\\%
    Question \YesNo\\%
    Question \YesNo% <--- % needed
    }%
    & & & & & \\
    \cline{1-3}\cline{5-8}
    \rule[-0.45cm]{0pt}{1cm} & s & & & & & & & \\
    \cline{1-3}\cline{5-8}
    \multicolumn{2}{|P{2.8cm}}{\rule[-0.45cm]{0pt}{1cm}} & & & & \multicolumn{3}{P{2.8cm}}{} &\\
    \hline

  \end{tabular}

  % document end
\end{document}


text:
Q: Atmel UC3A0512 FAT API problems after defining FREERTOS_USED symbol I'am using FAT API provided by ASF to read data from the flash,
The FAT API uses a global variable fs_g_status to help debugging the problems, but it seems that  fs_g_status takes
meaningless values:
Possible values for fs_g_status :
#define  FS_ERR_HW               (FAIL+0)    //!< Hardware driver error
#define  FS_ERR_NO_FORMAT        (FAIL+1)    //!< The selected drive isn't formated
#define  FS_ERR_NO_PART          (FAIL+2)    //!< The selected partition doesn't existed
#define  FS_ERR_NO_SUPPORT_PART  (FAIL+3)    //!< The selected partition isn't supported
#define  FS_ERR_TOO_FILE_OPEN    (FAIL+4)    //!< The navigation have already opened a file
#define  FS_ERR_END_OF_DRIVE     (FAIL+5)    //!< There are not other driver
#define  FS_ERR_BAD_POS          (FAIL+6)    //!< The position is over the file
#define  FS_ERR_FS               (FAIL+7)    //!< File system error
#define  FS_ERR_NO_FIND          (FAIL+8)    //!< File no found
#define  FS_ERR_ENTRY_EMPTY      (FAIL+9)    //!< File entry empty
#define  FS_ERR_ENTRY_BAD        (FAIL+10)   //!< File entry bad
#define  FS_ERR_ENTRY_BADTYPE    (FAIL+11)   //!< File entry type don't corresponding
#define  FS_ERR_NO_DIR           (FAIL+12)   //!< The selected file isn't a directory
#define  FS_ERR_NO_MOUNT         (FAIL+13)   //!< The partition isn't mounted
#define  FS_ERR_NO_FILE_SEL      (FAIL+14)   //!< There are no selected file
#define  FS_NO_LAST_LFN_ENTRY    (FAIL+15)   //!< The file entry isn't the last long file entry

#define  FS_ERR_ID_FILE          (FAIL+17)   //!< The file identifier is bad
#define  FS_ERR_NO_FILE          (FAIL+18)   //!< The selected file entry isn't a file
#define  FS_LUN_WP               (FAIL+19)   //!< Drive is in read only mode
#define  FS_ERR_READ_ONLY        (FAIL+20)   //!< File is on read access only
#define  FS_ERR_NAME_INCORRECT   (FAIL+21)   //!< The name don't corresponding at the filter name
//...

with
#define FAIL      1

This is the function i use to read data from flash
int read_Flash_Data()
{
  /* initialize FSACCESS mutex and navigators */
  if (b_fsaccess_init())
  {
    usart_write_line((&AVR32_USART0), " b_fsaccess_init return true \r\n");
  }
  //fs_g_status = 0x00 OK

  /* Try to init data flash */
  if (at45dbx_mem_check())
  {
    /* display message */
    usart_write_line((&AVR32_USART0), " at45dbx_mem_check return true \r\n");
}
else
{
    /* display error message */
    usart_write_line((&AVR32_USART0),"  at45dbx_mem_check return false\r\n");
    return (-1);
}
//fs_g_status = 0x00 OK

if (nav_drive_set(LUN_ID_1) == false)
{
    usart_write_line((&AVR32_USART0)," nav_drive_set return false \r\n");
    return (-1);
}
//fs_g_status = 0x01 ==> Hardware driver error NOK , but the nav_drive_set(LUN_ID_1) return true !!!!

if( !nav_partition_mount() )
{
    usart_write_line((&AVR32_USART0),"nav_partition_mount return false \r\n");
    return (-1);
}
//fs_g_status = 0x04 ==> The navigation have already opened a file, but the nav_partition_mount() return true !!!!

if ((ret = open(ACTUAL_CONFIG_FILE_PATH, O_RDONLY)) < 0)
{
    usart_write_line((&AVR32_USART0),"Opening file failed \r\n");
    return (-1);
}
//fs_g_status = 0x10 ==16(decimal) open return true !!!!
//...
}

I think that this is not logic, fs_g_status should only be set if the functions return false.
OK let's say that there is minor problems and major ones that lead the functions to fail and the comments are not good enough.
Now this function is used in a freeRTOS task and i have to define the symbol FREERTOS_USED in the compilation to protect flash in concurent access, in the description above the symbol wasn't defined.
and now nav_partition_mount() return false and fs_g_status = 0x01.
Does anyone encounter the problem i can't seem to find ways  to debug the problem, any suggestion is welcome.

A: You forgot to initialize the ctrl_access_semphr,
you have to use the function ctrl_access_init defined in ctrl_access.c.
#ifdef FREERTOS_USED

bool ctrl_access_init(void)
{
 // If the handle to the protecting semaphore is not valid,
 if (!ctrl_access_semphr)
 {
   // try to create the semaphore.
   vSemaphoreCreateBinary(ctrl_access_semphr);

   // If the semaphore could not be created, there is no backup solution.
   if (!ctrl_access_semphr) return false;
  }

 return true;
}
#endif

Your function should look like :
int read_Flash_Data()
{
  /* initialize FSACCESS mutex and navigators */
  if (b_fsaccess_init())
  {
    usart_write_line((&AVR32_USART0), " b_fsaccess_init return true \r\n");
  }

  /* initialize ctrl_access semaphore */
  if (ctrl_access_init())
  {
    usart_write_line((&AVR32_USART0), " ctrl_access_init return true \r\n");
  }
  //......


text:
Q: Line numbers are outside the box in algorithm2e Here is my code:
\documentclass[11pt]{llncs}
\usepackage[utf8]{inputenc}
\usepackage{parskip}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{dsfont}
\usepackage{float}
\usepackage{multicol}
\usepackage{fixltx2e}
\usepackage{multicol}
\newcommand\blfootnote[1]{%
  \begingroup
  \renewcommand\thefootnote{}\footnote{#1}%
  \addtocounter{footnote}{-1}%
  \endgroup
  }

\usepackage[T1]{fontenc}
\usepackage{comment}
\usepackage{amsmath}                                    %
\setcounter{MaxMatrixCols}{20}
\usepackage[margin=1in]{geometry}
\usepackage[noend, boxruled, linesnumbered]{algorithm2e}
\usepackage{xcolor}
\usepackage{setspace}
\usepackage{hyperref}
\definecolor{bl}{rgb}{0.0,0.2,0.6}
\definecolor{dark-red}{rgb}{0.4,0.15,0.15}
\definecolor{dark-blue}{rgb}{0.15,0.15,0.4}
\definecolor{medium-blue}{rgb}{0,0,0.5}
\usepackage{sectsty}
\hypersetup{
    colorlinks, linkcolor={dark-red},
    citecolor={dark-blue}, urlcolor={medium-blue}
}
\usepackage{graphicx}
\usepackage[compact]{titlesec}
\newtheorem{observation}{\textsc{Observation}}
%%% Start of the document
\begin{document}
\begin{algorithm}[H]
\label{alg:seed}
    \SetAlgoLined
     \SetKwInOut{Input}{input}
    \Input{\textsc{Graph} $G$}
    line number outside the box\;
    another line\;
    a third line\;
    what is going on?\;
    \caption{\textsc{Caption}}
\end{algorithm}
\end{document}

And here is the output:

Which command sends line numbers outside of the box?

A: You can use algorithm2e and parskip in the same document if you load algorithm2e first:
\usepackage[noend, boxruled, linesnumbered] {algorithm2e}
\usepackage{parskip}

Code:
\documentclass[11pt]{llncs}
\usepackage[utf8]{inputenc}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{dsfont}
\usepackage{float}
\usepackage{multicol}
\usepackage{fixltx2e}
\usepackage{multicol}
\newcommand\blfootnote[1]{%
  \begingroup
  \renewcommand\thefootnote{}\footnote{#1}%
  \addtocounter{footnote}{-1}%
  \endgroup
  }

\usepackage[T1]{fontenc}
\usepackage{comment}
\usepackage{amsmath}
\setcounter{MaxMatrixCols}{20}
\usepackage[margin=1in]{geometry}
%
\usepackage[noend, boxruled, linesnumbered] {algorithm2e}
\usepackage{parskip}
%
\usepackage{xcolor}
\usepackage{setspace}
\usepackage{hyperref}
\definecolor{bl}{rgb}{0.0,0.2,0.6}
\definecolor{dark-red}{rgb}{0.4,0.15,0.15}
\definecolor{dark-blue}{rgb}{0.15,0.15,0.4}
\definecolor{medium-blue}{rgb}{0,0,0.5}
\usepackage{sectsty}
\hypersetup{colorlinks, linkcolor={dark-red},
citecolor={dark-blue}, urlcolor={medium-blue}}
\usepackage{graphicx}
\usepackage[compact]{titlesec}
\newtheorem{observation}{\textsc{Observation}}

\usepackage{blindtext}% dummy text
% Start of the document
\begin{document}
\begin{algorithm}[H]
\label{alg:seed}
    \SetAlgoLined
    \SetKwInOut{Input}{input}
    \Input{\textsc{Graph} $G$}
    line number outside the box\;
    another line\;
    a third line\;
    what is going on?\;
    \caption{\textsc{Caption}}
    return
\end{algorithm}
\blindtext

\blindtext
\end{document}

A: I don't know what causes the conflict, my study shows that removing the parkskip package will send the line number into the box.

\documentclass[11pt]{llncs}
\usepackage[utf8]{inputenc}
%\usepackage{parskip}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{dsfont}
\usepackage{float}
\usepackage{multicol}
\usepackage{fixltx2e}
\usepackage{multicol}
\newcommand\blfootnote[1]{%
  \begingroup
  \renewcommand\thefootnote{}\footnote{#1}%
  \addtocounter{footnote}{-1}%
  \endgroup
  }

\usepackage[T1]{fontenc}
\usepackage{comment}
\usepackage{amsmath}                                    %
\setcounter{MaxMatrixCols}{20}
\usepackage[margin=1in]{geometry}
\usepackage[noend, boxruled, linesnumbered] {algorithm2e}
\usepackage{xcolor}
\usepackage{setspace}
\usepackage{hyperref}
\definecolor{bl}{rgb}{0.0,0.2,0.6}
\definecolor{dark-red}{rgb}{0.4,0.15,0.15}
\definecolor{dark-blue}{rgb}{0.15,0.15,0.4}
\definecolor{medium-blue}{rgb}{0,0,0.5}
\usepackage{sectsty}
\hypersetup{colorlinks, linkcolor={dark-red},
citecolor={dark-blue}, urlcolor={medium-blue}}
\usepackage{graphicx}
\usepackage[compact]{titlesec}
\newtheorem{observation}{\textsc{Observation}}
%%% Start of the document
\begin{document}
\begin{algorithm}[H]
\label{alg:seed}
    \SetAlgoLined
    \SetKwInOut{Input}{input}
    \Input{\textsc{Graph} $G$}
    line number outside the box\;
    another line\;
    a third line\;
    what is going on?\;
    \caption{\textsc{Caption}}
    return
\end{algorithm}
\end{document}


text:
Q: Convert functional component from class component I want to convert my class component to functional component and t is difficult for me to convert render() of class component.
Here is my code sandbox link. https://codesandbox.io/s/snowy-smoke-s65vx4?file=/src/App.js
Can anyone please help me with this

A: The render part is just going to be the body of the function and the return.
const myfunccomp : React.FC = ({id, info, msgList}) => {
    const chatContentHeader = () => {...}
    const chatContentBody = () => {...}
    const chatContentFooter = () => {...}
    ...
    return (
      <div className="chat-content">
        {chatContentHeader(info.name)}
        {chatContentBody(msgList, id)}
        {chatContentFooter()}
      </div>
    );
  }


text:
Q: infinite scroll no foreach Alguém poderia me ajudar? Estou tentando achar alguma forma de usar o infinite scroll nesse código:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "lista.m3u8");
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

if (substr($info["http_code"], 0, 2) != 20) {
    die("Não possível conectar ao servidor!");
}

preg_match_all('/(tvg-logo="(?<logo>.*?)".+group-title="(?<name>.*?)".+\n(?P<link>http?:\/\/.+))/', $response, $channels, PREG_SET_ORDER);

?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>nPlay</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://mdbootstrap.com/previews/docs/latest/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://mdbootstrap.com/previews/docs/latest/css/mdb.min.css" rel="stylesheet">

        nPlay

                    <?php foreach($channels as $channel): ?>

                        <a href="<?php echo $channel["link"] ?>" title="<?php echo $channel["name"] ?>">
                            <img src="<?php echo $channel["logo"] ?>" class="img-responsive img-circle" />

                              <?php echo $channel["name"] ?>

                    <?php endforeach; ?>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

%channel_name%

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

A: Como comentei anteriormente, é necessário separar o PHP do HTML. Nesse caso iremos criar um arquivo chamado loadChannels.php, com o seguinte código:
<?php

header("Access-Control-Allow-Origin: *");

/* Captura a página */
if (isset($_GET['page'])) {
    $page = (int)$_GET['page'];
} else {
    $page = 1;
}

/* Acessa o parquivo `lista` + número da página + `.m3u8` */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8081/lista{$page}.m3u8");
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

if (substr($info["http_code"], 0, 2) != 20) {
    die();
}

preg_match_all('/(tvg-logo="(?<logo>.*?)".+group-title="(?<name>.*?)".+\n(?P<link>http?:\/\/.+))/', $response, $channels, PREG_SET_ORDER);

/**
 * Cria a lista LI e escreve na tela.
 * Como vamos acessar via AJAX, o conteúdo
 * será retornado via JavaScript
 */
foreach($channels as $channel): ?>

    <a href="<?php echo $channel["link"] ?>" title="<?php echo $channel["name"] ?>">
        <img src="<?php echo $channel["logo"] ?>" class="img-responsive img-circle" />

          <?php echo $channel["name"] ?>

<?php endforeach; ?>

Agora no arquivo HTML, podemos utilizar o seguinte JavaScript:
/* Define a página inicial */
let scrollPage = 1;

/* Cria uma função para detectar se o usuário rolou a barra até o final */
$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       loadChannels();
   }
});

/* Utilizamos o método `on` para detectar o evento de clique de novos elementos */
$("#channels-list").on("click", "a", function(e) {
    e.preventDefault();

    $("#modal").find(".modal-title").text( $(this).attr("title") );
    $("#modal").find(".modal-body")
        .empty()
        .append( "" ); //Altere essa linha para chamar outro arquivo

    $("#modal").modal("show");

    /*
     * Utilizamos esse evento para executar uma função ao fechar o modal
     * Caso o modal seja fechado sem remover o `iframe`, o player continuará funcionando.
     */
    $('#modal').on('hidden.bs.modal', function (e) {
      $("#modal iframe").remove();
    })
});

/*
 * Utilizamos esse evento para executar uma função ao fechar o modal
 * Caso o modal seja fechado sem remover o `iframe`, o player continuará funcionando.
 */
$('#modal').on('hidden.bs.modal', function (e) {
  $("#modal iframe").remove();
})

/**
 * Função responsável por realizar a requisição para `loadChannels.php`
 */
function loadChannels(page) {

    /* Realizamos a requisição e retornamos o resultado na variável `data` */
    $.get("loadChannels.php?page="+scrollPage, function(data) {

        /* Incrementamos o valor retornado na DIV indicada e somamos o valor de `scrollPage` + 1 */
        $("#channels-list").append(data);
        scrollPage++;
    });
}

/* Carregamos a primeira lista */
loadChannels();

É necessário remover o código da DIV #channels-list


text:
Q: How to find and change every match in excel find from VBA not just the next one? I have some VBA code I wrote that finds cells that contain a specific formula and then appends to that formula.
Sub macro()
    Cells.Find(What:="0.0049>SUM", After:=ActiveCell, LookIn:=xlFormulas2, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Activate
    ActiveCell.Formula2R1C1 = _
        "=RC[-4]+0.0049>SUM(RC[-11]:RC[-5])-OFFSET(INDIRECT(ADDRESS(ROW(),COLUMN())),0,-6)"
End Sub

This does what I want it to do but only for the next cell it can find. I want to run this once and have it find every instance on a sheet and append to it. Similar to how replace vs replace all works, currently my code is just doing a replace but I want a replace all.
I am not too familiar with VBA how can I achieve this?
Thank you.


text:
Q: Database mapping I have created a MySql database with two tables (books, members). A member can have many books and a certain book can have only one member. I want to create a spring boot project that will be a REST API that preforms CRUD operations on a database. For database operations I'm using Spring Data JPA.

Next I have created two classes called books and members.
    @Entity
    @Table(name = "members")
    public class Members {
        @Id
        @Column(name = "id")
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;

        @Column(name = "last_name")
        private String lastName;

        @Column(name = "first_name")
        private String firstName;

        @Column(name = "address")
        private String address;

        @Column(name = "phone_num")
        private String phoneNum;

        @Column(name = "email")
        private String email;

        @OneToMany(mappedBy = "members", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
        private List<Books> books;

//getters and setters

@Entity
@Table(name = "books")
public class Books {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "title")
    private String title;

    @Column(name = "author_last_name")
    private String authorLastName;

    @Column(name = "author_first_name")
    private String authorFirstName;

    @Column(name = "publisher")
    private String publisher;

    @Column(name = "publishing_year")
    private String publishingYear;

    @ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name = "id_member")
    private Members members;
//getters and setters

I have created an interface called LibraryRepository that extends JpaRepository.
    public interface LibraryRepository extends JpaRepository<Members, Integer> {
    }

My LibraryService interface
public interface LibraryService {
    List<Members> findAll();
}

and LibraryServiceImpl classes
@Service
public class LibraryServiceImpl implements LibraryService {

    private LibraryRepository libraryRepository;

    @Autowired
    public LibraryServiceImpl(LibraryRepository libraryRepository) {
        this.libraryRepository = libraryRepository;
    }

    @Override
    public List<Members> findAll() {
        return libraryRepository.findAll();
    }
}

And rest controller
@RestController
@RequestMapping("/api")
public class LibraryRestController {

    private LibraryService libraryService;

    @Autowired
    public LibraryRestController(LibraryService libraryService) {
        this.libraryService = libraryService;
    }

    @GetMapping("/loans")
    public List<Members> findAll(){
        return libraryService.findAll();
    }
}

One of the members has one book on loan.
When I run the application and use a GET method on http://localhost:8080/api/loans what is returned is an infinite list. A member has a book and this book has a member, and this member has a book and so on.....
I believe that something is wrongly mapped on my entity classes but I can't find what exactly.

A: The problem is that you have a bi-directional mapping between Member and Book. This is a circular dependency and if the JSON marshaller (Jackson) is converting the objects to JSON it follows the dependencies and produces an infinite loop.
You have to use JSON annotations to break this loop.
For example:
@JsonBackReference
@OneToMany(mappedBy = "members", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
private List<Books> books;

and
@JsonManagedReference
@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
@JoinColumn(name = "id_member")
private Members members;

This is just an example and it's up to you to decide which of the dependency is the managed reference.
Read more about that topic here:
https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion


text:
Q: asp.net nHibernate selecting data from a View mapped I have two tables and one view:
TABLE "Table_1" (
    "Id" INTEGER NOT NULL DEFAULT AUTOINCREMENT,
    "Field_1" VARCHAR(11) NOT NULL,
    PRIMARY KEY ( "Id" ASC )
) IN "system";

TABLE "Table_2" (
    "Table_1_Id" INTEGER NOT NULL,  //// (THIS FIELD HAVE A FOREIGN KEY WITH TABLE "Table_1" FIELD "Id")
    "Field_2" VARCHAR(11) NOT NULL,
    PRIMARY KEY ( "Table_1_Id" ASC )
) IN "system";

VIEW "vwView_1"()
AS
select
    Id,
    Field_1,
    Field_2
from Table_1 key join Table_2

This is the View map:
...
Table("vwView_1");
Mutable(false);
Id(x => x.Id);
Property(x => x.Field_1);
Property(x => x.Field_2);
...

This is the View data in the database:
Id  Field_1  Field_2
1   Green    Blue
1   Green    Red
2   Black    White
3   Orange   Blue
6   Red      Orange
6   Red      Green

When I get the data with nHibernate, I got this data:
Id  Field_1  Field_2
1   Green    Blue
1   Green    Blue
2   Black    White
3   Orange   Blue
6   Red      Orange
6   Red      Orange

I think that the problem is in View map, but I can't find a way to resolve this :(
Somebody have an idea to resolve?

A: Your view is not returning a unique ID therefore when NHibernate sees the duplicate Id it already thinks that the row is hydrated as it is in the first level cache. Therefore it just returns the same duplicated row, which is why you are seeing the behaviour 1, Green, Blue and 1, Green, Blue
You have two options:-

*

*in your view return a unique id which is the unique Id in table 2 although that judging by your schema that does not look possible

*You need to override equals and GetHashCode in your view map class, see this blog for more info.

A: You have the Id column mapped as the Identifier field, so NHibernate's first level cache doesn't bother to re-read rows that it has already cached. That's why all the values with the same Id value have the same values for Field_1 and Field_2.
Maybe you can add a ROW_NUMBER() field in your view and map that as the identifier.


text:
Q: How to set a max timeout for Jest test running Puppeteer? Tried looking through the docs, but didn't find a way to set a max timeout for a test case. Seems like a simple feature.
import puppeteer from 'puppeteer'

test('App loads', async() => {
  const browser = await puppeteer.launch({ headless: false, slowMo: 250 });
  const page = await browser.newPage();
  await page.goto('http://localhost:3000');
  await browser.close();
});

A: Jest's test(name, fn, timeout) function can take a 3rd parameter that specifies a custom timeout.
test('example', async () => {
  ...
}, 1000); // timeout of 1s (default is 5s)

Source: https://github.com/facebook/jest/issues/5055#issuecomment-350827560

A: You can also set the timeout globally for a suite using jest.setTimeout(10000); in the beforeAll() function:
beforeAll(async () => {

    jest.setTimeout(10000); // change timeout to 10 seconds

});


text:
Q: How to fix error : 'make' is not recognized as an internal or external command, operable program or batch file I tried install the COCO API in win10 with code
git clone https://github.com/cocodataset/cocoapi.git
cd cocoapi/PythonAPI
make
cp -r pycocotools <path_to_tensorflow>/models/research/

In step 3, i got a error :
'make' is not recognized as an internal or external command,
operable program or batch file.

i tried fix it, then i got a problem is i dont have path gnuwin32
What is gnuwin32 ? and how to fix error "make" is not recognzied ??

A: 'make' is a program that can be run on Linux. On windows, you can't run it. You have to use Visual Studio or other compile tools.
You are trying to build COCO API on your hand.
But it may be so complicated for you, especially on Windows.
I recommend install COCO API using pip
Usually, you can run like this :
pip install pycocotools

But on Windows, you may met some error.
In that case you can run a modified verision.
Try this :
pip install git+https://github.com/philferriere/cocoapi.git#egg=pycocotools^&subdirectory=PythonAPI

If it is installed successfully, you don't need to build COCO API by yourself.
I hope it help you.