text:
Q: How can I create a JavaScript global variable? This is the part of my .html file, where I use an xmlhttp request, and then try to access the JSON object outside of a function.
''''
<html>
  <head>
    <title>make_activities_table.html</title>
  </head>
  <body>

    <script>

      var act_obj_array;

      // Get file activities.json and create JSON object
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
        if ( this.readyState == 4 && this.status == 200 ) {
          act_obj_array = JSON.parse( this.responseText);
        }
        console.log(this.responseText);
        console.log('Inside function = ' + act_obj_array);
      };

      xmlhttp.open( "GET", "activities.json", true);
      xmlhttp.send();

      console.log( 'Outside function = ' + act_obj_array);

    </script>
  </body>
''''

I'm trying to access the JSON object 'act_obj_array' outside of the xmlhttp.onreadystatechange function.  From what I read, in JavaScript, to make a variable global, you define it outside of any function, which, clearly I have done here. But when I console.log 'act_obj_array, outside the function, I get undefined.
activities.json, is a file, that exist in the same directory of my web hosting's server.  It is a JSON formatted file.  I can see the information in the file quite clearly when I console.log( this.responseText );
What do I need to do to create a JSON object from an xmlhttp request, and then be able to access the JSON object from the rest of my code?

A: Well, since no one wanted to answer, I came up with a solution, and, I want to work on a second solution.
The solution I have now, I added a function after the line, inside a function:
act_obj_array = JSON.parse( this.responseText);

which is a function, that builds my table from my JSON object.  At first, I just added the script in the body of the document, but, then, I defined the function in an external JavaScript sheet.  This looked much cleaner.
The other solution, and one I haven't played with yet, is to use the 'fetch' method to read in my JSON file.  That way, I may not have to use a function to create my JSON object.


text:
Q: mapping jms property to RabbitMQ We use spring integration to communicate components using MQSeries and RabbitMQ.
With MQseries there are a lot of JMS properties that are used by customers.
We would like to add an intermediate function between the input and the output which makes a mapping of these properties (getting the jms_priority from mqseries and put in the output message the property "priority" for RabbitMQ).
Without the specific properties JMS it works very well.
Below the code we use:
<int:channel id="input" ></int:channel>
<int-jms:message-driven-channel-adapter id="jmsIn" connection-factory="connectionFactoryCaching"  channel="input" ...>

<int:service-activator id="sa1" input-channel="input" ref="serviceBean"  output-channel="output"/>
<bean id="serviceBean" class="com.poc.ServiceActivator"> </bean>

<int:channel id="output" ></int:channel>
<int-amqp:outbound-channel-adapter channel="output"  .../>

import org.springframework.amqp.core.MessageProperties;

