text:
Q: Why does $\sum_{x,y} p(x,y) log(P(x)P(y))$ decrease as the random variables $X$ and $Y$ become more dependant? I think this must be so because of how Mutual Information is defined. The formula is
$$ I = \sum_{x,y} [p(x,y) \log(p(x,y)) - p(x,y)\log(p(x)p(y))] $$
This is apparently $\ge0$. I can understand it equals 0 when $X$ and $Y$ are independent, and that its maximum is $H(X)$ (if $Y=X$). And I know the $\ge0$ result can be proven with Gibb's inequality.
But I'm curious as to how $\sum_{x,y} p(x,y) \log(P(x)P(y))$ behaves as they become more dependant. Because $I$'s lowest point is $0$ I guess that as they become more dependant it must decrease. But I can't see a way to frame the problem so as to find an answer to the question why it can only decrease as they become more dependant.
edit: I've now done multiple edits where I changed increase/decrease. To be clear $- p(x,y)\log(p(x)p(y))$ increases, $p(x,y)\log(p(x)p(y))$ decreases.

A: The quantity you're interested in is the negative of the cross entropy between the joint distribution and the product of the marginal distributions:
$$H(p(x,y), p(x) p(y)) = -\sum_{x,y} p(x,y) \log(p(x) p(y))$$
Here's an explanation of why it must decrease as $X$ and $Y$ become more dependent, assuming we hold the joint entropy constant:
We can measure the dependence between $X$ and $Y$ using the mutual information, which is defined as the KL divergence between the joint distribution and the product of the marginal distributions. That is, it measures how different the true joint distribution is from what it would be if $X$ and $Y$ were independent:
$$I(X,Y) = D_{KL}(p(x,y) \parallel p(x) p(y))$$
The KL divergence $D_{KL}(P \parallel Q)$ is equal to the difference between the cross entropy $H(P,Q)$ and the entropy $H(P)$, so:
$$I(X,Y) = H(p(x,y), p(x) p(y)) - H(p(x,y))$$
Let's consider two possible joint distributions $p_0(x,y)$ and $p_1(x,y)$, where the mutual information between $X$ and $Y$ is higher for $p_1$ than for $p_0$. Writing out the mutual information for both cases, we have:
$$H(p_1(x,y), p(x) p(y)) - H(p_1(x,y)) >
H(p_0(x,y), p(x) p(y)) - H(p_0(x,y))$$
Assume that the joint entropy is held fixed, so $H(p_0(x,y)) = H(p_1(x,y))$. In that case, these terms cancel out, and we're left with:
$$H(p_1(x,y), p(x) p(y)) > H(p_0(x,y), p(x) p(y))$$
Therefore, assuming the joint entropy is constant, the cross entropy between the joint distribution and the product of the marginal distributions increases as the mutual information between $X$ and $Y$ increases. The quantity you're interested in (the negative cross entropy) therefore decreases.


text:
Q: Convert a collection of objects with a string property to an enumeration of those strings using LINQ I have an IEnumerable object where Foo has a string property called 'Name'.  Is there an easy LINQ statement that will let me return a collection of strings from that enumeration for those names?
e.g.
IEnumerable<Foo> (which contains...)
    Foo.Name = First
    Foo.Name = Second
    Foo.Name = Third

I want to return an IEnumerable that contains 'First', 'Second' and 'Third'
Howdoyadoozat?

A: If your initial IEnumerable is called list, this will do it:
list.Select(f => f.Name);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript and JSON (DOM) So I have this kind of website where it is kinda online shop of shoes where you have a JSON file where I have to display this in HTML using javascript. So the JSON file looks like this:
[

    {
       "name": "DKNY",

       "category": "Stilettos",

       "location": "Texas",
    },

    {
       "name": "Prada",

       "category": "Wedge",

       "location": "Texas",
    },

    {
       "name": "Jimmy Choo",

       "category": "Stilettos",

       "location": "Melbourne",
    },
]

and there is this HTML file with the categories
*Wedge
*Stilettos
where once you click those categories (like for example you click Stilettos) in HTML for Stilettos, it will display all the categories and data written on json file like "stilettos" then will display the name of shoes and its location. Is there any way you could do this? into JavaScript?

A: Store all your data in variable, let's say:
var allShoes = ... //your JSON data

then add function for filter your shoes by category, like this:
function filterShoesByCategory(category) {
    return allShoes.filter(shoe => shoe.category === category); // returns filtered array - original array is kept unchanged
}

In addition you need some logic for update your DOM. It depends if you're using pure JS, jQuery or some framework.

A: You have to improve this code to fit your needs, but this is the concept you have to use.

var shoes = [{
    "name": "DKNY",

    "category": "Stilettos",

    "location": "Texas",
  },

  {
    "name": "Prada",

    "category": "Wedge",

    "location": "Texas",
  },

  {
    "name": "Jimmy Choo",

    "category": "Stilettos",

    "location": "Melbourne",
  },
];

async function show(cat) {
  if (!shoes) { //check if shoes are already loaded
    var response = await fetch("shoes.json"); //fetch the file
    shoes = await response.json(); //convert the file to JSON
  }
  var list = document.getElementById("list"); //get the output element
  list.innerHTML = ""; //clear the output element
  var selected = shoes.filter(s => s.category && s.category === cat);
  //filter the shoes to only contain elements with the right category
  selected.forEach(s => { //iterate over the shoes to display them
    list.innerHTML += "
" + s.name + "
";
  });
}
<button onclick="show('Stilettos')">Stilettos</button><button onclick="show('Wedge')">Wedge</button>


text:
Q: How do I work with JS objects in PHP more efficiently? I have an onclick button that sends a JS object to my PHP via the following AJAX (data is the name of my object):
function send_to_php() {
$(document).ready(function() {
// pt_packet = JSON.stringify(data)
console.log(data)
var request = $.ajax({
    url: "post_results.php",
    type: 'POST',
    data: (data),
    success: function(result) {
    $("#note").append(result)}})
})}

The problem is when I try to sanitize the data, I the var_dump I get is only the first array and the rest of the information is gone:
array(1) { ["{"Cheif_Complaint":"]=> array(1) { [""Mood issues""]=> string(0) "" } }

Yet this is the information I send:

I've dropped trying to sanitize the data, but now it looks like I'm having to var_export every single array and then use RegEx to get rid of the "array => (" stuff that I'm left with from var_export. Is there not an easier way to sent a JS object and work with it in PHP?

A: You had the right idea in your commented line of converting the object into a JSON string. This is how you should make the request
$.ajax({
    url: 'post_results.php',
    type: 'POST',
    data: JSON.stringify(data),
    contentType: 'application/json'
})

In your PHP script post_results.php you need to read the raw body of the POST request. You can do this by reading the PHP input stream php://input and then decoding the raw JSON string. Here is an example
$rawJsonString = file_get_contents("php://input");
$jsonData      = json_decode($rawJsonString, true);

The result should be in $jsonData to have the same structure as your JS object.


text:
Q: Converting binary string to 32bit floats with Python sometimes shifts the decimal place I'm reading out my sensor values via a protocol closely resembling Modbus RTU using Python. Sometimes, two consecutive values have their decimal point shifted by one place, say I read a voltage of 538.154 in one packet and on the next packet it shows 53.963, which I know is off by a factor of ten as the voltage is stable. I'm not really good at programming and am not sure if it is my python code or a problem in the sensor.
The above two values originate from these packets (only first few bytes given, voltage is the first value after id, function code) which I store in a variable called answ:
1:   b'\x04\x03 \xc58D\x06\x89\xd9>\x1d\x00\x00\x00\x00n~<\xd9\x11\xb4K [....]'
(correct voltage)

2:   b'\x04\x03 \xa1\xf4BW\xda(>\x95\x00\x00\x00\x00\xf6\x0f@\x16\x01.D [....]'
(off by factor of 10)

(The voltage values described are the first values in the 'payload' of both packets.)
I remove the header information via
data = answ[5:37]

first and then try to get the floating point values by
helper = 0
for i in range(0, len(data) ,4):
    try:
        global_vars.sensor_vals[helper] = float(struct.unpack(">f", bytearray(data[i:i+4]))[0])
        global_vars.sensor_vals[helper] = float("{:3.3f}".format(global_vars.sensor_vals[helper]))
        helper = helper + 1

Please excuse my crude Python code.
I also tried different approaches like bytes.fromhex(...) instead of bytearray, but with the same result.
Am I doing something wrong or does the sensor show me wrong values?
Best regards & Thank you!


text:
Q: Mouse Scroll Normalisation + Horizontal Scrolling I'm currently in the process of producing a website. This website features an element that horizontally scrolls through a carousel of images. This acts as the client's portfolio.
In an attempt to improve the user experience, I included the following script (in conjuction with jquery.mousewheel.js) to translate any vertical mouse scrolling to horizontal scrolling when hovering over the .carousel element.
$('.carousel').mousewheel(function(e, delta) {

  $(this).scrollLeft(this.scrollLeft + (-delta * 40));

  e.preventDefault();

});

This works fine in translating the input.
The problem I'm facing is that different input devices (Trackpad, Regular Mouse) scroll at vastly different rates, despite jquery.mousewheel.js handling normalisation between these devices.
If I adjust the script to allow for trackpads (-delta * 1), the regular mouse will scroll way to slowly (around one pixel per wheel adjustment). If I allow for regular mouse input (-delta * 40), trackpads will scroll ridiculously fast.
Here is an example of the intended functionality.
The only things I can think of, is that the second script is in some way interfering with jquery.mousewheel.js, perhaps preventing the normalisation initialising correctly. Secondly, and more likely, I'm not implementing this correctly.
Any insight would be greatly appreciated.


