text:
Q: libGL error for MATLAB When I call matlab from terminal
I got
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast

My libgl drivers
-rw-r--r-- 1 root root 459392 Ago 11 19:49 /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1.2.0
lrwxrwxrwx 1 root root 14 Ago 11 19:49 /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1 -> libGL.so.1.2.0
lrwxrwxrwx 1 root root 19 Out 25 16:43 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/sys/opengl/lib/glnxa64/libGL.so.1 -> libGL.so.1.5.070200
-r-xr-xr-x 1 root root 3200281 Dez 29  2014 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/sys/opengl/lib/glnxa64/libGL.so.1.5.070200

My graphics card
 lspci -vnn | grep VGA -A 12
03:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] Caicos [Radeon HD 6450/7450/8450 / R5 230 OEM] [1002:6779] (prog-if 00 [VGA controller])
    Subsystem: Hightech Information System Ltd. Caicos [Radeon HD 6450/7450/8450 / R5 230 OEM] [1787:2311]
    Flags: bus master, fast devsel, latency 0, IRQ 42
    Memory at e0000000 (64-bit, prefetchable) [size=256M]
    Memory at d0100000 (64-bit, non-prefetchable) [size=128K]
    I/O ports at 1000 [size=256]
    Expansion ROM at d0140000 [disabled] [size=128K]
    Capabilities: <access denied>
    Kernel driver in use: radeon
    Kernel modules: radeon

03:00.1 Audio device [0403]: Advanced Micro Devices, Inc. [AMD/ATI] Caicos HDMI Audio [Radeon HD 6400 Series] [1002:aa98]
    Subsystem: Hightech Information System Ltd. Caicos HDMI Audio [Radeon HD 6400 Series] [1787:aa98]

I can locate library
milenko@milenko-desktop:~$ locate r600_dri.so
/usr/lib/x86_64-linux-gnu/dri/r600_dri.so

I have made symbolic link
 sudo ln -sf /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1.2.0 /usr/local/MATLAB/MATLAB_Production_Server/R2015a/sys/opengl/lib/glnxa64/libGL.so.1.5.070200

but
libGL: OpenDriver: trying /usr/lib/x86_64-linux-gnu/dri/tls/r600_dri.so
libGL: OpenDriver: trying /usr/lib/x86_64-linux-gnu/dri/r600_dri.so
libGL: dlopen /usr/lib/x86_64-linux-gnu/dri/r600_dri.so failed (/usr/local/MATLAB/MATLAB_Production_Server/R2015a/bin/glnxa64/../../sys/os/glnxa64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by /usr/lib/x86_64-linux-gnu/dri/r600_dri.so))
libGL: OpenDriver: trying ${ORIGIN}/dri/tls/r600_dri.so
libGL: OpenDriver: trying ${ORIGIN}/dri/r600_dri.so
libGL: dlopen ${ORIGIN}/dri/r600_dri.so failed (${ORIGIN}/dri/r600_dri.so: cannot open shared object file: No such file or directory)
libGL: OpenDriver: trying /usr/lib/dri/tls/r600_dri.so
libGL: OpenDriver: trying /usr/lib/dri/r600_dri.so
libGL: dlopen /usr/lib/dri/r600_dri.so failed (/usr/lib/dri/r600_dri.so: cannot open shared object file: No such file or directory)
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600

What should I try?I am on Ubuntu 16.04.

A: Apprarently the problem is due to having the drivers installed in two folders. I found a solution on the official MATLAB forum.
I solved the problem by renaming the driver file:
cd MATLAB_ROOT/sys/os/glnxa64/
sudo mv libstdc++.so.6 libstdc++.so.6.old

A: You can try following command to make a symbolic link.
ln -sf /usr/lib/x86_64-linux-gnu/libstdc++.so.6 /opt/MATLAB/XXXXX(R2014b)/sys/os/glnxa64/libstdc++.so.6

A: I solved the problem by renaming the driver file.
cd MATLAB/sys/os/glnxa64/
sudo mv libstdc++.so.6 libstdc++.so.6.old


text:
Q: Is contraction obligatory in negative interrogative sentences? I know that a verb and "not" are usually contracted when together in a negative interrogative sentence. Example:

Aren't they lovely?

Is it grammatically wrong to avoid the contraction? Example:

Are not they lovely?

A: It's not necessarily grammatically wrong, but the order you've presented is not idiomatic and would strike my ear as possibly archaic. The idiomatic version places the subject between the verb and the negation.

Aren't they lovely?  becomes
  Are they not lovely?

See a famous version of this from the movie Gladiator:

Are you not entertained? Is this not why you're here?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a fifo queue in SQS using boto3 Can anyone help me with creating a fifo queue in sqs using boto3. Tried this but this doesn't work
sqs.create_queue(QueueName='test', Attributes={'FifoQueue':'true'})

A: This is a complete working example of creating a FIFO queue on SQS:
import boto3
import pprint
import time

sqs = boto3.resource('sqs', region_name='us-west-2')

queue = \
    sqs.create_queue(QueueName='test.fifo', Attributes={'FifoQueue': 'true'})
pprint.pprint(queue)

A: Your queue name has to end in .fifo and you have to be using either us-west-2 or us-east-2 region as those are the only regions that currently support the FIFO feature.


text:
Q: Method invocation "setImageBtimap" I am getting this exception every time and I don't know at which point I am wrong.
Here is my Code:
package com.example.hp.hospiva;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

private boolean fileUri;
private int REQUEST_CAMERA;
private Bitmap bitmap;

public void clickPic (View view) {
    if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, 100);
    } else {
        Toast.makeText(getApplication(), "Camera not Supported!", Toast.LENGTH_LONG).show();
    }
}

protected void onActivityResult(int RC, int RQC, Intent I) {

    super.onActivityResult(RC, RQC, I);

    if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {

        Uri uri = I.getData();

        try {

            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

            ImageView imageview = null;
            imageview.setImageBitmap(bitmap);

        } catch (IOException e) {

            e.printStackTrace();
        }
   /* super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CAMERA) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        assert thumbnail != null;
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File destination = new File(Environment.getExternalStorageDirectory(),"temp.jpg");
        FileOutputStream fo;
        try {
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        new uploadFileToServerTask().execute(destination.getAbsolutePath());*/
        /*Uri selectedImage = data.getData();
        Bitmap photo = (Bitmap) data.getExtras().get("data");

        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        assert cursor != null;
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        photo = (Bitmap) data.getExtras().get("data");
        ImageView imageView = (ImageView) findViewById(R.id.Image);
        imageView.setImageBitmap(photo);*/
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

}
I am getting error at "setImageBitmap". What i want to do is to show image in imageview after capturing. It captures a picture and the picture goes to gallery direct and the imageview remains clear. Help me in identifying the mistake. Thanks

A: Please write this code inside your OnCreate.
Imageview imageview = (Imageview) findViewById(R.id.imageview);
imageview.setImageBitmap(bitmap);

A: You are setting bitmap on null ImageView Object first your need to initialize your ImageView inside the onCreate()
ImageView imageview;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageview=(ImageView) findViewById(R.id.imageview);
}

and Remove below line from onActivityResult
 ImageView imageview = null;


text:
Q: how can I access $formatters.push function validity in parent controller I have a directive called players which I use to decide how many players are at which position on a team. I have 4 of these, one for goal keeper, defence, mid-field and forward, so it might look something like this (the + and - are increment and decrement buttons):
- Forwards: 2 +
- Mid-Field: 4 +
- Defence: 4 +
- Goal Keeper: 1 +

I validate the increment to make sure it doesn't go over 11, but how can I access the maxPlayers validity in another class?
require: any = '^ngModel';
    restrict: string = 'A';

    link: ng.IDirectiveLinkFn = (scope: any,
        element: ng.IAugmentedJQuery,
        attributes: any,
        ngModel: ng.INgModelController) => {

        scope.getTotalPlayers = (): number => {
            return this.playerStateService.getTotalPlayers();
        };

        function customValidation(modelValue: number) {
            var totalPlayers: number = scope.getTotalPlayers();

            if (totalPlayers > 11) {
                ngModel.$render = () => {
                    ngModel.$setValidity('maxPlayers', false);
                };
            } else {
                ngModel.$setValidity('maxPlayers', true);
            }
            return modelValue;
        }
        ngModel.$parsers.push(customValidation);

A: What do you want to achieve? More specifically, why you function the number of players checking in outside of the directive?
I see two ways.

*

*Getting to the controller function. In controller write something like $scope.myForm.myModelController.$parsers[0].

*Create the controller or service the number of players check function. Then transfer this function to the directive. That is, to make the logic verification of the directive.

Examples:
First way.
function ExampleController($scope){
   var validityFunc = $scope.myForm.myModelController.$parsers[0];
}

Second way.
In controller:
function ExampleController($scope){
   $scope.validityFunc = function(){ return totalPlayers>11;};
}

In directive:
function customValidation(modelValue: number) {
        ngModel.$setValidity('maxPlayers', !scope.validityFunc());.
        return modelValue;
    }
ngModel.$parsers.push(customValidation);


text:
Q: Black and White background CSS I have a background image on the  block.
I want to make it black and white by using the webkit-filter: grayscale(100%);
But when I'm applying this filter to the body block, all the images on my site becomes black and white too. I want only my background to be black and white. How can I do it?

A: Insert an absolutely positioned div and apply the background to that.

....
other code here
....

#BG{
   position:fixed;
   left:0;
   right:0;
   top:0;
   bottom:0;
   background-image:(yourimage);
   webkit-filter: grayscale(100%);
   z-index:-500;
}

Fiddle: http://jsfiddle.net/m5d5w/6/
Don't forget to add filters for non-webkit browsers too. See:
Greyscale Background Css Images


text:
Q: Intelliji idea is very slow in debug mode and it is running perfectly in normal mode Intelliji idea is very slow in debug mode and it is running perfectly in normal mode.
I already tried by setting the below thing in /etc/hosts file
sudo nano /etc/hosts and add these two entries.
127.0.0.1 .local
::1 .local
But it did not work out for me.
Any help on this is highly regarded.

A: I have solved a similar problem by disabling breakpoints; it was remote debugging.
I did not make any performance measurements, but it looks like it is ok to have about 10 active breakpoints, but disastrous to have about 100 of them (I guess, the breakpoint list is sent over the network).
Idea lets you to group breakpoints and disable the whole groups.
Note that a click on the wrong mouse button clears your breakpoint instead of letting you edit its condition, so be careful!

A: clicked on "Mute Breakpoints" and started it and it started like as if starting in normal mode(means no any delay)

A: Remove breakpoints off your method and use them inside the method as that can cause your debug to take a very long time.
Try running IntelliJ as admin. I had this issue at work where debugging was extremely slow and running as admin actually made it a lot faster.
Method breakpoints may dramatically slow down debugging
There is a simple explanation from the IntelliJ Team: "Method breakpoints will slow down debugger a lot because of the JVM design, they are expensive to evaluate"
https://intellij-support.jetbrains.com/hc/en-us/articles/206544799-Java-slow-performance-or-hangups-when-starting-debugger-and-stepping