The ServiceActivator code:
public class ServiceActivator {
    public org.springframework.amqp.core.Message convertMessageMQSeriesToRabbit (Message obj){

        MessageProperties messageProperties = new MessageProperties();
        try {
            messageProperties.setCorrelationId(obj.getJMSCorrelationID());
            System.out.println("getJMSReplyTo "+obj.getJMSReplyTo());
            System.out.println("getJMSPriority "+obj.getJMSPriority());
            messageProperties.setPriority(obj.getJMSPriority());
            System.out.println("getJMSType "+obj.getJMSType());
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Is this the right way to do it? In the convertMessageMQSeriesToRabbit method, what type of return object should be passed to the outbound? org.springframework.amqp.core.Message ?
In this method we want to fill all RabbitMQmessage properties (content_type, content_encoding, priority, correlation_id, reply_to, expiration, message_id, timestamp, type, user_id, app_id, cluster_id) with corresponding JMS value.
We also need to do it the other way (inboud rabbitMQ => outbound mqseries)

A: No, Spring Integration uses its own abstraction org.springframework.messaging.Message<?>. You don't need to interact with it directly, simply use a header-enricher.
See JmsHeaders and AmqpHeaders for the constants.
<header-enricher id="headerEnricherWithShouldSkipNullsFalse" input-channel="fromJms" output-channel="toRabbit">
    <header name="amqp_correlationId" expression="headers.jms_correlationId"/>
    ...
</header-enricher>

For AMQP priority, the standard IntegrationMessageHeaderAccessor.PRIORITY value is used.
Also see the DefaultAmqpHeaderMapper and DefaultJmsHeaderMapper to see how the adapters map from Message<?> to/from RabbitMQ and JMS messageds.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JSON to cell google sheet array work but object not working by binanace API this is Response:
{
 "makerCommission": 15,
 "takerCommission": 15,
 "buyerCommission": 0,
 "sellerCommission": 0,
 "canTrade": true,
 "canWithdraw": true,
 "canDeposit": true,
 "updateTime": 123456789,
 "accountType": "SPOT",
 "balances": [
   {
  "asset": "BTC",
  "free": "4723846.89208129",
  "locked": "0.00000000"
   },
   {
  "asset": "LTC",
  "free": "4763368.68006011",
  "locked": "0.00000000"
   }
            ],
  "permissions": [
  "SPOT"
  ]
 }

This is my code :
   var jsonResponce = JSON.parse(data); // To JSON
   Logger.log(jsonResponce.accountType); // Return SPOT

   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheet = ss.getActiveSheet();
   var rows = [],
       balanc;

  for (i = 0; i < jsonResponce.length; i++) {
     balanc = jsonResponce[i];
     rows.push([balanc.accountType]);
    }
  Logger.log(rows); /////////////// return []  why not return SPOT
  dataRange = sheet.getRange(1, 1, rows.length, 1);
  dataRange.setValues(rows);

The JSON return accountType if run without array but after add in array give me [] empty any help pls.
this is picture:
enter image description here

A: The reason why your rows is empty is because your jsonResponce is not an array. If you will log jsonResponce.length it will return null.
Sample code:
function myFunction() {
  var jsonData = [{
 "makerCommission": 15,
 "takerCommission": 15,
 "buyerCommission": 0,
 "sellerCommission": 0,
 "canTrade": true,
 "canWithdraw": true,
 "canDeposit": true,
 "updateTime": 123456789,
 "accountType": "SPOT",
 "balances": [
   {
  "asset": "BTC",
  "free": "4723846.89208129",
  "locked": "0.00000000"
   },
   {
  "asset": "LTC",
  "free": "4763368.68006011",
  "locked": "0.00000000"
   }
            ],
  "permissions": [
  "SPOT"
  ]
 }];
  var data = JSON.stringify(jsonData);
  var jsonResponce = JSON.parse(data); // To JSON
  Logger.log(jsonResponce);
  Logger.log(Array.isArray(jsonResponce))
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheet = ss.getActiveSheet();
   Logger.log(jsonResponce.length);
   var rows = [],
       balanc;

  for (i = 0; i < jsonResponce.length; i++) {
     balanc = jsonResponce[i];
     rows.push([balanc.accountType]);
    }
  Logger.log(rows); /////////////// return []  why not return SPOT
  dataRange = sheet.getRange(1, 1, rows.length, 1);
  dataRange.setValues(rows);

}

Modifications done:

*

*create a json array. (encapsulate original json data with [])

Output:
6:37:31 AM  Notice  Execution started
6:37:31 AM  Info    [{canDeposit=true, sellerCommission=0.0, balances=[{locked=0.00000000, asset=BTC, free=4723846.89208129}, {locked=0.00000000, asset=LTC, free=4763368.68006011}], takerCommission=15.0, permissions=[SPOT], canTrade=true, makerCommission=15.0, updateTime=1.23456789E8, buyerCommission=0.0, accountType=SPOT, canWithdraw=true}]
6:37:32 AM  Info    1.0
6:37:32 AM  Info    [[SPOT]]
6:37:34 AM  Notice  Execution completed

Note:
You can use Array.isArray(), to check if the variable is an array or not then read the data accordingly.
Sample:
  if(Array.isArray(jsonResponce)){
    for (i = 0; i < jsonResponce.length; i++) {
     balanc = jsonResponce[i];
     rows.push([balanc.accountType]);
    }
  }else{
    rows.push([jsonResponce.accountType])
  }

(UPDATE)
If you want to make the Binance API response into an array, you can append "[" and "]" on your data.
Sample:
 var jsonData = {
 "makerCommission": 15,
 "takerCommission": 15,
 "buyerCommission": 0,
 "sellerCommission": 0,
 "canTrade": true,
 "canWithdraw": true,
 "canDeposit": true,
 "updateTime": 123456789,
 "accountType": "SPOT",
 "balances": [
   {
  "asset": "BTC",
  "free": "4723846.89208129",
  "locked": "0.00000000"
   },
   {
  "asset": "LTC",
  "free": "4763368.68006011",
  "locked": "0.00000000"
   }
            ],
  "permissions": [
  "SPOT"
  ]
 };

  var data = JSON.stringify(jsonData);

  data = "["+data+"]";
  var jsonResponce = JSON.parse(data); // To JSON
  Logger.log(jsonResponce);
  Logger.log(Array.isArray(jsonResponce))

Output:
12:21:48 AM Info    [{makerCommission=15.0, canDeposit=true, balances=[{free=4723846.89208129, locked=0.00000000, asset=BTC}, {free=4763368.68006011, asset=LTC, locked=0.00000000}], takerCommission=15.0, updateTime=1.23456789E8, accountType=SPOT, canTrade=true, sellerCommission=0.0, buyerCommission=0.0, canWithdraw=true, permissions=[SPOT]}]
12:21:48 AM Info    true

A: function myfunk() {
  const data = '{"makerCommission":15,"takerCommission":15,"buyerCommission":0,"sellerCommission":0,"canTrade":true,"canWithdraw":true,"canDeposit":true,"updateTime":123456789,"accountType":"SPOT","balances":[{"asset":"BTC","free":"4723846.89208129","locked":"0.00000000"},{"asset":"LTC","free":"4763368.68006011","locked":"0.00000000"}],"permissions":["SPOT"]}';
  const obj = JSON.parse(data);
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const vs = obj.balances;
  const oA = vs.map(obj => [obj.asset,obj.free,obj.locked]);
  sh.getRange(1,1,oA.length, oA[0].length).setValues(oA);
}

Sheet1:

Col1
Col2
Col3

BTC
4723846.892
0

LTC
4763368.68
0


text:
Q: Карта для игрушки Такой вот вопросик, есть много игрушек на javascript'e, тобишь там можно бегать, как бегать, перемещать картинку своего персонажа по bacground'у. Вот интересно, как это сделать, подскажите пожалуйста, или скажите статейку на это дело, заранее спасибо)
A: Вы же позавчера начали учить JavaScript, куда вы гонитесь? Прочитайте нормальных книг, да усвойте материал.
A: Могу помочь с передвижением блока по экрану на jQuery, может это вам чем то поможет:
CSS:
body{
   background: black;
   font-family: verdana;
   font-size: 12px;
}
#sqr{
   background: -webkit-gradient(linear, left top, left bottom, from(#fefefe), to(#dddddd));
   background: -o-linear-gradient(top, #fefefe, #dddddd);
   background: -moz-linear-gradient(top, #fefefe, #dddddd);
   position: absolute;
   top: 1%;
   left: 1%;
   width: 10%;
   height: 20%;
   border-radius: 6px;
   -webkit-box-shadow:0px 0px 15px white;
   -moz-box-shadow: 0 0 15px rgb(255, 255, 255);
   box-shadow: 0 0 15px rgb(255, 255, 255);
}
#str{
   position: absolute;
   right: 0%;
}
#vv, #vn, #vl, #vp{
   outline: none;
   border-radius: 8px;
   border: #057ed0 1px solid;
   color: #ffffff;
   border-radius: 3px;
   -moz-border-radius: 3px;
   -webkit-border-radius: 3px;
   background: #029bd2;
   background: -webkit-gradient(linear, left top, left bottom, from(#32bbef), to(#029bd2));
   background: -o-linear-gradient(top, #32bbef, #029bd2);
   background: -moz-linear-gradient(top, #32bbef, #029bd2);
   cursor: pointer;
}

HTML:
<!DOCTYPE html>

<title>Поиграем с квадратиком</title>
<meta charset='window-1251'>
<link rel='stylesheet' type='text/css' href='style.css'>

<input type='button' id='vv' value='Вверх'>

<input type='button' id='vl' value='Влево'> <input type='button' id='vp' value='Вправо'>

<input type='button' id='vn' value='Вниз'>

jQuery:
$(document).ready(function(){

var vv = $('#vv'); //Вверх
var vn = $('#vn'); //Вниз
var vl = $('#vl'); //Влево
var vp = $('#vp'); //Вправо
var sqr = $('#sqr'); //Квадратик

var tp = 1;
var rt = 1;

vv.click(function(){
tp = tp - 7;
$('#sqr').animate({'top':tp+'%'},300);
});

vn.click(function(){
tp = tp + 7;
$('#sqr').animate({'top':tp+'%'},300);
});

vl.click(function(){
rt = rt - 5;
$('#sqr').animate({'left':rt+'%'},300);
});

vp.click(function(){
rt = rt + 5;
$('#sqr').animate({'left':rt+'%'},300);
});

});

Код, конечно, далеко от идеального, но это может Вам помочь.
A: Скорее всего вам нужен Canvas, это HTML5. Сейчас уже много игрушек на нем.
A: Думаю, эти ссылки вам помогут.
http://www.pawelch.com/html_create_game
http://habrahabr.ru/post/125857/
http://firstdev.org/post/programmirovanie/uroki/sozdaem-svoyu-pervuyu-igru-na-html5-urok-1/
A: http://home.onfind.net/
сделана без канваса


text:
Q: Extracting summarized information from one large dataset and then storing in another dataset I am relatively new to R and I am facing an issue in extracting summarized data from one dataset and then storing this data in another dataset. I am presently trying to analyze flight dataset along with the weather information. I am a having a query in this regard which is as follows:
I am having one dataset for the flight data.This dataset comprises of columns such as flight number, date,origin city name, origin state name, departure time, departure time block(each block of 1 hour duration spanning the entire 24 hours), arrival time, arrival time block, flight distance, total flight time and a binary response variable indicating whether the flight was delayed or not.
I have another dataset which comprises of weather data. This dataset includes columns such as date, time of recording, hour block(each block of 1 hour duration spanning the entire 24 hours), state, city and the respective weather related data such as temperature,humidity levels, wind speed etc. For each city,state,date and a single hour block, there can be several entries in the weather dataset indicating varying temperature levels at various times in the hour block.
I am trying to extract the temperature and humidity levels from the weather dataset and place this information in the flight dataset. I have created four new columns in the flight dataset for origin temperature,origin humidity, destination temperature and destination humidity for this purpose.
My objective is to store the average temperature and humidity levels for the origin city during the departure time hour block as well as for the destination city during the arrival time hour block in the flight dataset. The reason I am choosing average temperature and humidity is because there can be multiple entries in weather dataset for the same hour block,city and state combination.
I have tried to extract the origin temperature information from weather dataset using the following loop:
for(i in 1:nrow(flight))
  {

  flight[[i,13]]=mean(weather$temperature[weather$date == flight[[i,1]] & weather$time_blk == train[[i,5]]
              & weather$state == train[[i,3]] & weather$city == train[[i,2]]])

  }

However, the weather data set contains around 2 Million rows and the flight dataset also comprises of around 20000 observations. As a result, the above calculation takes a lot of time to execute and even then the origin temperature data in flight data set is not calculated properly.
I am also attaching the images of sample flight and weather datasets for reference.
Can you please suggest another approach for obtaining the above information considering the constraints of the large datasets and the time required for processing.


text:
Q: C# linq build table from sub list of list In result of linq query I want to get List<Record> records that should contain something like this:
Id=1, Number=1,Weight=23,Street="Testing street"

Id=1, Number=1,Weight=23,Street="Testing street"

Id=1, Number=1,Weight=23,Street="Testing street"

Id=1, Number=1,Weight=23,Street="Testing street"

Id=1, Number=1,Weight=23,Street="Testing street"

Id=1, Number=1,Weight=23,Street="Testing street"

Code:
namespace ConsoleApplication24
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Train> Depos = new List<Train>();
            Train train = new Train();
            train.Id = 1;
            List<Wagon> wagons = new List<Wagon>();
            wagons.Add(new Wagon { Number = 1, Weight = 23 });
            wagons.Add(new Wagon { Number = 1, Weight = 23 });
            wagons.Add(new Wagon { Number = 1, Weight = 23 });
            wagons.Add(new Wagon { Number = 1, Weight = 23 });
            wagons.Add(new Wagon { Number = 1, Weight = 23 });
            wagons.Add(new Wagon { Number = 1, Weight = 23 });
            train.Wagons = wagons;
            Depos.Add(train);

            List<Adress> Adresses = new List<Adress>();
            Adress adress = new Adress();
            adress.Id = 1;
            adress.Street = "Testing street";
            Adresses.Add(adress);
            List<Record> records = (from dep in Depos join adr in Adresses on dep.Id equals adr.Id select new Record { Id = dep.Id }).ToList();
        }
    }
    public class Record
    {
        public int Id { get; set; }

        public int Weight { get; set; }

        public string Street { get; set; }

        public int Number { get; set; }
    }

    public class Train
    {
        public int Id { get; set; }

        public List<Wagon> Wagons { get; set; }
    }

    public class Wagon
    {
        public int Weight { get; set; }

        public int Number { get; set; }
    }

    public class Adress
    {
        public int Id { get; set; }
        public string Street { get; set; }
    }
}

What is the best way to do this?

A: You need to use SelectMany, or, in query syntax, a second from, to flatten your list of lists:
  List<Record> records =(from dep in Depos
                         join adr in Adresses on dep.Id equals adr.Id
                         from wgn in dep.Wagons
                         select new Record
                         {
                            Id = dep.Id,
                            Number = wgn.Number,
                            Weight = wgn.Weight,
                            Street = adr.Street
                          }).ToList();

A: Or less readable LINQ with extension methods :)
IEnumerable<Record> records =
    Depos.Join(Adresses,
               myTrain => train.Id,
               addr => addr.Id,
               (myTrain, addr) => myTrain.Wagons
                                         .Select(wagon => new Record
                                         {
                                             Id = addr.Id,
                                             Street = addr.Street,
                                             Number = wagon.Number,
                                             Weight = wagon.Weight
                                         }))
         .SelectMany(myWagons => myWagons);

As you see SelectMany method is key method for this query


text:
Q: Single Sign On (SSO) from desktop app and web app Let's say I have an Angular web application that authenticates users in the Azure AD using MSAL: tuturial:https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-angular
Is there any way so that when a user is authenticated in a desktop app that an organization is using, for example Microsoft Outlook, it will do SSO on the Angular web app. So far, SSO to other web apps seem to work. However, not between desktop apps and web apps.

A: This scenario is practically not possible currently. Please raise user voice here .
Note:  As long as the same browser is used, it should achieve SSO.


text:
Q: Side Lengths of Triangles Die This is Exercise 3-5 from the Art of Problem Solving Volume 2 by Richard Rusczyk and Sandor Lehoczky. I looked at the solution in the solution manual, but I don't quite understand it, so I'm hoping that someone here could explain how to solve this problem
In triangle $ABC$, let $D$ be a point on $BC$ such that $AD$ bisects angle $A$. If $AD=6$, $BD=4$, and $DC=3$, then find $AD$.
The solution they gave is as follows:
Let $AB=x$ and $AC=y$. Since $\angle ADB = 180 - \angle ADC$, $\cos \angle ADB = -\cos \angle ADC$, and:
$$
(x^2-52)/-48 = -(y^2-45)/-36
$$
Rearranging this we find $3 x^2+4 y^2=336$. From the Angle Bisector Theorem we have $x/y = 4/3$, and our equation becomes $21 x^2/4 = 336$, so $x=8$.
My main issue with this is that I don't understand where they got the second line from.
*Edit: Sorry I may not have been clear enough before but when I said second line I meant the equation with the (x^2)-52/-48 and all that. I have no idea where those numbers came from and why x and y are squared, etc.

A: Remember that cosine is an even function, so $\cos (-\theta) = \cos \theta$. Also remember that the graph of a function $f(x-a)$, is just $f(x)$ shifted $a$ units to the right.
So, given two angles, $\alpha$ and $\beta$, if $\alpha = 180^\circ - \beta$, then $$\begin{align} \cos \alpha &= \cos(180^\circ - \beta) \\ &= \cos(\beta - 180^\circ) \\ &= -\cos \beta.\end{align}$$
If you're referring to why $x/y = 4/3$, then see the proof of the angle bisector theorem. It uses the law of sines, so it's fairly quick.


text:
Q: Gödel's 2nd for a theory of strings over a convenient alphabet? I am trying to find a proof of Gödel's second incompleteness theorem for an axiomatic theory T of finite strings from some fixed alphabet Γ, where Γ is, or is similar to, the set of symbols required to write T-sentences. I'm not fussy about what function and predicate symbols are taken as primitive in T (probably at least concatenation, but whatever it takes to make the proof easier). It is also fine (and preferred, if it simplifies the proof at all) if Γ is not finite (with a function symbol to construct variable names) but the union of a finite set with an infinite set of variables $x_1,x_2,\ldots$ (as is often done in the definition of FOL).
Something similar was mentioned in the following question answer as "the computer scientist's dream formulation", but for "lisp-like data":
https://math.stackexchange.com/a/2095088/330299
Paulson wrote a computer checked proof of the incompleteness theorems for a theory of hereditarily finite sets, documented in these two papers:

*

*https://www.cl.cam.ac.uk/~lp15/papers/Formath/Goedel-ar.pdf

*https://www.cl.cam.ac.uk/~lp15/papers/Formath/Goedel-logic.pdf


text:
Q: JSON post using jQuery is working fine with FF, Chrome & Safari but does not work in IE8 I have to Post Email and Password to my REST Service and it is hosted on different domain and i have allowed cross domain origin to * for access any cross domain request. and this is
Working fine

*

*with FF 16

*Chrome 22

*Safari 5
but it is not working in IE 8.0
I have tried several approach to resolve but still i m looking for solution.
<input type="button" value="POST" onclick="postData();" />

//Call authorization process
function postData() {
    var url = 'http://www.mydomain.com/authorize';
    var data = { 'email': 'myemail@gmail.com', 'password': 'mypassword' };
    jQuery.post(url, data, authorizeCallback, 'json');
}
jQuery.extend({
    post: function (url, data, callback, type, errorcallback) {
        return _ajax_request(url, data, callback, type, 'POST', errorcallback);
    }
});
function _ajax_request(url, data, callback, type, method, errorcallback) {
    if (typeof errorcallback == 'undefined') errorcallback = defaulterrordisplay;
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type,
        error: errorcallback
    });
}

