text:
Q: kamailio: how to get a value from SIP INVITE Header Please help me to get the a value from SIP INVITE header reached to kamailio like INVITE sip:+341930203454@sub.domain.com;myid=+34@sub.domain.com SIP/2.0 and i want to save the myid value +34 into a variable, without the domain name.
     $var(uri) = $sel(ruri);
     xavp_params_explode("$(var(uri){s.unbracket})", "uri");
     xlog("L_INFO", "$var(uri) Received converted to $xavp(uri=>myid[0])\n");

I tried above and it prints +34@sub.domain.com But i want to just save +34 into a variable to further check the prefix based routing from the database.
Could you please help how to get it or If there is any alternate/single line approach to get this value, please help.
thanks in advance.

A: An one line statement variant can be:
$var(result) = $(ru{uri.param,myid}{s.select,0,@});

Where:

*

*$ru - is the request URI (sip address in the first line of request)

*{uri.param,myid} - is a transformation returning the value of a parameter (myid in this case) in a URI

*{s.select,0,@} - is a transformation returning first token from a string by splitting it using the delimiter @

A: I think something like this will work:
$var(uri) = $sel(ruri);
$var(myid-param) = $(var(uri){param.value,myid}); # this should return +34@sub.domain.com
$var(sip-myid-param) = "sip:" + $var(myid-param); # this should return sip:+34@sub.domain.com
$var(user-part) = $(var(sip-myid-param){uri.user}); # this should return +34

All above string operation is possible to put in one line, I used several lines just to show it in simple way.
In one line it should be something like below, but please do not quote me on this, but I hope you can get an idea
$var(user-part) = $(var("sip:" + $var($(var(uri){param.value,myid}))){uri.user});


text:
Q: MultiAutoCompleteTextView with custom adapter (BaseAdapter) I am using a MultiAutoCompleteTextView and setting my own custom adapter (BaseAdapter) on it. But every time I write something in MultiAutoCompleteTextView, the constraint in the performFiltering method always gets null value for every character I write.
Here is my code for the BaseAdapter class:
public class ListItemAdapter extends BaseAdapter implements Filterable{
    ArrayList<ListItem> listItems;
    ArrayList<ListItem> suggestions = new ArrayList<>();
    private Filter filter = new CustomFilter();
    Context context;
    LayoutInflater inflater;

    public ListItemAdapter(ArrayList<ListItem> listItems, Context context) {
        this.listItems = listItems;
        this.context = context;
        inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return listItems.size();
    }

    @Override
    public Object getItem(int position) {
        return listItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;

        v = inflater.inflate(R.layout.single_item, null);
        TextView title = (TextView) v.findViewById(R.id.title);

        title.setText(listItems.get(position).getTitle());
        return v;
    }

    @Override
    public Filter getFilter() {
        return filter;
    }

    private class CustomFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            suggestions.clear();

            Log.d("FILTERRES", ""+listItems.size() + ", " + constraint);

            if(listItems != null && constraint != null) {
                for(int i=0 ; i<listItems.size(); i++) {
                    if(listItems.get(i).getTitle().toLowerCase().contains(constraint)) {
                        suggestions.add(listItems.get(i));
                    }
                }
            }

            FilterResults results = new FilterResults();
            results.values = suggestions;
            results.count = suggestions.size();
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if(results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

Here is how I am setting the adapter to MultiAutoCompleteTextView:
MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.auto);
ListItemAdapter adapter = new ListItemAdapter(items, this);
textView.setThreshold(1);
textView.setAdapter(adapter);

What am I doing wrong here?
Edit:
I changed my MultiAutoCompleteTextView to AutoCompleteTextView and now it is working, does anyone know how to make it work for MultiAutoCompleteTextView?

A: You need to setTokenizer() to your MultiAutoCompleteTextView in order to get it work.
You can use -
 textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

Even you can set your own custom tokenizer if you have any special requirements else you can use CommaTokenizer which appends comma(,) everytime you select any option from the dropdown.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set default Date in Hibernate and MySQL using @Before and xml file I'm trying build a table with Hibernate + Spring and testing it with JUnit.
Here is my class model:
@Id
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "user_name")
private User user;

@Id
@Column(name = "date_exam")
private Date dateExam;

@Column
private Float percent;

When I'm trying to testing it using JUnit:
@Test
public void testGetAll() {
    List<Score> scores = service.getScores();
    assertEquals(1, scores.size());
}