A: I had the similar issue. In my case it was method breakpoints. There was just one break point on a method. My spring boot app took around 20 mins to launch. When I removed the breakpoints it took 4 seconds to launch.
I also changed the debugger settings.

*

*Unchecked - Enable alternative view view for Collections classes

*Unchecked - Enable 'toString()' object view:

but these settings didn't make a difference.

A: If you disable this options in Build, Execution, Deployment -> Debugger -> Data Views --> Java, things will start work faster when debugging.

A: Make sure that you don't use "biz.paluch.logging.gelf.logback.GelfLogbackAppender" among your logs. In my case usage of such kind of appender was the cause of drastically slow starting in debug mode.

A: In my case I just had to disable the option: "Show method returns values"
Image of the option

A: I also faced same problem, after deleting all breakpoints it started working fine.

A: I faced similar problem with the Eclipse also and found the solution.
It is happening because your IntelliJ is using online Java and not using the same which is installed in your system.
You should set the java path to your system one in the IntelliJ configuration. Below link will help you for the same:
https://intellij-support.jetbrains.com/hc/en-us/articles/206544879-Selecting-the-JDK-version-the-IDE-will-run-under
Hope this will help you. :-)

A: Remove breakpoint from DAO interface and all work nice!

A: In my case, slowness is specific to REST calls. After testing all of the above proposed solutions, I finally find a way to remove these slowness issues by switching my JDK from JDK 11 to JDK 8.
Note: The same slowness appears in Visual Studio Code. This seems related to JDK 11 (OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.10+9, mixed mode) on macOS)

A: In my case i had more than 100 breakpoints active and this was the cause of this issue.
I clicked Ctrl + Alt + F8 and disabled all the breakpoints.
After that i enabled few new breakpoints i needed and all was ok.
It seems that having a lot of active breakpoints causes this issue.

A: Removing all Interface method breakpoints will fix the long spring boot startup Idea debug run.

A: In my case the problem was caused by the "Threads" view. When I remove this view it becomes fast again.
When I add the Threads view, I continuously see "Collecting data..." in the threads view, it flickers every 5s where the threads list shows for a moment then it goes back to "Collecting data...". When its like this, stepping through the code is painfully slow - takes about 10s for each step.

A: I cam across this post looking for a solution for my CLion (Rust). I removed all breakpoints, and it was enough to make the starting time on the debug mode too quick again.
Thanks to everyone who suggested that. This suggestion does not work only for Java, it also works for Rust/Clion


text:
Q: Django ForeignKey data grouping Django ForeignKey need to grouping
from django.db import models

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

    class Meta:
        ordering = ('headline',)

I want to list of all reporter with their all article showing the below format. How It possible?
-------------------------------
Reporter Name |  Total Article
-------------------------------
Reporter 1    |   3
-------------------------------
Reporter 2    |   4
-------------------------------

A: If you want to list all reporters you can use Reporter.objects.all() it will return you a queryset of all reporters, and for getting Articles of them use reverse relationship i.e -
reporter_object.article_set because you didn't define any related name. see this
I can give you an simple example how you can print All reporters with their Articles -
for reporter in Reporter.objects.all():
    print(reporter)
    for article in reporter.article_set.all():
        print(article)

when you defined a ForeignKey relationship, a one to many relationship is created between Reporter and Article, additionally one more attribute is added in Reporter, by default it is the name of your model with the suffix _set i.e article_set but when you specify the related_name then that will be same as your related_name, now you can easily call article by its related name with object of Reporter.
Still have any doubts comment it.


text:
Q: Can't to clone Github repo over HTTP but SSH is ok (Assuming this is reason why Vundle not working) I am able to clone any repo to my PC through SSH in cygwin(x-server) but it is not working with HTTPS.
When I try:
git clone https://github.com/gmarik/vundle.git ~/.vim/bundle/vundle

It stay in following forever and no error displayed.
$ git clone https://github.com/gmarik/vundle.git
Cloning into 'vundle'...

If I change HTTPS to SSH, it works.
The reason I worry about this is that I assume this is resaon why my Vundle not working.
I am using Vundle in my pc (whcih is working on my mac).
When I try BundleInstall or PluginInstall, it will stuck on plugins whatever is github repo and there is no error display. I think this situation is similar to when I try to clone repo.
Can anyone help me with this problem?
Thanks!!!!

A: One possibility is that you have a firewall "protecting" you from the dangers of GitHub.  By default, SSH uses Port 22 and HTTPS uses Port 403.  I am not sure what utilities are included in cygwin, but you can test this by connecting to Port 22
$ ssh -T git@github.com
$ telnet github.com 22

and Port 403
$ wget https://...
$ curl https://...
$ telnet github.com 403

I tend to have the opposite problem:  some of the servers I use allow outgoing connections on 403 but block 22.


text:
Q: Example of wx.FindWindowByName() Could you tell me how FindWindowByName works? I couldn't find any example implementing it.
I need to identify and open an open frame to append messages to it.I could only find syntax and am having trouble understanding it.Throws unbound method error.I know that this error pops up when a method is called using a wrong object.But I cannot call this method using a wx.Window object as that is what am trying to obtain in the first place....

A: The main requirement is setting the name of the window, either when it is created by passing name="foo" to its __init__ or by using the SetName("foo") method.  Then you can use wx.FindWindowByName to fetch that window later:
>>> import wx
>>> frm = wx.Frame(None, title='FooBar', name='foobar')
>>> frm.Show()
True
>>>
>>> f = wx.FindWindowByName('busted')
>>> print f
None
>>> f = wx.FindWindowByName('foobar')
>>> print f
<wx._windows.Frame; proxy of <Swig Object of type 'wxFrame *' at 0x1003cdf30> >
>>> print frm
<wx._windows.Frame; proxy of <Swig Object of type 'wxFrame *' at 0x1003cdf30> >
>>>
>>> f == frm
True
>>> f is frm
True
>>>

In addition to the the global function used above, there is a static method named FindWindowByName in the wx.Window class that does the same thing, and in earlier versions of wxPython there was a non-static method that only searched the children of the window.  So that is probably where the confusion you experienced comes from.  Using the global function as shown above should be safe to use in all versions of wxPython however, and if you need to restrict your search to a specific subtree of the containment hierarchy then you can pass the parent window as a second parameter.


text:
Q: Today Date + Link I want to make a link depend on current date.
Here is my Javascript:

Above Javascript will show, example: 1124 (month/day)
I want to make this link follow the current day:
http://example.com/JS-RESULT

Today date is 24 11 2014 so the url will be like this
Today Budget

How can I make this work?
p.s: i love jquery.

A: I am a little confused about your question, hopefully you are looking for one of the things below:
How to form the URL to example.com/1124?
Perform a simple string + string in javascript.

How "my manager just click the link and get into the current day" works?
Given that you have "one year list of links which have daily budgets", put all those webpages in the same folder as your current page which has Today Budget; or create a new folder called budgets for those daily budgets and change the url to http://example.com/budgets/1124.
My answer is very basic and I'm not sure if I got you correctly, let me know.

A: JQuery Solution:
$(function(){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 1
    var day = currentTime.getDate();

    $("#content").append("Today Budget");
});

JSFiddle: http://jsfiddle.net/ehLku1oq/


text:
Q: Add GeoJSON features from an API call in OpenLayers 4, layer not displayed I'm trying to create a little demo to show the data from our API into a map but I cannot see my layer
Here my code, is just basic for the moment, we just need to display the data:
const projection = new ol.proj.Projection({
  code: 'EPSG:27700',
  getPointResolution: (r) => {
    return r
  },
  units: 'm'
})

var view = new ol.View({
  projection: projection,
  center: [383000, 398000],
  extent: [0, 0, 700000, 1250000],
  resolution: 28,
  resolutions: [140, 70, 28, 14, 7, 2.8, 1.4, 0.7],
})

var maplayer = new ol.layer.Tile({
  extent: [0, 0, 700000, 1250000],
  preload: Infinity,
  source: new ol.source.TileWMS({
    url: 'https://www.buchananmapping.co.uk/mapcache/?',
    params: {
      'LAYERS': 'bccache2',
      'TILED': true
    },
    ratio: 1,
    projection: 'EPSG:27700',
    tileGrid: new ol.tilegrid.TileGrid({
      resolutions: [140, 70, 28, 14, 7, 2.8, 1.4, 0.7],
      extent: [0, 0, 700000, 1250000],
      tileSize: [128, 128]
    })
  })
})

var appSource = new ol.source.Vector({
  projection: 'EPSG:27700',
  format: new ol.format.GeoJSON()
})

var appLayer = new ol.layer.Vector({
  source: appSource,
  style: new ol.style.Style({
    fill: new ol.style.Fill({
      color: 'rgba(255, 255, 255, 0.1)'
    }),
    stroke: new ol.style.Stroke({
      color: 'rgb(85, 172, 238)',
      width: 2
    })
  })
})

var map = new ol.Map({
  target: 'map',
  layers: [
    appLayer,
    maplayer
  ],
  view: view
})

  $.ajax({
    type: 'GET',
    url: 'https://www.traffwebdev.uk/tro/v1/restrictions?epsg=&x=383666+&y=398197&area=&radius=500&output=',
    dataType: 'json',
    success: function (data) {
      // reads and converts GeoJSon to Feature Object
      var features = (new ol.format.GeoJSON()).readFeatures(data.geometry)
      appSource.addFeatures(features)
    }
  })

Both my map and GeoJSON use EPSG:27700 but I cannot see any features in the map, I can see that the call to the API is made.
Sorry I don't have a demo but if you copy the whole code is working, there is no other code a part from that.

A: If you take a look at actual GeoJSON data, you'll see that it's coded in EPSG:4326, so reading features statement should be:
var features = (new ol.format.GeoJSON()).readFeatures(data.geometry, {dataProjection: 'EPSG:4326', featureProjection: 'EPSG:27700'});

You'll also have to change order of layers in map declaration, otherwise features will be covered by base map:
var map = new ol.Map({
  target: 'map',
  layers: [
    maplayer,
    appLayer
  ],
  view: view
});


text:
Q: Twilio on Call-Connect or Hangup get call details I am using ASP.NET MVC Web calling with Twilio
Here is my Connect function
function callCustomer(phoneNumber) {
    updateCallStatus("Calling " + phoneNumber + "...");
    phoneNumber = phoneNumber.replace(/ /g, '');
    var params = { To: phoneNumber };
    Twilio.Device.connect(params);
}

Here is my Hangup function
function hangUp() {
    Twilio.Device.disconnectAll();
}

Here is my TwiML Bin
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Dial callerId="++516xxx9999" record="record-from-answer">{{To}}</Dial>
</Response>

I am using Twilio client v1.6
//media.twiliocdn.com/sdk/js/client/v1.6/twilio.min.js

I want to collect complete information of each call as I connect to call or as I hang up the call like Call Duration, Call Sid, Record Sid, Call To, and other. Then with that information I would like implement play recorded call in my application.
I believe one way of doing it is set CALL STATUS CHANGES under Voice & Fax and receive all params.