 //Callback from authorization process
function authorizeCallback(data, textStatus, jqXHR) {
/*Here i am getting Message :  'Invalid email or password' only for IE,
otherwise it will return Message : "OK" with Authorization ID and Token
*/
}

Note: i am using pure HTML no server technology are used. and everything are working fine with all browsers except IE8.
Seeking for your best answer and suggestion for the same.
Thanks and Regards,
Imdadhusen

A: Did you say you are getting "Invalid email or password". This makes me think that you should debug the server code on http://www.mydomain.com/authorize.


text:
Q: None of my classes include in the stacktrace from Android developer console I received 4 crash reports from Android developer console with the same stacktrace, which seems to suggest a NullPointerException occured when the system is building the UI. However the trace does not include any of my class nor any of my layout file. Is there anyway to pinpoint the cause of the problem?  Thanks in advance!
Edit:
The 4 failed cases reported are all running on Android 5.0, 2 cases on Galaxy A5 and 2 on ZenFone 2.
Stacktrace:
java.lang.String java.lang.Object.toString()' on a null object reference
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:197)
at android.widget.Spinner.onMeasure(Spinner.java:507)
at android.view.View.measure(View.java:17442)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17442)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:727)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:463)
at android.view.View.measure(View.java:17442)
at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1260)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.widget.ScrollView.onMeasure(ScrollView.java:337)
at android.view.View.measure(View.java:17442)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17442)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:727)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:463)
at android.view.View.measure(View.java:17442)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
at android.view.View.measure(View.java:17442)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at android.view.View.measure(View.java:17442)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:447)
at android.view.View.measure(View.java:17442)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560)
at android.view.View.measure(View.java:17442)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5253)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)

A: Thanks Xose Sanchez to point out that there are enough information to start investigating even though the stack trace somehow only include Android's classes in this specific situation.
Answering my own question, in my case the app does have a few spinner which display values from the server. So it is entirely possible that the app will attempt to display null values in a Spinner. I added additional null checking code to all these places and hope this can fix the issue.


text:
Q: Addition of natural numbers represented as double or double plus one Firstly, this is about a homework problem.
I've got a data structure representing a natural number as:
NUM = zero
      double(NUM)
      double_plus_one(NUM)

Eg, 6 = double(double_plus_one(double_plus_one(zero))). I've got the algorithm to convert a number into or from this representation fine. But now I'm expected to come up with algorithms to add and subtract two numbers in this format. I'm not seeing any patterns in how this can be done (and I can only assume that I'm not supposed to convert it to a regular number, add that, and convert back to this form).
Any advice?

A: Your format is just reversed binary.  Every time you have double plus one it is a $1$ and every time you have double you have a $0$.  The outer operator is the ones bit, the next one in is the twos, and so on.  You need to write bitwise add, carry, subtract and borrow as operations on the text of your format.

A: You can define addition recursively through

*

*n + zero = zero + n = n

*double(n) + double(m) = double(n+m),

*double_plus_one(n) + double_plus_one(m) = double((n+m) + 1)

*double_plus_one(n) + double(m) = double_plus_one(n+m).
These aren't necessarily the most efficient, but they should work.


text:
Q: Can NAN and INFINITY be used under non-default rounding modes? Sample code:
#include <stdio.h>
#include <math.h>
#include <fenv.h>

#if _MSC_VER && ! __clang__ && ! __INTEL_COMPILER
#pragma fenv_access (on)
#else
#pragma STDC FENV_ACCESS ON
#endif

int main(void)
{
    float f;
    if (fesetround(RM) != 0) return 1;
    f = V;
    printf("%f\n", f);
    return 0;
}

Invocations:
$ gcc t583.c -std=c11 -pedantic -Wall -Wextra -DV=NAN -DRM=FE_TOWARDZERO && ./a.exe
nan

$ gcc t583.c -std=c11 -pedantic -Wall -Wextra -DV=INFINITY -DRM=FE_TOWARDZERO && ./a.exe
inf

$ cl t583.c /std:c11 /Za /fp:strict /DV=NAN /DRM=FE_TOWARDZERO /nologo && ./t583.exe
0.000000

$ cl t583.c /std:c11 /Za /fp:strict /DV=INFINITY /DRM=FE_TOWARDZERO /nologo && ./t583.exe
340282346638528859811704183484516925440.000000

GCC defines NAN and INFINITY as:
#define NAN           (__builtin_nanf(""))
#define INFINITY      (__builtin_inff())

while MSVC defines NAN and INFINITY as:
#define NAN           ((float)(INFINITY * 0.0F))
#define INFINITY      ((float)(_HUGE_ENUF * _HUGE_ENUF))

and _HUGE_ENUF as:
#define _HUGE_ENUF    1e+300 // _HUGE_ENUF*_HUGE_ENUF must overflow

So, with MSVC under /fp:strict AND under FE_TOWARDZERO and FE_DOWNWARD:

*

*the INFINITY evaluates to FLT_MAX, and

*the NAN evaluates to 0.0.

Confused.
However, is it allowed at all to use NAN and INFINITY under non-default rounding modes, such as FE_TOWARDZERO and FE_DOWNWARD?

Reason of the question: better understanding of the C standard.
What problem is being solved: experimenting with non-default rounding modes using MSVC, trying to produce expected results.

UPD. Answer from Microsoft:

Thanks for reporting this and help us improve our libraries. This issue has been fixed and will be available in a future update.

A:
is it allowed at all to use NAN and INFINITY under non-default rounding modes, such as FE_TOWARDZERO and FE_DOWNWARD?

The language specification does not express any limitation on using INFINITY.  A conforming implementation must therefore accept it and interpret it consistently with the provisions of the language specification regardless of rounding mode.  Specifically, it

expands to a constant expression of type float representing positive
or unsigned infinity, if available; else to a positive constant of
type float that overflows at translation time.

(C17 7.12/4)
That is not conditioned on the rounding mode in effect at any particular time.  Since MSVC does have an available float representation for infinity and FLT_MAX is required to be a representation of a finite number, it is non-conforming for INFINITY to evaluate equal to FLT_MAX in MSVC, under any circumstances.  Indeed, MSVC is non-conforming to whatever extent INFINITY ever fails to evaluate to a positive float infinity.
It is even more clear for NAN.  The specification says that it

is defined if and only if the implementation supports quiet NaNs for the float type.

In that case,

It expands to a constant expression of type float representing a quiet NaN.

(C17 7.12/5)
If NAN is defined at all then it expands to an expression that evaluates to a quiet NaN.  Period.  If MSVC provides for circumstances in which it instead expands to 0.0, then MSVC is non-conforming under those circumstances.

It should be acknowledged that most, if not all, C implementations have some non-conformity, whether by default or accessible via command-line options or similar.  Nevertheless, MSVC is notorious for its comparatively poor conformance among the widely used C implementations.


text:
Q: How do I load separate pages based on params for the dynamic route in nuxt.js? I am working on a nuxt project, and I have a folder structure like this.

*

*_category

*

*_subCategory

*

*_pageAlias

*

*_post.vue

*_pageAlias.vue

*anotherPage.vue

*samplePage.vue

*_subCategory.vue

_pageAlias.vue, anotherPage.vue, samplePage.vue are at the same level and working fine. The problem comes when I have to add another page which is similar to samplePage but have different URL.  All the above pages have different page structure and functionalities. But now I want to merge the functionality and looking for a way to define a custom route in a way that based I can check the URL parameter make an api call to find out the type of page and load the respective component.
Eg. A middleware where I can do something like
if(router.name === 'category-subcategory-pagealias') {
    let type = axio.get('api'+router.param._pageAlias)
    if(type === 'sample'){
        next({name: 'category-subcategory-samplepage'})
    }
}

In short: I want to load a page component like a dynamic component based on routes parameters so that I don't lose any of the page methods like asyncData.
I have tried using extend routes in nuxt config, but that doesn't work for this case because it will be a dynamic change in the router config.
I cannot use dynamic components inside a page; then I lose all the page methods.


text:
Q: Put tags over several parts of an equation, that are consistent with eq numbering and can be referenced in text Is it possible to put a tag (and a corresponding label) for a part of an equation over a brace, and another tag for a different part of the same equation over another brace?
Something like this:

