text:
Q: Magento multiple websites I'm trying to create multiple websites, so that I can have multiple currencies and each with its own payment gateway. The trouble is, how to I access the other website?
After setting up one website everything works fine. I add another one and use a different domain for "Base URL" for it, but when trying to access that URL (which on the backend is routed by Apache to a directory which is just a symlink to same old magento code) - magento just redirects me to the old URL. How do I make the other website visible?

A: It is meant to be done via the .htaccess file. You should add the following code at the bottom:
# domain1.com
SetEnvIf Host domain1\.com MAGE_RUN_CODE=domain1
SetEnvIf Host domain1\.com MAGE_RUN_TYPE=website

# domain2.com
SetEnvIf Host domain2\.com MAGE_RUN_CODE=domain2
SetEnvIf Host domain2\.com MAGE_RUN_TYPE=website

The MAGE_RUN_CODE must correspond to the website code you have entered in the Magento backoffice when creating that website.

A: There are comprehensive entries in the Magento Wiki and Knowledge Base:
http://www.magentocommerce.com/knowledge-base/entry/tutorial-multi-site-multi-domain-setup
and
http://www.magentocommerce.com/wiki/4_-_themes_and_template_customization/navigation/multiple-website-setup
If possible, you should use the VHOST approach from the second link, then the .htaccess if you can't edit the web server config. Of course if you are using NGINX then you will have to use the VHOST approach adapted for NGINX.


text:
Q: Do I need to install something else besides Spark release package? There seems to be two ways to install Spark.

*

*When installing Spark by downloading prebuilt Spark release  (e.g. spark-2.4.5-bin-hadoop2.7.tgz) from    https://spark.apache.org/downloads.html,

*

*do I need to  additionally install  java command, by  installing JRE?

*Do I  need to  additionally install java compiler javac by installing JDK?

*Do I need to  additionally install scala compiler? (I guess no, because I saw the downloaded Spark release contains
./jar/scala-compiler.jar.)

*Do I need to  additionally install pyspark?  (I guess no, because I saw the downloaded Spark release contains ./bin/pyspark.)

*When installing Spark by running pip install pyspark, does it
already install spark for Java and for Scala? Or do I need to
additionally install some things in order to program Spark
applications in Java and Scala?
Thanks.

A: https://spark.apache.org/faq.html

do I need to additionally install java command, by installing JRE?

yes see the faq.

Do I need to additionally install java compiler javac by installing JDK?

no. i guess no, but i always use sdk.

Do I need to additionally install scala compiler? (I guess no, because I saw the downloaded Spark release contains ./jar/scala-compiler.jar.)

no

Do I need to additionally install pyspark? (I guess no, because I saw the downloaded Spark release contains ./bin/pyspark.)

no

When installing Spark by running pip install pyspark, does it already install spark for Java and for Scala?

yes.
tree .venv/lib/python3.6/site-packages/pyspark/bin
.venv/lib/python3.6/site-packages/pyspark/bin
├── beeline
├── beeline.cmd
├── docker-image-tool.sh
├── find-spark-home
├── find-spark-home.cmd
├── load-spark-env.cmd
├── load-spark-env.sh
├── pyspark
├── pyspark.cmd
├── pyspark2.cmd
├── run-example
├── run-example.cmd
├── spark-class
├── spark-class.cmd
├── spark-class2.cmd
├── spark-shell
├── spark-shell.cmd
├── spark-shell2.cmd
├── spark-sql
├── spark-sql.cmd
├── spark-sql2.cmd
├── spark-submit
├── spark-submit.cmd
├── spark-submit2.cmd
├── sparkR
├── sparkR.cmd
└── sparkR2.cmd

Or do I need to additionally install some things in order to program Spark applications in Java and Scala?

to program in scala you need to install scala to actually create the application jar.
i think use the downloaded release is easier to migrate to run things in the cluster.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reliable data transfer on a lossy channel Suppose you have already an unreliable lossy channel between 2 peers. Which methods can you suggest to transfer data reliably and also without performance loss? Also the underlying protocol is not TCP (which is already reliable). (I used lossy channel to generalize the question.)
( AFAIK, some methods exist like RDT (rfc-908), Go Back-N. )

A: http://en.wikipedia.org/wiki/Transmission_Control_Protocol#Reliable_transmission
Because someone already solved the problem and there is a library (TCP/IP) or ten that does it in every language that exists.
Is this a philosophy question?

A: Without performance loss typically means reducing dependency on the back channel, from the receiver sending ACKs to the sender.  This usually means a custom protocol using datagrams and using some form of forward-error-correction (FEC).  Note that FEC is a sliding scale that can often be a significant performance penalty because, by definition, you are preemptively sending additional redundant data so that the receiver does not have to ask for it.
http://en.wikipedia.org/wiki/Forward_error_correction
http://udt.sourceforge.net/

A: As Steve-o said, FEC and as Kdansky suggested Retransmission, are good starting points. The main bottleneck of Retransmission is round-trip times, which causes the delay in receiving a lost packet. However, FEC is a whole different subject and applicable on the packet level. As Steve-o said again, the bottleneck becomes the bandwidth overhead you cause by generating a redundant stream. Although it seems so straightforward, different FEC schemes such as, Parity FEC, Reed-Solomon, Turbo codes, Raptor Q, etc... have different effects on the delay, bandwidth overhead, etc. according to their parameters. (Mostly on the encoding rate that you use to generate the redundant stream)


text:
Q: Derive the equations of motion and determine whether angular momentum is conserved.. Suppose that the gravitational force is not given by the inverse-square law, and instead is
$$ F_{grav}=\left(\frac{A}{r^{2}}+\frac{B}{r^{4}}\right)\hat{r}, $$
where A and B are real constants. Derive the equations of motion and determine whether angular momentum is conserved. By using the substitution $r = 1/u$, transform the radial component of the equations of motion into a differential equation for $u$ as a function of the angular coordinate $\theta$. Determine for what values of $A$, $B$, and
integration constants stationary solutions exist and whether they are stable.
I have found the differential equation for $U$, however I don't understand how one can determine the values of $A$, $B$ and the integration constants.
The differential equation is
$$ \frac{d^2u}{d^2\theta} + u = - A/h^2 - Bu^2/h^2 ,$$
where $A$, $B$ and $h$ are constants.
Any help is very much appreciated.


text:
Q: How to get only post of the user i am following from firebase database [I have structured my database as below][1]
{

"
Posts" : {
    "-KnDkoPgr0ePAUS1acRF" : {
      "author" : "fhfgjl",
      "full_url" : "https://firebasestorage.googleapis.com/v0/b/picchat-d70e2.appspot.com/o/PostPic%2Ftmp5881607398655738702.jpeg?alt=media&token=2f180ded-339d-49dc-9236-76f0850ab2fe",
      "profile" : "https://firebasestorage.googleapis.com/v0/b/picchat-d70e2.appspot.com/o/ProfilePic%2FIMG-20170206-WA0022.jpg?alt=media&token=1be56929-a657-4c8c-81f6-1d73d5534b57",
      "starCount" : 1,
      "stars" : {
        "8WZ6jPIvVuNUEjR1G1ewEPpr2Ln2" : true
      },
      "text" : "cheating",
      "timestamp" : 1498117523692,
      "uid" : "8WZ6jPIvVuNUEjR1G1ewEPpr2Ln2"
    },
    "-KnDl3vJF8wABvDP9SoE" : {
      "author" : "din",
      "full_url" : "https://firebasestorage.googleapis.com/v0/b/picchat-d70e2.appspot.com/o/PostPic%2FIMG-20170206-WA0018.jpg?alt=media&token=533406ac-5ca1-4fcd-b0a1-a73cbaa9194e",
      "profile" : "https://firebasestorage.googleapis.com/v0/b/picchat-d70e2.appspot.com/o/ProfilePic%2FIMG-20170206-WA0023.jpg?alt=media&token=0cdb8a03-ff4c-4f7f-8cbe-d22d7604b1cd",
      "starCount" : 1,
      "stars" : {
        "8WZ6jPIvVuNUEjR1G1ewEPpr2Ln2" : true
      },
      "text" : "chilling",
      "timestamp" : 1498117591383,
      "uid" : "KOag2Br7MOaJqJNSFbcTD3ljEnh2"
    }
  },
  "Users" : {
    "8WZ6jPIvVuNUEjR1G1ewEPpr2Ln2" : {
      "email" : "shekhar9065@gmail.com",
      "following" : {
        "KOag2Br7MOaJqJNSFbcTD3ljEnh2" : true
      },
      "name" : "raval",
      "posts" : {
        "-KnDkoPdke4p4Ns8NUkR" : true
      },
      "profilepic" : "https://firebasestorage.googleapis.com/v0/b/picchat-d70e2.appspot.com/o/ProfilePic%2FIMG-20170206-WA0022.jpg?alt=media&token=1be56929-a657-4c8c-81f6-1d73d5534b57",
      "userName" : "fhfgjl"
    },
    "KOag2Br7MOaJqJNSFbcTD3ljEnh2" : {
      "email" : "raval@gmail.com",
      "following" : {
        "8WZ6jPIvVuNUEjR1G1ewEPpr2Ln2" : true,
        "KOag2Br7MOaJqJNSFbcTD3ljEnh2" : true
      },
      "name" : "nirali",
      "posts" : {
        "-KnDl3vFUlSxyRm0z547" : true
      },
      "profilepic" : "https://firebasestorage.googleapis.com/v0/b/picchat-d70e2.appspot.com/o/ProfilePic%2FIMG-20170206-WA0023.jpg?alt=media&token=0cdb8a03-ff4c-4f7f-8cbe-d22d7604b1cd",
      "userName" : "din"
    }
  },
  "UsersPost" : {
    "8WZ6jPIvVuNUEjR1G1ewEPpr2Ln2" : {
      "-KnDkoPdke4p4Ns8NUkR" : {
        "author" : "fhfgjl",
        "full_url" : "https://firebasestorage.googleapis.com/v0/b/picchat-d70e2.appspot.com/o/PostPic%2Ftmp5881607398655738702.jpeg?alt=media&token=2f180ded-339d-49dc-9236-76f0850ab2fe",
        "profile" : "https://firebasestorage.googleapis.com/v0/b/picchat-d70e2.appspot.com/o/ProfilePic%2FIMG-20170206-WA0022.jpg?alt=media&token=1be56929-a657-4c8c-81f6-1d73d5534b57",
        "starCount" : 0,
        "text" : "cheating",
        "timestamp" : 1498117524012,
        "uid" : "8WZ6jPIvVuNUEjR1G1ewEPpr2Ln2"
      }
    },
    "KOag2Br7MOaJqJNSFbcTD3ljEnh2" : {
      "-KnDl3vFUlSxyRm0z547" : {
        "author" : "din",
        "full_url" : "https://firebasestorage.googleapis.com/v0/b/picchat-d70e2.appspot.com/o/PostPic%2FIMG-20170206-WA0018.jpg?alt=media&token=533406ac-5ca1-4fcd-b0a1-a73cbaa9194e",
        "profile" : "https://firebasestorage.googleapis.com/v0/b/picchat-d70e2.appspot.com/o/ProfilePic%2FIMG-20170206-WA0023.jpg?alt=media&token=0cdb8a03-ff4c-4f7f-8cbe-d22d7604b1cd",
        "starCount" : 0,
        "text" : "chilling",
        "timestamp" : 1498117591912,
        "uid" : "KOag2Br7MOaJqJNSFbcTD3ljEnh2"
      }
    }
  },
  "followers" : {
    "8WZ6jPIvVuNUEjR1G1ewEPpr2Ln2" : {
      "KOag2Br7MOaJqJNSFbcTD3ljEnh2" : true
    },
    "KOag2Br7MOaJqJNSFbcTD3ljEnh2" : {
      "8WZ6jPIvVuNUEjR1G1ewEPpr2Ln2" : true
    }
  }

}
My Activity looks somthing like this
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_detail);

    currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
    mFollowing = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUser).child("following");
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Posts");
    posts = new ArrayList<>();
    mRecyclerView = (RecyclerView)findViewById(R.id.following_post_list);
    mRecyclerView.setLayoutManager(mlayoutManager);
    mAdapter = new PostQueryAdapter(posts);
    mRecyclerView.setAdapter(mAdapter);
}

