问:
Android Recycler View with Firebase
I'm trying to use a recycler view inside a fragment and am using firebase to get data from the database. The problem is none of my recycler view methods such as onCreateViewHolder, onBindViewHolder, getItemCount are being called when I'm setting the adapter. This I can confirm by running the app in debugger mode.
My fragment:

public class Ongoing extends Fragment {

```<code>RecyclerView recyclerView;
ProjectAdapter adapter;
ArrayList<ProjectModel> project ;

String[] project_name = new String[3];
String[] project_desc = new String[3];

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.project_layout, container, false);
        recyclerView = (RecyclerView) v.findViewById(R.id.rv_projects);
        project = new ArrayList<>();
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("projects");

        ref.child("ongoing").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                int i = 0;
                for(DataSnapshot dsp: dataSnapshot.getChildren()){
                    //System.out.println(dsp.child("name").getValue());
                    //System.out.println(dsp.child("description").getValue());
                    //ProjectModel p = new ProjectModel(dsp.child("name").getValue().toString(),dsp.child("description").getValue().toString());
                    //project.add(i,p);
                    project_name[i]= dsp.child("name").getValue().toString();
                    project_desc[i]= dsp.child("description").getValue().toString();
                    i++;
                }
                System.out.println(project_name);
                System.out.println(project_desc);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        adapter = new ProjectAdapter(project_name, project_desc,getActivity());
        recyclerView.setAdapter(adapter);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(llm);
        return v;

    }
</code>```

}

My RecyclerView adapter:

```<code>import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.adg.adgofficial.R;

public class ProjectAdapter extends RecyclerView.Adapter<ProjectAdapter.ProjectViewHolder>{

    String[] project_name,project_desc;
    //ArrayList<ProjectModel> project;
    Context context;

    public ProjectAdapter( String[] project_name,String[] project_desc ,Context context) {

        this.project_name = project_name;
        this.project_desc = project_desc;
        this.context = context;
    }

    @Override
    public ProjectViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.projects_element,parent,false);
        return new ProjectViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ProjectViewHolder holder, int position) {
        holder.title.setText(project_name[position]);
        holder.desc.setText(project_desc[position]);
    }

    @Override
    public int getItemCount() {
        return 3;
    }

    public static class ProjectViewHolder extends RecyclerView.ViewHolder {

        TextView title, desc;

        public ProjectViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.proj_element_title);
            desc = (TextView) itemView.findViewById(R.id.proj_element_desc);
        }
    }
}
</code>```

This issue has been troubling me for weeks and I can't seem to find a solution to it. Thanks in advance for the help.

答:
Try this:</p>

```<code> ArrayList<String> project_name = new ArrayList<>();
    ArrayList<String>  project_desc = new ArrayList<>();

             ref.child("ongoing").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        for(DataSnapshot dsp: dataSnapshot.getChildren()){

   ProjectModel p = dsp.getValue(ProjectModel.class);
                            project_name.add(p.getproject_name);
                            project_desc.add(p.getproject_desc);

                        }
                        System.out.println(project_name);
                        System.out.println(project_desc);
         adapter = new ProjectAdapter(project_name, project_desc,getActivity());
                recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
</code>```

Title: Android Recycler View with Firebase

Body:
I'm trying to use a recycler view inside a fragment and am using firebase to get data from the database. The problem is none of my recycler view methods such as onCreateViewHolder, onBindViewHolder, getItemCount are being called when I'm setting the adapter. This I can confirm by running the app in debugger mode.
My fragment:

public class Ongoing extends Fragment {

RecyclerView recyclerView;
ProjectAdapter adapter;
ArrayList<ProjectModel> project ;

String[] project_name = new String[3];
String[] project_desc = new String[3];

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.project_layout, container, false);
        recyclerView = (RecyclerView) v.findViewById(R.id.rv_projects);
        project = new ArrayList<>();
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("projects");

        ref.child("ongoing").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                int i = 0;
                for(DataSnapshot dsp: dataSnapshot.getChildren()){
                    //System.out.println(dsp.child("name").getValue());
                    //System.out.println(dsp.child("description").getValue());
                    //ProjectModel p = new ProjectModel(dsp.child("name").getValue().toString(),dsp.child("description").getValue().toString());
                    //project.add(i,p);
                    project_name[i]= dsp.child("name").getValue().toString();
                    project_desc[i]= dsp.child("description").getValue().toString();
                    i++;
                }
                System.out.println(project_name);
                System.out.println(project_desc);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        adapter = new ProjectAdapter(project_name, project_desc,getActivity());
        recyclerView.setAdapter(adapter);
        LinearLayoutManager llm = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(llm);
        return v;

    }

}

My RecyclerView adapter:

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.adg.adgofficial.R;

public class ProjectAdapter extends RecyclerView.Adapter<ProjectAdapter.ProjectViewHolder>{

    String[] project_name,project_desc;
    //ArrayList<ProjectModel> project;
    Context context;

    public ProjectAdapter( String[] project_name,String[] project_desc ,Context context) {

        this.project_name = project_name;
        this.project_desc = project_desc;
        this.context = context;
    }

    @Override
    public ProjectViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.projects_element,parent,false);
        return new ProjectViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ProjectViewHolder holder, int position) {
        holder.title.setText(project_name[position]);
        holder.desc.setText(project_desc[position]);
    }

    @Override
    public int getItemCount() {
        return 3;
    }

    public static class ProjectViewHolder extends RecyclerView.ViewHolder {

        TextView title, desc;

        public ProjectViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.proj_element_title);
            desc = (TextView) itemView.findViewById(R.id.proj_element_desc);
        }
    }
}

This issue has been troubling me for weeks and I can't seem to find a solution to it. Thanks in advance for the help.

Body:
Try this:

 ArrayList<String> project_name = new ArrayList<>();
    ArrayList<String>  project_desc = new ArrayList<>();

             ref.child("ongoing").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        for(DataSnapshot dsp: dataSnapshot.getChildren()){

   ProjectModel p = dsp.getValue(ProjectModel.class);
                            project_name.add(p.getproject_name);
                            project_desc.add(p.getproject_desc);

                        }
                        System.out.println(project_name);
                        System.out.println(project_desc);
         adapter = new ProjectAdapter(project_name, project_desc,getActivity());
                recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });


来源: stackexchange

问:
CSS: Target a button after an id
I have a table that has an id of 'table-noValues' or 'table-values' depending on if it has values or not. The tables both have a button with an id of 'calculateButton'.

I'm trying to get the css to be something like:

```<code>#table-noValues //add calculateButton here -- idk how to call the button here
{
  opacity: 0.65;
  cursor: not-allowed;
}

#table-values //calculateButton
{
  cursor: pointer;
}
</code>```

But I'm not sure how to call the button inside of the div. The button is a <button>, not an <input>

答:
just use the ID you have on the button, and before it write the table ID like so

```<code>#table-noValues #calculateButton //when table has no values
{
  opacity: 0.65;
  cursor: not-allowed;
}

#table-values #calculateButton //when table has values
{
 cursor: pointer;
}
</code>```

and so it will give styles to the button depending on the table ID

ContentLicense: CC BY-SA 3.0

Title: CSS: Target a button after an id

Body:
I have a table that has an id of 'table-noValues' or 'table-values' depending on if it has values or not. The tables both have a button with an id of 'calculateButton'.

I'm trying to get the css to be something like:

#table-noValues //add calculateButton here -- idk how to call the button here
{
  opacity: 0.65;
  cursor: not-allowed;
}

#table-values //calculateButton
{
  cursor: pointer;
}

But I'm not sure how to call the button inside of the div. The button is a <button>, not an <input>

Body:
just use the ID you have on the button, and before it write the table ID like so

#table-noValues #calculateButton //when table has no values
{
  opacity: 0.65;
  cursor: not-allowed;
}

#table-values #calculateButton //when table has values
{
 cursor: pointer;
}

and so it will give styles to the button depending on the table ID


问:
return custom error codes to client in the response for a JAX-RS
I am new to JAX-RS and still learning it, so my question can be a little naive so please bear with it :)

I have been going through various SO questions for "error codes for http response" . I have found out that as long as one dont want to be pedantic he can return 4xx status codes in the response.

I have also gone through this link RFS 2616 also the W3

I wanted to know is there any general practice to return custom error codes other than standard HTTP response status codes.

e.g if in post request for getting user information by userid and return error if userid is invalid / doesnt exists. In this case HTTP status 422 sounds idle. But if detailed error description is needed can custom error like 40xx where xx is value other than http errors be returned to client.

similarly can 40xx be defined and returned in response to client ? ( having correct syntax in the request )

4001  - userid invalid

4002 -  post id invalid

etc..

or should I return 4xx status code and in the response body add by own codes for more error details?

答:
If the custom statuses are between integers 102 and 599 (inclusive), there is also an option to set the status with int value:

```<code>ResponseBuilder.status(451).build();
</code>```

In fact using the standard groupings (1xx,2xx,3xx,4xx,5xx) is highly recommended even with custom status codes. (The examples provided should probably be 4xx Client errors.)

Body:
If the custom statuses are between integers 102 and 599 (inclusive), there is also an option to set the status with int value:

ResponseBuilder.status(451).build();

In fact using the standard groupings (1xx,2xx,3xx,4xx,5xx) is highly recommended even with custom status codes. (The examples provided should probably be 4xx Client errors.)


问:
Invalid dynamic route name using React-router 2.4.0
I'm using react-router version 2.4.0 and i'm unable to solve if path like this

sari.yanti

actually this is the username where user will get it own pages along with their username. But how do I get react-router to work with path like that

答:
I resolved by adding this to my webpack dev server config:

```<code> historyApiFallback: {
disableDotRule: true
</code>```

}

or by this

```<code>devServer: {
   proxy: {
'/*.*': { // Match all URL's with period/dot
  target: 'http://localhost:8080/',  // send to webpack dev server
  rewrite: function(req){
    req.url='index.html';  // Send to react app
  }
}
</code>```

}
}

Body:
I resolved by adding this to my webpack dev server config:

 historyApiFallback: {
disableDotRule: true

}

