Sorting ListView with Item, and after that - Sub item 1

Question: I want to sort my items and sub items like this:
one - a
one - b
one - c
three - apricot
three - banana
two - orange
two - pear

I've set Sorting to Ascending, but that only sorts the first column.
Comment: What are we sorting?  A list of strings?  If so, then there aren't 2 columns.  If not strings, then what is it?  More code please.
Comment: It is an ordinary ListView. I have string items in there, and string subitems to the items.

Like this: http://spunit.tk/x/scrn2_3.png
Answer: You need to use the ListView.ListViewItemSorter property to provide a custom IComparer. You have access to the ListViewItem and it's sub-items in the Compare method.
Here's an example of doing so (quickly thrown together). Note the comments in the code that explain what part is just setting up the sample ListView. There's very little code required to actually implement the sorting you want, and I've marked by comments where they are located. The only setup I did that isn't in the code is dropping a ListView on a new blank WinForm; the rest is done in the code, and there's a sample image below that shows the results.
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      this.SuspendLayout();

      // This part is just setting up the ListView
      // Turn off default sorting, and set to display columns
      this.listView1.Sorting = SortOrder.None;
      this.listView1.View = View.Details;

      // Add two columns (ColumnA and ColumnB)
      this.listView1.Columns.Add(new ColumnHeader());
      this.listView1.Columns[0].Width = 100;
      this.listView1.Columns[0].Text = "ColumnA";
      this.listView1.Columns.Add(new ColumnHeader());
      this.listView1.Columns[1].Width = 100;
      this.listView1.Columns[1].Text = "ColumnB";

      // Add the actual column information
      ListViewItem listViewItem1 = new ListViewItem(new String[] {"three", "banana"});
      ListViewItem listViewItem2 = new ListViewItem(new String[] {"one", "c"});
      ListViewItem listViewItem3 = new ListViewItem(new String[] {"one", "b"});
      ListViewItem listViewItem4 = new ListViewItem(new String[] {"three", "apricot"});
      this.listView1.Items.AddRange(new ListViewItem[]{listViewItem1,
                                                       listViewItem2,
                                                       listViewItem3,
                                                       listViewItem4});

      /*
         Now the actual sorting - this next line makes it sort using
         the custom comparer we've defined. Assigning a new IComparer
         automatically sorts using it.
      */
      this.listView1.ListViewItemSorter = new ListViewItemComparer();

      this.ResumeLayout(false);
    }
  }

  // Implements the manual sorting of items by columns.
  class ListViewItemComparer : IComparer
  {
    public ListViewItemComparer()
    {

    }

    // This function actually does the comparison
    public int Compare(object x, object y)
    {
      /*
         We need to access the same item multiple times, so
         save a local reference to reduce typecasting over and
         over again
      */
      ListViewItem FirstItem = (ListViewItem) x;
      ListViewItem SecondItem = (ListViewItem) y;

      /*
         Compare the two columns of each item, combined to make
         a single item for comparing.
      */
      return String.Compare(FirstItem.SubItems[0].Text + FirstItem.SubItems[1].Text,
                            SecondItem.SubItems[0].Text + SecondItem.SubItems[1].Text);
    }
  }
}

The results of running the above code (notice the items are not in the same order they were added):
Comment: Thanks, I pasted all inside "public class ListViewSortForm : Form" in my Form1. I put the "class ListViewItemComparer : IComparer" at the very end of it all. However I get an error saying "Method must have a return type". I'm a real beginner at C# so excuse me if I'm a bit slow. This is my C# project: http://spunit.tk/x/PassPlace.rar
Comment: @spunit: I re-did the sample code and added the image for you. Read the new text and the code comments carefully.
Comment: Thanks for your help. I made it now =).


Roaming Profiles & Redirected Folders - storage consumption? offline files and caching?

Question: I understand the concepts of both roaming profiles and folder redirection and have used both separately before. I am about to set up a network from scratch and would ideally like to use both for the following reasons primarily

Roaming profiles allow users to log on to any machine and have their profile
Redirected profiles allow users to have their My Documents and Desktop etc backed up without the need to log off at the end of the day. The servers can run their backups overnight and there are no missing files due to the user not logging off.
Redirected profiles largely alleviate the slow log in times caused by large profiles.

My question is if some of the folders are redirected and therefore not part of the roaming profile what happens on machines which truly roam (i.e. laptops)?
If there's offline files or a cache does this mean that the problem whereby a user has to log off comes back?
By having them both enabled, is there any duplication i.e. if I have a users$ share and a profiles$ share would I have Desktop twice for example?
Answer: I've stayed away from using redirected folders and roaming profiles.  From my experience they've caused more headaches than they have solved, especially when you add laptops into the mix.
Large profiles tend to cause a lot of extra network traffic, especially if you ever have remote sites with VPNs setup - pulling people's profiles over the VPN is painful.  I've also run into problems with some programs which store settings in the user's profile that are machine or location specific, though I can't remember exactly which programs at the moment.
My solution, which may solve some of your concerns is:

Everyone gets a network drive P:, which is configured in their AD profile to go to one of our file servers.  Since it's configured in their profile, it will follow them around to other computers.
Laptops have offline files enabled for the network drive so they can use them remotely.  In windows 7 this works very nicely and files are synced back to the file server as soon as they reconnect.  No need to logoff or anything.
Users are required to save all important company documents to the X: drive.  Since our file servers are backed up every night, our documents are safe.
Personal documents, temporary files and internet downloads are saved on the local hard drive - this saves us a LOT of storage space on the server.  I've seen quite a few users store lots of photos/music/whatever in My Documents, not realizing it's actually taking up space on our fileserver.  With this setup it's clearer to users what is stored locally and what is stored on the fileserver.
Backups work just fine even if people don't logout, since the only files in use will be documents people are actively working on (and a good backup program should be able to backup most in use files anyways).

The only downside is that users need to be trained to save things to their network drive.  I haven't found this to be much of an issue with most users.


Drupal 7 Omega responsive theme. How to disable the mobile breakpoint?

Question: I'm aware that responsive design is mobile led and what I am trying to do may not be considered responsible. However, I have an omega theme and the previous developer has (or the theme default) is poorly rendering the mobile only version.
When the site is resized to a mobile width, all the content snaps into one column. Until there is time to consult the expertise of UX and Design experts to implement this properly, I want to disable this one column layout. I want the iPhone to display the site like a normal website with pinch to zoom.
Any ideas how I can turn this break point off?
Thanks
Answer: You can switch off this via the theme settings. Just go to "Appearance" and click on the settings link next to you omega sub-theme. There in the "Grid settings" switch off the "Fluid layout".
Comment: If that does not work you can always remove the @media style for the iPhone screen resolution in the stylesheet. But try the theme setting option first before you go hacking and slashing.
Comment: @lance The grid systems is already set to "Default 960px" (not "Fluid") :/
Comment: @Cromian I've just done a search in the subtheme and the original omega theme and in the stylesheets, there are on @ media queries. Is this done with JS somehow?
Comment: @Nadine: Are you sure you unchecked the checkbox in the section "Default (960px) layout settings" / "Fluid Layout" / "Use this layout with the responsive grid"?
Comment: @Lance ahhh I see. I've unchecked that and now the site is now permanently in the one column layout, regardless of the browser size. I'm guessing this is now a problem with the CSS? It seems it could be that the correct layout is only applied to the other style sheets and not the first (global) mobile one?
Comment: @Nadine: Difficult to tell. Usually it works this way out of the box. But probably some other stylesheets or something else is doing something. Have you cleared the cache?
Answer: you can try to disable the mobile breakpoint with the breakpoint module.


Prove $4(a^2 + b^2 + c^2) + 9(abc)^2 \geq 21.$

Question: Could anyone advise me how to prove this inequality? Hints will suffice, thank you.
Let $a,b,c \in [0, \infty)$ such that $ab+bc+ ca =3.$ Prove $4(a^2 + b^2 + c^2) + 9(abc)^2 \geq 21.$
My attempt: By AM-GM inequality, $(abc)^{2}\leq 1$ and $a^2 + b^2 + c^2 \geq 3(abc)^{\frac{2}{3}}.$
Comment: How did you get $(abc)^{2}\leq 1$? :)
Comment: $1=(a b+b c+c a)/3\geq ((a b)(b c)(c a))^{1/3}=(a b c)^{2/3}$.
Comment: @Kf-Sansoo, I do not know. But I will try to use it now. So the inequality is :$ x^3 + y^3 + z^3 + 3xyz \geq xy(x+y) + xz(x+z)+ yz(y+z) ? $
Comment: And what do $p, q, r$ denote in the inequality?
Answer: If we assume the following condition (without loss of generality) $a\geq b \geq c$ then we have :
$$4(a^2+b^2+c^2)+9(abc)^2\geq 4(a^2+b^2+c^2)+9(c)^6$$
With your initial condition $ab+bc+ca=3$ the RHS of the inequality  can be rewritten as follows :
$$4((\frac{3-ab}{a+b})^2+(a+b)^2-2ab)+9(\frac{3-ab}{a+b})^6$$
Now we put $a+b=cst=x$ and remark that the inequality is minimal when $ab$ is maximal where the maximum value of $ab$ in term of $x$ is $\frac{x^2}{4}$
So we have to study this function :
$$f(x)=4((\frac{3-\frac{x^2}{4}}{x})^2+(x)^2-2\frac{x^2}{4})+9(\frac{3-\frac{x^2}{4}}{x})^6$$
But $max(a+b)=2$ so we have to study on the domain $]0;2]$ the function $f(x)$
It's clear that the function is decreasing on his domain and furthermore we have :
$$f(x)\geq f(2)\geq 21$$
So to conclude we have :
$$4(a^2+b^2+c^2)+9(abc)^2\geq 4(a^2+b^2+c^2)+9(c)^6\geq 21$$


How sqlite can be used after deleting local database file?

Question: I tried to open local database file by sqlite3. After that I delete this file or move it to another location, I still can execute SQL queries on this database.
<code>$ sqlite3 test.db
sqlite> select * from my_table limit 10;
        <10 rows>

// then I delete "test.db" file

sqlite> select * from my_table order by random() limit 10;
        <10 random rows>
</code>
So I have 2 questions?

If "test.db" is 2GB file, sqlite load it and store it in memory?
If not, how sqlite can still execute SQL queries on non-existent database?
Answer: Is not a sqlite "function", is how linux work with open files.
On Linux or Unix systems, deleting a file via rm or through a file manager application will unlink the file from the file system's directory structure; however, if the file is still open (in use by a running process) it will still be accessible to this process and will continue to occupy space on disk. Therefore such processes may need to be restarted before that file's space will be cleared up on the filesystem.
For more information:
https://access.redhat.com/solutions/2316


Graphene with SQLAlchemy results in "AssertionError: You need to pass a valid SQLAlchemy Model" with no additional information as to what is wrong

Question: I'm trying to build a FastApi app with a Postgres db and am using SQLAlchemy and Alembic (for handling DB modeling and migrations respectively). And this will be a GraphQL API, so I'm using graphene for that.
Here are my files:-
models.py
from sqlalchemy import Column, DateTime, Integer, Enum, String, Boolean, JSON
from sqlalchemy.orm import column_property, validates, relationship
from sqlalchemy.sql.schema import ForeignKey
from sqlalchemy.sql import func
from config import DEFAULT_AVATARS
from database import Base
import enum