@Override
protected void onStart() {
    super.onStart();

    mFollowing.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

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

                DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("UsersPost").child(following.getKey());

                mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(
                        Post.class , R.layout.post_item , PostViewHolder.class , reference) {
                    @Override
                    protected void populateViewHolder(PostViewHolder viewHolder, Post model, int position) {

                        viewHolder.bindToPost(model);
                    }
                };
                mRecyclerGrid.setAdapter(mAdapter);

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    }

Recycler adapter as follow
public class PostQueryAdapter extends RecyclerView.Adapter {
public ArrayList<Post> mdata;

public PostQueryAdapter(ArrayList<Post> data) {
    mdata = data;
}

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

@Override
public void onBindViewHolder(PostViewHolder holder, int position) {

    Post post = mdata.get(position);
    holder.bindToPost(post);

}

@Override
public int getItemCount() {
    return mdata.size();
}

public void add(int position, Post post) {
    mdata.add(position, post);
    notifyItemInserted(position);
}
I am not getting any thing in recyclerview and also no error in logcat
it is just not displaying any thing.
What is to be change in code ...

A: Inside onDAtaChange,try like this ways and let me know
    Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
    while (dataSnapshots.hasNext()) {
        DataSnapshot dataSnapshotChild = dataSnapshots.next();
        String id = dataSnapshotChild.getKey();
        mDatabase.child(id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // check here the datasnapshot
                Post post = dataSnapshot.getValue(Post.class);
                mAdapter = new PostQueryAdapter(posts);
                mAdapter.add(mAdapter.mdata.size(), dataSnapshot.getValue(Post.class));
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }


text:
Q: Too many queries, php. Creating lite forum engine I've started to writing my engine of forum, just to refresh php skills.
My problem is that, when I make a board and one theard, I have double queries.
I know why, I have "foreach in different foreach" but I cannot find a way to sort it out, can you guys help me how would you do it? To avoid this big number of queries?
An example, SMF forum main page has only 12 queries (NO MATTER OF NUMBERS BOARDS AND THEARDS).
My page have 12 already, but I have only 2 categories, 5 boards, 4 theards, 1 user.
If I add one board, and one theard I have +2 queries.
<?php
if(!defined('USED'))
    exit;
# Name of page!
$page = 'Forum';

$db = new Database();
$array = $db -> select("SELECT `id`,`name` FROM `".PREFIX."category`");

if(count($array) > 0)
{
    $container .= '';
    foreach($array as $category)
    {
    $container .= '

                '.$category['name'].'

                Board Name
                Latest

';
    $array2 = $db -> select("SELECT `id`,`id_category`,`name`,`info` FROM `".PREFIX."boards` WHERE `id_category`=".$category['id']."");
        if(count($array2) > 0)
        {
            foreach($array2 as $board)
            {
            $container .='

                            '.$board['name'].'

                            '.$board['info'].'
                        	';
            $array3 = $db -> select("SELECT `id`,`id_board`,`title`,`created_by`,`created_date` FROM `".PREFIX."theards` WHERE `id_board`=".$board['id']." ORDER BY `created_date` DESC LIMIT 1");
                if(count($array3) > 0)
                {
                    foreach($array3 as $theards)
                    {
                        $array4 = $db -> select("SELECT `id`,`name` FROM `".PREFIX."users` WHERE `id`=".$theards['created_by']."");
                            foreach($array4 as $user)
                            {
                                $created_by = $user['name'];
                            }
                    $container .='
                                '.$theards['title'].'
'.$created_by.', less than a month ago
                            	';
                    }
                }
                else
                {
                $container .= '
                            Nothing is here!
                            	';
                }
            $container .='

';
            }
        }
        else
        {
        $container .='

                        Nothing is here!
                        ...

';
        }
    $container .='

';
    }
}
else
{
    Site::Error("You need to add a category first!");
}

And my select:
public function select($query) {
    $rows = array();
    $result = $this -> query($query);
    if($result === false) {
        return false;
    }
    while ($row = $result -> fetch_assoc()) {
        $rows[] = $row;
    }

    global $db_count;
    $db_count = !isset($db_count) ? 1 : $db_count + 1;

    return $rows;
}

Ive added $db_count at the end of the file to check numbers of queries.

A: Instead of running one query to get a list of IDs, then looping across those IDs to get another set of IDS, then looping across those IDs to get a set of data, how about writing one query, using a JOIN to line up the three tables?


text:
Q: Add event handler to Html.CheckboxFor I'm working on a project previously developed by someone else and I've worked around to not make too many changes to it since it is time sensitive. I've hit a little block though.
In the .vbhtml file, there is a line as follows:
@Html.CheckBoxFor(Function(m) m.item(counter).value, New With{.id = "chkValue_" & counter})

This is inside a for loop so there are many of them being created inside a table. What I need to do is add an event handler to that checkbox so that it goes to a JavaScript function that I created.
After I'm done with this, I also have a dropdown list that I have the same issue with inside this same table as seen below:
Html.EnumDropDownListFor(Function(m) m.item(counter).PreferredLanguage, New With {.id = "ddlPrefLang_" & counter})

Any suggestions/help is greatly appreciated.

A: I wound up adding onclick to the HTML attributes as was suggested in the comments. The result is below:
@Html.CheckBoxFor(Function(m) m.item(counter).value, New With{.id = "chkValue_" & counter, .onclick = "//Call function here"})


text:
Q: Can I get individual man pages for the bash builtin commands? Is there anywhere you can download a manpage for every builtin commands?
I know you can just use help or man bash and search to find info about it, but I want them separated, so I can just do man read and get the read manpage.

A: help read
help read | less

In zsh:
run-help read

or type read something and press M-h (i.e. Alt+h or ESC h).
If you want to have a single man command so as not to need to know whether the command is a built-in, define this function in your ~/.bashrc:
man () {
  case "$(type -t "$1"):$1" in
    builtin:*) help "$1" | "${PAGER:-less}";;     # built-in
    *[[?*]*) help "$1" | "${PAGER:-less}";;       # pattern
    *) command -p man "$@";;  # something else, presumed to be an external command
                              # or options for the man command or a section number
  esac
}

A: Try this:
bashman () { man bash | less -p "^       $1 "; }

You may have to hit n a couple of times to get to the actual command instead of a paragraph that happens to have the command name as the first word.
Explanation: this pipes the entire output of man bash, i.e. bash's entire man page (which is a huge document, and has subsections explaining each bash builtin command) to the reading program less. less' -p flag stands for "pattern"; what it does is automatically scroll to the first point in the input text that matches the pattern. The pattern here is a regex which matches "The start of a line (^), followed by a specific number of spaces, followed by ..." – and here, bash inserts the first argument provided to the bashman function, because bash sees the special $1 token (which means "the first argument") in a string delimited with double-quotes (single quotes would tell bash that you literally mean the characters $1). So, if you run bashman cd, you will effectively be searching for any line in bash's man page with starts with a bunch of spaces, then the string "cd". Because there might be other points in bash's entire man page that also match this pattern besides the actual heading of the section that explains, eg., "cd", this function may not actually take you to the correct part of the bash man page.


text:
Q: How to Overcome the JFreeChart Issue? I'm using the Jfree chart in my struts application. Y-Axis is Over Shipment Pieces and X-Axis is Supplier Code and secondary axis is used for the Over Shipment %. What the problem i faced here is , If the Over Shipment % values all comes to Zero it hide the X-Axis Supplier Value also. How can i overcome to avoid this. I have attached here screen shot for your consideration. Thanks to all to read this question.