text:
Q: JanusGraph 0.2.0 Spark failed to connect to master When I use the example in Chapter 35 of JanusGraph 0.2.0 documentation, it is OK. But when I change spark.master in conf/hadoop-graph/hadoop-load.properties from local[*] to spark://192.168.63.105:7077, I get some warn infos.
There is a note in Chapter 35 of JanusGraph 0.2.0 documentation:
The example in this chapter are based on running Spark in local mode. Additional configuration is required when using Spark in standalone mode or when running Spark on Yarn or Mesos.
What is additional configuration?
The warn info:
> WARN org.apache.tinkerpop.gremlin.spark.process.computer.SparkGraphComputer - class org.apache.hadoop.mapreduce.lib.output.NullOutputFormat does not implement PersistRequestGraphAware and thus, persistence options are unknown -- assuming all options are possible

> WARN org.apache.spark.deploy.client.AppClient$ClientEndpoint - Failed to connect to master 192.168.63.105:7077

> java.lang.RuntimeException: java.io.EOFException
> at java.io.DataInputStream.readFully(DataInputStream.java:197)
> at java.io.DataInputStream.readUTF(DataInputStream.java:609)
> at java.io.DataInputStream.readFully(DataInputStream.java:564)
> at org.apache.spark.rpc.netty.RequestMessage$.readRpcAddress(NettyRpcEnv.scala:582)
> at org.apache.spark.rpc.netty.RequestMessage$.apply(NettyRpcEnv.scala:592)
> at org.apache.spark.rpc.netty.NettyRpcHandler.internalReceive(NettyRpcEnv.scala:651)
> at org.apache.spark.rpc.netty.NettyRpcHandler.receive(NettyRpcEnv.scala:636)
> at org.apache.spark.network.server.TransportRequestHandler.processRpcRequest(TransportRequestHandler.java:157)
> at org.apache.spark.network.server.TransportRequestHandler.handle(TransportRequestHandler.java:105)
> at org.apache.spark.network.server.TransportChannelHandler.channelRead(TransportChannelHandler.java:118)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:357)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:343)
> at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:336)
> at io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:287)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:357)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:343)
> at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:336)
> at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:102)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:357)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:343)
> at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:336)
> at org.apache.spark.network.util.TransportFrameDecoder.channelRead(TransportFrameDecoder.java:85)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:357)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:343)
> at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:336)
> at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1294)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:357)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:343)
> at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:911)
> at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
> at io.netty.channel.nio.NioEventLoop.processSelectedkey(NioEventLoop.java:643)
> at io.netty.channel.nio.NioEventLoop.processSelectedkeyOptimized(NioEventLoop.java:566)
> at io.netty.channel.nio.NioEventLoop.processSelectedkey(NioEventLoop.java:480)
> at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:442)
> at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:131)
> at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
> at java.lang.Thread.run(Thread.java:745)

> at org.apache.spark.network.client.TransportResponseHandler.handle(TransportResponseHandler.java:186)
> at org.apache.spark.network.server.TransportChannelHandler.channelRead0(TransportChannelHandler.java:106)
> at org.apache.spark.network.server.TransportChannelHandler.channelRead0(TransportChannelHandler.java:51)
> at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:356)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:342)
> at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:335)
> at io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:286)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:356)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:342)
> at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:335)
> at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:102)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:356)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:342)
> at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:335)
> at org.apache.spark.network.util.TransportFrameDecoder.channelRead(TransportFrameDecoder.java:86)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:356)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:342)
> at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:335)
> at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1302)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:356)
> at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:342)
> at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
> at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
> at io.netty.channel.nio.NioEventLoop.processSelectedkey(NioEventLoop.java:646)
> at io.netty.channel.nio.NioEventLoop.processSelectedkeyOptimized(NioEventLoop.java:581)
> at io.netty.channel.nio.NioEventLoop.processSelectedkey(NioEventLoop.java:498)
> at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:460)
> at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:131)
> at java.lang.Thread.run(Thread.java:745)

My configuration file is conf/janusgraph-hbase-es-test-spark.properties whose content is following:
storage.backend=hbase
storage.hostname=192.168.63.105,192.168.63.107,192.168.63.109
storage.hbase.ext.hbase.zookeeper.property.clientPort=2181
storage.hbase.table=janus_test_spark_7077
gremlin.graph=org.janusgraph.core.JanusGraphFactory
cache.db-cache=true
cache.db-cache-clean-wait=20
cache.db-cache-time=18000
cache.db-cache-size=0.5
index.search.backend=elasticsearch
index.search.hostname=192.168.63.105,192.168.63.107,192.168.63.109
index.search.elasticsearch.client-only=true

The spark version which I use is spark-2.2.0-bin-hadoop2.7.
I also try spark-1.6.0-bin-hadoop2.6, the warn info is following:
WARN org.apache.spark.scheduler.TaskSetManager - Lost task 0.0 in stage 0.0 (TID 0, SparkWorker109): java.io.InvalidClassException: org.apache.spark.rdd.MapPartitionsRDD; local class incompatible: stream classdesc serialVersionUID=6732270565076291202, local class SerialVersionUID=-1059539896677275380

at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:616)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1630)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1521)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1781)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2018)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1942)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1808)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
at org.apache.spark.serializer:JavaDeserializationStream.readObject(JavaSerializer.scala:76)
at org.apache.spark.serializer:JavaSerializerInstance.deserialize(JavaSerializer.scala:115)
at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:64)
at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:41)
at org.apache.spark.scheduler.Task.run(Task.scala:89)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:213)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Thanks for your attention and help.

A:
Here is my hadoop-load.properties.