or by this

devServer: {
   proxy: {
'/*.*': { // Match all URL's with period/dot
  target: 'http://localhost:8080/',  // send to webpack dev server
  rewrite: function(req){
    req.url='index.html';  // Send to react app
  }
}

}
}


问:
Bulletin board - Database optimisation

This question is a follow on from this
Question

The project and problem

The project I am currently working on is a bulletin board for a large non-profit organisation. The bulletin board will be used to allow inter-office communication within the organisation.

I am building the application and have been having trouble extracting the results that I need from my database because I don't think it is properly normalized and because of limitations in my knowledge of relational database theory and mysql.

I would appreciate input into the design of the board in general and in particular, ways that the database structure can be improved to facilitate efficient queries and help me develop this application and future application faster

Business Logic

The bulletin board will be used in the following way

 Posting bulletins and responses to bulletins

Employees or 'users' in offices around the country will be able to post messages to the bulletin board.Bulletins must be posted to a location and categorised- i'll call these "bulletins".

Users will be able to post any number of replies to any one bulletin and users will be able to reply to their own bulletin - i'll call these 'replies'.

Rating bulletins and replies

Users will be able to either 'like' or 'dislike' a bulletin or a reply and the total number of likes or dislikes will be shown for each bulletin or reply.

Viewing the bulletin board and responses

Bulletins can be displayed chronologically.

 Users can sort bulletins chronologically or chronologically by the latest reply to that bulletin(let me know if you need more explanation)

When a particular bulletin is selected, replies to that bulletin will be displayed chronologically

```<code>-- phpMyAdmin SQL Dump
-- version 3.2.4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jan 16, 2011 at 06:44 PM
-- Server version: 5.1.41
-- PHP Version: 5.3.1

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `bulletinboard`
--

-- --------------------------------------------------------

--
-- Table structure for table `bbs`
--

CREATE TABLE IF NOT EXISTS `bbs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bb_locations_id` int(11) NOT NULL,
  `bb_categories_id` int(11) NOT NULL,
  `users_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `content` text NOT NULL,
  `created_date` int(11) NOT NULL,
  `rank` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=87 ;

--
-- Dumping data for table `bbs`
--

INSERT INTO `bbs` (`id`, `bb_locations_id`, `bb_categories_id`, `users_id`, `title`, `content`, `created_date`, `rank`) VALUES
(83, 8, 28, 44, 'sdaf', 'asdfasdf', 1292712797, 0),
(84, 8, 28, 44, 'asdf', 'asdfasd', 1292875089, 0),
(86, 8, 28, 44, 'Robert is leaving', 'Robert is leaving and going back to the states ', 1294344916, 0);

-- --------------------------------------------------------

--
-- Table structure for table `bb_categories`
--

CREATE TABLE IF NOT EXISTS `bb_categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `description` varchar(255) NOT NULL,
  `list_order` varchar(255) NOT NULL,
  `admin` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=30 ;

--
-- Dumping data for table `bb_categories`
--

INSERT INTO `bb_categories` (`id`, `title`, `description`, `list_order`, `admin`) VALUES
(28, 'Travel', 'Rideshares, proposed trips etc', '1', 1);

-- --------------------------------------------------------

--
-- Table structure for table `bb_locations`
--

CREATE TABLE IF NOT EXISTS `bb_locations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `description` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `post_code` int(11) NOT NULL,
  `list_order` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;

--
-- Dumping data for table `bb_locations`
--

INSERT INTO `bb_locations` (`id`, `title`, `description`, `address`, `post_code`, `list_order`) VALUES
(8, 'Washington DC', 'asdkf', 'dsf', 0, 1);

-- --------------------------------------------------------

--
-- Table structure for table `bb_ratings`
--