I pasted my code here for your clear understanding,
/**
     *
     * @param response
     * @throws IOException
     */
    public void writeOccurrenceBasedParetoChart(HttpServletResponse response) throws IOException
    {
        String METHOD_NAME = "writeOccurrenceBasedParetoChart";
        log.entering(CLASS_NAME, METHOD_NAME);

         CategoryDataset dataset1 = createDataSetForPercentBasedChart1();
         CategoryDataset dataset2 = createDataSetForPercentBasedChart2();
         String rangeAxisLabel = "";
         String numOfSupplrs = "";
         //Behind Schedule "4"
         if(searchRatingElement.equalsIgnoreCase("4"))
         {
             System.out.println("*******************searchRatingElement"+searchRatingElement);
             rangeAxisLabel = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.ovrshptpcs");
         }
         else
         {
             rangeAxisLabel = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.ovrshptpcs");
         }

         JFreeChart chart = ChartFactory.createBarChart(
                "",       // chart title
                "",               // domain axis label
                rangeAxisLabel,                  // range axis label
                dataset1,                  // data
                PlotOrientation.VERTICAL, // orientation
                true,                     // include legend
                true,                     // tooltips?
                false                     // URLs?
            );

            // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

            // set the background color for the chart...
            chart.setBackgroundPaint(Color.white);
            CategoryPlot plot = (CategoryPlot) chart.getPlot();
            plot.setBackgroundPaint(Color.lightGray);

            plot.setDataset(1, dataset2);
            plot.mapDatasetToRangeAxis(1, 1);

            CategoryItemRenderer renderer1 = plot.getRenderer();
            renderer1.setSeriesItemLabelGenerator(0,new CategoryItemLabelGenerator() {

                public String generateRowLabel(final CategoryDataset arg0, final int arg1) {
                    // TODO Auto-generated method stub
                    return null;
                }

                public String generateLabel(final CategoryDataset dataset1,final int series,final int category) {
                    String result = null;
                    //CHAPTER 12. ITEM LABELS 91
                    final Number value = dataset1.getValue(series, category);
                    if (value != null) {
                    final double v = value.doubleValue();
                    if (v > 0) {
                    result = value.toString(); // could apply formatting here
                    }
                    }
                    return result;
                    }

                public String generateColumnLabel(final CategoryDataset arg0, final int arg1) {
                    // TODO Auto-generated method stub
                    return null;
                }
            });
            renderer1.setSeriesItemLabelsVisible(0,true);

            BarRenderer renderer = (BarRenderer) plot.getRenderer();
            renderer.setDrawBarOutline(false);
            renderer.setSeriesOutlinePaint(0,Color.BLACK);
            renderer.setDrawBarOutline(true);
            renderer.setMaximumBarWidth(0.02);
            renderer.setSeriesPaint(0,new Color(170, 0, 85));

            CategoryAxis domainAxis = plot.getDomainAxis();
            domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(.6));
            domainAxis.setLabelFont(new Font("Helvetica", Font.BOLD, 14));
            domainAxis.setTickLabelFont(new Font("Helvetica", Font.BOLD, 14));

             //Behind Schedule "4"
             if(searchRatingElement.equalsIgnoreCase("4"))
             {
                 System.out.println("||||||||||||||||||||||||||||||||searchRatingElement"+searchRatingElement);
                 numOfSupplrs = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.bhndschpctforchart");
             }
             else
             {
                 numOfSupplrs = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.ovrshptpctforchart");
             }

            ValueAxis axis2 = new NumberAxis(numOfSupplrs);
            axis2.setLabelFont(new Font("Helvetica", Font.BOLD, 14));
            axis2.setTickLabelFont(new Font("Helvetica", Font.PLAIN, 14));
            //if(!this.isValueDataZeros)
                //axis2.setRange(0,13);
            plot.setRangeAxis(1, axis2);

            NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
           // if(!this.isNumberDataZeros)
                //rangeAxis.setRange(0,90);
           //rangeAxis.setTickUnit(new NumberTickUnit(1));
           rangeAxis.setLabelFont(new Font("Helvetica", Font.BOLD, 14));
           rangeAxis.setTickLabelFont(new Font("Helvetica", Font.PLAIN, 14));

            LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();
            renderer2.setSeriesPaint(0, Color.BLUE);
            /*Start */
            renderer2.setSeriesItemLabelGenerator(0,new CategoryItemLabelGenerator() {

                public String generateRowLabel(final CategoryDataset arg0, final int arg1) {
                    // TODO Auto-generated method stub
                    return null;
                }

                public String generateLabel(final CategoryDataset dataset1,final int series,final int category) {
                    String result = null;
                    //CHAPTER 12. ITEM LABELS 91
                    final Number value = dataset1.getValue(series, category);
                    if (value != null) {
                    final double v = value.doubleValue();
                    if (v > 0) {
                    result = value.toString(); // could apply formatting here
                    }
                    }
                    return result;
                    }

                public String generateColumnLabel(final CategoryDataset arg0, final int arg1) {
                    // TODO Auto-generated method stub
                    return null;
                }
            });
            renderer2.setSeriesItemLabelsVisible(0,true);
            /* End */
            plot.setRenderer(1, renderer2);
            plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

            ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart,
                    1150, 450);
    }
    /**
     *
     */
    public DefaultCategoryDataset createDataSetForPercentBasedChart1()
    {
        String METHOD_NAME = "createDataSetForPercentBasedChart1";
        log.entering(CLASS_NAME, METHOD_NAME);

        DefaultCategoryDataset dataSetForOccurrenceBasedChart = new DefaultCategoryDataset();

        boolean flagForPercentPareto = false;
        String occurrenceCountLabelName = null;
        try
        {
            if(paretoReportBasedDataQO != null && paretoReportBasedDataQO.size()>0)
            {
                //Behind Schedule "4"
                if(searchRatingElement.equalsIgnoreCase("4"))
                {
                    occurrenceCountLabelName = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.bhndschpctforchart");
                }
                else
                {
                    occurrenceCountLabelName = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.ovrshptpcs");
                }
                if(!flagForPercentPareto)
                {
                    for(int i =0;i<paretoReportBasedDataQO.size();i++)
                    {
                        dataSetForOccurrenceBasedChart.addValue(paretoReportBasedDataQO.get(i).getOverShipmentPiecesCount(), occurrenceCountLabelName, paretoReportBasedDataQO.get(i).getSupplierName());
                    }
                }
            }
        }
        catch(Exception exceptionOccurrenceBasedChart)
        {
            flagForPercentPareto = true;
            System.out.println("Exception In createDataSetForPercentBasedChart1 : "+exceptionOccurrenceBasedChart.getMessage());
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return dataSetForOccurrenceBasedChart;
    }
    /**
     *
     */
    public DefaultCategoryDataset createDataSetForPercentBasedChart2()
    {
        String METHOD_NAME = "createDataSetForPercentBasedChart2";
        log.entering(CLASS_NAME, METHOD_NAME);

        DefaultCategoryDataset dataSetForOccurrenceBasedChart = new DefaultCategoryDataset();

        boolean flagForPercentPareto = false;
        String occurrenceCountLabelName = null;
        try
        {
            if(paretoReportBasedDataQO != null && paretoReportBasedDataQO.size()>0)
            {
                if(searchRatingElement.equalsIgnoreCase("4"))
                {
                    occurrenceCountLabelName = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.bhndschpctforchart");
                }
                else
                {
                    occurrenceCountLabelName = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.ovrshptpctforchart");
                }
                if(!flagForPercentPareto)
                {
                    for(int i =0;i<paretoReportBasedDataQO.size();i++)
                    {
                        dataSetForOccurrenceBasedChart.addValue(paretoReportBasedDataQO.get(i).getOverShipmentPercentageCount(), occurrenceCountLabelName, paretoReportBasedDataQO.get(i).getSupplierName());
                    }
                }
            }
        }
        catch(Exception exceptionOccurrenceBasedChart)
        {
            flagForPercentPareto = true;
            System.out.println("Exception In createDataSetForPercentBasedChart2 : "+exceptionOccurrenceBasedChart.getMessage());
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return dataSetForOccurrenceBasedChart;
    }

A: What if you put the label in another position?
For example:
renderer.setBasePositiveItemLabelPosition(
new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));


text:
Q: 'Diamagnetic' inequality for negative Sobolev spaces Let us look at the subspace of smooth complex functions of $L^2(\mathbb{R}^n,\mathbb{C})$, call $H^s$ the Sobolev spaces. By the diamagnetic inequality $\lvert \nabla \lvert\psi\rvert\rvert (x) \le \lvert\nabla \psi\rvert(x)$ (a proof is here), we have
\begin{align*}
\lVert\,\lvert\psi\rvert\,\rVert_{H^s} \le c_s  \lVert  \psi\rVert_{H^s}
 \end{align*}
for $s=1$ and $c_1 = 1$, where $c_1$ does not depend on $\psi$. It is also true for $s=0$ with $c_0 = 1$. Do we have such a result for $s=-1$, with $c_{-1} < + \infty$?

A: This is not true in the case of $H^{-1}(\Omega) = H_0^1(\Omega)^*$ (real spaces), where $\Omega \subset \mathbb R^d$ is bounded:

*

*In https://math.stackexchange.com/questions/336834/decomposition-of-functionals-on-sobolev-spaces, we see that $|\psi|$ cannot be defined for all $\psi \in H^{-1}(\Omega)$.

*Even if $|\psi|$ can be defined (as a measure), it might not belong to $H^{-1}(\Omega)$, see https://math.stackexchange.com/questions/1402697/decomposition-of-measures-acting-on-sobolev-spaces

*Even if $|\psi| \in H^{-1}(\Omega)$, we do not get a bound. On $\Omega = (0,1)$, you can consider $\psi_n(x) = \sin(n x)$ as an element in $H^{-1}(\Omega)$. Then, $\|\psi_n\|_{H^{-1}} \to 0$, but $\||\psi_n|\|_{H^{-1}} \not\to 0$.

I would expect that the same arguments can be adopted to your situation.


text:
Q: Native Google Drive MIME types failing to save in Drive UI integration I'm working on a Google Drive UI "Open with" integration.
I'm trying to populate the "Secondary MIME Types" with Google Doc & Google Spreadsheet mime types (https://developers.google.com/drive/api/v3/mime-types) in Google Cloud Console under Google Drive API config.
They are as follows:

application/vnd.google-apps.document
application/vnd.google-apps.spreadsheet

However, the form throws a bad request every time I add either of those mime types.
The following does WORK:

The following does NOT WORK:

Anyone else run into this issue, and how have they solved it? According to Google's own docs (https://developers.google.com/drive/api/v3/enable-sdk) it should be allowed.

A: It appears that you do not need to include the google specific mime types in order for your app to show up under "Open with" for docs, slides & spreadsheets.
Adding the application/pdf mime type should suffice, then google drive passes the exportIds as a query parameter to your open URL. You can then use that id in conjunction with the google drive API export file method (https://developers.google.com/drive/api/v3/reference/files/export) to export the document as a PDF.


text:
Q: Checking for transactions in Sequelize In Sequelize, you can:

*

*Manually pass a transaction as a second argument to each query

*Or automatically pass transactions to all queries using CLS.

I'd like to go with the manual option, but I'd like to change the default model behavior so that queries will throw an error if no transaction is provided. An optional noTransaction argument will allow you to bypass the transaction check.
i.e.
myModel.update({newValue: true}); // throws Error "No transaction specified"
myModel.update({newValue: true}, {transaction}); // OK
myModel.update({newValue: true}, {noTransaction: true); // OK

What's the best way to go about updating the default behavior of model methods in Sequelize?

A: Turns out this is simple as Sequelize supports adding a hook to all models:
sequelize.addHook('beforeCreate', checkForTransaction);
sequelize.addHook('beforeUpdate', checkForTransaction);
sequelize.addHook('beforeDestroy', checkForTransaction);

function checkForTransaction (data, options) {
  if (!options.transaction && !options.noTransaction) {
    throw new Error('Transaction is required');
  }
}

A: Actually, I think the best solution is not to create a transaction manually at all. But to let decorators do the work for you.
function start() {
    try {
      const transaction = sequelize.transaction();

      // allowing me to pass it to multiple functions.
      foo(transaction);
      bar(transaction);

      transaction.commit();
    } catch(err) {
      transaction.rollback();
      throw err;
    }
}

Becomes as short as
@Transactional
function start(@Tx transaction) {
  foo(transaction);
  bar(transaction);
}

The transaction parameter becomes optional, and will be initialized automatically whenever necessary. It basically allows all methods to be executed individually or as part of a bigger transaction. And you never have to write code for it.
This requires a package:
npm install zb-sequelize

You do have to give it access to your sequelize instance.
import { initSequelizeResolver } from 'zb-sequelize';
initSequelizeResolver((args) => sequelize);


text:
Q: asp.net application requests stuck in "SendResponse" state Im troubleshooting some application performance issues and have noticed that when i look in IIS 7 (under worker processes), the long running requests are stuck in "SendResponse" in the pipeline.
Some of these requests can be in that state for 200+ seconds.
I'm not sure if this questions is best asked here or in serverfault, but figured I would ask here since I'm guessing its an application issue instead of a server issue.
Anyways, has anyone seen this before, and know what might be causing it?  I'm running asp.net 3.5 32 bit on a 64 bit machine in classic mode.
Thanks in advance.


text:
Q: How to use add() in ArrayList class in Java I have a question about constructing an ArrayList, I have had a Car Class, now I need to make an ArrayList to put content in, I named it as Race, please see code below:
import java.util.ArrayList;

public class Race {

private ArrayList<Car>cars;

public Race(){
cars=new ArrayList<Car>();
}

Now I need to have a method for add content to the ArrayList, there are two ways to write that I am confused with:
First one
public void addCars(){

Car Toyota=new Car("Toyota",1.0,1.0,2.0,2.0);
Car Honda=new Car("Honda",1.0,2.0,1.0,2.0);
Car Mazda=new Car("Mazda",1.0,3.0,2.0,3.0);
Car Suzuki=new Car("Suzuki",1.0,4.0,4.0,2.0);

cars.add(Toyota);
cars.add(Honda);
cars.add(Mazda);
cars.add(Suzuki);

    }

Second one
public void addCars(Object nm,String n, double s, double p, double a, double b){

Car name=new Car(n,s,p,a,b);
cars.add(name);
    }

Both ways have no mistake reported when I coding, but I am not sure which one is correct, or maybe neither is correct, please help, cheers!
UPDATE:
    public void addCars(Car car){
cars.add(car);

   }

This is what I used finally, then I created a new class called Test that using main method to add cars individually, but there is mistake in the last line:
    public class Test {

public static void main(String[] args) {
    Car Toyota=new Car("Toyota",1.0,1.0,2.0,2.0);
    **cars.addCars(Toyota);**

I have no idea how to fix it, please help!

A: It depends on what you want to achieve. In general it is better to provide APIs and use them from the outside. In your case, however, I think your "addCars" function in used to populate your ArrayList(you should call it something like that) - which means to add predefined values to a Collection.
In that case, use the first one.
So, both of your methods are correct (though you should call the first populateCars and the second addCar) and should work, but you need to use them depending on your circumstance.
Also, if you want to provide an API for adding Cars, let the user get a Car object himself, rather than constructing one in the add method. (You might want to change it before adding it, you never know)
So I suggest using either of the methods, but changing the first to:
public void populateCars(){
    Car Toyota=new Car("Toyota",1.0,1.0,2.0,2.0);
    Car Honda=new Car("Honda",1.0,2.0,1.0,2.0);
    Car Mazda=new Car("Mazda",1.0,3.0,2.0,3.0);
    Car Suzuki=new Car("Suzuki",1.0,4.0,4.0,2.0);

    cars.add(Toyota);
    cars.add(Honda);
    cars.add(Mazda);
    cars.add(Suzuki);
}

or the second to:
public void addCar(Car car){
    cars.add(car);
}

A: Both the ways you mentioned are correct but you should modify the method addCars() to take an argument of type Car .
For example , change the method signature to :
public void addCars(Car car){
     cars.add(car);
}

And just pass a new car like this :
addCars(new Car("Toyota",1.0,1.0,2.0,2.0));

A: The only difference is that in first case you have hard coded elements in the list and in the second approach you add them dynamically.  What to use depends on your need.
I suppose you will use the arraylist later on to get elements from it, do sth with them etc. Then you will use getter method on the arraylist, iterate through it and so on... This will work on both approaches you choose.

A: Both answers are correct.  The first method uses a traditional approach to creating objects.  The second method is sometimes called a Factory method.  Using a factory method is useful when  the construction of an object is externally complicated or stamping out multiple objects.
So the answer is:  The first approach is correct for objects that are reasonably simple and safe to construct.  The second (factory) pattern is better for complex objects.

A: @pei wang nice question .. Second apporach is gud as ur not hardcoding values .. You should go little bit forward .. please Use DTO design pattern in second approach use setters and getters

A: Add method expects object type reference for the add method if you pass any reference variable other than object type reference variable then those reference variable upcasted to object type reference.


text:
Q: Filter XML elements of type anyURI using XSD I am using go-libxml2. I have an XSD and also a XML. I want to filter all anyURI elements in the XML based on XSD including nested elements. Because I am trying to update all anyURI elements in a XML by adding a queryparam. For example
XSD:
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="grandParent">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="AnyURI1" type="xs:anyURI"
         maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>
  <xs:element name="parent">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="AnyURI2" type="xs:anyURI"
           maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
    <xs:element name="children">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="AnyURI3" type="xs:anyURI"
             maxOccurs="unbounded"/>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
  </xs:element>
</xs:element>
</xs:schema>

XML
    <grandParent>
  <AnyURI1>    http://uri_gp1.com </AnyURI1>
  <AnyURI1>    http://uri_gp2.com </AnyURI1>
  <parent>
    <AnyURI2>    http://uri_p1.com    </AnyURI2>
    <AnyURI2>    http://uri_p2.com    </AnyURI2>
    <children>
      <AnyURI3>    http://uri_child1.com    </AnyURI3>
      <AnyURI3>    http://uri_child2.com    </AnyURI3>
    </children>
  </parent>
</grandParent>

In the above XML, I want to filter and update all element of type "anyURI" like <AnyURI1>, <AnyURI2> and <anyURI3>
How can I achieve this using golang?

A: I think you should consider alternative choices of technology for this. The problem becomes very easy with a schema-aware XSLT transformation:
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0"
               xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xsl:mode on-no-match="shallow-copy">
  <xsl:template match="element(*, xs:anyURI)/text()">
    <xsl:value-of select=". || '?param=value'"/>
  </xsl:template>
</xsl:transform>

A: For fully featured XML processors supporting XML Schema, the Post Schema Validation Infoset (PSVI) would provide you exactly what you want. A PSVI Example shows how to access it using Xerces C.
From what I can see, the problem with go-libxml2 is that libxml2 itself did not get to implement PSVI. The designers allowed for a "future" PSVI extension which I don't think ever materialized. (Have a look at libxml2 doc and search for PSVI.) Because of this, the answer is you can't achieve what you want.
If you're willing to integrate with other platforms, Java xerces would work in that you could delegate the task to it.


text:
Q: Display static Google Map image in BlackBerry 5.0 I'm having a really interesting problem to solve:
I'm getting a static google map image, with an URL like this.
I've tried several methods to get this information:
Fetching the "remote resource" as a ByteArrayOutputStream, storing the Image in the SD of the Simulator, an so on... but every freaking time I get an IlegalArgumentException.
I always get a 200 http response, and the correct MIME type ("image/png"), but either way: fetching the image and converting it to a Bitmap, or storing the image in the SD and reading it later; I get the same result... the file IS always corrupt.
I really belive its an encoding problem, or the reading method (similar to this one):
public static Bitmap downloadImage(InputStream inStream){
  byte[] buffer = new byte[256];
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  while (inStream.read(buffer) != -1){
    baos.write(buffer);
  }
  baos.flush();
  baos.close();

  byte[] imageData = baos.toByteArray();
  Bitmap bi = Bitmap.createBitmapFromBytes(imageData, 0, imageData.length, 1);
  //Bitmap bi = Bitmap.createBitmapFromBytes(imageData, 0, -1, 1);
  return bi;
}

The only thing that comes to mind is the imageData.lenght (in the response, the content length is: 6005 ), but I really can't figure this one out.
Any help is more than welcome...

A: try this way:
InputStream input = httpConn.openInputStream();
byte[] xmlBytes = new byte[256];
int len = 0;
int size = 0;
StringBuffer raw = new StringBuffer();
while (-1 != (len = input.read(xmlBytes)))
{
    raw.append(new String(xmlBytes, 0, len));
    size += len;
}
value = raw.toString();
byte[] dataArray = value.getBytes();
EncodedImage bitmap;
bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
final Bitmap googleImage = bitmap.getBitmap();

A: Swati's answer is good.  This same thing can be accomplished with many fewer lines of code:
InputStream input = httpConn.openInputStream();
byte[] dataArray = net.rim.device.api.io.IOUtilities.streamToBytes(input);
Bitmap googleImage = Bitmap.createBitmapFromBytes(dataArray, 0, -1, 1);


text:
Q: flv video flex core i have a flv video file
i loaded the binary data  of this flv file to memory by using
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/video.flv");
var myFileStream:FileStream = new FileStream();
myFileStream.open(myFile, FileMode.READ);
var bytes:ByteArray = new ByteArray();
myFileStream.readBytes(bytes);
myFileStream.close();
now i like to change some header of this loaded flv in bytes memory variable.
but after changing header, changed header was stored in bytes memory variable that is overwritten.
now how can i play that flv file from this memory (bytes memory variable)

A: One option would be to save the bytes as a temp file and then play back from the local filesystem.
// write to temp file
var f:File = File.createTempFile();
var fs:FileStream = new FileStream();
fs.open(f, FileMode.WRITE);
fs.writeBytes(bytes);
fs.close();

// play back
var display:VideoDisplay; // created somehow
display.source = f.url;

Not sure about some of the details (Does the temp file need a .flv extension?  Does the source URL need to be the native path or some such?) but that approach should work within AIR.


text:
Q: The jquery accordion overlaps the content of my header I am using the jquery accordion source for my website and what happens when I scroll down is the accordion overlaps my header.
I haven't made any adjustments to the CSS code in the accordion class so I don't have much to show but I've read a lot of people complaining that the accordion source from jquery UI has this problem but I have not been able to find out what it is?
Any ideas? Thanks!

About

Design

3D + Animation

Video Production

Contact

About

Farman Pirzada is this one dude who's pretty awesome and there's a lot you should learn about him because I love him

and here's the CSS
 #accordion {
 padding-left: 100px;
 }

http://imgur.com/EaQOT0g


text:
Q: Шаблоны классов и экземпляры их статических переменных Допустим, есть шаблон класса:
template<typename T>
class Link
{
public:
    Link(std::vector<T*> vars = std::vector<T*>()) : _vars(vars)
    {
    };
    ~Link() {};

private:
    std::vector<T*> _vars{};
};

Далее, я хочу иметь доступ ко всем экземплярам класса Link каждого типа в отдельности.
Я создаю статическую переменную links - контейнер, который заполняю в конструкторе (или это плохой подход?):
template<typename T>
class Link
{
public:
    static std::vector<Link*> links;

    Link(std::vector<T*> vars = std::vector<T*>()) : _vars(vars)
    {
        links.push_back(this);
    };
    ~Link() {};

    void job()
    {
        /* тут я могу обрабатывать все экземпляры Link конкретного типа */
    }

private:
    std::vector<T*> _vars{};
};

template<typename T>
std::vector<Link<T>*> Link<T>::links = std::vector<Link<T>*>();

Теперь я могу обрабатывать экземпляры каждого типа в отдельности, что мне и нужно. Но как мне перебрать все созданные экземпляры Link::links ? Т.е. как в данном примере перебрать все экземпляры Link<int> и Link<double> и всех созданных типов, я ведь не знаю, в общем случае, какие типы были созданы из шаблона?
int main()
{
    Link<int> L1{};
    Link<int> L2{};
    auto L3 = Link(std::vector<int*>());

    Link<double> L4{};
    Link<double> L5{};

    for (const auto& L : Link<int>::links)
    {
        /* все, что нужно, я могу сделать в Link::job() */
    }

    for (const auto& L : Link</*ALL*/>::links)
    {
        /* как перебрать все созданные экземпляры vector<Link> links ??? */
    }

    return 0;
}

UPD:
Пришла идея, что можно создать базовый класс LinkBase, в нем так же создать статический контейнер для всех Link<>, а Link отнаследовать от LinkBase... Но как-то много лишнего?

A: В общем, пришел к такому решению. Возможно, кому-то из новичков (как я) пригодится. А экспертам - для развлечения покритиковать :)
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <array>
#include <algorithm>

using std::vector;
using std::array;
using std::shared_ptr;
using std::pair;
using std::string;

enum class TYPE
{
    CONTACT,
    FLOW,
    INOUT
};

struct fluid
{
    static const vector<pair<TYPE, string>> entrails;
};

const vector<pair<TYPE, string>> fluid::entrails = {
        {TYPE::CONTACT, "P"},
        {TYPE::FLOW,    "Q"},
        {TYPE::CONTACT, "conc"}
};

struct thermo
{
    static const vector<pair<TYPE, string>> entrails;
};

const vector<pair<TYPE, string>> thermo::entrails = {
        {TYPE::CONTACT, "T"},
        {TYPE::CONTACT, "heat"}
};

struct electro
{
    static const vector<pair<TYPE, string>> entrails;
};

const vector<pair<TYPE, string>> electro::entrails = {
        {TYPE::CONTACT, "P"},
        {TYPE::FLOW, "I"}
};

/*****************************************************************************/

class BaseLink
{
    static vector<BaseLink*> ALL_LINKS;
public:

    ~BaseLink() {};

    BaseLink(const BaseLink&) = delete;
    BaseLink(BaseLink&&) = delete;
    BaseLink& operator=(const BaseLink&) = delete;
    BaseLink& operator=(BaseLink&&) = delete;

    static vector<BaseLink*> all_links();

    virtual size_t dimension() const
    {
        return _entrails_vars.size();
    }

    virtual size_t count() const = 0;
    virtual vector<string> names() const = 0;

protected:
    BaseLink()
    {
        ALL_LINKS.push_back(this);
    };

    vector<double>_entrails_vars{};
};

vector<BaseLink*> BaseLink::ALL_LINKS = vector<BaseLink*>();

vector<BaseLink*> BaseLink::all_links()
{
    return BaseLink::ALL_LINKS;
}

/*****************************************************************************/
template<typename T>
class Link: public BaseLink
{
    static vector<Link*> links;
public:

    Link(const std::initializer_list<T>& vars) : BaseLink(), _vars(vars)
    {
        _entrails_vars.resize(T::entrails.size());
        links.push_back(this);
    };
    ~Link() {};

    static vector<Link*> get_links();

    vector<string> names() const override
    {
        vector<string> names{};
        for (const auto& [type, name] : T::entrails)
            names.push_back(name);

        return names;
    }

    size_t count() const override
    {
        return _vars.size();
    }

    void job()
    {
        /* тут я могу обрабатывать все экземпляры Link конкретного типа */
    }

private:
    vector<T> _vars{};
};

template<typename T>
vector<Link<T>*> Link<T>::links = vector<Link<T>*>();

template<typename T>
vector<Link<T>*> Link<T>::get_links()
{
    //return links; // СМУЩАЕТ, НО РАБОТАЕТ
    return Link<T>::links;
}

int main()
{
    /*
     * переменные fluid, thermo, electro создаются где-то в приложении
     * тут просто заполняем дефолтными значениями для теста
     */
    auto L1 = Link({fluid{}, fluid{}});
    auto L2 = Link({ fluid{} });
    auto L3 = Link({ thermo{} , thermo{} , thermo{} });
    auto L4 = Link({ thermo{} , thermo{} , thermo{} , thermo{} });
    auto L5 = Link({ thermo{} , thermo{} });
    auto L6 = Link({ electro{} , electro{} , electro{} });

    std::cout << "ALL LINKS:\n";
    for (const auto& link : BaseLink::all_links())
    {
        std::cout << "\tdimension = " << link->dimension()
            << "; count = " << link->count() << ": names [";
        for (const auto& name : link->names())
            std::cout << name << ' ';
        std::cout << "]\n";
    }

    std::cout << "fluid LINKS:\n";
    for (const auto& link : Link<fluid>::get_links())
    {
        std::cout << "\tdimension = " << link->dimension()
            << "; count = " << link->count() << "\n";
    }

    std::cout << "thermo LINKS:\n";
    for (const auto& link : Link<thermo>::get_links())
    {
        std::cout << "\tdimension = " << link->dimension()
            << "; count = " << link->count() << "\n";
    }

    std::cout << "electro LINKS:\n";
    for (const auto& link : Link<electro>::get_links())
    {
        std::cout << "\tdimension = " << link->dimension()
            << "; count = " << link->count() << "\n";
    }

    return 0;
}

Вывод:
ALL LINKS:
    dimension = 3; count = 2: names [P Q conc ]
    dimension = 3; count = 1: names [P Q conc ]
    dimension = 2; count = 3: names [T heat ]
    dimension = 2; count = 4: names [T heat ]
    dimension = 2; count = 2: names [T heat ]
    dimension = 2; count = 3: names [P I ]
fluid LINKS:
    dimension = 3; count = 2
    dimension = 3; count = 1
thermo LINKS:
    dimension = 2; count = 3
    dimension = 2; count = 4
    dimension = 2; count = 2
electro LINKS:
    dimension = 2; count = 3


text:
Q: JavaFX: bindContent of TreeView selectedItems I want to bind a content of TreeView selected items list and bumped into a strange behaviour of the selected items change value when removing elements. I wrote a some test application:
public class TreeViewSelectedItemsBindingTest extends Application {

    public class Item extends TreeItem<Integer> {
        public Item(Integer... value) {
            Arrays.stream(value).forEach(v -> getChildren().add(new TreeItem<Integer>(v)));
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        TreeView<Integer> treeView = new TreeView<>();
        treeView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        treeView.setRoot(new Item(0, 1, 2, 3, 4, 5, 6, 7, 8, 9));
        treeView.getRoot().setExpanded(true);
        treeView.setShowRoot(false);

        ListView<TreeItem<Integer>> listView = new ListView<>();

        Bindings.bindContent(listView.getItems(), treeView.getSelectionModel().getSelectedItems());

        treeView.getSelectionModel().getSelectedItems()
                .addListener((ListChangeListener<? super TreeItem<Integer>>) change -> {
                    System.out.println("Change: " + change);
                    System.out.println("TreeView size: " + treeView.getSelectionModel().getSelectedItems().size());
                    System.out.println("ListView size: " + listView.getItems().size());
                    System.out.println("-------------------");
                });

        HBox box = new HBox();
        box.getChildren().addAll(treeView, listView);
        primaryStage.setScene(new Scene(box));
        primaryStage.show();
    }

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

This application bind TreeView selected items to ListView items. Select in the tree view all elements from 0 to 9 and then press SHIFT+element 5, for example, to change selection from 0 to 5 elements. You will got an exeption:
Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: toIndex = 9

It is because ListChangeListener.Change reports from index relative to initial unmodified list, not relative a list changed previously:
-------------------
Change: { [TreeItem [ value: 6 ]] removed at 6,  }
TreeView size: 9
ListView size: 9
-------------------
Change: { [TreeItem [ value: 7 ]] removed at 7,  }
TreeView size: 8
ListView size: 8
-------------------

You can see "removed at 6" then "removed at 7", but size of underlying lists also changed so index should not be increased here, i.e. all "removed at" should be at 6. And because of this a Bindings.bindContent is failed.

A: It is a bug JDK-8180359. As a workaround the bonded list should be updated as whole:
treeView.getSelectionModel().getSelectedItems().addListener(
    (ListChangeListener<? super TreeItem<Model>>) change -> {
            while (change.next()) {
                listView.setAll(change.getList().stream()
                        .filter(Objects::nonNull)
                        .map(i -> i.getValue())
                        .collect(toList()));
            }
        });


text:
Q: Form inputs not showing the same across browsers I have this JSFiddle that shows a user registration form. I am using Twitter Bootstrap. I have just realized that it shows fine when using Firefox.
However, when using Chrome or IE, the textfields are slightly above the input-group-addons where I have glyphicons.
How can I make the form inputs show correctly across browsers?

     <?php
          echo $this->Form->input('username', array('class' => 'form-control',
               'placeholder' => 'Username', 'required' => 'required', 'type' => 'text'));
     ?>

A: Move the glyph class out and into their own spans.

Always try to keep elements separate from their containers to prevent styles from conflicting with each other.


text:
Q: cocos2d create_project.py not working I am trying to create a new project on cocos2d in Win 8, but when I execute the create_proyect.py on the command prompt it seems to be skiping the parameters.
create_project.py -project randomName -package com.MyCompany.AwsomeGame -language cpp

The above command's result is the same as:
create_project.py

A: I was facing the same issue and Finally I solved the problem by using this command
$ python create_project.py -project MyGame -package com.MyCompany.AwesomeGame -language cpp


text:
Q: PlantUML: Packages next to each other, components in a list I want to have 2 packages next to each other and the containing components among each other.
Goal (Draft):

Code:
@startuml
left to right direction
() Mechanical
() Hydraulical
() Electrical
package Machine{
    Mechanical )-left- [Turning Disc]
    Mechanical )-left- [Vent]
    Electrical )-left-[Baler_ECU]
    Hydraulical )-left-[Arm]
}

package Tractor{
    [Engine] -right- Mechanical
    [Hydraulics] -right- Hydraulical
    [Tractor_ECU] -right- Electrical
}

@enduml

Current Result of this code:

Thank you for any help

A: Try to use "hidden" attribute
@startuml
left to right direction

rectangle interface{
    () Mechanical
    () Hydraulical
    () Electrical
}

package Machine{
    Mechanical )-- [Turning Disc]
    Mechanical )-- [Vent]
    Electrical )--[Baler_ECU]
    Hydraulical )--[Arm]
}