It shows this error (actually I tried with all the testing like Save, Update, Delete, Get A Record and same error occur):
java.sql.SQLException: Field 'dateExam' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3593)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3525)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1986)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2140)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2111)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1362)
at org.dbunit.database.statement.SimplePreparedStatement.addBatch(SimplePreparedStatement.java:80)
at org.dbunit.database.statement.AutomaticPreparedBatchStatement.addBatch(AutomaticPreparedBatchStatement.java:70)
at org.dbunit.operation.AbstractBatchOperation.execute(AbstractBatchOperation.java:195)
at org.dbunit.operation.CompositeOperation.execute(CompositeOperation.java:79)
at test.backend.config.dao.ScoreDaoTest.resetDatabase(ScoreDaoTest.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

I think the problem with the private Date dateExam; the thing that I confuse is the column dateExam I set the default to NULL but why it said SQLErrorException. Before this, I already build 4 more tables but without Date as the column type and without error. I try to changed it to private java.sql.Timestamp dateExam but error still occur.
Anyone can give me solution for this?
I'm very appreciated with your help. Thanks...
Update
I try to remove the @Id and set the nullable = true but still the same...
Update 30/04
I got the problem, when JUnit testing I try to load the first data from xml file:
@Before
public void resetDatabase() throws Exception {
    IDataSet dataSet = new FlatXmlDataSetBuilder().build(new File(
            "fixtures/score.xml"));
    final Connection conn = dtSource.getConnection();
    DatabaseOperation.CLEAN_INSERT.execute(new DatabaseConnection(conn),
            dataSet);
}

And the score.xml:
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<user
    user_name="crazenezz"
    first_name="craze"
/>
<score
    user_name="crazenezz"
    date_exam="2012-04-30"
    percent="100"
/>
</dataset>

The question now, what is the true format for the date date_exam here using java.util.Date if we initialize the value inside the xml file? Because I tried before to set the default value in the model private Date dateExam = new Date() the error still occur?

A: Use @Temporal(TemporalType.TIME) Hibernate annotation(TemporalType TIME/DATE/TIMESTAMP), initialize the date.

A: remove the id annotation for date(you can't have id value for two fields), to initialize you can just do this which give an initial date value.
@Column(name = "date_exam")
private Date dateExam = new Date();

But I would suggest using joda-time


text:
Q: convert row to column based on text I have a rather large file (single column) with data similar to this:
BT1111
2.2.2.2/3
3.3.3.3/4
7.2.1.1/5
BT6766
2.2.1.1/5
4.5.1.1/7
BT9898
4.4.4.4/2
8.8.8.8/9

I wish to find a function that can align it into two columns, by moving all entries starting with digit one column ($1 to $2) and enrich it with the corresponding BT field, so desired output should be
BT1111;2.2.2.2/3
BT1111;3.3.3.3/4
BT1111;7.2.1.1/5
BT6766;2.2.1.1/5
BT6766;4.5.1.1/7
BT9898;4.4.4.4/2
BT9898;8.8.8.8/9

I can't imagine how to ensure the "look for next occurence" should be performed, but hope there is a function for it I have managed to overlook ?

A: perl -nle'if (/^\D/) { $n=$_ } else { print "$n;$_" }' input.txt

See Specifying file to process to Perl one-liner for alternate usages.

A: $ awk '/BT/{a=$1; next}{print a ";" $1}' input.txt
BT1111;2.2.2.2/3
BT1111;3.3.3.3/4
BT1111;7.2.1.1/5
BT6766;2.2.1.1/5
BT6766;4.5.1.1/7
BT9898;4.4.4.4/2
BT9898;8.8.8.8/9


text:
Q: R Shiny - Run application in background and issue UI controls with code I am writing a vignette for my Shiny application package. At the beginning of my vignette, I source a file called screenshots.R that produces nice screenshots of my application. I am producing them like so:
webshot::appshot(mypackage::run_datepicker_app(),
                 file = "man/figures/datepicker.png", vwidth = 500, vheight = 200)

This works great and it gives me a great screenshot of what is - in this case - a couple dateInput fields. However, I'd like to be able to get a screenshot of the dateInput in use (say, with the calendar selection exposed).
Is there a way to issue commands to the application object in a script so I can get screenshots of the application in use, rather than having to do it manually?

A: Have you tried using ShinyDriver from the shinytest package?
You can use shinytest to have a headless browser run the app, interact with it, and take screenshots programmatically. If you don't have phantomJS installed, you'll need to run shinytest::installDependencies() before using ShinyDriver. All you need to do is point it to a directory containing a shiny app (in my case, the folder is 'myApp').
install.packages("shinytest")
shinytest::installDependencies()

app <- shinytest::ShinyDriver$new("myApp")
app$takeScreenshot("screenshot1.png")
button <- app$findElement("#button")
button$click()
Sys.sleep(1)
app$takeScreenshot("screenshot2.png")
app$stop()

I am starting the app in a headless browser, taking a screenshot, finding the button with the id 'button', clicking it, and taking another screenshot, then closing the app. Navigate to specific elements using "#id", where id is just the id you gave the shiny input. You can specify a file path to a png file in the takeScreenshot calls, so that you can then use them in your code elsewhere. Note that you may need to use Sys.sleep to stop the screenshots from being taken before the UI updates.


text:
Q: How expensive is an array allocation and initialization? TL;D: How expensive is allocation and initialization of an array of  of relatively large size K, compared to going through such an array, multiplying each float by a fixed float, and writing the result in a different array of size K? E.g. is there a big difference between doing both (allocate, initialize, multiply), or just doing the latter (multiply elements of existing array)?

I'll be recursively traversing through an unknown binary tree of height at most ~50, that has some attributes already set, and I'll be filling out some other attributes. Each node contains an array/list containing around 10k floats, I'll do some operation on all the floats of this array in the node - say multiply them by a float, and then the resulting 10k array will go down to the children.
Now to me the neatest way to implement this would be to actually just declare a tree node class and recursively create the children, etc. Thing is, the values in the node can only really effect the children nodes - so I don't actually need to create an array in each node. Since I have a bound of ~50 on the height of the tree, I could just use 50 arrays, one for each level of the tree. This seems a bit ugly to me though. Also, I'll still have to do the actual operation of a  multiplication, writing down the values, etc - so assuming complexity of initialization and allocation of a new array is linear in the size of the array (and I don't really know if that's true), then I'll still be doing 10k * number of nodes-many operations of multiplication, as opposed to 10k*number of nodes * (multiplication + initialization).
If it is a noticeable difference (which to me, something like say 0.1% difference is not), what would be the right way to use arrays that would keep track of the floats in the current node? Using static arrays would seem like the simplest solutions, but I'm sure that might be considered bad practice. I can't really think of another simple solution.
I was sort of expecting to just make a tree node class, and give it a traversal/"go down" method, keeping all the stuff in one class. But I guess I could make a different class with a function that would recursively traverse the tree, that might be cleaner anyway, as that way the new class could correspond to an actual "tree" object. Then I could just give tree object a field that would contain the arrays for each level.
Alternatively, I could still use just a node class with a traversal method, and just keep passing down a reference to an object with all of the 50 arrays.


text:
Q: ArrayList of arrays vs. array of ArrayLists vs. something similar I'm creating a TableModel which will have a fixed number of columns, but the number of rows will be changing (mostly, increasing as function of time). Which would be better approach to store the data,
ArrayList[] columns = new ArrayList[numberOfColumns];
// Each array element is one column. Fill each of them with a new ArrayList.
...
public Object getValueAt(int row, int column) {
    return columns[column].get(row);
}

i.e. creating an array of ArrayLists, each ArrayList representing one column, or:
ArrayList<Object[]> rows = new ArrayList<Object[]>();
// Each ArrayList element is one row.

public Object getValueAt(int row, int column) {
    return rows.get(row)[column];
}

i.e. creating one ArrayList that holds arrays, each of which represent one row.
Any ideas which of these is more efficient in terms of speed or storage? Alternative 1 requires extending N ArrayLists with each added row, while alternative 2 requires extending just one ArrayList but also creating a new array of length N (to represent the new row). Or is there an obvious, better solution?

A: If the number of columns is fixed then your data is probably row-oriented or at least row-variable at which point each row should be an array. Fixed numbers of columns means you don't need to reallocate your array.
So your structure is:
List<Object[]> rows;

where the array element is one row.
There are several options for what your row object should be however:

*

*An array;

*A List or other Collection; or

*A custom object.

(3) can probably be done by using some kind of interface that allows you to query the number, type and name of columns.

A: How about using a single ArrayList itself and accessing element like this
public Object getValueAt(int row, int column) {
    return data.get(row*NUMBER_OF_COLUMNS+column);
}

In this case, each ArrayList object is a cell in a table. And you need not require any other extra structure

A: I would go with option #2 for several reasons
First, arrays have a fixes length whereas ArrayList are flexible. Given that your #columns is fixes it seems natural to have array per row.
Option #1 is dangerous because it incurs the implicit requirement that all ArrayLists will be of the same length. You may accidentally neglect to add to any one of them thereby creating a bug. You will not have this problem in option #2.
Finally, it seems that the common convetion is that you first index the rows and only then the columns.

A: Personally, I'd go for an ArrayList of fixed-length arrays. If you're talking about a large quantity of rows, this may be more space efficient (and perhaps faster) than allocating a bunch of ArrayLists, which starts out backed by an array of length 10. Thus, if you have fewer columns than 10 you'll end up with wasted space. On the other hand if you have more, then the ArrayList will have to resize its backing array when you add additional columns.
Edit: actually, you can set the capacity in ArrayList's constructor, so I guess it may not make much difference:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html


text:
Q: Why is the download of images blocked when viewing it after Google image search, but not when "open image in new tab"? I've recently searched some images via Google image search:

*

*Search for "oscar the grouch pinterest"

*Click on the first image

*Click on "View image" (or similar, I use the German version)

*Now the URL should be https://s-media-cache-ak0.pinimg.com/736x/3f/c6/03/3fc60371e23e9be6bebce7c392b27bcc.jpg

*Right-click on the image: "Save image as... " or Ctrl + S

*It looks as if it was downloaded, but below the name it denotes "Failed - Blocked"

*Right-click on the image, "Open image in new tab"

*Right-click on the image: "Save image as... " or Ctrl + S
Why does 5 work but not 8? Both have the same url...


text:
Q: How the pipes of water don't freeze in -40 celsius? Does anyone have a good answer how comes that the water in the pipes in our houses doesn't freeze even if it is -40 celsius for a whole week? of course assuming we don't make the water to fluid in it

A: To the points akhmeteli already mentioned there I want to add two reasons:

*

*In larger buildings there will always be someone using water, so the water coming from the ground at approximately 6°C will keep the pipes warm enough

*A brick wall with a thickness of a few centimeter provides already good isolation, so a little bit of heating at the inside will keep the temperature well above the freezing point

Especially the isolation is also true for pipes outside in the ground, the thermal conductivity of soil is so low that in a depth of 2 meters it will stay warm for the whole winter. This does not work in very cold climates though, when it will be below zero all year long. This permafrost can reach down hundreds of meters.

A: There is no such thing as miracles. If water in the pipes does not freeze at -40 degrees Celcius, there is a reason for that. Either the pipes are indoors in heated spaces, or they are heat traced, or they are drained, or they are insulated, or they are buried, or water in the pipes is running (or at least dripping), at least intermittently. I remember such cold (-40 degrees C) in Moscow many years ago. In our 14-storey house, the elevator landings were heated by large, very heavy cast iron radiators. At almost all landings, water in the radiators froze, and radiators burst.


text:
Q: Интеграция с ПОС Госуслуги (витрина), не могу отправить файл csv Кто проходил этот слабо документированный квест, пожалуйста, откликнитесь. Речь идёт о Витрине ПОС Госуслуг, когда статистические данные о городских проблемах и жалобах отправляем из города --> в Москву.  Это вот отсюда
Проблема: при отправке файла CSV на точку /analytic-service/statistic-data получаем ответ null со статусом 400. Пробовали отправлять и на тест, и на прод.
    $url="$gosusREST/analytic-service/statistic-data";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_POST , 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, ['file' => $csv, "type"=>"application/vnd.ms-excel"]);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer '.$resultAuth["access_token"],
        "Content-Type: multipart/form-data",
            ));
    $rawdata=curl_exec($curl);

Ключи авторизации верные, далее получаем валидные токены, и даже приём есть, а передачи нет! Если поломать bearer, сервер ответит

401 {"error":"unauthorized","error_description":"Full authentication
is required to access this resource"}

...то есть сервер жив. Но как понять пустой ответ 400 и что может быть у них не так?

A: Успешный вариант отправки отличается в 3 местах: file, ssl и httpauth. Файл надо предварительно сохранить  на диск.
...
curl_setopt($curl, CURLOPT_POSTFIELDS, ['file' => new CURLFile($tempFilename), "type"=>"application/vnd.ms-excel"]);//только так! а иначе 500
//curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");   //не надо
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 100);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($curl, CURLOPT_HEADER, true);//чтобы выдало заголовки, но они тут неинформативные
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
...

А недокументированный код ответа 400, это если file пытаться послать прямым вложением.


text:
Q: Does GeoLiteCityv6.dat has city and region data in it? We are using GeoLiteCityv6 for detecting ipv6 address in our product.
However, we found that the state/region/city data can't be obtained from the database, while country data is available.
E.g. when resolving the IP address 2a02:2b88:2:1::419a:1 we get Country=Czech Republic, but Region is empty, also city is empty. We checked several IP addresses for and did not get any region/city information.
We are using C API for developing and the API we used are listed below:
GeoIPRecord *gir = GeoIP_record_by_addr_v6(gi, ip);
char *state = (char *)GeoIP_region_name_by_code(gir->country_code, gir->region);
printf("DB: state is %s.\n", state);         //return NULL
printf("DB: continent_code is %s.\n", gir->continent_code);  //right
printf("DB: country name is %s.\n", gir->country_name);  //right
printf("DB: country code is %s.\n", gir->country_code);  //right
printf("DB: region is %s.\n", gir->region);  //return NULL
printf("DB: city is %s.\n", gir->city);     //return NULL

So my question is, does the GeoLiteCityv6.dat NOT have relevant data for region/city, or we misuse the wrong API?
Many thanks here!

A: no, it doesn't have city level info despite it's name. just download the same file in csv format and open it. no city level info.


text:
Q: How to link casper with any storage I need to store tests results in any storage. But unfortunately it doesn't work with any db drivers any time it raise exception "CasperError: Can't find module net":
var require = patchRequire(require);
var redis = require("redis"),
    client = redis.createClient();

Is it possible connect casperjs to any storage (except plain files of course).

A: This may be useful for people having the same challenge
The solution I ended up is writing in a file using the fs module of phantomjs and then executing a redis-cli process with the child_process module. My tests actually import a common module which does the job. The database script is a simple suite of redis commands, one by line. See redis mass insertion for details on redis-cli --pipe.
The runDBScript function imported with var runDBScript = require("dbutils").runDBScript;
exports.runDBScript = function(scriptName) {
         var cp = require("child_process");
         cp.execFile('./dbscripts/exec_db_commands.sh', ["./dbscripts/" + scriptName], {}, function(error, stdout, stderr) {
         casper.echo("Error: " + error);
         casper.echo("Stdout: " + stdout);
         casper.echo("Stderr: " + stderr);
    });
};

The exec_db_commands.sh is a very simple shell script which calls the redis client :
#!/usr/bin/env bash