CREATE TABLE IF NOT EXISTS `bb_ratings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bbs_id` int(11) NOT NULL,
  `users_id` int(11) NOT NULL,
  `like_id` int(2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=68 ;

--
-- Dumping data for table `bb_ratings`
--

-- --------------------------------------------------------

--
-- Table structure for table `bb_replies`
--

CREATE TABLE IF NOT EXISTS `bb_replies` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `users_id` int(11) NOT NULL,
  `bbs_id` int(11) NOT NULL,
  `content` text NOT NULL,
  `created_date` int(11) NOT NULL,
  `rank` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=158 ;

--
-- Dumping data for table `bb_replies`
--

INSERT INTO `bb_replies` (`id`, `users_id`, `bbs_id`, `content`, `created_date`, `rank`) VALUES
(156, 44, 86, 'good ridance i say\r\n', 1294788444, 0),
(157, 44, 86, 'And stay away\r\n', 1294892751, 0);

-- --------------------------------------------------------

--
-- Table structure for table `bb_reply_ratings`
--

CREATE TABLE IF NOT EXISTS `bb_reply_ratings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bb_replies_id` int(11) NOT NULL,
  `users_id` int(11) NOT NULL,
  `like_id` tinyint(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=115 ;

--
-- Dumping data for table `bb_reply_ratings`
--

-- --------------------------------------------------------

--
-- Table structure for table `bb_sort_bys`
--

CREATE TABLE IF NOT EXISTS `bb_sort_bys` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(20) NOT NULL,
  `description` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `bb_sort_bys`
--

INSERT INTO `bb_sort_bys` (`id`, `title`, `description`) VALUES
(1, 'Newest', 'Posts are sorted by their creation date'),
(2, 'Popular', 'Posts are sorted by the date of their lates reply, or by post date if they have now replies');

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(10) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `permission` int(1) NOT NULL,
  `bb_sort_bys_id` varchar(10) NOT NULL,
  `bb_locations_csv` varchar(255) NOT NULL,
  `defaultLocation` int(11) NOT NULL,
  `bb_categories_csv` varchar(255) NOT NULL,
  `total_bulletins` int(5) NOT NULL,
  `bulletins_per_page` int(5) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=45 ;
</code>```

答:
They key to having an efficient database is to simplify. The main goal of a relational database is not to repeat any information. I took your SQL dump and quickly drafted a simpler version that is normalized, to the best of my knowledge. I did leave some of the fields you had in for cvs's ect. I have removed fields that it would be simpler to just recalculate by querying the db when the information is needed, such as a users total posts and a ranking of a given post. I also removed your bb_replies as you can accomplish the same result with referencing to a parent post. I have renamed the tables slightly to what made sense to me, you can use what ever naming scheme you feel comfortable with. I find that using terms that are simple makes it easier to understand how the data relates to each other.

I must admit that I do agree with some of the comments above, there are plenty of BBs out there that work just fine and would have all the functionality you are looking for. And you are lucky I am in the reading mood tonight lol that was one long question. Simplification is key in everything :)

```<code>SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';

-- -----------------------------------------------------
-- Table `users`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `users` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `username` VARCHAR(45) NULL ,
  `password` VARCHAR(100) NULL ,
  `email` VARCHAR(255) NULL ,
  `first_name` VARCHAR(100) NULL ,
  `last_name` VARCHAR(100) NULL ,
  `permission` INT NULL ,
  `created` DATETIME NULL ,
  `modified` DATETIME NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `categories`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `categories` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NULL ,
  `description` TEXT NULL ,
  `order` INT NULL ,
  `admin` INT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `locations`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `locations` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NULL ,
  `description` TEXT NULL ,
  `address` TEXT NULL ,
  `order` INT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `posts`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `posts` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `post_id` INT NOT NULL ,
  `user_id` INT NOT NULL ,
  `category_id` INT NOT NULL ,
  `location_id` INT NOT NULL ,
  `title` VARCHAR(45) NULL ,
  `content` TEXT NULL ,
  `created` DATETIME NULL ,
  `modified` DATETIME NULL ,
  PRIMARY KEY (`id`, `post_id`, `user_id`, `category_id`, `location_id`) ,
  INDEX `fk_posts_users` (`user_id` ASC) ,
  INDEX `fk_posts_posts1` (`post_id` ASC) ,
  INDEX `fk_posts_categories1` (`category_id` ASC) ,
  INDEX `fk_posts_locations1` (`location_id` ASC) ,
  CONSTRAINT `fk_posts_users`
    FOREIGN KEY (`user_id` )
    REFERENCES `users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_posts_posts1`
    FOREIGN KEY (`post_id` )
    REFERENCES `posts` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_posts_categories1`
    FOREIGN KEY (`category_id` )
    REFERENCES `categories` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_posts_locations1`
    FOREIGN KEY (`location_id` )
    REFERENCES `locations` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `likes`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `likes` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `user_id` INT NOT NULL ,
  `post_id` INT NOT NULL ,
  `like` TINYINT(1)  NULL ,
  PRIMARY KEY (`id`, `user_id`, `post_id`) ,
  INDEX `fk_posts_users_users1` (`user_id` ASC) ,
  INDEX `fk_posts_users_posts1` (`post_id` ASC) ,
  CONSTRAINT `fk_posts_users_users1`
    FOREIGN KEY (`user_id` )
    REFERENCES `users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_posts_users_posts1`
    FOREIGN KEY (`post_id` )
    REFERENCES `posts` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `sort_options`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `sort_options` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NULL ,
  `description` TEXT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `preferences`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `preferences` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `user_id` INT NOT NULL ,
  `pagination` INT NULL ,
  `sort_option_id` INT NOT NULL ,
  `categories_csv` VARCHAR(45) NULL ,
  `locations_csv` VARCHAR(45) NULL ,
  PRIMARY KEY (`id`, `user_id`, `sort_option_id`) ,
  INDEX `fk_preferences_users1` (`user_id` ASC) ,
  INDEX `fk_preferences_sort_options1` (`sort_option_id` ASC) ,
  CONSTRAINT `fk_preferences_users1`
    FOREIGN KEY (`user_id` )
    REFERENCES `users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_preferences_sort_options1`
    FOREIGN KEY (`sort_option_id` )
    REFERENCES `sort_options` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Bulletin board - Database optimisation

Body:
This question is a follow on from this
Question

The project and problem

The project I am currently working on is a bulletin board for a large non-profit organisation. The bulletin board will be used to allow inter-office communication within the organisation.

I am building the application and have been having trouble extracting the results that I need from my database because I don't think it is properly normalized and because of limitations in my knowledge of relational database theory and mysql.

I would appreciate input into the design of the board in general and in particular, ways that the database structure can be improved to facilitate efficient queries and help me develop this application and future application faster

Business Logic

The bulletin board will be used in the following way

 Posting bulletins and responses to bulletins

Employees or 'users' in offices around the country will be able to post messages to the bulletin board.Bulletins must be posted to a location and categorised- i'll call these "bulletins".

Users will be able to post any number of replies to any one bulletin and users will be able to reply to their own bulletin - i'll call these 'replies'.

Rating bulletins and replies

Users will be able to either 'like' or 'dislike' a bulletin or a reply and the total number of likes or dislikes will be shown for each bulletin or reply.

Viewing the bulletin board and responses

Bulletins can be displayed chronologically.

 Users can sort bulletins chronologically or chronologically by the latest reply to that bulletin(let me know if you need more explanation)

When a particular bulletin is selected, replies to that bulletin will be displayed chronologically

-- phpMyAdmin SQL Dump
-- version 3.2.4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jan 16, 2011 at 06:44 PM
-- Server version: 5.1.41
-- PHP Version: 5.3.1

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `bulletinboard`
--

-- --------------------------------------------------------

--
-- Table structure for table `bbs`
--

CREATE TABLE IF NOT EXISTS `bbs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bb_locations_id` int(11) NOT NULL,
  `bb_categories_id` int(11) NOT NULL,
  `users_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `content` text NOT NULL,
  `created_date` int(11) NOT NULL,
  `rank` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=87 ;

--
-- Dumping data for table `bbs`
--

INSERT INTO `bbs` (`id`, `bb_locations_id`, `bb_categories_id`, `users_id`, `title`, `content`, `created_date`, `rank`) VALUES
(83, 8, 28, 44, 'sdaf', 'asdfasdf', 1292712797, 0),
(84, 8, 28, 44, 'asdf', 'asdfasd', 1292875089, 0),
(86, 8, 28, 44, 'Robert is leaving', 'Robert is leaving and going back to the states ', 1294344916, 0);

-- --------------------------------------------------------

--
-- Table structure for table `bb_categories`
--

CREATE TABLE IF NOT EXISTS `bb_categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `description` varchar(255) NOT NULL,
  `list_order` varchar(255) NOT NULL,
  `admin` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=30 ;

--
-- Dumping data for table `bb_categories`
--

INSERT INTO `bb_categories` (`id`, `title`, `description`, `list_order`, `admin`) VALUES
(28, 'Travel', 'Rideshares, proposed trips etc', '1', 1);

-- --------------------------------------------------------

--
-- Table structure for table `bb_locations`
--

CREATE TABLE IF NOT EXISTS `bb_locations` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `description` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `post_code` int(11) NOT NULL,
  `list_order` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;

--
-- Dumping data for table `bb_locations`
--

INSERT INTO `bb_locations` (`id`, `title`, `description`, `address`, `post_code`, `list_order`) VALUES
(8, 'Washington DC', 'asdkf', 'dsf', 0, 1);

-- --------------------------------------------------------

--
-- Table structure for table `bb_ratings`
--

CREATE TABLE IF NOT EXISTS `bb_ratings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bbs_id` int(11) NOT NULL,
  `users_id` int(11) NOT NULL,
  `like_id` int(2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=68 ;

--
-- Dumping data for table `bb_ratings`
--

-- --------------------------------------------------------

--
-- Table structure for table `bb_replies`
--

CREATE TABLE IF NOT EXISTS `bb_replies` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `users_id` int(11) NOT NULL,
  `bbs_id` int(11) NOT NULL,
  `content` text NOT NULL,
  `created_date` int(11) NOT NULL,
  `rank` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=158 ;

--
-- Dumping data for table `bb_replies`
--

INSERT INTO `bb_replies` (`id`, `users_id`, `bbs_id`, `content`, `created_date`, `rank`) VALUES
(156, 44, 86, 'good ridance i say\r\n', 1294788444, 0),
(157, 44, 86, 'And stay away\r\n', 1294892751, 0);

-- --------------------------------------------------------

--
-- Table structure for table `bb_reply_ratings`
--

CREATE TABLE IF NOT EXISTS `bb_reply_ratings` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bb_replies_id` int(11) NOT NULL,
  `users_id` int(11) NOT NULL,
  `like_id` tinyint(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=115 ;

--
-- Dumping data for table `bb_reply_ratings`
--

-- --------------------------------------------------------

--
-- Table structure for table `bb_sort_bys`
--

CREATE TABLE IF NOT EXISTS `bb_sort_bys` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(20) NOT NULL,
  `description` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `bb_sort_bys`
--

INSERT INTO `bb_sort_bys` (`id`, `title`, `description`) VALUES
(1, 'Newest', 'Posts are sorted by their creation date'),
(2, 'Popular', 'Posts are sorted by the date of their lates reply, or by post date if they have now replies');

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(10) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `permission` int(1) NOT NULL,
  `bb_sort_bys_id` varchar(10) NOT NULL,
  `bb_locations_csv` varchar(255) NOT NULL,
  `defaultLocation` int(11) NOT NULL,
  `bb_categories_csv` varchar(255) NOT NULL,
  `total_bulletins` int(5) NOT NULL,
  `bulletins_per_page` int(5) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=45 ;

Body:
They key to having an efficient database is to simplify. The main goal of a relational database is not to repeat any information. I took your SQL dump and quickly drafted a simpler version that is normalized, to the best of my knowledge. I did leave some of the fields you had in for cvs's ect. I have removed fields that it would be simpler to just recalculate by querying the db when the information is needed, such as a users total posts and a ranking of a given post. I also removed your bb_replies as you can accomplish the same result with referencing to a parent post. I have renamed the tables slightly to what made sense to me, you can use what ever naming scheme you feel comfortable with. I find that using terms that are simple makes it easier to understand how the data relates to each other.

I must admit that I do agree with some of the comments above, there are plenty of BBs out there that work just fine and would have all the functionality you are looking for. And you are lucky I am in the reading mood tonight lol that was one long question. Simplification is key in everything :)

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';

-- -----------------------------------------------------
-- Table `users`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `users` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `username` VARCHAR(45) NULL ,
  `password` VARCHAR(100) NULL ,
  `email` VARCHAR(255) NULL ,
  `first_name` VARCHAR(100) NULL ,
  `last_name` VARCHAR(100) NULL ,
  `permission` INT NULL ,
  `created` DATETIME NULL ,
  `modified` DATETIME NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `categories`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `categories` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NULL ,
  `description` TEXT NULL ,
  `order` INT NULL ,
  `admin` INT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `locations`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `locations` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NULL ,
  `description` TEXT NULL ,
  `address` TEXT NULL ,
  `order` INT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `posts`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `posts` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `post_id` INT NOT NULL ,
  `user_id` INT NOT NULL ,
  `category_id` INT NOT NULL ,
  `location_id` INT NOT NULL ,
  `title` VARCHAR(45) NULL ,
  `content` TEXT NULL ,
  `created` DATETIME NULL ,
  `modified` DATETIME NULL ,
  PRIMARY KEY (`id`, `post_id`, `user_id`, `category_id`, `location_id`) ,
  INDEX `fk_posts_users` (`user_id` ASC) ,
  INDEX `fk_posts_posts1` (`post_id` ASC) ,
  INDEX `fk_posts_categories1` (`category_id` ASC) ,
  INDEX `fk_posts_locations1` (`location_id` ASC) ,
  CONSTRAINT `fk_posts_users`
    FOREIGN KEY (`user_id` )
    REFERENCES `users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_posts_posts1`
    FOREIGN KEY (`post_id` )
    REFERENCES `posts` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_posts_categories1`
    FOREIGN KEY (`category_id` )
    REFERENCES `categories` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_posts_locations1`
    FOREIGN KEY (`location_id` )
    REFERENCES `locations` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `likes`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `likes` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `user_id` INT NOT NULL ,
  `post_id` INT NOT NULL ,
  `like` TINYINT(1)  NULL ,
  PRIMARY KEY (`id`, `user_id`, `post_id`) ,
  INDEX `fk_posts_users_users1` (`user_id` ASC) ,
  INDEX `fk_posts_users_posts1` (`post_id` ASC) ,
  CONSTRAINT `fk_posts_users_users1`
    FOREIGN KEY (`user_id` )
    REFERENCES `users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_posts_users_posts1`
    FOREIGN KEY (`post_id` )
    REFERENCES `posts` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `sort_options`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `sort_options` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NULL ,
  `description` TEXT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `preferences`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `preferences` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `user_id` INT NOT NULL ,
  `pagination` INT NULL ,
  `sort_option_id` INT NOT NULL ,
  `categories_csv` VARCHAR(45) NULL ,
  `locations_csv` VARCHAR(45) NULL ,
  PRIMARY KEY (`id`, `user_id`, `sort_option_id`) ,
  INDEX `fk_preferences_users1` (`user_id` ASC) ,
  INDEX `fk_preferences_sort_options1` (`sort_option_id` ASC) ,
  CONSTRAINT `fk_preferences_users1`
    FOREIGN KEY (`user_id` )
    REFERENCES `users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_preferences_sort_options1`
    FOREIGN KEY (`sort_option_id` )
    REFERENCES `sort_options` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;


问:
Adding color to Polar Scatter plot data points
I'm trying to make a polar plot with Python, of which I've been somewhat successful so far

polar scatter plot example

I did have a few questions for which I was hoping to get some ideas/suggestions:

is it possible set the color of the circles to a specific value (e.g.: "n" in the sample code below)? If so, can I set specific color ranges? E.g: 0-30: red color, 31-40: yellow; 41-60: green

Note: following the examples from Plot with conditional colors based on values in R, I tried ax.scatter(ra,dec,c = ifelse(n < 30,’red','green'), pch = 19 ) without success =(

how can I make the data circles a little bit bigger?

can I move the "90" label so that the graph title does not overlap? I tried:
x.set_rlabel_position(-22.5) but I get an error ("AttributeError: 'PolarAxes' object has no attribute 'set_rlabel_position'")

Is it possible to only show the 0,30, and 60 elevation labels? Can these be oriented horizontally (e.g.: along the 0 azimuth line)?

Thank you so much! Looking forward to hearing your suggestions =)

```<code>import numpy
import matplotlib.pyplot as pyplot

dec = [10,20,30,40,50,60,70,80,90,80,70,60,50,40,30,20,10]
ra = [225,225,225,225,225,225,225,225,225,45,45,45,45,45,45,45,45]
n = [20,23,36,43,47,48,49,50,51,50,48,46,44,36,30,24,21]

ra = [x/180.0*3.141593 for x in ra]
fig = pyplot.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8],polar=True)
ax.set_ylim(0,90)
ax.set_yticks(numpy.arange(0,90,10))
ax.scatter(ra,dec,c ='r')
ax.set_title("Graph Title here", va='bottom')
pyplot.show()
</code>```

答:
for color you can use c=[list of colors for each element], for size s=
like here:

```<code>ax.scatter(ra,dec,c =['r' if a < 31 else 'yellow' if a < 41 else 'green' for a in n], s =40)
</code>```

for the title and axis I would recommend changing the position of the title:

```<code>ax.set_title("Graph Title here", va='bottom', y=1.08)
</code>```

you may have to adjust the size of the figure to show the title correctly:

```<code>fig = pyplot.figure(figsize=(7,8))
</code>```

for visibility of ticks you can use:

```<code>for label in ax.yaxis.get_ticklabels():
    label.set_visible(False)
for label in ax.yaxis.get_ticklabels()[::3]:
    label.set_visible(True)
</code>```

overall:

```<code>import numpy
import matplotlib.pyplot as pyplot

dec = [10,20,30,40,50,60,70,80,90,80,70,60,50,40,30,20,10]
ra = [225,225,225,225,225,225,225,225,225,45,45,45,45,45,45,45,45]
n = [20,23,36,43,47,48,49,50,51,50,48,46,44,36,30,24,21]

ra = [x/180.0*3.141593 for x in ra]
fig = pyplot.figure(figsize=(7,8))
ax = fig.add_axes([0.1,0.1,0.8,0.8],polar=True)
ax.set_ylim(0,90)
ax.set_yticks(numpy.arange(0,90,10))

ax.scatter(ra,dec,c =['r' if a < 31 else 'yellow' if a < 41 else 'green' for a in n], s =40)
ax.set_title("Graph Title here", va='bottom', y=1.08)
for label in ax.yaxis.get_ticklabels():
    label.set_visible(False)
for label in ax.yaxis.get_ticklabels()[::3]:
    label.set_visible(True)
pyplot.show()
</code>```

Body:
I'm trying to make a polar plot with Python, of which I've been somewhat successful so far

polar scatter plot example

I did have a few questions for which I was hoping to get some ideas/suggestions:

is it possible set the color of the circles to a specific value (e.g.: "n" in the sample code below)? If so, can I set specific color ranges? E.g: 0-30: red color, 31-40: yellow; 41-60: green

Note: following the examples from Plot with conditional colors based on values in R, I tried ax.scatter(ra,dec,c = ifelse(n < 30,’red','green'), pch = 19 ) without success =(

how can I make the data circles a little bit bigger?

can I move the "90" label so that the graph title does not overlap? I tried:
x.set_rlabel_position(-22.5) but I get an error ("AttributeError: 'PolarAxes' object has no attribute 'set_rlabel_position'")

Is it possible to only show the 0,30, and 60 elevation labels? Can these be oriented horizontally (e.g.: along the 0 azimuth line)?

Thank you so much! Looking forward to hearing your suggestions =)

import numpy
import matplotlib.pyplot as pyplot

dec = [10,20,30,40,50,60,70,80,90,80,70,60,50,40,30,20,10]
ra = [225,225,225,225,225,225,225,225,225,45,45,45,45,45,45,45,45]
n = [20,23,36,43,47,48,49,50,51,50,48,46,44,36,30,24,21]

ra = [x/180.0*3.141593 for x in ra]
fig = pyplot.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8],polar=True)
ax.set_ylim(0,90)
ax.set_yticks(numpy.arange(0,90,10))
ax.scatter(ra,dec,c ='r')
ax.set_title("Graph Title here", va='bottom')
pyplot.show()

Body:
for color you can use c=[list of colors for each element], for size s=
like here:

ax.scatter(ra,dec,c =['r' if a < 31 else 'yellow' if a < 41 else 'green' for a in n], s =40)

for the title and axis I would recommend changing the position of the title:

ax.set_title("Graph Title here", va='bottom', y=1.08)

you may have to adjust the size of the figure to show the title correctly:

fig = pyplot.figure(figsize=(7,8))

for visibility of ticks you can use:

for label in ax.yaxis.get_ticklabels():
    label.set_visible(False)
for label in ax.yaxis.get_ticklabels()[::3]:
    label.set_visible(True)

overall:

import numpy
import matplotlib.pyplot as pyplot

dec = [10,20,30,40,50,60,70,80,90,80,70,60,50,40,30,20,10]
ra = [225,225,225,225,225,225,225,225,225,45,45,45,45,45,45,45,45]
n = [20,23,36,43,47,48,49,50,51,50,48,46,44,36,30,24,21]

ra = [x/180.0*3.141593 for x in ra]
fig = pyplot.figure(figsize=(7,8))
ax = fig.add_axes([0.1,0.1,0.8,0.8],polar=True)
ax.set_ylim(0,90)
ax.set_yticks(numpy.arange(0,90,10))

ax.scatter(ra,dec,c =['r' if a < 31 else 'yellow' if a < 41 else 'green' for a in n], s =40)
ax.set_title("Graph Title here", va='bottom', y=1.08)
for label in ax.yaxis.get_ticklabels():
    label.set_visible(False)
for label in ax.yaxis.get_ticklabels()[::3]:
    label.set_visible(True)
pyplot.show()


问:
Deploying a War file to Azure
I am attempting to upload a War file of a web service to Azure, running tomcat 8.

I have the war file in the relevant webapps folder on onedrive, however the deployment consistently fails, and frustratingly it does so without an error message.

I'm pretty sure that if I can't use a method involving uploading the binary file to Azure, I cannot use Azure. When using repositories like github, the build would fail due to reference issues, so I believe that is not an option.

Unfortunately I must use Azure, I'm aware that with other services like AWS I'd be done in 5 minutes as you can directly upload without any Microsoft (tm) hassle.

答:
Quick note that gave me a lot of frustration to figure out. If you use ftp via a client (I use FileZilla for it), think about this:

Place the .war file under: site > wwwroot > webapps > [Place .war file here].

Do also change the .war file name to: ROOT.war

It has to be that name for the system to deploy it. At least for me, the GitHub integration is not working, so I use this ftp method.

The deployment via ftp can take several minutes to be deployed and running.

Title: Deploying a War file to Azure


问:
Joi validation set default as empty object
I'm running into an issue (or what I believe to be one) with Joi validation.  I'm trying to assign a value to a non-existent key if it's been passed as part of the request body.

So for example:

```<code>parameters: Joi.object().keys({
  keyA: Joi.string().allow('').allow(null).default(null),
  keyB: Joi.object().keys({
    b1: Joi.string(),
    b2: Joi.string(),
    b3: Joi.object().keys({
      b3_1: Joi.string(),
      b3_2: Joi.string(),
      b3_3: Joi.string()
    })
  }).default({}),
  keyC: Joi.object().keys({
    c1: Joi.number(),
    c2: Joi.number(),
    c3: Joi.boolean(),
    c4: Joi.boolean()
  }).default({}),
  keyD: Joi.object().keys({
    d1: Joi.number(),
    d2: Joi.number()
  }).default({}),
  keyE: Joi.object().keys({
    e1: Joi.number()
  }).default({})
}).allow(null)
</code>```

So to be specific if I were to pass in:

```<code>{
  keyA: "foo",
  keyD: {
    d1: 21.9,
    d2: 21.1
  },
  keyE: {
    e1: 42
  }
}
</code>```

I would get this in return

```<code>{
  keyA: "foo",
  keyB: {},
  keyC: {},
  keyD: {
    d1: 21.9,
    d2: 21.1
  },
  keyE: {
    e1: 42
  }
}
</code>```

With :eyes: on the empty objects.  What am I missing with the Joi.default() method?  Am I overextending what Joi is meant for?

答:
You can set the default values, you should try this:</p>

```<code>parameters: Joi.object().keys({
  keyA: Joi.string().allow(null).default(null),
  keyB: Joi.object().keys({
    b1: Joi.string().default("abc"),
      b2: Joi.string().default("abc"),
      b3: Joi.object().keys({
        b3_1: Joi.string().default("abc"),
        b3_2: Joi.string().default("abc"),
        b3_3: Joi.string().default("abc")
      })
    })
  }).default({}),
  keyC: Joi.object().keys({
    c1: Joi.number().default(0),
    c2: Joi.number().default(0),
    c3: Joi.boolean().default(0),
    c4: Joi.boolean().default(0)
  }).default({}),
  keyD: Joi.object().keys({
    d1: Joi.number().default(0),
    d2: Joi.number().default(0)
  }).default({}),
  keyE: Joi.object().keys({
    e1: Joi.number().default(0)
  }).default({})
}).allow(null)
</code>```

Body:
I'm running into an issue (or what I believe to be one) with Joi validation.  I'm trying to assign a value to a non-existent key if it's been passed as part of the request body.

So for example:

parameters: Joi.object().keys({
  keyA: Joi.string().allow('').allow(null).default(null),
  keyB: Joi.object().keys({
    b1: Joi.string(),
    b2: Joi.string(),
    b3: Joi.object().keys({
      b3_1: Joi.string(),
      b3_2: Joi.string(),
      b3_3: Joi.string()
    })
  }).default({}),
  keyC: Joi.object().keys({
    c1: Joi.number(),
    c2: Joi.number(),
    c3: Joi.boolean(),
    c4: Joi.boolean()
  }).default({}),
  keyD: Joi.object().keys({
    d1: Joi.number(),
    d2: Joi.number()
  }).default({}),
  keyE: Joi.object().keys({
    e1: Joi.number()
  }).default({})
}).allow(null)

So to be specific if I were to pass in:

{
  keyA: "foo",
  keyD: {
    d1: 21.9,
    d2: 21.1
  },
  keyE: {
    e1: 42
  }
}

I would get this in return

{
  keyA: "foo",
  keyB: {},
  keyC: {},
  keyD: {
    d1: 21.9,
    d2: 21.1
  },
  keyE: {
    e1: 42
  }
}

With :eyes: on the empty objects.  What am I missing with the Joi.default() method?  Am I overextending what Joi is meant for?

Body:
You can set the default values, you should try this:

parameters: Joi.object().keys({
  keyA: Joi.string().allow(null).default(null),
  keyB: Joi.object().keys({
    b1: Joi.string().default("abc"),
      b2: Joi.string().default("abc"),
      b3: Joi.object().keys({
        b3_1: Joi.string().default("abc"),
        b3_2: Joi.string().default("abc"),
        b3_3: Joi.string().default("abc")
      })
    })
  }).default({}),
  keyC: Joi.object().keys({
    c1: Joi.number().default(0),
    c2: Joi.number().default(0),
    c3: Joi.boolean().default(0),
    c4: Joi.boolean().default(0)
  }).default({}),
  keyD: Joi.object().keys({
    d1: Joi.number().default(0),
    d2: Joi.number().default(0)
  }).default({}),
  keyE: Joi.object().keys({
    e1: Joi.number().default(0)
  }).default({})
}).allow(null)


问:
Possible to create new variable with new name upon button onclick?
I was wondering if it was possible to create a new variable when a button is pressed. For example: if I have a variable named enemy1 and the button is pressed, Can a variable named enemy2 be created? I'm sorry if this seems like a silly question.  I wanted to create a for loop where I can define a variable thats name changes depending on 'i'. </p>

答:
You do not require dynamic variable, instead you need one variable that would contain dynamic size (dynamic number of enemies). Following is the code you need. Here you can see demo

```<code>    <button id='createEnemy' onclick='addEnenemy()'>Add Enenmy</button>
    <div id='enemiesContainer'> </div>
    <script>
        var enemies = [];
        var enemyDiv = document.getElementById('enemiesContainer');
        function addEnenemy() {
           var newEnenmy = 'enemy'+(enemies.length+1);
           enemies.push(newEnenmy);
           //following will show it in your page
           enemyDiv.innerHTML = enemyDiv.innerHTML + '<br/><label>'+newEnenmy+'</label>';
           console.log(enemies); //shows in console
        }
    </script>
