text:
Q: How can I make the user add a new field using a button using javascript? I have a script posted down below, and I want the user to add a new field, when the new field gets added I want a new var to be added.
Live example:
User clicks on the "add new field"
var gets added below var Reason2 called Reason3, Reason4, etc.
"Reason Three: " +Reason3+ gets added below Reason Two on line 51.
I don't have an idea of how to do the above honestly.
<!DOCTYPE html>

<form name="TRF" method="post">

Accepted Format

Accepted Format

                  Applicant's Name:
                  <input type="text" name="accname" size="75" placeholder="" required>

                  Reason 1:
                  <input type="text" name="R1" size="75" placeholder="" required>

                  Reason 2:
                  <input type="text" name="R2" size="75" placeholder="" required>

CODE:

              <textarea  id="box" cols="100" rows="10"></textarea>

GENERATE CODE

            <button id="newField">
            add new field
            </button>

</color>

User clicks on the "add new field"
var gets added below var Reason2 called Reason3, Reason4, etc.
"Reason Three: " +Reason3+ gets added below Reason Two on line 51.

A: In Javascript it's possible to create html elements at runtime using the createElement() function. In your case we need to create quite a lot of individual elements to replicate the structure of the table. Those are
  <input>.
The tr element needs to be added to the table, the td containing the text 'Reason #:' as well as the td holding the input element are childs of tr. To add a dynamically created element to the DOM, the appendChild() function is used.
The input element needs some special treatment because it contains an unique id. The two html-made elements you have are 'R1' and 'R2' - so a new one should follow that pattern and start with 3. This is done by setting up a global variable , appending it to the name and increment it afterwards.
Finally we need to add a 'Create new field' button.
Take a look at this example (you have to scroll down to see the button):

var newField = document.getElementById("newField");
var counter = 3;

function createNewField() {
  var tr = document.createElement("tr");
  var td1 = document.createElement("td");
  var td2 = document.createElement("td");
  td1.innerHTML = "Reason " + counter + ":";
  var inp = document.createElement("input");
  inp.type = "text";
  inp.size = "75";
  inp.name = "R" + counter;
  td2.appendChild(inp);

  document.getElementById("theTable").appendChild(tr);

  tr.appendChild(td1);
  tr.appendChild(td2);

  counter++;
}
newField.addEventListener("click", createNewField);

function generateCode2() {
  var AccoutName = document.forms["TRF"]["accname"].value;
  var reasons = "";

  for (var a = 1; a < counter; a++) {
    reasons += "Reason " + a + ": " + document.forms["TRF"]["R" + a].value + "\n";
  }

  document.getElementById("box").value =
    "[center][img width=500 height=500]https://i.imgur.com/FuxDfcy.png[/img][/center]" +
    "[hr]" +
    "\n" +
    "[b]Dear[/b] " + AccoutName +
    "\n" +
    "After reading your Application, Imperials staffs have decided to [color=green][b]Accept[/b][/color] you. " +
    "\n" + reasons +
    "Welcome to the Family. " +
    "\n" +
    ""
}
<form name="TRF" method="post">

Accepted Format

Accepted Format

                  Applicant's Name:
                  <input type="text" name="accname" size="75" placeholder="" required>

                  Reason 1:
                  <input type="text" name="R1" size="75" placeholder="" required>

                  Reason 2:
                  <input type="text" name="R2" size="75" placeholder="" required>

CODE:

              <textarea id="box" cols="100" rows="10"></textarea>

GENERATE CODE

            <button id="newField">
            add new field
            </button>


text:
Q: asp.net with autofac - all controls on webform are null I'm using autofac with asp.net. In Global.asax I register all my web pages:
AssertNotBuilt();
// Register Web Pages
m_builder.RegisterAssemblyTypes(typeof(AboutPage).Assembly)
  .Where(t => t.GetInterfaces().Contains(typeof(IHttpHandler)))
  .AsSelf().InstancePerLifetimeScope();

m_container = m_builder.Build();
m_wasBuilt = true;

Then I use a custom httpHandler to get the current web page:
    public class ContextInitializerHttpHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            //Get the name of the page requested
            string aspxPage = context.Request.Url.AbsolutePath;

            if (aspxPage.Contains(".aspx"))
            {
                // Get compiled type by path
                Type webPageBaseType = BuildManager.GetCompiledType(aspxPage).BaseType;

                // Resolve the current page
                Page page = (Page)scope.Resolve(webPageBaseType);

                //process request
                page.ProcessRequest(context);

            }
        }
        public bool IsReusable
        {
        get { return true; }
        }
  }

All works ok, but then when it enters the web page_load, I see that all the asp controls that exist on the page are null. Why are they null and how do I initialize them?

A: I figured it out. The pages that I registered aren't compiled like the pages that I can take from the context in my http handler:
string aspxPage = context.Request.Url.AbsolutePath;
Type webPageBaseType = BuildManager.GetCompiledType(aspxPage);

and these are the pages that I need that do hold all the controls. The problem is, I can't register them at my http handler because they are dynamic and look in a form of somewebpage_aspx and the assembly is App_Web_somewebpage.aspx.cdcab7d2.r3x-vs2n, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null.
So the solution (or hack..) was not to register the web pages, and instead resolve the page controls from the scope:
ILifetimeScope scope = IocInitializer.Instance.InitializeCallLifetimeScope();
Type webPageType = BuildManager.GetCompiledType(aspxPage);
Page page = (Page)Activator.CreateInstance(webPageType);