The tag(label) numbering should continue the numbering of the equation counter, and should be referenced later in the text.
I'm sorry if this was already answered, but I haven't managed to find such a question.
Thanks in advance.


text:
Q: Loop to split list in different sublists I want to split one list of number comparing the first number of the sequence with the next one to figure out if it's bigger, in this case we create that sublist till find one number who is smaller. And each other
Inputdata = [45,42,78,120,47,2,50,32,34]

compare 45 with 42 is bigger not, so create list just with 45, and start with 42 to compare with the next one till find the smaller than 42:
Output = [45] [42,78,120,47] [2,50,32,34]

this is my code:
data = [45,42,78,120,47,2,50,32,34]

m = (len(data))
i=0
list1=[]
emptylist = True
while i <= m:

 for j in range(i+1,len(data)-1):

    if data[i] < data[j]:
        list1.append(data[j])
        emptylist = False

    else:

        if emptylist:

            list1.insert(0,data[i])
            print list1
            i += j
            list1 = []
            emptylist = True
            break

        else:
            list1.insert(0,data[i])
            print list1
            print j
            i += j
            print i
            list1 = []
            emptylist = True
            i += j
            break

My Output is:
[45]
[42, 78, 120, 47]

and I can't find the problem... any suggestions? thanks
PD1. The idea is create sublist where the first element is the smaller one.

A: L = [45, 42, 78, 120, 47, 2, 50, 32, 34]

cond = L[0]
res = [[cond]]
for item in L[1:]:
    if item > cond:
        res[-1].append(item)
    else:
        cond = item
        res.append([cond])

Now resis :
[[45], [42, 78, 120, 47], [2, 50, 32, 34]]

Details:
Indexing with 0 gives you the first element:
>>> cond = L[0]
>> cond
45

We create new list res that will hold our result and put the 45, i.e. the very first element into a list that in turn becomes the first element of res:
>>> res = [[cond]]
>>> res
[[45]]

Now, we iterate over the list starting form the second element. L[1:] gives this sublist:
>>> L[1:]
[42, 78, 120, 47, 2, 50, 32, 34]

Note, res[-1] always gives us the currently last element of a list. This itself must be list and we append the next number (item) if it is bigger than our cond. Otherwise, we append a new sublist with only one element res.append([cond]). During the next round we do the same. Therefore, the list that makes up the last element in our res will grow as long as item > cond. If not, we append a new list with cond. Rinse and repeat until the end of the original list.
Variation
The L[1:] makes a copy of L. This not the most efficient way of doing it. If we turn L into an iterator we can avoid this:
L = iter([45,42,78,120,47,2,50,32,34])
cond = next(L)
res = [[cond]]
for item in L:
    if item > cond:
        res[-1].append(item)
    else:
        cond = item
        res.append([cond])

Each next(L) will give us the next item in the iterator. The for-loop will go over the rest. So in our case it starts at the second element because we called next() once.


text:
Q: Remove redundant DNS servers in Ubuntu 22.04 Ubuntu 22.04
Original:
root@ubuntu:~# resolvectl
Global
       Protocols: -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
resolv.conf mode: stub

Link 2 (ens5)
    Current Scopes: DNS
         Protocols: +DefaultRoute +LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Current DNS Server: 12.34.56.78
       DNS Servers: 12.34.56.78 12.34.56.79

What I did:

*

*Add nameservers entry in /etc/netplan/01-netcfg.yaml file

# This file describes the network interfaces available on your system
# For more information, see netplan(5).
network:
  version: 2
  renderer: networkd
  ethernets:
    ens5:
      dhcp4: yes
      nameservers:
        addresses: [8.8.8.8, 1.1.1.1]

netplan apply

*Add DNS servers in /etc/systemd/resolved.conf file

[Resolve]
DNS=8.8.8.8 1.1.1.1
FallbackDNS=8.8.4.4

systemctl restart systemd-resolved
systemctl enable systemd-resolved

After rebooting:
root@ubuntu:~# resolvectl
Global
           Protocols: -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
    resolv.conf mode: stub
  Current DNS Server: 8.8.8.8
         DNS Servers: 8.8.8.8 1.1.1.1
Fallback DNS Servers: 8.8.4.4

Link 2 (ens5)
    Current Scopes: DNS
         Protocols: +DefaultRoute +LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Current DNS Server: 8.8.8.8
       DNS Servers: 8.8.8.8 1.1.1.1 12.34.56.78 12.34.56.79

How to remove 12.34.56.78 and 12.34.56.79 in DNS server list?


text:
Q: Solve a system equation in $\mathbb{R}$ - $\sqrt{x+y}+\sqrt{x+3}=\frac{1}{x}\left(y-3\right)$ how to solve a system equation with radical
$$\sqrt{x+y}+\sqrt{x+3}=\frac{1}{x}\left(y-3\right)$$
And $$\sqrt{x+y}+\sqrt{x}=x+3$$
This system has $1$ root is $x=1;y=8$,but i have no idea which is more clearly to solve it. I tried substituting and squaring to find the factor but failed.

A: From the second equation we get
$$\sqrt{x+y}=x+3-\sqrt{x}$$ y squaring this equation we obtain
$$y=(x+3-\sqrt{x})^2-x$$ plugging this in the first equation we get
$$\sqrt{(x+3-\sqrt{x})^2}+\sqrt{x+3}=\frac{1}{x}((x+3-\sqrt{x})^2-x-3)$$
Can you proceed?
Hint: $$x=1,y=8$$
Ok, we can also eliminate the square root:
$$\sqrt{x+y}=x+3-\sqrt{x}$$ so
$$x+3-\sqrt{x}+\sqrt{x+3}=\frac{1}{x}(y-3)$$
this is only a littlebit better.

A: Let $\sqrt{x+y}=a\ge0,\sqrt{x+3}=b\ge0$
$$(b^2-3)(a+b)=a^2-b^2$$
If $a+b=0,a=b=0$
Else $b^2-3=a-b\iff a=b^2+b-3=x+b\iff x=a-b\  \  \  \ (1)$
Squaring we get
$$x+y=x^2+x+3+2bx$$
$$\iff y=x^2+3+2x\sqrt{x+3}$$
The value of $x,y$ must satisfy $(1)$

A: Remember that $$ \sqrt{a}+\sqrt{b}= {a-b\over \sqrt{a}-\sqrt{b}}$$
so $$\sqrt{x+y}+\sqrt{x+3}={y-3\over \sqrt{x+y}-\sqrt{x+3}} $$
and now we have $${y-3\over \sqrt{x+y}-\sqrt{x+3}}=\frac{1}{x}\left(y-3\right)$$
Obviuosly $y\neq 3$ so we have $$\sqrt{x+y}-\sqrt{x+3}=x$$
Since  $$\sqrt{x+y}+\sqrt{x}=x+3$$
we have now $$\underbrace{\sqrt{x}+\sqrt{x+3}}_{f(x)} = 3\implies x= 1$$
($f$ is strictly increasing function so this equation has at most $1$ solution.) And then we get $y=8$.


text:
Q: The inclusion map $V\subset U$ is nullhomotopic. - Is this proof legit? There are many discussions has done on Hatcher 0.5, some here, and some there. But I am primarily uncertain about the invoke of tube lemma. Wonder if someone would kind help me take a look at my proof and help me verify or revise? Thank you.

Show that if a space $X$ deformation retracts to a point $x \in X$, then for each neighborhood $U$ of $x$ in $X$ there exists a neighborhood $V \subset U$ of $x$ such that the inclusion map $V\subset U$ is nullhomotopic.

Given $X$ deformation retracts to a point $x \in X$, we know there is a family of maps $f_t: X \to X, t \in I$, such that $f_0 = \mathbb{I}$ (the identity map), $f_1(X) = x$, and $f_t|x=  \mathbb{I}$ for all $t$.

Tube Lemma: Let $X$ and $Y$ be topological spaces with $Y$ compact, and consider the product space $X \times Y$. If $N$ is an open set containing a slice in $X \times Y$, then there exists a tube in $X \times Y$ containing this slice and contained in $N$.

To make sure $f_t(V) \subset V$, we need to find the appropriate $V$. By the definition of retraction, we know that $f_t(x) = x$, that is the slice $x \times I$ is contained in some open set $N$, and hence by tube lemma, $N$ also contains a tube containing the slice $x \times I$. Hence, let $V = N$.
Now we consider the inclusion map $i: V \to U$, and consider another family of maps: $\tilde{f}_t = f_t \circ i: X \to X, t \in I$ such that $\tilde{f}_0 = \mathbb{I} \circ i = i, \tilde{f}_1 = c \circ i$, $\tilde{f}_t|c=  \mathbb{I}$ for all $t$.
Hence we constructed a homotopy map from inclusion map to a constant map, hence it is nullhomotopic.


text:
Q: HTML Modal Title attribute AngularJS I am trying to dynamically set the Title of a 'modal' view using AngularJS (the title should change with respect to some selected user). The HTML is of the form
<modal  title="modalRolesTableTitle" visible="showModalRolesTable"> SOME CONTENT</modal>

In my AngularJS file I have declared both scope variables
$scope.showModalRightsTable = false;

$scope.modalRolesTableTitle = null;

and the visible attribute works fine. The modalRightsTableTitle variable is being assigned correctly (firebug).
I was hoping someone could explain functionality wise why the visible attribute binds and the title does not and perhaps provide a solution.
Also I have tried ng-attr-title="modalRolesTableTitle" without success (It just displays the text 'modalRolesTableTitle' ).

A: Always use expression for binding.
<modal  title="{{modalRolesTableTitle}}" visible="{{showModalRightsTable}}"> SOME CONTENT</modal>

See example
If you are using AngularJS 1.1.4 and above then you can use ng-attr-title
See this stackoverflow post

A: It's very work around but maybe this solution can be appropriate for you:
var myEl = angular.element( document.querySelector( '#myModal' ) );
myEl.attr('title',"My tooltip");

of course you have to set:
<modal id="myModal"  title="" visible="{{showModalRightsTable}}"> SOME CONTENT</modal>


text:
Q: Json Parsing error string converting I wrote this code and ı wrote httphandler etc. But when ı ran the app ı saw error:

.............

Java parsing error:Value  of type java.lang.String cannot be converted to JSONObject
 ı searched on internet but ı cannot solve it. what is wrong? where should ı add code?
MainActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();
    private ListView lv;

    ArrayList<HashMap<String, String>> contactList;

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

        contactList = new ArrayList<>();
        lv = findViewById(R.id.list);

        new GetContacts().execute();
    }

    private class GetContacts extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_LONG).show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();
            // Making a request to url and getting response
            String url = "http://api.androidhive.info/contacts/";
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("contacts");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);
                        String id = c.getString("id");
                        String name = c.getString("name");
                        String email = c.getString("email");

                        // Phone node is JSON Object
                        JSONObject phone = c.getJSONObject("phone");
                        String mobile = phone.getString("mobile");

                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);
                        contact.put("name", name);
                        contact.put("email", email);
                        contact.put("mobile", mobile);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    });

                }

            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, contactList,
                    R.layout.list_item, new String[]{"email", "mobile"},
                    new int[]{R.id.email, R.id.mobile});
            lv.setAdapter(adapter);
        }
    }
}

HttpHandler.java
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

A: You need to receive JSON content but the server is returning HTML content.
Modify your server and add application/json as content type:
Content-type:application/json


text:
Q: How to use author meta in shortcode? I am trying to create a shortcode that will return a link to a book on Amazon with a specific affiliate tracking code specific to the author. I created a user option called "amz" to hold the author's tracking code. This works fine when I'm using it elsewhere. This is the shortcode I created:

      function amazon_link_function($atts, $content = null) {
      extract(shortcode_atts(array(
      'isbn' => ' ',
      'title' => ' '
      ), $atts));
  $amztrack = the_author_meta( 'amz' );

  return '' .$title. '';

}
   add_shortcode("amazon", "amazon_link_function");

The isbn and title values return properly, but the tracking code stored in the $amztrack variable is displayed as plain text before the paragraph the shortcode is used in:(
I also tired this for the return line and got the same result:
  return '' .$title. '';

A: the_author_meta() prints the content immediately. Use instead:
$amztrack = get_the_author_meta( 'amz', FALSE );

This will return the value.

A: shortcodes need to return the value, therefore you cannot use a function which prints the output, like the_author_meta();
use get_the_author_meta() http://codex.wordpress.org/Function_Reference/get_the_author_meta


text:
Q: React Native change Button Text color I am a beginner in React Native and I want I just wrote my first line of code in it. I made a button and started wondering how can I change the colour and other properties of the text in the button.
<Button title="Click Me"></Button>
I was also wondering if there are some good packages that are recommended for beginners. Thanks for the help.

A: You can use a Button from react-native like this and can also pass the color prop.
Button
  onPress={onPressLearnMore}
  title="Click Me"
  color="#841584"
/>

For complex and custom buttons you can create it by your own styles using Touchables which are given by react-native you don't have to use any third-party libraries for that.
Example:
    <TouchableOpacity style={{ here you can specify custom styles for button container }} onPress={gotoDashboard}>
        <Text style={{here you can specify text styles}}>Button Text Here</Text>
  // You can add there as many components according to your designs.
      </TouchableOpacity>

A: You should use titleStyle like this:
<Button
  titleStyle={{
     color: '#00BAD4',
     fontSize: 30,
     fontStyle: 'italic',
  }}
  title="Title"
  buttonStyle={{
     backgroundColor: '#FFF',
     borderRadius: 4,
     margin: 5,
  }}
/>

Btw here's more useful information about buttons:
https://reactnativeelements.com/docs/components/button


text:
Q: Simple VIewHolder pattern implementation bug using convertView I'm trying to implement the ViewHolder pattern with convertView. Two questions:
1) When I comment lines #1 and #2 (which are required for the pattern) everything works fine. When the if is in place everything gets scrambled, the first element of the list gets shown twice (in the beginning and in the end of the list) and after some orientation changes and list scrolling everything gets jumbled. Why is this happenning?
2) I'm using a ListActivity and providing the TextView and array of Strings for the ArrayAdapter (#3) but for some reason I still need line (#4) otherwise the list items are blank. Is this because i'm not using super.getView()?
class SushiAdapter extends ArrayAdapter<String> {

    private final Activity context;

    SushiAdapter(Activity context) {
        super(context, R.layout.row, R.id.label, MenuItems); // #3
        this.context = context;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
                View row = convertView;
                if (row == null) { //#1
                    LayoutInflater inflater = context.getLayoutInflater();
                    row = inflater.inflate(R.layout.row, parent, false);
                    ViewHolder holder = new ViewHolder();
                    holder.icon = (ImageView) row.findViewById(R.id.icon);
                    holder.position = position;
                    holder.item = (TextView) row.findViewById(R.id.label);
                    row.setTag(holder);
                } // #2
                ViewHolder newHolder = (ViewHolder) row.getTag();
                newHolder.item.setText(MenuItems[newHolder.position]); // #4
                newHolder.icon.setImageResource(R.drawable.sushi);
                return row;
    }
}

A: If you are creating a new instance of array adapter, for example:
ArrayAdapter<T> sushiAdapter = new ArrayAdapter<T>(context, R.layout.row, R.id.label, MenuItems)

this instance already has it's own implementation of getView method. So it's obvious that in your case when override getView, you provide the complete implementation by yourself and take all responsibilities for filling views with content.
So if you want to add add something new, please call super.getView() before.
But in your case, when you have Image + text view you need to extend BaseAdapter and provide all implementation by yourself. ArrayAdapter provides simple functionality and extending it is not a common practice.


text:
Q: How to properly access Strings of 2D array in JavaScript? Solved
I thought this would be a simple task, but I can't seem to figure out how to properly access elements of a 2D array in JavaScript.
The array was created by taking keys and values from an object:
uassPairs.push(value);
uassPairs[uassPairs.indexOf(value)][1] = key;

^That occurred within a $.each loop.
Let's say that at uassPairs[0][0] I have the String "foo" stored. If I run alert(uassPairs[0]);, it displays foo to the screen.
However, if I try to access "foo" via uassPairs[0][0], only the first character of the string is displayed: f.
Additionally, trying to access uassPairs[i][1] (where i is some index), I again only receive the first letter of that string - to clarify, the string stored in the index 1 column. The arr[i][j] format is how I've seen most folks handling arrays here.
How do I access the entire string, not just a single character?
Thank you.
Edit: thank you to dandavis, the correct syntax is arr[0, 0], not arr[0][0]. Cheers.

A: Apparently
uassPairs[uassPairs.indexOf(value)]

returns value again. So if value was a string then another index acces like [1] returns the character at the specified position.
The strange thing is that it looks as if you were allowed to assign something to that position. However, there is no assignment, so a read access again returns the character.


text:
Q: Script for last edited/modified time & date I have been searching around for a script that will give me the time & date that a google sheet was last modified.
I have a list of all the google sheet workbook IDs in column E of a sheet called 'Planner Directory' and I would like it to return the time & date last modified in column F.
This would be really helpful if anyone can assist?

A: Since you already have all the data in a Google Sheet, I think the easiest way to get this working automatically is using Google Apps Script. I will leave an example of how it would work.
Try this code:
function myFunction() {
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet20"); // Change it to the name
                                                                 // of the sheet you. are using
  var range = ss.getDataRange();
  var values = range.getValues();
  for(var i=1; i<values.length; i++)
  {
    values[i][1] = lastModifiedTime(values[i][0]); // 0 is the column number in my testing sheet
                                                   // where the IDs are.
                                                   // 1 is the column number where the time will be.
  }
  range.setValues(values);
}

function lastModifiedTime(id)
{
  var file = DriveApp.getFileById(id);
  return file.getLastUpdated();
}

Input data:
Replace the Sheet ID fields with valid IDs.

Result:

Remember to change the format of the column where you want you have the last modified time to Number > Date time.
Now, in order for you to automate this script you can use a time-driven trigger from Google Apps Script so that the script runs every 5, or 10 minutes for example and so that you can always get the latest time in the results.
Trigger:

References:

*

*Method: getLastUpdated()

*Time-driven triggers

A: I was able to use the suggested script to get the last modified date of a file, which is great but I am having two issues. In the next column of the spreadsheet I had a formula which would tell me if the last modified date is today's date.  =if(C2=Today(),"Updated","Not Updated")

*

*The formula doesn't recognize the last modified date that is entered by the script, even though I have that column format set to Date.

*When the script suggested in this thread runs, it wipes out the formula entirely and replaces it with static text.


text:
Q: Is there a difference in Initializing javascript variable using [] versus {} Well I have always used
var j= {};
j['field'] = value;

Apparently below works too
var j= [];
j['field'] = value;

Any difference?
Edit: Sorry I guess I used the wrong word json here instead of object. My bad. But my questions till stands. Most people are explaining the difference between an array and object to me which I am familiar with.
I always do var x = []; x.push('blah') etc.
I also do var x = {}; x.Name = 'Michael'; x.Age = 21 etc.
What I was surprised to see and what prompted me to ask this is I saw code that goes like
var x = [];
x.name = 'Michael';
This is something I wasn't used to and hence posted the question.
Thanks for all the answers. I have marked accepted answer which addressed my question the best

A: Your objects aren't "JSON", they're (empty) object and array literals.  JSON is the serialized form you get by passing such a value of JSON.stringify.
The latter won't work if you do try to convert it to JSON, even though it's legal JavaScript:
var json = [];             // ok, it's an array
json["field"] = "value";   // still OK - arrays can have properties too
JSON.stringify(json);
> "[]"

i.e. you just get an empty array, because when you try to serialize an array you only get out the numerically indexed properties from 0 to myArray.length - 1, and not named properties.

A: [] is an array initializer
{} is an object initializer

A: *

*[] is a zero length array literal.

*{} is an empty object literal.

A: [] creates an Array instance (which is an object instance with certain additional properties/methods), {} an Object instance.
The one created using [] will have methods from Array's prototype like push(), slice() etc. whereas the second one won't.

A: [] is array, and {} is literal object.
You can do both things because both are JavaScript primitive objects.
When you do it in an array, you're setting an property in your array object, and you're not adding an item to it.
When you do it in the literal object... well, as said above, you're setting an property in that object.

A: There is no difference.
In both cases you are setting a property on an object. It is just that the second object is an array.
In other words, in your latter example, you effectively use the same technique that you use in your former example, that is, you are setting a property on an object. in this case, an array. But you are not changing the contents of the array.