</code>```

Body:
You do not require dynamic variable, instead you need one variable that would contain dynamic size (dynamic number of enemies). Following is the code you need. Here you can see demo

    <button id='createEnemy' onclick='addEnenemy()'>Add Enenmy</button>
    <div id='enemiesContainer'> </div>
    <script>
        var enemies = [];
        var enemyDiv = document.getElementById('enemiesContainer');
        function addEnenemy() {
           var newEnenmy = 'enemy'+(enemies.length+1);
           enemies.push(newEnenmy);
           //following will show it in your page
           enemyDiv.innerHTML = enemyDiv.innerHTML + '<br/><label>'+newEnenmy+'</label>';
           console.log(enemies); //shows in console
        }
    </script>


问:
Convert optional string to double in Swift 3

I have a option string and want to convert  that to double.

this worked in Swift 2 , but since converted to Swift 3, I am getting value of 0.

```<code>var dLati = 0.0
dLati = (latitude as NSString).doubleValue
</code>```

I have check and latitude has a optional string value of something like -80.234543218675654 , but dLati value is 0

*************** ok, new update for clarity *****************

I have a viewcontroller which i have a button in it, and when the button is touched, it will call another viewcontroller and pass a few values to it
here is the code for the first viewcontroller

```<code>var currentLatitude: String? = ""
var currentLongitude: String? = ""
var deviceName = ""
var address = ""
// somewhere in the code, currentLatitude and currentLongitude are get set
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "map" {
       let destViewController : MapViewController = segue.destination as! MapViewController
       print(currentLongitude!)  // Print display: Optional(-80.192279355363768)
       print(currentLatitude!) // Print display: Optional(25.55692663937162)
       destViewController.longitude = currentLongitude!
       destViewController.latitude = currentLatitude!
       destViewController.deviceName = deviceName
       destViewController.address = address
    }
}
</code>```

Here is the code for the second view controller called MapViewController

```<code>   var longitude: String? = " "
   var latitude: String? = ""
   .
   .
   override func viewDidLoad() {
       if let lat = latitude {
          print(lat) // Print display: optiona(25.55692663937162)
          dLati = (lat as NSString).doubleValue
          print(dLati)  // Print display: 0.0
       }
       .
       .
   }