foreach (var webPageProperty in webPageType.GetProperties(BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.Public))
{
    if (scope.IsRegistered(webPageProperty.PropertyType))
    {
        var service = scope.Resolve(webPageProperty.PropertyType);
        webPageProperty.SetValue(page, service, null);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do something before app removing I've got an app that stores few files on sd card. I want my app to remove those files, if user wants to delete the application. How can I do that? Is there a method like onDelete() or something?

A:
I've got an app that stores few files on sd card. I want my app to
  remove those files,

Don't store them directly on the sdcard. Use the app's cache space or the directory pointed by getExternalFilesDir. Both are cleaned up by the system when the app is uninstalled

A: No, there is no way for you app to know when it is being deleted/removed from a device.

Intent.ACTION_PACKAGE_REMOVED
Broadcast Action: An existing application package has been removed from the device.
  The data contains the name of the package. The package that is being installed does not receive this Intent.

This comes mostly because if a code would be executed on the app that was about to be removed some might prevent removal etc.
You should provide an option to your users to wipe sdcard data, or use another storage option (that is linked to your app), but I guess you're using the sdcard on purpose.


text:
Q: LoaderManager.onLoadFinished is called even when the specific query doesn't match the update I have a Android app which has a Content Provider which I update frequently. To load the lists of the said data, I'm using a LoaderManager.
On the detail page, I also use a LoaderManager, but I create the CursorLoader like this:
return new CursorLoader(getActivity(), DataProvider.POST_URI, projection, "_id = ?", new String[]{String.valueOf(post_id)}, null);

As you can see, I'm only getting a single item from the table. When the row is updated the the onLoadFinished callback is updated, but, also, when other rows are added/modified to the table. It wouldn't be much of a hassle, but sometimes, it causes the whole list to get blank and redrawn, which can be frustrating for the user when it happens multiple times.
Do you know how could I avoid this behavior?

A: The reloading is taking place because you are associating this cursor loader with the DataProvider.POST_URI which I assume is the one you use for your posts table. Whenever there is a change in any of the elements in this table, all the cursors with that Uri will be notified. If you want to receive notification of a single item you should implement a new Uri scheme to match just that one item. Have a look at the documentation for the UriMatcher class for an example. You should do something similar to the PEOPLE and PEOPLE_ID cases.
EDIT
You can find a good tutorial on ContentProvider here. Section 9.4 in special should be helpful in correctly implementing the ContentProvider.


text:
Q: How to increase the throughput of elastic beanstalk server? Here is my configuration for elastic beanstalk:
We are using Elastic Beanstalk with ngnix puma on m3.medium instances for our Rails application based on Ruby-2.2.3 and Rails 3.2.22.
We are using m4.large RDS for postgresql server with 3000 provisional IOPS and 300 Storage space.
The max_pool for database connection is set to 20.
Our database shows it allows around 250 connections.
Still, our server gets 5xx errors and the load balancer instances spin up frequently. Our IOPS consumption is always high. During a large product pull from FTP locations, the Read IOPS goes up to 3000 IOPS and write IOPS goes up to 400 IOPS.
The production log shows that the 5xx errors are generated because of no connection available to the database. Max connection is set to 20. Please consider to increase it.
For product pulling we have implemented batch product search(upto 30 products) instead of searching single product every time.
This IOPS is also high when the product pull is also not running.
We have also implemented Elastic Cache,  Delayed Job, Fragment Caching
, Eager Loading etc. to optimize our code.
Possible Reasons:
We have

*

*around 6 million products We pull around 1 million products everyday
during EST night time.

*We are using sunspot solr in a separate server which reindex the products once in a week.

*Number of requests as per EBS report is 7.2K per hour


text:
Q: The correct definition of Klein Factor Klein factors are the operators which make sure that the anticommutation between the different species is correct during the bosonization procedure. According to this famous review by Jan Von Delft, they are the operators responsible for raising or lowering the fermionic number. But most of the literature often tend to ignore this factor. Recently I have come across this paper where they have given an explicit representation of the Klein factors (in appendix A). But unfortunately, this representation can't connect the different fermionic particle number states. I am really confused with what exactly is Klein factors are. Please help me resolve my doubt.

A: Preface
Fully understanding Klein factors is one of those things that doesn't really matter, except for when it does... I think that's why you'll find many different, seemingly incompatible versions in the literature. I also found this confusing when I was learning bosonization, so I feel you. Eventually I stumbled on the lecture notes by Schultz, Cuniberti, and Pieri, which proved very helpful. (In the arXiv version, the relevant discussion is after Eq. (4.17), and in the appendix. In the version published by Springer, it's after Eq. (2.96), and in the appendix. Haldane's derivation in his 1979 paper (paywalled) might also be useful, although it's considered less straight-forward.)
What's the right definition?
We often start with a fermionic Hamiltonian, and bosonize that. As you say, the idea of Klein factors is to ensure that the bosonized version faithfully replicates the fermionic one. There are two things the bosonic fields cannot do, for which the cure is to introduce the Klein factors

*

*Ensuring anticommutation between different fermion species

*Connect different fermion number sectors

The definition given in von Delft and Schoeller achieves precisely this. When we are interested in thermodynamic properties (e.g. correlation functions as $L\rightarrow \infty$), however, the fact that the Klein factors change the particle number amounts to a vanishing shift in $k_F$. Hence, this structure is often neglected, and one is left with a much simpler-looking Klein factor. Often a representation in terms of Dirac gamma matrices is used, which obeys the familiar Clifford algebra. (These are often viewed as some kind of fictitious Majorana fermion.) In my experience this is the most common form of Klein factors encountered in the literature.
Suppose then that we work in the thermodynamic limit, and have opted for a "Majorana" representation for our Klein factors, which I'll denote $\eta$. We bosonize all the terms in our Hamiltonian, and decide to group them according to their Klein factor parts. If these (for a lack of a better word) "Klein factor prefactors" commute, we can assume we are in a certain sector of this $4\times 4$ Klein space, and replace these prefactors by their eigenvalues. This can be considered a sort of gauge fixing.
For a good example of how this works in practice, see the appendix of the Schultz et al. lecture notes. If we actually do this, replace these prefactors by their eigenvalues, why, we have achieved a purely bosonic Hamiltonian! A considerable part of the literature makes this jump right away, and assumes that is possible - ignoring the Klein factors, as it were. To be fair, this is usually possible, at least in many physically relevant cases, such as fermions with internal SU(N) symmetry.
So long story short, depending on what system you aim to describe, different appropriate choices of Klein factors may be available.
About the Klein factors in the Teo and Kane paper
I haven't checked this carefully, but I expect that they implicitly assuming they're in the thermodynamic limit. Then all we need the Klein factor for is to get the anticommutation relations right, which can be achieved in different ways (as is noted in e.g. Sénéchal's notes on bosonization). You'll note that the form they're using in Eq. (A3) is very similar to the way anticommutation relations are enforced in the Jordan-Wigner transformation from spins to fermions. The advantage of this kind of Klein factor* is that there is no need to introduce an extra Hilbert space for the Klein eigenstates to live in.
*I'm not sure that's an appropriate name, but they use it, so I'll stick with it.


text:
Q: Sometimes can't assign to array and sometimes can I have the next code:
Function findRanges(keyword) As Variant()

Dim foundRanges(), rngSearch As Range
Dim i, foundCount As Integer

i = 0
foundCount = 0
ReDim foundRanges(0)

Set rngSearch = ActiveDocument.Range
    Do While rngSearch.Find.Execute(FindText:=keyword, MatchWholeWord:=True, Forward:=True) = True
        Set foundRanges(i) = rngSearch.Duplicate
        i = i + 1
        ReDim Preserve foundRanges(UBound(foundRanges) + 1)
        rngSearch.Collapse Direction:=wdCollapseEnd

    Loop

ReDim Preserve foundRanges(UBound(foundRanges) - 1)

findRanges = foundRanges

End Function

And:
Sub test()
Dim rngIAM_Code() As Range
...
Dim rngIAM_Title() As Range

rngIAM_Code = findRanges("IAM_Code")
...
rngIAM_Title = findRanges("IAM_Title")

End Sub

What is very confuding is that sometimes the compiler says "Can't assign to array" and sometimes it works fine. For example, when I only try to search one value and populate one array, the code works. When I try to populate both array, there is an error "Can't assign to an array". I can then switch lines of code like this:
rngIAM_Title = findRanges("IAM_Title")
...
rngIAM_Code = findRanges("IAM_Code")

And then the error happens with another array. The error can happen anywhere: on the first line, in the middle, or in the end, but it is consistent as long as I don't move lines. And again, if I leave only one-two lines of code with arrays in sub "test"everything works fine.

A: The following works for me.
In this code, every object variable is explicitly assigned a type. In VBA, every variable must be typed, else it's assigned the type Variant by default. In the following declaration line, for example, foundRanges() is of type Variant because it's not followed by As with a data type. The same with i in the next line of code in the question.
Dim foundRanges(), rngSearch As Range

And since the arrays in the calling procedure are of type Range the function should return the same type.
I also took the liberty of passing the Document object to the function as, conceivably, some day the document in question might not be ActiveDocument but a Document object assigned using Documents.Open or Documents.Add. If this is not desired it can be changed back, but not relying on ActiveDocument is more reliable...
Additionally, I added the Wrap parameter to Find.Execute - it's always a good idea to specify that when executing Find in a loop to prevent the search from starting again at the beginning of the document (wdFindContinue).
Sub testRangesInArrays()
    Dim rngIAM_Code() As Range
    Dim rngIAM_Title() As Range

    rngIAM_Code = findRanges("You", ActiveDocument)
    rngIAM_Title = findRanges("change", ActiveDocument)
End Sub

Function findRanges(keyword As String, doc As Word.Document) As Range()
    Dim foundRanges() As Range, rngSearch As Range
    Dim i As Integer, foundCount As Integer

    i = 0
    foundCount = 0
    ReDim foundRanges(0)

    Set rngSearch = doc.content
    Do While rngSearch.Find.Execute(findText:=keyword, MatchWholeWord:=True, _
                       Forward:=True, wrap:=wdFindStop) = True
        Set foundRanges(i) = rngSearch.Duplicate
        ReDim Preserve foundRanges(UBound(foundRanges) + 1)
        i = i + 1
        rngSearch.Collapse Direction:=wdCollapseEnd
    Loop

    findRanges = foundRanges

End Function

A: Here is an alternative based on a Collection instead of an Array:
I used also included Cindys Input regarding passing the document and adding wrap.
I don't exactly know what the you use the return value for, but in general a collection is a bit more flexible than an Array.
I also removed the underscores since they indicate a function of an implemented Interface and may cause problems later down the line. are used when implementing an Interface (improves readability).
As explained here you can use wrap or collapse to prevent a continuous Loop.
Option Explicit

Sub test()
    Dim rngIAMCode As Collection
    Dim rngIAMTitle As Collection

    Set rngIAMCode = findRanges("IAM_Code", ActiveDocument)
    Set rngIAMTitle = findRanges("IAM_Title", ActiveDocument)

    Debug.Print "Code found : " & rngIAMCode.Count & " Times."
    Debug.Print "Title found : " & rngIAMTitle.Count & " Times."

End Sub

Function findRanges(ByVal keyword As String, doc As Document) As Collection

    Set findRanges = New Collection
    Dim rngSearch As Range

    Set rngSearch = doc.Content
    With rngSearch.Find
        .Text = keyword
        .MatchWholeWord = True
        .Forward = True
        .Wrap = wdFindStop

        While .Execute
            findRanges.Add rngSearch.Duplicate
            rngSearch.Collapse Direction:=wdCollapseEnd
        Wend

    End With
End Function


text:
Q: how to keep displaying a border bottom for a link element when a user is active on a page When I click on one link in the navbar I want my border bottom to keep displaying
There are two behaviours :
- On hover : display the border-bottom.
- When active on the link keep displaying the border-bottom (the user is active on the page).
I don't find how to do this, can someone help me ? thank you !

*

*File scss -

 a {
    span {
     padding-bottom: 5px;
    }
   }
   a:nth-child(1) :hover {
    border-bottom: 3px solid "blue";
   }
   a:nth-child(2) :hover {
    border-bottom: 3px solid #8e1cfb;
   }

*

*react component navbar tsx file -

       <Link to={`${process.env.REACT_STATIC_PUBLIC_PATH}`}>
        Link 1
       </Link>
       {''}
       <Link to={`${process.env.REACT_STATIC_PUBLIC_PATH}`}>
        Link 2
       </Link>

A: Just handle the active class in your css.For example .active {
    color: white;
    border-bottom: 3px solid #2196f3;
  }
Since you're using react router Link, you'll get active class added by default when the route is active.

A: [Edit]: My solution below works fine but does not use the default 'active' class added by react router itself when you click on a Link. I played with it on This Stackblitz for react-router (You will need to update package and change Link to NavLink if you are using router v5) but couldn't make the active class work properly, the active class wasn't removed from the first Link, don't know why (But you can inspect the code and you'll see it is added to your other links).
Now, if you want, there is also a activeStyle you can use (Not recommanded, bleh).

Your links are all first child of a div so you could do :
const App = () => {
  const setActiveLink = e => {
    // easier for me, you can change with getElementById or getElementByClassName
    const links = document.getElementsByTagName("a");

    Array.from(links).forEach(el => el.classList.remove("active"));
    e.target.classList.add("active");
  };

  return (

        link 1

        link 2

        link 3

  );
};

Adn in your css simply add :
div > a {

  text-decoration: none;
  padding: 5px;
}

div > a:hover{
  border-bottom: 1px solid red;
}

.active {
  border-bottom: 1px solid red;
}

Of course you have to adapt the the css tags I chose to match your code. Here the stackblitz for exemple : Example on Stackblitz


text:
Q: Can Only Access Site Via Localhost Have a have a Windows VPS using Plesk 9.
Until today I have been using the http://myIPaddress:8443 method of accessing Plesk Panel but now I can't access via a browser.
This is the Google Chrome error (Error 101 (net::ERR_CONNECTION_RESET): Unknown error).
If I use an RDC connection and open a browser window and connect via http://localhost:8443 it works just fine.
What could have gone wrong?

A: The ERR_CONNECTION_RESET indicates that the communication between your browser and your server is cut short, in effect, your browser is asking your server "What's up!" and before your server can respond, the communication drops.
This can be several things. It could be the firewall on your server. It could be a firewall on your internet connection and/or PC or it could be your ISP itself.
If you have the ability to try a different ISP (maybe even from a different PC, like an internet cafe) to test that it's not on your end, you can eliminate any software on your PC or your own network from this almost instantly.
Using RDP and being able to access your Plesk installation on the server itself indicates that there's nothing wrong, it could be as simple as just a piece of software you installed or setting you changed by accident. (Peerblock sometimes block's communication that's legitimate)
The last thing you can check is (if you're running IIS, which I assume you are) to check on the website settings which IP addresses, for that installation, is allowed. It could be that it's set to 127.0.0.1, by default I'd keep it to listen on all IP addresses if I were you.
Otherwise, if you've checked from a different ISP and computer and you're still not able to access it, I'd recommend submitting a support ticket with your hosting company to double check the installation.


text:
Q: My first backbone model / view. Am I on the right track? The goal is to build a UI to select a make, size, and color for a T-shirt. Not all colors are available for every size, and not all sizes/colors are available for every make.
So the basic UI is three select elements for make, size, and color.
After reading a bunch of tutorials, I started out by creating models for Make, Size, and Color, and collections for Makes, Sizes, Colors, and views for each, and code to connect them.. and sort of lost my mind.
Second attempt is here, where I created a single "Confg" model, and a single "Config" view. The model as attributes for the current make, size, and color, and also attributes for the currently select-able makes, models, and colors.
Is this how you, you being a seasoned backbone.js expert, would have approached this?
Here's the model. Basically, I "manually" handle fetching correct sizes / colors in the setMake method, and correct colors in the setSize method, and then set the necessary changes on the model.
var design_id = 2; // set server-side

var ConfigModel = Backbone.Model.extend({

    initialize: function(){
      this.baseUrl = "/designs/" + design_id + "/configure/";
    },

    setMake: function(make_id){
      var me = this;
      var make = _.find(this.get("makes"), function(el){
                  return el.id == make_id });
      // aggregate changes to the model:
      var changes = {
        "make": make
      };
      // get current make/size/color:
      var cur_make_id = make.id;
      var cur_size_id = this.get("size").id;
      var cur_color_id = this.get("color").id;

      // get sizes for the current make:
      $.getJSON(me.baseUrl + "makes/" + cur_make_id + "/sizes/",
           function(data){
            changes.sizes = data;
            if(!_.find(data, function(el){
                  return el.id == cur_size_id })){
            // the currently selected size is not available,
            // so use the first size
            changes.size = data[0];
            cur_size_id = changes.size.id;
          }
        // and get the colors for the current make and size:
        $.getJSON(me.baseUrl + "makes/" + cur_make_id
               + "/sizes/" + cur_size_id + "/colors/",
             function(data){
               changes.colors = data;
               if(!_.find(data,
                      function(el){
                         return el.id == cur_color_id })){
                          // the currently selected color
                          // is not available,
                          //so use the first one in the list
                     changes.color = data[0];
                       }
                me.set(changes);
              });
         });
      },

    setSize: function(size_id){
      // retrieve colors for the new size
      var me = this;
      var size = _.find(this.get("sizes"),
              function(el){ return el.id == size_id });
      var changes = {
        "size": size
      };

      var cur_make_id = this.get("make").id;
      var cur_size_id = size.id;
      var cur_color_id = this.get("color").id;

      $.getJSON(me.baseUrl + "makes/" + cur_make_id +
                "/sizes/" + cur_size_id + "/colors/",
          function(data){
             changes.colors = data;
             if(!_.find(data,
                function(el){
                  return el.id == cur_color_id })){
             changes.color = data[0];
          }
          me.set(changes);
      });
    },

    setColor: function(color_id){
      var color = _.find(this.get("colors"),
             function(el){
                return el.id == color_id });
      this.set({"color": color});
    }
  });

Here's the model instance. The initial defaults are set server-side:
  var Config = new ConfigModel({
    design_id: 2,

    make: {"id": 1, "name": "Men's Organic Cotton Tee"},
    size: {"id": 4, "name": "L"},
    color: {"id": 2, "name": "Black"},

    makes: [{"id": 2, "name": "Women's Organic Cotton Tee"},
            {"id": 1, "name": "Men's Organic Cotton Tee"}],
    sizes: [{"id": 2, "name": "S"},
            {"id": 3, "name": "M"},
            {"id": 4, "name": "L"}],
    colors:  [{"id": 2, "name": "Black"},
             {"id": 3, "name": "red"}]

  });

And here's the view. I think this is pretty straighforward.. bind to change events on the select elements and call setMake or setSize on the model, and then listen for change events from the model:
var ConfigView = Backbone.View.extend({
        el: $("#config"),

        optionsTemplate: _.template($("#options-template").html()),

        events:{
          "change #make select": "onChangeMake",
          "change #size select": "onChangeSize",
          "change #color select": "onChangeColor"
        },

        initialize: function(){
          Config.bind("change:makes", this.updateMakes, this);
          Config.bind("change:sizes", this.updateSizes, this);
          Config.bind("change:colors", this.updateColors, this);
        },

        render: function(){
        //console.log("ConfigureView.render");
        this.updateSelect("make");
        this.updateSelect("size");
        this.updateSelect("color");
        },

        updateMakes: function(){
          this.updateSelect("make");
        },

        updateSizes: function(){
          this.updateSelect("size");
        },

        updateColors: function(){
          this.updateSelect("color");
        },

        updateSelect: function(which){
          // updates the select specified by "which"
          this.$("#" + which + " select").html(this.optionsTemplate({
            chosen:Config.get(which),
            options:Config.get(which + "s")
          }));
        },

        onChangeMake: function(){
        Config.setMake(this.$("#make select").val());
        },

        onChangeSize: function(){
        Config.setSize(this.$("#size select").val());
        },

        onChangeColor: function(){
          Config.setColor(this.$("#color select").val());
        }
    });

    var app = new ConfigView();
    app.render();

A: Something tells me that your $.getJSON functions should instead be Backbone Collections.
http://documentcloud.github.com/backbone/#Collection
Using collections instead of what you're doing will make your application easier to read and manage. Also using $.getJSON instead of backbone's collection kind of steers away from backbone's sole model.
Here is actually a question I posted not too long ago on StackOverflow which might relate to what I'm saying. Look at what Julien had to say.
Integrating JSON feed with Backbone JS


text:
Q: Does second countable and functionally Hausdorff imply submetrizable? A topological space $\mathbf{X}$ is functionally Hausdorff, if for any two distinct $x, y \in \mathbf{X}$ there exists a continuous function $f_{xy} : \mathbf{X} \to [0,1]$ with $f(x) = 0$ and $f(y) = 1$.
A space $\mathbf{X} = (X,\tau)$ is submetrizable, if there exists a topology $\tau' \subseteq \tau$ such that $(X,\tau')$ is metrizable. Equivalently, if there is a continuous injection $\iota : \mathbf{X} \to \mathbf{X}'$ to some metric space $\mathbf{X}'$.
It is rather easy to see that any submetrizable space is functionally Hausdorff. I am wondering whether restricted to second-countable spaces, the converse might hold, too.
Failed solution attempts:
My naive attempt to prove this was to pick a dense sequence $(a_n)_{n \in \mathbb{N}}$, and to consider the continuous map $F : \mathbf{X} \to [0,1]^\omega$ where $F(x)(\langle n,m\rangle) = f_{a_na_m}(x)$ for some tupling functions for unequal pairs. This map can fail to be injective, though: Take an uncountable space with a dense sequence of isolated points, pick the $f_{xy}$ suitably, and $$F[\mathbf{X}] = \{x \in [0,1]^\omega \mid \exists n \ \forall i \neq n \ x_n = 1 \wedge x_i = 0\} \cup \{0^\omega\}$$ is countable.
The initial topology induced by all $f_{xy}$ should be regular, and is nested between two countably-based topologies, but I do not see why it should be countably-based itself.
Searching on $\pi$-base for secound countable, functionally Hausdorff (aka Urysohn) but not metrizable spaces yields the following:
https://topology.jdabbs.com/spaces?q=Second%20Countable%20%2B%20Urysohn%20%2B%20~metrizable
Of these examples most are just defined by adding open sets to a metrizable topology. The other two (irregular lattice topology and Roy's Lattice Subspace) are countable, hence the argument above with a total enumeration shows their submetrizability.

A: Fact. Each second-countable functionally Hausdorff space is submetrizable.
This fact follows from a more general result:
Theorem. Each functionally Hausdorff space $X$ with hereditarily Lindelöf square $X\times X$ is submetrizable.
Proof. Denote by $\Delta$ the diagonal of the square $X^2:=X\times X$. For any distinct points $x,y\in X$ choose a continuous function $f_{x,y}:X\to[0,1]$ such that $f_{x,y}(x)=0$ and $f_{x,y}(y)=1$.
Then $$U_{x,y}=\{(x',y')\in X\times X:f_{x,y}(x')<\tfrac12<f_{x,y}(y')\}$$ is an open neighborhood of $(x,y)$ in $X^2\setminus \Delta$. Since $X^2\setminus \Delta$ is Lindelof (by the hereditary Lindelofness of $X\times X$), the open cover $\{U_{x,y}:x,y\in X^2\setminus \Delta\}$ has a countable subcover $\{U_{x,y}\}_{(x,y)\in A}$ for some countable set $A\subset X^2\setminus\Delta$. Then the map $$f:X\to[0,1]^A,\;\;f:z\mapsto (f_{x,y}(z))_{(x,y)\in A}$$ is injective and hence $X$ is submetrizable (as $X$ admits a continuous injective map into the metrizable space $[0,1]^A$).
Corollary. Each functionally Hausdorff space with countable network is submetrizable.


text:
Q: How can i wait for a Tcl/Tk toplevel widget to be created before moving on? I'm using Tcl/Tk to build a UI and im running into the problem of trying to interact with a toplevel window before it's actually been created.
I created the toplevel window like this:
toplevel .t

Then i try and interact with it like this:
wm stackorder .t isabove .

But .t doesn't exist yet and i get an error about the window not being mapped. Effectively it equates to doing this:
winfo ismapped [toplevel .t]

which returns 0 but if i immediately run the following:
winfo ismapped .t

Then the return value is 1.
How can i know when a toplevel window is mapped (and therefore ready to interact with) so that i can proceed with my program?

A: I found the answer, i needed the following:
tkwait visibility .t


text:
Q: How to join three tables to get Sum I have three tables: Products, Purchase, Invoice
Product table:
Producct_no     Name
1                        A
2                        B
3                        C
Purchase table:
Purchase_no    Product_no    Qty
001                    1                     81
002                    2                     150
003                    3                     10
Invoice table:
Invoice_no    Product_no    Qty
001                    1                 20
002                    2                 10
003                    3                 10
I want to get each product's purchase quantity and invoice quantity, I used following query

    SELECT PR.product_no, sum(P.qty),sum(I.qty)
    FROM products PR
    LEFT  JOIN invoice I ON I.product_no=PR.product_no
    LEFT  JOIN purchase P ON P.product_no=PR.product_no
    group by PR.product_no

product_no    sum(P.qty)    sum(I.qty)
001                    162             160
002                    150             50
003                    10                10
EDIT: Expected results

product_no    sum(P.qty)    sum(I.qty)
001                    81             20
002                    150             10
003                    10                10
My query is giving me wrong response (sum of quantities are wrong), please help me to correct my query to get the results properly. thanks

A: I don't think your sample data is really what you have based on the information provided.  My best guess here is that your query is doing a fan-out on either or both of those joins which is messing up your sums.  You need to sum them separately, else additional rows in either on of those joins will fan out the other join, duplicating your results in the sum.  This is evident in your result since 001 looks to be double (even though your sample data doesn't show it).
Something like this would ensure sums independent of each other:
SELECT PR.product_no,
    ( SELECT sum(I.qty)
      FROM invoice I
      WHERE I.product_no=PR.product_no ) invoice_qty,
    ( SELECT sum(P.qty)
      FROM purchase P
      WHERE P.product_no=PR.product_no ) purchase_qty
FROM products PR

A: I think you have a problem with GROUP BY there. I would do something like this in this case
SELECT P.Product_no, Inv.InvProdSum, Pur.PurProdSum
FROM Product P
LEFT JOIN (SELECT Product_no, SUM(Qty) AS InvProdSum
          FROM Invoice
          GROUP BY Product_no) AS Inv
ON P.Product_no = Inv.Product_no
LEFT  JOIN (SELECT Product_no, SUM(Qty) AS PurProdSum
            FROM Purchase
            GROUP BY Product_no) AS Pur
ON P.Product_no = Pur.Product_no

Here is SQL FIddle for that http://sqlfiddle.com/#!9/731a5/1
NOTE i add some extra value here to test how it's work...
GL!

A: Here is my solution without subqueries:
with
  product(product_no, name) as (values
  (1, 'A'),
  (2, 'B'),
  (3, 'C')
),
  purchase(purchase_no, product_no, qty) as (values
  ('001', 1, 81),
  ('002', 2, 150),
  ('003', 3, 10),
  ('004', 1, 1000)
),
  invoice(invoice_no, product_no, qty) as (values
  ('001', 1, 20),
  ('002', 2, 10),
  ('003', 3, 10),
  ('004', 2, 5000)
),
  mixed as
(select d.product_no,
  purchase_no, p.qty as qty_purchase,
  invoice_no, i.qty as qty_invoice,
  row_number() over(partition by purchase_no) as rn_purchase,
  row_number() over(partition by invoice_no) as rn_invoice
from product d
left join purchase p on p.product_no = d.product_no
left join invoice i on i.product_no = d.product_no
)
select product_no,
  sum((case when rn_purchase = 1 then 1 else 0 end) * qty_purchase) as sum_purchase,
  sum((case when rn_invoice = 1 then 1 else 0 end) * qty_invoice) as sum_invoice
from mixed
group by product_no
order by product_no
;

And results:
product_no|sum_purchase|sum_invoice|
----------|------------|-----------|
         1|        1081|         20|
         2|         150|       5010|
         3|          10|         10|


text:
Q: Do Community Users gain Community access via OWD / Sharing rules and/or by using Sharing Sets? I'm having a hard time finding documentation that makes this clear, nor can I find an answer that directly answers this question for me.
According to this Salesforce article, Community access is granted via Sharing Sets. However, it's my understanding that Sharing Sets are only needed (and available) when the OWD is set to Private on the object you are granting access.
When setting up access for Salesforce Community Users, is record access (row level, not CRUD / FLS) granted using the org's Sharing Settings (OWD) or is row level access granted using Community Sharing Sets? Or, is it a combination of both?

A: For normal Community users (not Customer Community Plus), sharing determined by:

*

*Org-wide Defaults first

*If the record is private according to OWD, then it can be made accessible via Sharing Sets

What you can't do is use the more complex sharing models on Customer Community users: Apex, User-managed, Sharing rules. And it has special effects on Implicit Sharing that you might want to be careful about:

[Implicit sharing provides] Access to data owned by high volume users associated with a sharing
  set for users member of the sharing set's access group. All members of
  the sharing set access group gain access to every record owned by
  every high volume user associated with that sharing set

If this doesn't give you the control you need, then Customer Community Plus licences are better as they give you the same sharing options as internal users.


text:
Q: Writing a simple plugin/component I want to write a component(or plugin) like that.
when i write: var a = new myPluginName ('#myElement', { bla:bla});
or
$('#myElement').myPluginName();

It must create two input. Thats all.
How can i do this? Can you give me an example like that? Or any idea will be helpful.
In other words, my goal is create two input with my component.Thank you.

A: You can create custom jQuery plugin like this:
(function($){
 $.fn.extend({
     //plugin name - inpuX
     inputX: function(options) {
        var defaults = {
            width: 200,
            defaultPadding: 2,
            border: '2px solid red'
        };

        var options = $.extend(defaults, options);

        return this.each(function() {
              var o =options;
              var obj = $(this);

              $(obj)
                  .css('padding', o.defaultPadding)
                  .css('width', o.width)
                  .css('border', o.border)
                  .css('display', 'block');
        });
    }
});
})(jQuery);

and then call it like this:
 $('#inputA').inputX({width: 150, defaultPadding:5, border: '1px dashed black'});
 $('#inputB').inputX({width: 200, defaultPadding:10});

on elements in html:
<input id="inputA" type="text" />
<input id="inputB" type="text" />


text:
Q: Focus first button when there are two buttons in a window I use Window to show a dialog, the dialog has two buttons: confirm and cancel, but the cancel button always focus, even i set its Focusable=False, while i want to let confirm button to be focused as default, then i can execute the confirmhandler when enter key is pressed.
  <Button x:Name="btnConfirm" Content="Confirm" HorizontalAlignment="Right" Margin="0,0,100,10" VerticalAlignment="Bottom" Width="75" Click="btnConfirm_Click" Focusable="True"/>
  <Button x:Name="btnCancel" Content="Cancel" HorizontalAlignment="Right" Margin="0,0,10,10" VerticalAlignment="Bottom" Width="75" IsDefault="True" Click="btnCancel_Click" Focusable="False"/>

A: You need to move IsDefault="True" from btnCancel to btnConfirm:
<Button x:Name="btnConfirm" ... IsDefault="True" ... />

For btnCancel you can set IsCancel:
<Button x:Name="btnCancel" ... IsCancel="True" ... />


text:
Q: How to fit requirements into MVC Let's say we have a website requirement to allow User functionality. Simple!
We create the UserModel, UserController and UserView. Works perfectly.
However, let's assume that User has a many-to-one relational table connected to it titled Child which also has its own MVC components: ChildModel, ChildController, ChildView. Now if we had a requirement to create a CSV file for download containing a few details from the User and a few details from its Child, how would we go about designing this requirement?
"DownloadCSV" could essentially have its own CRUD methods, it's own Controller, it's own View but its Model is based on the details from other tables, so should it have its own Controller, View, Model(/DB View) or should it just be another method besides CRUD in User or Child controller?

A: In terms of a web application (not sure if that is the case here, but the concept is the same I think) On ChildController there is typically an "index" method that is used to render a page listing all children.
I view this "DownloadCSV" functionality as very similar to that, except that the server is sending a CSV file as the HTTP response rather than an HTML page.  Therefore, it seems to me that this would be appropriate as another method of ChildController.

A: Maybe you shouldn't try to force it to fit MVC.  Many times, reporting and data dump tasks don't fit the framework used to build the interactive applications which create and manipulate the data. And that is not a bad thing.  It is quite possible that you could generate this data download using a separate class/task that could use the same stored procedures internally for consistency, but is driven by the reporting needs which are different from needs for the presentation/control of data in the application.


text:
Q: Calculate total and elapsed number of working days in the month for a given date I am stuck with a SQL query.
I am trying to calculate two different things in a same query:

*

*Number of business days in a month (this will exclude weekends).

*How many days working days have been passed in a month.

Let's say for November (as on 11/9/2018)
no.of business days        no. of business days passed
22                                7

I tried like this :
WITH cteAllDates AS
(
    DECLARE @StartDate DATETIME
    DECLARE @EndDate DATETIME

    SET @StartDate = '10/01/2018'
    SET @EndDate = '10/31/2018'

    SELECT
        (DATEDIFF(dd, @StartDate, @EndDate) + 1)
        - (DATEDIFF(wk, @StartDate, @EndDate) * 2)
        - (CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
        - (CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END) AS x
) AS y
SELECT x
FROM cteAllDates

I would like to create  a virtual table so that I can use these fields in my complete query. And if its possible I can do this with GETDATE() and not to declare dates every time.

A: Since you want to do it in a CTE, and based on the earlier answer you found on SO, here is a version that does it all for the current month without needing to define start and end dates:
EDIT: To create a holiday table
First, create a holiday table. Don't do this every time, make it a persistent table, and keep it filled up with all holidays you need - easter, xmas etc.
create table holidays(holiday date)
insert holidays values ('2018-09-23'),('2018-09-24')

Now the query, including the check for number of holidays between the dates
;with dates as(
    select dateadd(d,-day(getdate())+1,convert(date,getdate())) as startofmonth,
    dateadd(d,-1,dateadd(m,1,dateadd(d,-day(getdate())+1,convert(date,getdate())))) as endofmonth,
    convert(date,getdate()) as today
)
,holidaycount as (
    select count(*) as holidaysinmonth,
        sum(case when holiday<=today then 1 else 0 end) as holidaystodate
    from dates
    join holidays on holiday between startofmonth and endofmonth
)
,daycounts as(
    select dates.*,

       (DATEDIFF(dd, startofmonth, endofmonth) + 1)
      -(DATEDIFF(wk, startofmonth, endofmonth) * 2)
      -(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END)
      -(CASE WHEN DATENAME(dw, endofmonth) = 'Saturday' THEN 1 ELSE 0 END)
      -isnull(holidaysinmonth,0) as wkdaysinmonth,

       (DATEDIFF(dd, startofmonth, today) + 1)
      -(DATEDIFF(wk, startofmonth, today) * 2)
      -(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END)
      -(CASE WHEN DATENAME(dw, today) = 'Saturday' THEN 1 ELSE 0 END)
      -isnull(holidaystodate,0) as wkdaystodate

    from dates
    cross join holidaycount
)

select * from daycounts

EDIT: If you cant create a temp table, add this as an additional CTE before the holidaycount one like so:
,holidays as (
    select holiday from (values ('2018-11-23'),('2018-11-24')) t(holiday)
)
,holidaycount as (

A: You can try to use cte recursive make a calendar table, then use condition aggregate function to get your result.
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = DATEADD(DAY, 1, EOMONTH(GETDATE(), -1));
SET @EndDate = DATEADD(DAY, 1, EOMONTH(GETDATE()));

;WITH CTE AS (
    select @StartDate startdt,@EndDate enddt
    UNION ALL
    SELECT  DATEADD (day ,1 , startdt) , @EndDate
    FROM CTE
    WHERE DATEADD (day,1,startdt) <= @EndDate
)

select SUM(CASE WHEN DATENAME(dw, startdt) NOT IN ('Sunday','Saturday') THEN 1 END) 'no.of business days',
       SUM(CASE WHEN DATENAME(dw, startdt) NOT IN ('Sunday','Saturday') AND GETDATE() >= startdt THEN 1 END) 'no. of business days passed'
FROM CTE

sqlfiddle
Result
no.of business days     no. of business days passed
22                      7


text:
Q: Regex for tickers on stock and crypto market I am struggling to create a functional regex with the following criteria:

*

*Identify a MAX of 5 lowercase characters ONLY after a '$' sign and before a space OR at the end of a sentence (empty string or peroid '.')

*AND match a MAX of 5 UPPERCASE letters with OR without a '$' sign at the front that HAVE to be followed by a space, symbol (comma, exclamation) or be at the end of a sentence (empty string or peroid '.')

*If there is a match of any kind
Examples of matches
"The $APPL fell on the TSLA." (should match $APPL and TSLA)
"$gme is an APEs game" (should only match $gme)
"This a game of $money. Where LAMBO" (should match $money and LAMBO)
I have been playing with the following, getting some parts to work but never all in one:
const found = [
    "this is an APPL",
    "this is an APPL.",
    "this is an $APPL",
    "this is an $appl",
    "this is an $appl.",
    "this is an $appl and orange.",
    "this is an $appl, and orange.",
    "this is an $APPL and orange.",
    "this is an $APPL, and orange.",
    "this is an APPL! and orange."
];

const notFound = [
    "this is an appl.",
    "this is an $applasdfasdf.",
    "this is an APPLLLLLL",
    "this is an $APPLLLLLL"
];

const matchTicker = /[$][A-Za-z]{0,5}/;

// Should evaluate to TRUE
console.log("\nFOUND\n");
found.forEach((ticker) => {
    console.log(matchTicker.test(ticker));
});

// Should evaluate to FALSE
console.log("\nNOT FOUND\n");
notFound.forEach((ticker) => {
    console.log(matchTicker.test(ticker));
});

A: Would this work for you:
\$[a-z]{2,5}\b|\$?\b[A-Z]{2,5}\b

RegEx Demo
RegEx Explanation:

*

*\$[a-z]{2,5}\b: first case with lowercase letters

*|: or

*\$?\b[A-Z]{2,5}\b: second case with uppercase letters


text:
Q: Knockoutjs: Can't wrap 'update' on checked binding, how to run js on update? I'm using KnockoutJS 3.0, and I'm trying to create a wrapped version of the 'checked' binding. I'd like it to simply do a $.scrollto() after the checked value changes. I'm trying just to wrap the binding for now, without any additional behavior:
ko.bindingHandlers.checkedWithPostScroll = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        //Do extra UI stuff here
        ko.bindingHandlers.checked.init(element, valueAccessor,allBindingsAccessor, viewModel, bindingContext);
    }
};

I started off wrapping "update" but found that there was no "update" for the checked binding, so I moved to wrap 'init.' But the code in init only fires once. How can I override this binding such that every time an element is checked, some javascript runs?
Here's a jsfiddle:
http://jsfiddle.net/R9k6W/1/
I'd like the alert box to show every time an element is checked or unchecked.
A second part of the question: Is there any way to pass in an extra bit of information to the binding on top of the binding target (specifically the id of the dom element to which to scroll)? Like:
<input type="checkbox" data-bind="checkedWithPostScroll:{myObservableArray,'domElementScrollPoint'}" />

Thanks...
-Ben
-Ben

A: A different way to achieve this is to subscribe to change notifications on the observable (or observableArray) to which you are binding. This is what I ended up with:
self.selectedColors = ko.observableArray();

self.selectedColors.subscribe(function (changes) {

    if (changes[0].status === 'added' && self.selectedColors().length == 1)
        setTimeout(function () {
            $('html, body').animate({
                scrollTop: $("#NextSection").offset().top
            }, 1000);
        }, 200);

}, null, "arrayChange");

Does not use a custom binding, but does work.


text:
Q: iPhone text input with rounded edges Is there an obvious way to make a text input box that has rounded edges?
I'm not talking about setting a UITextField's borderStyle to UITextBorderStyleRoundedRect. That only gives me rounded corners.
I'm talking about the style text field used as input in the SMS app (before you hit send), or the UISearchBar. I've also seen it used in 3rd party applications (for example, the comment input box in the Facebook application).
Is this possible using standard Cocoa Touch? Or do I have to bring my own background images to the table?

A: for iPhone text input with rounded edges,

*

*include - #import <QuartzCore/QuartzCore.h> to access this

*textField.layer.cornerRadius = 10;
this is the best and simple way to make rounded edge of the UITextField.

A: You can also set the corner radius on the textField, which might give you enough control to get the look you want:
textField.layer.cornerRadius = 10;

Be sure to include #import <QuartzCore/QuartzCore.h> to access this.
(the above answer it probably a better answer; this just might be easier)

A: I think that the easiest way of doing this is to use a custom background. Here is a complete API overview of the UITextField class.


text:
Q: Scrollable Cells in JTable I have a Jtable in which I have to show some big data. I cann't increase the size of the Cells So I need to add a scrollbar in each cell of the table through which I can scroll the text of cells.
I have tried to add a Custom Cell Renderer
private class ExtendedTableCellEditor extends AbstractCellEditor implements TableCellEditor
{
    JLabel area = new JLabel();
    String text;

    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex)
    {
        area.setText(text);
        return new JScrollPane(area);
        }
            public Object getCellEditorValue()
        {
        return text;
    }
}