#
# SparkGraphComputer Configuration
#
spark.master=yarn-client
spark.executor.memory=512m
spark.serializer=org.apache.spark.serializer.KryoSerializer
spark.app.name=janusgraph-data-load
spark.app.id=janusgraph-data-load
spark.executor.extraClassPath=/opt/janusgraph-lib/*:/etc/hadoop/conf:/etc/hbase/conf:/etc/spark/conf
#hdp version
spark.yarn.am.extraJavaOptions=-Dhdp.version=2.6.1.0-129
spark.executor.extraJavaOptions=-Dhdp.version=2.6.1.0-129
spark.driver.extraJavaOptions=-Dhdp.version=2.6.1.0-129


text:
Q: Ajax Call returning 'undefined' - Companies House API I'm getting data via Companies House API and it loops fine when I output the json array out on the page, but when I come to looping it out in jQuery I get about 16 undefined results. I've tried to find an answer everywhere but I just can't seem so suss it. My only thought is that the 16 undefined are buried inside another object?
Any help would be really appreciated, code below:
jQuery(function($) {
  $('[data-button-search]').click(function(event) {
      var $this = $(this);
      event.preventDefault();
      var value = $('[data-company-id]').val();
      $.ajax({
          type: 'GET',
          url: "https://link.to.site.com/company/"+value+"/name",
          dataType: 'json', // ** ensure you add this line **
          success: function(data){
              $.each(data, function(){
                  $.each(this, function(key, val) {
                      console.log(val.title + " : company number : " + val.company_number);
                      $('[data-select]').append(`
                          <option value='`+key+`'>`+val.title+`</option>
                      `);
                  });
              });
          },
          error: function(XMLHttpRequest, textStatus, errorThrown) {
              console.log("Error!");
          }
      });

  });
});

Sample Array which is a result of me entering "AWD" into the search box:
{
  "items_per_page": 50,
  "items": [
    {
      "title": "AWD  LTD",
      "description": "11308643 - Incorporated on 13 April 2018",
      "matches": {
        "snippet": [],
        "title": [
          1,
          3
        ]
      },
      "company_type": "ltd",
      "company_status": "active",
      "links": {
        "self": "/company/11308643"
      },
      "company_number": "11308643",
      "description_identifier": [
        "incorporated-on"
      ],
      "address": {
        "locality": "London",
        "postal_code": "WC1N 3AX",
        "premises": "27 ",
        "address_line_1": "Old Gloucester Street",
        "country": "United Kingdom"
      },
      "date_of_creation": "2018-04-13",
      "kind": "searchresults#company",
      "snippet": "",
      "address_snippet": "27  Old Gloucester Street, London, United Kingdom, WC1N 3AX"
    },
  ],
  "kind": "search#companies",
  "start_index": 0,
  "page_number": 1,
  "total_results": 184
}

Logged in console

A: The Issue:
The behavior you're seeing is because you're iterating over all of the properties on your returned data, and then trying to iterate of the 'items' property of each one. This results in you getting one successful return and then 16 (or however many properties the json has) undefined returns.
The Solution:
Instead of using nested $.each loops, you can refactor this block:
success: function(data){
          $.each(data, function(){
              $.each(this, function(key, val) {
                  console.log(val.title + " : company number : " + val.company_number);
                  $('[data-select]').append(`
                      <option value='`+key+`'>`+val.title+`</option>
                  `);
              });
          });
      },

... to a much simpler version:
success: function(data){
            $.each(data.items, function(key, val) {
                console.log(val.title + " : company number : " + val.company_number);
                $('[data-select]').append(`
                    <option value='`+key+`'>`+val.title+`</option>
                `);
              });
      },

In the block above, I got rid of your outer $.each loop and instead changed your inner loop to target 'data.items'.
Hope that helps.


text:
Q: AWS Simple Email Service not filtering IP addresses When using Amazon SES and defining IP Address Filters on the email server, users who are not part of the IP address filters can still send emails through Amazon SES.
I am looking to know if this is expected behaviour or if there is something that I need to do in order to get IP filtering working on Amazon SES in order to protect the email server from being compromised.
I have looked into using the IP Address Filters on the Amazon SES documentation but nothing seems to be working. I created a block list and a allow list.
I created a block list and a allow list for an environment that should not be able to access the server yet users can still send emails from Amazon SES if they know the trusted email address.


text:
Q: Best way to convert object typed data to value type I was tasked to create code that would fetch data from database using data reader and I'm curious of what is going to be the best practice between the 3 methods that I could use below to convert data from my data reader which by default fetched with a type of object.
    internal static RoomType SelectRoomType(int roomTypeID)
    {
        SqlCommand commRoomTypeSelector = ConnectionManager.MainConnection.CreateCommand();
        commRoomTypeSelector.CommandType = CommandType.StoredProcedure;
        commRoomTypeSelector.CommandText = "Rooms.asp_RMS_RoomType_Select";
        commRoomTypeSelector.Parameters.AddWithValue("RoomTypeID", roomTypeID);

        SqlDataReader dreadRoomType = commRoomTypeSelector.ExecuteReader();
        if (dreadRoomType.FieldCount != 0)
        {
            dreadRoomType.Read();
            RoomType roomType = new RoomType();
            roomType.RoomTypeID = (int)dreadRoomType["RoomTypeID"];
            roomType.RoomTypeName = (string)dreadRoomType["RoomType"];
            roomType.IsActive = ((string)dreadRoomType["IsActive"]).ToUpper() == "Y";
            roomType.LastEditDate = (string)dreadRoomType["LastEditDate"] != string.Empty ? DateTime.Parse((string)dreadRoomType["LastEditDate"]) : DateTime.MinValue;
            roomType.LastEditUser = (string)dreadRoomType["LastEditUser"];
            dreadRoomType.Close();
            return roomType;
        }
        dreadRoomType.Close();
        return null;
    }

What confuses me here is the unboxing part, According to http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx Boxing and Unboxing is quite expensive and should be avoided. I know that i could use
   int.Parse(dreadRoomType["RoomTypeID"].ToString())

instead of
   roomType.RoomTypeID = (int)dreadRoomType["RoomTypeID"];

The question is are there still ways of converting this data in a much more efficient way that both of this option and if there are no possible ways which of the two ways do you prefer to use. Thanks in advance all help and suggestions are accepted :)

A: You can use SqlDataReader.GetInt32() to avoid having to convert/parse to int again, for this you do have to know at what index the integer is within the columns selected though:
roomType.RoomTypeID = dreadRoomType.GetInt32(0);

A: Boxing isn't that expensive.
Other alternatives won't help; once you have an object, it's already boxed.
String parsing in particular is probably much more expensive than boxing.  (although I haven't measured)
If a typed API exists, you can use it to avoid boxing (eg, calling GetInt32).
(although these typed methods are sometimes just wrappers around the untyped method so that they box too)

Bottom line: Don't worry about it.
That guideline is telling you to avoid boxing things in the first place by using typed (generic) collections where possible

A: If boxing/unboxing is "slow" (it really isn't)... why would converting to a string and back not be terribly slow? (It really is a waste: boxing/unboxing is significantly faster.) I would first make sure there is a performance problem, before worrying about it, however...
In my experience, for my data, which includes thousands of items loaded at once, I found that much more performance can be gained with pre-determining the column indices (but do so dynamically with GetOrdinal!), and then I don't worry about the rest :)
For one item, as per this post, I wouldn't even worry about ordinals: it's an entirely different use-case and the "expensive" part is talking to the database.
Happy coding.

A: Boxing and unboxing are not as expensive as parsing a string and extracting an int. Please profile before doing premature optimization.

A:     private static void GetValue<T>(object o, ref T defaultValue)
    {
        try
        {
            if (defaultValue == null)
            {
                throw new Exception("Default value cannot be null");
            }
            else if (o != null)
            {
                if ((o is T))
                {
                    defaultValue = (T)o;
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

You can use the above method to Convert an object to any basic data type as follows.
Convert to dateTime
    public static DateTime GetDateTime(object o, DateTime defaultValue)
    {
        try
        {
            GetValue<DateTime>(o, ref defaultValue);
            return defaultValue;
        }
        catch (Exception)
        {
            throw;
        }
    }

Convert to Integer
    public static int GetInteger(object o, int defaultValue)
    {
        try
        {
            GetValue<int>(o, ref defaultValue);
            return defaultValue;
        }
        catch (Exception)
        {
            throw;
        }
    }

Refer and download the complete code with all basic data types here
http://www.dotnetlines.com/Blogs/tabid/85/EntryId/39/Convert-Object-type-into-its-specific-data-type-using-a-Generic-Method.aspx


text:
Q: Catch bash exit code in if statement If I do a simple test of exit codes directly with single commands:
[user@localhost ~]$ date
Tue Sep  8 14:00:11 CEST 2020
[user@localhost ~]$ echo $?
0
[user@localhost ~]$ dat
bash: dat: command not found...
[user@localhost ~]$ echo $?
127

But if I want to get them into an if sentence, I see that for the exit code 0 the output is OK, however, for the "command not found" code (it should be 127) it returns "1".
[user@localhost ~]$ date
Tue Sep  8 14:02:18 CEST 2020
[user@localhost ~]$ if [ $? -eq 0 ]; then   echo "Success: $?"; else   echo "Failure: $?" >&2; fi
Success: 0
[user@localhost ~]$ dat
bash: dat: command not found...
[user@localhost ~]$ if [ $? -eq 0 ]; then   echo "Success: $?"; else   echo "Failure: $?" >&2; fi
Failure: 1

What am I missing?

A: If you want to catch and print the exit code for each command, I would not bother saving it in a variable. This would be necessary only if you need this exit code agains at a later time, or if there are some non-zero exit codes which you don't regard as error.
Instead, I would do it like this:
Replace your existing
command_to_verify

by
if command_to_verify
then
  echo Success
else
  echo Failure: $?
fi

A: Every command has it own exit state, so the command [ 1 will override $?. To prevent this, save the exit code to a variable, and use that in the if statement;
le=$?
if [ "$le" -eq 0 ]; then   echo "Success: $le"; else   echo "Failure: $le" >&2; fi

Try it online!

1:
The single bracket [ is actually an alias for the test command, it's not syntax. For more info, check this comment on unix.stackexchange


text:
Q: GDB in DDD on Assembly .asm file won't allow me to look up variable value I've been trying to look up a value using gdb in ddd but when I type x/uw &min at the prompt I just get a return character that resembles a logic negation simple that has been tilted upward ninety degrees.
My computer is an Evolve III maestro and my operating system is linux amd 64 architecture Ubuntu 22.04 LTS.
I've tried looking at keyboard settings and making sure they're standard to US settings. I really need this debugger to work properly so any help would be appreciated. Thanks.


text:
Q: Uncaught ReferenceError: xx is not defined at HTMLInputElement.onchange I am trying to add the textbox value but getting the error:

"Uncaught ReferenceError: Buffalo is not defined at HTMLInputElement.onchange

Blade file showing red error on onchange="------"
Code is

    @foreach ($buffalodata as $item )

            {{$item->buffaloID}}
            <input type="number" id="eachmorningmilk{{$item->buffaloID}}" name="eachmorningmilk{{$item->buffaloID}}" onchange="totalmilk({{$item->buffaloID}})" value="0">
            <input type="number" id="eacheveningmilk{{$item->buffaloID}}" name="eacheveningmilk{{$item->buffaloID}}" onchange="totalmilk({{$item->buffaloID}})"  value="0">
            <input type="text"   id="eachtotalmilk{{$item->buffaloID}}"   name="eachtotalmilk{{$item->buffaloID}}" value="00" readonly>

    @endforeach

onchange code
function totalmilk(id){
    var morningmilk = "#eachmorningmilk"+id;
    var eveningmilk = "#eacheveningmilk"+id;
    var totalmilk = "eachtotalmilk"+id;
    eachbmorning = parseInt($(morningmilk).val());
    eachbevening = parseInt($(eveningmilk).val());
    var eachbuffalototalmilk = eachbmorning + eachbevening;

    document.getElementById(totalmilk).value=eachbuffalototalmilk;

Ref Image

A: Given this error

"Uncaught ReferenceError: Buffalo is not defined at HTMLInputElement.onchange

I suspect what causing's it, is because $item->buffaloID contains the value Buffalo thus generating the following code
onchange="totalmilk(Buffalo)"

Since Buffalo is not defined in your Javascript, Javascript will raise this error.
You can easily fix it by surround the value with quotes
onchange="totalmilk('{{$item->buffaloID}}')"

And it will generate the following
onchange="totalmilk('Buffalo')"


text:
Q: Strange "uneditable" symbols on specific linebreaks in vim, Debian 10 (Pic) In all files I open with vim, I see a strange 1/2 symbol showing up on the second line, but only if the second line contains a unix linebreak. It always appears on line 2 of the file. The character is neither editable nor selectable.
I'm using a fresh vanilla Debian 10 install with no modifications to any vimrc files and no .vimrc in my user dir. Actually I just created my .vimrc file and it made no difference.
See pic:

Edit 1:
I'm now also seeing ;?;? at the beginning of all new files and files that begin with an empty unix linebreak. Like the 1/2 symbol, these characters are neither editable nor selectable.
In the below pic, deleting the leading empty line will cause the ;?;? to disappear and 1/2 to reappear on an empty line 2 after closing/reopening the file.

Edit 2:
Answering questions from the comments:

*

*Here is a pastebin of od -cx /etc/apt/sources.list, the source of the first screenshot.

*My terminal software is SecureCRT, with setting in options Terminal > Emulation = Xterm. These extra characters do not appear when using a vanilla version of PuTTY.

*The output of vim's :help startup-terminal|set term is term=xterm.

*My locale from cat /etc/default/locale = LANG="en_US.UTF-8"

A: Changing the SecureCRT character encoding in Session > Properties > Terminal > Appearance from Default to UTF-8 fixed the problem.
Also, changing the SecureCRT Session > Properties > Terminal > Emulation > Terminal from Xterm to Linux also fixed the problem, but with a 16-color terminal restriction.


text:
Q: Error with flume and remote hdfs sink I'm trying to run flume with an hdfs sink. The hdfs is running in a different machine properly and I can even interact with the hdfs from the flume machine, but when I run flume and send events to it I get the following error:
2013-05-26 14:22:11,399 (SinkRunner-PollingRunner-DefaultSinkProcessor) [WARN - org.apache.flume.sink.hdfs.HDFSEventSink.process(HDFSEventSink.java:456)] HDFS IO error
java.io.IOException: Callable timed out after 25000 ms
    at org.apache.flume.sink.hdfs.HDFSEventSink.callWithTimeout(HDFSEventSink.java:352)
    at org.apache.flume.sink.hdfs.HDFSEventSink.append(HDFSEventSink.java:727)
    at org.apache.flume.sink.hdfs.HDFSEventSink.process(HDFSEventSink.java:430)
    at org.apache.flume.sink.DefaultSinkProcessor.process(DefaultSinkProcessor.java:68)
    at org.apache.flume.SinkRunner$PollingRunner.run(SinkRunner.java:147)
    at java.lang.Thread.run(Thread.java:679)
Caused by: java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:258)
    at java.util.concurrent.FutureTask.get(FutureTask.java:119)
    at org.apache.flume.sink.hdfs.HDFSEventSink.callWithTimeout(HDFSEventSink.java:345)
    ... 5 more

Again, conectivity is not an issue since I can interact with hdfs using the hadoop command line (the flume machine is NOT a datanode).
The weirdest part is that after killing flume I can see that the tmp file is created in hdfs but it's empty (and the .tmp extension remains).
Any ideas as to why could this be happening? Thanks a lot!

A: Check 3 things, if your firewall is off i.e. iptables should be stopped. Secondly, value of the property agent.sinks.hdfs-sink.hdfs.path = hdfs://PUBLIC_IP:8020/user/hdfs/flume and not Private IP.
And change
agent.sinks.hdfs-sink.hdfs.callTimeout = 180000 because the default is 10000 ms which is very less time for HDFS to react.
Thanks,
Shilpa


text:
Q: Share Connection Speed, Possible? is it possible to share the connection speed between two servers / PCs
example :
person A have a speed of 8mbps and person B have a speed of 2mbps
so the download speed of person A is more than the person B
i was wondering if person A can share his connection speed (to be a ISP) to person B , so person B may get more download speed ?

A: The answer is yes.  It's called load balancing.  However, the configuration can be a bit tricky and depends a lot on your available hardware and the specifics of the servers, their OSs, etc.
This thread has some suggestions that will get you started.  For detailed help, you'll have to post a lot more information about your servers, connections, networking devices, etc., and what you have tried so far.


text:
Q: ASP.net MVC : Create MVC 5 Application using EF6 with Code First and Existing Database I have to create an application in MVC 5 using EF6. I have already created the schema for the database in SQL Server 2012 and now I want to query this in my app.
The workflow that seems fit is Code First with Existing Database and I have tried to follow below resources but they are a little confusing to me as I am a beginner.
Is there a way I can still use my DB schema in SQL server and go ahead with Code First approach using generated data models from DB.
http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
http://www.asp.net/mvc/overview/getting-started/introduction/getting-started

A: Yes you can reverse engineer code first from existing DB schema. Here you can find instructions how do do it. Since you already created your DB schema you can start from point 3. Reverse Engineer Model.
This process will create for you a DbContext, POCO classes for the tables you selected in the wizard and the mappings. You can use it to query your DB.
When your DB schema changes in the future you can either regenerate POCO classes again or simply edit them by hand (if column type changed simply change the property type, if new column was added add new property to your class). Most devs use reverse engineer code first from existing DB only as a starting point when they need to target existing legacy database. After initial creation all future changes in schema are reflected by manually editing the classes that were originally generated by the tool.


text:
Q: Babel's funny import Since no browser I know implements currently the ES6 modules interface - but transpilers do - I tested babel with this simple example
import { getUsefulContents } from "file.js";
getUsefulContents("http://www.example.com", data => {
  doSomethingUseful(data);
  });

I just wanted to see how does it transpile these lines. To my surprise it produced following output:
"use strict";

var _fileJs = require("file.js");

(0, _fileJs.getUsefulContents)("http://www.example.com", function (data) {
  doSomethingUseful(data);
});

The last line looks mysterious to me - especially the (0, _fileJs.getUsefulContents) part, what is going on there? What is the purpose of that (0, ...) on that line?

A: Calling a function like that forces it to call it in the global context.

function whoAmI() {
  document.querySelector('pre').innerText += this.name + '\n';
}
window.name = 'window';
var mike = {
  name: 'mike',
  whoAmI: whoAmI
};
mike.whoAmI();
(0, mike.whoAmI)();

The reason this works is because when it evaluates (0, filesJs) it runs through each of the statements in the parentheses, similar to how you can declare multiple variables using a ,
var a = 1,
    b = 2,
    ...

As the last expression is reference to a function, it uses that when evaluating the function call with the next set of parentheses. Being that the expression was already evaluated, the _filesJs context is lost. It's effectively the same as doing this:
0; // Legal, just pointless
var f = _filesJs.getUsefulContents;
f("http://example.com", ...);


text:
Q: How do I escape illegal characters in a sunspot/solr fulltext search? I have a sunspot/solr setup for fulltext searching model attributes.  My QA just searched on " and +, both of which caused a 500 error:
Solr Response: orgapachelucenequeryParserParseException_Cannot_parse__Encountered_EOF_at_line_1_column_0_Was_expecting_one_of_____NOT______________________________QUOTED______TERM______PREFIXTERM______WILDTERM__________________NUMBER______TERM____________
How can I make these query strings safe?  Is there a method in Sunspot to handle this?

A: There is no method in Sunspot to filter those, because they are valid in certain kinds of Lucene queries. Sunspot is using the DisMax Query Parser by default, so you can read its documentation to learn more about those characters.

[DisMax] is designed to be support raw input strings provided by users with no special escaping. '+' and '-' characters are treated as "mandatory" and "prohibited" modifiers for the subsequent terms. Text wrapped in balanced quote characters '"' are treated as phrases […]

If you intend to never use those characters, you can filter them yourself from queries(the back slash is to escape minus sign).
Post.search do
  keywords params[:q].gsub(/[+\-"]/,'')
end

You may want to wrap that in a controller method, if you're invoking Sunspot's search method within a controller, or a model method if you're calling Sunspot's solr_search method from within your class's own custom search method.


text:
Q: iOS: update a field in model any time managed object model gets modified I have a "last updated" field on my model. Any time a managed object model gets changed, I'd like that field to get updated. Is there any way I can have this happen automatically? Or do I need to just update that field manually when I make the other modifications?

A: "Is there any way I can have this happen automatically?"
No. Core Data is not a database, it's an API for abstract object graph management. It has no concept of uniqueness, auto-incrementing values, etc.
"Or do I need to just update that field manually when I make the other modifications?"
Correct, for example having a lastModified property that your application sets with each change.

A: You could KVO all keys in your entity but maybe this is not necessary. I would suggest you only update the lastUpdated property when you actually save the object because before that you could still just throw away the changes (either on purpose or e.g. because the app terminates).
Therefore, you can simply override willSave. This is specifically designed for this kind of situation (it mentions a "last-modified" attribute), but note the caveats mentioned in the documentation

If you want to update a persistent property value, you should typically test for equality of any new value with the existing value before making a change. If you change property values using standard accessor methods, Core Data will observe the resultant change notification and so invoke willSave again before saving the object's managed object context. If you continue to modify a value in willSave, willSave will continue to be called until your program crashes.
For example, if you set a last-modified timestamp, you should check whether either you previously set it in the same save operation, or that the existing timestamp is not less than a small delta from the current time. Typically it's better to calculate the timestamp once for all the objects being saved (for example, in response to an NSManagedObjectContextWillSaveNotification).


text:
Q: UITableView - move people from one section to another I would like to create a tableview where I can move people from different departments into other departments, and I have some code posted below.
I have an issue with this, I can never seem to get it to get the usual ui gadget to move rows. I don't want the user to edit/delete the rows; simply move them about however the "move" buttons never seem to appear.
Is there something I am doing wrong?
Also I am not sure if I am doing the move code right.
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Departments";

    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.tableView.allowsSelectionDuringEditing = YES;

    _objects = [NSMutableArray array];

    NSDictionary *sales = @{ @"name" : @"sales",
                             @"employees" : @[ @"Mike", @"Tom", @"Alex"] };

    NSDictionary *marketing = @{ @"name" : @"marketing",
                             @"employees" : @[ @"Heather", @"Richard", @"Simon"] };

    [_objects addObject:sales];
    [_objects addObject:marketing];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
}

#pragma mark - IBActions

-(IBAction) editButton:(id)sender
{
    [self setEditing:!self.editing animated:YES];
}

#pragma mark - UITableView delegate

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_objects count];
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *department = [_objects objectAtIndex:section];
    NSArray *employees = department[@"employees"];
    return [employees count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId" forIndexPath:indexPath];

    // Configure the cell...
    NSDictionary *department = [_objects objectAtIndex:indexPath.section];
    NSArray *employees = department[@"employees"];
    NSString *employeeName = [employees objectAtIndex:indexPath.row];
    cell.textLabel.text = employeeName;

    return cell;
}

-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSDictionary *department = [_objects objectAtIndex:section];
    return department[@"name"];
}

- (BOOL) tableView: (UITableView *) tableView canEditRowAtIndexPath: (NSIndexPath *) indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    if( fromIndexPath == toIndexPath ) return;

    NSDictionary *department = [_objects objectAtIndex:fromIndexPath.section];
    NSArray *employees = department[@"employees"];
    NSString *employeeName = [employees objectAtIndex:fromIndexPath.row];

    [self.tableView beginUpdates];
    [_objects removeObjectAtIndex:fromIndexPath.row];
    [_objects insertObject:employeeName atIndex:toIndexPath.row];
    [self.tableView endUpdates];

    [tableView reloadData];
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    if (indexPath.section == 1 && [_objects count] > 1)
    {
        return YES;
    }
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(editingStyle == UITableViewCellEditingStyleDelete){
        [_objects removeObjectAtIndex:indexPath.row];
        NSArray *rows = [NSArray arrayWithObject:indexPath];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:rows withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];
    }
}

A: call this method after your array initialised. [self.tableView reloadData]
This will load the table data once again.


text:
Q: Is there a way to determine the URL where a particular Visualforce page is being used in an org? I know there's the Preview URL that's available from the Setup > Visualforce Pages screen. But I have many VF pages that use variable data and standard controllers and would like to view those VF pages in context.

A: I don't think there's a simple way to do what you're asking without writing some code to search your visualforce pages and related controllers to find the information you'll need. I say that because if you go to the VisualForce page's properties in Setup, you can click on "Where is is used?" to see where a page is called from. You can also click on "Dependencies" find related classes that must be present for it to run.
The methods in the Controllers for the referring pages that call a page will determine what the final pageReference will look like. Don't forget that the final url will also likely be parameter and recordId specific (depends on the design of the page).
What you're asking for is not a trivial matter to determine. I would expect creating a script to collect this information would be the most appropriate way to successfully compile the information you're looking for *if you want this task to be automated for you.


text:
Q: Help with sum of a series of fractions I was expected to have this series $$S = \frac{1}{2^{2}} + \frac{1}{2^{3}} + ... + \frac{1}{2^{k}} $$
summed up to 1. However, I couldn't do that using this calculation:
$$ S = \frac{1}{2} + S - \frac{1}{2} $$ where $$ \frac{1}{2} + S = \frac{1}{2} + \frac{1}{2^{2}} + \frac{1}{2^{3}} + ... + \frac{1}{2^{k}} $$ was a geometric series.
Thus, $$ S = \frac{1}{2} + S - \frac{1}{2} = a(\frac{1 - r^{k}}{1 -r}) - \frac{1}{2} $$
where $ a = \frac{1}{2} $, and $ r = \frac{1}{2} $.
Substituting the values of $a$ and $r$ into the expression above, I got $$ S = \frac{2^k - 1}{2^k} - \frac{1}{2} $$
Then taking limit on the right hand side $$ \lim_{k \to \infty} (\frac{2^k - 1}{2^k} - \frac{1}{2}) $$
I got $$ S = \frac{1}{2} $$
What did I do wrong?
EDIT: The reason I wanted to have $S$ summed to 1 because of this requirement (highlighted in yellow):

A: Note that there are two cases for each case containing $k$ letters (e.g. for 2 letters: aa,bb; for 3 letters: acc, bcc). So the probability of all the cases actually sum to $$2\cdot \frac{1}{2^2}+2\cdot \frac{1}{2^3}+\cdots =\frac{1}{2}+\frac{1}{2^2}+\cdots =\frac{1/2}{1-1/2}=1$$

A: $$\sum_{k=0}^{n} r^k=\frac{r^{n+1}-1}{r-1}$$
Here
$$S = \frac{1}{2^{2}} + \frac{1}{2^{3}} + \frac{1}{2^{4}}... + \frac{1}{2^{k}} $$
$$S=\frac{1}{2^2}\left(1+\frac{1}{2}+\frac{1}{2^2}+...+\frac{1}{2^{k-2}}\right)$$
$$S=\frac{1}{4}\frac{2^{-(k-1)}-1}{2^{-1}-1}=\frac{1}{2}(1-2^{1-k})$$
So if $k\to \infty$, $S\to \frac{1}{2}$


text:
Q: Env variables are undefined on frontend with React I'm trying to move all the sensitive variables to .env file. It works just fine server side on Node but I'm having trouble doing it with React.
I referenced these answers: this and that
1.I changed my .env so it looks like this
REACT_APP_SIGNER_PK = xxxxxx-xxxxx-xxxxxx

Added the variable itself to the file containing script
const REACT_APP_SIGNER_PK = process.env.REACT_APP_SIGNER_PK;

*Placed .env inside of my root folder

*I restart the server after the changes with yarn run dev
To test out the changes I put this print statement from the file where I put the env variable in
console.log(REACT_APP_SIGNER_PK);

On the restart of the local server I check the console and in the terminal where the server is running I see the print statement with my environmental variable, but in the browser console I see this print as undefined
The only thing that differs in my action from the references is that I use yarn run other than npm start
What did I do wrong?

A: Thanks to the comment from @OFRBG I managed to find a solution.
Adding REACT_APP_ app to the my .env variables did not work because I was using nextJS instead of Create-React-App.
In order to fix the problem this problem for nextJS users add NEXT_PUBLIC_ instead as a prefix for your .env variables


text:
Q: How to add particles to scene on collision I'm a bit confused by this. I've got a particle system as a prefab, and I only want it to appear in the scene when a collision happens with the player. I also want it to appear in the same place as the player like the player has exploded. Here's what I have so far, forgive me if this is way off:
public class particleManager : MonoBehaviour {

    public ParticleSystem explosion;

    public bool emittingParticles = false;

    public void Update () {
            if (emittingParticles == true) {
            explosion.enableEmission = true;
        }
    }
}

    void OnCollisionEnter2D (Collision2D col) {

            if (col.gameObject.tag == "enemyPlanet") {

                particles.emittingParticles = true;

    }
}

Am I on the right lines here? How do I instantiate the particle?


text:
Q: webpack: express can't find bundle Error 404 I know this question is was asked a lot but i have tried everything and nothing work!
Here the thing: I am working on an Isomorphic React App for practise witch a big copy of this tutorial of 2017 that i try to update it
https://medium.com/@phoebe.greig/headache-free-isomorphic-app-tutorial-react-js-react-router-node-js-ssr-with-state-and-es6-797a8d8e493a
app folder
build folder
A big part of her code is now deprecated and i recode it.
One important things, I use webpack for compile all of the folder of the app including the index.js file and not babel for all the folder and only webpack for the index.js file like she did.
The problem is I render my HTML page by a js fonction renderFullPage.js
export default function renderFullPage(html, preloadedState)
    return `
    <!DOCTYPE html>

    <html lang="fr">

        <head>
            <meta charset="UTF-8"/>
            <title> Isomorphic Router React Mongoose App initialised with data</title>
        </head>

        <body>

            <div id="root">
                ${html}
            </div>
            <script>
                window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
            </script>
            <script type="application/javascript" src="bundle-app.js"></script>

        </body>
    </html>

    `;
}

My goal is to call a request to the express server who will collect with Mongoose MongoDB's data and send it back to the client.
Before continuing with React, I want to check if everything is ok by using console.log for some data in client.the HTML using React load perfectly
That the problem: no console.log is display in client because it can't load the bundle-app.js file from the build folder. I get everytime an Error 404 and i believe that it's because i set my path wrong but i have no idea what i doing wrong. Error loading Script http://localhost:8080/bundle-app.js
I have no idea in what path my server got loached also.
Here are the app.js file from app/server:
import path from 'path';
import express from 'express';
import cors from 'cors';

import router from './router';

const app = express();

const assets = express.static(path.join(__dirname,'../'));

app.use(cors());
app.use(assets);

app.get("*", router);

export default app;

And here and the webpack.config.js:
{
  "name": "ssr-react-router-mongoose-isomorphic-app",
  "version": "1.0.0",
  "description": "isomorpic app",
  "main": "./app/index.js",
  "scripts": {
    "build:server": "babel ./app/server -d build/server",
    "build:watch:server": "babel ./app/server -d build/server --watch",
    "build:client": "webpack --mode development --config webpack.config.js/  --progress ",
    "build:watch:client": "webpack-dev-server -d --hot --config webpack.config.js --watch",
    "build:prod": "npm run build:server && npm run build:client",
    "start": "npm run build:prod && NODE_ENV=production node ./build/server/index.js",
    "start:dev": "parallelshell \"npm run build:watch:client\" \"nodemon ./build/server/bundle-server.js\" ",
    "start:dev:client": "webpack-dev-server"
  },
  "author": "Rando Mathias",
  "license": "ISC",
  "dependencies": {
    "babel-polyfill": "^6.26.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongoose": "^5.10.6",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.11.6",
    "@babel/core": "^7.11.6",
    "@babel/preset-env": "^7.11.5",
    "@babel/preset-react": "^7.10.4",
    "babel-loader": "^8.1.0",
    "file-loader": "^6.1.0",
    "html-webpack-plugin": "^4.5.0",
    "nodemon": "^2.0.4",
    "parallelshell": "^3.0.1",
    "webpack": "^4.44.2",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
var fs = require('fs');

var nodeModules = {};
fs.readdirSync('node_modules')
  .filter(function(x) {
    return ['.bin'].indexOf(x) === -1;
  })
  .forEach(function(mod) {
    nodeModules[mod] = 'commonjs ' + mod;
  });

var config = { // la configuration commune pour les 2 modes.
  devtool: 'inline-source-map',
  context: path.resolve(__dirname, './app'),
  entry: {
    '/bundle-app': ['babel-polyfill','./index.js'],
    '/components/bundle-components': ['./components/App.js','./components/Home.js'],
    '/server/bundle-server': ['./server/app.js','./server/index.js','./server/renderFullPage.js','./server/router.js','./server/routes.js'],
    '/services/bundle-services': './services/getMongoose_data.js'
  },
  target:'node',
  output:
  {
    path: path.resolve(__dirname, './build'), // on crée l'application de sortie dans un dossier "public"
    publicPath: '/',
    filename: '[name].js', // les fichier bundle seront dans le chemin qui est le nom des fichiers d'entrées
  },
  module:
  {
    rules: [
      {
        test: /\.(js|jsx)$/, // pour les fichiers de type js et jsx
        loader: 'babel-loader', // on charge babel un transcompileur
        exclude: /node_modules/,
        options:
        {
          presets: ['@babel/preset-env', '@babel/preset-react']
        }
      },
    ]
  },
  // plugins: [
  //   new HtmlWebpackPlugin({
  //       template: './app/server/renderFullPage.js',
  //       filename: 'index.html',
  //       inject: 'body',
  //   }),
  // ],
};

module.exports = (env, argv) =>
{
    return config;
}

I want to load the bundle-app.js from the build folder
Thanks in advance for your help

A: You start your script from root of your project.
"start": "npm run build:prod && NODE_ENV=production node ./build/server/index.js",

And tries to access static files by setting pass to them as below.
const assets = express.static(path.join(__dirname,'../'));

But issue here is that path should be relative to the script start folder.
In your case it is your project root folder where you execute npm start command.
You need to change static files path to set be relative to your project root instead of server bundle.
If I'm right it will be as below.
const assets = express.static(path.join('./build'));


text:
Q: How can I save user's followers in firebase? React Native I have two collections in my database one called Buyers and the other called Sellers. Whenever the buyer follows the seller I save the seller's Uid in a subcollection called userFollowings in the Buyers collection.
How can I save the followers Uids too? Save the buyer uid in a subcollection called userFollowers in the Sellers collection every time a buyer follows a seller?
here's my code:

const onFollow = () => {
  firebase.firestore()
      .collection("Buyers")
      .doc(firebase.auth().currentUser.uid)
      .collection("userFollowings")
      .doc(props.route.params.uid)
      .set({})

}
const onUnfollow = () => {
  firebase.firestore()
      .collection("Buyers")
      .doc(firebase.auth().currentUser.uid)
      .collection("userFollowings")
      .doc(props.route.params.uid)
      .delete()
}

A: You can use a batched write, as follows, in such a way the two writes complete atomically.
  const db = firebase.firestore();

  const onFollow = () => {
    const buyerID = firebase.auth().currentUser.uid;
    const followerID = props.route.params.uid;

    const buyerFollowerRef = db
      .collection('Buyers')
      .doc(buyerID)
      .collection('userFollowings')
      .doc(followerID);

    const sellerFollowerRef = db
      .collection('Sellers')
      .doc(followerID)
      .collection('userFollowers')
      .doc(buyerID);

    const batch = db.batch();
    batch.set(buyerFollowerRef, { foo: 'bar' });
    batch.set(sellerFollowerRef, { foo: 'bar' });
    batch.commit();
  };

For the onUnfollow function, use batch.delete().

You could also use a Cloud Function triggered when the doc in the userFollowings subcollection is created.
This would be the way to go if the end-user does not have the permission to write to the userFollowers subcollection, and therefore cannot execute the above batched write.


text:
Q: Column misalignment in grid I am having difficulty aligning my columns in my grid. I just cant figure out why columns are not aligning. First i thought its due to scroll bar but even if i remove scroll bar i cant get columns to align. This is my html code

        <colgroup>
            <col style="width: 120px;">
                <col style="width: 60px;">
                    <col style="width: 50px;">
                        <col style="width: 70px;">
                            <col style="width: 70px;">
                                <col style="width: 50px;">
                                    <col style="width: 100px;">
                                        <col style="width: 100px;">
                                            <col>
        </colgroup>

                First Col
                Second col
                Third col
                Fourth col
                Fift col
                Sixth col
                seventh col
                eigth col

            <colgroup>
                <col style="width: 120px;">
                    <col style="width: 60px;">
                        <col style="width: 50px;">
                            <col style="width: 70px;">
                                <col style="width: 70px;">
                                    <col style="width: 50px;">
                                        <col style="width: 100px;">
                                            <col style="width: 100px;">
                                                <col>
            </colgroup>

                     Tom cruise

                     AB

                     1

                     7

                     1

                     CCC

                     Arnold

                     AB

                     1

                     7

                     1

                     CCC

This is my Fiddle which could be easy for you guys to help me out.
You can see that output is different in chrome and IE and i really dont understand why is it like that.

A: I am sorry if I am wrong or not sure for what you're trying to achieve. But, in my opinion, you can set the width of each columns in the second and the third rows with the same size with all column in your first row, so that the table is aligned. You can set the size directly in the "TH" markup.

                First Col
                Second col
                Third col
                Fourth col
                Fift col
                Sixth col
                seventh col
                eigth col

And
                     Tom cruise

                     AB

                     1

A: The first thing is, that a closing  is missing. You also shouldn't set width to more than max-width!
To your problem now:
Just remove your "overflow-y: scroll; " from the div containing the second table and you are ready to go...
I think that's all you need to do.

A: My last attempt on this topic. I have used fixed width and I think it works out. If you can't define a certain % value you might need to use different fix values for different screen resolutions / devices. Fiddle at the bottom of the post.
CSS Code (Changed .gridHover {width: 640px;}
    .overflow {
  overflow-y: auto;
  overflow-x: hidden;
  height: 480px;"
}

.gridHover {
    width: 640px;
    margin-bottom: 20px;
}
.gridHover th, .gridHover td {
    padding: 8px;
    line-height: 20px;
    text-align: left;
    vertical-align: top;
    border-top: 1px solid #dddddd;
}
.gridHover th {
    font-weight: bold;
}
.gridHover thead th {
    vertical-align: bottom;
}

HTML CODE (changed it to the original 8 col layout again):

            <colgroup>
                <col style="width: 120px;">
                    <col style="width: 60px;">
                        <col style="width: 50px;">
                            <col style="width: 70px;">
                                <col style="width: 70px;">
                                    <col style="width: 50px;">
                                        <col style="width: 100px;">
                                            <col style="width: 100px;">

            </colgroup>

                    First Col
                    Second col
                    Third col
                    Fourth col
                    Fift col
                    Sixth col
                    seventh col
                    eigth col

                <colgroup>
                    <col style="width: 120px;">
                        <col style="width: 60px;">
                            <col style="width: 50px;">
                                <col style="width: 70px;">                                    <col style="width: 70px;">
                                        <col style="width: 50px;">
                                            <col style="width: 100px;">
                                                <col style="width: 100px;">

                </colgroup>

                         Tom cruise

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

                         Arnold

                         AB

                         1

                         7

                         1

                         CCC

You can check the result in this fiddle -> http://jsfiddle.net/4KB3C/56

A: You are using two different tables. that's why you are getting the alignment issue. I suppose this is what you require.
http://jsfiddle.net/4KB3C/35/

        <colgroup>
            <col style="width: 120px;">
                <col style="width: 60px;">
                    <col style="width: 50px;">
                        <col style="width: 70px;">
                            <col style="width: 70px;">
                                <col style="width: 50px;">
                                    <col style="width: 100px;">
                                        <col style="width: 100px;">
                                            <col>
        </colgroup>

                First Col
                Second col
                Third col
                Fourth col
                Fift col
                Sixth col
                seventh col
                eigth col

            <colgroup>
                <col style="width: 120px;">
                    <col style="width: 60px;">
                        <col style="width: 50px;">
                            <col style="width: 70px;">
                                <col style="width: 70px;">
                                    <col style="width: 50px;">
                                        <col style="width: 100px;">
                                            <col style="width: 100px;">
                                                <col>
            </colgroup>

                     Tom cruise

                     AB

                     1

                     7

                     1

                     CCC

                     Arnold

                     AB

                     1

                     7

                     1

                     CCC

A: Change the max width to 100%, because it doesn't make sense if the original widht is smaller than the max widht.
.gridHover {
width: 100%;
margin-bottom: 20px;
max-width: 100%;
}

I delete your padding that cause your table width to be minimized by that, and the line-height that is a little annoying.
.gridHover th, .gridHover td {
text-align: left;
vertical-align: top;
border-top: 1px solid #dddddd;
}


text:
Q: Pointer to object created in parameter I have a class called Rectangle which holds two pointers to objects of the class Point2D.
class Rectangle: public GeoObjekt
{
private:
    Point2D* lu;
    Point2D* ro;
public:
    Rectangle(Point2D lu, Point2D ro);
}

Rectangle::Rectangle(Point2D lu, Point2D ro) {
    this->lu = &lu;
    this->ro = &ro;
}

To create an object of this class, I call the following line:
Rectangle rectangle(Point2D(0, 0), Point2D(2, 1));

The constructor is working fine, but when I try to access Point2D* lu; or Point2D* ro;, I get an access violation exception:

Exception thrown at 0xFEDC8589 in Rectangle.exe: 0xC00005: Access violation while executing at position 0xFEDC8589.

I checked it with the debugger and the values inside Point2D* lu; or Point2D* ro; are completely different from the values they initially had. They change after leaving the constructor.
Can someone tell me what I am doing wrong?
Note: The line Rectangle rectangle(Point2D(0, 0), Point2D(2, 1)); should remain as it is.

A: Change the members lu and ro to be Point2D instead of Point2D*.
The Point2Ds you supplied in the constructor are destroyed on the next line, so your pointers end up pointing at nothing (dangling pointers).


text:
Q: Update item in child adapter in nested recycler view from activity I have a nested recyclerview in my activity as following:

Activity xml has recyclerview (Parent)-> recycler view  adapter's xml has another recyclerview (Child)
I am using a media player with seek bar in my child adapter.
I have setup the media player in my activity to handle onDestroy and onPause methods. But I want to pass the mediaPlayer.currentPostion to the child adapter.
How can I update the progress of media player from activity to my child adapter view?
I tried doing mainAdapter.notifyDataSetChanged and set current position in recyclerview's model FROM ACTIVITY but it may be an expensive task as the media player's progress is updated in 100 milliseconds.


text:
Q: Why is this iframe not loading? Why won't this iframe work? I can't see why it isn't.
<iframe src='https://www.etsy.com/listing/175183631/beautiful-heroic-knights-armour'>
You browser does not support iframes and so cannot utilise our store.
</iframe>


text:
Q: C++ Knowing the type of Derived ptr after retrieving from a Base container I'm trying to implement some new capabilities to already existing codes. The existing codes contain a pure abstract class with a decode and encode method for message parsing/mapping. A Handler class inherit from this message interface, as well as from a class (let's call this Fields) that contains all the fields to be mapped. The Handler class only contains the definitions for the virtual methods from the interface. Inside the definition is where a mapping class (call it Mapping) that have all the logic for mapping the fields in the Fields class is called. This forms a Message.
class Interface
{
  virtual void Decode(char * buf, int len);
  virtual void Encode(char * buf, int len);
}

class Fields
{
  type1 field1;
  type2 field2;
}

class Mapping : public Mapping_Rules
{
  // Rules for mapping field1
  // Rules for mapping field2

  static int len = sizeof(type1) + sizeof(type2); // Redacted codes

  void Read()  { // Perform mapping from char buf to class structure }
  void Write() { // Perform mapping from class structure to char buf }
}

class Handler : public Fields, public Interface
{
  void Decode(char * buf, int len)
  {
    // Do stuff
    Mapping obj;
    obj.Read();
  }

  void Encode(char * buf, int len)
  {
    // Do stuff
    Mapping obj;
    obj.Write();
  }
}

There are several of these Messages, and what I want to do is create a generic container to store different types of Messages. I created my own Base interface that the Fields class can inherit from, and store the Handlers pointers (which inherit from Fields which inherit from the Base interface) after casting them to the Base pointers. So I ran into a problem with this, which is when I retrieve the pointer from the container, I don't know which type it originally was. This is a problem for me because the decode and encode methods that I mentioned before requires a length, which is unique to each message. So I need to know the type to pass in the correct length.
class My_Own_Interface { virtual ~My_Own_Interface(); }

class Fields : pubic My_Own_Interface {}

// Somewhere in the code
Handler * handler;
My_Own_Interface * container[5];
container[i] = static_cast<My_Own_Interface *>(handler));

item = container[i]; // Item is wondering what type he/she is because his/her creator
                        // is so bad at OOP design
// End

To resolve this, I'm trying to perform dynamic_cast<> on the container's item to see which Derived type it was.
if (dynamic_cast<Handler *>(item)) { // Do stuff }

Of course this works, but I read that it was not good design to re-cast the Base ptr back to the Derived ptr. So I was wondering, how can I design my container stuff to have good OOP design/structure without changing or changing too much of the original codes? I apologize ahead of time for showing bad designing on my part.


text:
Q: Variational inference engines After doing some research on the topic, I have noticed a surprising deficit of inference packages and libraries that rely on message-passing or optimization methods for Python and R.
To the best of my knowledge, these methods are extremely useful. For example, for a Bayes Network (directed, acyclic) belief-propagation alone should be able to give exact answers. However, most inference software that is available online (e.g. STAN, BUGS, PyMC) rely on MCMC methods.
In the Python case, to the best of my knowledge, neither PyMC, scikit-learn or statsmodels include variational inference algorithms such as belief propagation, message-passing methods or any of their variants.
Why is that? Are these methods less used in practice because they are seen not as powerful or generic as their MCMC counterparts? or Is it simply a matter of lack of manpower and time?

A: Some years have passed. STAN now implements ADVI (gradients of the ELBO with reparameterization trick), using the vb command (which I guess stands for Variational Bayes). E.g., in R:
library("rstan") # load the rstan library
fit = vb(model, data, output_samples = 20000, adapt_iter = 10000 ,init = list('param1' = param1, ...), seed)

Pyro is a python library that implements BBVI (gradients of the ELBO with log-derivative trick + variance reduction techniques). Main code is:
import pyro
auto_guide = pyro.infer.autoguide.AutoNormal(model)
adam = pyro.optim.Adam({"lr": 0.02})
elbo = pyro.infer.Trace_ELBO()
svi = pyro.infer.SVI(model, auto_guide, adam, elbo)
for step in range(1000):
    loss = svi.step(data)

A: Have you looked at Edward? The Inference API supports among other things Variational inference:

*

*Black box variational inference

*Stochastic variational inference

*Variational auto-encoders

*Inclusive KL divergence: KL(p∥q)


text:
Q: Constructing a trapping region in a 2D dynamical system
Consider a system of the form $$\frac{d}{dt}x \enspace = \enspace 2-\left(b+1\right)x + ax^2y$$ $$\frac{d}{dt}y\enspace=\enspace bx-ax^2y$$

This is the context of some homework I have. I've already proven that one fixed point exists (namely $\left(x^*,y^*\right)=\left(2,\frac{b}{2a}\right)$).
The remainder of the question assumes $a=b=1$. I'm asked to sketch the nullclines and construct a trapping region for the flow. I'm basing my method off of how Strogatz approaches the Selkov model of glycolysis in his textbook. A phase portrait of that model can be found on the 7th slide here.
Constructing the trapping region for my system is almost the same process as how Strogatz does it for glycolysis, but in my case the nullcline associated with $\dot{y}=0$ is asymptotic with the y-axis, whereas Strogatz has a handy y-intercept to work with.
The trapping region should look something like the thing on page 3 here. The difference is that I'm not sure where the upper end of the diagonal line stops and the horizontal line starts.
Thanks.


text:
Q: Ignore/skip weekends with strtotime I'm using strtotime within a while statment to automatically update entries in a database.
It adds on an amount of days depending on what the user has stated in the previous page.
Using this code:
    $calendardate = strtotime ( '+'.$calendarday.' day' , strtotime ( $date ) ) ;
    $calendardate = date ( 'Y-m-d' , $calendardate );

How can I get it to skip weekends? I need to use the same variable ($calendardate) but I need it to ignore Saturdays and Sundays.
Any help is most appreciated :)

A: $now = date("Y-m-d H:i:s");
$h = date("H:i:s");
$two_weekdays_later = strtotime(date("Y-m-d H:i:s", strtotime($now)) . " +2 weekdays $h");

A: In the end I settled on iterating day by day, testing if something is a Saturday or Sunday. Otherwise it's too hard to account for end of year etc. (granted I had other requirements too, like skipping other days than just weekends, but likely you'll end up with the same requirements one day - like skipping holidays etc.).

A: Use the date function as follows:
if ((date("w", $calendardate) == 0) || (date("w", $calendardate) == 6))
{
  echo "weekend";
}

Sunday = 0,
Saturday = 6
If you use date("N", $calendardate), then the numbers run for 1 = "Monday" through 7 = "Sunday"
http://php.net/manual/en/function.date.php
Note that $calendardate needs to be a unix timestamp as per the specification in the link.


text:
Q: SetWindowPos changes context menu size If a context menu is open in the program being resized/repositioned it's size and position are also changed, is there any way around this?
Example

A: Popup menus operate their own modal message loops. Key-presses are handled by the menu. Mouse clicks either invoke menu items, navigate sub-menus, or close the menu.
In short, there's no way for the user to invoke a move or size of a window whilst a menu is running its modal message loop.
Because of this, the designers of the system don't care what happens to the menu in the scenario that you describe because there's no supported way for that scenario to occur. It's happening for you because, I guess, you have a timer that calls SetWindowPos on the window that owns the menu.
The way around this is for you not to move or size windows whilst they have popup menus open.


text:
Q: Controlling when drawing finishes in openlayers When drawing a polygon in openlayers, it seems like the default behavior is to complete the polygon when either the first vertex is clicked again, or when the last vertex drawn is clicked again.  Is there anyway to prevent the drawing from finishing when the last vertex drawn is clicked, so that the only way to finish the drawing is by clicking again on the first vertex of the polygon?

A: I ended up achieving this by setting the finishCondition for the draw interaction to ol.events.condition.never.  Then I do a check for whether I am clicking on the first point I drew, in which case I call the finishDrawing() function.

A: You have to override this method
/**
 * Determine if an event is within the snapping tolerance of the start coord.
 * @param {ol.MapBrowserEvent} event Event.
 * @return {boolean} The event is within the snapping tolerance of the start.
 * @private
 */