A: This is how I ended up handling it.
/* Callback for when a call ends */
Twilio.Device.disconnect(function (connection) {
    console.log(connection);
    // Disable the hangup button and enable the call buttons
    hangUpButton.prop("disabled", true);
    callCustomerButtons.prop("disabled", false);
    callSupportButton.prop("disabled", false);

    updateCallStatus("Ready");
    addCallLog(connection.parameters.CallSid);
});

addCallLog function
function addCallLog(id) {
    var type = "";
    var entityId = Number($("#Id").val());
    $.ajax({
        url: "/Phone/AddCallLog?callId=" + id,
        type: "POST",
     contentType: "application/json;",
        success: function (data) {
            // Handle Success Event
        },
        error: function (data) {
           // Handle Error Event
        }
    });
}

Controller Method
[HttpPost]
        public ActionResult AddCallLog(string callId,string type,int entityId)
        {
            TwilioClient.Init(_callSetting.Twilio.AccountSid, _callSetting.Twilio.Authtoken);

            var records = CallResource.Read(parentCallSid: callId).ToList();
            if (records.Any())
            {

                var callResource= records[0];
                var parentRecord = CallResource.Fetch(pathSid: callId);
                if (callResource.Status.ToString().Equals("completed", StringComparison.OrdinalIgnoreCase))
                {
                    CallRecord callRecord = new CallRecord
                    {
                        EntityKey = entityId,
                        EntityType = type,
                        CallDateTimeUtc = callResource.DateCreated ?? DateTime.UtcNow,
                        CallSId = callResource.Sid,
                        ParentCallSId = callResource.ParentCallSid,
                        CalledById = _operatingUser.Id,
                        DurationInSeconds = parentRecord==null? Convert.ToDouble(callResource.Duration): Convert.ToDouble(parentRecord.Duration),
                        ToPhone = callResource.To,
                        CompanyId = _operatingUser.CompanyId
                    };
                     var callRecordResult=   _callRecordService.Add(callRecord);
                    var recording = RecordingResource.Read(callSid: callId).ToList();
                    if (!recording.Any()) return Json(true);
                    foreach (RecordingResource recordingResource in recording)
                    {
                        using (var client = new WebClient())
                        {
                            var url =
                                "https://api.twilio.com" + recordingResource.Uri.Replace(".json", ".mp3");
                            var content = client.DownloadData(url);

                            CallRecordMedia callRecordMedia = new CallRecordMedia
                            {
                                CallRecordId = callRecordResult.Id,
                                ContentType = "audio/mpeg",
                                RecordingSId = recordingResource.Sid,
                                RecordingCallSId = recordingResource.CallSid,
                                FileType = "mp3",
                                Data = content,
                                Price = Convert.ToDouble(recordingResource.Price),
                                PriceUnit = recordingResource.PriceUnit,
                                DurationInSeconds = Convert.ToDouble(recordingResource.Duration)
                            };
                            _callRecordService.AddCallRecording(callRecordMedia);
                        }
                    }
                }
            }
           return Json(true);
        }


text:
Q: Adding API to Kong failed My docker-compose.yml
version: '2.1'

volumes:
    kong_data: {}

networks:
  kong-net:
services:
  kong-migrations:
    image: "${KONG_DOCKER_TAG:-kong:latest}"
    command: kong migrations bootstrap
    depends_on:
      db:
        condition: service_healthy
    environment:
      KONG_DATABASE: postgres
      KONG_PG_DATABASE: ${KONG_PG_DATABASE:-kong}
      KONG_PG_HOST: db
      KONG_PG_PASSWORD: ${KONG_PG_PASSWORD:-kong}
      KONG_PG_USER: ${KONG_PG_USER:-kong}
    links:
      - db:db
    networks:
      - kong-net
    restart: on-failure
  kong:
    image: "${KONG_DOCKER_TAG:-kong:latest}"
    user: "${KONG_USER:-root}"
    depends_on:
      db:
        condition: service_healthy
    environment:
      KONG_ADMIN_ACCESS_LOG: /dev/stdout
      KONG_ADMIN_ERROR_LOG: /dev/stderr
      KONG_ADMIN_LISTEN: '0.0.0.0:8001'
      KONG_CASSANDRA_CONTACT_POINTS: db
      KONG_DATABASE: postgres
      KONG_PG_DATABASE: ${KONG_PG_DATABASE:-kong}
      KONG_PG_HOST: db
      KONG_PG_PASSWORD: ${KONG_PG_PASSWORD:-kong}
      KONG_PG_USER: ${KONG_PG_USER:-kong}
      KONG_PROXY_ACCESS_LOG: /dev/stdout
      KONG_PROXY_ERROR_LOG: /dev/stderr
    networks:
      - kong-net
    ports:
      - "8000:8000/tcp"
      - "8001:8001/tcp"
      - "8443:8443/tcp"
      - "8444:8444/tcp"
    restart: on-failure
  db:
    image: postgres:9.5
    environment:
      POSTGRES_DB: ${KONG_PG_DATABASE:-kong}
      POSTGRES_PASSWORD: ${KONG_PG_PASSWORD:-kong}
      POSTGRES_USER: ${KONG_PG_USER:-kong}
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "${KONG_PG_USER:-kong}"]
      interval: 30s
      timeout: 30s
      retries: 3
    restart: on-failure
    stdin_open: true
    tty: true
    networks:
      - kong-net
    volumes:
      - kong_data:/var/lib/postgresql/data
  go-server:
    image: gobuild
    networks:
      - kong-net
    restart: on-failure

My docker containers
docker ps --format '{{.Names}}'
chapter11_go-server_1
chapter11_kong_1
chapter11_db_1

I am trying to make POST request to the Kong admin
API, which runs on port 8001. But it fails.
{
"name": "myapi",
"hosts": "server1",
"": "http://chapter11_go-server_1:3000",
"uris":["/api/v1"],
"strip_uri": true,
"preserve_host": false
}

Output
kong_1             | 172.21.0.1 - - [29/Apr/2019:10:36:58 +0000] "POST /apis HTTP/1.1" 404 23 "-" "PostmanRuntime/7.6.0"
kong_1             | 172.21.0.1 - - [29/Apr/2019:10:47:30 +0000] "POST /apis HTTP/1.1" 404 23 "-" "PostmanRuntime/7.6.0"

How to find out if what is wrong with my POST request?
What is upstream_url?

A: According to Kong 1.0.0 changelog:

The API entity and related concepts such as the /apis endpoint, are removed (deprecated since 0.13.0, March 2018). Use Routes and Services instead.

Since Kong 1.0 /apis endpoint is no longer available. Because of that you got 404 Not found response.
To add your API to Kong you have to use /services and /routes. This tutorial explains how to do it: Configuring a Service


text:
Q: Best practice for converting an object to string I've seen a number of ways of converting an Object to a String in .NET, typically for displaying the object's value to the user when the object type is not known.
These include:
Dim x as Object = 3
Dim y as Object = Nothing
Dim z as Object = DBNull.Value
Dim l_displayString As String

l_displayString = "" & x & "" & y & "" & z
l_displayString = If(x, "").ToString() & If(y, "").ToString() & If(z, "").ToString()
l_displayString = Convert.ToString(x) & Convert.ToString(y) & Convert.ToString(z)

Is there a method which is recommended by Microsoft, or do these all compile down to the same byte code?
EDIT:
Let me expand the question a little to include:
What are the differences between these methods? I can't see what's going on under the hood, so it'd be nice to know if there is any performance benefit of one over the others. In some cases, these calls may be made several thousand times (such as reading from a large table) and shaving off a couple seconds can make a big UX impact.

A: The  Convert.ToString(x) works gracefully even if x is null. In general, when dealing with stuff coming from database, I think Convert is the best approach. Another suggestion, when working with float/decimal numbers, keep an eye to the CultureInfo, ie don't trust the . as decimal sign, if you want to assume that use CultureInfo.InvariantCulture.

A: They do different things.  They compile to different MSIL code, but in most cases they will probably have the same result.
ToString is a method defined by Object, which is the inherent base type for all objects.  By default it returns the object's type name, but it can (and often is) overridden by each type so that it returns a more meaningful string.  For instance, in your example, x is an Int32 object, and Int32 overrides ToString so it returns "3" instead of the default "System.Int32".
I'm not positive, but I suspect when you do the concatenation "" & x, it is casting x to a String, in which case it is a shortcut to typing "" & CType(x, String) or "" & CStr(x).  Each type can overload the casting operator, so it assumes that the type (in this case Int32) has overloaded the operator and can therefore be cast to a string.  Indeed it has and can.
Convert.ToString does different things depending on which overload you call.  If you pass it an Int32, it just calls the object's ToString() method.  However, if you pass it an Object, for instance, it first checks to see if the object implements IConvertible or IFormattable.  If it does, it uses one of those, otherwise it uses the ToString method.  So, it tries, depending on the type of object you send it, to determine what it thinks it the most likely best way to get that type to a string.
As far as what is the preferred method, I would say x.ToString() is what you want to use most all of the time, unless you have some other concern (which all depends on what you are doing with the object).

A: I decided to test the performance of each method using a collection of 1,000,000 objects. The objects were one of: an integer, a class, Nothing or DBNull.Value. The same collection was used for each test, and I tested each method 50 times.
"" & x
This actually doesn't work for all objects. It works for DBNull.Value and Nothing, but trying to use this method with just any ol' object will cause an InvalidCastException. Interestingly, CStr(DBNull.Value) throws an InvalidCastException, so I'm not sure why it works.
Results with custom object: N/A
Results w/o custom object: avg 126.7 ms, median 126 ms
If(x, "").ToString()
Results with custom object: avg 140.46 ms, median 138 ms
Results w/o custom object: avg 69.32 ms, median 69 ms
Convert.ToString()
Results with custom object: avg 171.54 ms, median 171 ms
Results w/o custom object: avg 112.14 ms, median 112 ms
So it would seem that If(x, "").ToString() is a bit faster for a very large set of records, but that would need to be balanced with Convert.ToString()'s more powerful conversion options. Thanks for the answers.
Here's the code I used for testing:
Option Strict Off