Now I am able to see the Scroll bar on the cells but not able to click and scroll them.
Any suggestions to this issue will be great.
Thanks in Advance.

A: Adding a JScrollPaneand placing the JLabel in the JScrollPane solved the issue. So I would like to share it with you all.
private class ExtendedTableCellEditor extends AbstractCellEditor implements TableCellEditor
{
  JLabel _component = new JLabel();
  JScrollPane _pane = new JScrollPane(_component, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

 /**
  * Returns the cell editor component.
  *
  */
  public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex)
  {
    if (value == null) return null;
    _component.setText(value != null ? value.toString() : "");
    _component.setToolTipText(value != null ? value.toString() : "");

    _component.setOpaque(true);
    _component.setBackground((isSelected) ? Color.BLUE_DARK : Color.WHITE);
    _component.setForeground((isSelected) ? Color.WHITE : Color.BLACK);

    _pane.setHorizontalScrollBar(_pane.createHorizontalScrollBar());
    _pane.setVerticalScrollBar(_pane.createVerticalScrollBar());
    _pane.setBorder(new EmptyBorder(0,0,0,0));
    _pane.setToolTipText(value != null ? value.toString() : "");
    return _pane;
  }
  public Object getCellEditorValue()
  {
    return _component.getText();
  }
}