</code>```

Thanks
Borna

答:
In swift 3.1, we can combine extensions and Concrete Constrained Extensions

```<code>extension Optional where Wrapped == String
{
    var asDouble: Double
    {
        return NSString(string: self ?? "").doubleValue
    }
}
</code>```

Or

```<code>extension Optional where Wrapped == String
{
        var asDouble: Double
        {
            return Double(str ?? "0.00") ?? 0.0
        }
}
</code>```

Body:
I have a option string and want to convert  that to double.

this worked in Swift 2 , but since converted to Swift 3, I am getting value of 0.

var dLati = 0.0
dLati = (latitude as NSString).doubleValue

I have check and latitude has a optional string value of something like -80.234543218675654 , but dLati value is 0

*************** ok, new update for clarity *****************

I have a viewcontroller which i have a button in it, and when the button is touched, it will call another viewcontroller and pass a few values to it
here is the code for the first viewcontroller

var currentLatitude: String? = ""
var currentLongitude: String? = ""
var deviceName = ""
var address = ""
// somewhere in the code, currentLatitude and currentLongitude are get set
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "map" {
       let destViewController : MapViewController = segue.destination as! MapViewController
       print(currentLongitude!)  // Print display: Optional(-80.192279355363768)
       print(currentLatitude!) // Print display: Optional(25.55692663937162)
       destViewController.longitude = currentLongitude!
       destViewController.latitude = currentLatitude!
       destViewController.deviceName = deviceName
       destViewController.address = address
    }
}

Here is the code for the second view controller called MapViewController

   var longitude: String? = " "
   var latitude: String? = ""
   .
   .
   override func viewDidLoad() {
       if let lat = latitude {
          print(lat) // Print display: optiona(25.55692663937162)
          dLati = (lat as NSString).doubleValue
          print(dLati)  // Print display: 0.0
       }
       .
       .
   }

Thanks
Borna

Body:
In swift 3.1, we can combine extensions and Concrete Constrained Extensions

extension Optional where Wrapped == String
{
    var asDouble: Double
    {
        return NSString(string: self ?? "").doubleValue
    }
}

Or

extension Optional where Wrapped == String
{
        var asDouble: Double
        {
            return Double(str ?? "0.00") ?? 0.0
        }
}


答: Dont be afraid of joins. If i were you i would cut down on all the DB logic you need to write and use an ORM like Doctrine or Propel, it will make things infinitely easier to design and maintain - including all those joins youre trying to avoid.</p>

Title: Bulletin board - Database optimisation


问:
Issue In Firebase Custom Authentication And Service Account
Ok, so first of all I am not very much an expert in both java or android, in fact I am just beginner. So if anything sounds silly or irritating pardon me, I am on the verge of being blocked from asking any questions.

So, my issue is that while authenticating my server with firebase, I am facing some trouble while setting service account and creating custom token.

https://firebase.google.com/docs/admin/setup

https://firebase.google.com/docs/auth/admin/create-custom-tokens

I am taking help from here and following these steps, and this is what i have done.

```<code>FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");

FirebaseOptions options = new FirebaseOptions.Builder()
  .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
  .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
  .build();

FirebaseApp.initializeApp(options);

FirebaseAuth.getInstance()
            .createCustomToken(uid)
            .addOnSuccessListener(new OnSuccessListener<String>() {

    @Override
    public void onSuccess(String customToken)
    {
        // Send token back to client
    }
});
</code>```

But I am getting very unusual errors, i.e.

1) On service account - The method setCredential(FirebaseCredential) is undefined for the type FirebaseOptions.Builder

Now I've read that setserviceaccount is deprecated, but when i am using it, its not giving me any error

2) On Creating Custom Token - The method addOnSuccessListener(new OnSuccessListener<String>(){}) is undefined for the type String

It is another method error, and also I don't know how to send the token back to client. I couldn't find any example that how should i approach it. Any help will be greatly appreciated.

Any example that how others send there token to client, would be great.

答: Ok, so finally i have solved the issue,the issue was that in my pom.xml I was also using (Firebase Server SDK Library » 3.0.3)maven repository. And thats why there were method issues. </p>

Body:
Ok, so first of all I am not very much an expert in both java or android, in fact I am just beginner. So if anything sounds silly or irritating pardon me, I am on the verge of being blocked from asking any questions.

So, my issue is that while authenticating my server with firebase, I am facing some trouble while setting service account and creating custom token.

https://firebase.google.com/docs/admin/setup

https://firebase.google.com/docs/auth/admin/create-custom-tokens

I am taking help from here and following these steps, and this is what i have done.

FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");

FirebaseOptions options = new FirebaseOptions.Builder()
  .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
  .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
  .build();

FirebaseApp.initializeApp(options);

FirebaseAuth.getInstance()
            .createCustomToken(uid)
            .addOnSuccessListener(new OnSuccessListener<String>() {

    @Override
    public void onSuccess(String customToken)
    {
        // Send token back to client
    }
});

But I am getting very unusual errors, i.e.

1) On service account - The method setCredential(FirebaseCredential) is undefined for the type FirebaseOptions.Builder

Now I've read that setserviceaccount is deprecated, but when i am using it, its not giving me any error

2) On Creating Custom Token - The method addOnSuccessListener(new OnSuccessListener<String>(){}) is undefined for the type String

It is another method error, and also I don't know how to send the token back to client. I couldn't find any example that how should i approach it. Any help will be greatly appreciated.

Any example that how others send there token to client, would be great.


问:
JS setTimeout not firing on onclick
I have been using this for a odometer on my site
http://github.hubspot.com/odometer/ , it is great but i can not seem to get it t o be able to work on a button onclick action.  it will only work when page is loaded.  i have tried to add to other functions like a simple window.alert the alert will work but it wont initiate the  setTimeOUt

here is my latest code:

```<code><script>