echo "Executing cat $1 | redis-cli --pipe"
cat $1 | redis-cli --pipe


text:
Q: Python: Converting inches to feet I thought if I made the numbers float that it would give me a number with a decimal.
height = 65.0 / 12.0
print height

What I get back is 5 without the remainder when I use it in a string. Like say:
    print "He is %d tall." % height

A: If you want to stick to the %-formatting use %g to get the decimal places:
In [5]: print("He is %g tall." % height)
He is 5.41667 tall.

You could also define the number of decimal places (e.g. 2 places) like this %.2f:
In [13]: print("He is %.2f tall." % height)
He is 5.42 tall.

The pythonic way to format, however, would be:
In [14]: print("He is {0:.2f} tall.".format(height))
He is 5.42 tall.

Here you can find a nice overview: http://www.python-course.eu/python3_formatted_output.php
EDIT:
cricket_007 is right: OP is using Python2. Thus the correct syntax would be:
print "He is {0:.2f} tall.".format(height)


text:
Q: QMediaPlayer and volume control in decibel I'm rewriting my music player from Qt4 to Qt5. I switched from Phonon to QtMultimedia. I now have a serious problem with volume control. To support ReplayGain, I read the tags from media files and then change the volume with every track to keep it equal.
In phonon I use setVolumeDecibel because the volume differences stored in tags are in dB. But in QtMultiMedia I can not use it. The QMediaPlayer class only has a setVolume function. Is there any other possibility how I could control the volume in dB? What is the calculation for setVolume internally? Maybe I could reverse it to set the volume in dB.
Or do you have any other advice what I should do?


text:
Q: Why is the conditional probability treated as a definition in Kolmogorov's probability theory? The conditional probability is defined as:
$$P(A|B) = \frac {P(A \cap B)} {P(B)}$$
given that $$P(B) \neq 0$$
This is achieved based on our intuition, along with the Venn diagram description of the sample space $\Omega$, the event $A$, the event $B$ and the intersection of $A$ and $B$.
My question is: why can't we treat the conditional probability as the corollary of the axioms of the probability theory, instead of treating it as a separate definition? Additionally, based on this point of view, it is seen that the Bayesian rule is almost as trivial as a definition.
My takeaway is, for any event $X$, defined on the probability space $(\Omega, \sigma, P)$, $P(X)$ could always be defined as a conditional probability:
$$P(X) \equiv P(X | \Omega)$$
Am I on the right track, or am I missing something important? Thanks!


text:
Q: Gulp useref concatenates js files twice I have such  gulp task
 gulp.task('html', [], function() {
    var partialsInjectFile = gulp.src(options.tmp + '/partials/templateCacheHtml.js', {read: false});
    var partialsInjectOptions = {
        starttag: '<!-- inject:partials -->',
        ignorePath: options.tmp + '/partials',
        addRootSlash: false
    };

    var htmlFilter = $.filter('*.html');
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');
    var assets;

    return gulp.src(options.tmp + '/serve/*.html')
        .pipe($.inject(partialsInjectFile, partialsInjectOptions))
        .pipe(assets = $.useref.assets())
        .pipe($.rev())
        .pipe(jsFilter)
        .pipe($.ngAnnotate())
        .pipe($.uglify({preserveComments: $.uglifySaveLicense})).on('error', options.errorHandler('Uglify'))
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe(assets.restore())
        .pipe($.useref())
        .pipe($.revReplace())
        .pipe(htmlFilter)
        .pipe($.minifyHtml({
            empty: true,
            spare: true,
            quotes: true,
            conditionals: true
        }))
        .pipe(htmlFilter.restore())
        .pipe(gulp.dest(options.dist + '/'))
        .pipe($.size({title: options.dist + '/', showFiles: true}));
});

Generated by gulp angular yeoman, but I did some changes to isolate it from other tasks and localize problem.
The problem is, that after all concatenations produces app-%%%.js file contains dublicate code:
original code e.g. and minified one
 function() {
    "use strict";
    function e(e, t) {
        return e(t + "/something", {}, {get: {method: "get", isArray: !0}})
     }

    angular.module("app.mappings").factory("Something", e), e.$inject = ["$resource", "API_ROOT"]
    }(),

 angular.module("app.mappings").factory("Something", Something), Something.$inject = ["$resource", "API_ROOT"]

This breaks my application.
Can someone help understand what's wrong with this build task?
P.S It seems that scripts injected in html look like
<script src="app/mappings/mappings.module.js"></script>

and both .tmp/serve/ directory and src/ directory has the same structure. Useref searches both and duplicates happen

A: I realize the question is kind of old, but I've just came across the same problem.
The reason for duplicates was the line in index.html:
<!-- build:js({.tmp/serve,.tmp/partials,src}) scripts/app.js -->
...
<!-- endbuild -->

Gulp-useref looks for these lines and converts them like so:
From:
<html>
<body>
    <!-- build:js scripts/combined.js -->
    <script type="text/javascript" src="scripts/one.js"></script>
    <script type="text/javascript" src="scripts/two.js"></script>
    <!-- endbuild -->
</body>
</html>

To:
<html>
<body>
    <script src="scripts/combined.js"></script>
</body>
</html>

It looks for the script files in paths based on the comment

build:js({.tmp/serve,.tmp/partials,src})

So in this case in 3 locations:

*

*.tmp/serve

*.tmp/partials

*src

If your build scripts copied the files from src to .tmp/serve in meantime, useref found the files in both locations and so pasted them 2 times to the result file. So the fix is either to modify your build scripts not to copy the files or change that line in index.html to:
<!-- build:js(.tmp/serve) scripts/app.js -->

I guess it might not be the help for you after 5 years, but hopefully someone else will find it useful.


text:
Q: How to fix this hyperref warning? I have something like:
\subsection{FooBar-$\mu$Something}

