text:
Q: GWT how to inherit EditTextCell and override some methods, f.e.: edit(Context context, Element parent, String value) This is my implementation of EditTextCell:
public class MyEditTextCell extends EditTextCell {

    @Override
    protected void edit(Context context, Element parent, String value) {
        if (value.equals("")) {
            super.edit(context, parent, value);
        } else {
            clearViewData(context.getKey());
        }
    }
}

I would like to text input to be shown for only for empty cells. IT is why I've override the edit() method. The rest behaviour of oryginal EditTextCell is ok, so I've not changed it.
This unfortunatelly doesn't work. Please help.

A: The editor in EditTextCell is shown in onBrowserEvent method, so you just need:
public class MyEditTextCell extends EditTextCell {
    @Override
    public void onBrowserEvent(Context context, Element parent, String value, NativeEvent event, ValueUpdater<String> valueUpdater) {
        if(value == null || value.isEmpty())
            super.onBrowserEvent(context, parent, value, event, valueUpdater);
    }
}

Remember, to add the FieldUpdater to the column to save the edited value.
Here you have a full working example with simple table type containing only one String:
public class MyTableType {

    private String value;

    public MyTableType(String value) {
        super();
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

CellTable<MyTableType> table = new CellTable<MyTableType>();

MyEditTextCell cell = new MyEditTextCell();

Column<MyTableType, String> column = new Column<MyTableType, String>(cell) {
    @Override
    public String getValue(MyTableType object) {
        if(object.getValue() == null)
            return "";
        else
            return object.getValue();
    }
};
column.setFieldUpdater(new FieldUpdater<MyTableType, String>() {
    @Override
    public void update(int index, MyTableType object, String value) {
        object.setValue(value);
    }
});

table.addColumn(column, "Value");

ArrayList<MyTableType> values = new ArrayList<MyTableType>();
values.add(new MyTableType("one"));
values.add(new MyTableType("two"));
values.add(new MyTableType("three"));
values.add(new MyTableType(null));
values.add(new MyTableType(""));
table.setRowData(values);

Please, notice that once you edit the cell value to be non-empty, the editor will not be shown after that.


text:
Q: export mail to single text file using vbscript How do I export all emails in Inbox  of outlook  to a single text file?
As of now I have code which will export mails to a text file but each mails are saved in separate text files. I need in single text file
Sub saveEmailTxt()
Dim objItem As Object

Dim iCount As Integer 'iterate over all Items in the current folder and save the body as textfile in c:\'

For Each objItem In ActiveExplorer.CurrentFolder.Items
objItem.SaveAs "C:\Mail" & CStr(iCount) & ".txt", olSaveAsText
iCount = iCount + 1
Next

End Sub

This is my previous code which will save into text file, but it will create separate text files for each mail.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kendo Tree View doesn't load properly I wanna create a kendo ui tree view with remote data source in Asp.net mvc4. I'm having a problem with knowledge about kendo. I've tried those examples in kendo website .
But i couldn't even get those images to the treeView.
About the project : This project is to create a TreeView menu for load web forms. Each web form can be taken as an formObject. That objects has following attributes

*

*name

*id

*List of child objects (List childs)

Here is my Codes on the Controller
  public class HomeController : Controller
{
    ObjectService service = new ObjectService();
    private int cky = 11;
    private int usrky=28;

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult GetAllMenu(int prntKy = 1)// initially the parent key is = 1
    {
        List<ObjectModel> objects = new List<ObjectModel>();
        objects = service.GetObjectsByPrntKy(prntKy, cky, usrky);//get all parent nodes

        List<TreeViewModel> tree = new List<TreeViewModel>();

        if (objects != null)
        {
            foreach (ObjectModel model in objects)//for each parent node
            {
                TreeViewModel treeObj = new TreeViewModel();

                treeObj.id = model.ObjKy;
                treeObj.name = model.ObjNm;
                treeObj.childrens = GetChileByPrntObjKy(model.ObjKy);
                tree.Add(treeObj);
            }
        }

        return Json(tree, JsonRequestBehavior.AllowGet);

    }

    private List<TreeViewModel> GetChileByPrntObjKy(int prntKy)// method to get child nodes
    {
        List<TreeViewModel> tree = new List<TreeViewModel>();

        List<ObjectModel> Objects = new List<ObjectModel>();

        Objects = service.GetAllObjects();

        foreach (ObjectModel model in Objects)
        {

            TreeViewModel treeObj = new TreeViewModel();

            if (model.PrntObjKy == prntKy)
            {
                treeObj.id = model.ObjKy;
                treeObj.name = model.ObjNm;
                treeObj.childrens = GetChileByPrntObjKy(model.ObjKy);
                tree.Add(treeObj);
            }

        }
        return tree;
    }

}

Here is the model
    public class TreeViewModel
{
    public int pid { get; set; }
    public int id { get; set; }
    public string name { get; set; }
    public List<TreeViewModel> childrens { get; set; }
}

    public class ObjectModel
{
    public long UsrObjPrmsnKy { get; set; }
    public long UsrKy { get; set; }
    public int ObjKy { get; set; }
    public string ObjCd { get; set; }
    public string ObjNm { get; set; }
    public string ObjCaptn { get; set; }
    public bool isPrntObj { get; set; }
    public Nullable<int> PrntObjKy { get; set; }
    public int CallObjKy { get; set; }
    public string ObjPath { get; set; }
    public bool isAlwAcs { get; set; }
    public bool isAlwAdd { get; set; }
    public bool isAlwUpdate { get; set; }
    public bool isAlwDel { get; set; }
    public bool isAlwApr { get; set; }
}

and here is the View
        <div id="treeview">
    </div>
    <script type="text/javascript">

        $(document).ready(function () {
            LoadTreeView(1);
        });

        function LoadTreeView(prntKy)
        {
            var key = prntKy;
            homogeneous = new kendo.data.HierarchicalDataSource({
                transport: {
                    read: {
                        url: '@Url.Content("~/Home/GetAllMenu")',
                        data:{'prntKy':key},
                    dataType: "json"
                }
            },
                schema: {
                    model: {
                        id: "id",
                        hasChildren: "childrens",
                        name: "name"
                    }
                }
            });

        $("#treeview").kendoTreeView({
            dataSource: homogeneous,
            select: onSelectTree,
            dataTextField: "name",
            dataValueField: "id",
        });
        }

        function onSelectTree(e) {
            var data = $('#treeview').data('kendoTreeView').dataItem(e.node);
            alert(data.id);
            LoadTreeView(data.id);
        }
    </script>

I have uploaded the results images too. Please help me.

A: Your treeview isn't properly configured. You seem to be reinitializing it every time a node is selected which is redundant. I suggest you check the remote binding demo which implements a very similar case to yours. Here is how the treeview declaration looks:
var serviceRoot = "http://demos.kendoui.com/service";
    homogeneous = new kendo.data.HierarchicalDataSource({
       transport: {
          read: {
             url: serviceRoot + "/Employees",
             dataType: "jsonp" // you don't need "json" for your case
          }
       },
       schema: {
          model: {
             id: "EmployeeId",
             hasChildren: "HasEmployees"
          }
       }
   });

$("#treeview").kendoTreeView({
   dataSource: homogeneous,
   dataTextField: "FullName"
});

In this demo the treeview will ask the data source to load a new level of nodes when a parent node is expanded. For example when the user expands the root node in that demo the data source makes request to http://demos.kendoui.com/service/Employees?EmployeeId=2 which means "return the children of the node whose EmployeeID is equal to 2". Why "EmployeeId"? Because this is what the "id" of the data source model is:
  schema: {
     model: {
        id: "EmployeeId",
        hasChildren: "HasEmployees"
     }
  }


text:
Q: Set node positions using Graphviz in Jupyter Python I want to make a graph with random node positions but it seems that the "pos" attribute for nodes does nothing. Here is a minimal example:
import graphviz
import pylab
from graphviz import Digraph

g = Digraph('G', filename='ex.gv',format='pdf')
g.attr(size='7')
g.node('1',pos='1,2')
g.node('2',pos='2,3')
g.node('3',pos='0,0')
g.edge('1','2')
g.edge('1','3')
graphviz.Source(g)

Any ideas of how achieve that?
Thanks in advance.

A: Although not 100% clear in the docs, I think pos is not supported in the dot engine on input. The fdp or neato engines do support pos on input for setting the initial position, and if you end the coordinate specification with '!', the coordinates will not change and thus become the final node position.
Play with a live example at https://beta.observablehq.com/@magjac/placing-graphviz-nodes-in-fixed-positions
This standalone python script generates a pdf with the expected node positions:
#!/usr/bin/python

import graphviz
from graphviz import Digraph

g = Digraph('G', engine="neato", filename='ex.gv',format='pdf')
g.attr(size='7')
g.node('1',pos='1,2!')
g.node('2',pos='2,3!')
g.node('3',pos='0,0!')
g.edge('1','2')
g.edge('1','3')
g.render()

Since SO does not support pdf uploading, here's a png image generated with the same code except format='png':

Without the exclamation marks you get:

Without any pos attributes at all you get a similar (but not exactly the same) result:


text:
Q: Auto wrapping table columns when there is not enough space I have to work with an old templating system to display shopping products on a web page. Today, all products are displayed one by row with all the details
P1
P2
P3
P4

This old software uses a pair of tags <ED_START> <ED_END> to mark the product template that must be repeated in the HTML page. In fact, each product has its own HTML table. It works up to day.
What now I want is to reduce display size by displaying elements horizontally and vertically, like
P1 P2
P3 P4
P5 P6

or
P1 P2 P3
P4 P5 P6

according to screen resolution.
I know that if I change the product template to be a <td>, then the browser will try to render 10 or more products on the same row, which is exactly what I don't want.
Normally, I would insert a </tr><tr> every 2 elements, but this templating system (this is a legacy proprietary software) doesn't allow that. The template must be the same for all items, pure HTML plus their own markers for price, description, picture, etc.
My question is
How to I create in HTML a table that adapts the number of columns to available screen size (in other words, auto wrap columns as needed)? JavaScript and jQuery are usable.

A: What you want is a responsive design , twitter bootstrap is a good example of that.

A: Try it with media queries - DEMO
table {
    border: solid;
    float: left;
}

@media only screen and (max-width: 480px) {
    table { width: 100%; }
}

@media only screen and (max-width: 800px) and (min-width: 481px) {
    table { width: 49%; }
}

@media only screen and (min-width: 801px) {
    table { width: 33%; }
}

A: A good use of divs, like at http://android.hd2roms.com/, can help.
The secret is in the float:left style that makes them appear in sequence


text:
Q: java.lang.NoClassDefFoundError: Could not initialize class I'm trying to download a report from BingAds. My code works inside IDEA downloading the report, no big issue. When I try to make it run inside sbt like:
H24_BING_CONFIG=/home/oleber/del/develop_bing.json sbt clean 'project importerBing' 'run'
The execution fails like:
[oleber] [WARN] [home24-aws] [org.apache.cxf.transport.https.HttpsURLConnectionFactory] [Default key managers cannot be initialized: /home/oleber/.keystore (No such file or directory)]
[oleber] [WARN] [home24-aws] [org.apache.cxf.transport.https.HttpsURLConnectionFactory] [Default key managers cannot be initialized: /home/oleber/.keystore (No such file or directory)]
java.lang.NoClassDefFoundError: Could not initialize class com.sun.xml.internal.messaging.saaj.soap.SAAJMetaFactoryImpl
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at javax.xml.soap.FactoryFinder.newInstance(FactoryFinder.java:47)
    at javax.xml.soap.FactoryFinder.find(FactoryFinder.java:194)
    at javax.xml.soap.FactoryFinder.find(FactoryFinder.java:98)
    at javax.xml.soap.SAAJMetaFactory.getInstance(SAAJMetaFactory.java:74)
    at javax.xml.soap.MessageFactory.newInstance(MessageFactory.java:146)
    at javax.xml.soap.MessageFactory.newInstance(MessageFactory.java:111)
    at org.apache.cxf.binding.soap.saaj.SAAJFactoryResolver.createMessageFactory(SAAJFactoryResolver.java:56)
    at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor.getFactory(SAAJOutInterceptor.java:87)
    at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor.handleMessage(SAAJOutInterceptor.java:123)
    at org.apache.cxf.jaxws.handler.soap.SOAPHandlerInterceptor.handleMessage(SOAPHandlerInterceptor.java:120)
    at org.apache.cxf.jaxws.handler.soap.SOAPHandlerInterceptor.handleMessage(SOAPHandlerInterceptor.java:71)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
    at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:514)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:416)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:394)
    at org.apache.cxf.jaxws.JaxWsClientProxy.invokeAsync(JaxWsClientProxy.java:297)
    at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:136)
    at com.sun.proxy.$Proxy68.submitGenerateReportAsync(Unknown Source)
    at com.microsoft.bingads.reporting.ReportingServiceManager.submitDownloadAsync(ReportingServiceManager.java:196)
    at importer.bing.BingAdsImporterDownloader.submit(BingAdsImporterDownloader.scala:104)
    at importer.bing.BingAdsImporterDownloader$$anonfun$process$1$$anonfun$apply$2.apply(BingAdsImporterDownloader.scala:171)
    at importer.bing.BingAdsImporterDownloader$$anonfun$process$1$$anonfun$apply$2.apply(BingAdsImporterDownloader.scala:170)
    at common.ManagedResource$.withTmpDir(ManagedResource.scala:47)
    at importer.bing.BingAdsImporterDownloader$$anonfun$process$1.apply(BingAdsImporterDownloader.scala:170)
    at importer.bing.BingAdsImporterDownloader$$anonfun$process$1.apply(BingAdsImporterDownloader.scala:159)
    at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:253)
    at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:251)
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
    at scala.concurrent.impl.ExecutionContextImpl$AdaptedForkJoinTask.exec(ExecutionContextImpl.scala:121)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