A: Below is an javascript Object,
var json = {};
json['field'] = value; //Valid

Below is an javascript Array,
var json = [];
//Below does not set the value in array instead it sets a property name field.
//json['field'] = value;
json.push(value);      //proper way to add an element to an array

Both are Javascript objects and nothing to do with JSON yet.
JSON is a notation, a convention followed across different language for easy data communication. Basically the above will be transformed to a string literal following JSON convention which can be read across different language.
There are two methods,

*

*JSON.stringify - Convert the above to string literal following JSON notation.

*JSON.parse     - Convert the JSON string literal to a valid javascript object.

The same function are available as a library in most languages which allows you to communicate across different language easily.


text:
Q: Get google maps getplace lat and long I am using google maps api in localhost for address auto completion. The address fetching fine, However, i would like to fetch the lat/lon as well, but my code no longer work, what to do ?
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=true"></script>

place = places.getPlace();
address = place.formatted_address;
latitude = place.geometry.location.H;
longitude = place.geometry.location.L;

Cheers all

A: You can always reference the latitude and longitude properties of the place.geometry.location object like this:
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();

The PlaceGeometry class's location property is a LatLng object:

*

*https://developers.google.com/maps/documentation/javascript/reference#PlaceGeometry

*https://developers.google.com/maps/documentation/javascript/reference#LatLng
The H and L properties are undocumented, and are liable to change with every new release of the Maps API, and shouldn't be used.


text:
Q: How to run alert only once within range in if statement? function sendWeightAlert(){
 if(petInfo.weight >= 100 && previousWeight < 100){
  $(".treat-button").one("click", function(){
    alert(petInfo.name + " is going obese...");
  });
 }
}

Here basically what I want to do is to display the alert only once when the petInfo.weight is equal or over 100 and stop alerting every time after I click on the treat-button. I have tried to look for the answer and tried everything I could but it's not working... Please help me good code masters!!

A: You can create a variable and check its state before showing the alert

let showAlert = true;
$(".treat-button").click(function() {
  if ((petInfo.weight >= 100 && previousWeight < 100) && showAlert) {
    alert(petInfo.name + " is going obese...");
    showAlert = false;
  }
});

A: How about declaring a global variable by default true,
make it false when you execute alert.
and add it in your if condition.
var isAlertShown = true;

and your function,
function sendWeightAlert(){
 if(petInfo.weight >= 100 && previousWeight < 100 && isAlertShown){
  $(".treat-button").one("click", function(){
    isALertShown = false;
    alert(petInfo.name + " is going obese...");
  });
 }
}

A:

var alerted = false;

var previousWeight = 99

var petInfo = {
  weight: 101,
  name: 'petName'
}

$(".treat-button").one("click", function(){
  if(!alerted && petInfo.weight >= 100 && previousWeight < 100){
    alerted = true;
    alert(petInfo.name + " is going obese...");
  }
});

TREAT

A: I run your code and it actually wokrs fine - so probably the reason is that you run sendWeightAlert() again after button click (which bind event handler again - and show alert after next click)

let previousWeight= 10;
let petInfo = { weight: 100, name: 'dog' };

function sendWeightAlert(){
 if(petInfo.weight >= 100 && previousWeight < 100){
  $(".treat-button").one("click", function(){
    alert(petInfo.name + " is going obese...");
  });
 }
}

sendWeightAlert();  // here we bind handler only once, and jQuery `one` will run it once.

<button class="treat-button">click me</button>


text:
Q: Multiple Custom Headers I am trying to add this function:
add_theme_support( 'custom-header' );

I would like this to somehow combine with multiple headers. I saw some code that was PHP that checked which template was loaded then add the image (header) that was defined in the code.
This is not totally optional since I want my theme to allow the user of the theme to change the header for his "buyers" template, the "sellers" template, so forth. Is there any way to make the 'custom header' page allow several custom headers that are called on different templates?

A: What you want to achieve is posible but not with WordPress custom-header feature because it's you can use multiple images in random sequence.
If you mean 'different page templates' you can simply hard code your images links in your templates, but this is not good solution.
Another solution is to write function which will check the name of page template and change header image.
If you need that functionality for normal users you need to create a new settings page for your theme. It should save to WP options information about template name and image for it.


text:
Q: Java MigLayout problem I'm trying to build a calculator GUI using migLayout, but I'm not familiar with this layout.
My problem is that my GUI is a straight line of buttons.
1 2 3 + 4 5 6 - ... etc

I would like to get
1 2 3 +
4 5 6 -
7 8 etc...

import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.*;

public class Calculator1 {

    public static void main(String args[]) {
        JFrame frame = new JFrame("Calculator1");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new MigLayout());

        frame.add(new JTextField("                                               "),"wrap");
        frame.add(new JButton("1"));
        frame.add(new JButton("2"));
        frame.add(new JButton("3"));
        frame.add(new JButton("+"));
        frame.add(new JButton("4"));
        frame.add(new JButton("5"));
        frame.add(new JButton("6"));
        frame.add(new JButton("-"));
        frame.add(new JButton("7"));
        frame.add(new JButton("8"));
        frame.add(new JButton("9"));
        frame.add(new JButton("*"));
        frame.add(new JButton("0"));
        frame.add(new JButton("/"));
        frame.add(new JButton("="));

        frame.pack();
        frame.setVisible(true);
    }
}

A: Try this:
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.*;

public class Calculator1 {

    public static void main(String args[]) {
        JFrame frame = new JFrame("Calculator1");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new MigLayout("fill, wrap 4", "[25%][25%][25%][25%]", "[shrink]"));

        frame.add(new JTextField("                                               "),"span 4, wrap");
        frame.add(new JButton("1"));
        frame.add(new JButton("2"));
        frame.add(new JButton("3"));
        frame.add(new JButton("+"));
        frame.add(new JButton("4"));
        frame.add(new JButton("5"));
        frame.add(new JButton("6"));
        frame.add(new JButton("-"));
        frame.add(new JButton("7"));
        frame.add(new JButton("8"));
        frame.add(new JButton("9"));
        frame.add(new JButton("*"));
        frame.add(new JButton("0"));
        frame.add(new JButton("/"));
        frame.add(new JButton("="));

        frame.pack();
        frame.setVisible(true);
    }
}