package Tractor{
    [Engine] -- Mechanical
    [Hydraulics] -- Hydraulical
    [Tractor_ECU] -- Electrical
}

interface -[hidden]- Machine
Tractor -[hidden]- interface
@enduml


text:
Q: Arm64 is not showing in Unity 5.6.6 32bit I made a game and tried to upload in google play store but it said to set my native code to 64 bit android. I searched for the solution in which I found out to check ARM64 in player setting but I couldn't find that check button. Could anyone help me..?

A: Based on this unity blog:

The move to a 64-bit Android world is imminent, and we at Unity
  believe that it's a good thing! We added support for Android 64-bit
  with Unity 2018.2, and we have now backported it to Unity 2017.4. Read
  on to get more details on Google's  64-bit requirement, ARM 64-bit
  advantages, and Android App Bundle support in Unity.


text:
Q: Cudafy.NET Compilation error I'm trying to use Cudafy.NET for my programming.
At first, I tested the example of cudafy.NET, but it does not work.
cudafyModule km = CudafyTranslator.Cudafy();

This code showed a compilation error.
So, I checked CUDA test in the cudafyviewer, but it was same.
I installed the CUDA Toolkit 7.0 and I added the path of cl.exe to environment variable's system path.
What more do I need?

A: Are you by any chance using VS 2015?  Nvcc.exe says doesn't work with that yet.
You can try running nvcc.exe /? from a command prompt and you'll likely see this error if you have VS 2015:
C:\WINDOWS\system32>nvcc /?
nvcc fatal   : nvcc cannot find a supported version of Microsoft Visual Studio. Only the versions 2010, 2012, and 2013 are supported
Update: I was able to get it to work by making sure the path to cl.exe I'd added to my PATH statement was the one pointing to C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64.  (In other words, point it to the version 12 cl.exe instead of the version 14 one.)  Now Cudafy.net is working in VS 2015 for me.