java.lang.NoClassDefFoundError: Could not initialize class com.sun.xml.internal.messaging.saaj.soap.SAAJMetaFactoryImpl
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at javax.xml.soap.FactoryFinder.newInstance(FactoryFinder.java:47)
    at javax.xml.soap.FactoryFinder.find(FactoryFinder.java:194)
    at javax.xml.soap.FactoryFinder.find(FactoryFinder.java:98)
    at javax.xml.soap.SAAJMetaFactory.getInstance(SAAJMetaFactory.java:74)
    at javax.xml.soap.MessageFactory.newInstance(MessageFactory.java:146)
    at javax.xml.soap.MessageFactory.newInstance(MessageFactory.java:111)
    at org.apache.cxf.binding.soap.saaj.SAAJFactoryResolver.createMessageFactory(SAAJFactoryResolver.java:56)
    at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor.getFactory(SAAJOutInterceptor.java:87)
    at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor.handleMessage(SAAJOutInterceptor.java:123)
    at org.apache.cxf.jaxws.handler.soap.SOAPHandlerInterceptor.handleMessage(SOAPHandlerInterceptor.java:120)
    at org.apache.cxf.jaxws.handler.soap.SOAPHandlerInterceptor.handleMessage(SOAPHandlerInterceptor.java:71)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
    at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:514)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:416)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:394)
    at org.apache.cxf.jaxws.JaxWsClientProxy.invokeAsync(JaxWsClientProxy.java:297)
    at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:136)
    at com.sun.proxy.$Proxy68.submitGenerateReportAsync(Unknown Source)
    at com.microsoft.bingads.reporting.ReportingServiceManager.submitDownloadAsync(ReportingServiceManager.java:196)
    at importer.bing.BingAdsImporterDownloader.submit(BingAdsImporterDownloader.scala:104)
    at importer.bing.BingAdsImporterDownloader$$anonfun$process$1$$anonfun$apply$2.apply(BingAdsImporterDownloader.scala:171)
    at importer.bing.BingAdsImporterDownloader$$anonfun$process$1$$anonfun$apply$2.apply(BingAdsImporterDownloader.scala:170)
    at common.ManagedResource$.withTmpDir(ManagedResource.scala:47)
    at importer.bing.BingAdsImporterDownloader$$anonfun$process$1.apply(BingAdsImporterDownloader.scala:170)
    at importer.bing.BingAdsImporterDownloader$$anonfun$process$1.apply(BingAdsImporterDownloader.scala:159)
    at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:253)
    at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:251)
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
    at scala.concurrent.impl.ExecutionContextImpl$AdaptedForkJoinTask.exec(ExecutionContextImpl.scala:121)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

The warnings are in both places.
I'm completely lost. Do you have any possible solution?

A: The warnings about the keystore are not relevant to the exceptions.
The problem is most probably that the failing build is lacking dependencies surrounding com.sun.xml.internal.messaging.saaj.soap.SAAJMetaFactoryImpl. IDEA probably delivers that dependency. This is possible since internal builds may live in another build environment (classpath/target platform).
The most common reasons for NoClassDefFoundErrors are exceptions thrown in static initializers of referenced classes (ExceptionInInitializer as root cause) and ClassNotFoundExceptions for referenced classes. The latter is what would happen if a dependency of the SAAJMetaFactoryImpl is missing, but not the library with the FactoryImpl itself.
I suspect the exception contains another Caused-By chain link which in turn contains the root cause of that exception, mentioning the actually missing class. Maybe you can reconfigure the build to display the complete cause-chain of thrown exceptions.
In general, try to compare the two build environments with respect to the target platforms they use to resolve dependencies. This makes the missing libraries obvious.


text:
Q: Why should I use BeginWrite instead of Write? I am working on a service that manages up to 30.000 remote devices.
Doing some load tests it seems like the async method BeginWrite use more resources then regular Write (I think due to the overhead needed to create a callback thread); on the other hand, the Write method always returns faster then BeginWrite.
So my question is: what is the reason to prefer BeginWrite?
Another question is: any reason to set a WriteTimeout for sync Write? In which cases the Write method doesn't generate an immediate exception (due to closed socket, for example) but doesn't complete in a reasonable time?
EDIT: I have a set of worker threads (32 or 64), so I send data to 500-1000 devices at once and Write seems to work better than BeginWrite.
EDIT 2: after a little search I understand that sync Write hangs only if the write buffer is full. Default write buffer size is 8KB, and I just send 1-2KB of data at once, so in my application Write should never hangs and it is performing better that BeginWrite. I set a security WriteTimeout of 1 second.

A: Scalability.
Synchronous calls block the thread while they complete. Async methods don't. Depending on how many concurrent requests you're going to be dealing with, this may matter.


text:
Q: Fetch data from two tables using spark sql based on run date My application(scala/spark 2.4) reads last 6 months data from a table in hdfs(Table1) . This data will be available in a different table(Table 2) from next month. Since my application uses last 6 months of data, the source has to be both table for the first couple of months and once the new table (Table 2) has 6 months worth of data, the source should be the new table.
If the new table(Table 2) has 1 month of data, then  the program should take 1 month of data from Table 2 and 5 months prior to that from Table 1.
Similarly, when the new table(Table 2) has 2 months of data, then the program should take  2 months of data from Table 2 and prior 4 months data from Table 1.
Once the new table(Table 2) has 6 months worth of data, it shouldn't take any data from the old table(Table 1)
.
How can this be achieved?
I am a  beginner in spark and haven't been able to come up with a solution yet.


text:
Q: jQuery AJAX dataType: 'script' not working on firefox I have this code for my form in jQuery:
$('form.ajax_form').on('submit', function(){
    event.preventDefault();
    var form_errors_space = $(this).find('.ajax_form_errors:first');
    $.ajax({
      type: "POST",
      dataType: 'script',
      url: $(this).attr('action'),
      data: $(this).serialize(),
      // show success response from server.
      success: function(data, status, jqXHR) {
        console.log(data);
        console.log(status);
        console.log(jqXHR);
      },
      // show error response from the server.
      error: function(data, status, error_message) {
       // error handeling here
      }
    });
  });

Code works for chrome and safari. Issue is with Firefox, which sends the AJAX request as 'HTML' data type instead of JS/script. Any idea?
Note: I am doing this on Ruby on Rails 4, Ruby 2.1.1, I can't use default remote: true option for project specific reasons.
Firefox version: 30.0
**UPDATE: ** I tried to override content type and MIME type as well, and it didn't work either.
  ...
  data: $(this).serialize(),
  contentType: 'application/javascript',
  accepts: 'text/script',
  beforeSend: function( xhr ) {
    xhr.overrideMimeType( "application/script; charset=x-user-defined" );
  },
  .....