text:
Q: PHP: Fetching from database returns nothing, nor any errors - maybe path issue? From index.php I'm calling the function <?php displayTitle(7) ?> passing the id in order to get this record's title. The function doesn't return anything, nor do I get any errors. What am I missing here?
Any help would be greatly appreciated.
Folder structure:
index.php
|_includes/
  |_downloads/
  |  |_displayInfo.php
  |
  |_db.php

index.php
<?php include('includes/downloads/displayInfo.php'); ?>

<?php displayTitle(7) ?>

db.php
<?php
$DBServer = 'xxxx';
$DBUser   = 'xxxx';
$DBPass   = 'xxxx';
$DBName   = 'xxxx';
$DBtable  = 'db_name';

$conn = mysqli_connect($DBServer, $DBUser, $DBPass, $DBName);

// check connection
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

displayInfo.php
<?php
require_once('../includes/db.php');
function displayTitle($id) {
    $sql = "SELECT title FROM " . $DBtable . " WHERE id = $id";
    $rs=$conn->query($sql);
    if($rs === false) {
      trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
    } else {
      $arr = $rs->fetch_all(MYSQLI_ASSOC);
    }

    foreach($arr as $row) {
      $titles = $row['title'];
      echo $titles;
    }
}
?>

Database table:
CREATE TABLE IF NOT EXISTS `db_name` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `url` varchar(250) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `clicks` int(11) NOT NULL,
  `dates` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;