text:
Q: Select input appened to page I have an input field that is appended to a div tag through a location.href reload.  How would select that input field using jQuery?  If I add it to the page it won't work, I'm assuming because the input isn't loaded into the DOM yet.
$('#fileName1').focus(function() {
  alert('Handler for .focus() called.');
});

A: Use
$('#fileName1').live('focus', function() {
  alert('Handler for .focus() called.');
});


text:
Q: Audio detector work on device but not on simulator ... and accuracy Hi Sarem
Background
I have an application that detects when somebody says 'Hi Sarem' as a kind of electronic lock. I wanted to do something like 'Hi Siri' but since that is taken I went for something a bit different, like 'Hi Sarem'.
Implementation
The code samples audio from the mic, fits an FFT and then checks for three consecutive frequencies, so you could trigger it if you e.g. whistle or play the correct three notes on a piano as well. Those frequencies need to be triggered within a certain time from one another and are configurable using the sliders. The code contains the parameters you need to set timings and tolerances and so on. The three sliders represent the three 'notes' in 'Hi-Sa-rem'.
UI
The image here gives an idea of the UI. As the relevant frequencies are detected the bullets turn red and once the whole sequence is detected the big one turns red. The slider at the top acts as a monitor that continuously monitors the frequency 'heard' so you can use that to calibrate the notes.