A: Change your code to as shown below:
$('form.ajax_form').on('submit', function(e){
  e.preventDefault();

instead of:
$('form.ajax_form').on('submit', function(){
    event.preventDefault();

more information

A: Try to use 'text' instead of script:
$('form.ajax_form').on('submit', function(){
    event.preventDefault();
    var form_errors_space = $(this).find('.ajax_form_errors:first');
    $.ajax({
      type: "POST",
      dataType: 'text',
      url: $(this).attr('action'),
      data: $(this).serialize(),
      // show success response from server.
      success: function(data, status, jqXHR) {
        console.log(data);
        console.log(status);
        console.log(jqXHR);
      },
      // show error response from the server.
      error: function(data, status, error_message) {
       // error handeling here
      }
    });
  });


text:
Q: Javascript OOP -or- why the heck is this a window I foolishly thought that a good way to get into javascript and making games would be to make a game in javascript. I used this as a tutorial, but I'm an OOP programmer, so I thought I would make it OOP. In brief my new version is this:
function Game(){this.whatever = that;...};
Game.prototype.reset = function() {...};
Game.prototype.update = function(dt) {...};
Game.prototype.render = function() {...};
Game.prototype.main = function() {
    var now = Date.now();
    var delta = now-this.then;
    this.update(delta/1000);
    this.render();
    this.then = now;

    requestAnimationFrame(this.main);
};

var g = new Game();
g.reset();
g.main();

I can't figure out what's wrong, but I get this error:
TypeError: this.update is not a function
I added the console.log for this and it shows me that it runs main twice on the correct object, and then suddenly on the third time this is the window. What am I doing wrong?


text:
Q: How does asynchronous request work for server side validation How can I asynchronously validate against a database for a value in form field?
For e.g. I have a text-box where users enter an userID to check if its available or not, I want check the input against a database table asynchronously without refreshing the page. How can I make this happen?
Thanks in advance

A: You could use the [Remote] attribute in ASP.NET MVC 3.


text:
Q: Link in "Your Projects" isn't working in WAMP server I'm on windows 8, I downloaded the wamp server and I have my index.php saved into the "www" folder within a subfolder called websites. When I'm on the localhost page, it displays the subfolder under "Your Projects" but when I click it, it takes me here
http://www.dnsrsearch.com/index.php?origURL=http%3A//websites/&r=http%3A//localhost/
and it says
"Why Am I Here?
You entered an unknown web address that was used to present site suggestions that you may find useful. Clicking any of these suggestions provides you with search results, which may include relevant sponsored links.
If this service is not right for you, please visit your Preferences page to opt out. At any point in time, you can opt back in to the service by visiting your Preferences page.
If you have other questions about this service, please visit our FAQ."
Basically, it's taking me to a search engine and trying to show some suggestions for what I could've wanted, but I'm not trying to go to a website. I'm trying to access and display my test site so I can start practicing PHP. It's been really frustrating just getting started with this because I've come across all these different ways to do php and different problems and so far, using this wampserver seems like the best option but I'm stuck. Please please please help. This is driving me nuts!
Summary:
I installed the WAMP server, I have my index.php saved in my www folder with its designated www subfolder (wamp\www\Websites\index.php), it displays on the localhost under my projects, but the link to display it doesn't work.
Any answers?
FOLLOWING UP A YEAR LATER
I appreciate the responses I've received. What I ended up doing to get the ball rolling (I went on a web development hiatus to pursue other things) and make things a lot easier to work with is I setup a LAMP server instead and it made the install process super easy and straight forward, and from there I've had no problems at all creating virtual hosts and making my websites work and having everything interact the way it should. If you're stuck where I was, setting up and using WAMP on windows is a lot more involved and touchy than setting it up on a linux system. On a linux system, you won't get a dedicated gui program like WAMP, but you'll have everything running in your operating system to handle it and it basically turns your computer into a local web server with php/sql support, and whatever else you'd like to add onto it. I'm using kali linux and it's working out fine for me. If you just want to dive into php without having to get over the huge hurdle on windows virtual hosts, I highly recommend just doing the research and setting it up on a linux system. If you have an additional hard drive, put linux on it. If you don't, setup a dual boot configuration on your drive so you'll have windows and linux. It helped me out a ton with learning how to make things on the backend reference each other the way I wanted to while also getting a significantly better understanding of it as I went. All you need installed is apache, mysql, and php and after setting everything up, it should work just fine on your local machine. Learning linux can seem scary at first, but this process is a lot more straight forward and easier to understand than doing it on windows.

A: Run the wamp server, Start apachee and enter the url as
http://localhost/websites/index.php

A: I believe this is the best and easiest solution:
Open index.php in www folder and set
change line 30:$suppress_localhost = true;
to $suppress_localhost = false;
This will ensure the project is prefixed with your local host IP/name

A: Just change the value in wamp/www/index.php line no 338.
Change this :
From
$projectContents .= '
'.$file.'
';

to
$projectContents .= '
'.$file.'
';

A: There is a document on the WAMPServer forum HERE is the link that documents an amendment you can make to revert the Project links back to Pre 2.5 mechanisms
Look for the section entitled Revert WAMPServer 2.5 "Your Projects" links to pre 2.5 mechanism
Here is the amendment :-

Revert WAMPServer 2.5 "Your Projects" links to pre 2.5 mechanism

It would appear that some WAMPServer users cannot cope with creating Virtual Hosts for each of their sites/projects.
This is code that will be in the next version of WAMPServer so if you want your "Your Projects" menu to provide links in the form 'localhost/folder_name' rather than 'folder_name' so you dont have to create a simple Virtual Host definition, here is how it should be done.
I would enphasise, this is not the recommended mechanism. The only GOOD solution is to use the Virtual Host mechanism
However, making these changes will not harm WampServer and you can always set suppressLocalhost = "yes" to keep the WAMPServer2.5 mechanism.

*

*Edit wamp/wampmanager.conf

In the section [main] add this line :
suppressLocalhost = "no"

Save the file
If this is set to "no" Your Project links will be in the form localhost/folder_name i.e. the pre WAMPServer 2.5 way.
If this is set to "yes" Your Project links will be in the form folder_name and require a Virtual Hosts definitions to work.

*

*Edit \wamp\www\index.php

Locate this line
$suppress_localhost = true;

and comment it out like so:
//$suppress_localhost = true;

*

*Find this line
$wampserverVersion = str_replace('"','',$result1); ajouter/add
and after that line add this code
//[modif oto] - On récupère la valeur de suppressLocalhost
preg_match('|suppressLocalhost = "(.*)"|',$wampConfFileContents,$result);
if($result[1] != "yes" )
    $suppress_localhost = false;
else
    $suppress_localhost = true;

Save this file

*

*Edit /wamp/scripts/config.inc.php

Find this line
$c_editor = $wampConf['editor']; ajouter/add :

and after that line add
//[modif oto] Ajout variable suppressLocalhost
if($wampConf['suppressLocalhost'] != "yes" )
    $c_suppressLocalhost = false;
else
    $c_suppressLocalhost = true;

Save the file

*

*Edit /wamp/scripts/refresh.php

Find this line
    {
        $myreplacesubmenuProjects .= 'Type: item; Caption: "'.$projectContents[$i].'"; Action: run; FileName: "'.$c_navigator.'"; Parameters: "['.$projectContents][$i].'/"; Glyph: 5

and REPLACE it with
    { //[modif oto] Support de suppressLocalhost dans wampmanager.conf
        $myreplacesubmenuProjects .= 'Type: item; Caption: "'.$projectContents[$i].'"; Action: run; FileName: "'.$c_navigator.'"; Parameters: "'.($c_suppressLocalhost ? "["]; : 'http://localhost/').$projectContents[$i].'/"; Glyph: 5

Save this file.
The changes are now complete.
Now restart WAMPServer


text:
Q: GUI Builder xml exception on build Using the new GUI builder, I have a simple GUI builder container that causes an error on build, despite of the fact that I did not touch the xml manually.  This was built with the latest version of the cn1 netbeans plugin (v3.8). The error I get is:
javax.xml.bind.UnmarshalException
 - with linked exception:
[org.xml.sax.SAXParseException; systemId: file:/Users/yaakov/Development/workspace/medonline/medonline-cn1-new/MedonlineCn1/res/guibuilder/il/co/medonline/forms/components/DoctorListItem.gui; lineNumber: 9; columnNumber: 76; An invalid XML character (Unicode: 0x8) was found in the value of attribute "name" and element is "component".]
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:335)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:563)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:249)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:162)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:171)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:189)
    at com.codename1.build.client.GenerateGuiSources.generateGuiSource(GenerateGuiSources.java:241)
    at com.codename1.build.client.GenerateGuiSources.generateGuiSource(GenerateGuiSources.java:231)
    at com.codename1.build.client.GenerateGuiSources.execute(GenerateGuiSources.java:202)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
    at sun.reflect.GeneratedMethodAccessor201.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:435)
    at org.apache.tools.ant.Target.performTasks(Target.java:456)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1393)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1364)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1248)
    at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:286)
    at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:555)
    at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:153)

My .gui file looks like this:
<?xml version="1.0" encoding="UTF-8"?>

<component type="Container" layout="LayeredLayout" layeredLayoutPreferredWidthMM="0.0" layeredLayoutPreferredHeightMM="0.0"  autolayout="true" name="DoctorListItem">
  <component type="Container" layout="BoxLayout" boxLayoutAxis="Y"  name="Container">
    <layoutConstraint insets="0px 0px 0px 0px" referenceComponents="-1 -1 -1 -1" referencePositions="0.0 0.0 0.0 0.0" />
    <component type="Container" layout="BorderLayout" borderLayoutAbsoluteCenter="false"  name="Container_2">
      <component type="Container" layout="FlowLayout" flowLayoutFillRows="false" flowLayoutAlign="1" flowLayoutValign="0"  uiid="PaddedContainer" name="Container_3">
        <layoutConstraint value="West" />
        <component type="Button" uiid="MarginlessContainer" name="ExpertPic">
        </component>
      </component>
      <component type="Container" layout="BoxLayout" boxLayoutAxis="Y"  name="Container_4">
        <layoutConstraint value="East" />
        <component type="SpanLabel" name="ExpertArea">
        <custom name="textUiid" type="java.lang.String" value="LargeText"/>
        </component>
        <component type="SpanButton" uiid="TopPaddedContainer" name="ExpertName">
        <custom name="textUiid" type="java.lang.String" value="BoldText"/>
        </component>
        <component type="SpanLabel" name="ExpertSubtitle">
        <custom name="textUiid" type="java.lang.String" value="LargeText"/>
        </component>
      </component>
    </component>
    <component type="Container" layout="FlowLayout" flowLayoutFillRows="false" flowLayoutAlign="1" flowLayoutValign="0"  uiid="DocListLowerHalf" name="Container_1">
      <component type="SpanLabel" name="ExpertShortDesc">
      <custom name="textUiid" type="java.lang.String" value="SmallText"/>
      </component>
    </component>
  </component>