ol.interaction.Draw.prototype.atFinish_ = function(event) {

Here, the potentiallyFinishCoordinates variable containes the "candidates" point used to determine if the last click is "at finish" of the drawing.
For the polygon case, that variable contains the first and the last drawn points.
potentiallyFinishCoordinates = [this.sketchCoords_[0][0],
        this.sketchCoords_[0][this.sketchCoords_[0].length - 2]];

Try removing the second element of that array.


text:
Q: Why method defined like "cons[B >: A](v: B)" accepts argument of type which is not supertype of A? I am studying variance in scala right now, and I think I have a good understanding of contravariance. For example given trait List[-A], I know that List[Int] is a supertype of List[AnyVal].
But say that I have the following trait:
trait List[+A] {
  def cons(hd: A): List[A]
}

Why is cons parameter type wrong?
Why it is necessary to have def cons[B >: A](v: B): List[B] ?
For example:
val animal_list: List[Animal] = List(tiger, dog)

if we call:
animal_list.cons(tiger)

since Tiger <: Animal, doesn't cons ran into problem? Since B is Tiger and A is Animal and B >: A is not true.

A: Why is cons's parameter type wrong?
trait List[+A] {
  def cons(hd: A): List[A]
}

Compiler give you error:
covariant type A occurs in contravariant position in type A of value hd
because method parameters count as contravariant positions, but A is covariant.
Let's imagine that this method declaration would compile. Then we could do:
class ListImpl[A] extends List[A] {
  override def cons(hd: A): List[A] = ???
}

val strings: List[String] = new ListImpl[String]
val values: List[Any] = strings // OK, since List[String] <: List[Any] (in List[A], A is covariant)
values.cons(13) // OK(??), since values's static type is List[Any], so argument of cons should be Any, and 13 conforms to type Any

Is the last line above really OK? We are calling cons on values. values is the same as strings, and strings is object of type ListImpl[String]. So cons invocation in the last line is expecting String argument, but we are passing Int, because values's static type is List[Any] and Int conforms to Any. Something is definitely wrong here - which line is to blame? The answer is: cons method declaration. To fix this issue, we have to remove covariant type parameter A from contravariant position (in cons declaration). Alternatively we can make A non-covariant.
See also these questions: #1, #2.
... doesn't cons ran into problem?
trait List[+A] {
  def cons[B >: A](v: B): List[B]
}

val animal_list: List[Animal] = List(tiger, dog)  // We are assuming that List.apply and concrete implementation of List is somewhere defined.

No, animal_list.cons(tiger) invocation is type-correct.
I assume that Animal is common supertype of Dog and Tiger, and that dog and tiger are instances of Dog and Tiger respectively.
In animal_list.cons(tiger) invocation, both A and B type parameters are instantiated to Animal, so cons method takes form of:
def cons[Animal >: Animal](v: Animal): List[Animal]

Animal >: Animal constraint is satisfied because:

Supertype and subtype relationships are reflexive, which means a type
  is both a supertype and a subtype of itself. [source]

The argument to cons is Tiger which conforms to type Animal, so the method invocation is type-correct.
Notice that if you force B to be instantiated to Tiger, like animal_list.cons[Tiger](tiger), then this invocation won't be type-correct, and you'll get compiler error.
See similar example here.


text:
Q: Showing Empty Screen in FlowListView in Xaml Xamarin.Forms How to do FlowListView in XAML Xamarin.Forms?
Here is my Code:
XAML:
<flv:FlowListView FlowColumnCount="3" SeparatorVisibility="None" HasUnevenRows="true" x:Name="grid_list" ItemsSource="{Binding list_grid}" HeightRequest="100" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
    <flv:FlowListView.FlowColumnTemplate>
      <DataTemplate>
        <Image Source="{Binding Image}" Margin="20" VerticalOptions="Fill" HorizontalOptions="Fill" XAlign="Center" YAlign="Center"/>
      </DataTemplate>
    </flv:FlowListView.FlowColumnTemplate>
  </flv:FlowListView>

CODE.cs
 public partial class PlanCampaign_DetailPage : ContentPage
{
    ObservableCollection<CarosualImages> list_grid { get; set; }
    public PlanCampaign_DetailPage()
    {
        InitializeComponent();
        this.BindingContext = this;

        list_grid = new ObservableCollection<CarosualImages>()
        {

             new CarosualImages { Image="maharastra.jpg"},
             new CarosualImages {Image="delhi.jpg"},
             new CarosualImages {Image="delhi.jpg"},
             new CarosualImages {Image="delhi.jpg"},
             new CarosualImages {Image="delhi.jpg"},

        };

        grid_list.ItemsSource = list_grid;

    }

ModelClass:
public class CarosualImages
{
    public string Image { get; set; }
}

Could anyone tell that where i did mistake here, this is showing Empty Screen.

A: Here is the code for INotifyPropertyChanged
public class CarosualImages : INotifyPropertyChanged
{
    private string _name = String.Empty;

    public CarosualImages()
    {
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

     public string ImageName
     {
        get { return _name; }
        set
        {
            _name= value;
            OnPropertyChanged();
        }
     }
 }

A: Put Public before
ObservableCollection<CarosualImages> list_grid { get; set; }


text:
Q: lost profile access to 3 separate computers the same day. computers just lock up I have three dell computers with Windows 7 professional on the Server using Windows Server 2003.
On 9/11 those three computers which were installed on the system in my office all froze up.  When you try to reset them they get to the Windows screen and the curser just goes round and round.  In safe mode the user and password boxes come on and we can get in but no access to the server or internet.
We have tried to delete the profile and set up a new one to get the computer to allow us to sign in under a different domain and it seemed to work but then shortly it went back to the same problem.  Two other computers and 2 laptops on the same server are not affected at all in the same office.  Any ideas.

A: You most likely have a virus on these machines. It was just waiting until 9/11 to act.
I have heard of viruses that wait until certain days. Then crash or empty the C drive.


text:
Q: WildFly 10 NoDefClassFound com/fasterxml/jackson/jaxrs/cfg/ObjectWriterModifier To ease developing my endpoints returning JSON, I want to enable prettyprinting.
The solution I'm tyring to implement is adding a filter that injects an ObjectWriterModifier enabling the default pretty printer, if the query string is ?pretty=1.
Deployment fails as it cannot find the class com/fasterxml/jackson/jaxrs/cfg/ObjectWriterModifier
which is contained in jackson-jaxrs-base-2.7.4.jar under modules/system/layer/base/com/fasterxml/jackson/core/jaxrs/jackson-jaxrs-json-provider of my WildFly 10 installation.
In my build.gradle I do specify the dependicy as provided:
dependencies {
    providedCompile 'javax:javaee-api:7.0'
    providedCompile 'com.fasterxml.jackson.core:jackson-core:2.7.4'
    providedCompile 'com.fasterxml.jackson.core:jackson-annotations:2.7.4'
    providedCompile 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.7.4'
}

Here is module.xml for jackson-jaxrs-json-provider
<module xmlns="urn:jboss:module:1.3" name="com.fasterxml.jackson.jaxrs.jackson-jaxrs-json-provider">
     <resources>
        <resource-root path="jackson-jaxrs-json-provider-2.7.4.jar"/>
        <resource-root path="jackson-jaxrs-base-2.7.4.jar"/>
        <resource-root path="jackson-module-jaxb-annotations-2.7.4.jar"/>
    </resources>

    <dependencies>
        <module name="javax.api"/>
        <module name="javax.ws.rs.api"/>
        <module name="javax.xml.bind.api"/>
        <module name="com.fasterxml.jackson.core.jackson-annotations"/>
        <module name="com.fasterxml.jackson.core.jackson-core"/>
        <module name="com.fasterxml.jackson.core.jackson-databind"/>
    </dependencies>
</module>

I don't see how WildFly can't find a class that's inside one of the jars it provides

A: Have a look at the class loading documentation. You may need to add a module dependency as all modules aren't just automatically added as a dependency to deployments.


text:
Q: any idea how gnash is doing? For those who don't know GNASH is an open source flash movie player. It can also run as a browser plugin. However I don't know its cross-browser support. I think it only supports firefox and the konqurer web browsers so far. Just want to know if people have started using the product, what their experience was so far using it, etc.

A: I'm currently using it in Google Chrome and it works great. The development is ongoing, but the progress is not that fast. I hope it will continue to evolve until it becomes a viable flash replacement, which will happen at the point it starts playing flash 10 videos...


text:
Q: PHP dynamic object properties syntax - is there a way to write this within one statement? In PHP the following syntax is possible (access dynamic object property):
foreach($props as $prop) {
    echo $my_object->$my_property;
}

Also this is possible therefore:
foreach($obj as $o) {
    $prop = $o->key;
    echo $my_object->$prop;
}

The question is - can I write the above code within one line? I tried:
$my_object->$o->key;
$my_object->($o->key);

Both gives me an error. Can i write this within one statemen somehow?


text:
Q: How can i fill one datatable column with rows and the other columns later? i get a few thousends Data from a Server, i want to write that data in a table, the problem is i don't know how can i fill only the first Column with rows. The second and third Column i want to fill later when i have the data for that.
Here my code to receive the Data and insert into the datatable:
while (true)
        {
            receiving_socket.Receive(receive_buffer);
            if (receive_buffer.Length > 0)
            {
                string data = CreateStringFromByteArray(receive_buffer);
                string[] arrayData = data.Split('/');
                foreach (string str in arrayData)
                {
                    neu = str;
                    //varNamenArray has all ColumnHeaders inside
                    for (int i = 0; i < varNamenArray.Length; i++)
                    {
                        if (str == varNamenArray[i])
                        {
                            string nameColumnToFill = varNamenArray[i];
                        }
                        else
                        {
                            //insert the data in the column, i search something like the next row
                            //dataTable.nameColumnToFill.Item.Add(str);

                        }
                    }
                }
            }
        }

Edit: My Datatable has the Columnname as Header and already exits with all Columns but no Rows.

A: Add an empty row and then set the value of the particular column, e.g.:
DataRow newRow = dataTable.Rows.Add();
newRow[nameColumnToFill] = str;