text:
Q: How to make my selectlist scroll to bottom? I have created a multi-select list, input text box and a add button. User can insert the new option in the multiselect list through input box and add button. I have created an example fiddle also :
http://jsbin.com/exuwis/7/edit
I have used knockout.js in my example.The select list is defined with "size="5". After I get more than 5 entries in the list, I can't see any new entries without manually scrolling to the bottom. I want that when user enter any new entry in the list the scroll bar automatically moves to the bottom of the list. How can i do this ?

A: add bindingHandler:
ko.bindingHandlers.scrollDown = {
update: function (elem, valueAccessor) {
    var shouldBeSelected = ko.utils.unwrapObservable(valueAccessor());
    if (shouldBeSelected) {
        //scroll
        $(elem).scrollTop(val);
        // back to previous state
        var boundProperty = valueAccessor();
        if (ko.isWriteableObservable(boundProperty))
            boundProperty(false);
    }
}};

add data-bind to scrolling element:
  select data-bind="scrollDown: scrollDown ...

add to MainModel:
self.scrollDown = ko.observable(false);
self.CourseOptions.subscribe(function(){
  setTimeout(function () {
    self.scrollDown(true);
  }, 0);
});

example: http://jsbin.com/exuwis/14/edit

A: Consider adding the new option on top of the other options.
Not a good practice to auto scroll content.
Use
self.CourseOptions.unshift(self.OptionToAdd());
instead of
self.CourseOptions.push(self.OptionToAdd());
to insert item at the begging of the array.


text:
Q: Loading Very Large data(over 1milion records) in RadGridview and having filtering/sorting/grouping functionality I am using telerik components (radgridview) in my project and i want to load huge data typically more than 1,000,000 records from SQL server database.
I have tried two scenarios:
1- I have used virtual mode and works fine but i will lose filtering/sorting/grouping functionality(which i need them somehow).
2- At first i load about 1000 records, and then i run a BackGroundWorker which adds rows  to my grid in a for loop, in this way i cant interact with my grid properly(because it is invoking more than 100 times in a sec).
does anyone know how to enable filtering/sorting/grouping in virtual mode?
or any other solutions to keep both filtering/sorting/grouping and performance together?
I Forgot to mention that the project is WindowsFormApplication!
Thank you very much


text:
Q: Mocha with Azure Mobile App: Getting Started tl;dr;
Because of the close vote, I wanted to clarify what I'm asking. I want to know how to go from a functional, local Azure Mobile App with a Node.js backend to one that can be tested successfully with Mocha and Chai. The 3 issues listed below are all hurdles that I see that are keeping me from testing my App Service in this way. There seems to be something extra that is required that makes an Azure App Service different from a standard Node.js web application. I am trying to figure out what those differences are and how to work around them or fix them.

Intro
I have been working to get a copy of my Azure Mobile App with Node.js backend running locally.
Here are some of the resources I've been using:

*

*30 Days of Zumo.v2 (Azure Mobile Apps): Day 2

*Testing Node.js with Mocha and Chai

*Ensure Express App has started before running Mocha/Supertest tests
I have finally gotten that to work, but I am encountering issues with running Mocha tests against my code.
All is well when I run this:
node app.js

I get all of the expected outputs (specifically, the API routes added), and my browser can browse my site/API.
When I run mocha, however (or npm test if I have added that to my scripts property), nothing seems to work properly. My initial tests are failing, but they're failing because of:

*

*timeout issues, or

*API not created errors (404 errors)

Just for fun, I changed my test.js file to only run the following test:
describe('Addition', function () {
    it('should add two numbers correctly', function(done) {
        (2 + 4).should.equal(6);
        done();
    });
});

It worked exactly as expected, so the issue appears to be with loading up my custom API in my app.js file, or some other, Azure-related, non-Node.js-specific issue/error.

Issue 1:
As I believe is normal for an Azure Mobile App, my app.js file loads all of my API (.js/.json file pairs). Here are the pertinent lines:
var mobile = azureMobileApps({
    homePage: true
});
mobile.api.import('./api');
app.use(mobile);

When I run the mocha command in Terminal, I consistently get the following warning:
warn: Requested configuration path
      (/{path to repo}/node_modules/mocha/bin/api)
      does not exist

This seems to me to be trying to use the './api' reference from the app.js file and apply it to the mocha "whatever" (script? executable?) that is found here: /{path to repo}/node_modules/mocha/bin.
Now, I'm pretty sure I could apple a band-aid fix to this problem by changing this line:
mobile.api.import('./api');