function playSound() {

    setTimeout(function(){

    var audio = new Audio('sounds/machine-002-short.mp3');
    var audio2 = new Audio('sounds/coin-drop-4.mp3');

    audio.play();
    audio.volume = 0.65;
    audio.currentTime = 0.90;

    audio2.pause();
    audio.addEventListener("ended", function() {
    audio2.play();
    audio2.volume = 1.5;

        }); // event listener

    $('.odometer').html(<?php echo $Display;?>);
  }, 1000);
}
</script>
</code>```

and the button:

```<code><button id="submit" type="submit" type="button" name="roll" onclick="playSound();">Start</button>
</code>```

if i just add a winow.alert it works just not with this set time out,  im very inexperienced in JS  so i am sure it is something simple

答:
a button can submit (type=submit - default) or not (type=button)

If you need to submit the form, you cannot submit until after the setTimeout has run

if the textarea is .odometer, use .val() instead of .html()

Perhaps you do NOT want to submit the form, but instead AJAX in the content of the action. Like this:

function getContent() {
  $.get($("#form1").prop("action", {data:$("#odometer").val()},function(data) {
     $('#odometer').val(data); // here we replace the $Display with what is returned
  });
}
function playSound() {

  setTimeout(function() {

    var audio = new Audio('sounds/machine-002-short.mp3');
    var audio2 = new Audio('sounds/coin-drop-4.mp3');

    audio.play();
    audio.volume = 0.65;
    audio.currentTime = 0.90;

    audio2.pause();
    audio.addEventListener("ended", function() {
      audio2.play();
      audio2.volume = 1.5;
      getContent();
    }); // event listener

    $('#odometer').val(<?php echo $Display;?>);
  }, 1000);
}
```

<pre class="lang-html prettyprint-override"><code><form id="form1" action="somefile.php">
  <textarea id="odometer"></textarea>
  <button type="button" id="but">Start</button>
</form>
</code>```

Title: JS setTimeout not firing on onclick

Body:
I have been using this for a odometer on my site
http://github.hubspot.com/odometer/ , it is great but i can not seem to get it t o be able to work on a button onclick action.  it will only work when page is loaded.  i have tried to add to other functions like a simple window.alert the alert will work but it wont initiate the  setTimeOUt

here is my latest code:

and the button:

<button id="submit" type="submit" type="button" name="roll" onclick="playSound();">Start</button>

if i just add a winow.alert it works just not with this set time out,  im very inexperienced in JS  so i am sure it is something simple

Body:
a button can submit (type=submit - default) or not (type=button)

If you need to submit the form, you cannot submit until after the setTimeout has run

if the textarea is .odometer, use .val() instead of .html()

Perhaps you do NOT want to submit the form, but instead AJAX in the content of the action. Like this:

function getContent() {
  $.get($("#form1").prop("action", {data:$("#odometer").val()},function(data) {
     $('#odometer').val(data); // here we replace the $Display with what is returned
  });
}
function playSound() {

  setTimeout(function() {

    var audio = new Audio('sounds/machine-002-short.mp3');
    var audio2 = new Audio('sounds/coin-drop-4.mp3');

    audio.play();
    audio.volume = 0.65;
    audio.currentTime = 0.90;

    audio2.pause();
    audio.addEventListener("ended", function() {
      audio2.play();
      audio2.volume = 1.5;
      getContent();
    }); // event listener

    $('#odometer').val(<?php echo $Display;?>);
  }, 1000);
}

<form id="form1" action="somefile.php">
  <textarea id="odometer"></textarea>
  <button type="button" id="but">Start</button>
</form>


问:
AlertDialog within an element of an Array
I have the following question, results that I have an adapter class
In which it shows a list of elements (which may have photographs)

Examples

Array [0] Contains a photo

Array 1 Does not contain a photo

Array 2 Contains a photo

My question is how can I display aDialog alert inside Array 1?

He tried, set the alertDialog, but it is always placed twice inside the Array in the position [0]
I just wish I could display theDialog alert at the Array position 1

Could anyone help me please.

```<code>displayImage = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
</code>```

final ChatMessage myMessage = pathsLocal.get(position);

```<code>        AttachmentObject attachmentObject = null;
        switch (myMessage.getMessageType()) {
            case IMAGE:
                attachmentObject = myMessage.getFullsizePhoto();
                break;
            case VIDEO:
                attachmentObject = myMessage.getAttachment("video");
                break;
        }

            File fileImage = new File(attachmentObject.localPath);

            if (fileImage.exists()) {
                Uri uri = Uri.fromFile(fileImage);

                Picasso.with(ApplicationSingleton.getInstance())
                        .load(uri)
                        .into(displayImage);
            } else {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(activityAdapter);
                alertDialog.setTitle(R.string.title);
                alertDialog.setMessage(R.string.subtitle);
                alertDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
                AlertDialog alertDialogBuilder1 = alertDialog.create();
                alertDialog.show();
            }
        }
</code>```

What I am trying to do is just an AlertDialog entry within position 1 without affecting element 0 and 2 of the viewPager

I'm just trying to add an AlertDialog to position 1 of the viewPager element

答:
Don't create or show your AlertDialogs when creating the ViewPager pages, instead you should check if you need an AlertDialog when a page is selected, and then build and show the dialog, using ViewPager.OnPageChangeListener or ViewPager.SimpleOnPageChangeListener

```<code>myViewPager.addOnPageChangeListener(new SimpleOnPageChangeListener() {
   void onPageSelected(int position) {
      boolean shouldIShowAlert = // implement this
      if (shouldIShowAlert) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(activityAdapter);
                alertDialog.setTitle(R.string.title);
                alertDialog.setMessage(R.string.subtitle);
                alertDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
                AlertDialog alertDialogBuilder1 = alertDialog.create();
                alertDialog.show();
      }
   }
});
</code>```

Body:
I have the following question, results that I have an adapter class
In which it shows a list of elements (which may have photographs)

Examples

Array [0] Contains a photo

Array 1 Does not contain a photo

Array 2 Contains a photo

My question is how can I display aDialog alert inside Array 1?

He tried, set the alertDialog, but it is always placed twice inside the Array in the position [0]
I just wish I could display theDialog alert at the Array position 1

Could anyone help me please.

displayImage = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);

final ChatMessage myMessage = pathsLocal.get(position);

        AttachmentObject attachmentObject = null;
        switch (myMessage.getMessageType()) {
            case IMAGE:
                attachmentObject = myMessage.getFullsizePhoto();
                break;
            case VIDEO:
                attachmentObject = myMessage.getAttachment("video");
                break;
        }

            File fileImage = new File(attachmentObject.localPath);

            if (fileImage.exists()) {
                Uri uri = Uri.fromFile(fileImage);

                Picasso.with(ApplicationSingleton.getInstance())
                        .load(uri)
                        .into(displayImage);
            } else {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(activityAdapter);
                alertDialog.setTitle(R.string.title);
                alertDialog.setMessage(R.string.subtitle);
                alertDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
                AlertDialog alertDialogBuilder1 = alertDialog.create();
                alertDialog.show();
            }
        }

What I am trying to do is just an AlertDialog entry within position 1 without affecting element 0 and 2 of the viewPager

I'm just trying to add an AlertDialog to position 1 of the viewPager element

Body:
Don't create or show your AlertDialogs when creating the ViewPager pages, instead you should check if you need an AlertDialog when a page is selected, and then build and show the dialog, using ViewPager.OnPageChangeListener or ViewPager.SimpleOnPageChangeListener

myViewPager.addOnPageChangeListener(new SimpleOnPageChangeListener() {
   void onPageSelected(int position) {
      boolean shouldIShowAlert = // implement this
      if (shouldIShowAlert) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(activityAdapter);
                alertDialog.setTitle(R.string.title);
                alertDialog.setMessage(R.string.subtitle);
                alertDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
                AlertDialog alertDialogBuilder1 = alertDialog.create();
                alertDialog.show();
      }
   }
});


问:
Use REGEX to find line breaks within a wrapped content
The direct question: How can I use REGEX lookarounds to find instances of \r\n that occur between a set of characters (stand in open and closing tags), "[ and ]" with arbitrary characters and line breaks inside as well?

The situation:

I have a large database exported to tab or comma delineated text files that I'm trying to import into excel. The problem is that some of the cells come from text areas that contain line breaks, and are qualified by double quotes. Importing into excel these line breaks are treated as new rows. I cannot adjust how the file is exported. I data needs to be preserved, but the exact format doesn't, so I was planning on using some placeholder for the returns
 or ~

Here's a generic illustration of the format of my data:

```<code>column1rowA    column2rowA    column3rowA    column4rowA
column1rowB    column2rowB   "column3rowB
3Bcont
3Bcont
3Bcont