text:
Q: Detect Autofilter changes I am looking to detect any changes in an autofilter on a specific table, for the purpose of forcing a UDF that does some simple arithmetic on the table entries that are currently visible to update its result. Making the UDF volatile has had no impact so far, but it doesn't target the table directly either.
This solution (https://stackoverflow.com/a/15906275/4604845) does not work for me, probably because I have only manual calculation.
My a-little-too-dirty workaround is Workbook_SelectionChange, and while the UDF doesn't kill resource consumption this way, I'd rather avoid it in case the data grows larger. Also I have some users that are complete novices in terms of using computers, and I have trouble being confident that I can get all of them to understand that they need to click something else after updating the autofilter for the result to be correct.
Any ideas? I have tried Workbook_Change and Workbook_Calculate but none of them are triggered (or I can't figure out how to trigger them) by the autofilter changes.

A: Even if you have no other formulas on the worksheet, if you include a Subtotal() formula somewhere on the sheet referencing the table, the Subtotal() will recalculate every time the autofilter is changed.
You can use this to trigger a Calculate() event macro.
EDIT#1:
Say we have an AutoFilter set on column A of a sheet named data.  Sheet data also contains many other formulas.  If we use the Calculate() event in the data worksheet, we will get fires any time any of these formulas re-calculate.
We create a new worksheet called trigger.  This new worksheet is comletely empty except for a single cell that contains:
=SUBTOTAL(3,data!A1:A20)

It is in the trigger worksheet that we place the Calculate() event macro.
Now if we are using the data worksheet, we can make arbitrary changes and perform various recalculation and nothing fires, but if we change the AutoFilter, the event macro on trigger will see the change and fire!

A: How to trigger Worksheet Calculation following AutoFilter changes while in Manual Calculation
As we know changes to the AutoFilter selection cannot be automatically detected, as these changes do not trigger any Workbook Event or Worksheet Event. Therefore, only option available is to have the user triggering worksheet calculations with an action i.e. Cell Selection Change, Right Click, Double Click, etc; or just by pressing [F9]; which is the preferable action as there is nothing else involved and it's the way it's designed to work.
Nevertheless, at the user request, I'm providing this VBA code that although needs to be initiated by user's action, this action can be done immediately after the AutoFilter change is selected, just by Double Clicking.
The DoubleClick can be unrestricted (double clicking any cell in the worksheet) by using this code:
Private Sub Worksheet_BeforeDoubleClick(ByVal rTrg As Range, blCancel As Boolean)
    rTrg.Worksheet.Calculate
End Sub

or setting up to three types of restrictions:

*

*Any cell of the Table

*The Header of the Table

*The Body of the Table
Use this code to restrict the DoubleClick area:
Currently the code is set to restriction type 1, use variable bRType to change it to the preferred type. This code assumed the name of the Table is Table1 (change as required)
Private Sub Worksheet_BeforeDoubleClick(ByVal rTrg As Range, blCancel As Boolean)
Dim ObjLst As ListObject, rTbl As Range, bRType As Byte

    Rem Set Restriction Type
    Rem 1: DoubleCliking any cell of the Table - Default
    Rem 2: DoubleCliking any cell of the Table Header
    Rem 3: DoubleCliking any cell of the Table Body
    bRType = 1

    With rTrg
        Set ObjLst = .Worksheet.ListObjects("Table1")

        Select Case bRType
        Case 2:     Set rTbl = ObjLst.HeaderRowRange
        Case 3:     Set rTbl = ObjLst.DataBodyRange
        Case Else:  Set rTbl = ObjLst.Range
        End Select

        If Not (Intersect(.Cells, rTbl) Is Nothing) Then
            .Worksheet.Calculate
            blCancel = True
        End If
    End With
End Sub

Both procedures are Worksheet Events, therefore ensure that the one that you decide to implement goes into the module of the worksheet holding the Table. (do not change the name of the procedures)


text:
Q: How to query in sequelize by an association without loading the associated object? I have multiple models which are associated to each other.
e.g:
var User = sequelize.define("user")
var Project = sequelize.define("project")

Project.hasMany(User)

Now I want to query all Projects containing a specific user.
e.g.:
Project.findAll({
    include: [
        {
            model: User,
            where: { id }
        }
    ]
})

This works, but loads also the user and attaches it to the project.
How can I tell sequelize, that the user should not be added to the found projects?

A: I just managed to address the same problem (using Sequelize 4).
You can specify that you don't want any fields of User just using attributes: [], so your code would become:
Project.findAll({
    include: [
        {
            attributes: [],
            model: User,
            where: { id }
        }
    ]
})

A: Many-to-many relationships are defined using the belongsToMany() method in sequelize on both sides. For your specific use case you would have to use a through model for the relation and query the through model directly.
var User = sequelize.define("user")
var Project = sequelize.define("project")
var ProjectUser = sequelize.define("projectUser")

Project.belongsToMany(User, {
    through: ProjectUser
})

User.belongsToMany(Project, {
    through ProjectUser
});

ProjectUser.findAll({
    where: {
        UserId: 'someId'
    },
    // We only want the project, not the user.
    // You might need to do ProjectUser.belongsTo() for both
    // models for this to work.
    include: [Project]
})
.then(function(results) {
    // Here we are getting an array of ProjectUsers, to return all the projects
    // we map it to a new array of only projects.
    return results.map(function(userProject) {
        return userProject.Project;
    });
})


text:
Q: Trying to display tables in the one view in my MVC application I creating a repository in a MVC application which displays data in a SQL database.
In my Application view, when creating a new record i want to display my servers in my Server DB.
My Application details are in my application view and my server details are in my Server view.
Below is what i want to be in my App View, however due to this being in the App Model I don't think this is possible. Does anyone know how to have 2 different databases in the one view?

            @Html.LabelFor(model => model.Servers, "Servrs", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownList("Servers", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Servers, "", new { @class = "text-danger" })


text:
Q: lxml.etree.ParserError: Document is empty I am writing a Google Analytics scraper for research purposes. This is my first post, so sorry in advance if the format is wrong. It might be a noob question (and I have tried as suggested in #25491872), but here it comes anyways.
Python version: 2.7.6
Requests version: 2.2.1
etree.LXML_VERSION: (3, 3, 3, 0)
lxml is returning ParserError:

lxml.etree.ParserError: Document is empty

The error part of the code looks like this:
user_agent={'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/53.0.2785.143 Chrome/53.0.2785.143 Safari/537.36'}

for _ in range(row_count):
    url="http://"+linecache.getline("sourcelist.csv", i).rstrip('\n') #the error only occurs on a specific webpage: http://www.mixednews.ru

    headers = {"User-Agent": , "Accept-Encoding": "gzip, deflate"}
    print url
    page=requests.get(url, headers=headers, timeout=10)

    print page.headers
    print repr(page)

    except requests.exceptions.Timeout:
        i =i+1
        fields=[url,["TimeOut"]]
        with open ("output.csv", "ab") as o:
            writer=csv.writer(o)
            writer.writerows([fields])
        print "timeout"
        continue

    except requests.exceptions.ConnectionError: #HTTPSConnectionPool:
        i=i+1
        fields=[url, "URL not valid"]
        with open ("output.csv", "ab") as o:
            writer=csv.writer(o)
            writer.writerows([fields])
        print "URL not valid"
        continue

    except requests.exceptions.ContentDecodingError:
        i=i+1
        fields=[url, "Host server error"]
        with open ("output.csv", "ab") as o:
            writer=csv.writer(o)
            writer.writerows([fields])
        print "Host server error"
        continue
    tree=html.fromstring(page.content) #error

page.headers and repr(page) returns content:

CaseInsensitiveDict({'wp-super-cache': 'Served supercache file from PHP', 'content-encoding': 'gzip', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,Cookie', 'server': 'nginx', 'connection': 'keep-alive', 'cache-control': 'max-age=3, must-revalidate', 'date': 'Sun, 12 Mar 2017 13:36:05 GMT', 'content-type': 'text/html; charset=UTF-8'})
Response [200]

Any ideas to why this is happening, and what can be done to fix it?


text:
Q: Fill an empty XML tag using JavaScript I'm currently trying to fill an empty tag of an XML response from an API
<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <order>
        <id><![CDATA[1]]></id>
        <shipping_number notFilterable="true"></shipping_number>
        <associations>
            <order_rows nodeType="order_row" virtualEntity="true">
                <order_row>
                    <!-- More tags -->
                </order_row>
            </order_rows>
        </associations>
    </order>
</prestashop>

<!-- I have much more items but they don't matter for what I'm trying to do -->

But I can't edit it.
responseBody.getElementsByTagName("id")[0].childNodes[0].nodeValue = "test"; // Works perfectly
responseBody.getElementsByTagName("shipping_number")[0].childNodes[0].nodeValue = "test"; //  Does not Work

//responseBody being my xml body

Console is telling me that I can't access the value of undefined or null, which makes sense to me but I can't find how to fill shipping_number.
I feel so dumb right now but it's the first time I work on XML files with JavaScript
The only answer I found was to delete the tag and recreate it with its value, but I don't want to believe that you can't edit an empty tag.
Does someone have a solution?
Edit : Thanks to @kjhughes
I managed to do what I wanted:
var cdata = responseBody.createCDATASection('someValue');
responseBody.getElementsByTagName('shipping_number')[0].appendChild(cdata);

A: First of all, there's a typo in your XML.
Change
<shipping_number notFilterable="true"></shipping_number

to
<shipping_number notFilterable="true"></shipping_number>
                                                       ^

Now that you've fixed the typo, the next issue is that shipping_number has no children, so
responseBody.getElementsByTagName("shipping_number")[0].childNodes

will be empty.  Before you can proceed further, you'll have to add a child node.  Contrast this with your other working case where id already has a child, a CDATA node.
To add a child node, use Node.appendChild().


text:
Q: Heat Equation on Disk with Heat Source I am given the heat equation with a source term in polar coordinates.
$$
u_{t} = k ( \frac{1}{r} \frac{\partial}{\partial r} (r  \frac{\partial u}{\partial r}) + \frac{1}{r^{2}}\frac{\partial^2 u}{\partial \theta^2}) + g(r,\theta,t)
$$
The boundary conditions are such that:
$$
u(1,\theta, t)= 0, u(r,0, t)= u(r,\frac{\pi}{2}, t)=0
$$
The initial condition is some function such that $ u(r,\theta, 0) = f(r,\theta,t)$.
I've attempted solving for the solution through eigenfunction expansion, but I may need a different method to solve the above PDE.
Is there a better way to go about this than through eigenfunction expansion?


text:
Q: Nokogiri: How to retrieve the text from an XML::Element, excluding the text from its descendants? Is there a more elegant way to write the following code?
def get_text(element)
  text_node = element.children.find &:text?
  text_node.text if text_node
end

A: You can write
element.xpath('text()').to_s

which returns the raw text of text children of element excluding any text in descendant nodes (whereas your code only return the first text child of element).

A: Remember that the DOM is hierarchical so you need to remove the child nodes:
Starting with this:
require 'nokogiri'

xml = <<EOT
<xml>
  <a>some text
    <b>
      <c>more text</c>
    </b>
  </a>
</xml>
EOT

doc = Nokogiri::XML(xml)

If you don't mind doing it destructively:
doc.at('b').remove
doc.text #=> "\n  some text\n    \n  \n"

If you do mind:
a_node = Nokogiri::XML.fragment(doc.at('a').to_xml)

a_node.at('b').remove
a_node.text #=> "some text\n    \n  "

Strip the trailing carriage returns and you should be good to go.

A: of course this syntax will also help you

==================================

doc = Nokogiri::Slop <<-EOXML
<employees>
  <employee status="active">
    <fullname>Dean Martin</fullname>
  </employee>
  <employee status="inactive">
    <fullname>Jerry Lewis</fullname>
  </employee>
</employees>
EOXML
====================================
# navigate!
doc.employees.employee.last.fullname.content # => "Jerry Lewis"

fullname = @doc.xpath("//character")
puts fullname.text


text:
Q: how to prove homomorphism with identity element I have this,
Let $\phi: G → G$ defined by $\phi(x) = e$ , for all $x\in G$ ,where $e$ is the identity element. How to show that $\phi$ is a homomorphism?

A: We need to see that $\phi(xy) = \phi(x)\phi(y)$ for all $x,y \in G$. But $\phi(xy) = e = e\cdot e = \phi(x)\phi(y)$. So $\phi$ is a homomorphism.
These kinds of early group theory proofs about the identity pretty much always rely on the fact that $e\cdot e = e$. Another similar problem is to prove that the identity is unique -- i.e., if there are two elements $e$ and $f$ in $G$ with $ex = xe = x$ and $fx = xf = x$ for all $x \in G$, then $e=f$. See if you can work that one out too.


text:
Q: How to return correct type from a function in Typescript? I have the following interfaces:
interface Functor<T> {
  map <T1>(f: (x: T) => T1): Functor<T1>
}

interface Maybe<T> extends Functor<T> {}

Next, I have map function implementation, which takes Functor and calls it .map method:
function map<T, U>(f: (x: T) => U, a: Functor<T>): Functor<U>

function map(f, a) {
  return a.map(f);
}

If I use this map function with Maybe, return type of it will be Functor<T> instead of Maybe<T>:
// type is Maybe<number>
const mb = new Just(5);

// type is Functor<string>, but should be Maybe<string>
const result = map((x) => 'str', mb)

I can solve this by adding additional overload to map function:
function map<T, U>(f: (x: T) => U, a: Maybe<T>): Maybe<U>

But the problem is that Functor and Maybe types are in different npm packages and map function implementation doesn't know anything about Maybe.
How, can I achieve this?

A: TypeScript currently (as of 2.4) lacks higher kinded types, which is what you need to properly express the relationship between the a parameter and the return value.  If, for example, TypeScript allowed a generic type parameter to itself be generic, you could say this:
function map<T, U, F<X> extends Functor<X>>(f: (x: T) => U, a: F<T>): F<U> {...}

(using an F<X> notation I just made up), or:
function map<T, U, F extends Functor>(f: (x: T) => U, a: F<T>): F<U> {...}

(using the bare Functor in a way you can't do currently).
Then the compiler would presumably automatically infer Maybe for F.
If you think your use case is compelling enough, you might want to go to the relevant GitHub issue and show your support for it by contributing or at least giving a  to the top post.

As @Stephan pointed out, there aren't really any workarounds much better than what you're currently doing.  I've occasionally tried my hand at implementing functors and the like in not-expressive-enough languages and it ends up devolving into a sea of manual type annotations and unchecked type assertions.  I mostly recommend giving up ☹ and implementing only the specific functors you need without trying to abstract over them.
Hope that helps.  Good luck.


text:
Q: Timing Queries in Redis-Cli? This seems like it ought to be trivial, but I want to run a query through redis-cli, and then just get back how long it took on the server, along with the results. This is just for debugging purposes, to factor out problems with my client library or latency. Is there a way to do this?

A: You can set the Slow Log to 0 (zero). Doing so will log every command.
The time you will see is in microseconds, and from the documentation this time means:

The execution time does not include the I/O operations like talking
  with the client, sending the reply and so forth, but just the time
  needed to actually execute the command (this is the only stage of
  command execution where the thread is blocked and can not serve other
  requests in the meantime)

To factor in the network performance you might have to hack your client library, logging just before and after the communication with redis, leaving out any tranformation your library may do.

A: You can do this by wrapping the redis command you're investigating in a MULTI/EXEC block, where the TIME command is used right before and right after your command. For example:
Using the node library:
var multi = redis.multi();
multi.time(); // start time
multi.sunionstore(['fast_food_joints', 'pizza_hut', 'taco_bell']); // this is the command I'm investigating
multi.time(); // end time
multi.exec(function(err, responses){
    var response = responses[1]; // the response i care about
    var start = (parseInt(responses[0][0]) * 1000) + (parseInt(responses[0][1]) / 1000);
    var end   = (parseInt(responses[2][0]) * 1000) + (parseInt(responses[2][1]) / 1000);
    var execution_time = end - start; // in milliseconds
});

Or... using the command line (which is what you asked for in your question):
192.168.1.1:6379> MULTI
OK
192.168.1.1:6379> TIME
QUEUED
192.168.1.1:6379> SUNIONSTORE fast_food_joints pizza_hut taco_bell
QUEUED
192.168.1.1:6379> TIME
QUEUED
192.168.1.1:6379> EXEC
1) 1) "1450818240"
   2) "666636"
2) (integer) 48886
3) 1) "1450818240"
   2) "666639"