to this:
mobile.api.import('../../../api');

So, when I do that, I no longer get the Requested configuration path does not exist error, but I also don't get the printout in the console telling me that the API methods were created. Trying with other depths (e.g., '../api' or '../../api') gives me the Requested configuration path does not exist error, so I think the '../../../api' path is the correct one, but it doesn't appear to do anything with that path now (when using mocha).

Issue 2:
I'm also not seeing the verbose: SQL Azure database detected - setting connection encryption line printed out. This seems to be telling me that my azureMobile.js file isn't being loaded when calling mocha as it appears to be when calling node app.js.
Is there something different that happens for an Azure Mobile App when calling node app.js that isn't happening when calling mocha? If so, what is it, and how can I get mocha to actually act like node?
One thought I had was that my app.js file has these declarations at the top:
var express = require('express'),
    azureMobileApps = require('azure-mobile-apps');

I'm obviously using azureMobileApps to create the mobile variable, which is what is supposed to .import() the API files. Is there another pathing issue with how mocha loads app.js for testing? express seems to get loaded OK, so I am doubting that's the issue, but I'm grasping for any and all straws at this point.

Issue 3
I am trying to make sure that my "site" has time to load everything up before attempting to run tests. To that end, I have attempted to install an EventEmitter that will wait for my API to load before beginning my tests.
This assumes that my mobile.api.import() call is asynchronous, which might be a faulty assumption. Also, that call might be failing not due to timing, but due to the azureMobile.js issue discussed above.
Here's the pertinent code:
app.js:
app.listen(port, function () {
    console.log('App has started');
    app.emit('appStarted');
});

module.exports = app;

test.js:
var app = require('../app');
before(function (done) {
    app.on('appStarted', function(){
        console.log('Got appStarted event');
        done();
    });
});

Although I see the 'App has started' message in the console, the app.on('Started'... code is never called.
Summary
So, in short, while I am able to facilitate local development, I have not yet been able to figure out how to use Mocha to test my local development. Any pointers or fixes for problems shown above are much appreciated!


text:
Q: Programming a manual square root function? For my class I'm programming a square root function using inclusion. No, I may not use any other method...
This is my code so far, with the program nearly working. It works for perfect square roots and some other values (like 11 or 5) but it gets into an infinite loop for others (8, 2).
The reason why this happens is that the upper and lower bounds (b and a) do not change. Ideally, the bounds would be current x and previous x, creating new x. What happens is that new x is currently formed by current x and either a or b, being a constant.
I've tried for so long but I have not yet found a way to 'remember' or find the 'previous x', as every time the while loop repeats, only the current x is available for use. Anyone know how such a problem could be solved?
void inclusion ()
{
    double v ;
    cout << "*** Now solving using Inclusion ***" << endl << "To calculate the square root, enter a positive number: " ;
    cin >> v ;

    while (v<0)
    {
        cout << "Square roots of negative numbers cannot be calculated, please enter a positive number: " ;
        cin >> v ;
    }

    cout << endl ;

    int n = 0;
    while (v >= n*n)
        n++ ;

    double b = n ;
    double a = n-1 ;

    int t = 0 ;
    double x = (a+b)/2 ;

        while ((x * x - v >= 0.1) || (x * x - v <= -0.1))
        {
            t++ ;

            if (x * x < v)
                {
                cout << "Lower Bound: " << x << '\t' << '\t' ;
                cout << "Upper Bound: " << b << '\t' << '\t' ;
                x = (b + x)/2 ;
                cout << "Approximation " << t << ": " << x  << endl ;
                }

            else
                {
                cout << "Lower Bound: " << a << '\t' << '\t' ;
                cout << "Upper Bound: " << x << '\t' << '\t' ;
                x = (a + x)/2 ;
                cout << "Approximation " << t << ": " << x  << endl ;
                }
        }

    cout << endl << "The answer is " << x << ". Iterated " << t << " times." << endl << endl ;
}

A:
I have not yet found a way to 'remember' or find the 'previous x'

Have a variable previous_x that you previous_x = x at the end of the loop
But that's not your problem. You are changing x, but not a or b, so you get into an infinitely repeating pattern. You should instead adjust whichever bound brings you tighter in.
void inclusion ()
{
    double v ;
    cout << "*** Now solving using Inclusion ***" << endl << "To calculate the square root, enter a positive number: " ;
    cin >> v ;

    while (v<0)
    {
        cout << "Square roots of negative numbers cannot be calculated, please enter a positive number: " ;
        cin >> v ;
    }

    cout << endl ;

    int n = 0;
    while (v >= n*n)
        n++ ;

    double b = n ;
    double a = n-1 ;

    int t = 0 ;

    double x;
    for (x = (a+b)/2; abs(x * x - v) >= 0.1; x = (a+b)/2, ++t)
    {
        if (x * x < v)
        {
            cout << "Lower Bound: " << x << '\t' << '\t' ;
            cout << "Upper Bound: " << b << '\t' << '\t' ;
            a = (b + x)/2 ;
            cout << "Approximation " << t << ": " << x  << endl ;
        }
        else
        {
            cout << "Lower Bound: " << a << '\t' << '\t' ;
            cout << "Upper Bound: " << x << '\t' << '\t' ;
            b = (a + x)/2 ;
            cout << "Approximation " << t << ": " << x  << endl ;
        }
    }

    cout << endl << "The answer is " << x << ". Iterated " << t << " times." << endl << endl ;
}

A: You need to update the bounds too:
a = x;
x = (b + x)/2;

and
b = x;
x = (a + x)/2;


text:
Q: How to get this kind of parameter in node.js express router? I have a router like this:
app.get('/blog/:id/delete', function (req, res) {

})

how can I get the :id parameter?
I have tried req.query.id req.param.id ,but both failed
How can I get the correct id value?

A: It's req.params.id.
So, basically you were nearly right, just an s was missing ;-)


text:
Q: cannot override dragfinished method I have a subclass of the Button class and I would like to override the dragFinished method of the Component class. However, when I try to do this:
@Override
protected void dragFinished(int x, int y){
    // other code here
}

I am getting an error: method does not override or implement a method from a supertype.
Also, if this provides more information, when I try to call super.dragFinished(x, y) within the method, I get this error: dragFinished(int,int) is not public in Component; cannot be accessed from outside package.
Any help will be appreciated. Thanks!

A: Is it possible your IDE auto-completed inheritance from the wrong class e.g. java.awt.Button instead of com.codename1.ui.Button?


text:
Q: Mailgun attach file Gitlab CI I'm trying to send csv file - artifact from Gitlab CI over Mailgun.
Regular mail works well, but when I'm add attachment it fails with an error:
curl: (26) Failed to open/read local data from file/application
My yaml file:
artifact:
  paths:
    -report_folder/result.csv

send_email:
script: curl --user "api:$Mailgun_API_KEY"
  "https://api.mailgun.net/v3/$Mailgun_domain/messages"
    -F from='Gitlab <gitlab@example.com>'
    -F to=xxx@mail.com
    -F subject='test'
    -F text='hello form mailgun'
    -F attachment='@report_folder/result.csv'

I guess something wrong in last line in a file path, but I tried different combinations, nothing works for now.


text: Q: Table in JSP and how to use jsp -Jstl tag I have displayed one table in jsp page.Now I want a number attached with every row means displayed serial number as first field with every row.The records are dynamic.how I do that?please help me I am new in jsp page


text:
Q: Make input and label elements appear on same line within columns I am trying to create a form for our website, and am struggling with trying to get labels to appear to the right of radio buttons. It is instead forcing the labels to appear directly beneath the radio buttons.
HTML

    Adult Living Arrangements: (18 and over - please check one)

            <input type="radio" class="radiobuttons" id="adult_fostercare" name="livingarrangements" value="Adult Foster Care" tabindex="48" />
            Adult Foster Care
            <input type="radio" class="radiobuttons" id="adult_alone" name="livingarrangements" value="Alone/Independent Living" tabindex="49" />
            Alone/Independent Living
            <input type="radio" class="radiobuttons" id="adult_grouphome" name="livingarrangements" value="Adult Group Home" tabindex="50" />
            Group Home
            <input type="radio" class="radiobuttons" id="adult_homeless" name="livingarrangements" value="Homeless" tabindex="51" />
            Homeless
            <input type="radio" class="radiobuttons" id="adult_nursinghome" name="livingarrangements" value="Nursing Home" tabindex="52" />
            Nursing Home
            <input type="radio" class="radiobuttons" id="adult_other" name="livingarrangements" value="Other" tabindex="53" />
            Other
            <input type="radio" class="radiobuttons" id="adult_otherpublic" name="livingarrangements" value="Other Public/Private" tabindex="54" />
            Other Public/Private
            <input type="radio" class="radiobuttons" id="adult_supportiveliving" name="livingarrangements" value="Supportive Living" tabindex="55" />
            Supportive Living

            <input type="radio" class="radiobuttons" id="adult_transitional" name="livingarrangements" value="Transitional Facility" tabindex="56" />
            Transitional Facility
            <input type="radio" class="radiobuttons" id="adult_children" name="livingarrangements" value="With Children" tabindex="57" />
            With Children
            <input type="radio" class="radiobuttons" id="adult_family" name="livingarrangements" value="With other Family member" tabindex="58" />
            With other Family member
            <input type="radio" class="radiobuttons" id="adult_parent" name="livingarrangements" value="With Parent" tabindex="59" />
            With Parent
            <input type="radio" class="radiobuttons" id="adult_spouseandchildren" name="livingarrangements" value="With Spouse and Children" tabindex="60" />
            With Spouse and Children
            <input type="radio" class="radiobuttons" id="adult_spouse" name="livingarrangements" value="With Spouse" tabindex="61" />
            With Spouse
            <input type="radio" class="radiobuttons" id="adult_unrelated" name="livingarrangements" value="Unrelated Person" tabindex="62" />
            Unrelated Person

CSS
.radiobuttons {
                display: flex;
            }
            .column {
                float: left;
                width: 50%;
            }
            .row:after {
                content: "";
                display: table;
                clear: both;
            }

Any help would be greatly appreciated!

A: Possibly you can use a grid like this?
.row {
    display: grid;
  grid-template-columns: auto auto;
}
.column {
  display: grid;
  grid-template-columns: 1.5em auto;
}

Example:

.row {
    display: grid;
  grid-template-columns: auto auto;
}
.column {
  display: grid;
  grid-template-columns: 1.5em auto;
}

    Adult Living Arrangements: (18 and over - please check one)

            <input type="radio" class="radiobuttons" id="adult_fostercare" name="livingarrangements" value="Adult Foster Care" tabindex="48" />
            Adult Foster Care
            <input type="radio" class="radiobuttons" id="adult_alone" name="livingarrangements" value="Alone/Independent Living" tabindex="49" />
            Alone/Independent Living
            <input type="radio" class="radiobuttons" id="adult_grouphome" name="livingarrangements" value="Adult Group Home" tabindex="50" />
            Group Home
            <input type="radio" class="radiobuttons" id="adult_homeless" name="livingarrangements" value="Homeless" tabindex="51" />
            Homeless
            <input type="radio" class="radiobuttons" id="adult_nursinghome" name="livingarrangements" value="Nursing Home" tabindex="52" />
            Nursing Home
            <input type="radio" class="radiobuttons" id="adult_other" name="livingarrangements" value="Other" tabindex="53" />
            Other
            <input type="radio" class="radiobuttons" id="adult_otherpublic" name="livingarrangements" value="Other Public/Private" tabindex="54" />
            Other Public/Private
            <input type="radio" class="radiobuttons" id="adult_supportiveliving" name="livingarrangements" value="Supportive Living" tabindex="55" />
            Supportive Living

            <input type="radio" class="radiobuttons" id="adult_transitional" name="livingarrangements" value="Transitional Facility" tabindex="56" />
            Transitional Facility
            <input type="radio" class="radiobuttons" id="adult_children" name="livingarrangements" value="With Children" tabindex="57" />
            With Children
            <input type="radio" class="radiobuttons" id="adult_family" name="livingarrangements" value="With other Family member" tabindex="58" />
            With other Family member
            <input type="radio" class="radiobuttons" id="adult_parent" name="livingarrangements" value="With Parent" tabindex="59" />
            With Parent
            <input type="radio" class="radiobuttons" id="adult_spouseandchildren" name="livingarrangements" value="With Spouse and Children" tabindex="60" />
            With Spouse and Children
            <input type="radio" class="radiobuttons" id="adult_spouse" name="livingarrangements" value="With Spouse" tabindex="61" />
            With Spouse
            <input type="radio" class="radiobuttons" id="adult_unrelated" name="livingarrangements" value="Unrelated Person" tabindex="62" />
            Unrelated Person


text:
Q: How and when does Foundation's Locale data get updated? My financial exchange app needed to be updated as Venezuela added a new currency in August. Below is the ISO currency information from the Swiss Assoc. for Standardization on Venezuela's new currency. The currency code is VES.
<CcyNtry>
<CtryNm>VENEZUELA (BOLIVARIAN REPUBLIC OF)</CtryNm>
<CcyNm>Bolívar Soberano</CcyNm>
<Ccy>VES</Ccy>
<CcyNbr>928</CcyNbr>
<CcyMnrUnts>2</CcyMnrUnts>
</CcyNtry>

But I'm still not seeing the currency code VES in Apple's Locale struct. This code appears correct for other currencies. I'm using Xcode 10.1.
let currencyCode = "VES"
let identifierList = Locale.availableIdentifiers.map { Locale(identifier: $0)}.filter { return currencyCode == $0.currencyCode }
print(identifierList)

Have I failed to do something on my end to see the currency? Is the code wrong? Do I wait for a new Xcode version? I'm trying to get a sense of how and when built-in data gets updated.


text:
Q: Can we select group in drop down list in HTML? I want to show some data in the form of groups in drop down list. Can we select a group instead of a group member in order to select full group in drop down list. If yes then how, if no then any other way or ant other control which can be used?
Thanks
Ashwani

A: If you mean can you collect a sub-set of options within a select box of a form, then yes, I believe you can:
      <form method="post" action="" enctype="form/multipart">
        <fieldset>
          <select>
            <optgroup label="numbers">
              <option>One</option>
              <option>Two</option>
              <option>Three</option>
            </optgroup>

            <optgroup label="letters">
              <option>a</option>
              <option>b</option>
              <option>c</option>
            </optgroup>
          </select>
        </fieldset>
      </form>

demo at: http://jsbin.com/iwada3/edit

Edited after realising I'm a moron, and addressing the question that was really asked (I'm sorry, long day...):
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

  <script type="text/javascript">

    $(document).ready(
      function() {
       $('option.all').click(
         function() {
           $(this).parent().children().attr('selected','selected');
           $(this).attr('selected','');
         }
         );
      }
      );

  </script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup,
  menu, nav, section { display: block; }
</style>
</head>
<body>

  <form>
    <fieldset>
      <select multiple>
        <optgroup class="num" label="numbers">
          <option class="num all">Select all:</option>
          <option class="num">One</option>
          <option class="num">Two</option>
          <option class="num">Three</option>
        </optgroup>

        <optgroup  class="let"label="letters">
          <option class="let all">Select all:</option>
          <option class="let">a</option>
          <option class="let">b</option>
          <option class="let">c</option>
        </optgroup>
      </select>
    </fieldset>
  </form>
</body>
</html>

Demo at: http://jsbin.com/ebeke3
It does require jQuery (in this version, at least), but I can't see an alternative to JS for what you require, I'm sorry to say.
If you mean something else, then I'm not sure I understand the question.


text:
Q: How to call a UDF with a parameter which is known only at "execution time"? I'm trying to join a table with another table, which is provided by a UDF.
Check out this self-explained piece of sql code:
SELECT table1.column1 FROM Table1 table1
INNER JOIN UDF1(table1.column2) as UDF1 ON XXX(condition doesn´t matter)
WHERE table1.id=100

The problem is: table1.column2 can´t be resolved.
I can´t believe there is no way to get this done, but i can´t find how to do it.
Thanks.

A: If you want to use a column from a table as a parameter to a UDF you need to use cross apply (or outer apply).
Test this. It might do what you want.
SELECT table1.column1
FROM Table1 table1
  CROSS APPLY UDF1(table1.column2) as UDF1
WHERE table1.id=100


text:
Q: PHP get more then one argument in command line On php command line i can read only the first argument. When i add the site name the program not breaking before the password input.
echo "Site name: ";
$handle = fopen ("php://stdin","r");
$base_name = trim(fgets($handle));
fclose($handle);

echo "Password:";
$handle = fopen ("php://stdin","r");
$base_password = trim(fgets($handle));
fclose($handle);

How can i read these two variables from stdin?

A: Your arguments passed at command time will be in the global $argv as well as the super global $_SERVER["argv"] with $argv[0] and $_SERVER["argv"][0] being the command that was called.
A useful function for parsing out for example the call ./myscript.php --user=root --password=foobar
function parse_argvs(){
    if( $params = $_SERVER["argv"] ){
        $file = array_shift( $params );
        while( $params ){
            $param = array_shift( $params );
            switch( strspn( $param, "-" ) ){
                case( 1 ):
                    $OPTS[ trim( $param, " -" ) ] = array_shift( $params );
                break;
                case( 2 ):
                    list( $key, $value ) = explode( "=", $param );
                    $OPTS[ trim( $key, " -" ) ] = $value;
                break;
                default:
                    $OPTS[ $param ] = true;
                break;
            }
        }
    }
    return $OPTS ?: array();
}

Called something like
$parsed = parse_argvs();
echo $parsed['user']; //root
echo $parsed['password']; //password

These are actual command line arguments passed at call time. I hope this helps.

A: Try this:
$base_name     = readline("Site Name: ");
$base_password = readline("Password: ");

PHP Readline Function


text:
Q: Here Maps: How to retrieve speed limit information in an efficent way? We are trying to retrieve speed limit information for a specific point (latitude, longitude). We are using the Geocoder API and Fleet Telematics Advanced Data Sets from Here Maps.
For some GPS points, the speed limit values retrieved does not match with the real speed limit. Following are the possible causes:

*

*GPS accuracy. If a GPS point can be related to different road types. How we can filter by type road?

*Multilevel roads.

*Roads very close to each other.

*We are not applying the correct method to retrieve the speed limit information. :)

We retrieve the speed limit information following these steps:
Step 1. Apply reverse geocode request from a GPS point (latitude, longitude).
https://reverse.geocoder.cit.api.here.com/6.2/
We apply the following parameters:
prox=latidude,longitude,radius(value: 10)
mode=retrieveAddresses
maxresults=1
additionaldata=SuppressStreetType,Unnamed
locationattributes=linkInfo

Step 2.
From the JSON response we retrieve the following information:
ReferenceId (View->Result->Location->MapReference->ReferenceId)
FunctionalClass (View->Result->Location->LinkInfo->FunctionalClass)
SpeedCategory (View->Result->Location->LinkInfo->SpeedCategory)

Step 3. Apply a PDE request:
https://pde.api.here.com/1/tile.json
We apply the following parameters (values are related to the results of the first geocoder request):
layer=SPEED_LIMIT_FCX
level (value is 8 + functional class)
tileX
tileY

the values for tileX and tileY are calculated following this example:
https://github.com/seaBass3/here-pde-speed-limit/blob/master/Here_PDE_Demo.php
Step 4.
From the JSON response we search the row result that matches with the ReferenceID retrieved from the geocoder request.
Can you confirm if the methodology is the right one?
For some points, the values obtained differs from the results displayed in this demo:
https://tcs.ext.here.com/examples/v3/link_speed_locator
Any suggestion?
Can you help us to improve this method?
Also, there is any method to do these requests for multiple points?

A: All you need is the GeocoderAPI. Use the following parameter to retrieve the posted speed limits and the 'freeflow' speed:

*

*addressattributes=additionalData

*locationattributes=linkInfo
'speedLimit' is the posted speed limit for both directions. If you use mode=trackPosition with a bearing, then the response items will be sorted in a way that the first item will match the given bearing.
'traffic' shows the freeflow speeds. A Free-flow speed is the speed at which traffic would be traveling at on a road segment when conditions are good (e.g., no rain or snow) and when traffic is not congested.


text:
Q: Bash wrong date formatting at Team City Getting date locally by
DATE=`date +%Y-%m-%d`

works fine, but at Team City the same script returns 1m13. I think, because of 13/08/18. Any ideas will be helpful.

A: Have found a solution. TeamCity uses percent signs for its properties. So to use % in TeamCity we should escape it with other %, i.e. for % it must be %%.


text:
Q: changing TOC font family / removing chapter headings in 'report' document class? I'm new to LaTeX, so please bear with me for a bit if the description of my problem seems incoherent :)
I've started to write my thesis using the report document class, but I've soon found out that it insists on prepending a redundant Chapter n to any chapter I begin. I've tried to work around this by declaring my chapters as \chapter*{Sneaky chapter}, but this causes them to be omitted from the TOC.
I've switched to the scrreprt document class since then, and it does pretty much what I wanted from it regarding the chapter headings, aside from the unsightly sans-serif font it insists on using. So, I've restyled my chapter headings (and sections, and so on and so forth) using the following:
\titleformat{\chapter}
  {\normalfont\huge\bfseries}{\thechapter}{1em}{}

Again, this does exactly what it says on the tin, but the headings in the TOC remain in the default sans-serif font.
So, in a nutshell, it would be pretty awesome if the chapter headings were set using the default serif font, and the unneeded Chapter n gotten rid of. There are no doubt dozens of possible ways to achieve this, I'm sure, but my LaTeX-fu is sadly not up to the task yet.