"    column4rowB
column1rowC    column2rowC                   column4rowC
column1rowD    column2rowD   "column3rowD
3Dcont"    column4rowD
</code>```

My thought has been to try to select and replace line breaks within the quotes using REGEX search and replace in Notepad++. To try and make is simpler I have tried adding a character to the double quotes to help indicate whether it is an opening or closing quote:

```<code>"[column3rowB
3Bcont
3Bcont
3Bcont

]"
</code>```

I am new to REGEX. The progress I've made (which isn't much) is:

(?<="[) missing some sort of wildcard \r\n(?=.*]")

Every iteration I've tried has also included every line break between the first "[ and last ]"

I would also appreciate any other approaches that solve the underlying problem

答:
Great answer from Brian. I added an option that would only consider real linebreaks (i.e. \n\r), which worked for my CSV file:</p>

```<code>(?!\n|\r(([^"]*"){2})*[^"]*$)\n|\r
</code>```

Body:
The direct question: How can I use REGEX lookarounds to find instances of \r\n that occur between a set of characters (stand in open and closing tags), "[ and ]" with arbitrary characters and line breaks inside as well?

The situation:

I have a large database exported to tab or comma delineated text files that I'm trying to import into excel. The problem is that some of the cells come from text areas that contain line breaks, and are qualified by double quotes. Importing into excel these line breaks are treated as new rows. I cannot adjust how the file is exported. I data needs to be preserved, but the exact format doesn't, so I was planning on using some placeholder for the returns
 or ~

Here's a generic illustration of the format of my data:

column1rowA    column2rowA    column3rowA    column4rowA
column1rowB    column2rowB   "column3rowB
3Bcont
3Bcont
3Bcont

"    column4rowB
column1rowC    column2rowC                   column4rowC
column1rowD    column2rowD   "column3rowD
3Dcont"    column4rowD

My thought has been to try to select and replace line breaks within the quotes using REGEX search and replace in Notepad++. To try and make is simpler I have tried adding a character to the double quotes to help indicate whether it is an opening or closing quote:

"[column3rowB
3Bcont
3Bcont
3Bcont

]"

I am new to REGEX. The progress I've made (which isn't much) is:

(?<="[) missing some sort of wildcard \r\n(?=.*]")

Every iteration I've tried has also included every line break between the first "[ and last ]"

I would also appreciate any other approaches that solve the underlying problem

Body:
Great answer from Brian. I added an option that would only consider real linebreaks (i.e. \n\r), which worked for my CSV file:

(?!\n|\r(([^"]*"){2})*[^"]*$)\n|\r


问:
5 input and 3 output features for machine learning
Need some advise here.

I am trying to build a model where it can predict the 3 different output features when 5 input features are given.

for example,
5 input features: size of the house, house floor, house condition, number of rooms, parking.
3 output features: price for selling, price for buying,  price for renting

What I am confusing right now is that, is that possible that the trained model are able to predict the 3 outputs? What I found from others' example/tutorial is that they mostly trying to do one thing only on their model.

Sorry if my explanations are bad, I am new to tensorflow and machine learning.

答:
In common practice, we build a model to predict only one output, that is because in surpervised learning, we should input some certain kinds of variables, and find a relation between them with a wanted output. Because this relation generally cannot work between the input and another wanted output.

But we can have a special technique to fit your problem:

If we have four input variables : I1, I2, I3, I4, and we want three output lables (generally discrete): O1, O2, O3. so we can created a new lable O4 after mergering the original three outputs. For example, if O1, O2, O3 can onlt be 0 or 1, the O4 have 2^3, in total, 8 possible values. So, we can build a prediction model between four input variables and the output O4. And once value of O4 is known, O1-O3 are all known as well.

Howover, if the output variable are not all discrete, especially regression technique is used, the technique above wonnot work. So, to predict three output, we normally do training three times and make three models.


问:
Simple Math with JS
Hello I need a quick hand, I have this div below

$1500

I need to do some simple math with that amount I need to divide it in half, then divide it by 6 and display the result like below.

Pay as low as $"result here"

I am a graphic designer I need this for a webpage and I know this should be simple but I just can't figure it out I really appreciate any help here.

答:
You can achieve this as below mentioned.

$(document).ready(function(){
 var price = $(".price").text(),
     price = price.replace('$', '');
     finalPrice = (price/2).toFixed(2);

$(".final-price").text(finalPrice/6);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<br> <br>

<div class="payment">Pay as low as $<span class="final-price"></span> </div></code>```

Title: Simple Math with JS

Body:
You can achieve this as below mentioned.

$(document).ready(function(){
 var price = $(".price").text(),
     price = price.replace('$', '');
     finalPrice = (price/2).toFixed(2);

$(".final-price").text(finalPrice/6);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<br> <br>

<div class="payment">Pay as low as $<span class="final-price"></span> </div>


问:
JSF 2 : Accessing managed bean's instance in the phase listener object?
Is it possible to get a reference to the to-be-executed managedbean in the before-invokeApplication-phaselistener ?

Before the invoke application phase, it should be clear which managedBean that is going to execute the method.

For the sake of the example, assume there's 1 main manage bean to handle 1 jsf page.

So what i need is basically :

The user access the program from the menu

Because it's accessed from the menu, the main manage bean's init() method gets called to initialize stuffs like preparing data, doing authorization checks

Subsequent submits dont need to call the init() method anymore until it's reaccessed from the menu

To implement the point #2, im thinking of intercepting one of the phases

I've checked the API docs about getting the managed bean in the phases implementation, but i couldnt seem to find any.

After typing this question, i realize i could do this in @PostConstruct or the managed bean's constructor, but that would do only at the first time the bean is constructed, and my need is to call the method everytime the jsf is being accessed from the menu.

Any suggestions ?

Regards,

Albert Kam

答:
You can access your managed beans via the ELContext/ELResolver.  This is explained nicely in the MyFaces wiki (also works in vanilla JSF).

For example:

```<code>ELContext elContext = FacesContext.getCurrentInstance().getELContext();
NeededBean neededBean = (NeededBean) FacesContext.getCurrentInstance().getApplication()
    .getELResolver().getValue(elContext, null, "neededBean");
</code>```

See the MyFaces wiki entry for further explanation, and implementations for other JSF versions.

Your idea of using @PostConstruct is a good one.  Consider changing your scope to something liked @ViewScoped, so the logic is executed everytime you navigate to that view.

Also, have a look at the PreRenderViewEvent (for JSF 2).  This code is embedded in your facelet page:

```<code><f:metadata>
<f:viewParam name="foo" value="#{bean.foo}"/>
<f:event type="preRenderView" listener="#{bean.doSomething}"/>
</f:metadata>
</code>```

The f:event listener is executed before every page view.

Body:
You can access your managed beans via the ELContext/ELResolver.  This is explained nicely in the MyFaces wiki (also works in vanilla JSF).

For example:

ELContext elContext = FacesContext.getCurrentInstance().getELContext();
NeededBean neededBean = (NeededBean) FacesContext.getCurrentInstance().getApplication()
    .getELResolver().getValue(elContext, null, "neededBean");

See the MyFaces wiki entry for further explanation, and implementations for other JSF versions.

Your idea of using @PostConstruct is a good one.  Consider changing your scope to something liked @ViewScoped, so the logic is executed everytime you navigate to that view.

Also, have a look at the PreRenderViewEvent (for JSF 2).  This code is embedded in your facelet page:

<f:metadata>
<f:viewParam name="foo" value="#{bean.foo}"/>
<f:event type="preRenderView" listener="#{bean.doSomething}"/>
</f:metadata>

The f:event listener is executed before every page view.


问:
Multiline label in UIStackView
When putting multiline label (with linebreak set to Word Wrap) into a stack view, the label immediately loses the linebreak and displays the label text in one line instead.

Why is this happening and how does one preserve multiline label within a stack view?

答:
For a horizontal stack view that has a UILabel as one of its views, in Interface Builder firstly set label.numberOfLines = 0. This should allow the label to have more than 1 line. This initially failed to work for me when the stack view had stackView.alignment = .fill. To make it work simply set stackView.alignment = .center. The label can now expand to multiple lines within the UIStackView.

The Apple documentation says

For all alignments except the fill alignment, the stack view uses each
arranged view’s intrinsicContentSize property when calculating its
size perpendicular to the stack’s axis

Note the word except here. When .fill is used, the horizontal UIStackView does NOT resize itself vertically using the arranged subviews' sizes.

Title: Multiline label in UIStackView

ContentLicense: CC BY-SA 4.0


问:
How to redirect oldblog.com/any-post.html to newblog.com/any-post.html in blogger
I have set custom domain on my blogger account bow I need to change my blog domain again without losing seo. How can I redirect my oldblog.com/any-post.html to newblog.com/any-post.html. I can redirect my oldblog.com to newblog.com but can't redirect post URLs like oldblog.com/any-post.html to newblog.com/any-post.html. please help I stuck here</p>

答:
Yes you can do it, you need to contact with your domain providers. Ask them to update your DNS settings. You need to update following I.ps in the A-section:

```<code>216.239.32.21
216.239.34.21
216.239.36.21
216.239.38.21
</code>```

Also other changes should be made which you have in that file which was downloaded when you were connecting your domain to your blog.

The conclusion is you need to make changes in DNS of your domain and set it to redirect your old domain URLS to new domain URLs.

Here is a post which may help you. https://support.google.com/blogger/answer/1233387?visit_id=1-636264533431348716-1244965263&p=customdomain&hl=en&rd=2

Body:
Yes you can do it, you need to contact with your domain providers. Ask them to update your DNS settings. You need to update following I.ps in the A-section:

216.239.32.21
216.239.34.21
216.239.36.21
216.239.38.21

Also other changes should be made which you have in that file which was downloaded when you were connecting your domain to your blog.

The conclusion is you need to make changes in DNS of your domain and set it to redirect your old domain URLS to new domain URLs.

Here is a post which may help you. https://support.google.com/blogger/answer/1233387?visit_id=1-636264533431348716-1244965263&p=customdomain&hl=en&rd=2


问:
ANTLR LEXER RULE to have two rules, one will accept every characters including symbols and another will accept only characters
Is it possible in ANTLR LEXER RULE to have two rules, one will accept every characters including all symbols(like (,),_ etc) and another will accept only characters a to z?

Something like below:

```<code>String: ('a'..'z'|'A'..'Z')*;
EVERYTHING:(.)*;
</code>```

答:
Yes, it is possible.

This is how ANTLR lexer decides which rule to use:
- whichever rule can match the longest sub-sequence of the input (starting form current position in the input)
- in case more rules can match this sub-sequence (i.e. it's a tie), the first rule (as defined in the grammar file) wins

So in your case, for alpha-only input, both rules will match it, but since String is further up in the grammar, it will be used. In case of non-alpha input, the EVERYTHING rule will be able to match a longer sub-sequence and therefore will be used.

Note however that as it's written, your EVERYTHING rule matches even spaces and newlines, so in this specific case String rule will be used only if the whole input is just alpha characters and nothing else; whole input will be matched as a single token in either case. So in real grammar, the EVERTYHING rule will be probably slightly different.

Body:
Is it possible in ANTLR LEXER RULE to have two rules, one will accept every characters including all symbols(like (,),_ etc) and another will accept only characters a to z?

Something like below:

String: ('a'..'z'|'A'..'Z')*;
EVERYTHING:(.)*;


问:
Angular 2 - multiple HTTP POST request : handle error from each request
I am looking for a way where in i can post multiple HTTP POST requests and just in case there is error on one or more of them then i can know which of those got the error.

I tried implementing many logic via observables but no success. Please suggest.

答:
You could use Promises

```<code>for all requestItems {
    http.post(url, body).toPromise().catch(error => {
       // This request failed.
    })
}
</code>```

or if you want to wait for all to finish, you can collect the promises to an array and then use

```<code>Promise.all(promises)
    .catch(error => ...)
    .then(results => ...);
</code>```

as can be seen in Handling errors in Promise.all

Edit:

You can use Promise.all this way:

```<code>// Create an array of your promises
const promises = [...];
const resolvedPromises = [];
promises.forEach(promise => {
    // Collect resolved promises - you may return some values from then and catch
    resolvedPromises.push(promise
        .then(result => 'OK')
        .catch(error => 'Error')
    );
});
Promise.all(resolvedPromises).then(results => {
    // results contains values returned from then/catch before
    console.log('Finished');
})
</code>```

Body:
You could use Promises

for all requestItems {
    http.post(url, body).toPromise().catch(error => {
       // This request failed.
    })
}

or if you want to wait for all to finish, you can collect the promises to an array and then use

Promise.all(promises)
    .catch(error => ...)
    .then(results => ...);

as can be seen in Handling errors in Promise.all

Edit:

You can use Promise.all this way:

// Create an array of your promises
const promises = [...];
const resolvedPromises = [];
promises.forEach(promise => {
    // Collect resolved promises - you may return some values from then and catch
    resolvedPromises.push(promise
        .then(result => 'OK')
        .catch(error => 'Error')
    );
});
Promise.all(resolvedPromises).then(results => {
    // results contains values returned from then/catch before
    console.log('Finished');
})


问:
What should be a component?
I am struggling with myself about what needs to be a component?

For example:

I have a page where everything within is relevant only to itself.

I have a text input on every form control; Do I need to wrap this in a component? But every place will need a different kind of validation and other stuff related only to it, so why do this?

Usually, when it comes to forms, only the style is the same so why we need to wrap this in a component? We can just share the style with CSS.

答:
The tl;dr; is that a component is a reusable, encapsulated piece. It's similar to Brad Frost's Atomic Design. This is not rocket science, different people may split their apps into different components.

That said, there are more than enough tutorials/articles that will help you to understand when to create a component. To get you started:

https://medium.com/@rajaraodv/step-by-step-guide-to-building-react-redux-apps-using-mocks-48ca0f47f9a

https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0

Title: What should be a component?


问:
Input won't trim
Brand new to this but I'm not sure what I am doing wrong as the output will not trim.</p>

```<code>package cs520.hw3.part1;

import javax.swing.JOptionPane;

public class StringTest {

    public static void main(String[] args) {

        String input = JOptionPane.showInputDialog("Enter data using the format Name, Age, City");
        //String delimiter = ",";
        //String[] tokens = input.split(delimiter);
        System.out.println(input.trim());
    }
}
</code>```

答:
There is a difference between removing the leading & trailing spaces (using trim() and replacing all spaces from a String (using replaceAll(" ", ""))

Example output

```<code>' Andrew,      52,  Sydney         '
'Andrew,      52,  Sydney'
'Andrew,52,Sydney'
</code>```

Raw String

trim()

replaceAll(" ", "")

Code

```<code>import javax.swing.*;

public class TrimSpace {

    TrimSpace() {
        String s = JOptionPane.showInputDialog(null,
                "Name, Age, City",
                "Person Details",
                JOptionPane.QUESTION_MESSAGE);
        // show the raw string entered by user
        System.out.println(String.format("'%1s'", s));
        // remove leading & trailing space from string
        System.out.println(String.format("'%1s'", s.trim()));
        // remove all spaces from string
        System.out.println(String.format("'%1s'", s.replaceAll(" ", "")));
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new TrimSpace();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
</code>```

Title: Input won't trim

Body:
Brand new to this but I'm not sure what I am doing wrong as the output will not trim.

package cs520.hw3.part1;

import javax.swing.JOptionPane;

public class StringTest {

    public static void main(String[] args) {

        String input = JOptionPane.showInputDialog("Enter data using the format Name, Age, City");
        //String delimiter = ",";
        //String[] tokens = input.split(delimiter);
        System.out.println(input.trim());
    }
}

Body:
There is a difference between removing the leading & trailing spaces (using trim() and replacing all spaces from a String (using replaceAll(" ", ""))

Example output

' Andrew,      52,  Sydney         '
'Andrew,      52,  Sydney'
'Andrew,52,Sydney'

Raw String

trim()

replaceAll(" ", "")

Code

import javax.swing.*;

public class TrimSpace {

    TrimSpace() {
        String s = JOptionPane.showInputDialog(null,
                "Name, Age, City",
                "Person Details",
                JOptionPane.QUESTION_MESSAGE);
        // show the raw string entered by user
        System.out.println(String.format("'%1s'", s));
        // remove leading & trailing space from string
        System.out.println(String.format("'%1s'", s.trim()));
        // remove all spaces from string
        System.out.println(String.format("'%1s'", s.replaceAll(" ", "")));
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new TrimSpace();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}


问:
Use PowerShell to stop 'Default Web Site' in IIS6
I've done several Google searches and can't find a good sample to stop/start the 'Default Web Site' (in II6) using PowerShell.

This...

```<code>$server = "localhost"
$siteName = "default web site"
$iis = [ADSI]"IIS://$server/W3SVC"
$site = $iis.psbase.children | where { $_.keyType -eq "IIsWebServer"
        -AND $_.ServerComment -eq $siteName }
</code>```

from here got me started, but I can't get the 'start'/'stop' syntax right.

答: http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true. The example is in VBScript, but it's exactly the same technique in PowerShell.</p>

OwnerDisplayName: MattH

Body:
I've done several Google searches and can't find a good sample to stop/start the 'Default Web Site' (in II6) using PowerShell.

This...

$server = "localhost"
$siteName = "default web site"
$iis = [ADSI]"IIS://$server/W3SVC"
$site = $iis.psbase.children | where { $_.keyType -eq "IIsWebServer"
        -AND $_.ServerComment -eq $siteName }

from here got me started, but I can't get the 'start'/'stop' syntax right.

LastEditorDisplayName: MattH

OwnerDisplayName: Don Jones


问:
Compiling iOS library with bitcode enabled
I need to release a framework with bitcode enabled which turns out as a hassle. I set 'Enable Bitcode' in the project's settings to 'YES' and it builds cleanly for both a real device and a simulator.

I wanted to test the library so I integrated it to a new app I created for this purpose but now it only build for simulators. When I try to build for a real device I get:

```<code>ld: '/path/to/Framework.framework/Company(File.o)' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Like I said, I had built it with Bitcode enabled so I'm not sure why this happens.

Any ideas? thanks

答:
Another way with RunScript code: (build setting -- Build Phases RunScript)

# define output folder environment variable
UNIVERSAL_OUTPUTFOLDER=${BUILD_DIR}/${CONFIGURATION}-universal

# Step 1. Build Device and Simulator versions
xcodebuild -target TARGETNAME ONLY_ACTIVE_ARCH=NO -configuration Release -sdk iphoneos  BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}"
xcodebuild -target TARGETNAME -configuration Release -sdk iphonesimulator BUILD_DIR="${BUILD_DIR}" BUILD_ROOT="${BUILD_ROOT}"

# make sure the output directory exists
mkdir -p "${UNIVERSAL_OUTPUTFOLDER}"

# Step 2. Create universal binary file using lipo
lipo -create -output "${UNIVERSAL_OUTPUTFOLDER}/lib${PROJECT_NAME}.a" "${BUILD_DIR}/${CONFIGURATION}-iphoneos/lib${PROJECT_NAME}.a" "${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/lib${PROJECT_NAME}.a"

# Last touch. copy the header files. Just for convenience
cp -R "${BUILD_DIR}/${CONFIGURATION}-iphoneos/include" "${UNIVERSAL_OUTPUTFOLDER}/"```

Body:
I need to release a framework with bitcode enabled which turns out as a hassle. I set 'Enable Bitcode' in the project's settings to 'YES' and it builds cleanly for both a real device and a simulator.

I wanted to test the library so I integrated it to a new app I created for this purpose but now it only build for simulators. When I try to build for a real device I get:

ld: '/path/to/Framework.framework/Company(File.o)' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Like I said, I had built it with Bitcode enabled so I'm not sure why this happens.

Any ideas? thanks


问:
How to set horizontal progress bar based on total number of minutes in android?
Hi I want to set horizontal progress bar width based on total minutes.

For example

Total hours 7hrs 30 minutes - > 450 minutes

Xml

```<code><ProgressBar
   android:id="@+id/progress_bar_total_sleep"
   style="@style/SleepProgressFill"
   android:layout_width="270dp"
   android:layout_height="wrap_content"/>
</code>```

Please give any suggestion

答:
```<code>int minutes=450;
int total = (int) ((timePassed/ minutes) * 100);
progressbar.setProgress(total);
</code>```

Body:
Hi I want to set horizontal progress bar width based on total minutes.

For example

Total hours 7hrs 30 minutes - > 450 minutes

Xml

<ProgressBar
   android:id="@+id/progress_bar_total_sleep"
   style="@style/SleepProgressFill"
   android:layout_width="270dp"
   android:layout_height="wrap_content"/>

Please give any suggestion