Module Module1

    Sub Main()
        Dim l_objectArray = Enumerable.Range(0, 1000000).Select(Function(x) GetObject(x)).ToArray()

        Dim l_stopWatch As New Stopwatch()
        Dim l_testResults As New List(Of Long)
        Dim l_testIterations As Integer = 50
        Dim l_displayValue As String

        Do

            ' --------------------

            'Console.WriteLine()
            'Console.WriteLine("Conversion using string concatenation")
            'l_testResults.Clear()

            'For iteration = 0 To l_testIterations - 1
            '    l_stopWatch.Start()
            '    For Each o In l_objectArray
            '        l_displayValue = "" & o
            '    Next
            '    l_stopWatch.Stop()
            '    l_testResults.Add(l_stopWatch.ElapsedMilliseconds)
            '    l_stopWatch.Reset()
            'Next

            'Console.WriteLine()
            'Console.WriteLine("Average: " & l_testResults.Average())
            'Console.WriteLine("Median: " & GetMedian(l_testResults.ToArray()))

            ' --------------------

            Console.WriteLine()
            Console.WriteLine("Conversion using Object.ToString()")
            l_testResults.Clear()

            For iteration = 0 To l_testIterations - 1
                l_stopWatch.Start()
                For Each o In l_objectArray
                    l_displayValue = If(o, "").ToString()
                Next
                l_stopWatch.Stop()
                l_testResults.Add(l_stopWatch.ElapsedMilliseconds)
                l_stopWatch.Reset()
            Next

            Console.WriteLine()
            Console.WriteLine("Average: " & l_testResults.Average())
            Console.WriteLine("Median: " & GetMedian(l_testResults.ToArray()))

            ' --------------------

            Console.WriteLine()
            Console.WriteLine("Conversion using Convert.ToString(x)")
            l_testResults.Clear()

            For iteration = 0 To l_testIterations - 1
                l_stopWatch.Start()
                For Each o In l_objectArray
                    l_displayValue = Convert.ToString(o)
                Next
                l_stopWatch.Stop()
                l_testResults.Add(l_stopWatch.ElapsedMilliseconds)
                l_stopWatch.Reset()
            Next

            Console.WriteLine()
            Console.WriteLine("Average: " & l_testResults.Average())
            Console.WriteLine("Median: " & GetMedian(l_testResults.ToArray()))

            ' --------------------

            Console.WriteLine()
            Console.Write("Exit? (y/n): ")
            Dim l_key = Console.ReadKey(False)
            If l_key.Key = ConsoleKey.Y Then
                Exit Sub
            End If

        Loop

    End Sub

    Private Function GetMedian(ByVal values As Long()) As Long
        Array.Sort(values)
        If values.Length Mod 2 = 0 Then
            Return (values(values.Length / 2) + values(values.Length / 2 - 1)) / 2
        Else
            Return values(CInt(Math.Floor(values.Length / 2)))
        End If
    End Function

    Private Function GetObject(ByVal someNumber As Integer) As Object
        Select Case someNumber Mod 4
            Case 0
                Return someNumber
            Case 1
                Return New SomeClass(someNumber)
                'Return Nothing
            Case 2
                Return DBNull.Value
            Case Else
                Return Nothing
        End Select
    End Function

    Private Class SomeClass

        Private _seed As Integer

        Public Sub New(ByVal seed As Integer)
            _seed = seed
        End Sub

        Public Overrides Function ToString() As String
            Return _seed.ToString()
        End Function

    End Class

End Module


text:
Q: Create a group by and display a sequence number? I'm trying to understand if it is possible to create an SQL query that can satisfy the following requirement. Turn this table:

Into this:

The trick or challenge is to obtain the order of the cycle using the chronological order of the event type timestamp. I have tried different combination of ORDER BY with COUNT (*) but I haven't had any success. Can it be achieved using SQL? Any help that can lead me to the right path is welcome.

A: I notice that you are starting over based on the first six characters of event_type.  So, you need partition by:
select t.*
       row_number() over (partition by left(event_type, 6) order by timestamp) as cycle_id
from t;

EDIT:
If your numbering is based on the month:
select t.*
       row_number() over (partition by year(timestamp), month(timestamp) order by timestamp) as cycle_id
from t;

A: For the sample data that you posted I think that the grouping you want is for the part of the column EventType before the underscore:
select
  *,
  row_number() over (
    partition by left([Event Type], charindex('_', [Event Type]) - 1)
    order by [TimeStamp])
  ) [Cycle Id]
from tablename


text:
Q: Why in SAS does a numeric literal in scientific notation give a different number to the number written out explicitly? The following SAS code:
data _null_;
  format t u best32.;
  t = 10000000000000000000000000;
  u = 1e25;
  put t u;
  if t ne u then put 'diff';
run;

on my Windows machine prints out:
10000000000000000905969664 9999999999999998758486016
diff

While I understand that only the first 15-16 digits are to be trusted, why do they give different underlying numbers at all? How is SAS computing 1e25?
Edit: I've been asked to give the output for other powers of 10 up to 1e25. The following program:

%macro doit;
data _null_;
  format t u best32.;
%let t=1;
%do i=1 %to 25;
  %let t=&t.0;
  t = &t;
  u = 1e&i;
  put t u;
%end;
run;
%mend;
%doit;

gives the following output:

10 10
100 100
1000 1000
10000 10000
100000 100000
1000000 1000000
10000000 10000000
100000000 100000000
1000000000 1000000000
10000000000 10000000000
100000000000 100000000000
1000000000000 1000000000000
10000000000000 10000000000000
100000000000000 100000000000000
1000000000000000 1000000000000000
10000000000000000 10000000000000000
100000000000000000 100000000000000000
1000000000000000000 1000000000000000000
10000000000000000000 10000000000000000000
100000000000000000000 100000000000000000000
1000000000000000000000 1000000000000000000000
10000000000000000000000 10000000000000000000000
99999999999999991611392 99999999999999991611392
999999999999999983222784 999999999999999983222784
10000000000000000905969664 9999999999999998758486016

A: It looks like it might actually be calculating 1 * 10 * 10 ... * 10 and the errors are creeping in as soon as you get beyond the significant number of bits for the underlying float type.
But I don't believe that would happen for an IEE754 type float/double since it's quite able to represent 1x10full-range without loss of precision.
One possibility is that the problem you are having is related to the ability to store floats with less precision than allowed (which could possibly screw up a 1e25 calculation) - see http://www.uc.edu/sashtml/lrcon/z0695157.htm#z0695187 for an explanation.
Update 1:
Okay, so based on your comment, you're not restricting the length. What does the following code give you?
t = 10;
u = 1e1;
put t u;
t = 100;
u = 1e2;
put t u;
t = 1000;
u = 1e3;
put t u;
: : :
t = 10000000000000000000000000;
u = 1e25;
put t u;

Based on that output, we can probably deduce what's going on under the covers.


text:
Q: Wireless Access Point Without Physically Connecting DD-WRT Routers I have two routers running DD-WRT. The main one is connected to the modem which is on the second floor, and I would like to boost my wifi strength so my entire house is covered with wifi. I would like to place my second router on the first floor and turn it into a wireless access point.
I have been looking at tutorials and all of them require both routers to be physically connected via a network cable. Is there a way for the routers to not be connected via a network cable and instead be connected via wifi signal?
In addition, I would like the computers that connect to the second router to also be able to see my homegroup.

A: DD-WRT supports a number of router linking modes, including the repeater bridge mode:

New in DD-WRT v24 is Repeater Bridge mode. This extends your primary LAN via secondary router (bridge router) and also allows wireless clients to connect to your secondary router. This extends the range of your wireless network while simultaneously allowing wired clients to connect to your secondary router.

Note that recent version of DD-WRT is required. Moreover, the wireless bandwidth on your secondary router will be essentially halved (since all wireless traffic will have to be re-broadcast again, wirelessly. Also, it appears that both routers will be on the same channel, which is sub-optimal.
In conclusion, it can be done, but if you can run the network cable to the secondary router, your network will have better bandwidth and be more stable.


text:
Q: How to write to SHPR2 correctly on cortex M0 What is wrong with this code?
When I debug it in DAVE4 with XMC1100 Boot Kit the SHPR2 register not changing in the debugger. The code is based on EasyMain (LED blinking is working for example with a modified main).
I have studied the DDI0419C_arm_architecture_v6m_reference_manual I think it should work.
#include "XMC1100.h"

int main(void)
{
 unsigned int a;

 a = 0x0B << PPB_SHPR2_PRI_11_Pos;
 PPB->SHPR2 |= a;

 while(1);
}

A: CMSIS functions should be used.


text:
Q: What's the difference between these 2 SQL Server XQuery queries? We have a column in a table that contains xml and is setup as a non-schema based xml column
The data can contain multiples instance of a node that looks like this:
<eq:Fund>
  <v:FundCode>
    <v:type>SEDOL</v:type>
    <v:value>3049141</v:value>
  </v:FundCode>
</eq:Fund>
<eq:Fund>
  <v:FundCode>
    <v:type>Product Provider Specific</v:type>
    <v:value>CASH</v:value>
  </v:FundCode>
</eq:Fund>

This query returns 448 rows:
 WITH XMLNAMESPACES ('http://schema1' as eq, 'http://schema2' as v, DEFAULT 'http://schema3')
select * from xml_request
WHERE xml_request_body.value('contains( string( (//v:type)[1] ),"SEDOL")','bit') = 1

This query returns 784 rows (after removing blanks in the result column)
    WITH XMLNAMESPACES ('http://schema1' as eq, 'http://schema2' as v, DEFAULT 'http://schema3')
select xml_request.xml_request_ser, xml_request.agency_number, xml_request.policy_holder, xml_request.product,
xml_request_body.query('for $x in /eq:EQuote/eq:Request/eq:Fund where $x/v:FundCode/v:type = "SEDOL" return $x') as result
from xml_request

1) Why do they return different number of rows? The first query doesn't find all the rows where the element contains SEDOL? Why not?
I'm guessing it may be due to the fact that the element with SEDOL may not be the first? 2) How do I change the first query to look through all elements not just the first?

A: The [1] in the first means that it explicitly requires the first type element (in document order) to contain SEDOL, in order for a match to be made. So yes, if as you say some rows have a non-SEDOL FundCode first, they won't match.
What you want to do it the first way is
WHERE xml_request_body.exist('//v:type[contains(., "SEDOL")]') = 1

This looks for any v:type element such that the text contains SEDOL.


text:
Q: Runtime error "BadImageFormatException: Cannot load file or assembly for execution. Reference assemblies should not be loaded"" I have a C# Winforms desktop project targeting .NetFramework 4.8 which I run with VS 2022. The project builds and runs OK within VS 2022. The project has a number of Nuget packages loaded by with PackageReference rather than Packages.config. The project runs OK in VS 2022 and if I click on the .exe file in Debug/bin using the account in which VS2022 runs. If I create an installer project to create an msi file using the primary output of the main project,and click on the msi file from another account on the same machine, the installation runs OK and the application starts when I click on the executable but throws the error "BadImageFormatException: Cannot load file or assembly for execution. Reference assemblies should not be loaded for execution" when accessing one of the Nuget references added as PackageReference. Looking at the Detected dependencies for the install project, the Nuget components loaded as PackageReference have the same icon ( a small and a larger square connected by a horizontal line) as other components (such as System.Drawing) but for the main project the icons are different ( a blue rounded square containing 2 white disks).
Is there some property of the items listed in Detected Dependencies of the install project which stops the item from being loaded? I have tried changing PackageAs from vsdpaDefault to vsdpaLoose but this does not fix the problem.


text:
Q: ios stringWithContentsOfURL with encoding? I have a problem using "stringWithContentsOfURL" to get source page of a web(chinese)
Thinking using "NSUTF8StringEncoding" but didn't work(got null for result). My code looks like this
NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.morningstar.com.tw/download_pdf_2-1.aspx"] encoding:NSUTF8StringEncoding error:nil];
NSLog(@"html = %@",string);
replaced "NSUTF8StringEncoding" by "NSASCIIStringEncoding", did get a result but words are scrambled.
Thanks for the help!

A: You need a different encoding:
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingDOSChineseTrad);

You can also use kCFStringEncodingDOSChineseSimplif for simplified chinese. Use encoding in place of NSASCIIStringEncoding or the other standard ones.
See the documentation for more encodings if these do not work properly.