Problem
I have a few problems with this. Accuracy is a big one but not the primary one. (I think if I had a scarier mama this might have been more accurate and also done by lunch but that is another story ...)
So here goes - the primary problem.
This works decently on a device, but on a simulator I get the following in the log
2020-07-26 18:47:13.543219+0200 HiSarem[68826:1238118] [plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x600000788320> F8BB1C28-BAE8-11D6-9C31-00039315CD46
2020-07-26 18:47:13.575866+0200 HiSarem[68826:1238118] No exclusivity (null)

I suspect it is to do with access rights but I am not sure. I looked everywhere I know but it does not make sense to me that the error will complain about a factory not being registered. Also, why is it working on the device and not in the simulator? Now I do print out that I could not get exclusive access to the device but even without requesting or locking the mic I still get the problem.
Code
This comes from the default ViewController that a single view app will give and I did describe how the UI is hooked up to it. So you should be able to paste it simply into a project and run it if you need to. This is a bit of a test project and not refined, but also in the spirit of MRE you have all the code.
#import <AVKit/AVKit.h>
#import <Accelerate/Accelerate.h>

#import "ViewController.h"

// Amplitute threshold
#define THRESHOLD    500

// Maximum frequency
#define MAXFREQ     7000

// Tolerance (% so 0.1 is 10%)
#define TOL          0.1

// Reset if no match within so many millis
#define RESETMIL    1500
#define BIGRESETMIL 5000

@interface ViewController () < AVCaptureAudioDataOutputSampleBufferDelegate >

@property (weak, nonatomic) IBOutlet UISlider  * monitorSlider;
@property (weak, nonatomic) IBOutlet UISlider  * phrase1Slider;
@property (weak, nonatomic) IBOutlet UISlider  * phrase2Slider;
@property (weak, nonatomic) IBOutlet UISlider  * phrase3Slider;

@property (weak, nonatomic) IBOutlet UILabel   * phrase1Label;
@property (weak, nonatomic) IBOutlet UILabel   * phrase2Label;
@property (weak, nonatomic) IBOutlet UILabel   * phrase3Label;
@property (weak, nonatomic) IBOutlet UILabel   * successLabel;

@property (nonatomic)         BOOL               busy;
@property (nonatomic, strong) AVCaptureSession * avSession;
@property (nonatomic, strong) AVCaptureInput   * avInput;
@property (nonatomic, strong) AVCaptureDevice  * avDevice;
@property (nonatomic, strong) AVCaptureOutput  * avOutput;

@property (nonatomic) double   prevF;
@property (nonatomic) NSDate * prevTime;

@end

@implementation ViewController

+ ( NSString * ) offText
{
    return @"⚫";
}

+ ( NSString * ) onText
{
    return @"";
}

// See if we can turn on for a given frequency
- ( BOOL ) turnOn:( double ) f
         want:( double ) w
{
    double wLo = w * ( 1 - TOL );
    double wHi = w * ( 1 + TOL );

    return self.prevF < wLo && f >= wLo && f <= wHi;
}

// Update the value
- ( void ) measure:( int    ) s
         n:( int    ) n
{
    // Convert
    double f = 44100.0 * s / n;

    if ( f <= MAXFREQ )
    {
        self.monitorSlider.value = f;

        // See where we are with the sliders
        if ( [self.phrase1Label.text isEqualToString:ViewController.offText] )
        {
            // See if we can turn on 1
            if ( [self turnOn:f want:self.phrase1Slider.value] )
            {
                self.phrase1Label.text = ViewController.onText;

                // Match
                self.prevTime = NSDate.date;
            }
        }
        else if ( [self.phrase2Label.text isEqualToString:ViewController.offText] )
        {
            // See if we can turn on 2
            if ( [self turnOn:f want:self.phrase2Slider.value] )
            {
                self.phrase2Label.text = ViewController.onText;

                // Match
                self.prevTime = NSDate.date;
            }
        }
        else if ( [self.phrase3Label.text isEqualToString:ViewController.offText] )
        {
            // See if we can turn on 3
            if ( [self turnOn:f want:self.phrase3Slider.value] )
            {
                self.phrase3Label.text = ViewController.onText;
                self.successLabel.text = ViewController.onText;

                // Big match
                self.prevTime = NSDate.date;
            }
        }
    }

    // Reset if we do not get a match fast enough
    if ( self.prevTime )
    {
        NSTimeInterval d = [NSDate.date timeIntervalSinceDate:self.prevTime] * 1000;

        if ( d > RESETMIL )
        {
            self.phrase1Label.text = ViewController.offText;
            self.phrase2Label.text = ViewController.offText;
            self.phrase3Label.text = ViewController.offText;
        }
        if ( d > BIGRESETMIL )
        {
            self.successLabel.text = ViewController.offText;
        }
    }
}

- ( void ) viewDidLoad
{
    super.viewDidLoad;
}

- ( void ) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if ( self.requestPermission )
    {
        self.startCapture;
    }
}

- ( void ) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    if ( self.avSession )
    {
        self.avSession.stopRunning;
        self.avSession = nil;
    }
}

- ( BOOL ) requestPermission
{
    if ( AVAudioSession.sharedInstance.recordPermission == AVAudioSessionRecordPermissionGranted )
    {
        return YES;
    }
    else if ( AVAudioSession.sharedInstance.recordPermission == AVAudioSessionRecordPermissionDenied )
    {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"No ears"
                                        message:@"I can not hear you - please change it quickly"
                                     preferredStyle:UIAlertActionStyleDefault];

        [alert addAction:[UIAlertAction actionWithTitle:@"Apologies"
                              style:UIAlertActionStyleDefault
                            handler:nil]];

        [self presentViewController:alert
                   animated:YES
                 completion:nil];

        return NO;
    }
    else
    {
        [AVAudioSession.sharedInstance requestRecordPermission:^ ( BOOL granted ) {

            if ( granted )
            {
                self.startCapture;
            }

        }];

        return NO;
    }
}

- ( void ) startCapture
{
    if ( ! self.busy )
    {
        self.busy = YES;

        // Create the capture session.
        NSError          * avErr;
        AVCaptureSession * captureSession = [[AVCaptureSession alloc] init];

        // Default anyhow
        captureSession.sessionPreset = AVCaptureSessionPresetHigh;

        // Lookup the default audio device.
        AVCaptureDevice * audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];

        if ( [audioDevice lockForConfiguration: & avErr] )
        {
            // Wrap the audio device in a capture device input.
            AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice
                                                  error: & avErr];

            audioDevice.unlockForConfiguration;

            if ( audioInput )
            {
                // If the input can be added, add it to the session.
                if ( [captureSession canAddInput:audioInput] )
                {
                    [captureSession addInput:audioInput];

                    AVCaptureAudioDataOutput * audioOutput = [[AVCaptureAudioDataOutput alloc] init];

                    if ( [captureSession canAddOutput:audioOutput] )
                    {
                        [audioOutput setSampleBufferDelegate:self
                                           queue:dispatch_queue_create ( "ears", NULL )];
                        [captureSession addOutput:audioOutput];

                        // Do on background
                        dispatch_async ( dispatch_queue_create ( "spotty", NULL ), ^ {

                            NSLog ( @"Come to papa" );
                            captureSession.startRunning;

                            // Done
                            dispatch_async ( dispatch_get_main_queue (), ^ {

                                self.busy      = NO;
                                self.avSession = captureSession;
                                self.avDevice  = audioDevice;
                                self.avInput   = audioInput;
                                self.avOutput  = audioOutput;

                            } );
                        } );
                    }
                    else
                    {
                        NSLog ( @"Not today : add output" );
                        self.busy = NO;
                    }
                }
                else
                {
                    NSLog( @"Sorry : add input" );
                    self.busy = NO;
                }
            }
            else
            {
                NSLog( @"Ooops %@", avErr );
                self.busy = NO;
            }
        }
        else
        {
            NSLog( @"No exclusivity %@", avErr );
            self.busy = NO;
        }
    }
}