# Status Choices for User's Membership Status
class MembershipStatusChoice(enum.Enum):
    UI = 'UNINITIALIZED'
    PE = 'PENDINIG'
    AP = 'APPROVED'
    SU = 'SUSPENDED'
# End of Status Choices

# Start of setting up Course status choices
class CourseStatusChoice(enum.Enum):
    DR = 'DRAFT'
    PU = 'PUBLISHED'
    AR = 'ARCHIVED'
# End of status choices

class AnnouncementsSeen(Base):
    __tablename__ = 'announcements_seen'
    id = Column(Integer, primary_key=True)
    user_id = relationship('User', backref='user')
    announcement_id = Column(ForeignKey('announcement.id'), index=True)

class CompletedCourses(Base):
    __tablename__ = 'completed_courses'
    id = Column(Integer, primary_key=True)
    participant_id = relationship('User', backref='user')
    course_id = Column(ForeignKey('course.id'), index=True)

class CompletedChapters(Base):
    __tablename__ = 'completed_chapters'
    id = Column(Integer, primary_key=True)
    participant_id = relationship('User', backref='user')
    chapter_id = Column(ForeignKey('chapter.id'), index=True)
    course_id = Column(ForeignKey('course.id'))
    status = Column(Enum(CourseStatusChoice))
    scored_points = Column(Integer, default=0)
    total_points = Column(Integer, default=0)
    percentage = Column(Integer, default=0)

class User(Base):
    __tablename__ = "user"
    id = Column(Integer, primary_key=True, index=True)
    firstname = Column(String(50), default="Uninitialized", nullable=False)
    lastname = Column(String(50), default="User", nullable=False)
    name = column_property(firstname + " " + lastname)
    email = Column(String(255), nullable=False, unique=True)
    avatar = Column(String(250), nullable=False, default=DEFAULT_AVATARS['USER'])
    institution_id = Column(Integer, ForeignKey('institution.id'), nullable=False)
    role = Column(String, ForeignKey('user_role.name'), nullable=True)
    title = Column(String(150), nullable=True)
    bio = Column(String(300), nullable=True)

    @validates('email')
    def validate_email(self, key, email):
        if isinstance(email, str):
            return email.lower()
        return email

    membership_status = Column(Enum(MembershipStatusChoice), nullable=False, default='SU')
    chapters = relationship('CompletedChapters', backref='completed_chapters')
    courses = relationship('CompletedCourses', backref='completed_courses')
    announcements = relationship("AnnouncementsSeen", backref='announcements_seen')
    searchField = Column(String(1000))
    active = Column(Boolean, default=True)
    created_at = Column(
        DateTime(timezone=True),
        server_default=func.now()
    )
    updated_at = Column(
        DateTime(timezone=True),
        server_default=func.now(),
        server_onupdate=func.now()
    )

class UserRole(Base):
    __tablename__ = 'user_role'
    name = Column(String(50), primary_key=True, unique=True, index=True)
    description = Column(String(500))
    priority = Column(Integer) # Lower the number higher the priority

    def default_permissions():
        return {}

    permissions = Column(JSON, default=default_permissions)
    searchField = Column(String(600))
    active = Column(Boolean, default=True)
    created_at = Column(
        DateTime(timezone=True),
        server_default=func.now()
    )
    updated_at = Column(
        DateTime(timezone=True),
        server_default=func.now(),
        server_onupdate=func.now()
    )

schemas.py
from graphene_sqlalchemy import SQLAlchemyObjectType
from pydantic import BaseModel

from models import User

class UserSchema(BaseModel):
    title: str
    content: str

class UserModel(SQLAlchemyObjectType):
    class Meta:
        model = User

main.py
import graphene
from models import User
from schemas import UserModel
from database import db_session

db = db_session.session_factory()

class Query(graphene.ObjectType):

    all_users = graphene.List(UserModel)
    user_by_id = graphene.Field(UserModel, user_id=graphene.Int(required=True))

    def resolve_all_users(self, info):
        query = UserModel.get_query(info)
        return query.all()

    def resolve_user_by_id(self, info, user_id):
        return db.query(User).filter(User.id == user_id).first()

app = FastAPI()

app.add_route("/graphql", GraphQLApp(schema=graphene.Schema(query=Query)))

I have this all in a docker. So I use these commands to make the migrations and run the app:-
    "makemigrations": "docker-compose run app alembic revision --autogenerate -m 'New Migration'",
    "migrate": "docker-compose run app alembic upgrade head",