</component>

Any help will be greatly appreciated
Update
Running the app in the simulator normally produces no error, but the file doesn't seem to be building - the components I added in the GUI builder don't get generated in the java file.  When I try running Build or running the app in debug mode, the error appears and the execution is stopped.

A: This seems to be a bug in the GUI builder that somehow got the 0x8 character (backspace) into the output. You don't see this character in the editor since it's invisible. Open the file in your editor and retype the "name" entry in line 8 then save. It should workaround this specific error. If additional errors like this exist notice the parser writes the specific line and attribute where corrupted data was saved.


text:
Q: Retrieve all albums from a specific year from Facebook I'm trying to get all albums in a specific year from a fan page on Facebook.  Right now Facebook is giving me in order of the most current album, but what i want is to tell Facebook that i want only albums from 2014, for example.  I'm not finding anything in the Graph API docs, any help would be really appreciated.

A: You can use the since and until request parameters as outlined in

*

*https://developers.facebook.com/docs/graph-api/using-graph-api/v2.2#paging
like this
GET /{page_id}/albums?since=1388534400&until=1420070399


text:
Q: Pandas Weighted Sum / Sumproduct Creating example data:
import pandas as pd

d = {
    "id" : [1, 1, 1, 1, 1],
    "value" : [12313, 413251, 41241, 12929, 5325],
    "R1" : [0.01, 0.15, 0.155, 0.234, 0.0003],
    "R2" : [0, 0.1, 0.009, 0.02, 0.001]
}

df1 = pd.DataFrame(d)

df2 = df1.copy()
df2['id'] = 2

df = df1.append(df2)

which is:
id  value   R1  R2
0   1   12313   0.0100  0.000
1   1   413251  0.1500  0.100
2   1   41241   0.1550  0.009
3   1   12929   0.2340  0.020
4   1   5325    0.0003  0.001
0   2   12313   0.0100  0.000
1   2   413251  0.1500  0.100
2   2   41241   0.1550  0.009
3   2   12929   0.2340  0.020
4   2   5325    0.0003  0.001

Want to calculate:
For id 1:
sumproduct[value, R1] / sum(value)
For id 2:
sumproduct(value, R1) / sum(value)
(and so on for N ids)
In this case since numbers are the same we get:
id   frac1
1    0.147
2    0.147

but should work for numbers being different too. And in the real problem I have more than just 2 ids.
And I want to do the same for R2 and more columns, but always from "value", so;
For id 1:
sumproduct[value, R2] / sum(value)
For id 2:
sumproduct(value, R2) / sum(value)
I've been trying some kind of df.groupby("id").prod()
but can't make it flexible enough / and to work

A: One easy way is group().apply():
cols = ['R1','R2']
(df.groupby('id')
   .apply(lambda x: x[cols].mul(x['value'],axis=0)
                          .sum()/x['value'].sum()
         )
)

Output:
          R1        R2
id
1   0.147467  0.086505
2   0.147467  0.086505


text:
Q: ExactTarget Triggered Send is not processing any messages I have created a triggered send in Exacttarget which I am calling via APIs (SOAP and REST). While trying out the REST APIs I ran into two errors after which the triggered send has stopped processing emails. I see that the error count is 2 and the queued count is increasing but no emails are being sent.

*

*Firstly how and where can I see details of the errors while invoking the triggered send. I am unable to get any clue on this.

*How do I get the triggered send to start processing other calls? I have tried pausing and restarting. Also tried archiving and restarting but the queue is not being processed.

Any help is greatly appreciated. I am stuck on this point now for several hours.

A: You'll have to contact SFMC Support to get the exact error that's causing your issues.
In the meantime, if you've configured your Triggered Send Definition to write to a Triggered Send templated Data Extension, you can do a Send Preview on your Email using that data to reveal any send-time errors.  The Data Extension row is written before the email is triggered.
Pausing and starting is the way to get the queue processing again.  It may take a few minutes.  If you pause it, you can also view the queue and clear it.

A: Could you tell a bit more about how you construct your API call?
If your trigger send definition is based on Data Extension. it is likely you have wrong TriggerSendSubscriber attribute name, it needs to match data extension field name. Or you didn't specify TriggerSendSubscriber's SubscriberKey/Email attribute.


text:
Q: Is there major difference between Minikube and Kind? I know Kind needs Docker, and Minikube needs Virtual Box - but for learning Kubernetes features are they the same?
Thank you.

A: In terms of learning Kubernetes features, they are the same. You will get the same Kubernetes and Kubernetes resources in both: Pod, Deployments, ConfigMaps, StatefulSets, Secrets, etc. assuming they both have the same Kubernetes version.
Under the hood they very similar too with some implementation differences.

*

*Minikube

*

*Runs K8s in VM (1.7.0 vesion now supports running minikube on Docker)

*Support multiple Hypervisors (VirtualBox, Hyperkit, parallels, etc)

*You need to ssh to VM to run docker. (minikube ssh)

*On the positive side, if you are using VMs, you get the VM isolation which is 'more secure' per se.

*Update: It does support running in docker with --driver=docker

*Kind

*

*Runs Docker in a VM (Part of the docker desktop installation for Mac, or Windows)

*Runs Kubernetes in that "Docker" VM

*Supports Hyperkit (Mac) or Hyper-V (Windows) hypervisors.

*Has the convenience that you can run the docker client from your Mac or Windows.

*You can actually run it in Linux with no need to use a VM (It's a docker native installation on Linux)

*It runs all K8s components in a single container.


text:
Q: Simplify JSON serialization in @ManyToOne relationship I have a question about ORM mapping with Spring JPA.
Consider a simple class Person:
@Entity
public class Person {

    @Id
    @NotNull
    @Column(unique = true, updatable = false, name = "PERSON_ID")
    private long personId;

    @NotNull
    @Size(min = 1)
    private String name;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Car> cars;

    public Person() {
    }
    //continue....

and a simple class Car:
@Entity
public class Car {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "CAR_ID")
    private long carId;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "PERSON_ID")
    private Person person;

    @NotNull
    @Size(min = 1)
    private String typeOfCar;

    public Car() {
    }
    //continue....

Person has a OneToMany relationship with Car.
Recalling that carId is auto-generated, when I POST a new car at the moment I am forced to specify a full Person object (apart from the nullable list of cars):
{
  "person": {
    "personId": 200,
    "name": "Jack"
  },
  "typeOfCar": "Ferrari"
}

I would like to be able to POST a car object just like this:
{
  "person": 200,
  "typeOfCar": "Ferrari"
}

thus specifying only the personId (key of the Person entity).
I guess that I need the Person reference in Car to be serialized only as its key and not as the whole object.
How to achieve this?
So far, what I have tried are the following annotations @JsonIdentityReference and @JsonIdentityInfo on the Person reference in Car as follows:
@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PERSON_ID")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "personId")
@JsonIdentityReference(alwaysAsId = true)
private Person person;

but when I POST the simplified JSON I am getting the following 404:
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Unresolved forward references for: ; nested exception is com.fasterxml.jackson.databind.deser.UnresolvedForwardReference: Unresolved forward references for: \n at [Source: java.io.PushbackInputStream@25614608; line: 5, column: 1]Object id [2] (for myapp.ws.people.entity.Person) at [Source: java.io.PushbackInputStream@25614608; line: 2, column: 13].",

A: I think one way to achieve it is to

*

*create a DTO class
class CarDto {
private long person;
private String typeOfCar;
}

*then in your service have 2 repositories. one for person and other for car.
class PersonService {

  public void post(CarDto car) {
   Person person = personRepository.findByPersonId(car.getPerson());
   Car newCar = new Car();
   newCar.setPerson(person);
   newCar.setTypeOfCar(car.getTypeOfCar);
   carRepository.save(newCar);
  }

}


text:
Q: react-apollo getClient is undefined There appears to be an error with how I'm using react-apollo. Following the docs, I am attempting to make a basic query with Apollo. This is the error I get in the browser when on the Review page. It appears that this.getClient is undefined and unable to call watchQuery.
react-apollo.browser.umd.js:417 Uncaught TypeError: this.getClient(...).watchQuery is not a function
at GraphQL.createQuery (react-apollo.browser.umd.js:417)
at GraphQL.setInitialProps (react-apollo.browser.umd.js:404)
at GraphQL.componentWillMount (react-apollo.browser.umd.js:260)
etc...

Here is the code for the Review page. I create a Review React Component, declare a graphql-tag that calls the userInfo query, and export the graphql tag connected to the Review page below.
import React from 'react'
import { graphql } from 'react-apollo';
import gql from 'graphql-tag'

class Review extends React.Component {...}

const userInfoQuery = gql`
query userInfoQuery{
  userInfo {
    _id
    email
    name {
      first
      last
    }
    isVerified
  }
}`

const ReviewWithData = graphql(userInfoQuery)(Review)
export default ReviewWithData;

A: The issue was I was defining the wrong client in the root index.js file. So for the code below, the client I was exporting was not actually the correct Apollo client. So the variable client on the sixth import was importing some other functions. Lesson learned! Should have been more careful!
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter } from 'react-router-dom'
import { ApolloProvider } from 'react-apollo';

import App from './containers/app';
import client from './services/Apollo'

const CustomerFrontendApp = (
  <ApolloProvider client={BitsyApollo.client}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </ApolloProvider>
);

render(BitsyCustomerFrontendApp, document.getElementById('root'));


text:
Q: Add Week and Month tabs to all Stack Exchange sites I find the Week and Month tabs on the home page of stackoverflow.com to be indispensable for how I use the site. In particular, most of the time that I browse the site I want to find interesting questions and answers so that I can learn from them. However, I am not able to spend much time on the site so I browse it once or twice a week for a relatively brief time. The Week and Month tabs allow me to quickly find interesting content that I would not have time to find by browsing through thousands of questions.
Now, I understand that these tabs do not necessarily show the most interesting questions but instead show the most popular questions, which might be the questions that have been bumped several times, received an answer from a high profile member of the community, or are about a common as opposed to novel issue. These tabs are not perfect; nonetheless, they go a long way toward helping me quickly pick interesting questions out of the vast sea of noise.
Unfortunately, many Stack Exchange sites, such as mathoverflow.net, programmers.stackexchange.com and politics.stackexchange.com, don't have these tabs. Fortunately, I did notice that math.stackexchange.com recently acquired them so perhaps there is already a push to add them throughout Stack Exchange. If not, I kindly request addition of these tabs to the sites that don't have them.