and I get a warning:
Package hyperref Warning: Token not allowed in a PDF string (PDFDocEncoding): (hyperref) removing `\mu' on input line 267.

What is going on? Why I cannot use a greek letter in my subsection title? Any suggested fix?

A: From your source code a pdf-file gets created.
Fonts get embedded for displaying the text of your document.
But there are things where these fonts are not relevant.
That is the case, e.g., with the hyperlinks within the bookmarks.
The bookmarks do not belong to the pages that form the document.
They are something extra, and they are there for making navigating through the document more easy.
The text related to a bookmark is displayed using a font that comes from the programs/platforms used for displaying the pdf-file.
Those characters that form text related to a bookmark must be encoded in an encoding which the programs/platforms used for displaying the pdf-file do understand and whose characters the programs/platforms used for displaying the pdf-file can display.
There currently are two such encodings known to me: PdfDocEncoding and Unicode (UTF-16 Big Endian).
These two encodings do represent single characters by byte-sequences.
Sequences of characters in turn that belong together are called strings.
Those strings which (La)TeX during creation of a pdf-file must include into the pdf-file either encoded in PdfDocEncoding or encoded in Unicode so that the programs/platforms used for displaying the pdf-file in question can process/display them properly, e.g., for displaying bookmarks with hyperlinks, are in TeX-jargon called pdf-strings.
Thus you need to ensure that (La)TeX delivers pdf-strings (, e.g., text that goes into the bookmarks and thus is to be processed by the programs/platforms used for displaying the pdf-file,) as plain-text in one of these two encodings.
When you use (La)TeX for creating pdf-files, the encoding of the .tex-input-files you type most likely is not PdfDocEncoding, and TeX-engines other than LuaTeX and XeTeX also don't have built-in support for .tex-input-files in some Unicode-encoding. Common input-encodings are latin 1 and ansinew and the like.
Therefore the hyperref-package does provide the macro \texorpdfstring.
This macro takes two arguments. In situations of ordinary TeX-processing it delivers the tokens contained in the first argument untouched. In situations where a string needs to be delivered in PdfDocEncoding or UTF-16-Big-Endian-Encoding, so that programs/platforms used for displaying the pdf-file can properly process/handle/display it, the tokens contained in the second argument are delivered. But that is not all: \texorpdfstring also makes sure that the things contained in the second argument get re-encoded properly. This re-encoding is necessary because the encoding of the .tex-input-file is not necessarily PdfDocEncoding or UTF-16-Big-Endian. \texorpdfstring also provides alternative ways of handling things: E.g., at the time of compiling a .tex-input-file for creating a pdf-file, there is a LaTeX-compiler which obeys directives like $ or $$ for switching to math-mode and leaving math-mode. But at the time of displaying the pdf-file, there is no LaTeX-compiler. There is the program/platform used for displaying the pdf-file. This program does not care about directives which were intended for the LaTeX-compiler at the time of compiling the .tex-input-file and creating the pdf-file. Thus this program will not understand directives like $\mu$. Thus within the second argument of \texorpdfstring you can omit all those things which the LaTeX-compiler does understand but the program/platform used for displaying the pdf-file does not understand.
Within pdf-strings and thus within the second argument of \texorpdfstring you can escape bytes by a backslash trailed by a three-digit-number (with leading zeros if necessary) denoting the value of the byte in question in octal notation.
In case the escape-octal-representation of a byte denotes the higher byte of a UTF-16-Big-Endian-character, within the second argument of \texorpdfstring it is a convention to prefix that 3-octal-digit-sequence with the digit "9".
This can be done because "9" is not a digit of the octal system.
Another convention with the octal-representation of the higher byte of an UFT-16-Big-Endian-character within the second argument of \texorpdfstring is: In case octal representation of the higher byte has two leading zeros, you can, instead of \900⟨single octal digit⟩ do \8⟨single octal digit⟩.
When loading the hyperref-package, pdf-strings usually need to be encoded in PdfDocEncoding.
In PdfDocEncoding (see http://www.verypdf.com/document/pdf-format-reference/pg_1001.htm), there is a Micro-Sign which is assigned to code-point number 181(dec) = 265(oct).
When you provide the option unicode=true to the hyprref-package,  pdf-strings need to be encoded in Unicode (UTF-16 Big Endian).
In Unicode (see  https://dev.w3.org/html5/html-author/charref), there is μ, which is assigned to code-point number 956(dec).
For finding the bytes of that code-point-number's UTF-16-Big-Endian-representation, let's write that code-point-number in the base 256:
956(dec) = 3(dec) * (256(dec)1(dec)) + 188(dec)* (256(dec)0(dec))
Thus in UTF-16 (Big Endian), μ is encoded with two bytes whereof the higher byte has the value 3(dec) and the lower byte has the value 188(dec).
Let's express the values of each of these bytes in 3-digt-octal notation:
Higher byte's value = 3(dec) = 003 (oct)
Lower byte's value = 188(dec) = 274 (oct)
The facility of escaping the encoding of characters of pdf-strings via octal-sequences is nice because it offers a way of writing characters of pdf-strings in PDFDocEncodng or UTF-16 Big-Endian without the need of the .tex-input-file being written in the same encoding.
Even in ASCII the digits 0..9 and the backslash are available...
When loading the hyperref-package without option unicode, you can within pdf-strings use PDFDocEncoding and hereby escape characters not contained in the encoding of your .tex input-file by their byte-wise representation in octal-notation:
\documentclass{article}
\usepackage{hyperref}
\begin{document}

\tableofcontents

\section{\texorpdfstring{$\mu$}{\265} Something}

\end{document}

When loading the hyperref-package with option unicode, you can within pdf-strings use unicode-encoding and hereby escape characters not contained in the encoding of your .tex input-file by their byte-wise representation in octal-notation:
\documentclass{article}
\usepackage[unicode]{hyperref}
\begin{document}

\tableofcontents

\section{\texorpdfstring{$\mu$}{\9003\274} Something}

\end{document}


text:
Q: How to update bower.json file to reflect changes when uninstalling a specific package(s)? How to update bower.json file to reflect changes when uninstalling a specific package(s)?

A: Use -S or --save:

-S, --save              Remove uninstalled packages from the project's bower.json dependencies

You can check other options with bower uninstall --help.

A: Just for more clearness and depending of @mziccard answer, to update the bower.json file with the uninstalled packages, use the next command in your terminal:
To uninstall one package..
$ bower uninstall <package_name> --save

And to uninstall multiple packages (3 for example), you can use the above command 2 more times, each time with its package_name or you can use the next one line command:
$ bower uninstall <package_name1> <package_name2> <package_name3> --save


text:
Q: $injector:modulerr while using angular-chartist Just added angular-chartist to my app and am now getting the following error:
Failed to instantiate module routerApp due to:
Error: [$injector:modulerr] http://errors.angularjs.org/1.3.14/$injector/modulerr?p0=...)
    at Error (native)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:6:417
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:35:320
    at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:7:302)
    at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:34:399)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:35:63
    at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:7:302)
    at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:34:399)
    at ab (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:38:135)
    at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:17:381

I think this error occurs when I define the angular app:
//define Angular app
var routerApp = angular.module("routerApp", ["ui.router", "angular-chartist"]);

Did I set up something incorrectly?
The following code also deals angular-chartist:
//draw chart
var drawChart = function(results) {
    var data = {
        labels: [],
        series: []
    }

    for (var i = 0; i < results.length; i++) {
        data.labels.push(results[i].trait);
        data.series.push(results[i].normalized);
    }

    new Chartist.Bar('.ct-chart ct-perfect-fourth', data);

};

You can find docs for angular-chartist here

A: Make sure you also include chartist.js in your index.html, anywhere before angular-chartist:
<script type="text/javascript" src="bower_components/chartist/dist/chartist.min.js"></script>


text:
Q: Image Fonts with MvvmCross binding I'm working on a mobile app (for android and ios) using mvvmcross w/ xamarin.  There is a screen where the users want to use their custom images for numbers 0-9, for a numeric field.  For example if the number is 123, there would be 3 images on the screen, an image for 1, for 2, and 3.  What would be the best way to wire up the solution for this?
Off the top of my head I am thinking the following:
1) Encourage them to use text stylings instead of custom images.  The issue here is that a legacy version of the app already exists and uses the images.  They might have spent a lot of time on those images and may be dead set on using them.  Still if it is a bad practice and I can do something similar with styles, I wouldn't be opposed to trying to sway them this direction.  The images have a gradient shadowing that I'm guessing would be hard to duplicate.
2) Use an image for each digit.  Use a custom converter to convert the digit (0-9) to the corresponding image.  So the model would contain Digit1, Digit2, Digit3, etc.  Hide digits that don't apply (ie shorter numbers).  I'm not sure of the feasibility of this, or how I would deal with hiding elements, or handling things such as if the padding needs to be different based on the number.
3) Do everything completely on the UI side of things.  It's been done before on the native app so I believe this is doable.  I just need to implement it using C# instead of objective C, and would need to implement it twice (once on IoS, once on Android).

A: To me, the important thing here is that 'the app is king'
The general app approach is to let the User Experience to drive the technology choice - and often you operate a 'no compromise' policy on User Experience!
(Obviously though, sometimes there can be a little compromise when costs start to escalate).
I think all 3 of your options could work.
Personally I suspect I might go for your 3rd option - drawing a custom data-bound view provides the most flexibilty and the most native solution for your app. For more on custom data-bound views see N=18 and N=19 in http://mvvmcross.wordpress.com/

*

*An Android custom data-bound View - http://slodge.blogspot.com.au/2013/05/n18-android-custom-controls-n1-days-of.html

*An iOS custom data-bound UIView - http://slodge.blogspot.com.au/2013/05/n19-custom-controls-on-ios-n1-days-of.html
I think these custom controls could easily reuse your number images, and would be fairly easy to size, animate, etc. - in order to provide the beautiful app experience your customer is looking for.


text:
Q: Make box vertically in middle How i make div with different sizes vertically in middle of page.
For example with 100px height.
like windows 8 messages.
Thnk you.
Mohammad.

A: If I understand the question, this is how one of the options  DEMO

text

text

text

text

text

text

text

text

.wrap {
  width: 800px;
  margin: 0 auto;
  background: #ccc;
  display:block;
  overflow: hidden;
  padding: 100px 0 0 0;
}
.block {
  width: 100px;
  height: 50px;
  background: green;
  margin: 10px auto;
  display:block;

}
.block:nth-of-type(2) {
  height: 80px;
}
.block:nth-of-type(4) {
  height: 150px;
}
.block:nth-of-type(7) {
  height: 20px;
}

A: If you don't need to support decrepit browsers, this is probably the easiest way. The dimensions of the element don't matter:
.vert_element {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

DEMO

A: Use margin:auto in combination with position: absolute. Then declare all the left/top/right/bottom as zero.
It only works if you have added a height in your css.
It doesn't work for variable heights.
See this fiddle http://jsfiddle.net/mBBJM/1/


text:
Q: GTest: Handle Segmentation Fault I'm using GTest for unittesting my project.
One of the functions I want to test terminates with a Segmentation Fault, which is is not the correct behavior of this function.
I want gtest to report this error, like every other error, but it doesnt. It doesnt run other test cases and it doenst print a report at the end.
It there a way to get a correct report from gtest for this kind of behavior?

A: You didn't link any code example, so the best answer I can give you is very general.
Your problem is either:

*

*Your function is incorrect and is segmentation faulting (edge cases or main body)

*You wrote your test badly, and it (the test itself) is segmentation faulting

Seg Faulting happens when your program/test tries to do something it isn't allowed to do (i.e.. you try to dereference a null ptr, access memory that isn't yours, etc..). Google Test is not able to handle the signal SIGSEGV (nobody is), so your program will crash. Seg Faults are the operating systems way of telling you that you did something illegal and they instantly terminate your program. You need to fix the segmentation fault in order to get results. I would recommend doing the following things:

*

*Learn how to use GDB, and run your program in GDB to figure out where it is segmentation faulting

*Use print statements to figure out where your program is segmentation faulting.


text:
Q: How to extract the data from Generic  List object I wanna create the generic function inwhich I will just pass the class name and get the data in CSV format that is from JSON object on the bases of Generic Class Type.
But I am not able to access the class  member while foreach loop.
public class Lifetouch
{
    public int LifetouchID { get; set; }
    public string Data { get; set; }
}

public class Lifetemp
{
    public int LifetempID { get; set; }
    public string Data { get; set; }
}

main()
{
    getPerodicListofVitalSigns <Lifetouch>(new Lifetouch());
}

public static void getPerodicListofVitalSigns <T>( T clazz)
{
    List<T> list_of_measurements_Original = JsonConvert.DeserializeObject<List<T>>(json_response);

    // Got the list_of_measurements_Original count 2.

    StringBuilder sb = new StringBuilder();
    sb.Append("[");

    foreach (var element in list_of_measurements_Original)
    {
        sb.Append(element.LifetouchID + ", ")  // Not able to access the element of list LifetouchID
    }
    sb.Append("]");
 }

A: I would like to create the generic function inwhich I will just pass the class name and get the data (ID's) in CSV format that is from JSON object on the bases of Generic Class Type. That all the ids will pass through webservice and update the database. Its the requirement.
I would like to create the Generic function in which I would like to pass the class name as a paramenter. So in future its easy for me to use that generic function if new class added.
Now its working fine..
public class Lifetouch
{
    public int LifetouchID { get; set; }
    public string Data { get; set; }
}

public class Lifetemp
{
    public int LifetempID { get; set; }
    public string Data { get; set; }
}

main()
{
    getPerodicListofVitalSigns <Lifetouch>(new Lifetouch());
    getPerodicListofVitalSigns <Lifetemp>(new Lifetemp());
}
public static void getPerodicListofVitalSigns <T>( T clazz)
{
    List<T> list_of_measurements_Original = JsonConvert.DeserializeObject<List<T>>(json_response);

    // Got the list_of_measurements_Original count 2.

    StringBuilder sb = new StringBuilder();
    sb.Append("[");

    foreach (var element in list_of_measurements_Original)
    {
         if (VitalSignName == "Lifetouch")
                            {
                                var vitalSign = element as Lifetouch;
                                dataString = dataString + (vitalSign.LifetouchID + ",");
                            }
                            else if (VitalSignName == "Lifetemp")
                            {
                                var vitalSign = element as Lifetemp;
                                dataString = dataString + (vitalSign.LifetempID + ",");
                            }
    }
    sb.Append("]");

    string WebserviceAddress = "192..../json/reply/UpdateSyncStatus";
    JSON_POST_Sender.ClassPost(WebserviceAddress, dataString), "true")
 }


text:
Q: Trabalhando com dados do Excel no C# Necessito criar uma aplicação que leia uma pequena sequencia de dados disponibilizados cada em uma coluna do Excel.
A minha dúvida é se o melhor caminho é tratar direto no SQL fazendo upload do arquivo e depois tratando com uma procedure ou então trabalhar com os dados no C# e enviar os mesmos a cada coluna da minha tabela do SQL.
Tratando do lado do C# acredito que consigo ter mais segurança com relação ao o que estou enviando ao banco, dei uma lida nessa questão: https://stackoverflow.com/questions/657131/how-to-read-data-of-an-excel-file-using-c mas não compreendi muito bem.
Para o exemplo de procedure estou utilizando esse artigo como base: http://www.aspsnippets.com/Articles/How-to-Import-Excel-Sheet-data-into-SQL-Server-using-ASPNet.aspx

A: Não é aconselhável regras de negócio no banco de dados! Somente por este motivo o ideal seria você usar C#.
Recomendo a biblioteca: LinqToExcel
Você consegue ler arquivos Excel de forma bem intuitiva:
var excel = new ExcelQueryFactory("excelFileName");
var indianaCompanies = from c in excel.Worksheet<Company>()
                       where c.State == "IN"
                       select c;


text:
Q: How to compile/install mplayer on MacOS with subtitle support? In order to play video files with a sub title file on MacOS 10.13.6 on the command line: How to install mplayer so that I am able to use subtitles?
I tried the following suggestion made in some other post:
brew uninstall mplayer
brew reinstall freetype
brew reinstall fontconfig
brew install --build-from-source mplayer

The last command provoked an error:
Error: Xcode alone is not sufficient on High Sierra.
Install the Command Line Tools:
  xcode-select --install

and so I did install the Command Line Tools. Then I repeated the mplayer install command. It was installed with the following configure line:
./configure --cc=clang --host-cc=clang --disable-cdparanoia --prefix=/usr/local/Cellar/mplayer/1.3.0 --disable-x11

But then running the command as follows
mplayer  testvideo.mkv  -sub SubTest.srt

with the content of SubTest.srt as follows:
1
00:00:00,000 --> 00:00:05,000
TEST TEXT

does NOT show any subtitle, nor any error.
The output of brew info mplayeris:
mplayer: stable 1.3.0 (bottled), HEAD
UNIX movie player
https://mplayerhq.hu/
/usr/local/Cellar/mplayer/1.3.0 (11 files, 28.8MB) *
  Built from source on 2019-01-11 at 07:40:20
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/mplayer.rb
==> Dependencies
Build: yasm ✔
Optional: libcaca ✘, libdvdnav ✘, libdvdread ✘
==> Options
--with-libcaca
    Build with libcaca support
--with-libdvdnav
    Build with libdvdnav support
--with-libdvdread
    Build with libdvdread support
--HEAD
    Install HEAD version
==> Analytics
install: 1,198 (30 days), 3,569 (90 days), 15,129 (365 days)
install_on_request: 1,140 (30 days), 3,408 (90 days), 14,307 (365 days)
build_error: 0 (30 days)

What else can I try? I rather would not like to install and use a virtual box ...


text:
Q: Multiple jQuery libraries gives conflict I have a problem using multiple jQuery and js plug-ins and they seem to get in conflict. This is the error I get from the console:
"Uncaught TypeError: undefined is not a function"
Directing me to main.js > ($.scrollTo(scrollPosition + "px", 800, { axis: 'y' });)
The problem occurred when I was trying to add a slider (slick) to my webpage. Can someone help me with this problem individually?
The code just before closing my  tag looks like this:
    <script src="js/vendor/jquery-1.11.1.min.js"></script>
    <script src="js/vendor/jquery.scrollTo-1.4.3.1-min.js"></script>

    <script src="js/plugins.js"></script>
    <script src="js/main.js"></script>
    <script src="js/detail.js"></script>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script type="text/javascript" src="js/slick/slick.min.js"></script>
    <script>
        $(document).ready(function(){
            $('.single-item').slick();
              //setting-name: setting-value
        });
    </script>
</body>

A: You do not need a different inclusion of jQuery for each plugin, 1 is enough.
    <script src="js/vendor/jquery-1.11.1.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="js/vendor/jquery.scrollTo-1.4.3.1-min.js"></script>

    <script src="js/plugins.js"></script>
    <script src="js/main.js"></script>
    <script src="js/detail.js"></script>
    <script src="js/slick/slick.min.js"></script>
    <script>
        $(document).ready(function(){
            $('.single-item').slick();
              //setting-name: setting-value
        });
    </script>
</body>

The only exception is when you're trying to use a plugin written for say, jQuery 1.2.6 that isn't at all compatible with the latest version. However, i would suggest instead finding a new plugin in that case.


text:
Q: Set Friday as Weekend day in moment() Is there any way to set "Friday" as a weekend day in moment() globally.
I am using moment and moment-business plugin in node.js
I need to consider 3 days as Weekend (Friday, Saturday and Sunday) and 4 days as Weekday (Monday, Tuesday, Wednesday, Thursday).
const moment = require('moment');
const business = require('moment-business');


text:
Q: How to set an ID in Multi Dimensional array as per parent-child relationship I have a multidimensional array in Parent-Child format.
I want to add a new id in the array. The new id  'TTID' will be set in the order of Parent-Child. Meaning if ParentTTID is 1 then Child TTID should be  2, and its child should be 3.
So it's in order of Parent->Child->CHild. with unlimited levels of depth. Now the New Parent node id will start from last child's ID say 4 and its child will be 5 and so on
Array
(
    [0] =Array
        (
            [id] =0
            [value] =Total Income
            [parent] =-1
            [ttid] =1
            [children] =Array
                (
                    [0] =Array
                        (
                            [id] =2
                            [value] =Total Contributions
                            [parent] =0
                            [ttid] =0
                            [children] =Array
                                (
                                    [0] =Array
                                        (
                                            [id] =5
                                            [value] =Total Employers Contributions
                                            [parent] =2
                                            [ttid] =0
                                            [children] =Array
                                                (
                                                    [0] =Array
                                                        (
                                                            [id] =10
                                                            [value] =Employes unclassfied Contributions
                                                            [parent] =5
                                                            [ttid] =0
                                                        )

                                                )

                                        )

[1] =Array
    (
        [id] =1
        [value] =Total Expenses
        [parent] =-1
        [ttid] =0
        [children] =Array
            (
                [0] =Array
                    (
                        [id] =4
                        [value] =Total Benifit Payments
                        [parent] =1
                        [ttid] =0
                        [children] =Array
                            (
                                [0] =Array
                                    (
                                        [id] =9
                                        [value] =Directly to Participant
                                        [parent] =4
                                        [ttid] =0
                                        [children] =Array
                                            (
                                                [0] =Array
                                                    (
                                                        [id] =14
                                                        [value] =Some participant
                                                        [parent] =9
                                                        [ttid] =0
                                                    )

                                            )

                                    )

                            )

                    )

            )

    )

)
I tried to solve this using a method where I send 1 parent node Id at a time so that all its child will get marked. However, it doesn't seem to be working and it also gives me a warning:  Cannot use a scalar value as an array in the line
function treetable_markRowChildren($elements,$parentId,$new_id)
{
  $i = 1; $arr=array();
    foreach ($elements as $element)
    {
        if ($element['parent'] == $parentId)
          $element['ttid'] = $new_id+$i; // The Error is shown in this line
          $i=$i+1;
          $new_id=$element['ttid'];

         if(isset($element['children']))
             {
             $parentId=$element['id'];
            $arr2= treetable_markRowChildren($element,$parentId,$new_id);
         }
        else
             break; //No CHildren

      $arr=$element;

    }

  return $arr;
}

I just want the TTID to be set in this sequential format. How do I achieve this?
Thanks in advance.
Array
(
    [0] =Array
        (
            [id] =0
            [value] =Total Income
            [parent] =-1
            [ttid] =1
            [children] =Array
                (
                    [0] =Array
                        (
                            [id] =2
                            [value] =Total Contributions
                            [parent] =0
                            [ttid] =2
                            [children] =Array
                                (
                                    [0] =Array
                                        (
                                            [id] =5
                                            [value] =Total Employers Contributions
                                            [parent] =2
                                            [ttid] =3
                                            [children] =Array
                                                (
                                                    [0] =Array
                                                        (
                                                            [id] =10
                                                            [value] =Employes unclassfied Contributions
                                                            [parent] =5
                                                            [ttid] =4
                                                        )

                                                )

                                        )

    [1] =Array
        (
            [id] =1
            [value] =Total Expenses
            [parent] =-1
            [ttid] =4
            [children] =Array
                (
                    [0] =Array
                        (
                            [id] =4
                            [value] =Total Benifit Payments
                            [parent] =1
                            [ttid] =6
                            [children] =Array
                                (
                                    [0] =Array
                                        (
                                            [id] =9
                                            [value] =Directly to Participant
                                            [parent] =4
                                            [ttid] =7
                                            [children] =Array
                                                (
                                                    [0] =Array
                                                        (
                                                            [id] =14
                                                            [value] =Some participant
                                                            [parent] =9
                                                            [ttid] =8
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

)


text:
Q: full list of all subscripts and diacritical marks in unicode Answered: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt is a a list of all unicode chars, and 0xcc99 # U+0319 COMBINING RIGHT TACK BELOW is somewhat like a comma for a monospaced font..(example: 10̡9̡8̡7̡6̡5̡4̡3̡2̡1̡0̡ )
Is there a complete list of all unicode characters along with their verbal descriptions, e.g. a list of lines like
...
0xcc99  #  U+0319       COMBINING RIGHT TACK BELOW
..
Particularly, what diacritical mark do I use to type 1. or 2o3 ?
The motivation is that I want to be able to add a point or comma in
a monospace font in a terminal, without actually adding a character.

A: There is no complete list of all Unicode characters along with their verbal descriptions, not even a list of them with their Unicode names. The UnicodeData.txt files refers to large ranges of characters generically, e.g.
4E00;<CJK Ideograph, First>;Lo;0;L;;;;;N;;;;;
9FCB;<CJK Ideograph, Last>;Lo;0;L;;;;;N;;;;;

and
AC00;<Hangul Syllable, First>;Lo;0;L;;;;;N;;;;;
D7A3;<Hangul Syllable, Last>;Lo;0;L;;;;;N;;;;;

It would be possible to construct a complete list with Unicode names, but what would be the purpose? The Unicode names, such as COMBINING PALATALIZED HOOK BELOW, are identifiers, not descriptions. Taken as English texts, some of them are intuitively descriptive, some are very vague, some are obscure, and some are outright wrong—and will never be changed, due to the stability principle. The principle is largely necessitated by the use of Unicode names in programs; they must not be changed, for the same reasons why the Unicode numbers must not be changed.
Some of the Unicode names for diacritics, too, are misleading or at least incomplete. The shape of a diacritic cannot be inferred from the Unicode name alone, and the shape may even vary a lot (e.g., t with caron is ť in lowercase, with the diacritic looking like a conna, whereas the corresponding uppercase letter Ť has... well, a caron-like caron).
Using characters like U+0319 and U+0321 in your text data implies that will require a relatively extensive font and relatively advanced rendering software that displays combining diacritic marks well. Moreover, if you intend to use them in meanings and contexts they were not intended for (they are meant for use in phonetic notations where they are associated with letters to indicate features of pronunciation), you may need poor software that implements them improperly (considering the intended use and rendering). For example, U+0319 is supposed to appear below a letter

A: Yes, it's on the CD that comes with TUS, or downloadable from unicode.org: the Unicode Character Database.

A: "my application is as follows: sometimes I work in command line in xterm with programs that output long numbers I find hard to read. So I want to use diacritics to add dots or commas so that 2938485860 becomes 2.938.485.860 and formatting is preserved. U+0321 is not really good for that...."
If you want to add periods to numbers inline, there's a way to do it. In unicode, there's the set of "Enclosed Alphanumerics", which includes numbers with trailing periods.
2.938.485.860 -> ⒉93⒏48⒌860
Note that in a terminal, these may be unreadable. You could alternatively try

*

*2⑨38④85⑧60 - using circled numbers on every third digit (ugly too)

*2̲9384̲8̲5̲860 - using - underlined characters

*2388560 - changing some digits to a "MATHEMATICAL SANS-SERIF BOLD DIGIT"


text:
Q: Custom CNN tuning for detecting vertical vector patterns in an image I have NxN images composed from time series data, for each horizontal axis stands for time and vertical axis stand for features.
Order of the features are also attention based, and important. So, order of pixels in each column are very related with the class, and should be handled as "one-column as a whole".
In this context, different vertical slices may be related to different 10 classes, the most frequent class detected among N columns would be the final class of the NxN image.

*

*What is the correct approach to search Nx1 patterns in this problem?

*Is it possible to classify each column with a DNN-like model and use the output probabilities for each class as an input of another classifier (and how)?

*Or a fine-tuned CNN would work better?

Thanks for any comment.


text:
Q: Has anyone designed a low noise amplifier in the ISM band (24 GHz) using the discrete fet CEL CE3520K3? I have been trying to design an LNA in the 24 GHz ISM band using CE3520K3.
The FET is inherently unstable and one cannot use resistor loading at the input, resistive loading at the output, source inductor or drain gate feedback (RLC) circuit to stabilize the FET.
The only way to stabilize it is probably to use a bandpass filter at 24 GHz, with a very low bandwidth.
This filter might be used at its out- or input, but the best way might be to use it at the FET's output to preserve the noise figure.
Another limitation at 24 GHz is that there are no capacitors that behave like capacitors (i.e. the series resonant frequency of the capacitors is much less than 24 GHz). So has anyone designed an LNA using CE3520K3?

I have designed filters at 24 GHz using AWR MWO and Ansys HFSS. I can make the amplifiers stable using a bandpass microstrip filter. Also, I am using interdigital microstrip capacitors for blocking the DC. For dc bias at the gate and the drain, I am using quarterwave microstrip lines  to get an RF open.
I have asked the guys at CEL for an application note or any circuit that they have used to design the LNA. But they do not seem to have any application note or a circuit.
This is the plot of the input and output stability circles. You can see that the pink color plots are the input stability circles and the blue color plots are the output stability circles. These circles are plotted in AWR MWO.


text:
Q: XML Schema : substitution groups I'm investigating substitution groups in XML schema and I can't seem to find the official spec. can anyone point me to it ?
I'm wondering if an element with substitution group attribute can replace an element inside a complex or only global elements as w3schools claims :

"Note that all elements in the
  substitutionGroup (the head element
  and the substitutable elements) must
  be declared as global elements,
  otherwise it will not work!"

is the above statement true ?
since global elements can each be a root of the XML instance - what is the point of defining substitution groups on them ?

A: Substitution groups are a very complex beast. Essentially, what it gives is an alternative way of expressing <xs:choice> structures, without having to list all of the possible choices. This means you can come along at a later date and additional options to the choice, without having to modify the original schema.
The use cases where this is actually useful are very few and far between, being limited to schemas that are designed to be extensible by 3rd parties. In reality, they are very hard to work with, and very hard to understand (see here for more reasons to avoid them).


text:
Q: Forcing 5 GHz on MacBook Pro I currently have the retina MacBook Pro running OS X lion and want to force the wireless card to only connect only to 5GHz networks.
Both the 2.4GHz and 5GHz have the same SSID so I can not pick which band the wireless card connects to.
Notes:
I live in a college dorm, so renaming networks is not an option.
They do not have 2 different names in the preferred networks list.
The network also needs a 802.1X profile to connect to the network. (I can modify it if needed)
The security is TTLS with PAP.

A: Apple does not provide an API for forcing the band selection.
If you're seeing a bug or suboptimal behavior out of the band selection algorithm, it might be interesting to see the output from the "Wi-Fi" section of a full System Profiler report, because that'll show your current connection as well as the signal strength and other parameters of the other APs around you.
Well, on second thought, I suppose that only scratches the surface, because that wouldn't show how busy those other channels are, and it wouldn't show the effects of non-Wi-Fi interferers.

A: Did you try to manually set the wifi channel number?
If you want just to change from one frequency band to another then you can try the partial solution which I provide below. This worked for me (OSX Mavericks). Basically, if the frequency bands have different channel numbers then setting the channel number of the desired frequency will enable it. You can change the channel number using the airport, but first check if 2.4 and 5 GHz have different channel numbers:

*

*Open Wireless Diagnostics.app (it is located in
/System/Library/CoreServices/Applications).

*In the application menu select Window->Utilities (or press cmd+2).Utilities window should appear.

*Select WiFi Scan from Utilities window and press Scan Now button. This will show you all available networks, info about them and your active connection.

*Now, verify that BSSIDs of 2.4 and 5 Ghz with the same
network name are on different channel numbers. If so, then most likely you can change the band by setting the channel number of the desired frequency band.

*For this, open the Terminal.app and type: sudo /System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport --channel=num where num is the channel number to set. This command will only work under administrator account (so make sure that you are log as an Administrator i.e. su YourAdministratorAccount)

*You can check your active connection by re-scanning with Wireless Diagnostics or Alt+Click on the WiFi icon on OSX the menu bar.

That's it!
P.S. If you can not set the channel try to turn off the wifi device before using the airport command.
As suggested by 8bittree, the instructions were included here from this post.


text:
Q: Scrolling tabs like this? The Android developer site shows an example in Providing Descendant and Lateral Navigation Figure 7 (Labels/third one down in the image) which I'd like to use in my app. I can't find any reference to how to make this effect. The closest I found was a post in reference to the second item (tick marks) here. Is this supported in Android or is there a library I could use?

A: You should look into ViewPager with FragmentPagerAdapter. Here is an example showing how to do so.
Here is another example from the android developer site
Finally from Jake Wharton an example with different icons and views for tabs to help you understand how to customize the view.
In case these links die in the future here is the main part from the developer site:

You can create swipe views in your app using the ViewPager widget, available in the Support Library. The ViewPager is a layout widget in which each child view is a separate page (a separate tab) in the layout.
To set up your layout with ViewPager, add a  element to your XML layout. For example, if each page in the swipe view should consume the entire layout, then your layout looks like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

To insert child views that represent each page, you need to hook this layout to a PagerAdapter. There are two kinds of adapter you can use:
FragmentPagerAdapter
This is best when navigating between sibling screens representing a fixed, small number of pages.
FragmentStatePagerAdapter
This is best for paging across a collection of objects for which the number of pages is undetermined. It destroys fragments as the user navigates to other pages, minimizing memory usage.


text:
Q: How can you determine if a Coffeescript script is being run as a script vs being required in a module? I have a coffeescript file with code I'd like to be requirable by other scripts, but I also would like it to be run as a standalone script.
What is the most reliable way to determine if it's being required by another script vs being run directly?
e.g.
require("./myScript.coffee")
vs
coffee ./myScript.coffee

A: is this on node? if so here are two options
A) using the call stack
stack = new Error().stack

B) using require.cache
Check if your script is in the require.cache list. For example here is a unit test that finds a particular script on the current require.cache, and removes it
    for file in require.cache.keys()
      if file.contains(['node/server.coffee']) or  file.contains(['node-cov/server.coffee'])
        pathToApp = file
        break

    require.cache[pathToApp].assert_Is_Object()
    delete require.cache[pathToApp]

    app = require '../server'

A: My current solution is to include this line logic check before the 'standalone script execution'
if process.argv[1].toString().indexOf('myScript.coffee') != -1
    # Standalone script code here


text:
Q: How to write a regex only allow numbers and "(", ")", "-" Below is my regex but it seems not working
/[0-9\-\(\)]/.test(str)

when I test
 /[0-9\-\(\)]/.test('(12321)213213d')

It will return true

A: What you're actually testing is if any of those characters are in your test string. You want to check if it contains only those characters. To do that, you need to say from start ^ to finish $ it only contains those chars.
e.g.
/^[0-9()-]+$/.test('(12321)213213d')

A: Your current regex just checks that any one character in the string matches the character class. Add anchors and a quantifier: /^[0-9\-\(\)]+$/

*

*^ - "Beginning of input" anchor

*$ - "End of input" anchor

*+ - Require one or more of the preceding thing

Mind you, "()" will match that regex. :-)

A: You need to repeat it with either * or +. You also need to anchor it with ^ and $ to contain the whole string.

console.log(/^[0-9\-\(\)]+$/.test('(12321)213213d'));
console.log(/^[0-9\-\(\)]+$/.test('(12321)213213'));

A: I believe adding input beginning/end characters will fix this. Like
^[0-9\-(\)]$/.exec('(12321)213213d')

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

A: /^[\d\(\)\-]+$/.test('(12321)213213d')

^ start, $ end, \d for digit and ()-,
I think you are looking for telephone number matcher, if your answer is yes then this is not right regex for it.
for telephone matcher visit this link


text:
Q: Filter groups on whether the max of one column, subject to a condition on another, is equal to a specific value I want to slice (or filter for) those groups (Though, I'd settle for rows.) that belong to groups in d2.groupby('g') where the max of the values of s in the group, for rows where test is 1,  is 2.
pd.__version__
# '0.24.1'

d2 = pd.DataFrame({'g': [1, 1, 1, 2, 2, 2],
                   'test': [1, 1, 0, 1, 0, 0],
                   's': [1, 2, 3, 1, 2, 3]})

d2
   g  test  s
0  1     1  1
1  1     1  2
2  1     0  3
3  2     1  1
4  2     0  2
5  2     0  3

In plain English: I want to keep groups where the maximum value of s that has a corresponding test value of 1 is 2. For the example below, I want to keep the g group 1 because the second row has test == 1 and s == 2, and the third row has s == 0. Expected output for this data:
   g  test  s
0  1     1  1
1  1     1  2
2  1     0  3

I've tried d2.groupby('g').filter(lambda x: (x.test == 1)) # followed by nonsense, as well as d2.groupby('g')[[d2.s == 1]] # with more nonsense. The latter gives me the message about Series objects being mutable and unhashable. I've tried a number of other equally senseless and useless approaches. How do I groupby('g') and filter by the max of s where test is 1? This seems like it should be easy, but I can't get it. I could get there by adding a column, but that seems like a kludge.
Note: I have searched for the answer for this. I'd gladly take any search hints about how to find any current solutions for this question, if there are any. Thanks!

A: You can use groupby and transform to compute a mask, something like this:
df[df['s'].where(df['test'] == 1).groupby(df['g']).transform('max') == 2]

   g  test  s
0  1     1  1
1  1     1  2
2  1     0  3

The idea behind Series.where is to let us only consider values of "s" where "test" is 1.
Here's a similar version above inspired by WeNYoBen which will work because "test" is 0 or 1 here.
df[df['s'].mul(df['test']).groupby(df['g']).transform('max').eq(2)]

   g  test  s
0  1     1  1
1  1     1  2
2  1     0  3

A: Using filter
d2.groupby('g').filter(lambda x : (x['s']*x['test']).max()==2)
Out[390]:
   g  s  test
0  1  1     1
1  1  2     1
2  1  3     0

Another way using isin since filter usually slower in big data frame
s=d2.s.mul(d2.test).groupby(d2['g']).max()==2
d2.loc[d2.g.isin(s.index[s])]
Out[394]:
   g  s  test
0  1  1     1
1  1  2     1
2  1  3     0


text:
Q: read C function in R Some key algorithms are written with c/c++ in R. for example, in the package 'tree',  the related code is as follows,
fit <- .C(BDRgrow1, as.double(X), as.double(unclass(Y)),
    as.double(w), as.integer(c(sapply(xlevels, length),
      length(ylevels))), as.integer(rep(1, nobs)), as.integer(nobs),
    as.integer(ncol(X)), node = integer(control$nmax), var = integer(control$nmax),
    cutleft = character(control$nmax), cutright = character(control$nmax),
    n = double(control$nmax), dev = double(control$nmax),
    yval = double(control$nmax), yprob = double(max(control$nmax *
      length(ylevels), 1)), as.integer(control$minsize),
    as.integer(control$mincut), as.double(max(0, control$mindev)),
    nnode = as.integer(0L), where = integer(nobs), as.integer(control$nmax),
    as.integer(split == "gini"), as.integer(sapply(m, is.ordered)),
    NAOK = TRUE)

BDRgrow1 should be the name of a C function. how to read the source code of the function? Any help will be greatly appriciated.


text:
Q: How to keep a label updated with the content of a variable? I'm making a program that has a form on the main monitor and another on a secondary one.
I want to keep the content of a label in the secondary form updated with the value of a variable in the main form.
Right now I'm doing it with a timer in the secondary form that reads the variable from the main form and updates the label content when the variable changes, but I wanted to know if there is a better way for doing this, without the timer that's working all the time.

A: The source of the event (variable changing its value) is the primary form. So it is its duty to notify every external entity (the second form) that this value has been changed.
Following this line of thought you should implement an event in the primary form and let other entity subscribe to this event to be notified when the variable changes
In Form1 (the main form)
public delegate void OnVeryImportantValueChanged(int newValue);
public event OnVeryImportantValueChanged ImportantValueChanged;

when you change the value of your important value, check if someone has subscribed to the event, and if positive, call the event handler
importantValue = CalculateNewValue();
if(ImportantValueChanged != null)
    ImportantValueChanged(importantValue);

In Form2 (the secondary form)
Form1 newForm1 = new Form1();
newForm1.ImportantValueChanged += ReceiveNotificationForChange;
newForm1.Show();

public void ReceiveNotificationForChange(int newValue)
{
    label.Text = "NewValue received:" + newValue.ToString();
}

In the above scenario, the Form2 opens the Form1, but if this is not the case (It is Form1 that opens Form2) then the process requires that you pass  the instance of Form1 inside the constructor of Form2 and use that instance to wire the event
In Form1
 Form2 newForm2 = new Form2(this);
 newForm2.Show();

in the constructor of Form2
 public void Form2(Form1 callerInstance)
 {
      InitializaComponents();
      callerInstance.ImportantValueChanged += ReceiveNotificationForChange;
 }

A: In your main form code, instead of using a variable to store your value, use a property which automatically sets the label:
private string _value;
private string Value {
  get { return _value; }
  set {
    _value = value;
    if (secondForm != null) secondForm.lblValue.Text = value;
  }
}

Then when you set the value in your main form, do it with Value = "blah blah";, and the property setter will change the label for you.


text:
Q: Can Duktape make http requests I have a very simple duktape plugin running embedded in another program. Simple stuff works, but I am not sure how to make HTTP requests.  Is it even possible to make HTTP Request from within a Duktape VM?

A: No you can't. The hosting application must provide it to Duktape. Duktape provides a  JavaScript runtime but does not provide function you also find in browsers when using JavaScript.

A: In order to make http requests within your duktape program, you must bind a native function (in C if your program is in C) that will make the request and inject back the answer

A: It would be nice to implement XMLHttpRequest in duktape. That would open the door to many useful use cases and bring it one step closer to using popular js libraries. Are there any plans for that?

A: You can implement socket interface in c, then register to duktape.


text:
Q: Real-time update of values inside a call_back function[the values are from external function(of another .m file)] I have an external function say "external_func" (seperate .m file)
Inside this function a while loop is called, and this while loop update a variabl named "update_prog"
Now I will pass this value into the GUIDE using
assignin('base', 'update_prog', update_prog); % passing to workspace

I am making this
"update_prog" as global variable and calling it into GUIDE .m file
function pb1_Callback(hObject, eventdata, handles)
global update_prog

% hObject    handle to pb1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% else
%      set(handles.pb1,'enable','on');
% end
% update_prog first value prints, but it wont updates as the loop in external_func goes on.
drawnow;
set(handles.slider1,'Value',update_prog)
 external_func;

so here in the GUIDE .m file I can get the value
"update_prog" but it wont keep up with the while loop. I used "drawnow" but its of no use.
How can I refine this value "update_prog" as the while loop in the "external_func" goes through multiple iterations. [Note: The updated values are there in the callback function of GUIDE, but unless there is a callback the callback function wont update the "update_prog"], so how can I acheive this real-time update inside a call_back function.
[Note: passing the variables through function input is not possible here in my case, so I am looking for alternatives]
Edit1: please consider this link, which has an exampleWhich may clarify you what I am trying to acheive
What I am doing here is

*

*Passing the variable(which is being updated in the while loop of the externel function) into GUI.

*I will use this variable to show the progress on the progress bar(Slider).

What is the problem?
 1. The variable inside the GUI callback(Consdier I will press a push button and then it will call the function with while loop) will put the updated values into the set(handles.slider,'Value',variable)
By doing this I cant move the slider.
Why?

*

*Callback updates the variable only when I press the push button, next all the updates to the variable will not be updated, so progress bar/slider wont move.

A: I wouldn't recommend to pass your variable in 3 steps with an intermediate workspace (external->base workspace->GUI). I would rather recommend to pass your variable directly (external->GUI).
Each Matlab figure offers a space to store variables (Application Data) of any type. I would suggest reading the article Share Data Among Callbacks and read the documentation for the 3 functions:

*

*guidata

*setappdata

*getappdata
This way will offer you much more control over the scope of your variables and you won't need any global declaration.

Below is an example of a simple gui. The gui declare the variable in it's user space (with setappdata), then uses a timer to periodically read this variable (with getappdata).
The external function do whatever you want it to do (just a random number in the example), then to update the variable you use the same setappdata. The only thing you need for that is the handle of the main GUI figure, so in the example I give it as input of the external function.
The GUI also has two buttons to start and stop the update.

The code for the main example GUI 'theGui.m' is :
function h = theGui

%// basic GUI with 2 buttons and 1 slider
h.fig = figure('Position',[433 434 500 100],'Menubar','none','CloseRequestFcn',@my_closefcn) ;
h.sld = uicontrol('Style','Slider','Position',[20 20 460 20]) ;
h.btnStart = uicontrol('Style','pushbutton','String','Start updating','Callback',@btnStart_callback,'Position',[20 50 200 30]);
h.btnStop  = uicontrol('Style','pushbutton','String','Stop updating','Callback',@btnStop_callback,'Position',[280 50 200 30],'Max',1,'Min',0);

%// Define the timer
h.t = timer ;
h.t.Period = 0.1 ; %// 0.1s refresh interval
h.t.TimerFcn = {@timer_callback,h.fig} ;
h.t.ExecutionMode = 'fixedSpacing' ;

%// initialise the variable to update in the GUI appdata
update_prog = 0 ;
setappdata( h.fig , 'update_prog' , update_prog ) ;

%// save handles
guidata( h.fig , h );

function btnStart_callback(hobj,~)
    h = guidata( hobj ) ;           %// retrieve handles
    if strcmp('off',h.t.Running)    %// Start timer (only if not already running)
        start(h.t)
    end

function btnStop_callback(hobj,~)
    h = guidata( hobj ) ;   %// retrieve handles
    stop(h.t)               %// Stop timer

function timer_callback(~,~,hfig)
    update_prog = getappdata( hfig , 'update_prog' ) ;  %// retrieve the 'update_prog' variable value
    h = guidata( hfig ) ;                               %// retrieve handles
    set(h.sld , 'Value' , update_prog) ;                %// update the slider object with the retrieved value

function my_closefcn(hobj,~)
%// this function is only to clean up when the GUI will be closed.
%// It is recommended to delete the timer manually
    h = guidata( hobj ) ;   %// retrieve handles
    stop(h.t)               %// Stop timer (in case it is still running)
    delete(h.t) ;           %// delete the timer
    delete(h.fig) ;         %// destroy the figure

And the code for external_func.m
function external_func( guiMainFigureHandle )
%// This function will only generate random numbers and push them into the
%// variable 'update_prog' contained in the GUI appdata.
%// This is why this function NEEDS the handle of the gui to be able to
%// access the Application Data space of the gui.

for k = 1:100
    randomValue = rand(1) ;                              %// generate a random value
    hfig = ancestor( guiMainFigureHandle , 'figure' ) ;  %// make sure the handle provided is the top level figure
    setappdata( hfig , 'update_prog' , randomValue) ;    %// update the variable value
    pause(0.1) ;
end

Edit:
I place this in edit instead of changing the code above because I don't recommend messing with the root object if you don't need to. But in your case it can be a way round your problem.
If your external function doesn't have access to the GUI, it can always update a part of memory which is available for all the programs running in a given Matlab session, namely the root object. The handle for it is reserved and is the same for any program: 0 (although since v2014b there is another way to invoke it : groot, it is still always the same handle for all Matlab).
So in the example above, in theGui.m, use instead:
setappdata( 0 , 'update_prog' , update_prog ) ;

in the main routine, then in the subfunction function timer_callback(~,~,hfig), use:
update_prog = getappdata( 0 , 'update_prog' ) ;  %// retrieve the 'update_prog' variable

And your function external_func() doesn't need any extra argument, the update only needs one line:
setappdata( 0 , 'update_prog' , update_prog) ;    %// update the variable value

A: I "suspect" that your update_prog variable in the base workspace is not a global (you must define it to be global in every workspace that you want to use it).
Since your using globals (there are many better ways to do this - but thats not your question) - why don't you simply define the update_prog variable to be global in your external_func function (replace the assign call).
edit  put a drawnow in your external_func function.  That way when you click on the button it will update.
edit 3
I think I know what you want to do, try this example and see if it does what you want - updated to show how you find the slider object in your code and update inside your loop:
function  mygui
  % create a figure
  f = figure;
  % create a uicontrol slider - note that I give it a tag.
  uicontrol ( 'style', 'slider', 'Position', [0 200 200 40], 'tag', 'MYSLIDER', 'backgroundcolor', 'white', 'parent', f );
  % create a push button which we can press to update
  uicontrol ( 'string', 'Press 2 start', 'callback', @(a,b)myLoop(), 'Position', [0 0 200 50] )
end

% This replicates your "external_func" function.
function myLoop()
  % since you cant pass in any var -> you need to find the slider object
  % you can do this by using findobj and search for the tag of the item
  uic = findobj ( 0, 'tag', 'MYSLIDER' );
  % find the figure handle (only needed for this demo)
  f = ancestor ( uic, 'figure' );
  % initialise the value which will be used to update the slider
  count = 0;
  % create your loop
  while ishandle(f)
    % incrememt the count variable -> this will end up on the slider value
    count = count + 1e-5;
    % reset count if > 1 -> so the slider cant go out of range.
    if count >= 1
      count = 0;
    end
    set ( uic, 'Value', count );
    % initiate a drawnow -> this allows matlab to process GUI events
    drawnow();
  end
end

The downside of this is you insert a drawnow in your loop -> which could slow it down somewhat.
If this doesn't fix your problem you need to explain better what you want to do... (in my view)


text:
Q: Why my Pepper robot is not able to be activated by trigger sentences? I'm trying to start behaviours that actually works on Pepper by using trigger sentences. I'm able to start them by using Launch Trigger Conditions and Run buttons (of course). The Autonomous Life is on but Pepper seems not to listen to me, even though it hears and localizes sounds (its eyes are not blue). I applied the procedure found at this link: https://www.brainaryinteractive.com/news/2017/8/14/nao-tipsvol-3-how-to-packageand-installapplications-with-trigger-sentences

A: With NAOqi 2.5, according to this piece of documentation about basic conversation abilities, you must first subscribe and install the Basic Channel.
If this does not works for some reason,
you can still create a dialog, set it public,
and call ^switchfocus(applicationID/behavior_1) from there.


text:
Q: Is it possible to create child window in opengl parent? In my opengl project, i need to create some children of opengl window to get some UserInterface to the user and opengl to make some graphic in my program, and actually i have been successfully to make it all.. but the problem is: where we are going to move or resize the child window, my opengl background is getting fall appart yet when resizing and moving are done, my opengl background back to normal.
if it possible, could you explain me step by step to do it?
what should i do to solve this case?


text:
Q: string after  shown with quotes in dev tools I am using chrome dev tools.
I see two different ways my span element is shown in dev tools (based on the way it is being rendered in backend. I don't have the details about this)
1.
<span>
    random text with some whitespace </span>

I don't see any expand button (an arrow that looks like |> in chrome dev tools) on this span.

*Same text shown as this:

<span> "

              random text with too much whitespace and quotes

    "
</span>

This span has an expand arrow.
What the backend is doing: This might be a helpful hint:
It is a JSP page.
In case 1. If the text contains an anchor tag, it is rendered as plain text and not an actual link by the backend UI rendering framework
In case 2. it shows up as a link correctly
The UI rendering framework uses custom tag like

 Adding anchor tag here causes it to show up as proper link
There is extra whitespace in 2. but UI is exactly the same in both.
Can someone help me figure out what is going on?


text:
Q: Help with HTML server request syntax - concat strings I am trying to execute a script when a button is pressed on my webpage. Currently the following code works:
<input type="button" onclick="newAJAXCommand('focuser1.htm?moveOut=100');" value="Out" style="width: 130px; height: 80px">

Instead of sending the hardcoded value of 100 I want to send whatever number is entered in a textbox that is also on the page that looks like this...
<input type="text" name="inc" maxlength="10" style="width: 80px" value="10"> <input type="submit" name="setInc" value="Set" style="width: 75px;">

So I am sure I have the syntax all wrong but this is basically what I want to do:
<input type="button" onclick="newAJAXCommand('focuser1.htm?moveOut=" + document.getElementById('inc').value" ');" value="Out" style="width: 130px; height: 80px">

Is that even possible?

A: Yes, it is possible
<input type="button" onclick="newAJAXCommand('focuser1.htm?moveOut=' + document.getElementById('inc').value);" value="Out" style="width: 130px; height: 80px">

Ah, and you need to add id attribute to text input
<input type="text" id="inc" maxlength="10" style="width: 80px" value="10">

Anyway, I think its better to do such things within function:
function newAJAXCommand(url, id)
{
     //do something with url and document.getElementById(id);
}


text:
Q: Receive android intent in Chrome 57: any documentation? According to this Chromium blog post we should now be able to receive intents in Chrome for Android:

"Progressive Web Apps [..] will be able to receive incoming intents
  from other apps."

Except it looks like this is undocumented? There is not a single link to be found in the post and a quick Google didn't help me either.
Anyone know where to find the docs?

A: This doesn't mean anything fancy, just that the manifest will include an intent filter for the app's URL.
Here's a snippet from https://cs.chromium.org/chromium/src/chrome/android/webapk/shell_apk/AndroidManifest.xml
<intent-filter>
    <action android:name="android.intent.action.VIEW"></action>
    <category android:name="android.intent.category.DEFAULT"></category>
    <category android:name="android.intent.category.BROWSABLE"></category>
    <data android:scheme="{{{scope_url_scheme}}}"
          android:host="{{{scope_url_host}}}"
          android:pathPrefix="{{{scope_url_path}}}"></data>
</intent-filter>