text:
Q: Position text next to rectangle in TikZ Consider the following TikZ code:
\filldraw[fill=black!40!white,thick] (0,1.5) node[above left] {start} rectangle (3.2,2) node[below right] {end} node [midway] {cp} ;

It produces a rectangle at the required co-ordinates, with text cp inside the rectangle. I require text labels to the left and the right of the rectangle. I have attempted to produce these with the text attached to the above left and below right nodes. However, the end label is positioned slightly lower than the start label. How can I fix this, or, is there a better/easier way to position text next to rectangles. I have looked through the tutorials in the first section of the 700+ TikZ manual.
Edit: Additional information in response to percusses's answer below:
\filldraw[fill=black!40!white,thick] (0,2.5) rectangle (3.2, 3) node [midway] {cp} ;
\node[fill=black!40!white,thick,draw,minimum height=0.5cm,minimum width=3.2cm,label=0:end,label=west:start] at (0,1.5) {cp};

Note the different x positions. Your code (the second line above) places the entire structure such that start is positioned at position 0. For some reason, the structure produced by my code is shifted to the right so that it starts in the middle of the rectangle relative to yours.

A: The manual is indeed long but it's very well structured so you can skip many irrelevant parts. For this specific example, you can use a node and put labels around it.
\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\node[fill=black!40!white,
      thick,
      draw,
      minimum height=0.5cm,
      minimum width=3.2cm,
      label=0:end,%< -- This uses angle zero degree on the border for the location
      label=west:start %< -- This uses an anchor of the node for the location
] at (0,1.5) {cp};
\end{tikzpicture}
\end{document}


text:
Q: How can supervisord restart the npm start command successfully? I've started the "node start" via supervisord.
My problem is
Stopping / rebooting at supervisord will cause the node app.js process to remain without being killed
How can supervisord restart the npm start command successfully in this case?
supervisord.conf
[supervisord]
nodaemon=true

[program:node]
command=npm start
directory=/xx
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
user=root
autostart=true
autorestart=true
redirect_stderr=true
exitcodes=1

package.json
{
  "name": "xx",
  "version": "1.0.0",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "xxx
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  },
  "description": ""
}

A: This worked for me: change npm start to node app.js inside the Supervisor config file.
Why?
I've noticed that using npm start starts two processes:
$ ps aux | grep node
ubuntu   19363  0.0  0.0   4508   708 ?        S    17:43   0:00 sh -c node index.js
ubuntu   19364  1.3  5.2 1041288 52996 ?       Sl   17:43   0:00 node index.js

And stopping it in Supervisor only stops the parent process:
$ sudo supervisorctl stop all
my_worker: stopped
$ ps aux | grep node
ubuntu   19364  0.3  5.2 1041288 52996 ?       Sl   17:43   0:00 node index.js

So putting node index.js directly in the supervisor config solved the problem for me.


text:
Q: System of Delay Differential Equation In my differential equations course we are looking at systems of DDEs and I was wondering if there is a particular method that is used to solve these types of systems? One example that was given in class is the following;
$$\begin{align}v_1^\prime(t)&=\phi(t)v_1(t)\\  v_2^\prime(t)&=\alpha(v_1(t-1)-v_2(t-1)) \end{align}$$
Where $\alpha\in\mathbb{R}$ and $\phi(t)$ is some quasi-periodic function. Does an analytical solution exist? Or should I relay on numerical solutions as I have got here

Where x1 and x2 are v1 and v2 respectively, solutions to the above equation with $\phi(t)=1+2(t+\omega) (mod\ 1)$ for $w$ random.

A: From the first ODE we have
$$
v_1(t) = C_0 e^{\int_0^t \phi(\tau)d\tau}
$$
and the second after substitution
$$
v_2'(t) + \alpha v_2(t-1) = C_0 e^{\int_0^{t-1}\phi(\tau)d\tau}
$$
to solve this ODE you can use many numerical methods and also when $\phi(t)$ is a linear function like $b t$, the Laplace transform can provide algebraically suitable methods to make parametric considerations, as follows
$$
\alpha  \left(e^{-s} \left(\mathcal{L}_t[v_2(t)](s)\right)+e^{-s} \int_{-1}^0 e^{-s t} v_2(t) \, dt\right)+s \left(\mathcal{L}_t[v_2(t)](s)\right)-\frac{\sqrt{\pi
   } C_0 e^{\frac{(c-s)^2}{4 b}} \left(\text{erf}\left(\frac{c-s}{2 \sqrt{b}}\right)+1\right)}{2 \sqrt{b}}-v_2(0)=0
$$
or calling $V_2(s) = \mathcal{L}_t[v_2(t)](s)$
$$
V_2(s) = \frac{\sqrt{\pi } C_0 e^{\frac{(c-s)^2}{4 b}+s} \left(\text{erf}\left(\frac{c-s}{2 \sqrt{b}}\right)+1\right)-2 \sqrt{b} \left(\alpha  \int_{-1}^0
   e^{-s t} v_2(t) \, dt-e^s v_2(0)\right)}{2 \sqrt{b} \left(\alpha +e^s s\right)}
$$
now making some assumptions like $v_2(t) = 0$ for $-1\le t\le 0$ and using for $e^s$ the Padé expansion we can proceed making stability considerations involving $\{\alpha, b, c\}$ as
$$
V_2(s) = \frac{\sqrt{\pi } C_0e^{\frac{(c-s)^2}{4 b}+s} \left(\text{erf}\left(\frac{c-s}{2 \sqrt{b}}\right)+1\right)}{2 \sqrt{b} \left(\alpha +e^s s\right)}
$$


text:
Q: Iphone application store url in application My iPhone application does some processing on a server, and I save the url in a core data database so that every time the application is run I can read the url value from the database.
My issue is: if this url value changes, my application will stop working.  How can I get the url value dynamically without storing it in a database so that if url is changed, my application will continue working?

A: You could get get it from any server, open a NSURLConnection class reference and read the response. So basically at the beginning your app would always check with the server to make sure it has the latest URL.


text:
Q: What is the Elasticsearch-py equivalent to alias actions? I am trying to implement multiples indices approach using elasticsearch-dsl. There are basically two steps:
1. Create aliases:
PUT /tweets_1/_alias/tweets_search
PUT /tweets_1/_alias/tweets_index

2. Change alias when necessary:
POST /_aliases
{
  "actions": [
    { "add":    { "index": "tweets_2", "alias": "tweets_search" }},
    { "remove": { "index": "tweets_1", "alias": "tweets_index"  }},
    { "add":    { "index": "tweets_2", "alias": "tweets_index"  }}
  ]
}

I could only implement the step 1 using elasticsearch-py (not the dsl):
from elasticsearch.client import IndicesClient
IndicesClient(client).("tweets_1", "tweets_search")
IndicesClient(client).("tweets_1", "tweets_index")

I have no clue how to do that for step 2. So, what would be the equivalent in elasticsearch-dsl (or at least in elasticsearch-py)?

A: To implement that you need to use elasticsearch-py:
from elasticsearch import Elasticsearch
es = Elasticsearch()

# use es.indices instead of instantiating IndicesClient
es.indices.put_alias(index='tweets_1', name='tweets_search')
es.indices.put_alias(index='tweets_1', name='tweets_index')

es.indices.update_aliases({
  "actions": [
    { "add":    { "index": "tweets_2", "alias": "tweets_search" }},
    { "remove": { "index": "tweets_1", "alias": "tweets_index"  }},
    { "add":    { "index": "tweets_2", "alias": "tweets_index"  }}
  ]
})

A: index_list_for_realias = [...]
aliases_list_to_realias = [...]

for i in index_list_for_realias:
    print(i)
    for j in aliases_list_to_realias:
        es.indices.put_alias(index=i, name="logstash5-uni-" + j, body={
                "filter": {
                    "term": {
                        "uni": j
                    }
                }
            }
        )


text:
Q: Audio watermarking open source projects Are you aware of any open source libraries/projects that offer audio watermarking capability?

A: check wikipedia: http://en.wikipedia.org/wiki/Steganography#Implementations
section 3 of this site site is on audio:  http://www.binary-universe.net/
same author did a project on codeplex.
these also do audio:
  StegHide
mpeStego

A: We made a C++ watermarking library as a student project.
It implements:

*