A: Week and Month tabs are only visible when you are logged in. You don't have an account on any of the sites you mentioned, so that's why you don't see the tabs.
This is what I see when I log into Programmers.SE:

Conversely, I do not have an account on Math.SE, so I do not see the tabs that you have recently noticed.

A: I agree that this can be kind of hidden sometimes. You have to click the icon for name of the exchange and then you have access to those links. For whatever reason, these links are not accessible if "Questions" is clicked.


text:
Q: QML Canvas: different behaviour in rendering I am trying to draw an annulus sector in QML using the Canvas object.
First, I have written the javascript code, and I have verified that it is correct by executing it in a browser.
Here it is:
var can = document.getElementById('myCanvas');
var ctx=can.getContext("2d");
var center = {
  x: can.width / 2,
  y: can.height / 2
};
var minRad = 100;
var maxRad = 250;

var startAngle = toRad(290);
var endAngle = toRad(310);

drawAxis();
drawSector();

function drawSector() {
  var p1 = {
    x: maxRad * Math.cos(startAngle),
    y: maxRad * Math.sin(startAngle)
  }
  p1 = toCanvasSpace(p1);

  var p2 = {
    x: minRad * Math.cos(startAngle),
    y: minRad * Math.sin(startAngle)
  }
  p2 = toCanvasSpace(p2);

  var p3 = {
    x: minRad * Math.cos(endAngle),
    y: minRad * Math.sin(endAngle)
  }
  p3 = toCanvasSpace(p3);
  var p4 = {
    x: maxRad * Math.cos(endAngle),
    y: maxRad * Math.sin(endAngle)
  }
  p4 = toCanvasSpace(p4);

  ctx.beginPath();
  ctx.moveTo(p1.x, p1.y);
  ctx.arc(center.x, center.y, maxRad, startAngle, endAngle);
  ctx.lineTo(p3.x, p3.y);
  ctx.arc(center.x, center.y, minRad, endAngle, startAngle, true);
  ctx.closePath();

  ctx.strokeStyle = "blue";
  ctx.lineWidth = 2;
  ctx.stroke();
}

function drawAxis() {
  ctx.beginPath();
  ctx.moveTo(can.width / 2, 0);
  ctx.lineTo(can.width / 2, can.height);
  ctx.stroke();
  ctx.beginPath();
  ctx.moveTo(0, can.height / 2);
  ctx.lineTo(can.width, can.height / 2);
  ctx.stroke();
}

function toRad(degrees) {
  return degrees * Math.PI / 180;
}

function toCanvasSpace(p) {
  var ret = {};
  ret.x = p.x + can.width / 2;
  ret.y = p.y + can.height / 2;
  return ret;
}

Here you can run the code above.
The output is this:

Next, I moved the same code into a Canvas object in Qml.
See here the main.qml containing the Canvas:
import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    visible: true
    width: 500
    height: 500
    x:500

    Canvas
    {
        id: can
        anchors.fill: parent
        antialiasing: true

        onPaint: {
            var ctx=can.getContext("2d");

            var center = {
                x: can.width / 2,
                y: can.height / 2
            };
            var minRad = 100;
            var maxRad = 250;

            var startAngle = toRad(290);
            var endAngle = toRad(310);

            drawAxis();
            drawSector();

            function drawSector() {
                var p1 = {
                    x: maxRad * Math.cos(startAngle),
                    y: maxRad * Math.sin(startAngle)
                }
                p1=toCanvasSpace(p1);

                var p2 = {
                    x: minRad * Math.cos(startAngle),
                    y: minRad * Math.sin(startAngle)
                }
                p2=toCanvasSpace(p2);

                var p3 = {
                    x: minRad * Math.cos(endAngle),
                    y: minRad * Math.sin(endAngle)
                }
                p3=toCanvasSpace(p3);
                var p4 = {
                    x: maxRad * Math.cos(endAngle),
                    y: maxRad * Math.sin(endAngle)
                }
                p4=toCanvasSpace(p4);

                ctx.beginPath();
                ctx.moveTo(p1.x, p1.y);
                ctx.arc(center.x, center.y, maxRad, startAngle, endAngle);
                ctx.lineTo(p3.x, p3.y);
                ctx.arc(center.x, center.y, minRad, endAngle, startAngle, true);
                ctx.closePath();

                ctx.strokeStyle="blue";
                ctx.lineWidth=2;
                ctx.stroke();
            }

            function drawAxis() {
                ctx.beginPath();
                ctx.moveTo(can.width / 2, 0);
                ctx.lineTo(can.width / 2, can.height);
                ctx.stroke();
                ctx.beginPath();
                ctx.moveTo(0, can.height / 2);
                ctx.lineTo(can.width, can.height / 2);
                ctx.stroke();
            }

            function toRad(degrees) {
                return degrees * Math.PI / 180;
            }

            function toCanvasSpace(p) {
                var ret = {};
                ret.x = p.x + can.width / 2;
                ret.y = p.y + can.height / 2;
                return ret;
            }

        }
    }
}

In this case I get this output:

As you can see there is an imperfection at the bottom.
I really don't understand why there is that imperfection; moreover I don't understand why the same code gives different output.
Any help is appreciated!
Thanks

A: The lineTo p3 is not needed, because when an arc segment is drawn, the connecting line is drawn automatically, according to the Canvas specifications:

The arc() method is equivalent to the ellipse() method in the case
  where the two radii are equal. [...]
When the ellipse() method is invoked, it must proceed as follows.
  First, if the object's path has any subpaths, then the method must add
  a straight line from the last point in the subpath to the start point
  of the arc.

Also, the moveTo p1 is not needed, because it would be done as part of the first arc.
As to why the extra line is being drawn further than the start of the second arc, it could be a bug in Qt (maybe a division by 0 issue - just guessing here), or maybe you simply did not compute its position correctly.


text:
Q: Salesforce Integration from third party app I'm making saleforce integration from 3rd party app, I made callout(rest API) and got  response xml schema (xsd) format.
I'm trying to generate apex classes from xsd, wsdl generation is not working because api from 3rd party app returns xml schema file not wsdl. I have no access on 3rd party app.
Can you tell me strategy how to create custom objects from this xsd (which contains metadata information)?


text:
Q: generating httptemplate (html) using python code I have used python so far only for simple applications. I want to create a html file using python code which I can use on web server. How can I create this template using Django?

A: you'll need an intro, take a look at this post http://elleestcrimi.me/2012/03/15/introduction-django-guestbook-application/
it walks you through creating a simple django app.
if there's something you can't understand there, you can comment on the blog post,
the owner is very helpful


text:
Q: Display content of large file in NSTextView I'm trying to work with large files e.g. > 1Gb and NSTextView. Of course I do not want to load whole file into memory, but load only the "visible window" of lets say of 4mb. Does anyone tried this before?
I tried to load 4mb window of file into the NSTextStorage but it is quite slow, when user is change scrollbar position the time spent for loading of next portion of data is noticeable and disturbing.
Is there some other way to deal with this kind of data loading?


text:
Q: Route match to dynamic actions in rails Can I write one row route for below two rows?
match "/article/:id/"  => "articles#redirect"
match "/articles/:id/" => "articles#redirect"

I tried something like
  match "/:article_redirect/:id/" => "articles#redirect", :constraints => {:article_redirect => /[article|articles]/}

But it didn't work.

A: I think your regexp id not good: try
match "/:article_redirect/:id/" => "articles#redirect", :constraints => {:article_redirect => /(article|articles)/}

that is (article|articles) instead of [article|articles]


text:
Q: Python/Javascript: WYSIWYG html editor - Handle large documents fast and/or design theory Background:
I am writing an ebook editing program in python. Currently it utilizes a source-code view for editing, and I would like to port it over to a wysiwyg view for editing. The best (only?) html renderer I could find for python was webkit (I am using the PyQt version).
Question:
How do I accomplish wysiwyg editing? The requirements/issues are as follows:

*

*An ebook may be up to 10,000 paragraphs / 1,000,000
characters.

*

*PyQt Webkit (ContentEditable): No problem.

*PyQt Webkit (TinyMce, etc): Takes forever to open them!

*The format is
...

...
.... The body element contains only paragraphs, there are no divs, etc (but in the paragraph there may be spans, links, etc.). Editing must take place with no significant delays as far as the user is concerned.

*

*PyQt Webkit (ContentEditable): If you try deleting text across multiple paragraphs, it takes forever!! My understanding is that this is because it resets the common-parent of the elements being changed - i.e. the entire body element, since two different paragraphs are being deleted/merged. But, there should be no need for this - it should need only delete/merge/change those individual paragraphs!

I am open to implementing my own wysiwyg editing, but for the life of me I can't figure out how to delete/cut/paste/merge/change the html code correctly. I searched online for articles about html wysiwyg design theory, and came up dry.
Thanks!

A: Can i suggest a complete another approach ? Since your ebook is only

:

*

*Split the text on

 to get an indexed array of all your paragraphs

*Make your own pagination system, and fill the screen with N paragraphs, that automatically get enough text to show from the indexed array

*When you are doing selection, you can use [paragraph index + character index in the paragraph] for selection start / end

*Then implement cut/copy/paste/delete/undo/redo based on thoses assumptions.

(Note: when you'll do a selection, since the start point is saved, you can safely change the text on the screen / pagination, until the selection end.)


text:
Q: UIDocumentPickerViewController buttons look disabled but work -- why? I am using UIDocumentPickerViewController to export images to the Files app in iOS 11. The picker comes up, and I am able to pick a destination for the files. I get the callback that the files were moved and I can see them in Files, so that appears to be working fine. However, the UI is wrong -- the Add and Cancel buttons look disabled, but they actually work fine. The buttons don't look this way if I just use Save to Files in the Share Sheet.
This is my code:
UIDocumentPickerViewController *docPicker =
[[UIDocumentPickerViewController alloc] initWithURLs:self.assetURLs inMode:UIDocumentPickerModeExportToService];

docPicker.delegate = self;
[vc presentViewController:docPicker animated:YES completion:nil];

Things I have tried:
1) I have tried both Move and Export types
2) I have enabled the iCloud capability (all three items: key-value, Document, and CloudKit) - no difference in the experience [in fact, the code worked even without these set, though the docs say otherwise])
Here is an screenshot of what the UI looks like. As you can see, the UI says it will add the item to the chosen directory (and it, in fact, does if I tap on Add):