And then do the math yourself. The above example took 3 microseconds.


text:
Q: Exact mp4 framerate (synchronisation issues) I'm writing an audio stretcher to convert audio from 24p to PAL video.
24p is 24000 / 1001 ~= 23.976 fps
PAL is exactly 25 fps.
The algorithm I use is very simple. If 'm' is the output sample number and 'n' is the input sample number, then m = floor(f(n + 0.5)), where f is the speed factor. In this case f = 25 / (24000 / 1001) = 1001 / 960 . Yes am basically dropping samples every 30 or so samples, but the audio should be in sync, plus you will a ringing of around 2kHz.
However, in the resulting video, I am out of a/v sync by probably 0.1 - 0.3 secs 1.5 hours into the film.
I tried increase the precision of calculation by using long doubles instead of doubles, but I get the same audio offset. Anyways, this should not be a factor as long as you have you have >9 sig figs becuase there are 345 600 000 samples in a 2hr film sampled at 48kHz.
I don't think I am missing out of some magic syncing data, as when I split the original video into a video and wav file and play them together, they stay completely in sync.
I realised that media containers / streams, probably don't store the frame rate as a rational number, i.e. 24000 / 1001 , (correct me if I am wrong!) they would use a decimal. If so, my speed up factor is incorrect.
I tried getting the fps from various players: ffmpeg 23.98, vlc 23.976023. But I really need to know the exact framerate of the original video. By the looks of it takes it to 5 decimal places (0.2s / 2hrs). I tried plugging in vlc's fps, but I was still out by a bit.
So all in all, is there any way to extract the exact framerate from an mp4 file?
Or an I missing something here like interleaving that keeps the streams in sync.
(The code is here https://raw.github.com/rhlee/speed-alpha/22c28ddcb357649efd3dedd099e159ff024657fe/speed.c if anyone is interested.)


text:
Q: OrientDB one to many using Object API I'm using the Object API with OrientDB, and I need to change one of my fields. I currently have something like:
class Book { String author }

But I want to change it to:
class Book { List<String> authors }

My question is: how do I persist this list of Strings in OrientDB? Do I have to declare the list as @Embedded? Do I have to define the Schema as LINKLIST?
I tried the latter, which resulted in:
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to com.orientechnologies.orient.core.db.record.OIdentifiable

And, if I make the type in the database an Embbed, then it results in the error:
Caused by: java.lang.IllegalArgumentException: Type EMBEDDED must be a multi value type (collection or map)

Which doesn't provide to much information unfortunately.
So, how can I best fix this?

A: Start point:
I created a new db from the Java API, and I saved a list of authors.
CLASS BOOK
public class Book {

private List<String> authors;

public void setAuthors (List<String> pAuthors){
    this.authors = pAuthors;
}

public List<String> getAuthors(){
    return this.authors;
}

}
CLASS MAIN
public class DatabaseTipoObject {

private static String remote="remote:localhost/";

public static void main(String[] args) {
    String nomeDb="Object";
    String path=remote+nomeDb;

    try {
        OServerAdmin serverAdmin = new OServerAdmin(path).connect("root", "root");
        if(serverAdmin.existsDatabase()){
            System.out.println("Database '"+nomeDb +"' exist..");
        }
        else{
            serverAdmin.createDatabase(nomeDb, "object", "plocal");
            System.out.println(" Database '"+nomeDb +"' created!..");
        }

        OObjectDatabaseTx db = new OObjectDatabaseTx (path);
        db.open("root","root");

        db.getEntityManager().registerEntityClass(Book.class);
        Book book = db.newInstance(Book.class);
        List<String> myAuthors = new ArrayList();
        myAuthors.add("Archimede");
        myAuthors.add("Pitagora");
        book.setAuthors(myAuthors);

        db.save(book);
        System.out.println("Data inserted!" );

        //get info by query
        for (Book book_retrive : db.browseClass(Book.class)) {
            System.out.println("#: " +book_retrive.getAuthors().get(0) );
            System.out.println("#: " +book_retrive.getAuthors().get(1) );
        }

        db.close();

        serverAdmin.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From Studio:
the object 'Book' was created, and it has the field 'authors' as embeddedlist. (Created automatically)


text:
Q: What does 'wakeups' number represent when dumping all alarms using adb When i dump all alarms using the command adb shell dumpsys alarm, I see the number "wakeups" (17 below).
What does this mean - it is the number of times this  app has already woken up the phone or the number of times it is scheduled to wake up in the future.
If this is a cumulative tally of the past wakeups by this app - does this number ever get reset?
Alarm Stats:
 +442ms running, 17 wakeups:

A: It shows how many times the alarm has fired. The phone may have been awake when it fired.


text:
Q: Wishing to end a while: loop with break     nc = dict(zip(nation,cap))
    print("Countries and Capitals :{}".format(nc))

    k = 0
    while k != 5:
        k = input("input : ")
        if k == 1:
            break
        if k != 1:
            key = k
            print("The capital of {} is {} ".format(key,nc[key]))

#This only makes an error when I type in 1. I want it to stop the program when pressed 1. What can I do about it?

A: input("input ") returns a string.
You could do:
nc = dict(zip(nation,cap))
    print("Countries and Capitals :{}".format(nc))

    k = 0
    while k != 5:
        k = int(input("input : "))
        if k == 1:
            break
        if k != 1:
            key = k
            print("The capital of {} is {} ".format(key,nc[key]))

A: input() returns string by default.
So,
You need to take k as integer input using int() function.
k = int(input("input..."))


text:
Q: Applying do while loops My code is currently unable to start at the beginning of the program which is 'Please type in...'.  I want the code to be able to return to the beginning statement everytime choice 1 or 2 is executed. The while statement does not satisfy this as I cant use the while statement before 'choice' is declared. I understand that I'm suppose to be using a do while loop but everytime I try to implement it - it gives me an error with braces.
The following is a snippet of my code:
    System.out.println("Please type in 1 for a customer to view their portfolio, 2 to trade stocks or 3 to exit the application");
    int choice = Integer.parseInt(input.nextLine());
    {
while (!"3".equals(choice));
    {
        if (choice == 1) {
            System.out.println(mycustomers[menuchoice].toString());
            return;
                         }
        if (choice == 2) {
            String StockSelect = "Please select a stock";
            for (int i = 0; i < mystocks.length; i++) {
                // [i] is the element we are accessing
                StockSelect += " " + i + " " + (mystocks[i].getSymbol());
            }

            System.out.println(StockSelect);

            int stockchoice = Integer.parseInt(input.nextLine());

            System.out.println("Select 1 to buy or 2 to sell?");
            int choice2 = Integer.parseInt(input.nextLine());

            if (choice2 == 1) {
                System.out.println("How many stocks would you like to buy ");
                int volumebought = Integer.parseInt(input.nextLine());
                for (int i = 0; i < numofstocks; i++) {
                    mycustomers[menuchoice].setBalance(
                            mycustomers[menuchoice].getBalance() - (volumebought * mystocks[i].getprice()));
                    mycustomers[menuchoice].setPortfolio();
                }
                System.out.println(mycustomers[menuchoice].toString());
                return;
            }
            if (choice2 == 2) {
                System.out.println("How much stocks would you like to sell ");
                int volumesold = Integer.parseInt(input.nextLine());
                for (int i = 0; i < numofstocks; i++) {
                    mycustomers[menuchoice].setBalance(
                            mycustomers[menuchoice].getBalance() + (volumesold * mystocks[i].getprice()));
                            mycustomers[menuchoice].setPortfolio();
                }
                System.out.println(mycustomers[menuchoice].toString());
                return;
            }

        }
        if (choice == 3) // how to exit application
        {
            System.out.println("Thank you for using the application");
            System.out.println("The current state of all customers are:");
            for (int i = 0; i < mycustomers.length; i++) {
                System.out.println(mycustomers[i].toString());
            }
            System.out.println("The current state of all stocks are:");
            for (int i = 0; i < mystocks.length; i++) {
                System.out.println(mystocks[i].toString());
            }
            System.exit(0);
        }

    }

}}}

How would I implement the do-while loop so that it goes back to the initial statement every time after executing the code - if only if the input is not 3?

A: Ask for input inside the while loop, like this:
choice = Integer.parseInt(input.nextLine());