*Least Significant Bit watermarking (which won't resist anything),

*Spread-Spectrum Watermarking (which should resist quite a bit but is very audible),

*There is a MATLAB code for a Compression-Expansion algorithm which is said to be very robust according to the paper "Audio watermarking using time-frequency compression expansion".


text:
Q: Is there a way to use MAPE (Mean Average Percentage Error) with cross_validate on sklearn? I'm trying to use a regression model to train and predict a multi-output dataset (ie. predict multiple target columns).
There is no scorer for MAPE on this list from the sklearn documentation:
https://scikit-learn.org/stable/modules/model_evaluation.html
I know that separately, you can calculate MAPE by using sklearn.metrics.mean_absolute_percentage_error. But is there a way to combine it with cross_validate()? I'm open to using cross_val_score or other cross-validation methods.
Thank you!

A: I don't know if you found a solution already (as it has been long since you posted) but here is a solution I used:
I implemented my own MAPE function as described here using the MAPE formula explained here.
in short here is my code (not quite clean but it does the work):
def my_custom_MAPE(clf, X_val, y_true,epsilon = 0.000001):
      y_pred = clf.predict(X_val)
      ii = 0
      for i in y_true:
          if (i < epsilon) & (i > -epsilon):
             y_true[ii] = epsilon
          else:
             y_true[ii] = y_true[ii]
          ii = ii+1

MAPE = (1/len(y_true))*np.sum(np.abs(y_true - y_pred)/y_true)
return MAPE

Then called it in the cross_validate as such
Scoring_type = {'R2':'r2','NegMSE':'neg_mean_squared_error', 'MAPE': my_custom_MAPE}
cv = KFold(n_splits=K, shuffle=True, random_state=seed)
cv_results = cross_validate(Lin_model, X, y, cv=cv, scoring=Scoring_type)

I hope it helps


text:
Q: jQuery UI and Closure Compiler Advanced Optimizations I'm trying to use Closure Compiler with Advanced Optimizations with my project, I am using jQuery 1.11.1 and jQuery UI 1.10.4.
As extern for jQuery I found an extern of jQuery 1.9 that I think is going to work fine, but I'm having problems with jQuery UI, I am not able to find any extern for any version.
Knows anyonye any extern of jQuery UI?
Thank you.
PS: I tried with the webpage http://www.dotnetwise.com/Code/Externs/ but the extern generated is not helping :-/

A: I have had luck with creating my own simple externs file.  For instance, if I am only using .draggable and .resizable, this is what it contains:

jQuery.prototype.resizable = function (arg1, arg2, arg3) { };
$.prototype.resizable = function (arg1, arg2, arg3) { };
jQuery.prototype.draggable = function (arg1, arg2, arg3) { };
$.prototype.draggable = function (arg1, arg2, arg3) { };

And then in my .js file, use quoted strings instead of dot notation for the property names when initializing:

// USE THIS:
$(".draggable").draggable({ "axis":"x", "containment": "parent",
        "cursor":"move", "handle":".dragHandle", "snap":"#banner, .draggable", "snapMode":"outer"
    });
//INSTEAD OF THIS:
    $(".draggable").draggable({ axis:"x", containment: "parent",
        cursor:"move", handle:".dragHandle", snap:"#banner, .draggable", snapMode:"outer"
    });

A: No known extern for jQuery UI exists.


text:
Q: GAE w/ Objectify - Can you query a HashMap? In GAE, when using Objectify, can you query a HashMap? If so how would would you write it?
ofy().load().type(MyClass.class).filter("hashMapfieldName", "keyQueryinggFor").list();

Does not seem to work where the hashMapfieldName is a HashMap<String, String>. I am looking to find entities where hashMapfieldName contains a certain key.

A: Just like embedded classes, Objectify converts Map<String, String> to the low-level EmbeddedEntity object, which is not indexible. However, if you @Index your Map field (or embedded class field), Objectify will create a synthetic index that lets you query anyways.
Following your example, let's say you have a Map field named hashMapfieldName containing the mapping of strings "key" to "value". This query syntax will return entities that have the pair:
ofy().load().type(MyClass.class).filter("hashMapfieldName.key", "value");

If you are just looking for key existence, try filter("hashMapfieldName.key !=", null).

A: I have a similar case where I have stored device specific values in an embedded hashmap where the device id is the key, and I need to query for all entities that contain a certain value.
The suggested solution by stickfigure above does work in my test environment. But I realized I cannot use it the real application since it will not scale to the number of users we are projecting. This is because Objectify will generate a property index for each hashmap key that I save. In my case, that means that every user's device will have its own index, which could be 100000 indexes!
So instead, I went for this alternative approach:

*

*in the @OnSave method on the entity I store the values that I want to search for in a separate indexed list, that I only use for querying

*then I will do my filtered query like this:

ofy().load().type(MyEntity.class).filter("values", value)

A: I am not sure what Objectify does for HashMap.
But as per the docs, HashMap is not a supported field type in Datastore. Even if we serialize it and store, it will be stored as Blob which is by default unindexded.
So to my knowledge, HashMap cannot be queried as there is no indexes created for it.


text:
Q: Magento 2.2.3 Related Products add to cart button issue i'm just wondering if anybody faced with following issue.
I have enabled "add to card" button on my Related products as per this
article
Now button appeared but the problem is that is actually does not work, it point just to checkout/cart/ link
will really appreciate any comments, thanks!

A: By default Magento, there is no setting option in Admin for Add to Cart button on the related products block. If we want to custom the related, upsell, crosssel and new product template, we should override this template vendor/magento/module-catalog/view/frontend/templates/product/list/items.phtml.
Change $showCart = true; in case - related product.
We can refer here: Related Products template customize
source


text:
Q: HTML Email just showing html in the message I am trying to send mail using the simple mail() function in php and complete the formatting in HTML
PHP Code:
$headers = "From: ClubbedIn\r\n";
$to = $userEmail;
$subject = $rowclub['clubName']." - New Event: ".$eventName;
$message = '';
$message .= '';
$message .= '
';
$message .= "
Event Name: 	" . strip_tags($eventName) . "
";
$message .= "
Date: 	" . strip_tags($newdate) . "
";
$message .= "
Time: 	" . $startTime2." - ".$endTime2 . "
";
$message .= "
Description: 	" . strip_tags($desc) . "
";
$message .= "
";
$message .= "";

    //$message = "Event Name: ".$eventName."\nDate: ".$newdate."\nTime: ".$startTime2." - ".$endTime2."\nDescription: ".$desc;

    mail($to,$subject,$message,$headers);

However the email just ends up looking like this:

The html does not work for some reason?

A: you need to make changes to the header to indicate its HTML email. Try this:
$headers = "MIME-Version: 1.0\r\n";
$headers.= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers.= "From: ".$from_address."\r\n";

Update: changed \n to \r\n as suggested by Matt Bryant to meet rfc 2822 specification.

A: To send HTML mail, the Content-type header must be set
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
// Additional headers
$headers .= "To: Mary <mary@example.com\r\n";
$headers .= "From: Birthday Reminder <birthday@example.com>\r\n";
$headers .= "Cc: birthdayarchive@example.com\r\n";
$headers .= "Bcc: birthdaycheck@example.com\r\n";

(php.net)

A: Add the proper headers:
$headers = "From: ClubbedIn\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";


text:
Q: How do I execute an external program from Perl and have the perl script continue I am running a perl script from a cron job on Ubuntu. As part of the script it needs to execute an external program and not wait for the program to complete and also continue executing the script. I have tried the following but as near as I can tell it is not executing the program and also seams to not continue the script.
exec("/usr/bin/dotnet /usr/local/myprogram/myprogram.dll arg1, arg2, moreargs")
    or print STDERR "Couldn't exec myprogram";

A: *

*To call your program, you should pass the program arguments as separate arguments to exec. (See https://perldoc.perl.org/functions/exec.html.)

*Since you want the script to proceed without waiting for the program to return, you should use fork (see https://perldoc.perl.org/functions/fork.html) so that you have two separate processes running in parallel (one running the program, one running the rest of the script).

So:
my $child_pid = fork();
die "Couldn't fork" unless defined $child_pid;
if (! $child_pid) {
  exec '/usr/bin/dotnet', '/usr/local/myprogram/myprogram.dll', 'arg1', 'arg2', 'moreargs';
  die "Couldn't exec myprogram: $!";
}

# rest of script

wait();


text:
Q: how to Create a ListBox in windows phone for a Async Json datagetting from a url? I Done Json Parsing By this way
and in that if i try with (as a example)
public string id { get; set; }

i can able to make a constant data not a listBox...
I Already Done an android application.. for a Json form a Url.. This is my Json data(similar to this.)
{
"returnCode": "success",
"Data": {
"results": [
{
    "moredetails": [
        {
            "newoffers": [

            ],
            "recentoffers_count": 0,
            "sku": "30072246"
        },
        {
            "newoffers": [
                {
                    "availability": "Available",
                    "currency": "USD"
                }
            ]
        },
        {
            "newoffers": [
                {
                    "availability": "Available",
                    "currency": "USD"
                }
            ],
            "offers_count": 1,
            "name": "google.com"
        }
    ],
    ..."features": {
        ..
    },
    "length": "20",
    "geo": [
        "usa"
    ],
    .."images": ["http://timenerdworld.files.wordpress.com/2013/01/wpid-photo-jan-14-2013-1117-am.jpg"],
    ..
}
],
...
}
}

Like this Have a Huge JSON data this is Just a one loop of a JSon data ... i have a N number of loops of a JSON data So i want to display the data..
So in android i am Parsing Json with Hashmap and now in C# i am parsing similar way..

So at here I want a List Box.. In android i used ListView + onclick single item view By this Url
and in windows i found a List Box + onclick single item By this URL But it not JSON its a XML Json i want this for JSON..
and want to add i want to Create a Same List Box With a JSON data With and async task which is Based on
 JObject json = JObject.Parse(eArgs.Result);
        JArray category_list = (JArray)json["category_list"];

        this.jAbout.Text = (string)json["about"];

Like that...
So that this will Look same like android Application... is there any way to make the Same flicker app for JSON in windows phone  application.

A: In Windows phone 7 exist ListBox and LongListSelector (from the windows phone toolkit) controls for representing different sort of collections.
ListBox is more simply to use.
ListBox has ItemsSource property.
You have to work with UIElements only from the main thread. But you can prepare everything in the background thread
How to work with ListBox:

*

*You can put there any IEnumerable<yourDataModelClass> instance or bind some property with the type, that inherits from IEnumerable (for example List<yourDataModelClass> or ObservableCollection<yourDataModelClass>. Second one is better for binding). "yourDataModelClass" is some class, that contains all properties of the ListBox item. If you liked LINQ, with help of which this guys (developer.nokia.com) deserializing XML, you can use LINQ to JSON.
And for the ListBox you have to set ItemTemplate property (better do it from XAML) (http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemtemplate(v=vs.110).aspx).

*As I already mentioned, you can bind some collection to the ItemsSource property. So you put this collection into DataContext property of your ListBox, In XAML you can write like this <ListBox ItemsSource="{Binding}"/>. So if collection is ObservableCollection, so there is already implemented INotifyPropertyChanged, and this collection will notify its owner, if there appended some items (here is you also have to create some ItemTemplate). So if you already set this collection to the DataContex, you can't add something into it in the background thread. It's better to read something about MVVM pattern, it's cool \m/

*There is another way to work with ListBox: you can add ListBox items to its property called Items.

For asynchronous work here exist a couple ways:

*

*BackgroundWorker class (http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.95).aspx)

*async tasks (you'll need this library for it http://www.nuget.org/packages/Microsoft.Bcl.Async/) (here is an example of a task using Async await in Windows Phone web access APIs).

So this ways will help you to do whatever you want asynchronously. Enjoy =)
And don't forget to go back to the main thread, when your JSON is parsed and you ready to show it to a user ( Deployment.Current.Dispatcher.BeginInvoke(Action); - this is how to go back to the UI thread whenever you want, but my advice is to read about BackgroundWorker and  async tasks)


text:
Q: General orthogonality for periodic Sturm-Liouville problems Suppose you have a Sturm-Liouville problem with periodic boundary conditions, that is:
$\begin{align}
& \frac{-d}{dx}(p(x) \frac{dy}{dx})+q(x)y =\lambda r(x) y \\
& p(a) =p(b) , \; y(a) =y(b),\;  y'(a) =y'(b)
\end{align}$
We know that the eigenspaces can have dimension greater than one, as shown by the classical example:
$\begin{align}
& y''+\lambda y  =0 \\ & p(0) =p(2 \pi) ,\; y(0) =y(2 \pi) ,\; y'(0) =y'(2 \pi)
\end{align}$
Most textbooks prove that the eigenfunctions associated to different eigenvalues are orthogonal, which is easy once you know that L is self-adjoint under these conditions. Is this still true for linearly independent eigenfunctions associated to the same eigenvalue? (I'm guessing it'll be true due to some kind of Spectral Theorem for infinite dimension). If it's not, what is some counterexample?

A: For example, $\sin(nx),\cos(nx)$ are eigenfunctions with the same eigenvalue $\lambda=n^2$ of the periodic problem
$$
               -y'' = \lambda y,\;\;\;\; y(-\pi)=y(\pi),\; y'(-\pi)=y'(\pi).
$$
However, $\sin(nx)+\cos(nx)$ and $\cos(nx)$ are linearly independent eigenfunction solutions with the same eigenvalue $\lambda=n^2$, but these are not mutually orthogonal. When there are degeneracies, you have choose the eigenfunctions with the same eigenvalue so that they are orthogonal; there's no unique way to do that, but it is automatic that--whatever your choice--the pair of them will be orthogonal to the eigenfunctions with different eigenvalues. Though $\cos(nx)$ and $\sin(nx)$ are natural choices of orthogonal eigenfunctions for $n=1,2,3,\cdots$, the following are also orthogonal with the same eigenvalue
$$
       \sin(nx)-\cos(nx),\;\; \sin(nx)+\cos(nx).
$$
For one-dimensional eigenspaces, the eigenfunctions are unique up to a multiplicative constant.


text:
Q: Dapper Query ToList as IEnumerable> result is null My Code
    using (var connection = new SQLiteConnection("Data Source=:memory:"))
    {
        {
            var v = connection.Query(@"select 1 A,2 B ");
            var cV = v as IEnumerable<IDictionary<string,object>>;
            Console.WriteLine(v.GetType().FullName); // result : System.Collections.Generic.List`1[[Dapper.SqlMapper+DapperRow, Dapper, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]]
            Console.WriteLine(cV); // result : A=1,B=2
        }

        {

            var v = connection.Query(@"select 1 A,2 B ").ToList();
            var cV = v as IEnumerable<IDictionary<string, object>>;
            Console.WriteLine(v.GetType().FullName); // result : System.Collections.Generic.List`1[[System.Object, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]
            Console.WriteLine(cV); // result : null
        }
    }

My question is :
Dapper Query as IEnumerable<IDictionary<string,object>> is not null, but why after ToList then as IEnumerable<IDictionary<string,object>> is null
As I know List is extends by IEnumerable<T> so Dapper Query ToList Should be IEnumerable<IDictionay<string,object>> but result is not.
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>

update:
And It's work if specify IDictionary<string,object> type in foreach
        {
            var v = connection.Query(@"select 1 A,2 B ").ToList();
            foreach (IDictionary<string, object> e in v)
            {
                Console.WriteLine(v.GetType().FullName); // result : System.Collections.Generic.List`1[[System.Object, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]
                Console.WriteLine(e); // result : A=1,B=2
            }
        }

A: The return type of Query with no generic type argument is IEnumerable<dynamic>, the actual object is a List<DapperRow>.
DapperRow happens to implement IDictionary<string, object>. Therefore:

*

*In version 1 of your code you can cast the List directly to IEnumerable<IDictionary<string, object>.

*Version 2 you are calling ToList, but because you haven't got the exact type, you end up with a call to ToList<object>. Remember, ToList always creates a new list, even when the existing object is a list already.

*Your final version goes back to the original, but now it casts each object in the list to IDictionary<string, object>. So it is equivalent to the following code:
foreach (var e in v.Cast<IDictionary<string, object>())
{

Personally I always use actual classes with Query<MyClass> and I don't rely on dynamic or DapperRow as it can be inefficient and difficult to use.


text:
Q: Ignore certain changes for git commit Members of our team uses different version of visual studio, and VS seems to automatically update the sln file with code like:
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual C# Express 2010

or
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012

whenever we work with the solution. Can we configure git to ignore such changes? We're not interested in this line, but we are interested in other changes of the .sln file, e.g. adding of new csproj to the solution.

A: It's not possible to partially ignore a file. A simple solution would be to create two versions of the .sln file, and tell the team to open the one corresponding to their version.
Another solution would be a post-commit hook that rejects the commit if these lines are changed. Needs a bit of scripting, but it's feasible.

A: On your local side you can simply update git index to ignore changes in certain file like this:
git update-index --assume-unchanged SolutionFile.sln

The same thing can do any of your developers.
Another solution would be adding the file to .gitignore if you don't want to keep it under source control.

A: I would just ignore the .sln files for they are not relevant to building a project: Microsoft realized some time ago that project files must be versionable and novadays all building done by the Studio is carried out by msbuild engine which takes those .proj (and other .<whatever>proj, like .csproj, .vbproj etc) XML files and uses them to build a project.  Those files is actually everything which is needed to build a project, and the solution file just contains various bookkeeping information.

A: You can add a smudge/clean filter to git which calls a script to tweak the particular line to be consistent when committing. In "Can git automatically switch between spaces and tabs?", it shows how to implement a similar change, where spaces are converted to tabs on checkout, and back to spaces on commit.
You'll probably need to write the script to identify and modify the relevant line, whereas the linked example uses pre-existing unix commands for swapping between tabs and spaces.


text:
Q: Saving symbols to plot with Trellis I am plotting in xyplot() as per below.  I put symbols on the plot with print(panel.points()) and it works.  But I need to save the plot with the points to a variable (a in the example) so I can use grid arrange to combine it with other plots in the same picture.  Ideas?
dev.off()
x <- c(1:10)
y <- c(1:10)

a <- xyplot(y ~ x, type = "l")

trellis.focus("panel", 1, 1, highlight = FALSE)

print(panel.points(x[c(5,10)],
               y[c(5,10)],
               pch = 19,
               cex = 0.75,
               col = c("red", "black")))

A: Use panel.points within a panel function that calls panel.xyplot to do the main plot:
b = xyplot(
      y~x,type="l",
      panel=function(...){
       panel.xyplot(...)
       panel.points(
        x[c(5,10)],y[c(5,10)],
        cex=0.75, col=c("red","black"),pch=19
       )
       }
    )


text:
Q: Resistance of a diode in different regime and the physics of recombination current I would like to ask question about the resistance of a diode under different regime. Surely, in reverse bias, it has a breakdown voltage, and in forward bias,it rises exponentially according to the exponential relationship according to the theory ( ideal Shockley diode equation ) . But what happens at the flat band situation? I do not understand why it should obey Ohm's law well when the fermi levels are split by  eV=eVo, where Vo is the barrier height (when applied bias V is zero). (see Fig.1.)
Any Justifications with the physics of the charge carriers or using formulas would be much appreciated.

Thanks

A: I'll upgrade my comment to an answer.
You are thinking about this in the wrong way.
If you operate a diode at a fixed point on the IV curve (that is by sourcing or sinking current as needed), then the device's resistance is constant. For example, you might want to do this with a PN junction solar cell; they are operated at the maximum power point.
However, this does not mean that the diode obeys Ohms Law, that is a property of the whole IV curve, not just a single point.
Ohms Law states that for any applied bias the resistance is constant. This is clearly false for a diode because if the bias changes, even by a little bit, the resistance changes exponentially (in forward bias).
I think the confusion is arising from the fact that you are mentally equating the band structure of a forward bias diode (at the flat band point) to that of a simple resistor. And based on this fact, extrapolating to the statement that the diode must be Ohmic.
tl;dr Any device held at a particular point on it's IV curve has constant resistance, this doesn't mean that all electronic components are resistors.


text:
Q: Modo de criar página HTML com PHP Não possuo muito conhecimento e não sei se o modo que estou fazendo está correto ou possui algum ponto negativo. Tem alguma opção melhor para que eu possa fazer?
<?php
$ht = '
';
$ht .= '
';
$ht .= '<form id="searchthis" method="get">';
$ht .= '<input id="namanyay-search-box" name="search" size="40" type="text" placeholder="Search"/>';
$ht .= '<button id="namanyay-search-btn" type="submit" class="btn btn-primary"></button>';
$ht .= '</form>';
$ht .= '
Manage OneDrive Videos
';
$ht .= '
';
$ht .= '
';
$ht .= '
';

echo $ht;
?>

A: De forma geral não há problema em fazer assim, mas o pessoal costuma usar o sistema de template, ou seja, coloca-se em primeiro lugar o HTML e coloca um código PHP nas lacunas necessárias. O que não é o caso deste código, ou seja, esse exemplo deveria ser uma página estática HTML que nem passe pelo processador do PHP, seria absurdamente mais rápido assim.
Exemplo bem básico de como se costuma fazer:

        <title>PHP Test</title>

<?php echo "1 + 1 é " . (1 + 1); ?>

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Claro, o exemplo é bobo e assim também não precisaria passar pelo PHP, mas dá uma ideia de como é mais comum. O que você faria provavelmente é uma página que receberia o valor enviado pelo seu exemplo e trataria dando um resultado final que seria entregue para o navegador.


text:
Q: Proper way to handle SIGTERM with multiple threads I have a multi threaded program on Raspberry in which I want to handle SIGTERM and shut everything down gracefully. The issue is that I have a background thread that has called recvfrom() on a blocking socket. As per my understanding from the man pages, if I exit my handler all the system calls should be woken up and return with -1 and errno set to EINTR. However in my case the recvfrom call keeps hanging.
1) In general am I understanding this right, that all threads that have blocking system calls that are able to be woken up by a signal should wake up in this scenario?
2) Could it be that the operating system is setting some special signal mask on my thead?
The interresting part is that I am using the VideoCore primitives, not pthread, maybe that could be the cause? Here is a small test example:
#include <iostream>

#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>

#include "interface/vcos/vcos.h"

void SignalHandler(int nSignalNumber)
{
    std::cout << "received signal " << nSignalNumber << std::endl;
}

void* ThreadMain(void* pArgument)
{
    int nSocket = socket(AF_INET, SOCK_DGRAM, 0);
    if (nSocket >= 0)
    {
        sockaddr_in LocalAddress;
        memset(&LocalAddress, 0, sizeof(LocalAddress));
        LocalAddress.sin_family = AF_INET;
        LocalAddress.sin_addr.s_addr = INADDR_ANY;
        LocalAddress.sin_port = htons(1234);
        if (bind(nSocket, reinterpret_cast<sockaddr *>(&LocalAddress), sizeof(LocalAddress)) == 0)
        {
            sockaddr_in SenderAddress;
            socklen_t nSenderAddressSize = sizeof(SenderAddress);
            unsigned char pBuffer[512];
            std::cout << "calling recvfrom()" << std::endl;
            int nBytesReceived = recvfrom(nSocket, pBuffer, sizeof(pBuffer), 0, reinterpret_cast<struct sockaddr *>(&SenderAddress), &nSenderAddressSize);
            if (nBytesReceived == -1)
            {
                if (errno == EINTR)
                {
                    std::cout << "recvfrom() was interrupred by a signal" << std::endl;
                }
                else
                {
                    std::cout << "recvfrom() failed with " << errno << std::endl;
                }
            }
        }
        else
        {
            std::cout << "bind() failed with " << errno << std::endl;
        }
        close(nSocket);
    }
    else
    {
        std::cout << "socket() failed with " << errno << std::endl;
    }
    return NULL;
}

int main(int argc, char** argv)
{
    struct sigaction SignalAction;
    memset(&SignalAction, 0, sizeof(SignalAction));
    SignalAction.sa_handler = SignalHandler;
    sigaction(SIGTERM, &SignalAction, NULL);
    VCOS_THREAD_T Thread;
    VCOS_STATUS_T nVcosStatus = vcos_thread_create(&Thread, "", NULL, ThreadMain, NULL);
    if (nVcosStatus == VCOS_SUCCESS)
    {
        void* pData = NULL;
        vcos_thread_join(&Thread, &pData);
    }
    else
    {
        std::cout << "vcos_thread_create() failed with " << nVcosStatus << std::endl;
    }
    return EXIT_SUCCESS;
}

It can be compiled like this:
g++ test.cpp -I/opt/vc/include -L/opt/vc/lib -lvcos  -o test

When I run it and then call kill on the running instance the output is:
calling recvfrom()
received signal 15

and the process hangs. I'll try if a pthread behaves differently.
UPDATE
Ok I updated the sample to spawn a pthread thread as well and that one is not quitting as well. So I assume the signals are not populated to all threads?
#include <iostream>

#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>

#include "interface/vcos/vcos.h"

void SignalHandler(int nSignalNumber)
{
    std::cout << "received signal " << nSignalNumber << std::endl;
}

void* ThreadMain(void* pArgument)
{
    const char* pThreadType = reinterpret_cast<const char*>(pArgument);
    int nSocket = socket(AF_INET, SOCK_DGRAM, 0);
    if (nSocket >= 0)
    {
        sockaddr_in LocalAddress;
        memset(&LocalAddress, 0, sizeof(LocalAddress));
        LocalAddress.sin_family = AF_INET;
        LocalAddress.sin_addr.s_addr = INADDR_ANY;
        LocalAddress.sin_port = htons(pThreadType[0] * 100);
        if (bind(nSocket, reinterpret_cast<sockaddr *>(&LocalAddress), sizeof(LocalAddress)) == 0)
        {
            sockaddr_in SenderAddress;
            socklen_t nSenderAddressSize = sizeof(SenderAddress);
            unsigned char pBuffer[512];
            std::cout << "calling recvfrom()" << std::endl;
            int nBytesReceived = recvfrom(nSocket, pBuffer, sizeof(pBuffer), 0, reinterpret_cast<struct sockaddr *>(&SenderAddress), &nSenderAddressSize);
            if (nBytesReceived == -1)
            {
                if (errno == EINTR)
                {
                    std::cout << "recvfrom() was interrupred by a signal" << std::endl;
                }
                else
                {
                    std::cout << "recvfrom() failed with " << errno << std::endl;
                }
            }
        }
        else
        {
            std::cout << "bind() failed with " << errno << std::endl;
        }
        close(nSocket);
    }
    else
    {
        std::cout << "socket() failed with " << errno << std::endl;
    }
    std::cout << pThreadType << " thread is exiting" << std::endl;
    return NULL;
}

int main(int argc, char** argv)
{
    struct sigaction SignalAction;
    memset(&SignalAction, 0, sizeof(SignalAction));
    SignalAction.sa_handler = SignalHandler;
    sigaction(SIGTERM, &SignalAction, NULL);
    VCOS_THREAD_T VcosThread;
    VCOS_STATUS_T nVcosStatus = vcos_thread_create(&VcosThread, "", NULL, ThreadMain, const_cast<char*>("vcos"));
    bool bJoinVcosThread = false;
    if (nVcosStatus == VCOS_SUCCESS)
    {
        bJoinVcosThread = true;
    }
    else
    {
        std::cout << "vcos_thread_create() failed with " << nVcosStatus << std::endl;
    }
    pthread_t PthreadThread;
    int nPthreadStatus = pthread_create(&PthreadThread, NULL, ThreadMain, const_cast<char*>("pthread"));
    bool bJoinPthreadThread = false;
    if (nPthreadStatus == 0)
    {
        bJoinPthreadThread = true;
    }
    else
    {
        std::cout << "pthread_create() failed with " << nPthreadStatus << std::endl;
    }
    if (bJoinVcosThread)
    {
        void* pData = NULL;
        vcos_thread_join(&VcosThread, &pData);
    }
    if (bJoinPthreadThread)
    {
        void* pData = NULL;
        pthread_join(PthreadThread, &pData);
    }
    return EXIT_SUCCESS;
}

A: A signal such as SIGTERM is submitted to one thread in the process only.  The only precondition is that the chosen thread must either have not masked the signal, or must wait for it using sigwait.  The other threads will not be directly notified that the signal has been delivered.
A common approach to combine signals with threads is to have a separate thread which handles signals only and notifies the other threads using thread synchronization mechanisms such as condition variables.
For interrupting file I/O, this may not be sufficient because there is a race condition between checking for a termination request and making the system call to perform the I/O operation.  Some language run-time libraries use non-blocking I/O with poll or epoll with a special file descriptor which becomes ready on signal delivery (either using the previously-mentioned thread-based approach, or something Linux-specific like signalfd).  Others try to avoid this overhead by using the read and write system calls directly with a complicated dance which uses dup2 to replace the file descriptor with one that always causes I/O to fail, thereby avoiding the race condition (but the bookkeeping needed for that is fairly complicated).

A: The manpage for signal reads:

If a signal handler is invoked while a system call or library function call is blocked, then either:

*

*the call is automatically restarted after the signal handler returns; or

*the call fails with the error EINTR.
Which of these two behaviors occurs depends on the interface and whether or not the signal handler was established using the SA_RESTART flag (see sigaction(2)). The details vary across UNIX systems<...>

A few lines below, recvfrom is listed among the functions that use SA_RESTART behavior by default. (Note: this behavior is disabled if there's a timeout on the socket, though.)
Thus, you should fill the sa_flags field of the sigaction structure to carefully avoid setting the SA_RESTART flag.

A: A good way to deal with blocking sockets -see socket(7)- (and even non blocking ones) is to use a multiplexing syscall like poll(2) (or the obsolete select(2)....)
Regarding signals, be sure to read signal(7) and signal-safety(7).
A common way to handle signals with some event loop (using poll(2)) is to have a signal handler which simply write(2)-s a byte on a pipe(7) to self (you'll setup the pipe at initialization, and you'll poll it in your event loop). The Qt documentation explains how and why. You might also use the Linux specific signalfd(2).


text:
Q: Explanation of ln derivative... So we know that for example :

I'd like to know how do we get to this result based on:

I've been trying to do it for myself but I really have no idea how to get to the result starting.

A: I'll show you an alternative way of evaluating deriving that $\frac{d}{dx}\ln(x)=\frac{1}{x}$.

We know that if $f$ is differentiable in an interval $I$, with $f'(x) < 0$ or $f'(x) > 0$ for all $x \in I$, then $f$ has an inverse funcion $f^{-1}$which is defined and is differentiable on $f(I)$.

So let $f(x) = e^x$. Then $f$ is defined and differentiable in $\mathbb R$ and $\forall x \in \mathbb R,f'(x) > 0$, so there exists an inverse function defined and differentiable in $f(\mathbb R) = \mathbb R^+$, which is $f^{-1}(x) = \ln(x)$
We know that $f(f^{-1}(x)) = x$. If we differentiate from both sides we get:
$$\begin{align}
&(f^{-1})'(x)f'(f^{-1}(x)) = 1 \iff
\\
\\
&(f^{-1})'(x) = \frac{1}{f'(f^{-1}(x))}
\end{align}$$
We know that $f'(x) = e^x$ so $f'(f^{-1}(x)) = x$. So we conclude that
$$\begin{align}
&(f^{-1})'(x)=\frac{1}{x} \iff
\\
\\
&\frac{d}{dx}\ln(x)=\frac{1}{x}
\end{align}$$
Using then the chain rule you can get the derivative you want.
This is a common way of finding out derivatives for inverse functions.

A: If $f(x) = \ln(x)$
then
$f(xy) = f(x)+f(y)
$
so
$f(x+h)
=f(x(1+h/x))
=f(x)+f(1+h/x)
$
and
$f(1) = 0
$
(since
$f(x)
=f(1*x)
=f(1)+f(x)
$)
so
$\begin{array}\\
f(x+h)-f(x)
&=f(1+h/x)\\
\text{so}\\
\dfrac{f(x+h)-f(x)}{h}
&=\dfrac{f(1+h/x)}{h}\\
&=\dfrac{f(1+h/x)-f(1)}{h}\\
&=\dfrac1{x}\dfrac{f(1+h/x)-f(1)}{h/x}\\
&\to\dfrac1{x}f'(1)
\qquad\text{as } h \to 0 \text{ if } f'(1) \text{ exists}\\
\end{array}
$
Therefore,
if $f'(1)$ exists,
$f'(x) = \dfrac{f'(1)}{x}
$.
The natural log is the one
with $f'(1) = 1$.