Anyone know how to get the buttons to appear blue and look enabled? I have not found any sample code online that I could try -- if someone has a pointer, I can try that to see if it's something about my configuration or code.

A: I'm not a big fan of temporarily changing the global appearance like suggested in the approved answer. You can just reset the appearance for UIDocumentPickerViewController and the bar buttons will return to their original blue.
if #available(iOS 11.0, *) {
    UINavigationBar.appearance(whenContainedInInstancesOf: [UIDocumentBrowserViewController.self]).tintColor = nil
}

A: Based on your comment, your app is setting the tintColor using UINavigationBar.appearance. This will affect all navigation bars, including those of system navigation controller such as UIDocumentPickerViewController.
I've dealt with this in one of my own apps. One solution is to subclass UIDocumentPickerViewController and to use your subclass anywhere you need the picker view. In your subclass, override viewDidLoad and set UINavigationBar.appearance.tintColor back to nil. And also override viewWillDisappear to reset UINavigationBar.appearance.tintColor back to the desired color.


text:
Q: How to use conditional if statements in Jinja 2? So I am new to Django and can use some help.
I have used a for loop to display a list from my database. But I want to add an if statement such that, if the user input matches my database item, only then it should be displayed. Take a look :
{%for inc in all_items%}

        {#I want to add an if statement here, if user input == inc_element#}

{{inc.item_name}}

{%endfor%}

I know I 'd have to use HTML forums for taking user input. But how do I match it in if statement. Help would be appreciated.

A: Note: mess is a variable
Below code syntax for using 'for loop' and 'if statements' in Python Language together with Jinja in HTML file:
{% for mess in get_flashed_messages() %}
    {%if mess == "Your Dog's breed is rufus"%}
      {{mess}}
    {% else %}
      {{"Don't you have any other breed?"}}
      {% endif %}
    {% endfor %}

And below is the code if your using Jinja with Bootstrap in HTML file:
{% for mess in get_flashed_messages() %}
    {%if mess == "Your Dog's breed is rufus"%}

      {{mess}}
    {% else %}

      {{"Don't you have any other breed?"}}
      {% endif %}
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        ×
      </button>

    {% endfor %}

A: General conditional syntax is like this:
{% if some_variable == some_value %}
    {{ do_something }}
{% endif %}

Docs have some more examples.


text:
Q: Why is JSON returning only 1 image output for my query? I am executing a PHP script that encodes my query into JSON format, based on a database containing matches and teams. Match table has 2 fields

(team_1 name and team_2 name as foreign keys)

while the Team table has the name of the team + logo.
This is my query to get the names of the teams playing and their logo in every match:
Select m.team_1, t1.team_logo, m.team_2, t2.team_logo
From Match m, Team t1, Team t2
Where t1.name = m.team_1 and t2.name = m.team_2;

My problem is that JSON is only returning the first team name, second team logo, and second team name.
Why is that? and how can I fix it?

A: Try this:
Select
  m.team_1, t1.team_logo AS logo_team1,
  m.team_2, t2.team_logo AS logo_team2
From Match m, Team t1, Team t2
Where t1.name = m.team_1 and t2.name = m.team_2;

Regards


text:
Q: Hiding elements based on URL I'm trying to hide an element that is created dynamically, below is the code I have tried but for some reason the menu still appears after the JavaScript has run.  It works in an html page, but not in asp.net.
<script type="text/javascript">
   if (window.location.href.indexOf("http://www.test.com/xzy") != -1) {
       $("#Menu").hide();
   }
</script>

A: This would be the first step. Add a Document ready statement so javascript execute himself after DOM is loaded.
 document.addEventListener("DOMContentLoaded", function(event) {
    if (window.location.href.indexOf("http://www.test.com/xzy") != -1) {
         $("#Menu").hide();
    }
  });

if you need it to work in IE8, I read you can use this:
    r(function(){
        if (window.location.href.indexOf("http://www.test.com/xzy") != -1) {
           $("#Menu").hide();
        }
   });
   function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

Credits to the author.


text:
Q: Can't download .csv from dropbox require(data.table)
require(httr)

url = "http://www.dropbox.com/s/0brabdf53lc37i/data.csv?dl=1"
request <- GET(url)

Loading required package: data.table
Loading required package: httr
Error in curl::curl_fetch_memory(url, handle = handle) :
  Couldn't resolve host name
Calls: GET ... request_fetch -> request_fetch.write_memory ->  -> .Call
Execution halted

What gives? The URL works fine in my browser and others have had success downloading dropbox files this way...

A: I have an answer to your question, after a lot of searching around.  When I noticed that R was changing the protocol of your DropBox URL from http to https, I became suspicious that you might have a certificate problem.  As this SO post mentions, this seems to precisely be the case.  Try using this code:
require(data.table)
require(httr)

cafile <- system.file("CurlSSL", "cacert.pem", package = "RCurl")
url = "http://www.dropbox.com/s/0brabdf53lc37i/data.csv?dl=1"
request <- GET(url, config(cainfo = cafile))

What is happening here:
The cert file cacert.pem contains a list of trusted certificates, issued from a CA (Certificate Authority).  When DropBox sends R its public SSL certificate, R will search through this list of trusted certificates to see if it can find it.  If it can, it will allow the SSL handshake to complete, and your data will be downloaded.
The reason why you are having this problem but many who read your question do not have it, is that you likely never configured your curl settings in R.

A: The "can't resolve" message is occurring because dropbox is turning your http request into an https request (not all services can follow redirects) and (most likely) because your download protocol can't handle secure http and because the url doesn't request the raw data...
All problems are best fixed by moving to the format the host (dropbox) will direct you too, ie., https, and then switching your code (if necessary) to use the new protocol, and correcting the url to tell dropbox to serve the raw file (not the ?dl=1 suffix you're using, but ?raw=1
So:

*

*switch the url to secure

*

*"https://www.dropbox.com/s/0brabdf53lc37i/data.csv?dl=1"

*Switch the request to raw

*

*"http://www.dropbox.com/s/0brabdf53lc37i/data.csv?raw=1"

*Test that in a browser - would work if this wasn't a bad link.

*Open using R functions like url() that can handle secure transport (example of this is at this answer


text:
Q: I'm getting 415 error on spring, but same other code works I'm getting 415 error on spring, I used java script to send request.
I already added jackson dependency to use json, but still not working. also weird thing is that other url with same code works.
I added suggested code and it's still not working..
Client code:
let data = {
  id: category.id,
  act: "addAdmin",
  target: input,
};

fetch("http://localhost:8888/categoryset", {
  method: "POST",
  header: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(data),
});

Server code
// CategorySetDTO.java
@Getter
@Setter
@NoArgsConstructor
public class CategorySetDTO {
    private String act;
    private int id = -1;
    private String target;
}

// ApiController.java
@PostMapping(value = "/categoryset", consumes = MediaType.APPLICATION_JSON_VALUE)
public String updateCategory(HttpServletRequest request, @RequestBody CategorySetDTO data) {
    return pageService.updateCategory(request, data);
}


text:
Q: How to decide cross or straight cable I know that you have to connect same devices with cross cable and differents with straight. Although, that's the common idea, in Cisco Packet Tracer you have to connect a PC and a router with cross cable. What's the correct logic in this?

A: Switches and hubs (for the few that are still left) can be viewed as network infrastructure devices in which everything else plugs into them with a straight cable. All other connections, including switch-to-switch, hub-to-hub and hub-to-switch, will be accomplished with a crossover cable - hence the crossover between the PC and router within Packet Tracer.
These days a lot more equipment is showing up with "auto-detect" (sometimes referred to as auto-DIX or auto-MDI/MDIX) where the network port is able to determine its configuration, so it will work regardless of the cabling and equipment combination.

A: It's down to the actual wiring of the ports; you will find that a crossover has two pairs swapped around and the intention of this is to permit you to directly connect two hosts together (as originally they wouldn't physically be able to autodiscover their wiring and thus would require this)
In reality however, it's pretty much an archaic novelty; providing you're using cat5e cable or better, it's very unlikely to be an issue.
There is a small curio that on 1000BASE-T if you are missing one of those pairs, it will negotiate 1Gbps but never actually be able to transmit any data; fortunately a most modern Gbps interfaces will even handle this sort of foolishness and drop down to a slower speed if they don't see anything on the wire.


text:
Q: WCF Only Add Service Reference in Same Project I have a WCF service and I am able to create proxies for it if the project in which I am creating the proxies (by adding a service reference) is in the same solution as the WCF service.
However, if I try to add a service reference in a project, which is in a different solution to the WCF service (which I do have running), it is unable to find the endpoint.
The are message talks about meta data, but I have added the following behaviour which exposes the metadata
<serviceMetadata httpGetEnabled="true" />

The details of the error message are:
There was an error downloading 'http://localhost:8112/LTA/_vti_bin/ListData.svc/$metadata'.
The request failed with HTTP status 405: Method Not Allowed.
Metadata contains a reference that cannot be resolved: 'http://localhost:8112/LTA'.
There was no endpoint listening at http://localhost:8112/LTA that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
The remote server returned an error: (404) Not Found.
If the service is defined in the current solution, try building the solution and adding the service reference again.

Does anyone have any idea what the problem is? The whole ServiceModel element is:
<system.serviceModel>
<services>
  <service name="WCFLicenceService.LicenceTrackerService">
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8112" />
      </baseAddresses>
    </host>
    <endpoint address="LTS" binding="basicHttpBinding" contract="WCFLicenceService.ILicenceTrackerService" />
    <endpoint
      address="net.tcp://localhost:8113/LTS"
      binding ="netTcpBinding"
      contract="WCFLicenceService.ILicenceTrackerService" />
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceDebug includeExceptionDetailInFaults="true" />
      <serviceMetadata httpGetEnabled="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<bindings>
  <basicHttpBinding>
    <binding maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
      <readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" />
    </binding>
  </basicHttpBinding>
  <netTcpBinding>
    <binding maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
      <readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647"/>
    </binding>
  </netTcpBinding>
</bindings>
</system.serviceModel>

A: As you had seen, the service reference is created against http://localhost:8112/LTA/_vti_bin/ListData.svc/$metadata which has to be live. If the Web service project is in the same Sln, VS IDE could do the trick for you through launching the service on built-in Web server like IIS Express. If the service project is sitting in another sln, you will have to run the service in another instance of VS IDE.
For large projects, and for those Web services to be consumed by many other projects siting in other VS solutions, it is better not to use the Service Reference approach, rather, you may create a client API for each service. And the client API could be distributed to other .NET projects. For more details about how to create client API and respective benefits, please check
WCF for the Real World, Not Hello World


text:
Q: Calling a fragment and getting the id in the RecyclerView adapter I have a list using the RecyclerView, what I want is that when I click on the list item, it opens a fragment, I've been searching and I only found it with an activity, but I'm working only with fragments, if I use activity it disappears with my action bar, it's all set in the fragment.
This is my adapter class:
    public class CreditCardAdapter extends RecyclerView.Adapter<CreditCardHolder> {

    private final List<CreditCard> creditList;

    public CreditCardAdapter(List<CreditCard> creditList) {
        this.creditList = creditList;
    }

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

    @Override
    public void onBindViewHolder(@NonNull CreditCardHolder holder, int position) {
        CreditCard credit = creditList.get(position);
        String flag = credit.getFlag();
        holder.flag.setText(flag);
        String owner = credit.getOwner();
        holder.owner.setText(owner);
        String valueLimit = String.format("%.2f", credit.getLimit());
        holder.limit.setText(valueLimit.replace(".", ","));
        holder.creditCardId = credit.getId();

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               //Method on click
            }
        });
    }

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