#pragma mark -
#pragma mark Audio capture delegate

- ( void ) captureOutput:( AVCaptureOutput     * ) output
   didOutputSampleBuffer:( CMSampleBufferRef     ) sampleBuffer
      fromConnection:( AVCaptureConnection * ) connection
{
    CMItemCount n = CMSampleBufferGetNumSamples ( sampleBuffer );

    // We have our standards
    if ( n == 1024 )
    {
        AudioBufferList audioBufferList;

        CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer (
                                     sampleBuffer,
                                     NULL,
                                     & audioBufferList,
                                     sizeof ( audioBufferList ),
                                     NULL,
                                     NULL,
                                     kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
                                     & sampleBuffer
                                     );

        // Loop buffers
        for ( int b = 0; b < audioBufferList.mNumberBuffers; b ++ )
        {
            // Evaluate samples
            [self fft:audioBufferList.mBuffers [ b ].mData];
        }

        // Release the baby ... I mean buffer
        CFRelease ( sampleBuffer );
    }
}

- ( void ) fft:( SInt16 * ) samples
{
    // In place so r and i are both input and output
    COMPLEX_SPLIT c;

    float r [ 512 ];
    float i [ 512 ];

    c.realp = r;
    c.imagp = i;

    // Load it and calculate maximum amplitute along the way
    int amp = 0;

    for ( int s = 0; s < 512; s ++ )
    {
        SInt16 ev = samples [ s * 2     ];
        SInt16 od = samples [ s * 2 + 1 ];

        // Convert to float
        r [ s ] = ( float ) ev;
        i [ s ] = ( float ) od;

        if ( amp < ev )
        {
            amp = ev;
        }
        if ( amp < od )
        {
            amp = od;
        }
    }

    // Only proceed if we have a big enough amplitute
    if ( amp > THRESHOLD )
    {
        FFTSetup fft = vDSP_create_fftsetup ( 10, kFFTRadix2 );

        if ( fft )
        {
            // FFT!
            vDSP_fft_zrip ( fft, & c, 1, 10, FFT_FORWARD );

            // Get frequency
            int   maxS = 0;
            float maxF = 0;

            for ( int s = 1; s < 512; s ++ )
            {
                float f = r [ s ] * r [ s ] + i [ s ] * i [ s ];

                if ( f > maxF )
                {
                    maxF = f;
                    maxS = s;
                }
            }

            // Dealloc
            vDSP_destroy_fftsetup ( fft );

            // Done
            dispatch_async ( dispatch_get_main_queue (), ^ {

                [self measure:maxS
                        n:1024];

            } );
        }
    }
}

@end

Why does this work well on a device but refuses on a simulator?
Then, secondary question, since I did give all the detail here, any ideas on how to improve the accuracy or will that only be accomplished by using more frequency triggers?
TIA

A: Welcome to the world of debugging with only real devices cause Audio is involved and simulator can be picky with this.
Keep in mind that you want AVCaptureXYZ pointers set to nil/NULL before allocating anything to them. Audio is C business and Objective-C is not the ideal language to call methods that do buffer work fast fast fast. Even tho it works..
Nothing new yet.
Also you may want a device before opening any session, so AVCaptureSession can go after AVCaptureDevice initiation. I know the docs tell the oppsite.
But you don't need a session when there is no device, right? :)
when writing in dispatch_async(..., do self->_busy instead of self.busy. And dispatch_async(dispatch_get_main_queue(),^{}) is thread business, place it where it belongs, around the access to UIKit stuff. In example inside -(void)measure:(int)samples n:(int)n.
and do yourself a favour and change objective-C -(void)fft:(SInt16 *)samples;
to
void fft(SInt16* samples, int *result) {
    //do fast fourier transformation
}

if you need access to self inside this function, you are actually doing something close to wrong. Avoid using ObjC method calls in Audio threads. What about giving a void* pointer variable to this function to make self accessible from inside the function. Or pass a reference pointer to the function to change a given variables content. Or let it return the result instead.
And ignore this specific Simulator Warning. It's a warning that it adds an instance for factory because there where none yet with that CFUUID..
It is not a bug, it is because you run AV_XYZ-iOS stuff on Simulator which is OSX off course.
some tiny changes.. your float conversion could look like.
SInt16 amp = 0;
int s=0;
SInt16 evens;
SInt16 odds;
while ( s < 512 ) {
    evens = samples[s * 2    ];
    odds  = samples[s * 2 + 1];
    r[s] = (float)evens;
    i[s] = (float)odds;
    amp = MAX(amp,MAX(odds,evens));
    s++;
}

and in delegate Method -captureOutput:didOutputSampleBuffer:fromConnection:
CMItemCount numSamplesInBuffer = CMSampleBufferGetNumSamples(sampleBuffer);
// works only with 1024 samples
if ( numSamplesInBuffer == 1024 ) {
    AudioBufferList audioBufferList;
    CMBlockBufferRef buffer = CMSampleBufferGetDataBuffer(sampleBuffer);
    CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer,
                                 NULL,
                                 &audioBufferList,
                                 sizeof(audioBufferList),
                                 NULL,
                                 NULL,
                                 kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
                                 &buffer //now its correct pointer
                                 );

    //provide variable for feedback
    int result = 0;

    // Loop buffers
    int b = 0;
    for (; b < audioBufferList.mNumberBuffers; b ++) {
        // Evaluate samples
        // use C if possible, don't call ObjC in functions if possible
        fft(audioBufferList.mBuffers[b].mData, &result);
    }
    // later Release the baby ... I mean buffer <- yes buffer :)
    CFRelease(buffer);

    [self measure:result n:1024];
}


text:
Q: jQuery attach click event on empty select box using jQuery, how do i load select box options dynamically while clicking on the select box.
I am using redmine REST API's to load issue categories dynamically in to select box.
How do i attach event handler to the selectbox.
But this is not working, i.e event not attaching
<script>
    //dynamically load status values
    $('#newstatusField').on('click',function(){
        alert('inside');
    });
</script>
<select name="status" id="newstatusField" data-mini="true" data-native-menu="false">
 <!--dynamic option values -->
</select>

A: Always try to wrap the jQuery code inside document.ready fucntion and Change event will work for you :
Edit :  Also include latest jQuery library you can download from here jQuery Library
<head>

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>

<script>

    $(document).ready(function()
    {

         $('#newstatusField').on('change',function(){
            alert('inside');
         });

    });

    </script>

</head>


text:
Q: Filtering a File Array in Java How would I filter a File array to only assign pdf files to the array?
Some pseudo code for what I'm trying to accomplish:
File [] files; //this contains [3] array items

files.filter(pdf); //??

System.out.println("PDF only files:" files);

A: Use the FilenameFilter
File dir = new File("/your/dir");
File[] files = dir.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".pdf");
    }
});

A: If your pdf files end with .pdf you can simply filter on the name:
List<File> pdfs = new ArrayList<>();
for(File f : files) {
    if(f.getName().toLowerCase().endsWith(".pdf")) {
        pdfs.add(f);
    }
}

A: If you use Apache Commons you can also use SuffixFileFilter
File[] files = directory.listFiles(
    (FileFilter) new SuffixFileFilter(".pdf", IOCase.INSENSITIVE));


text:
Q: soft delete not working when $dateFormat="U" Im trying to import softDelete to current project. In migration file i added:
$table->softDeletes();

In model. I got this:
protected $dateFormat = 'U';

But deleting not working as i expected.

Invalid datetime format: 1292 Incorrect datetime value: '1579188678' for column 'deleted_at'

So my question is how can i use deleted_at as unix time or how to use deleted_at column as timestamp when protected $dateFormat = 'U'; this was still exist. Thanks in advance.

A: Since you want to use the Unix timestamp as format, you can't use the ->sofDeletes() and ->timestamps() methods in migration, you need to set them yourself as integers
$table->integer('created_at')->nullable();
$table->integer('updated_at')->nullable();
$table->integer('deleted_at')->nullable();


text:
Q: OCaml syntax for defining a helper function inside of another function? I apologize if this is a silly question, but I'm a newbie to OCaml and I wasn't able to find examples of this anywhere. Could somebody give me a simple example of the Ocaml syntax for defining a helper function inside of another function?
Thank you!

A: Here you go:
let outer x y =
  let inner z = x + z
  in inner y


text:
Q: Why is there no comma when adding multiple transforms in css If we want two background images we write:
background-image: url("img_tree.gif"), url("paper.gif"); // There's a comma between them!

But to use two transforms we write:
transform: rotate(90deg) skew(20deg); // No comma between them!

We is there no comma between the multiple transforms? Many other css properties use commas to indicate several parameters in one property.

A: This is actually a very good observation. Shame on these people saying it is just because. The spec isn't some magical tablet like the 10 commandments, that just appears into existence. It is extensively debated by several members of the community (mediated by W3), until there is some sort of consensus. Then the developers (mostly browser developers I imagine) will take the specs and implement. The interesting part is that the debate is open and public. So not only you can participate by giving your opinion on upcoming specs, but you can also search back and find out all the arguments that led to a consensus: https://lists.w3.org/Archives/Public/www-style/2004Oct/
I haven't read the whole discussion, but I can imagine that an implementation without commas would be harder and less predictable, since each background holds a set of properties. So for example, on the background shorthand it would be impossible to say where one background declaration starts and the other one ends, since there are no required properties. Like background: red url(img.png);. Is that one bg or two? And this is definitely two: background: red, url(img.png);
That is just what pops up in my head, but if you dig into the discussion you will see that there are all sorts of considerations, like the effect on other APIs, like js, backwards compatibility, etc


text:
Q: What is denormalization in Firebase Cloud Firestore? What is really this denormalization all about when talking about Firebase Cloud Firestore? I read a few articles on the internet and some answers here on stackoverflow and most of the answers recommend this approach. How does this denormalization really help? Is it always necessary?
Is database flatten and denormalization the same thing?
It's my fist question and hope I'll find an answer that can help me understand the concept. I know is different, but I have two years of experience in MySQL.