A: hint
If $ f(x) $ has the form
$$f(x)=\ln(g(x))$$
then
$$\frac{f(x+h)-f(x)}{h}=\frac 1h\ln(\frac{g(x+h)}{g(x)})$$
$$\sim \frac 1h(\frac{g(x+h)}{g(x)}-1)$$
$$\sim \frac{g(x+h)-g(x)}{h}\frac{1}{g(x)}$$
thus
$$\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}=\lim_{h\to 0}\frac{g(x+h)-g(x)}{h}\frac{1}{g(x)}$$
or
$$f'(x)=\frac{g'(x)}{g(x)}$$


text:
Q: How to include external JS file in JSP file in Spring WebMVC framework? I have tried below answer but it didn't work..
How include an external JS file in a JSP page
I have been searching on google but couldn't find anything useful...my JS file is at same level as that of WEB-INF..any help would be appreciated...
Below is the code that I'm using to include my JS file in JSP :-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.18.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/formValidation.js"></script>

below code is in web.xml :-
<servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>

Below code is in dispatcher-servlet.xml file :-
<context:component-scan base-package="com.programcreek.helloworld.controller" />

    <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

A: You might want to add ResourceHandler to resolve your static resources like js/css directory
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
        .addResourceHandler("/js/**")
        .addResourceLocations("/js/")
        .setCachePeriod(3600)
        .resourceChain(true)
        .addResolver(new PathResourceResolver());
}