I need to send the credit card id to the fragment, to call the controller and get the information from the database, I tried it with the intent, but it only worked if I call the activity with startActivity(intent).
So here it is the fragment class:
public class InfoCreditCardFragment extends Fragment {

    public InfoCreditCardFragment() {
        // Required empty public constructor
    }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_info_credit_card, container, false);

        String id; //Here I need the id from the Adapter

        TextView flagInfoTxt = view.findViewById(R.id.flagInfoTxt);
        TextView ownerInfoTxt = view.findViewById(R.id.ownerInfoTxt);

        CreditCard cc = CreditCardController.getWithId(id);
        flagInfoTxt.setText(cc.getFlag());
        ownerInfoTxt.setText(cc.getOwner());

        return view;
    }
}

If anyone knows anything to help, please, I'm desperate.

A: So, I managed to go to the fragment using this:
Bundle bundle = new Bundle();
bundle.putString("id", holder.creditCardId);

InfoCreditCardFragment fragment = new InfoCreditCardFragment();
AppCompatActivity activity = (AppCompatActivity) view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, fragment).addToBackStack(null).commit();

And inside the fragment I just get the bundle with "getArguments().getString("id");"


text:
Q: JSTL calculation error Is this the correct code to print out the calculated value? There seems to be no error but it just directly prints out all my values with the addition, times sign etc.
This is the code:
Monthly Instalment = <c:out value="(${LoanAmount} + (${LoanAmount} * ${IR} * ${param.loanPeriod}))/ (${param.loanPeriod} * 12)" />

A: You need to wrap the entire calculation in ${...} rather than just the individual variables:
Monthly Instalment = <c:out value="${(LoanAmount + (LoanAmount * IR * param.loanPeriod))/ (param.loanPeriod * 12)}" />

This causes the entire expression to be evaluated, whereas in your case each occurrence of ${...} being evaluated individually and the result inserted into a string.

A: One cause of that problem is not importing the JSTL library. Try putting
<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>
...at the top of the JSP file.


text:
Q: Ruby 2.1.1 with RVM: Getting libyaml errors I would like to use Ruby 2.1.1p76 and Rails 4.1.0beta1. I am getting some errors with RVM. I was using Ruby 2.0.0 and Rails 4.0.0. I upgraded to OS X Mavericks 10.9.2 and needed to reload everything.
Anyway, these are the commands I am running.
\curl -sSL https://get.rvm.io | bash -s stable --ruby

This installs successfully. Then I run this command to install rails.
sudo gem install rails

I get the following errors, says it is looking for libyaml.
/Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/yaml.rb:4:in `<top (required)>':
It seems your ruby installation is missing psych (for YAML output).
To eliminate this warning, please install libyaml and reinstall your ruby.
/Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require': dlopen(/Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/x86_64-darwin13.0/psych.bundle, 9): Library not loaded: /usr/local/lib/libyaml-0.2.dylib (LoadError)
  Referenced from: /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/x86_64-darwin13.0/psych.bundle
  Reason: image not found - /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/x86_64-darwin13.0/psych.bundle
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/psych.rb:1:in `<top (required)>'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/yaml.rb:5:in `<top (required)>'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems.rb:616:in `load_yaml'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/config_file.rb:328:in `load_file'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/config_file.rb:197:in `initialize'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/gem_runner.rb:74:in `new'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/gem_runner.rb:74:in `do_configuration'
      from /Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/rubygems/gem_runner.rb:39:in `run'
      from /Users/username/.rvm/rubies/ruby-2.1.1/bin/gem:21:in `<main>'

So, I run this command which is deprecated.
rvm pkg install libyaml

This gives me a deprecation warning and says to check out autolibs.
So I correct and verify both.
brew install libyaml
##
Warning: libyaml-0.1.4 already installed

more...
brew info libyaml
##
libyaml: stable 0.1.5 (bottled)
http://pyyaml.org/wiki/LibYAML
/usr/local/Cellar/libyaml/0.1.4 (7 files, 344K) *
  Built from source
From: https://github.com/mxcl/homebrew/commits/master/Library/Formula/libyaml.rb
==> Options
--universal

Install autolibs.
rvm get stable --autolibs=enable
rvm install ruby
rvm --default use ruby-2.1.1