The docker command that runs the app is uvicorn main:app --host 0.0.0.0 --port 8000 --reload
But when I make the migrations and migrate and start the app, this is what I get:-
app        | INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
app        | INFO:     Started reloader process [1] using statreload
app        | Process SpawnProcess-1:
app        | Traceback (most recent call last):
app        |   File "/usr/local/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
app        |     self.run()
app        |   File "/usr/local/lib/python3.8/multiprocessing/process.py", line 108, in run
app        |     self._target(*self._args, **self._kwargs)
app        |   File "/usr/local/lib/python3.8/site-packages/uvicorn/subprocess.py", line 76, in subprocess_started
app        |     target(sockets=sockets)
app        |   File "/usr/local/lib/python3.8/site-packages/uvicorn/server.py", line 50, in run
app        |     loop.run_until_complete(self.serve(sockets=sockets))
app        |   File "/usr/local/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
app        |     return future.result()
app        |   File "/usr/local/lib/python3.8/site-packages/uvicorn/server.py", line 57, in serve
app        |     config.load()
app        |   File "/usr/local/lib/python3.8/site-packages/uvicorn/config.py", line 318, in load
app        |     self.loaded_app = import_from_string(self.app)
app        |   File "/usr/local/lib/python3.8/site-packages/uvicorn/importer.py", line 22, in import_from_string
app        |     module = importlib.import_module(module_str)
app        |   File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module
app        |     return _bootstrap._gcd_import(name[level:], package, level)
app        |   File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
app        |   File "<frozen importlib._bootstrap>", line 991, in _find_and_load
app        |   File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
app        |   File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
app        |   File "<frozen importlib._bootstrap_external>", line 843, in exec_module
app        |   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
app        |   File "/app/api/./main.py", line 6, in <module>
app        |     from schemas import UserModel, UserSchema
app        |   File "/app/api/./schemas.py", line 12, in <module>
app        |     class UserModel(SQLAlchemyObjectType):
app        |   File "/usr/local/lib/python3.8/site-packages/graphene/utils/subclass_with_meta.py", line 52, in __init_subclass__
app        |     super_class.__init_subclass_with_meta__(**options)
app        |   File "/usr/local/lib/python3.8/site-packages/graphene_sqlalchemy/types.py", line 210, in __init_subclass_with_meta__
app        |     assert is_mapped_class(model), (
app        | AssertionError: You need to pass a valid SQLAlchemy Model in UserModel.Meta, received "<class 'models.User'>".

I found these GitHub issues that indicate that there may be silent errors that sqlalchemy is giving off that are not showing up in the stack trace. But I'm not able to use that info to precisely pinpoint what is wrong with my model configurations. I tried working out the many to many relationships there and even removing them to see if it fixes it. But it keeps showing the same error. Need help!
Answer: Hi I think the error is coming because in main.py you haven't called the meta data.
class User(SQLAlchemyObjectType):
    """
    User Connection
    """
    class Meta:
        """setting up connection for flow_details"""
        model = models.User

        # use `exclude_fields` to exclude specific fields ie "id"
        interfaces = (relay.Node,)

        # fields = "__all__"

class Query(graphene.ObjectType):
node = relay.Node.Field()
get_user=SQLAlchemyConnectionField(User.connection)

import from graphene import relay as well. You need to set a connection first. When you are calling the resolver its not getting any Sqlalchemyobject to fetch data from
Answer: I was able to solve it by commenting a relationship from class definitions like below. Seems to be issue with Class definition and relationship, next I need to look into that.
class Department(Base):
    __table_args__ = {"schema":"dbo"}
    __tablename__ = 'graphql_department_temp'
    id = Column(Text, primary_key=True)
    name = Column(Text)

class Employee(Base):
    __table_args__ = {"schema":"dbo"}
    __tablename__ = 'graphql_employee_temp'
    id = Column(Text, primary_key=True)
    name = Column(Text)
    # hired_on = Column(DateTime, default=func.now())
    department_id = Column(Text, ForeignKey('department.id'))

    # This section
    #
    # department = relationship(
        # Department,
        # backref=backref('employees',
                        # uselist=True,
                        # cascade='delete,all'))


Question about classification with hidden Markov models using depmixS4

Question: I am using the depmixS4 package to fit HMMs.
I have three different classes of data and I have fitted 3 separate HMMs using the depmixS4 depmix and fit functions and given a new sequence of observations, I would like to be able to compute the probability (or log odds) of that new observation sequence given each of the three models that have already been trained.
I understand this would normally be done using the Viterbi algorithm, but I have no idea how this can be implemented in depmixS4.
Due to the functionality of depmixS4 I cannot use the HMM or HiddenMarkov packages
Your help is greatly appreciated!
Thank you in advance
Comment: If the package is able to fit an HMM then has to be computing the probability of sequences given a model, so it's got to be in there somewhere. And the Viterbi algorithm is not what you want; that computes the most likely state path. All you need is the probability of a sequence given a model, which only requires some multiplication and summation.
Answer: You must use forward function to calculate the likelihood by sum forward's probability from first step until last one.
<code>sum(forward_prob(t))
</code>


How to preserve the epoch number with Keras when performing multiple runs?

Question: With a Keras model, I've included the TensorBoard callback to generate logs files to be visualised later.
The problem is that if I train my model multiple times, it generates multiple logs files, and the step number always restart to 0 instead of continuing on the last step of the previous run.
This leads to inexploitable graph in TensorBoard (screenshot below).
With raw Tensorflow, I've seen this could be solved by adding a "global_step" tensor to keep track of the epoch number between the runs.
But how can I do this using Keras ?
Answer: model.fit has an argument initial_epoch, 0 by default, that lets you tell the model which epoch it's starting at. You can use this to resume a previous training.


How to take square root of $x^2 + y^2 = 144$?

Question: I've to take square root of the equation. Which of the following two is correct way and why?
Taking square root of  $x^2+y^2=144$

$x + y = 12$
OR
$\sqrt{x^2+y^2} = 12$
OR
$\sqrt{x^2} + \sqrt{y^2} = 12$
Comment: Try some numbers out. Pick two numbers that sum to $12$, i.e. find $x$ and $y$ such that $x + y = 12$. Is it true that $x^2 + y^2 = 144$?
Comment: It's important to understand the difference between stating $\sqrt{x^2+y^2} = x+y$ as an **identity** vs. stating $\sqrt{x^2+y^2}=x+y$ for the **roots** $x$ and $y$. @user3452275's answer addresses this.
Answer: Because
$$(x+y)^2=x^2+2xy+y^2$$
$$x^2+2xy+y^2\neq x^2+y^2$$
$$\sqrt{x^2+2xy+y^2}\neq \sqrt{x^2+y^2}$$
$$x+y\neq \sqrt{x^2+y^2}$$
Answer: In general, the square root of a sum is not the sum of the square roots, so
$$\sqrt{x^2 + y^2} \neq x+y.$$
Answer: Just documenting here based on all the answers and comments.
It's option 3 in the question.
i.e $\sqrt{x^2} + \sqrt{y2} = 12$
Here's why :
Let's put two sample numbers to test above form, it should hold the equation true.
Sample numbers : 10 and 2. Notice sum of these two numbers is 12.
Putting values in our equation:
$\sqrt{10^2} + \sqrt{2^2} = \sqrt{144}$
$\sqrt{100} + \sqrt{4}$ = 12
10 + 2 = 12
12 = 12
Other two forms mentioned in the question won't hold this test, hence are invalid.


Can I just have a color coded HTML editor in Drupal 6 that keeps line indentations?

Question: I'm trying to get out some minimally designed pages. The WYSIWYG (CKEditor) has a habit of collapsing the code between saves. WHile this is fine and all, I'm finding myself copying copy and pasting it into sublime text in order to reformat. The copy-pasting -- while not difficult -- is thumbing me up a bit. I've copied/pasted the wrong code and had to redo a lot of my work.
So can I have stop CKEditor from minimizing the HTML code? This is a legacy site in Drupal 6.28.
Answer: Well I got myself halfway there and without the need to download an additional module, library, or plugin. By checking Apply source formatting and Preformatted, the Disabled Rich Text rendition shows code indented with some of the white spacing preserved.
You can find these settings in D6 via admin/settings/wysiwyg


Knockout.Js Array filter syntax

Question: Just getting into javascript and knockout.js. I've found a bunch of examples of what I'm trying to accomplish. And I feel like there is a small syntax error I may be overlooking. I'm trying to filter a set already returned (this.tasks) from a server via ajax/json. I have that working fine. What I would like to do, is have users be able to switch between complete and incomplete tasks.
I switched the code to just run the foreach loop on tasksFiltered. "this.done" is either true or false.
Task template
var taskModel = function(id, title, description, done){
    var self = this;
    this.id = ko.observable(id);
    this.title = ko.observable(title);
    this.description = ko.observable(description);
    this.done = ko.observable(done);

    this.showEdit = ko.observable(false);
    this.titleUpdate = ko.observable(false);
    this.descriptionUpdate = ko.observable(false);
};

Page Model
var pageModelTasks = function(){
    var self = this;
    this.task_title = ko.observable("");
    this.task_description = ko.observable("");
        this.task_title_focus = ko.observable(true);
    this.tasks = ko.observableArray([]);

    this.tasksFiltered = ko.computed(function() {
        return ko.utils.arrayFilter(this.tasks, function(Task) {
        return Task.done == true;
      });
    });

   // CRUD functions excluded
};

this doesn't work.
Answer: Two minor corrections to your code. First, as @XGreen mentioned, you need to pass the array value, not the observableArray instance, as the first parameter of the arrayFilter function. Lastly, because Task.done is observable, you need to invoke the member to get the value. Here's the modified code:
this.tasksFiltered = ko.computed(function() {
    return ko.utils.arrayFilter(this.tasks(), function(Task) {
        return Task.done() === true;
    });
});

Comment: You're missing the "this" arg into the computed, or use "self.tasks()" instead of "this.tasks()"
Answer: The second solution has a problem with the method ko.utils.stringStartsWith.
ko.utils.stringStartsWith missing in release file.
You can use this code:
  var stringStartsWith = function (string, startsWith) {
        string = string || "";
        if (startsWith.length > string.length)
            return false;
        return string.substring(0, startsWith.length) === startsWith;
    };

See Issue Link
Answer: It might help you
if (myList().length > 0) {
    var text= this.filter().toLowerCase();
    return ko.utils.arrayFilter(myList(), function (item) {
                if (item.Label.toLowerCase().indexOf(text) > -1 || item.Desc.toLowerCase().indexOf(text) > -1) {
                    return true;
                 }
                 else {
                     return false;
                 }
          });
}

Comment: show where this.filter is defined in original poster's code

Knockout.Js Array filter syntax


Codeigniter set constants in custom library

Question: I am using codeigniter for a project. I have a custom library in which there are constants in which I will use in my custom functions in the library. How do I declare such constants?
Comment: declare constants in the application/config/constants.php. That's where it has to be.
Answer: If you are going to use that constants only in your library, you must declare it inside of your class:
<?php
class my_class {
    const MY_CONSTANT = 10;

And then call it with:
self::MY_CONSTANT

If you need that your constants are available in the rest of the application, you must declare it in your application/config/constants.php file
Answer: Access the constant in library as this way. It works.
 $this->load->library('library_name');
 echo library_name::MY_CONSTANT;

Answer: You should declare constants on config/constants.php as follows:
class MyConstantsClass {

    public static function get_timezones_list() {
        return array(
            "-12" => "(GMT -12:00) Eniwetok, Kwajalein",
            "-11" => "(GMT -11:00) Midway Island, Samoa",
            "-10" => "(GMT -10:00) Hawaii",
            "-9" => "(GMT -9:00) Alaska",
            "-8" => "(GMT -8:00) Pacific Time (US & Canada)",
            "-7" => "(GMT -7:00) Mountain Time (US & Canada)",
            "-6" => "(GMT -6:00) Central Time (US & Canada), Mexico City",
            "-5" => "(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima",
            "-4" => "(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz",
            "-3.5" => "(GMT -3:30) Newfoundland",
            "-3" => "(GMT -3:00) Brazil, Buenos Aires, Georgetown",
            "-2" => "(GMT -2:00) Mid-Atlantic",
            "-1" => "(GMT -1:00) Azores, Cape Verde Islands",
            "0" => "(GMT) Western Europe Time, London, Lisbon, Casablanca",
            "1" => "(GMT +1:00) Brussels, Copenhagen, Madrid, Paris",
            "2" => "(GMT +2:00) Kaliningrad, South Africa",
            "3" => "(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg",
            "3.5" => "(GMT +3:30) Tehran",
            "4" => "(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi",
            "4.5" => "(GMT +4:30) Kabul",
            "5" => "(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent",
            "5.5" => "(GMT +5:30) Bombay, Calcutta, Madras, New Delhi",
            "6" => "(GMT +6:00) Almaty, Dhaka, Colombo",
            "7" => "(GMT +7:00) Bangkok, Hanoi, Jakarta",
            "8" => "(GMT +8:00) Beijing, Perth, Singapore, Hong Kong",
            "9" => "(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk",
            "9.5" => "(GMT +9:30) Adelaide, Darwin",
            "10" => "(GMT +10:00) Eastern Australia, Guam, Vladivostok",
            "11" => "(GMT +11:00) Magadan, Solomon Islands, New Caledonia",
            "12" => "(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka"
        );
    }

    public static function get_codes() {
        return array();
    }

   // .... and so on....

}

Then inside your custom library :
class MyLibraryClass {

    private $timezones;

    public function __construct(){
        $this->CI =& get_instance(); //in case you need it
        $this->timezones = MyConstantsClass::get_timezones_list();
    }

    //do whatever you want with your constants
    echo $current_timezone = $this->timezones['-5']; //print (GMT -5:00) Eastern Time (US & Canada), Bogota, Lima

}

Answer: Generally Codeigniter constants should be inside config/constants.php. Then only we can access all the constants in the entire application.
Answer: You can create your own constants file and just include it in your library:
config/myconstants.php
In your library,
include(APPPATH. 'config/myconstants.php');


A hyperbolic solution to this differential equation

Question: I have the following differential equation: $$\Big(\frac{dy}{dx}\Big)^2=\frac{y^2-A^2}{A^2}.$$ I am looking to obtain a solution $$y(x)=A\cosh\Big({\frac{x+B}{A}}\Big),$$ where B and A are constants.
I have tried square-rooting and Taylor expanding, substitution of an integral but am getting nowhere.
Sorry if this is an inappropriate homework question but it has been annoying me for too long today...
Answer: Hint:
$$\dfrac{dy}{\sqrt{y^2-A^2}}=\pm\dfrac{dx}{A}$$
The only thing you need to do is to find the integral of the expression on the left side.
Comment: left hand side?
Answer: The way to test whether something is a solution of a differential equation is to substitute it in to the differential equation and check that both sides simplify to the same thing.


Matrix and its condition number

Question: This example is given in Higham [2002], and is provided without explanation. I am not sure how the condition number of the matrix is just 5. How can you directly calculate the condition number of a matrix with epsilon? I know that cond(A) = $\left\Vert |A^{-1}||A| \right\Vert_{\inf}$, but I'm not sure how that helps here.
I calculated $A^{-1} = \{(1, -1/\epsilon, 1),(0, 1/\epsilon, -1), (0, 0, 1)\}$
Example
Comment: @copper.hat Higham [2002, pg144] _Accuracy and Stability of Numerical Algorithms_
Comment: Please include in your question what you have tried. eg have you computed $A^{-1}$ (in terms of $\epsilon$)?
Comment: Did you compute $A^{-1}$?
Comment: I get $\operatorname{cond}_\infty T = \max(3,{2 \over |\epsilon|}) \max (2, 2 |\epsilon|)$, $\operatorname{cond}_\infty T^T = (1+|\epsilon|)\max(2,{2 \over |\epsilon|} )$.
Comment: @copper.hat What method did you use to calculate the condition number of T?
Comment: $\|T\|_\infty \|T^{-1}\|_\infty$.
Comment: So can we not reproduce cond(T) = 5?
Comment: I made some computational mistakes above, but, regardless of norm chosen, the condition number of $T$ (and $T^T$) varies as ${1 \over \epsilon}$ for small $\epsilon$. (This is because all norms are equivalent.)
Comment: Note that $\|A\|_\infty$ is just the $\max$ row sum (of the absolute values), so is easy to compute.
Comment: +1 Is $\left\Vert |T^{-1}||T| \right\Vert_{\inf}$ the same thing as $\left\Vert T \right\Vert_{\inf} \left\Vert T^{-1} \right\Vert_{\inf}$ ?
Comment: No, I presumed that was a typo., since we're talking about condition number. Usually, $\operatorname{cond} A = \|A\| \|A^{-1}\|$. However, I am frequently mistaken :-).
Comment: Do you have a more detailed description of Higham's paper, he seems to be a prolific lad, so a search turns up more than I am willing to troll through.
Comment: The condition number that Higham uses in that section is the one you have in the question which is different than the condition number one typically uses in the context of matrices. If you compute $|T^{-1}| |T|$ and take the $ \infty$ induced norm, then the result is $5$, as above.
Answer: $|T| = \begin{bmatrix} 1 & 1 & 0 \\
0 & |\epsilon| & |\epsilon| \\
0 & 0 & 1 \end{bmatrix} $
$|T^{-1}| = \begin{bmatrix} 1 & {1 \over |\epsilon|} & 1 \\
0 & {1 \over |\epsilon|} & 1 \\
0 & 0 & 1\end{bmatrix}$
$|T||T^{-1}| = \begin{bmatrix} 1 & 2 & 2 \\
0 & 1 & 2 \\
0 & 0 & 1
\end{bmatrix}$
$\| |T||T^{-1}| \|_\infty = 5$.

Matrix and its condition number


Proof verification: $\ 2^{n-1} \leq n! $

Question: Prove $\ 2^{n-1} \leq n! $ for all $\ n \in \mathbb{N}. $ I think I completed the proof correctly, but mine is different from the textbook solution. Would the following prove the statement adequately? Thank you.
Let $\ P(n) = 2^{n-1} \leq n! $ for all $\ n \in \mathbb{N} $
$\ P(1) = 2^{0} \leq 1 $ is true.
Let $\ P(m) = 2^{m-1} \leq m! $ for all $\ m \in \mathbb{N} $
Suppose $\ P(m) $ is true.
$\ P(m+1) = 2^{m-1+1} \leq (m+1)! $
$\ = 2^{m} \leq (m+1)! $
$\ = 2^{m-1} \cdot 2 \leq (m+1) \cdot m! $
Because we are assuming $\ 2^{m-1} \leq m! $ is true, the inequality depends on $\ 2 \leq m+1. $
$\ 2 \leq m+1 = 1 \leq m, $ which is true for all $\ m \in \mathbb{N}. $
Thus, $\ P(m) $ holds for $\ P(m+1). $
By induction, $\ P(n) $ holds for all $\ n \in \mathbb{N}. $
Comment: The way you wrote the step $P\left(m+1\right)$ holds assuming $P\left(m\right)$ is true is awkward for me. I feel like you should write in this order to be clearer : 1. We assume $2^{m-1} \leq m!$, 2. Then you show you can deduce $2^{m} \leq \left(m+1\right)!$ and you conclude.
Comment: Welcome to Math S.E.  I would write $2\le m+1\color{red}\iff 1\le m$, etc.; otherwise it looks like $m+1=1$
Comment: Your definition of $P(n)$ is for a single $n$, not all $n$. Also, you don't need to redefine it for m. Also, using equals for truth values can be confusing.
Comment: Lastly, it's better to write out how $P(m) $implies $P(m+1)$ in that order.  Think backwards (what you want to what you have), write your proofs forwards (what you have to what you want).
Comment: Consider using something other than "=" when talking about the definition of a predicate. It may seem pedantic, but you currently have statements like $P(1) = 2^0 \leq 1$, which seems to suggest the nonsensical statement "$P(1) \leq 1$". Better would be to write out "$P(1)$ is defined to be the statement $2^0 \leq 1$".
Comment: I know that the question asks for the induction proof, but for your information, the inequality can be rewritten as $$1 \times 2 \times ... \times 2 \leq 1 \times 2 \times 3 \times ... \times n$$ (each product containing $n$ factors), and hence is immediately true without induction.
Comment: The symbol  sometimes means the set of positive integers, and sometimes means the set of nonnegative integers. Which do you mean here?
Answer: Yes, your idea is correct but write it properly. Firstly, $2^{0} \leqslant 1!$. Now, suppose, $2^{n-1} \leqslant n!$ for some $n \geqslant 1$. Then, $2^{n} = 2.2^{n-1} \leqslant (n+1).n! = (n+1)!$. Hence, $2^{n-1} \leqslant n!$ for all $n \geqslant 1$ follows from induction principle.


A Gaussian non-linear regression model. What does it mean, and how can I simulate it?

Question: In Confidence regions when the Fisher information is zero - Matteo Bottai (2003) the effect of a singular information matrix on the confidence regions from statistical tests is getting looked at.
In the paper Bottai describes some models he uses to perform simulations. I would like to duplicate these simulations but I get stuck on how to generate the data. He says:

Model 1: Gaussian nonlinear regression. The data consist of $n$ independent observations $Y_i=(X_i,Z_i)$ of a bivariate vector $Y = (X, Z)$, with density:
  $$f(y) = f(x)f(z | x)$$
  where $f(x)$ is fixed and known and $$f(z|x) = \phi(z-e^{\theta x}+\theta x)$$ where $\theta$ is unknown and lies in some open interval and $\phi(\cdot)$ denotes the density of a standard normal variable.

A bit further he denotes:

Figure 2 shows typical loglikelihoods obtained by pseudorandomly generating four samples from Model 1, where $n = 10000$, $\theta =0$ and $X$ is generated from a $Un(- 1, 2)$ distribution. Note that, despite the large sample size, two of the loglikelihood functions are bimodal.

Generating uniformly distributed data is no problem in R. But how can I generate this $Y$ (or the $Z_i$).
Also, I guess $f(x)$ can be chosen at random? Would something like $f(x) = \phi(x)$ be valid?
Comment: You have not correctly transcribed the model. Please fix the question
Answer:
Note that you said $Y=(X,Z)$, so as soon as you have pairs of $X$ and $Z$ values, you have your $Y$ simply by putting them together.
You already have $X$ values, since they were drawn from a uniform.
note that $f(z|x) = \phi(z-\mu(x))$ specifies a normal density with mean $\mu(x)$ and standard deviation $1$.
As a result you proceed as follows (after you specify your $\theta$), repeating many times:
a. generate $X_i$ as you already have it (i.e. from a uniform); denote the observed generated value as $x_i$.
b. generate $Z_i\sim N(\mu(x_i),1)$, call the observed generated value $z_i$.
c. call the pair $(x_i,z_i)$ "$y_i$".

Also, I guess $f(x)$ can be chosen at random? Would something like $f(x) = \phi(x)$ be valid?

No, for the example $f(x)$ was specified to be uniform just above.


Página de Login

Question: Estou aprendendo angular.
Estou usando o angular 6
Estou tentando fazer a página de login do Admin LTE
Importei esses arquivos no angular.json
"styles": [
          "node_modules/admin-lte/bower_components/bootstrap/dist/css/bootstrap.min.css",
          "node_modules/admin-lte/bower_components/font-awesome/css/font-awesome.min.css",
          "node_modules/admin-lte/bower_components/Ionicons/css/ionicons.min.css",
          "node_modules/admin-lte/bower_components/jvectormap/jquery-jvectormap.css",
          "node_modules/admin-lte/dist/css/AdminLTE.min.css",
          "node_modules/admin-lte/dist/css/skins/_all-skins.min.css",
          "node_modules/admin-lte/plugins/iCheck/square/blue.css",
          "src/styles.css"
        ],
        "scripts": [
          "node_modules/admin-lte/bower_components/jquery/dist/jquery.min.js",
          "node_modules/admin-lte/bower_components/jquery-ui/jquery-ui.min.js",
          "node_modules/bootstrap/dist/js/bootstrap.min.js",
          "node_modules/admin-lte/dist/js/adminlte.min.js",
          "node_modules/admin-lte/bower_components/fastclick/lib/fastclick.js",
          "node_modules/admin-lte/bower_components/jquery-slimscroll/jquery.slimscroll.min.js",
          "node_modules/admin-lte/plugins/iCheck/icheck.min.js"
        ]

Mas a área cinza do fundo não está funcionando em toda a página e parece que nem o bootstrap está funcionando, enquanto que esta mesma importação funciona para a página em geral, mas quero deixar o login bem formatado, assim como é no original
Esta é a minha configuração

O cinza ficou na metade da página
E esse é o original

Tudo bem formatado
E esse é o código que inseri login.component.html

    AdminLTE

Sign in to start your session

    <form action="../../index2.html" method="post">

        <input type="email" class="form-control" placeholder="Email">

        <input type="password" class="form-control" placeholder="Password">

              <input type="checkbox"> Remember Me

          <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>

    </form>

- OR -

       Sign in using
        Facebook
       Sign in using
        Google+

    I forgot my password

    Register a new membership

Aqui está o projeto
Aqui tem a pergunta
Aqui está o stackblitz
Comment: Tenta criar um stackblitz com seu código, vai ser difícil alguém conseguir responder sem conseguir inspecionar o dom.
Comment: como faço pra enviar meu projeto pra la?
Comment: Cria um novo projeto angular la e copia o minimo possível pra reproduzir seu problema.
Comment: Estou tentando e não estou conseguindo
Comment: Acho que consegui mais ou menos.. [Aqui](https://stackblitz.com/edit/angular-7w545n)
Comment: Nao entendi qual o problema? O que esta errado no stackBlitz?
Comment: Não está formatando corretamente, creio que ele não esteja detectando o bootstrap
Comment: Dá uma olhada [aqui](https://adminlte.io/themes/AdminLTE/pages/examples/login.html) e outra, lá mostrou o background normal, mas no meu, aquela cor de background vai só até metade da página
Comment: Aqui para mim no Stack Blitz está normal http://prntscr.com/kixuh9
Comment: Só no meu projeto está ficando [assim](https://github.com/cbcarlos07/adminlte/issues/1)
Comment: @adventistaam tente outro navegadores e compare o código com o original do Admin LTE.
Comment: Sim eu testei. Estão do mesmo jeito
Comment: Sem simular o erro fica meio complicado de entender o por que do erro, tente inspecionar os elementos e verificar o motivo de estar quebrando.
Comment: No stackblitz não está pegando as fontes de redes sociais... nem formatando o checkbox pelo que eu percebi
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/81707/discussion-between-paulo-henrique-and-adventistaam).
Answer: Eu tinha este mesmo problema no AdminLTE, por alguma razão o tamanho da div login-box não está indo até o final do navegador. Eu apenas troquei o elemento body do index.html para isso:

Edit: sua cor é a default, eu tinha clareado um pouco mais o fundo.

Página de Login


How to add the Tawk chat widget script to nextjs react app

Question: I'm trying to figure out how to add a chat widget from Tawk to a next.js react app.
In my _app.js, I have added the script import tag and tried to set the widget as follows:
import Script from 'next/script'

      {/*  */}

When I try this, I get an error that says:

Unhandled Runtime Error SyntaxError: Unexpected identifier
Call Stack loadScript ../../node_modules/next/dist/client/script.js
(148:18) eval ../../node_modules/next/dist/client/script.js (167:62)

I contacted the tawk dev support team, who acknowledged an issue with react, and suggested that a fix had been pushed with a new version 2.0.1 heres the link
https://email@example.com/tawk-messenger-react
When I try that both in _app.tsx and _document.tsx, I get more than 10 errors with that package.
Has anyone figured out how to use tawk in a next.js react app?
Comment: for others that might be facing the same issue, I spoke to the tawk dev support. They have identified an issue with react and are working on a solution. I will update this post to share the solution when one is available.
Answer: I made a working project with a real Tawk.to account:
https://codesandbox.io/s/tawk-test-ovmsqy?file=/pages/_app.js
You should change the ids at s1.src line!
import Script from "next/script";

function MyApp({ Component, pageProps }) {
  return (
    <>
      <Component {...pageProps} />

    </>
  );
}

export default MyApp;

Answer: The problem is that dangerouslySetInnerHTML is outside the tag you have it like this:

    </>
  );
}

export default MyApp;

Comment: I tried this. It doesn't produce an error, but it also doesnt display the widget.
Comment: Sure I guess you didn't replace this : ` s1.src='https://embed.tawk.to/[]/[]'; `  by the url of your account. Where the `[ ]` go, goes the info that associates the widget to your tawk account.
Comment: I did- I just removed those strings for this post
Comment: the url should be like: https://embed.tawk.to/12345678/default
Comment: the tawk app does not use the word default - it uses random strings for both ids. Are you saying I'm supposed to substitute the second string for the word "default"?
Comment: I tried replacing the second string with default and a tawk error is returned in the console that says 'connection refused'
Comment: I also tried adding the two random string id I get from tawk, in the script, in _document.tsx - and I still dont get the widget to load.
Comment: try this url https://embed.tawk.to/56d59cac343e11f1034e44dc/default. I extracted it from: https://stackoverflow.com/questions/35725713/live-chat-jquery-plugin-tawk-to-not-visible I tested it in next and with this url you will see that the widget appears. That means your url is wrong.
Comment: When I copy the url direct from the tawk widget script or the id fields in the tawk chat dash page, I do not get the console error - but the widget does not display. Both of those sources use two separate strings for id fields. When I try replacing the second id field with the word 'default', I get a connection refused error in the console.
Answer: you should be able to create a twik.js file in the public folder and load it with next/script without any issues
Comment: I am asking this question because of the issues I'm having.
Comment: @Mel ye just create a twik.js file with the contents to init the twik chat widget after that you can use next/script with the property src pointing to /twik.js on Script
Answer: For cleaner approach you can use @tawk.to/tawk-messenger-react at NPM


Navegação Em Abas Com CSS E jQuery

Question: Estou com um problema na formatação da minha página...

Empreendimento

Detalhes

Fotos

Localização

Título

info

Título

info

Título

info

Meu conteúdo está ficando fora das abas...
CSS:
ul{list-style:none; padding-left:10px;}

.abas li{float:left; border:1px solid #ccc; border-bottom:0; margin-right:10px; padding:10px; border-top-left-radius:5px; border-top-right-radius:5px; -moz-border-radius-topleft:5px; -moz-border-radius-topright:5px; -webkit-border-radius-topleft:5px; -webkit-border-radius-topright:5px; }

.abas li:hover{box-shadow:0 -2px 3px #DFDFDF; -moz-box-shadow:0 -2px 3px #DFDFDF; -webkit-box-shadow:0 -2px 3px #DFDFDF; font-weight:bold; border-color:#c0c0c0;}

.ativo{background:#ccc; border-color:#333;}

.ativo a{color:#fff; font-weight:bold; text-shadow:0 0 5px #999;}

#noticia{position:relative; width:880px; height:auto; padding:10px; clear:both; border:1px solid #ccc; -moz-box-shadow:0 -1px 3px #ccc;}

#noticia div{display:none;}

.credito{font-size:1.1em; position:absolute; right:0; bottom:-40px; margin-top:15px;}

.credito a{font-size:1.1em;}

Comment: Eu acho que tem a haver com `margin:5px 0 0 -470px`
Comment: Posta um print do problema na pagina, fica melhor pra entender
Answer: Provavelmente você não está carregando o jQuery para essa página.
O problema que eu vejo é que false() não é uma função, ou seja, não tem os parênteses. Remova eles do seu return.
De return false(); para return false;
Testei seu código aqui, e aparentemente está funcionando. Veja o seu código funcionando abaixo:

$(function() {
  $('#conteudo').hide();
  var noticia;
  var hash = window.location.hash;
  if (hash != '') {
    noticia = $(hash).html();
    $('.abas li a[href="' + hash + '"]').parent().addClass('ativo');
  } else {
    noticia = $('#conteudo div:first-child').html();
    $('.abas li:first-child').addClass('ativo');
  }
  $('#noticia').append('
' + noticia + '
').find('div').slideDown();
  $('.abas li a').click(function() {
    $('.abas li').removeClass('ativo');
    $(this).parent().addClass('ativo');
    var ancora = $(this).attr('href');
    var nome = ancora.substr(1, ancora.length);
    noticia = $('#conteudo div[id="' + nome + '"]').html();
    $('#noticia').empty();
    $('#noticia').append('
' + noticia + '
').find('div').slideDown();
    return false;
  })
})
ul {
  list-style: none;
  padding-left: 10px;
}
.abas li {
  float: left;
  border: 1px solid #ccc;
  border-bottom: 0;
  margin-right: 10px;
  padding: 10px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-topright: 5px;
  -webkit-border-radius-topleft: 5px;
  -webkit-border-radius-topright: 5px;
}
.abas li:hover {
  box-shadow: 0 -2px 3px #DFDFDF;
  -moz-box-shadow: 0 -2px 3px #DFDFDF;
  -webkit-box-shadow: 0 -2px 3px #DFDFDF;
  font-weight: bold;
  border-color: #c0c0c0;
}
.ativo {
  background: #ccc;
  border-color: #333;
}
.ativo a {
  color: #fff;
  font-weight: bold;
  text-shadow: 0 0 5px #999;
}
#noticia {
  position: relative;
  width: 880px;
  height: auto;
  padding: 10px;
  clear: both;
  border: 1px solid #ccc;
  -moz-box-shadow: 0 -1px 3px #ccc;
}
#noticia div {
  display: none;
}
.credito {
  font-size: 1.1em;
  position: absolute;
  right: 0;
  bottom: -40px;
  margin-top: 15px;
}
.credito a {
  font-size: 1.1em;
}

Empreendimento

Detalhes

Fotos

Localização

Empreendimento

info

Detalhes

info

Fotos

info

Localização

info

Veja agora um exemplo sem jQuery carregado, e veja se está igual ao seu modelo:

$(function() {
  $('#conteudo').hide();
  var noticia;
  var hash = window.location.hash;
  if (hash != '') {
    noticia = $(hash).html();
    $('.abas li a[href="' + hash + '"]').parent().addClass('ativo');
  } else {
    noticia = $('#conteudo div:first-child').html();
    $('.abas li:first-child').addClass('ativo');
  }
  $('#noticia').append('
' + noticia + '
').find('div').slideDown();
  $('.abas li a').click(function() {
    $('.abas li').removeClass('ativo');
    $(this).parent().addClass('ativo');
    var ancora = $(this).attr('href');
    var nome = ancora.substr(1, ancora.length);
    noticia = $('#conteudo div[id="' + nome + '"]').html();
    $('#noticia').empty();
    $('#noticia').append('
' + noticia + '
').find('div').slideDown();
    return false;
  })
})
ul {
  list-style: none;
  padding-left: 10px;
}
.abas li {
  float: left;
  border: 1px solid #ccc;
  border-bottom: 0;
  margin-right: 10px;
  padding: 10px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-topright: 5px;
  -webkit-border-radius-topleft: 5px;
  -webkit-border-radius-topright: 5px;
}
.abas li:hover {
  box-shadow: 0 -2px 3px #DFDFDF;
  -moz-box-shadow: 0 -2px 3px #DFDFDF;
  -webkit-box-shadow: 0 -2px 3px #DFDFDF;
  font-weight: bold;
  border-color: #c0c0c0;
}
.ativo {
  background: #ccc;
  border-color: #333;
}
.ativo a {
  color: #fff;
  font-weight: bold;
  text-shadow: 0 0 5px #999;
}
#noticia {
  position: relative;
  width: 880px;
  height: auto;
  padding: 10px;
  clear: both;
  border: 1px solid #ccc;
  -moz-box-shadow: 0 -1px 3px #ccc;
}
#noticia div {
  display: none;
}
.credito {
  font-size: 1.1em;
  position: absolute;
  right: 0;
  bottom: -40px;
  margin-top: 15px;
}
.credito a {
  font-size: 1.1em;
}

Empreendimento

Detalhes

Fotos

Localização

Empreendimento

info

Detalhes

info

Fotos

info

Localização

info

Exemplo funcional no JSFiddle.

Navegação Em Abas Com CSS E jQuery


uidialog sending the form multiple times

Question: I have a jquery ui dialog with custom buttons that the first time sends the data fine, but when I click again on a newly opened dialog it sends twice, then three times and so on (without page reload). If I reload the page it works fine, but why? This is how my function looks:
function openPopup() {
     $('#box').dialog({
         autoOpen: true,
         modal   : true,
         title   : 'my title',
         width   : 500,
         open : function (event) {
            var dialog = $(this);
            $(".buttonclass").live('click', function(event) {
                dialog.dialog('destroy');
                alert('hello'); //This alerts hello once first time, twice second time, etc.
            });
         },
         buttons : [
             {
                 text: 'Cancel',
                 click: function() {
                    $(this).dialog("destroy");
                 }
             }
         ]
     });
    }

What am I missing? I have been looking around and found stuff like click unbinding, dialog destroying, but none of those are working (as you can see i am destroying my dialog).
Answer: The solution is to use unbind before creating the click event. This is how the open part above should look like:
open : function (event) {
      var dialog = $(this);
      $(".buttonclass").unbind('click').click(function(event) {
           dialog.dialog('destroy');
           alert('hello'); //This alerts hello once always now.
      });
},

That way, no extra clicks are binded to the button, and the form only sends once.


use statement not working in AppleScript

Question: I am creating my first AppleScript library in a script file, and would like to use the handlers in that file using the use statement (I followed these instructions). So I tried:
use script "My Library"

create_new_track(10, 2, 2)

Inside my "My Library.scpt" file, there is a handler called "create_new_track".
But when I try to call it after the use statement, I get this error:
error "«script» doesn't understand the "create_new_track" message." number -1708 from «script»

With the following snippet, I get get the handler to run though:
tell script "My Library"
    create_new_track(10, 2, 2)
end tell

I would rather be able to avoid numerous tell blocks in my script, though. Anyone got an idea what went wrong?
Answer: Unfortunately, you're assuming AppleScript's library system was designed by a competent engineer. This is not so: like almost everything the current AppleScript team spews out, it's the software version of a clown car: totally unpredictable, dangerously unsafe, and the moment you think you've finally figured out correctly how it works, all the doors fly off and dozens of lunatic clowns leap out and pelt you with unspeakable substances.
Anyway, to try and explain the insanity best I can...
The use statement injects dictionary-defined keywords into your global namespace. This in itself is an insane thing to do, considering that AppleScript is already notorious for creating terminology clashes between language, application, and scripting addition dictionaries.
However, the use statement does not inject user-defined identifiers (e.g. your create_new_track identifier). Which is somewhat ironic, given that user-defined identifiers are far, far safer to mix than arbitrary keywords, and it would make ObjC frameworks vastly less annoying to use (I mean, what on Earth possessed them to think current application's NSWhatever... is good syntax?!?!!).
While AppleScript does have problems binding static variable names correctly, handler names are always dynamically bound so user-defined command names normally work without problem (the message just passes up the object delegate chain until it's handled or a "handler not found" error occurs). However, the use mechanism doesn't use standard AppleScript delegation (not that it was intended for this kind of use anyway), but instead appears to rely on a global lookup table of known keywords to intercept messages with keyword-based names and redirect those messages to whatever object originally defined that keyword. But since your create_new_track message doesn't have a keyword based name, this "redirect" hack completely ignores it; an AppleScript Apartheid, if you will.
Therefore, if you want to refer to properties and handlers that have user-defined names within a script library, you must use a reference, e.g. create_new_track() of script "MyLibrary". This is actually a Good Thing, and brings the whole mess as near to "simple, predictable, and safe" as it ever gets, because it leaves all your scripts' namespaces intact and doesn't inject any more potentially conflicting keywords into AppleScript's global namespace.
If you're using a library repeatedly, then writing ...of script "MyLibrary" does get tedious. While you could use a tell script "MyLibrary"...end tell block to wrap multiple commands, excessive use of tell blocks is another easy way to create total confusion since they specify the default target for all commands within the block, not just the ones you actually want sent to that object. The best solution is to use a property statement at the top of your script to bind the script... specifier to a nice, neat identifier, which you can then use throughout the rest of the script whenever you need to send a command to that library:
property mylib : script "My Library"

...

mylib's do_this()

mylib's do_that()

etc.

Use this approach, and you'll avoid a ton of pain. Try to be "clever", and it'll almost invariably bite you in the ass. Mastering the AppleScript language has always been as much about learning its many defects and how to work around them as in actually learning to code. It's just unfortunate that the current AS team is so devoted to indulging its own pathological cleverness that this becomes harder, not easier, year after year. (I expect AS to surpass C++ eventually, assuming the rest Apple doesn't just put a bullet in it first - something as a 15-year AS veteran I increasingly wish they'd do before it strangles user scripting and automation completely.)
Comment: Thanks a lot for your explanation. To tell you the truth, I have actually liked the use clause a lot, compared to the previous state, (I actually wrote a library server, that let one call handlers from a stay open applet. :). I'll certainly read through your post thoroughly, and will probably adapt your way of doing stuff as a new usage pattern. Your way also fits well with store script and load script I guess. (But I'll try it out.)
Comment: I think what foo meant is the dirty hack of having an sdef file in script libraries. Developers who are not aware of the vulnerabilities, like global namespace pollution but also apple event code pollution (something that is hardly mentioned by Apple), makes sharing libraries impossible. To avoid all of that you stick with user defined names instead of enumerated/keyed names. In short, AppleScript is "safer" when you address your objects in a verbose way instead of putting everything in the global namespace.
Comment: Not impossible, but it greatly increases the likelihood of scripts going wrong in bizarre and unpredictable ways. The `global` and `use` statements are both fundamentally evil because they totally destroy script object encapsulation and so should never be used with or in libraries. The whole point of library-based construction is to manage complexity and avoid chaos, not create it, otherwise it's actually simpler and safer sticking to copy-and-paste. The _only_ time the `use` statement is safe to use (and also unavoidable) is when importing ObjC frameworks and, in turn, scripting additions.
Answer: Pointing out some useful information… If you choose the route of using a property to define a script library to be able to call handlers and script objects to be used in other scripts, it is important to keep in mind that, if any changes are made to your script library file… and is recompiled and saved, those changes will not carry over to the scripts you have created, which call script objects and handlers from your library file.  In short, you will need to open and recompile and save every single script created which calls on script objects and handlers from your library file.  This can become a nightmare if you have dozens or even hundreds of scripts.
Using this following example from one of the other answers…   the script library gets stored at compile time and will retain its value until the script is recompiled. Any updates or changes to the original library file will not be reflected in the scripts calling on them until those scripts are recompiled and saved as well
property mylib : script "My Library"

...

mylib's do_this()

mylib's do_that()

etc.

In my opinion a more favorable option would be to load the script library at run time.  This way, any script which depends on that library file, will automatically be updated when it is run… after the script library file has been altered and saved.
This is the code that I use to load libraries at runtime
property myLib : missing value
property theLibrary : missing value

on loadLibraries()
    set theLibrary to (path to home folder as text) & "Library:Script Libraries:My Library.scpt"
    set myLib to load script alias theLibrary
end loadLibraries

loadLibraries()

myLib's do_this()
myLib's do_that()

Comment: This is a lifesaver. Thank you. I'd had the comical workflow of "copy all my code over into a new Script Editor window each time I make a change to my library", and this lets my code reliably use the most up-to-date version of my library.
Answer: I think I'd try:
 use mylib : script "My Library"
 mylib's create_new_track(10, 2, 2)

If I have got it right, you can only use use statements as you have done above, in order to use the terminology from an app. -But I may have gotten that wrong.
Comment: I'd strongly recommend using `property :`, _not_ `use :`. The latter is fundamentally brain-damaged: while binds the identifier to the specifier as you'd expect, it _simultaneously_ imports the specified object's entire contents into your script, which you totally don't. (If you'd wanted your global namespace polluted, you wouldn't have bound it to an identifier in the first place.)
Comment: I actually haven't tried that, I guess you mean for instance: `property matrix : script "Matrix"`?
Comment: @McUsr The solution you proposed worked for me, thanks! So do I understand this right: For my original code to work, I need to have a "Library with Terminology"?
Comment: @foo: I tried with `property :` and that works! So this only imports the handlers that are called, correct?
Comment: `property :` defines a convenient shortcut for referring to the library. It doesn't add anything to your script's own namespace. (`property mylib : script "MyLibrary"` is basically equivalent to using `import mylib` in Python and `use script "MyLibrary"` is equivalent to `from mylib import *`, while `use mylib : script "MyLibrary"` is like using _both_.)
Comment: Oh, and avoid "Libraries with Terminology" like the plague, [for that way insanity lies](http://lovecraft.wikia.com/wiki/Cthulhu).


how would prove that $\prod_{k=1}^n 1 - 1_{A_k} = \sum_{I \subset \{1,2,...,n\} }(-1)^{card(I)}1_{A_I}$

Question: on this page there is a proof of the Inclusion–exclusion principle, which goes
Let $A_1, A_2, ..., A_n$ be finite sets
let $ A_I =   \cap_{i \in I} A_i$
then
$ \forall x \in \cup_{i = 1}^n A_i, \ (1 − 1_{A_1} ) ( 1 − 1_{A_2} ) ⋯ ( 1 − 1_{A_n} ) = 0 $
and
$\prod_{k=1}^n 1 - 1_{A_k} = \sum_{I \subset \{1,2,...,n\} }(-1)^{card(I)}1_{A_I} \ \ : \ \ (*)$
and then
$ \sum_{\emptyset \not= I \subset \{ 1,2,...,n\} } (-1)^{card(I)-1}1_{A_I} = 1 $
which inded, proves the principle by sum of x in $\cup_{k = 1}^nA_k$

but no matter how much I try, a cannot prove the second line (*), does anyone has an idea ?
Thank you for your time :).
Answer: When expanding $\prod_{k=1}^n(1-1_{A_k})$, a general term looks like $(-1)^{\mbox{card(I)}}\prod_{k\in I}  1_{A_k}$, where $I\subset\{1,2,\cdots,n\}$. Finally $\prod_{k\in I}  1_{A_k} = 1_{\cap_{k\in I}A_k}=1_{A_I}$, which completes the proof.
For the general term, first think about the simpler case $(1-b)^n$, which upon expansion has terms that will look like $1^ib^{n-i}$. You're just picking two exponents, such that they add to $n$. In the general case of $\prod_{k=1}^n(1-b_k)$, you pick an exponent for $1$, say $i$, and then you need to pick $n-i$ $b_k$'s, to give you $1^ib_{k_1}\cdots b_{k_{n-i}}$. Equivalently you're picking indices for $b$ out of $I\subset \{1,\cdots,n\}$, with $\mbox{card}(I)=n-i$. So when you sum all the terms, it's equivalent to just selecting subsets $I$ of $\{1,\cdots,n\}$.
Comment: Thank you ! Do you have the proof of your claim though? it is still not obvious to me. Anyway, your help means a lot. (Ps : I apologize if my english is inperfect, please note that it is not my mother tongue)
Comment: @S.lama: see edit.


Defining double exclamation?

Question: I understand what a double exclamation mark does (or I think I understand) but I am not sure how it is defined on a random object. For example in the code snippet below:
Assignment *a;
if (!getAssignment(query, a))
   return false;
hasSolution = !!a;

if (!a)
   return true;

How do I know what value will the double exclamation mark result in ? In other words does it always convert to true ? false ? or can you define a behavior for it such as executing a method to determine the result (how does the object know how to act in this situation) ? I am bit confused about this piece of code due to all these exclamation stuff going on.. Any explanation is appreciated.
Hope I was clear and thanks.
Comment: @ildjarn You should use self-explanatory code. Neither a cast nor `!!` does this. Compare explicitly instead of using implicit coercion (which, in the last consequence, is weak typing). Use `a != nullptr`.
Comment: `!!` in C++ is an anti-pattern, that's all.
Comment: @Konrad : You say anti-pattern, I say idiom of its own. Your dislike of `!!` does not make it "crap". Want to avoid a C4305 warning in VC++? You can use `static_cast` or `!!` -- which is easier to type and read?
Comment: @ildjarn I find it both, and if you are incapable of implementing a boolean operator (especially in C++11, but even before) you should keep your fingers off operator overloading completely. Ignorance of established idioms is no excuse to write or condone crap code, sorry.
Comment: @Konrad : I disagree -- it's not an anti-pattern, it's a pattern that allows for overloading only `operator!` instead of both `operator!` and `operator bool` (or some safe-bool idiom).
Comment: @ildjarn How does that make it not an anti-pattern? *Do* overload a boolean operator when it makes sense. And when it doesn't, don't overload `operator!` either. They come in pairs. Exclusively.
Comment: @Konrad : Only for the few who know how to _properly_ implement the safe-bool idiom. ;-] Not everyone is an expert, and `!!` is not unreadable or confusing.
Answer: a is a pointer. In C++, nullptr is defined to be an invalid pointer. !pointer turns a nullptr pointer into true and a non nullptr pointer into false. !boolean turns true into false and false into true. It will always work.
!(!a) is a useful way to think of it.
Comment: I have changed the 0 into NULL to avoid some common confusion that a NULL pointer must have binary value 0 (it does not, a 0 integer constant is implicitly convertible to a NULL pointer, but there is no guarantee on the representation of NULL)
Comment: NULL is NOT defined to be an invalid pointer, it is defined be false in logical context. a = NULL; is perfectly legal. The easiest way to remember !!a is to narrow a!=0 to 1 and a==0 to 0.
Comment: Using 0 for the canonical invalid pointer is legal in C++ and historically used as the standard. NULL is an artifact from C that is only supported as part of C standard library compatibility. [It was not recommended to use NULL within C++](http://www2.research.att.com/~bs/bs_faq2.html#null). To avoid an unnecessary argument, I'll switch it to `nullptr` which is a keyword in C++11.
Answer: Don't think of it as "double exclamation mark", think of it as two separate operators, one running on the result of the other.
For all primitive types, it will "work".  !a is equivalent to a == 0, so !!a is equivalent to !(a == 0), which in turn is equivalent to a != 0.
For user-defined types, it won't compile unless they overload operator !.  But obviously, in this case, the behaviour could be almost anything.
Answer: !! is not a single token in C++ and simply resolves to applying the ! operator twice.
As a is a pointer and not an object of class type the ! cannot be overloaded. It is defined to return true if a is a null pointer and false otherwise.
The second application of ! simply negates the result of the first !.
The expression !!a is equivalent to a != 0.
Answer: The code is horribly complicated. In reality, you want to test whether the getAssigment method is successful and whether the assigned pointer is non-null.
The code tests that, albeit in a convoluted fashion, taking advantage of weak typing, rather than trying to embrace explicitness and C++' strong typing. As a consequence, it's not idiomatic C++ and rather harder to understand than necessary.
In particular, don't use !!a in C++. This is an established idiom in weakly-typed languages such as JavaScript to coerce a value into a boolean type. But in C++, this is not commonly used.
It's not clear what the code does since hasSolution isn't defined or used. However, I suspect that the code is supposed to be equivalent to the following:
Assignment *a;
return getAssignment(query, a) and a == nullptr;

(Before C++11, you need to write 0 instead of nullptr.)
However, this code still reveals a bad design: why is a passed by reference? Why isn't it the return value? Worse, a is never used, so unnecessary. If a is indeed unnecessary, it should be left out completely. If it's necessary, it should be the return value. In other words, the prototype of getAssignment should be as follows:
Assignment* getAssignment(the_type_of_query query);

And it should be used simply as follows:
Assignment* a = getAssignment(query);

Furthermore, I suspect that this code actually assigns memory ownership to the raw pointer a. This is strongly discouraged in modern C++. Either use no pointers or a smart pointer.
Answer: bool result = true;
result = !!result; // result = true, e.g. !result is false, !!result is !false.

Answer: There is no "!!" operator, so in fact, the statement is equivalent to:
hasSolution = !(!a);
So first, operator!() is called on expression "a", then another operator!() is called on the result. In the case of our code, "a" is a pointer to Assignement. C++ defines a special case for using operator!() on a pointer type: it returns a bool which is true if the pointer is null and false otherwise. In short, the same as the expression (a == 0). Calling operator!() on the result of (!a), which is a bool, simply reverts the result, i.e. returns true if (!a) is false and false if (!a) is true.
So in conclusion, (!!a) return the same result as (a != 0). This is because "a" is a pointer.
Answer: The easiest way to remember double-negation !!a is to narrow a!=0 to 1 and a==0 to 0.
Which is in boolean context (i.e. C++) true or false.

Defining double exclamation?


Line integral for $y=1/x$

Question: I'm interested in calculating the line integral for $y=1/x$. I would be grateful if somebody could show me how this is done.
In case you were wondering I'm a bit too old for homework !!!  and maybe too old to be able to do this sort of calculus.
Comment: What are you integrating?
Comment: Where are you integrating y=1/x? the indefinite integral is log x + C
Comment: line integral and its not easy
Comment: ok heres the question rephrased to make it easier to see why im interested in the LINE INTEGRAL
Comment: ok heres the question rephrased to make it easier to see why im interested in the LINE INTEGRAL  suppose x*y=n as in the factorisation of a number ... then using parameterisation running the integral from say root(n) , root (n) [the square root of the number about which the line integral is symetric ] to 1,n   then the parametric equation  gives [root(n)  + ( 1 - root (n) t] , [root (n) + (n- root(n) t]  call them A and B The integral then becomes I { (root [ (1- root(n))^2 + (n+root(n) ^2] / (A*B)     hope its clearer now what im trying to do
Answer: If I have understood you want to calculate the length of the line $1/x$ over some interval. The line element is $\sqrt{dy^2+dx^2}$, so the length of the line is $\int \sqrt{(\frac{dy}{dx})^2+1} dx=\int \sqrt{1/x^4+1} dx$ (assuming you are staying away from $x=0$). Wolfram alpha will integrate this for you but it looks real ugly.
Comment: Its x * F not xF. F is an elliptic integral of the first kind and E elliptic integral of second kind. There should be a link to these on the same page Wolfram gave the answer on.
Comment: wolfram would not calculate 1/x as a line integral   it can be done i would imagine using parameterisation
Comment: it did indeed calculate it and it was very messy ...it also included two symbols i dont understand xF and xE   any idea what these might be ????  i cant get the result out of the gif its presented in so cant post it here sadly. It should be reflexive about root x,  after all its basically the multiplication of two numbers represented by x and y  thanks btw
Comment: Also Wolfram gives a simplified result further down the page assuming x>0.
Comment: yes it does in fact say so on the page though im not at all convinced from the graphical  output that the integral is correct As i said effectively it is x*y = say a number   and the graph doesnt give any degree of confidence knowing this simple fact .. when i asked this question i knew it looked simple but wasnt .. i had  a stab at using parameterisation but didnt get a sensible answer and i dont think the above gives it   Im very tempted to write a program to effectively integrate the line by generating a seris of points and adding the lengths
Comment: I noticed the graph, why is it negative for x>0? I guess because of the constant term which will go away when the limits are put in.

Line integral for $y=1/x$


How to insert data to TableView in another view controller Swift 4?

Question: I have ViewControllerA and ViewControllerB. I make a network call in ViewControllerB,when it success,I want to insert a data to the TableView in ViewControllerA,so the data can appear as 1st item in the TableView.
Here is what I tried:
ViewControllerB
 var myItem = [Item]() //here is the array in ViewControllerA

Alamofire.request(MyURL!, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseJSON{
            response in

            switch response.result{
            case .success(let result):

                let json = JSON(result)

                if let myJson = json.dictionary,let myItem = Item.init(dict: myJson){
                    self.myItem.insert(newPost, at: 0)
                    NotificationCenter.default.post(name: .reload, object: nil) //here I call notification center after insert to the array

                   self.dismiss(animated: true, completion: nil)
                   self.tabBarController?.selectedIndex = 0 //back to ViewControllerA
                }

            case .failure(let error):
                print("error = \(error)")
            }

        }

In ViewControllerA (which contain the tableView)
override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(updateTableView), name: .reload, object: nil)
   }

@objc func updateTableView(_ notification: Notification){
        print("here get called")
        self.tableView.reloadData()
    }

I create an extension for the NotificationCenter
extension Notification.Name {
    static let reload = Notification.Name("reloadTableView")
}

After done all this,the item that I insert to the array of ViewControllerB didnt appear in the 1st place of TableView in ViewControllerB.
I make a print in updateTableView() function which will call when received response from NotificationCenter in ViewControllerA,it get called,but the data is not appear.
I cant use segue,cause the both ViewController are 2 of the tab in TabbarController.
So in this case,how can I insert the data from ViewControllerB to TableView of ViewControllerA?
Comment: is there a common array for ViewController A and B ? Did you checked with breakpoints that do TableView in Controller A reloads when notification is post ? Try checking Array is It updated ?
Comment: common array is that mean,I define the array which use for tableView in ViewController A? In my question `var myItem = [Item]()` <--this is used for tableView in ViewControllerA.
Answer: The problem is that you create a new array by this line
var myItem = [Item]()

But the viewControllerA use the different array. Try to send a new array in notification
NotificationCenter.default.post(name: .reload, object: self.myItem)

Then in viewControllerA set the new array.
@objc func updateTableView(_ notification: Notification){
        var newItems = notification.object as! [Item]

        arrayOfControllerA.append(contentsOf: newItems)
        self.tableView.reloadData()
  }

Comment: bro I didnt use segue,cause is the TabbarController.So how to access the array in ViewControllerA?
Comment: Ok, then you could post the notification with this array, I edited the answer
Comment: Your answer is posting the notification in ViewControllerB,can you show me how to get the array in ViewControllerA as well?
Comment: So when I get the array in ViewControllerA,is it I insert this array to array in the existing array in ViewControllerA?
Comment: I got this error `Could not cast value of type 'MyApp.Item' (0x100ccd9a0) to 'NSArray' (0x1b4ced950).` Can u help?
Comment: Use self.myItem  when post notification


Why is there an asymmetry between the training step and evaluation step?

Question: It is well-known, especially in natural language processing, that machine learning should proceed in two steps, a training step and an evaluation step, and they should use different data.  Why is this? Intuitively, this process helps avoid overfitting the data, but I fail to see a (information-theoretic) reason this is the case.
Relatedly, I've seen some numbers thrown around for how much of a data set should be used for training and how much for evaluation, like 2/3 and 1/3 respectively.  Is there any theoretical basis for choosing a particular distribution?
Answer: It's funny that the most upvoted answer doesn't really answer the question :) so I thought it would be nice to back this up with a bit more theory - mostly taken from "Data Mining: Practical Machine Learning Tools and Techniques" and Tom Mitchell's "Machine Learning".

Introduction.
So we have a classifier and a limited dataset, and a certain amount of data must go into training set and the rest is used for testing (if necessary, a third subset used for validation).
Dilemma we face is this: to find a good classifier, the "training subset" should be as big as possible, but to get a good error estimate the "test subset" should be as big as possible - but both subsets are taken from the same pool.
It's obvious that the training set should be bigger than the test set - that is, the split should not be 1:1 (main goal is to train, not to test) - but it's not clear where the split should be.
Holdout procedure.
The procedure of splitting the "superset" into subsets is called holdout method. Note that you may easily get unlucky and examples of a certain class could be missing (or overpresented) in one of the subsets, which can be addressed via

random sampling, which guarantees that each class is properly represented in all data subsets - the procedure is called stratified holdout
random sampling with repeated training-testing-validation process on top of it - which is called repeated stratified holdout

In a single (nonrepeated) holdout procedure, you might consider swapping the roles of the
testing and training data and average the two results, but this is only plausible with a 1:1 split between training and test sets which is not acceptable (see Introduction). But this gives an idea, and an improved method (called cross-validation is used instead) - see below!
Cross-validation.
In cross-validation, you decide on a fixed number of folds (partitions of the data). If we use three folds, the data is split into three equal partitions and

we use 2/3 for training and 1/3 for testing
and repeat the procedure three times so that, in the end, every instance has been used exactly once for testing.

This is called threefold cross-validation, and if stratification is adopted as well (which it often true) it is called stratified threefold cross-validation.
But, lo and behold, the standard way is not the 2/3:1/3 split. Quotting "Data Mining: Practical Machine Learning Tools and Techniques",

The standard way [...] is to use stratified 10-fold cross-validation. The data is divided randomly into 10 parts in which the class is represented in approximately the same proportions as in the full dataset. Each part is held out in turn and the learning scheme trained on the remaining nine-tenths; then its error rate is calculated on the holdout set. Thus the learning procedure is executed a total of 10 times on different training sets (each of which have a lot in common). Finally, the 10 error estimates are averaged to yield an overall error estimate.

Why 10? Because "..Extensive tests on numerous datasets, with different learning techniques, have shown that 10 is about the right number of folds to get the best
estimate of error, and there is also some theoretical evidence that backs this up.." I haven't found which extensive tests and theoretical evidence they meant but this one seems like a good start for digging more - if you wish.
They basically just say

Although these arguments are by no means conclusive, and debate continues to
  rage in machine learning and data mining circles about what is the best scheme
  for evaluation, 10-fold cross-validation has become the standard method in
  practical terms. [...] Moreover, there is nothing magic about the exact number
  10: 5-fold or 20-fold cross-validation is likely to be almost as good.

Bootstrap, and - finally! - the answer to the original question.
But we haven't yet arrived to the answer as to, why the 2/3:1/3 is often recommended. My take is that it's inherited from bootstrap method.
It's based on sampling with replacement. Previously, we put a sample from the "grand set" into exactly one of the subsets. Bootstraping is different and a sample can easily appear in both training and test set.
Let's look into one particular scenario where we take a dataset D1 of n instances and sample it n times with replacement, to get another dataset D2 of n instances.
Now watch narrowly.
Because some elements in D2 will (almost certainly) be repeated, there must be some instances in the original dataset that have not been picked: we will use these as test instances.
What is the chance that a particular instance wasn't picked up for D2? The probability of being picked up on each take is 1/n so the opposite is (1 - 1/n).
When we multiply these probabilities together, it's (1 - 1/n)^n which is e^-1 which is about 0.3. This means our test set will be about 1/3 and the training set will be about 2/3.
I guess this is the reason why it's recommended to use 1/3:2/3 split: this ratio is taken from the bootstrapping estimation method.
Wrapping it up.
I want to finish off with a quote from the data mining book (which I cannot prove but assume correct) where they generally recommend to prefer 10-fold cross-validation:

The bootstrap procedure may be the best way of estimating error for very
  small datasets. However, like leave-one-out cross-validation, it has disadvantages
  that can be illustrated by considering a special, artificial situation [...] a completely random dataset with two classes. The true error rate is 50% for any prediction rule.But a scheme that memorized the training set would give a perfect resubstitution score of 100%
  so that etraining instances= 0, and the 0.632 bootstrap will mix this in with a weight
  of 0.368 to give an overall error rate of only 31.6% (0.632 ¥ 50% + 0.368 ¥ 0%),
  which is misleadingly optimistic.
Answer: Consider a finite set of m records. If you use all the records as a training set you could perfectly fit all the points with the following polynomial:
y = a0 + a1*X+a2*X^2 + ... + an*X^m
Now if you have some new record, not used in training set and values of an input vector X are different from any vector X, used in training set, what can you tell about the accuracy of prediction y?
I suggest you to go over an example where you have 1 or 2-dimensional input vector X (in order to visualize the overfitting polynomial) and check how big is the prediction error for some pair (X, y) which X values are just a little different from the values from the training set.
I don't know if this explanation is theoretic enough, but hopefully it helps. I tried to explain the problem on regression model as I consider it more intuitively understandable than others (SVM, Neural Networks...).
When you build a model, you should split the data into at least training set and test set (some split the data into training, evaluation, and cross validation set). Usually 70% of data is used for training set and 30% for evaluation and then, when you build the model, you have to check the training error and test error. If both errors are big, it means your model is too simple (the model has high bias). On the other hand if your training error is very small but there is a big difference between training and test error, it means your model is too complex (the model has high variance).
The best way to choose the right compromise is to plot training and test errors for models of various complexity and then choose the one where the test error is minimal (see the picture below).

Comment: This is a really great answer for how - not so much for why. But maybe that is just a [wrong question](http://lesswrong.com/lw/og/wrong_questions/) - what we really care about is what works empirically, not theory.
Comment: @winwaed The questions are "Why is there...?", "Why is this?", and "Is there any...?", all clearly indicated by question marks.  I'm familiar with the phenomenon, and I find it intuitive, and I'm familiar with empirical examples, but I don't know *why* it is the case, and it seems information theory should have an answer for me.  The above comment was just reflection that perhaps "why" questions aren't particularly relevant once you have empirically verified regularities that you can exploit.
Comment: @Thom: So really your question is the second paragraph and not the end of the first ("fail to see why") because what works empirically is that you get over-fitting: your model does an excellent job of handling minor quirks in your training data which are not present in the general case.
Answer: This is the problem of generalization—that is, how well our hypothesis will correctly classify future examples that are not part of the training set. Please see this fantastic example, what happened in case your model fit only the data you have and not a new one: Titius-Bode law
Comment: A good example - it is very much the same as with scientific hypotheses. We're still talking about models whether they are statistical ML models or models of the universe.
Answer: So far @andreiser gave a brilliant answer to the second part of OP's question regarding training/testing data split, and @niko explained how to avoid overfitting, but nobody has gotten to the merit of the question: Why using different data for training and evaluation helps us avoid overfitting.

Our data is split into:

Training instances
Validation instances
Test (evaluation) instances

Now we have a model, let's call it $\mathfrak{M}$. We fit it using the training instances and check its accuracy using the validation instances. We may even do cross validation. But why on earth would we check it again using the test instances?
The problem is that in practice, we try many different models, $\mathfrak{M}_1, ..., \mathfrak{M}_n$, with different parameters. This is where overfitting occurs. We selectively choose the model that performs the best on the validation instances. But our goal is to have a model that performs well in general. This is why we have the test instances - unlike the validation instances, test instances aren't involved in choosing the model.
It is important to realise what are the different roles of the Validation and Test instances.

Training instances - used to fit the models.
Validation instances - used to choose a model
Test (evaluation) instances - used to measure a model's accuracy on new data

See the page 222 of The Elements of Statistical Learning: Data Mining, Inference, and Prediction for more details.


computing Lefschetz number

Question: We have a fixed point theorem which says that :

Let $X$ be a compact polyhedron, $f:X\rightarrow X$ be a continuous map. If $L(f)\neq 0$ then $f$ must have a fixed point. (Lefschetz number is denoted by $L(f)$)

Now, i would like to know if there is any method to compute this $L(f)$ for any map.
There is a result which says for a nullhomotopic map $L(f)\neq 0$..
Can some one suggest how to proceed for this kind of computation.
Comment: $L(f)$ is given by the alternating sum of the trace of $f_* : H_i(X, \mathbb Z) \to H_i(X, \mathbb Z)$. If $f$ is a constant map, $f_*$ is identity on $H^0$ (Assume $X$ is path connected) and $f_* = 0$ for $i>0$.
Comment: In that case it would be $1$ (assume that $X$ is connected). As $f$ is nulhomotopic, you can calculate only for the constant map.
Comment: I don't think there is any way to compute $L(f)$ explicitly, if everything now are general.
Comment: what about some simple maps such as nullhomotopic maps? Is there any way @John
Comment: @John : How is that $1$.. How do i even proceed for that.. Can you give some hint....
Comment: Oh no... I got it... I don't know how i missed that simple point... @John
Answer: In general it really depends on how well you understand $f$ and its action on the cohomology of $X$. Here are two nice special cases where you only need to understand the action of $f$ on a single cohomology group and then everything else is determined by the cup product.

Tori
Let $\Gamma$ be a lattice in $\mathbb{R}^n$. (You can take $\Gamma = \mathbb{Z}^n$ if you want to be boring, but it's actually important that everything I'm about to say will be functorial in $\Gamma$.) Then $\mathbb{R}^n/\Gamma$ is a torus. Its cohomology (over $\mathbb{Z}$) is an exterior algebra
$$H^{\bullet}(\mathbb{R}^n/\Gamma) \cong \Lambda^{\bullet}(H^1(\mathbb{R}^n/\Gamma))$$
on $H^1$, so to understand the action of a map $f : \mathbb{R}^n/\Gamma \to \mathbb{R}^n/\Gamma$ on cohomology it suffices to understand the action of $f$ on $H^1$. Functorially in $\Gamma$,
$$H_1(\mathbb{R}^n/\Gamma) \cong \Gamma$$
and hence $H^1$ can be identified with the dual lattice $\Gamma^{\vee} = \text{Hom}(\Gamma, \mathbb{Z})$. $f$ acts on $H_1$ by some linear map
$$H_1(f) : \Gamma \to \Gamma$$
or, after picking a basis of $\Gamma$, by some element of $\text{GL}_n(\mathbb{Z})$, and then everything else is determined by that action as follows. The action of $f$ on $H^k$ is the $k^{th}$ exterior power of the action of $f$ on $H^1$, and hence its trace is the $k^{th}$ coefficient of the characteristic polynomial of $H^1(f)$ (up to sign), which is the same as the characteristic polynomial of $H_1(f)$. From here you can compute that the Lefschetz number of $f$ is
$$\boxed{ L(f) = \det(1 - H^1(f)) }.$$
Now for simplicity fix $\Gamma = \mathbb{Z}^n$. Any element of $\text{GL}_n(\mathbb{Z})$ in fact acts on $\mathbb{R}^n/\mathbb{Z}^n$ by matrix multiplication in the obvious way with induced action on $H_1$ given by the same element, and this remains true if in addition we translate by something. Applying the Lefschetz fixed point theorem we get the following.

Theorem: Suppose $g \in \text{GL}_n(\mathbb{Z})$ satisfies $\det (1 - g) \neq 0$. Then for all $w \in \mathbb{R}^n$ there is some $v \in \mathbb{R}^n$ such that $v \equiv gv + w \bmod \mathbb{Z}^n$.

This is an exercise to show directly, without the Lefschetz fixed point theorem.

Complex projective spaces
Complex projective space $\mathbb{CP}^{n-1}$ has cohomology
$$H^{\bullet}(\mathbb{CP}^{n-1}) \cong \mathbb{Z}[\alpha]/\alpha^n$$
where $\alpha$ has degree $2$. If $f : \mathbb{CP}^{n-1} \to \mathbb{CP}^{n-1}$ is a map, then it acts on $H^2 \cong \mathbb{Z} \alpha$ by multiplication by some integer $d$, and then it necessarily acts on $H^{2k} \cong \mathbb{Z} \alpha^k$ by multiplication by $d^k$. We find that the Lefschetz trace of $f$ is
$$\boxed{ L(f) = 1 + d + d^2 + \dots + d^{n-1} = \frac{d^n - 1}{d - 1} }$$
(or $n$, if $d = 1$). In particular, when $n$ is odd this is never zero. So applying the Lefschetz fixed point theorem we get the following.

Theorem: Every map $f : \mathbb{CP}^{2k} \to \mathbb{CP}^{2k}$ has a fixed point.

For all $n$ we can at least say that if $d = 0$ (in particular, if $f$ is nullhomotopic) then $L(f) = 1$, although as John mentions in the comments this is true of any nullhomotopic map acting on a connected space. A particularly interesting family of examples of nullhomotopic maps is given by the action of any $g \in \text{GL}_n(\mathbb{C})$ (which is connected). A fixed point of such a map $g$ acting on projective space is precisely an eigenvector, and so applying the Lefschetz fixed point theorem we get the following.

Theorem: Every $g \in \text{GL}_n(\mathbb{C})$ has an eigenvector.

This is equivalent to the fundamental theorem of algebra!
Moreover, trying to imitate this proof for the real projective spaces tells you exactly how strong the statement you can make over $\mathbb{R}$ is: the way the cohomology computation works out (do it over $\mathbb{Q}$ for simplicity) we get that every $g \in \text{GL}_n(\mathbb{R})$ has a real eigenvector (with a real eigenvalue) iff $n$ is odd. Hence a real polynomial of odd degree has a real root (which we also could've proven using the IVT), but a real polynomial of even degree doesn't necessarily, exactly as expected. (Actually, if you're more careful Lefschetz says something a bit stronger than this: it'll say that a real polynomial of even degree has a real root if its constant coefficient is negative, which also follows from the IVT.)
Comment: This is much more than what i have asked... I have got some idea but i am not used to some of the ideas that you have informed... But it is really motivating how this is related to fundamental theorem of algebra.... Thanks.. I think this answers my question

computing Lefschetz number