This method apply for java configuration class extends WebMvcConfigurerAdapter
The xml version should look like this
<mvc:resources mapping="/js/**" location="/js/"/>

This will resolve any .js file under /webapp/js/ directory, using something like below in .jsp file
<script src="js/custom.js"></script>

A: for help you can see this github link click here
I hope it will help you
and this is the project structure


text:
Q: Sort JSON data based on nested field I am trying to solve this problem in Java.
I need to read student data in JSON format from a URL and output it after sorting.
The model is:
[
  {
    "name": "string",
    "lecturers": [
      {
        "name": "string",
        "subject": "string"
      }
    ]
  }
]

Below is an example of what the JSON data looks like:
[
  {
    "name": "Jack",
    "lecturers": [
      {
        "name": "Mr.Smith",
        "subject": "Music"
      },
      {
        "name": "Mr.Cooper",
        "subject": "Physics"
      },
      {
        "name": "Miss.Rae",
        "subject": ""
      }
    ]
  },
  {
    "name": "Dan",
    "lecturers": [
      {
        "name": "Miss.Jane",
        "subject": "Physics"
      },
      {
        "name": "Mr.Smith",
        "subject": "Music"
      },
      {
        "name": "Mr.JJ"
      }
    ]
  },
  {
    "lecturers": [
      {
        "name": "Mr.Higgs",
        "subject": "Art"
      },
      {
        "name": "Mr.Jones",
        "subject": "Chemistry"
      }
    ]
  }
]

The output should be sorted alphabetically as below:
Subject A
   Lecturer X
      Student E
   Lecturer Y
Subject B
   Lecturer A
      Student C
      Student D

What I have done so far :
As below, read the JSON data using Jackson library's ObjectMapper.
public class Student {
    String name;
    List<Lecturer> lecturers;
}
public class Lecturer {
    String name;
    String Subject;
}

List<Student> student =  objectMapper.readValue(new URL("myUrl"), new TypeReference<List<Student>>(){});

How do I go about sorting ? Should I use Java comparator. Not sure how to sort based a field from a list of nested objects. Or should I store the JSON data differently and try to sort ?
Also, as you can see from the example, null values should be handled.