Then, I get the same error.
Using /Users/username/.rvm/gems/ruby-2.1.1
/Users/username/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/yaml.rb:4:in `<top (required)>':
It seems your ruby installation is missing psych (for YAML output).
To eliminate this warning, please install libyaml and reinstall your ruby.

A: brew unlink libyaml && brew link libyaml

https://github.com/wayneeseguin/rvm/issues/2689


text:
Q: UML Diagram Help (Aggregation/Composition) I'm having some trouble fully understanding composition and aggregation. From what i'm understanding a composition relationship means if one dies the other dies. aggregation means they're formed of that, but not necessarily dependent on that things continued existence.
This is the UML I put together for a game of hearts. Am I grasping this concept correctly?

A: What is composition and aggregation ?
The composition and aggregation represents a whole/part relationship (UML 2.5, section 11.5.3.1):

A binary Association may represent a composite aggregation (i.e., a
  whole/part relationship).

So if you use a diamond, you should first ask yourself if it's really a whole/part relationship, before thinking how objects are created or deleted.
Then composition have additional constraints over a shared aggregation. In a composition relationship (UML 2.5, section 9.5.3):

(...) the composite object has responsibility for the existence and storage
  of the composed objects.  Composite aggregation is a strong form of
  aggregation that requires a  part object be included in at most one
  composite object at a time. If a composite object is deleted, all of
  its  part instances that are objects are deleted with it.

Analysis of your specific diagramm
According to your diagram:

*

*The players exists only within a game (i.e. temporary identification not accounts existing across several games). The composition could make sense, as players can be seen as parts of the game.

*The hand exist only in relation to a player. That makes sense. But is it really a composition relationship ?  Is the hand a part of a player ? Is the player composed of hands ? Wouldn't a player have several hands sequentially but not in the same time ?  I really have my doubt about a composition here;  I'd represent this with a normal 1 player to many hands association.

*The game aggregates several decks.  I don't know your game but I'd expect one deck.  If several decks are used, and the decks only exists within a game (similarly to the players), I'd rather see a composition instead of an aggregation.  Alternatively you could mean not the deck, but the deck together with its state.  In this case, I'd opt for a one to many association and not a composition (the deck+state would not be a component of your game, but define the state of the game).

*A deck is the aggregation of cards that exist independently of the deck.  This troubles me a lot, as my world experience has always shown that a card is part of a deck. If I find an isolated card somewhere I always look for it's deck.  I'd therefore rather expect a composition between cards and deck.

*Finally a hand is the aggregation of several cards, which seems to make sense. Note that this is not incompatible with a composition between the deck and the card.


text:
Q: ASP.NET environment on Linux
Possible Duplicate:
Installation of Visual Studio On Linux Machine

I'm usually working with python/php and such, but now my professor demand me to work with Visual Studio 2010. Bad news is, I don't have a Windows OS, so -
Are there any options to get Visual Studio 2010 up and running on Debian/Ubuntu?

A: You can't run Visual Studio on Linux. You can run Mono Develop and create ASP.NET projects in it. It works pretty good.
Other alternative. Install Virtual Box, install Windows and then VS.

A: The best option is to use a virtual machine - the guest would be running Windows. Check DreamSpark - you may be able to get Windows Server 2008 R2 (and other software) for free if your school participates.
If you look at Wine, Visual Studio 2010 and 2012 are not doing very well, so that's not a real option at this time.
The mono project has a free C# IDE - Mono Develop, though it is not Visual Studio it is quite fully featured and supports ASP.NET development.

A: If you want to use Visual Studio you will have to install WINE (but do not think it's a good solution)
http://appdb.winehq.org/objectManager.php?sClass=application&iId=892
But you can also use the Mono Project
http://www.mono-project.com/Main_Page
Or just install a Virtual Machine with a windows OS
You are free to choose what best suits your needs


text:
Q: Python argparse: Is there a way to print help for only a specific parameter? I have a long list of parameters, so the output from mycommand --help is getting very big. I would like to provide my users a way to get the help text for only a specific parameter.
Something like this (doesn't work, shows the whole help text)
mycommand --help --parameter-of-interest

I don't want to split everything into subparsers if at all avoidable.

A: You can create your own actions to achieve this. Both of these will iterate the optional arguments and suppress any that are not found in sys.argv. I'd recommend the explain action as this doesn't mess with the -h/--help flag.
Explain Action
This creates an action ExplainParamsAction with the corresponding -e/--explain options that filters the help text for just specified parameters.
import sys
import argparse

class ExplainParamsAction(argparse.Action):
    def __init__(
        self,
        option_strings,
        dest=argparse.SUPPRESS,
        default=argparse.SUPPRESS,
        **kwargs
    ):
        super().__init__(option_strings, dest, default=default, nargs=0, **kwargs)

    def __call__(self, parser, namespace, values, option_string=None):
        opts = parser._option_string_actions
        for arg in opts:
            if arg not in sys.argv:
                setattr(opts[arg], "help", argparse.SUPPRESS)
        parser.print_help()
        parser.exit()

parser = argparse.ArgumentParser()
parser.add_argument(
    "-e",
    "--explain",
    action=ExplainParamsAction,
    help="Show help message for only specified parameters and exit",
)
parser.add_argument("--url", help="URL to the resource")
parser.add_argument("--port", help="Port to the resource")
parser.add_argument("--timeout", help="Connection timeout")
args = parser.parse_args()

Override the Help Action
Alternatively you can override the help action that you supply to your parser.
To use with an argparse.ArgumentParser you need to turn off the default helper and provide your own.
import sys
import argparse

class _CustomHelpAction(argparse._HelpAction):
    def __call__(self, parser, namespace, values, option_string=None):
        args = sys.argv[1:]
        opts = parser._option_string_actions
        # Check is needed for just -h/--help to work
        if len(args) > 1:
            for arg in opts:
                if arg not in args:
                    setattr(opts[arg], "help", argparse.SUPPRESS)
        super().__call__(parser, namespace, values, option_string)

# Init parser with help turned off
parser = argparse.ArgumentParser(add_help=False)

# Register your help action and manually add the `-h/--help` option
parser.register("action", "help", _CustomHelpAction)
parser.add_argument("-h", "--help", action="help", help="show this help message and exit")

# Add remaining arguments
parser.add_argument("--url", help="URL to the resource")
parser.add_argument("--port", help="Port to the resource")
parser.add_argument("--timeout", help="Connection timeout")
args = parser.parse_args()

Example usage:
All help:
python3 script.py --help
usage: script.py [-h] [--url URL] [--port PORT] [--timeout TIMEOUT]

optional arguments:
  -h, --help
  --url URL          URL to the resource
  --port PORT        Port to the resource
  --timeout TIMEOUT  Connection timeout

Specific parameters:
~ python3 script.py -h --url --timeout
usage: script.py [--url URL] [--timeout TIMEOUT]

optional arguments:
  --url URL          URL to the resource
  --timeout TIMEOUT  Connection timeout

~ python3 script.py -h --timeout --port
usage: script.py [--timeout TIMEOUT] [--port PORT]

optional arguments:
  --port PORT        Port to the resource
  --timeout TIMEOUT  Connection timeout

This naively assumes that you are only using sys.argv, I'm not really sure what would need to be done if it weren't.

A: This has been discussed here: Customize argparse help message
In essence, you can overwrite the help by adding --help as argument.
Edit: the custom help could be pointing to a syntax for getting help on a specific parameter like -s parameter_you_wish_help_about.
Edit 2: Haven't tested it, but something along this lines.
parser.add_argument('-s',action='store',dest='para', type=str, help='Get Help on specific parameter')
parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help='Use -s to get help on specific parameter')

help_dict={}
help_dict['para_1']='Help on para_1'
print (help_dict[args.para])


text:
Q: what is the difference between 10 <=n<=1 and n<=1 or n>=10? Given a number n, return True if n is in the range 1..10, inclusive. Unless outside_mode is True, in which case return True if the number is less or equal to 1, or greater or equal to 10.
def in1to10(n, y):
  if y:
    if n<= 1 or n >= 10:
      return True
    else:
      return False

  else:
    if n >= 1 and n <= 10:
      return True
    else:
      return False

I can't understand the difference between the code, please explain codingbat problem
def in1to10(n, y):
  if y:
    if 10 <= n <=1:
      return True
    else:
      return False

  else:
    if 1<= n <= 10:
      return True
    else:
      return False

A: 10 <= n <= 1 basically means n <= 1 and n >= 10 which is different from n <= 1 or n >= 10
Lets put them underneath each other to see the difference:
n <= 1 and n >= 10
n <= 1 or  n >= 10

As you can see they are identical, except the first one uses logical and while the other one uses logical or
This means that in the first one both comparisons must end up being true, while in the second one only one of them has to be true
This whole a <= b <= c syntax is just syntax sugar named 'comparison chaining' you can read more about it here

A:  def in1to10(n, outside_mode):
  if  outside_mode and( n>=10 or n<=1):
      return True
  elif outside_mode and( n<10 and n>1):
    return False
  else:
    if 1<=n<=10 and outside_mode == False:
        return True
    elif outside_mode == False and n<1 or n>10:
      return False


text:
Q: Mystery about Kafka's retention period I have a topic configured on our production cluster, it has a retention period of 432000000 ms i.e 5 days. But it is usually holding earliest messages containing timestamps of 10 days ago! For example, today on 22nd March I checked data in that topic using console consumer command. First record was having timestamp of 12th March. This data went in the topic at nearly the same time when it was generated, so there is no difference between timestamp in the log and actual time when it got queued up. So how can this happen that Kafka is storing messages well past the configured retention period?

A: The retention settings are lower bound limits.
In your example it means Kafka will not delete any messages that are less than 5 days old.
The logs on disk are split up in several segments. Kafka only performs deletion on full segments and does not touch the latest (active) segment. So in order for a segment to be deleted, the last message in it has to be older than 5 days and it must not be the latest segment.
By default, Kafka only rolls new segments if they are older than 7 days (log.roll.hours=168) or if they reach their max size (log.segment.bytes=1GB).
So it looks like you've not produced enough data to roll a new segment because of size, so I suggest to reduce log.roll.hours to force new segments to be created more frequently.


text:
Q: How to store a virtual member function in std::function? class foo
{
public:
    foo(void)
    {
        this->f = std::bind(&foo::doSomething, this);
    }

private:
    virtual void doSomething(void) { }

private:
    std::function<void(void)> f;
}

class bar : public foo
{
public:
    bar(void) { /* I have no idea what I have to */ }

private:
    virtual void doSomething(void) override { }
}

I want to assign overrided 'doSomething' function into 'foo::f'. but I have no idea how can I assign overrided 'doSomething' function. or I just write some code for assigning 'doSomething' function for each class?
class foo
{
public:
    foo(void)
    {
        this->f = std::bind(&foo::doSomething, this);
    }

private:
    virtual void doSomething(void) { }

private:
    std::function<void(void)> f;
}

class bar : public foo
{
public:
    bar(void)
    {
        this->f = std::bind(&bar::doSomething, this);
    }

private:
    virtual void doSomething(void) override { }
}

That code is my answer of my question. but I think I can assign virtual function into std::function automatically.

A: this->f = std::bind(&foo::doSomething, this);

This works just fine. Passing the object by pointer or reference will allow it to call the correct virtual function.


text:
Q: HTML form not sending post through submit I have checked all the solutions on Stack overflow...and I am meeting all I need. Still my HTML form is not sending post request.here is my code.
This is create_blog.php page ..this includes
<?php include_once ('blog_controller.php'); ?>

at top.
<form action="create_blog.php" method="post">

         <input type="text" name="title" class="field form-control input-lg" required id="field-fname" value="" placeholder="Title*" />

         <textarea class="textarea" name="body"  required id="field-message" placeholder="Content*"></textarea>

   <?php
   if (isset($error)) {
       echo '
' . $error . '
';
   }
   if (isset($success)) {
       echo '
' . $success . '
';
   }
   ?>

      <input type="submit" value="CREATE NOW" name="add_blog" class="button btn-purple btn-small" />

</form>

Here is blog_controller.php
<?php
include_once ('ManageBlogs.php');
$init = new ManageBlogs();

//CREATE NEW BLOG

if (isset($_POST['add_blog'])) {
    $title = $_POST['title'];
    $body = $_POST['body'];
    $date_created = date('Y-m-d H:i:s');

    if (empty($title)) {
        $error = 'You must provide a title to add this blog.';
    } else {
        $create_code = $init->addNewCode($title, $body, $date_created);

        if ($create_code == 1) {
            $success = 'Blog '.$title.' added Successfully';
        } else {
            $error = 'Error adding Blog. Please Try Again.';
        }
    }
}
?>

Still it's sending no POST request on submit button click.

A: Change :
<form action = 'create_blog.php' ...>

To :
<form action = 'blog_controller.php' ...>

You have handled the form in blog_controller.php
but the action of the form is create_blog.php
Also check if on javscript side you have this code :
event.preventDefault();

This javascript coding also prevents the form to transfer the control to PHP coding once the button is fired .

A: What I understood is, you want to send data from login.php to login_controller.php, right?
So the action in the form is going to be 'login_controller.php', not 'create_blog.php'.

A: I've gone through your code and it is working without any issues. Since I'm not including ManageBlogs.php which means it may cause this error. Try to remove the file inclusion and check again. If you are getting the output which means, some unwanted internal redirects are removing the POST values.
Here is the code which I tried and it is working.
<?php

include_once ('blog_controller.php');

if (isset($title)) {
   echo 'Title: '.$title;
}
?>
<form action="create_blog.php" method="post">

         <input type="text" name="title" class="field form-control input-lg" required id="field-fname" value="" placeholder="Title*" />

         <textarea class="textarea" name="body"  required id="field-message" placeholder="Content*"></textarea>

    <?php
    if (isset($error)) {
       echo '
' . $error . '
';
    }
    if (isset($success)) {
       echo '
' . $success . '
';
    }
   ?>

      <input type="submit" value="CREATE NOW" name="add_blog" class="button btn-purple btn-small" />

</form>

blog_controller.php
<?php
// include_once ('ManageBlogs.php');
// $init = new ManageBlogs();

if (isset($_POST['title'])) {
    $title =  $_POST['title'];
}
?>

A: Try this : Remove <?php include_once ('blog_controller.php'); ?> from top and change action from create_blog.php to blog_controller.php
As I got from your question you want data from current form to blog_controller.php where you have code to do something.


text:
Q: Javascript Array non empty array with 0 length I'm using knockout js to create a list with a search function.
Result of the console.log:

As you can see the array supposedly has 5 objects in it but then the proto has 0. I don't understand what might be wrong.
var iniList = [
    new Spot("Park"),
    new Spot("High School"),
    new Spot("Soccer Stadium"),
    new Spot("Railway Station"),
    new Spot("Hospital")
];

var viewModel = {
    spots: ko.observableArray(iniList),
    filter: ko.observable(''),
    search: function(value) {
        console.log(iniList);

        viewModel.spots.removeAll();
        for (x = 0; x < iniList.length; x++) {
            console.log("iniList[x]");
            if (iniList[x].name.toLowerCase().indexOf(value.toLowerCase()) >= 0) {
                viewModel.spots.push(iniList[x]);
            }
        }
    }
};

A: You're running "viewModel.spots.removeAll();" This removes all elements ofthe observable array.