A: Can all be done with internal features of KOMA Script.
\documentclass{scrreprt}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\setkomafont{disposition}{\normalfont\bfseries}

\begin{document}
  \tableofcontents

  \chapter{Foo}
\end{document}

For details see the user guide.

A: Use the tocloft package:
\documentclass{scrreprt}

\usepackage{tocloft}
\renewcommand\cftchapfont{%
  \normalfont\bfseries}

\begin{document}

\tableofcontents

\chapter{Foo}

\end{document}


text:
Q: What is the best way to implement smart pointers in C++? I've been evaluating various smart pointer implementations (wow, there are a LOT out there) and it seems to me that most of them can be categorized into two broad classifications:
1) This category uses inheritance on the objects referenced so that they have reference counts and usually up() and down() (or their equivalents) implemented. IE, to use the smart pointer, the objects you're pointing at must inherit from some class the ref implementation provides.
2) This category uses a secondary object to hold the reference counts. For example, instead of pointing the smart pointer right at an object, it actually points at this meta data object... Who has a reference count and up() and down() implementations (and who usually provides a mechanism for the pointer to get at the actual object being pointed to, so that the smart pointer can properly implement operator ->()).
Now, 1 has the downside that it forces all of the objects you'd like to reference count to inherit from a common ancestor, and this means that you cannot use this to reference count objects that you don't have control over the source code to.
2 has the problem that since the count is stored in another object, if you ever have a situation that a pointer to an existing reference counted object is being converted into a reference, you probably have a bug (I.E., since the count is not in the actual object, there is no way for the new reference to get the count... ref to ref copy construction or assignment is fine, because they can share the count object, but if you ever have to convert from a pointer, you're totally hosed)...
Now, as I understand it, boost::shared_pointer uses mechanism 2, or something like it... That said, I can't quite make up my mind which is worse! I have only ever used mechanism 1, in production code... Does anyone have experience with both styles? Or perhaps there is another way thats better than both of these?

A: Just to supply a different view to the ubiquitous Boost answer (even though it is the right answer for many uses), take a look at Loki's implementation of smart pointers. For a discourse on the design philosophy, the original creator of Loki wrote the book Modern C++ Design.

A: I've been using boost::shared_ptr for several years now and while you are right about the downside (no assignment via pointer possible), I think it was definitely worth it because of the huge amount of pointer-related bugs it saved me from.
In my homebrew game engine I've replaced normal pointers with shared_ptr as much as possible. The performance hit this causes is actually not so bad if you are calling most functions by reference so that the compiler does not have to create too many temporary shared_ptr instances.

A: Boost also has an intrusive pointer (like solution 1), that doesn't require inheriting from anything.  It does require changing the pointer to class to store the reference count and provide appropriate member functions.  I've used this in cases where memory efficiency was important, and didn't want the overhead of another object for each shared pointer used.
Example:
class Event {
public:
typedef boost::intrusive_ptr<Event> Ptr;
void addRef();
unsigned release();
\\ ...
private:
unsigned fRefCount;
};

inline void Event::addRef()
{
  fRefCount++;
}
inline unsigned Event::release(){
    fRefCount--;
    return fRefCount;
}

inline void intrusive_ptr_add_ref(Event* e)
{
  e->addRef();
}

inline void intrusive_ptr_release(Event* e)
{
  if (e->release() == 0)
  delete e;
}

The Ptr typedef is used so that I can easily switcth between boost::shared_ptr<> and boost::intrusive_ptr<> without changing any client code

A: If you stick with the ones that are in the standard library you will be fine.
Though there are a few other types than the ones you specified.

*

*Shared:    Where the ownership is shared between multiple objects

*Owned:     Where one object owns the object but transfer is allowed.

*Unmovable: Where one object owns the object and it can not be transferred.

The standard library has:

*

*std::auto_ptr

Boost has a couple more than have been adapted by tr1 (next version of the standard)

*

*std::tr1::shared_ptr

*std::tr1::weak_ptr

And those still in boost (which in relatively is a must have anyway) that hopefully make it into tr2.

*

*boost::scoped_ptr

*boost::scoped_array

*boost::shared_array

*boost::intrusive_ptr

See:
Smart Pointers: Or who owns you baby?

A:
"What is the best way to implement smart pointers in C++"

*

*Don't!  Use an existing, well tested smart pointer, such as boost::shared_ptr or std::tr1::shared_ptr (std::unique_ptr and std::shared_ptr with C++ 11)

*If you have to, then remember to:

*

*use safe-bool idiom

*provide an operator->

*provide the strong exception guarantee

*document the exception requirements your class makes on the deleter

*use copy-modify-swap where possible to implement the strong exception guarantee

*document whether you handle multithreading correctly

*write extensive unit tests

*implement conversion-to-base in such a way that it will delete on the derived pointer type (policied smart pointers / dynamic deleter smart pointers)

*support getting access to raw pointer

*consider cost/benifit of providing weak pointers to break cycles

*provide appropriate casting operators for your smart pointers

*make your constructor templated to handle constructing base pointer from derived.

And don't forget anything I may have forgotten in the above incomplete list.

A: It seems to me this question is kind of like asking "Which is the best sort algorithm?"  There is no one answer, it depends on your circumstances.
For my own purposes, I'm using your type 1.  I don't have access to the TR1 library.  I do have complete control over all the classes I need to have shared pointers to.  The additional memory and time efficiency of type 1 might be pretty slight, but memory usage and speed are big issues for my code, so type 1 was a slam dunk.
On the other hand, for anyone who can use TR1, I'd think the type 2 std::tr1::shared_ptr class would be a sensible default choice, to be used whenever there isn't some pressing reason not to use it.

A: The problem with 2 can be worked around. Boost offers boost::shared_from_this for this same reason. In practice, it's not a big problem.
But the reason they went with your option #2 is that it can be used in all cases. Relying on inheritance isn't always an option, and then you're left with a smart pointer you can't use for half your code.
I'd have to say #2 is best, simply because it can be used in any circumstances.

A: Our project uses smart pointers extensively.  In the beginning there was uncertainty about which pointer to use, and so one of the main authors chose an intrusive pointer in his module and the other a non-intrusive version.
In general, the differences between the two pointer types were not significant.  The only exception being that early versions of our non-intrusive pointer implicitly converted from a raw pointer and this can easily lead to memory problems if the pointers are used incorrectly:
void doSomething (NIPtr<int> const &);

void foo () {
  NIPtr<int> i = new int;
  int & j = *i;
  doSomething (&j);          // Ooops - owned by two pointers! :(
}

A while ago, some refactoring resulted in some parts of the code being merged, and so a choice had to be made about which pointer type to use.  The non-intrusive pointer now had the converting constructor declared as explicit and so it was decided to go with the intrusive pointer to save on the amount of code change that was required.
To our great surprise one thing we did notice was that we had an immediate performance improvement by using the intrusive pointer.  We did not put much research into this, and just assumed that the difference was the cost of maintaining the count object.  It is possible that other implementations of non-intrusive shared pointer have solved this problem by now.

A: What you are talking about are intrusive and non-intrusive smart pointers. Boost has both. boost::intrusive_ptr calls a function to decrease and increase the reference count of your object, everytime it needs to change the reference count. It's not calling member functions, but free functions. So it allows managing objects without the need to change the definition of their types. And as you say, boost::shared_ptr is non-intrusive, your category 2.
I have an answer explaining intrusive_ptr: Making shared_ptr not use delete. In short, you use it if you have an object that has already reference counting, or need (as you explain) an object that is already referenced to be owned by an intrusive_ptr.


text:
Q: Can I defer a configuration change until the next time SQL Server is restarted? Let's say that I want to change a SQL configuration setting like MAXDOP.  I know that changing this on an active instance will severely impact performance, as it will clear all of the cached query plans. Doing this while the instance is running is simply not an option.
Is there some way to modify the value now, but to "defer" the actual change until the next time SQL server is restarted?
What I'm looking for is an option like Oracle's "scope=spfile" for parameter changes.  Does such an option exist in SQL Server?

A: Create a stored procedure in master:
USE master;
GO
CREATE PROCEDURE dbo.FixMaxDop
AS
BEGIN
  SET NOCOUNT ON;
  EXEC sys.sp_configure N'show advanced options', 1;
  RECONFIGURE WITH OVERRIDE;
  EXEC sys.sp_configure N'max degree of parallelism', 8;
  RECONFIGURE WITH OVERRIDE;
  EXEC sys.sp_configure N'show advanced options', 0;
  RECONFIGURE WITH OVERRIDE;
  -- optionally, drop or alter the procedure so it doesn't run again
END
GO

Now, you can set the procedure to be a startup procedure (see here and here):
EXEC sys.sp_procoption N'dbo.FixMaxDop', 'startup', 'true';

If you only want this to run once, then you'll want to flip that option off after the configuration option has been set correctly:
EXEC sys.sp_procoption N'dbo.FixMaxDop', 'startup', 'false';

Alternatively, you can do as MichaelK suggested - create a job with a step that calls the above procedure, make sure it is owned by sa or someone in the sysadmin role, and then set it to start when SQL Server Agent starts. However, you're relying heavily on SQL Server Agent being set to start automatically (it might not be, and that might change before the next restart), and that Agent will start successfully after the next service restart (it might fail for a variety of reasons, including service account changes). You also can't create a schedule that runs when Agent starts and only runs once (it's one or the other), so you'd have to do something else like script an additional job step that disables the job or removes the schedule.
Not really a big deal for the procedure not to run again, I suppose, unless you make some other manual change later and forget about this - then you'll revert to this explicit setting the next time you restart after that change...

A: You could setup a SQL Server Agent job to run when SQL Server Agent starts up and set the schedule to only run once.


text:
Q: css arabic ttf font doesn't work I used many English ttf fonts in my website and it worked very well, but when I try to do the same thing using Arabic ttf fonts it does't work, it works only if I used otf fonts which it isn't available too much compared to ttf. is there any way to make the Arabic ttf fonts works ?
I am using this code:
<style>
@font-face {
font-family: myFont;
src: url(moga.ttf);
}

div {
font-family: myFont;
}
</style>

A: Your font from the jsFiddle works and displays correctly for me (in firefox 36), at least, it is arabic script, so I assume that's the desired result, although I can't understand it.
What browser are you using?
update 1
You need to ensure the font ttf is referenced correctly, you need to upload the ttf to the website and link to it, so for example only, if you are saving the ttf to /includes/fonts/CSDiwany4S_Inormal.ttf then your CSS should look like this
@font-face {
font-family: myFont;
src: url("/includes/fonts/CSDiwany4S_Inormal.ttf");
}

div {
font-family: myFont;
}

And this will work.
You have told me your font should look like this:
http://photoshop.cc/wp-content/fonts/arabic_fonts_img/horr/new/Tachkili%20Font%20TTF.gif (this is primarily for other westerners here who are seeing the original basic arabic font on the jsFiddle and are assuming that this is the intended output).