A:
What is denormalization in Firebase Cloud Firestore?

The denormalization is not related only to Cloud Firestore, is a technique generally used in NoSQL databases.

What is really this denormalization?

Denormalization is the process of optimizing the performance of NoSQL databases, by adding redundant data in other different places in the database. What I mean by adding redundant data, as @FrankvanPuffelen already mentioned in his comment, it means that we copy the exact same data that already exists in one place, in another place, to suit queries that may not even be possible otherwise. So denormalization helps cover up the inefficiencies inherent in relational databases.

How does this denormalization really help?

Yes, it does. It's also a quite common practice when it comes to Firebase because data duplication is the key to faster reads. I see you're new to the NoSQL database, so for a better understanding, I recommend you see this video, Denormalization is normal with the Firebase Database. It's for Firebase realtime database but the same principles apply to Cloud Firestore.

Is it always necessary?

We don't use denormalization just for the sake of using it. We use it, only when it is definitely needed.

Is database flatten and denormalization the same thing?

Let's take an example of that. Let's assume we have a database schema for a quiz app that looks like this:
Firestore-root
    |
    --- questions (collections)
          |
          --- questionId (document)
                 |
                 --- questionId: "LongQuestionIdOne"
                 |
                 --- title: "Question Title"
                 |
                 --- tags (collections)
                      |
                      --- tagIdOne (document)
                      |     |
                      |     --- tagId: "yR8iLzdBdylFkSzg1k4K"
                      |     |
                      |     --- tagName: "History"
                      |     |
                      |     --- //Other tag properties
                      |
                      --- tagIdTwo (document)
                            |
                            --- tagId: "tUjKPoq2dylFkSzg9cFg"
                            |
                            --- tagName: "Geography"
                            |
                            --- //Other tag properties

We can flatten the database by simply moving the tags collection in a separate top-level collection like this:
Firestore-root
    |
    --- questions (collections)
    |     |
    |     --- questionId (document)
    |            |
    |            --- questionId: "LongQuestionIdOne"
    |            |
    |            --- title: "Question Title"
    |
    --- tags (collections)
          |
          --- tagIdOne (document)
          |     |
          |     --- tagId: "yR8iLzdBdylFkSzg1k4K"
          |     |
          |     --- tagName: "History"
          |     |
          |     --- questionId: "LongQuestionIdOne"
          |     |
          |     --- //Other tag properties
          |
          --- tagIdTwo (document)
                |
                --- tagId: "tUjKPoq2dylFkSzg9cFg"
                |
                --- tagName: "Geography"
                |
                --- questionId: "LongQuestionIdTwo"
                |
                --- //Other tag properties

Now, to get all the tags that correspond to a specific question, you need to simply query the tags collection where the questionId property holds the desired question id.
Or you can flatten and denormalize the database at the same time, as you can see in the following schema:
Firestore-root
    |
    --- questions (collections)
    |     |
    |     --- questionId (document)
    |            |
    |            --- questionId: "LongQuestionIdOne"
    |            |
    |            --- title: "Question Title"
    |            |
    |            --- tags (collections)
    |                 |
    |                 --- tagIdOne (document) //<----------- Same tag id
    |                 |     |
    |                 |     --- tagId: "yR8iLzdBdylFkSzg1k4K"
    |                 |     |
    |                 |     --- tagName: "History"
    |                 |     |
    |                 |     --- //Other tag properties
    |                 |
    |                 --- tagIdTwo (document) //<----------- Same tag id
    |                       |
    |                       --- tagId: "tUjKPoq2dylFkSzg9cFg"
    |                       |
    |                       --- tagName: "Geography"
    |                       |
    |                       --- //Other tag properties
    |
    --- tags (collections)
          |
          --- tagIdOne (document) //<----------- Same tag id
          |     |
          |     --- tagId: "yR8iLzdBdylFkSzg1k4K"
          |     |
          |     --- tagName: "History"
          |     |
          |     --- questionId: "LongQuestionIdOne"
          |     |
          |     --- //Other tag properties
          |
          --- tagIdTwo (document) //<----------- Same tag id
                |
                --- tagId: "tUjKPoq2dylFkSzg9cFg"
                |
                --- tagName: "Geography"
                |
                --- questionId: "LongQuestionIdTwo"
                |
                --- //Other tag properties

See, the tag objects are the same as well in users -> uid -> tags -> tagId as in tags -> tagId. So we flatten data to group somehow existing data.
For more information, you can also take a look at:

*

*What is the correct way to structure this kind of data in Firestore?
Because you say you have a SQL background, try to think at a normalized design which will often store different but related pieces of data in separate
logical tables, which are called relations. If these relations are stored physically as separate disk files, completing a query that draws information from several relations (join operations) can be slow. If many relations are joined, it may be prohibitively slow. Because in NoSQL databases, we do not have "JOIN" clauses, we have to create different workarounds to get the same behavior.


text:
Q: Eclipse microprofile metrics @Timed does measure time, always 0 we have a problem with eclipse microprofile metrics @Timed annotation.
It does not seem to measure times (only counts number of calls).
Setup is with Payara 5 full.
Typical output via http://localhost:8080/metrics/application:
    # TYPE application:total_coffees_retrieved counter
application:total_coffees_retrieved 4
# TYPE application:total_coffees_consumed counter
application:total_coffees_consumed 4
# TYPE application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_rate_per_second gauge
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_rate_per_second 1.4044150172871745
# TYPE application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_one_min_rate_per_second gauge
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_one_min_rate_per_second 0.0
# TYPE application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_five_min_rate_per_second gauge
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_five_min_rate_per_second 0.0
# TYPE application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_fifteen_min_rate_per_second gauge
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_fifteen_min_rate_per_second 0.0
# TYPE application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_mean_seconds gauge
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_mean_seconds 0.0
# TYPE application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_max_seconds gauge
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_max_seconds 0.0
# TYPE application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_min_seconds gauge
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_min_seconds 0.0
# TYPE application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_stddev_seconds gauge
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_stddev_seconds 0.0
# TYPE application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_seconds summary
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_seconds_count 4
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_seconds{quantile="0.5"} 0.0
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_seconds{quantile="0.75"} 0.0
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_seconds{quantile="0.95"} 0.0
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_seconds{quantile="0.98"} 0.0
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_seconds{quantile="0.99"} 0.0
application:com_sebastian_daschner_hello_prometheus_coffees_retrieve_coffee_seconds{quantile="0.999"} 0.0

mean, max, quantiles are all "0.0", while count works well (= 4).
We have tried multiple combinations of Payara/JEE/Microprofile versions, each with the same result.
Here are some code snippets (base is taken from https://github.com/sdaschner/hello-prometheus/tree/microprofile, only added @Timed)
Coffee-Bean:
@ApplicationScoped
public class Coffees {

    @Counted(name = "total_coffees_retrieved", absolute = true, monotonic = true)
    @Timed
    public String retrieveCoffee() {
        try {
            Thread.sleep((int) (1000 * Math.random()));
        } catch (InterruptedException ex) {
            Logger.getLogger(Coffees.class.getName()).log(Level.SEVERE, null, ex);
        }

        return "Coffee!";
    }

}

JAX-RS REST Resource:
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("coffee")
public class CoffeesResource {

    @Inject
    Coffees coffees;

    @GET
    public String getCoffee() {
        return coffees.retrieveCoffee();
    }

}

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sebastian-daschner</groupId>
    <artifactId>hello-prometheus</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.microprofile.metrics</groupId>
            <artifactId>microprofile-metrics-api</artifactId>
            <version>1.1.1</version> <!-- also tried 1.0 and 1.1 -->
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>hello-prometheus</finalName>
    </build>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

Any ideas how to solve this?
EDIT: does not occur when requesting metrics with application/json
curl -H "Accept: application/json" http://localhost:8080/metrics/application

Issue is already solved for one of the next payara releases:
https://github.com/payara/Payara/issues/2970

A: If you want to see something other than 0 you will need to have a method that takes some more time to execute! Simply incrementing a counter and returning a string like that will take hardly any time at all, definitely far less than 0.1 seconds, so you'll never see any value in your metrics.
Try adding Thread.sleep(1500) to the method to see if the timer logs 1.5 seconds.
Since @Timed gives you lots of statistics, you could also try Thread.sleep(Math.random() * 1000) to give you some variation in the amount of time it takes to execute and give you more interesting metrics to examine.
Edit: As mentioned in the comments below, there appears to be a bug in Payara Micro 5.182 which results in the timer not working.


text:
Q: Restrict API access to my Frontend app using daily random API key I'm creating an API that will be accessed solely by my Vue.js application for displaying data like movie times, video on demand links, etc. No private sensitive info, but I would like to avoid other people and bots using my resources to get free data. I know restricting an API to my own one-page frontend application is almost impossible, as someone can always either:

*

*Get the API key from the page source

*Spoof the referrer header to the one that my API is restricted to

So I was thinking to "attenuate the damage", i.e. the amount of bots using my API, by having the backend server generate an API key every day at noon for example. Then when the PHP loads the Vue.js application, it inserts that API key in the Vue.js code, which will use it to query my Python API. If Vue gets an "incorrect API key" error (case when the page was loaded at 11:59 and a request was sent at 12:01), the Vue.js would refresh the page to get the new key.
This way, if someone took the API key from the source, it would expire in less than 24 hours anyways. Of course someone could scrape the page to get the API key every day and still use the API, but I feel this would stop a lot of bots and spammers.
Has anyone ever tried anything like this? Does it sound like a viable solution or there is something better to be done that I couldn't find on StackOverflow?

A: How about Server-side Rendering from the same location (server, private DNS) as the API server?
You can write fetch(api) within the server function itself.


text:
Q: Problema com Font Face Estou usando Font face no WORDPRESS, e na hospedagem local (WAMP) ele pega a font, porem quando publico online ele não pega a font que quero.
a pasta da font está em:
ONLINE: public_html/wp-content\themes\eddiemachado-bones-cfbfb62\library\fonts
LOCAL: localhost/ecg/wp-content\themes\eddiemachado-bones-cfbfb62\library\fonts
@font-face {
    font-family: 'Aileron-SemiBoldItalic';
    src: url('../fonts/Aileron-SemiBoldItalic.eot');
    src: url('../fonts/Aileron-SemiBoldItalic.eot?#iefix') format('embedded-opentype'),
         url('../fonts/Aileron-SemiBoldItalic.woff') format('woff'),
         url('../fonts/Aileron-SemiBoldItalic.ttf') format('truetype'),
         url('../fonts/Aileron-SemiBoldItalic.svg#Aileron-SemiBoldItalic') format('svg');
    font-weight: normal;
    font-style: normal;
}