text:
Q: Function that returns observable acts like it's call recursively I have a <select> that is populated with a list from the database.  I use a jquery ajax call to get the data.  At first I was setting async = false so the call is synchronous and I update my VM once the call is done.  I'm trying to get away from doing synchronous calls by using promises and I ran into an issue. (To simplify this example I have removed promises.)
I thought I could create a function that would make the call to ajax and return an observable.  Then once the ajax call finishes, the observable would be updated and new values would be seen in the <select>.  The problem I have is if I use a normal function, it behaves like a recursive call and the observable is updated over and over.  If I use a computed observable this doesn't happen.  The reason I'd like to use a function instead of a computed is so I can pass other arguments in. (My understanding is you can't pass arguments to an observable)
At this point, I think my best option is to use a computed and try and figure out a different way to get the arguments, but I'd like to understand why using a plain function doesn't work.
I have created a plunk to show this: (On the select element change getAvailableCountries() to getAvailableCountries2() to see the difference)
http://plnkr.co/v1Q0bBhWOAHQSv8N1vwu
HTML:
<!DOCTYPE html>

  <link rel="stylesheet" href="style.css" />

    Your country:
      <select class="form-control" data-bind="options: getAvailableCountries(),
                       optionsText: 'countryName',
                       value: selectedCountry,
                       optionsCaption: 'Choose...'"></select>

      You have chosen a country with population:

    ko.toJSON():

JS:
var Country = function(name, population) {
  this.countryName = name;
  this.countryPopulation = population;
};

var viewModel = function() {
  var availableCountries = ko.observableArray([new Country("First Country", 5000)]);
  var selectedCountry = ko.observable();

  function callAjax() {
    $.mockjax({
      url: '/Countries',
      responseTime: 2000,
      responseText: [{
        population: 1000,
        name: "Country A"
      }, {
        population: 2000,
        name: "Country B"
      }, {
        population: 3000,
        name: "Country C"
      }]
    });
    $.ajax({
      dataType: "json",
      url: "/Countries",
      success: function(data, status, jqXhr) {
        for (i = 0; i < data.length; i++) {
          var tmpData = data[i];
          var tmpCountry = new Country(tmpData.name, tmpData.population);
          availableCountries.push(tmpCountry);
        }
      },
    });
  }

  var getAvailableCountries = ko.computed(function() {
    callAjax();
    return availableCountries;
  });

  var getAvailableCountries2 = function() {
    callAjax();
    return availableCountries;
  };

  var testAjax = function() {
    $.ajax({
      dataType: "json",
      url: "/Countries",
      success: function(data, status, jqXhr) {
        var x = 1;
      }
    });
  };

  return {
    availableCountries: availableCountries,
    selectedCountry: selectedCountry,
    getAvailableCountries: getAvailableCountries,
    getAvailableCountries2: getAvailableCountries2,
    testAjax: testAjax,
  };
};

$(document).ready(function() {
  ko.applyBindings(viewModel);
});

Here's the plunk after reviewing the accepted answer: http://plnkr.co/edit/LvFWVG3pDrVbvPvLm7Cu

A:
At this point, I think my best option is to use a computed and try and figure out a different way to get the arguments, but I'd like to understand why using a plain function doesn't work.

Binding handlers in Knockout use a computed observable to update the UI whenever any observable in the binding is updated. When such an update occurs, the binding handler re-reads the binding value, which causes the function to be called again. This method ensures that the binding always gets the correct, latest value, regardless of how the binding itself was constructed.
Using a computed observable for getAvailableCountries provides separation between tracking when to get updated data from the server and when to update the view with that data. This is especially useful when you need to load new data in response to other observables, and this pattern is explained quite well on the Knockout wiki.


text:
Q: Average of of 2 coordinates So I am making a graph of the average between to lists of coordinates.
So I have been looking all over and can't seem to find any information on how I can find the average of the 2 lists of values. When I try I get an error "the index was outside the matrix boundaries" and when I got it to work I just made a graph where the years where extremely high and the graph itself were looking insane. What i do is importing 2 parts of(data/data2) information with Json.
        //
        // Data
        //

        int tal = dataSet.dataset.value.Count;
        //Add items in the listview
        int[] yData = new int[tal];
        int[] xData = new int[tal];
        int k = 0;

        foreach (var item in dataSet.dataset.dimension.Tid.category.label)
        {
            xData[k++] = int.Parse(item.Value.ToString());
        }

        for (int i = 0; i < tal; i++)
        {
            yData[i] = dataSet.dataset.value[i];
        }

        //
        // Data2
        //

        int tal2 = dataSet2.dataset.value.Count;
        int[] y2Data = new int[tal2];
        int[] x2Data = new int[tal2];
        int j = 0;

        foreach (var item in
        dataSet2.dataset.dimension.Tid.category.label)
        {
            x2Data[j++] = int.Parse(item.Value.ToString());
        }

        for (int p = 0; p < tal2; p++)
        {
            y2Data[p] = dataSet2.dataset.value[p];
        }

         This is the part
        ///////////////////////////////////////////////////////////
        int[] ySum = new int[xData.Length];

        for (int i = 0; i < xData.Length; i++)
        {
            ySum[i] = (yData[i] + y2Data[i]) / 2;

        }
        ///////////////////////////////////////////////////////////

        List<int> GenUd = new List<int>(yData.ToList());
        textBoxGenUd.Text = GenUd.Average().ToString();
        List<int> GenInd = new List<int>(y2Data.ToList());
        textBoxGenInd.Text = GenInd.Average().ToString();

        chartArea1.Name = "ChartArea1";
        chart2.ChartAreas.Add(chartArea1);
        chart2.Dock = DockStyle.Fill;

        for (int i = 0; i <xData.Count(); i++)
        {
            series1.Points.AddXY(ySum[i], x2Data[i]);
        }

        MySecChart2 mc3 = new MySecChart2(series1);
        mc3.ShowDialog();

A: mine is just an educated guess -  if the exception occurs at the following:
     This is the part
    ///////////////////////////////////////////////////////////
    int[] ySum = new int[xData.Length];

    for (int i = 0; i < xData.Length; i++)
    {
        ySum[i] = (yData[i] + y2Data[i]) / 2;

    }
    ///////////////////////////////////////////////////////////

My diagnosis would be that yData[i] and y2Data[i] they dont have the same length and of xData.Length define into the loop definition.
Was perhaps supposed to be yData.Length in the loop definition?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Customizing mezzanine to allow users to edit and publish their own blog I am trying to create a multi user blogging platform using Mezzanine, where each user of the site will get a blogging dashboard for posting and editing their blogs. Is there a way in mezzanine to give some admin permissions to users like to add and manage their blogs? I dont want to allow users to access the Site Admin completely.
I explored other blogging packages but since i have already customized mezzanine for other use cases so difficult to move away. Basically trying to find a solution in mezzanine itself.
Could you please guide me how to achieve this in mezzanine.
Regards!

A: It's mostly possible. You can create admin users that only have access to the blog app, and only their own blog posts will be listed.


text:
Q: Display an expanded drill down report by default initially but should collapse based on the parameters selected in ssrs I would like to create a report that is expanded by default when first run.
For eg : I am using 3 fields in the dataset- Country,State,City
The first group would be for Country, the second group for State and the details group for City. All the groups would be of a tablix and created in a stepped style report as I want to create a drill down report with the toggle.
The problem is - I have 3 parameters - Summary,Intermediate,Detailed. When the user selects the Summary parameter, only the Country field is displayed with the toggle which when clicked, expands the State column and the toggle in the State column when clicked expands the City column, and can be collapsed also by clicking on the toggle.
When the user selects the Intermediate parameter, only the Country column and the expanded State column should be displayed when the report is initially run, and the toggle on the State column should take me to the City column and can be collapsed also by clicking on the toggle.
Similarly, when the user selects the Detailed parameter, all of the three columns should be displayed in the expanded state when the report is initially run and can be collapsed also by clicking on the toggle.
How can I achieve this?? I have tried a number of ways but no luck.
Please help me..
Thanks

A: This is called Cascading Parameters. What you want to do is use separate datasets for each parameter. Use the Country parameter in your dataset for the State and then use the State parameter in your City dataset.
SELECT DISTINCT State
FROM yourTable
WHERE Country = @Country

For more info, check https://technet.microsoft.com/en-us/library/aa337498(v=sql.105).aspx

A: You can create three sets of each column (S_Country, S_State, S_City, then I_Counrty, and so on...).  Your visibility of the toggle items and unhidden items will be controlled by your parameter.  Here's what the Summary Countries Column visibility fx would be:
    =iif(Parameters!Format.Label = "Summary", False, True)

Set the Summary Country as the toggle item for the other two.  For the Intermediates, The Country and State visibility would be based on a similar formula as above, and the City hidden and toggled on the Intermediate Country.  All three Detail columns' visibility is controlled by the Parameter.
You might want to do a little research on Parameter Values and Labels.  It would be better to assign the words "Summary", "Intermediate", and "Detail" as Labels in the parameter, and use "1", "2", "3" for values.  That simplifies code to read:
=iif(Parameters!Format.value = 1, False, True)

It just takes a bit of creativity to get things like this to work in SSRS.


text:
Q: How to change grouped data in ungrouped data I have grouped data that I want to convert to ungrouped data.
year<-c(rep(2014,4),rep(2015,4))
Age<-rep(c(22,23,24,25),2)
n<-c(1,1,3,2,0,2,3,1)
mydata<-data.frame(year,Age,n)

I would like to have a dataset like the one below created from the previous one.
   year Age
1  2014  22
2  2014  23
3  2014  24
4  2014  24
5  2014  24
6  2014  25
7  2014  25
8  2015  23
9  2015  23
10 2015  24
11 2015  24
12 2015  24
13 2015  25

A: Try
mydata[rep(1:nrow(mydata),mydata$n),]

    year Age n
1   2014  22 1
2   2014  23 1
3   2014  24 3
3.1 2014  24 3
3.2 2014  24 3
4   2014  25 2
4.1 2014  25 2
6   2015  23 2
6.1 2015  23 2
7   2015  24 3
7.1 2015  24 3
7.2 2015  24 3
8   2015  25 1

A: Here's a tidyverse solution:
library(tidyverse)
mydata %>%
  uncount(n)

which gives:
   year Age
1  2014  22
2  2014  23
3  2014  24
4  2014  24
5  2014  24
6  2014  25
7  2014  25
8  2015  23
9  2015  23
10 2015  24
11 2015  24
12 2015  24
13 2015  25

A: You can also use tidyr syntax for this:
library(tidyr)

year<-c(rep(2014,4),rep(2015,4))
Age<-rep(c(22,23,24,25),2)
n<-c(1,1,3,2,0,2,3,1)
mydata<-data.frame(year,Age,n)

uncount(mydata, n)
#>    year Age
#> 1  2014  22
#> 2  2014  23
#> 3  2014  24
#> 4  2014  24
#> 5  2014  24
#> 6  2014  25
#> 7  2014  25
#> 8  2015  23
#> 9  2015  23
#> 10 2015  24
#> 11 2015  24
#> 12 2015  24
#> 13 2015  25

But of course you shouldn't use tidyr just because it is tidyr :) An alternate view of the Tidyverse "dialect" of the R language, and its promotion by RStudio.

A: We can use tidyr::complete
library(tidyr)
library(dplyr)

mydata %>% group_by(year, Age) %>%
    complete(n = seq_len(n)) %>%
    select(-n) %>%
    ungroup()

# A tibble: 14 × 2
    year   Age
   <dbl> <dbl>
 1  2014    22
 2  2014    23
 3  2014    24
 4  2014    24
 5  2014    24
 6  2014    25
 7  2014    25
 8  2015    23
 9  2015    23
10  2015    24
11  2015    24
12  2015    24
13  2015    25
14  2015    22


text:
Q: How to create a 3-way relationship between NHibernate entities? I have the following NHibernate entity classes:
public class ProductPrice
{
    private long _id;
    private long _price; //Let's not get side-tracked by the type
    private Currency _currency;
}

//Just showing for completeness; the link beween ProductPrice and Currency
//is working correctly
public class Currency
{
    private long _id;
    private String _threeLetterCode; //INR, USD, GBP, OMR etc.
    private String _displayName;
    private IList<ProductPrice> _productPrices = new List<ProductPrice>();
}

public class Item
{
    private long _id;
    private String _name;
    private IList<ProductPrice> _prices = new List<ProductPrice>();
}

public class Customer
{
    private long _id;
    private String _name;
    private IList<ProductPrice> _prices = new List<ProductPrice>();

}

I want to create a separate mapping table that links the tuple (Customer, Item,
ProductPrice) as we want to be able to offer the same item at different prices
to different customers.  The Currency to ProductPrice is a simple
one-to-many relationship.
I am at a loss how to map this in the .hbm.xml files.
So far I have (doing just a partial mapping):
<class name="Item" table="Items">
  <id name="ID">
    <generator class="native" />
  </id>
  <property name="Name" />
  <bag name="Prices" table="PriceList" inverse="true" cascade="none" lazy="false">
    <key column="ItemID" />
    <many-to-many class="ProductPrice" column="PriceID" />
  </bag>
</class>

and
<class name="ProductPrice" table="ProductPrices" lazy="true">
  <id name="ID">
    <generator class="native" />
  </id>
  <property name="Price" />
  <many-to-one name="Currency" class="Currency" column="CurrencyID" />
</class>

This only maps (Item, ProductPrice), but even this doesn't cause an entry to
be saved in the PriceList table when I create a new ProductPrice, add it to
a Currency, add it to a new Item, then save Item and Currency.
So the questions I have are:

*

*What am I missing?

*

*How do I make sure that an entry is made in the PriceList table when I
create a ProductPrice, add it to an Item and save the Item?

*How do I extend this two-way (Item, ProductPrice) mapping to a three-way
(Customer, Item, ProductPrice) mapping?

*How do I do it so that I can have multiple identical (Customer, Item,
ProductPrice) rows in the PriceList table (ProductPrice has validity
dates (not shown here) so as be able to offer short-lived special pricing)?

Version 2:
I have the following NHibernate entity classes:
public class ProductPrice
{
    private long _id;
    private long _price; //Let's not get side-tracked by the type
    private Currency _currency;
    private IList<Item> _items = new List<Item>();
}

//Just showing for completeness; the link beween ProductPrice and Currency
//is working correctly
public class Currency
{
    private long _id;
    private String _threeLetterCode; //INR, USD, GBP, OMR etc.
    private String _displayName;
    private IList<ProductPrice> _productPrices = new List<ProductPrice>();
}

public class Item
{
    private long _id;
    private String _name;
    private IList<ProductPrice> _prices = new List<ProductPrice>();
}

public class Customer
{
    private long _id;
    private String _name;
    private IList<ProductPrice> _prices = new List<ProductPrice>();

}

I want to create a separate mapping table that links the tuple (Customer, Item,
ProductPrice) as we want to be able to offer the same item at different prices
to different customers.  The Currency to ProductPrice is a simple
one-to-many relationship.
I am at a loss how to map this in the .hbm.xml files.
So far I have (doing just a partial mapping):
<class name="Item" table="Items">
  <id name="ID">
    <generator class="native" />
  </id>
  <property name="Name" />
  <bag name="Prices" table="PriceList" inverse="true" cascade="save-update" lazy="false">
    <key column="ItemID" />
    <many-to-many class="ProductPrice" column="PriceID" />
  </bag>
</class>

and
<class name="ProductPrice" table="ProductPrices" lazy="true">
  <id name="ID">
    <generator class="native" />
  </id>
  <property name="Price" />
  <many-to-one name="Currency" class="Currency" column="CurrencyID" />
  <bag name="Items" table="PriceList" >
    <key column="PriceID" />
    <many-to-many class="Item" column="ItemID" />
  </bag>
</class>

This only maps (Item, ProductPrice), but even this doesn't cause an entry to
be saved in the PriceList table when I create a new ProductPrice, add it to
a Currency, add it to a new Item, then save Item and Currency.
So the questions I have are:

*

*What am I missing?

*

*How do I make sure that an entry is made in the PriceList table when I
create a ProductPrice, add it to an Item and save the Item?

*How do I extend this two-way (Item, ProductPrice) mapping to a three-way
(Customer, Item, ProductPrice) mapping?

*How do I do it so that I can have multiple identical (Customer, Item,
ProductPrice) rows in the PriceList table (ProductPrice has validity
dates (not shown here) so as be able to offer short-lived special pricing)?

Update 1
Added a list of Item to ProductPrice and updated ProductPrice.hbm.xml.
Update 2
An unshophisticated way of solving this would be to define an entity PriceLink
like this:
public class PriceLink
{
    protected virtual long ID { get; set; }

    public virtual Customer Cust { get; set; }

    public virtual Item Item { get; set; }

    public virtual ProductPrice ProdPrice { get; set; }
}

and map it like so:
<class name="PriceLink">
  <id name="ID">
    <generator class="native" />
  </id>
  <many-to-one name="Cust" class="Customer" column="CustomerID" />
  <many-to-one name="Item" class="Item" column="ItemID" />
  <many-to-one name="ProdPrice" class="ProductPrice" column="ProductPriceID" />
</class>

However, with this solution I lose (I think) all of the power of NHibernate's
ability to retrieve an entire object graph.  Is this ghetto solution worth it?
Update 3
This is how I was saving the entities (before I tried PriceLink) in a unit
test (yes, I realize this is hack-y code and I am not using transactions):
Currency curr = new Currency { DisplayName = "XYZ Currency", ThreeLetterCode = "XYZ" };
ProductPrice prodPrice = new ProductPrice { SalePrice = 10000, ValidFrom = DateTimeOffset.MinValue, ValidUpto = DateTimeOffset.MaxValue };
Item item = new Item { Name = "Item 1"};
//PriceLink pl = new PriceLink();
using (ISession session = NHibernateHelper.OpenSession())
{
    prodPrice.Currency = curr;
    curr.ProductPrices.Add(prodPrice);
    //pl.Item = item;
    //pl.ProdPrice = prodPrice;
    prodPrice.Items.Add(item);
    item.Prices.Add(prodPrice);
    session.Save(curr);
    session.Save(item);
    //session.Save(pl);
}

A: Consider around what items you would like to access yourdata store. In other words, instead of tying all items together, think about the root aggregates.
In the described model you might want to consider just having a currency class without having a reference from currency towards the productprices.
That way the model will become somewhat simpler although the user stories might have driven you this way first, not sure?
Having said that, I would not want nhibernate be so powerfull to retrieve all the entire object graph, but rather choose multiple of those graphs. Like a product with its prices, and another user story you might want to go for the currency as the aggregate root.


text:
Q: ADD two numbers 0 - 255 from user input with print in Assembly x86 8086 I created this simple addition program in NASMIDE Assembly x86 Intel 8086. I don't really know how to change the code to be able to: ADD two numbers ( 0 - 255 ) from input and print them out. I've been searching for examples of this kind, but I can't find any.
org 100h
;program
mov ah,1 ; READ INTO AL
int 21h
mov dl,al ; DL = CURR AL

mov ah,1 ;READ INTO AL
int 21h

ADD dl,al ; DL = DL + AL
sub dl,48 ; ASCII TO NUMBER
mov ah,2 ; PRINT NUMBER
int 21h

;END
mov eax,4c00h
int 21h


text:
Q: As OpenVPN client, do all my internet traffic goes to the server? This is a simple question. On OpenVPN's site, I can read:

By default, when an OpenVPN client is active, only network traffic to and from the OpenVPN server site will pass over the VPN. General web browsing, for example, will be accomplished with direct connections that bypass the VPN.

I am not setting up any OpenVPN server. I am just connecting to one. I naively thought that if I connect to an OpenVPN server, all my internet traffic is sent to it. What does the above statement mean? What is actually happening?

A: It simply depends on how the OpenVPN server is setup.
Specifically which routes it pushes to the client.
It can be that all your traffic will be sent to it (meaning the OpenVPN client changes your default route).
But it's also very possible that only specific sub-nets are accessed via OpenVPN and other traffic is not.


text:
Q: How to bypass "Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet"? I have a use case where I need to use the navigator.vibrate API to vibrate once an image has finished sliding in from the side:
Code pen demo here: https://codepen.io/ifusion/pen/XeWqpj
Note, this only seems to work on Android Google Chrome & Android Firefox
However if the navigator.vibrate is not activated by an actual touch then in chrome throws an error in the console:
[Intervention] Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet: https://www.chromestatus.com/feature/5644273861001216.
Samsung are using it at the end of the second step on this site: https://explorethenextgalaxy.com/ (Only works on android chrome & android firefox).
Screenshot at the point of it happening: https://www.dropbox.com/s/e8h7s3nzfwdk9dk/Screenshot%202017-09-13%2016.50.24.png?dl=0
I have had a look through their code and they are just using the navigator.vibrate just like I am and can't see them doing anything differently.
Is there a way to by pass this? I have tried .click() etc but the error still shows.

A: Another way to this easily.
Disable this option on your chrome browser by going to
chrome://flags

and find option called :: Requiring user gesture for the Vibration API and change the value to Disable.
this will require reload your browser and now every thing work find.

A: The vibrate API is only available once the user has started interacting with your page (e.g, by tapping or dragging on the screen). It cannot be used before a user interaction -- this is to prevent web pages (particularly embedded advertisements!) from attempting to scare the user by making their phone vibrate.
There is no way to bypass this, short of restructuring your page such that the user has to tap something before seeing that content.

A: I just faced this problem and found easy solution:
window.navigator.vibrate() && window.navigator.vibrate(100);
using on event handler.
No more error console message.

A: Just check if it's mobile
const isMobile: () => {
    const nav = navigator.userAgent.toLowerCase();
    return (
        nav.match(/iphone/i) || nav.match(/ipod/i) || nav.match(/ipad/i) || nav.match(/android/i)
    );
};

isMobile() && window.navigator.vibrate(100);

A: if(window.navigator.userAgentData.mobile){
    window.navigator.vibrate(100);
}


text:
Q: atomic<> within a union as a performance hack I am considering implementing a homebrew shared pointer as part of a garbage collector, in order to avoid the (probably slight) overhead from std::shared_ptr being internally atomic. Something loosely equivalent to:
template <typename T>
struct my_atomic_shared
{
  std::atomic<std::size_t> refcount;
  std::unique_ptr<T> value;
};

My brief hope was that small integers and atomic<small integers> would be equivalent, but dumping asm shows mov for the std::size_t vs xchgl for the atomic. I am now considering the following, possibly UB invoking, implementation:
template <typename T>
struct my_normal_shared
{
  std::size_t refcount;
  std::unique_ptr<T> value;
};

template <typename T>
struct my_shared
{
  // Surprisingly tedious constructor/destructor definition omitted
  enum {ATOMIC, NORMAL} tag;
  union
  {
    my_atomic_shared<T> atomic;
    my_normal_shared<T> normal;
  } value;
  void promote()
  {
    // pseudocode. Sequential consistency, calls should go via store/load
    if(tag == NORMAL)
    {
      T got = *(value.normal);
      *(value.atomic) = got;
      tag = ATOMIC;
    }
  }
};

The premise would be to create the non-atomic version by default and call promote() before passing an instance of my_shared<> to another thread.
I would like to know if there is a better way to achieve this performance hack. I'm also be interested to know if there's a reason why putting atomic<> variables in unions is doomed to failure.
edit: Adding less incoherent pseudocode. The type stored is more interesting than the type used for the reference count.
template <typename T>
struct my_shared_state
{
  enum {ATOMIC, NORMAL} tag;
  union
  {
    std::atomic<std::size_t> atomic;
    std::size_t normal;
  } refcount;
  T value;
  void incr();
  void decr();
}

template <typename T>
struct my_shared_pointer
{
   my_shared_state<T> * state;
   // ctors and dtors modify refcount held in state
 }

A: First, in shared_ptr and other reference counted pointer designs, the reference count is not in the shared_ptr class. It's in the node to which the shared pointer points.
The relationship is thus:
template<typename T>
class Node
{
 std::atomic<unsigned int> RefCount;
 T * obj;
};

template<typename T>
class shared_ptr
{
 Node<T> * node;
 T *       shadow;
};

This is not code for a shared_ptr, but pseudo code for the data structure layout. The shared_ptr points to a Node<T>, which "owns" the object created dynamically, and the reference counter of all the shared_ptr's which have "linked" to it. The shared_ptr<T> has a "shadow" pointer to the Node<T>'s obj pointer.
That's the basic design layout. The atomic increment/decrement is done through a dereference, which is nearly as much overhead as you might think to remove from switching to a non-atomic increment/decrement counter.
I assume the objective is to permit a non-atomic reference counted ownership that may be used in non-threaded work, such that the reference counter need not be synchronized.
Note that the choice is not within shared_ptr, but within Node.
Further, a most important performance enhancement was adopted from boost::shared_ptr in recent C++11/C++14 libraries, embodied in the template function make_shared.
The concept is based on the observation that allocating this structure implies at least two allocations, one for the object being created with new, the other for the Node that will own it (the shared_ptr is presumed to be on the stack, or a member). As such, there was a design implemented in boost (then adopted by C++11), via the make_shared function, which performs one allocation for both the Node and the object being created, which uses "in place construction" and destruction of the object being managed (the T in all of this). This optimization is likely at least as much a performance enhancement, and a memory efficiency optimization on top of that, which you'd loose unless you choose to implement that as well.
Note, too, that garbage collection (of a kind) is now available in compliant C++11/C++14 releases, so one should ask if that's been inspected and rejected as unsuitable before proceeding.
Assuming that is rejected, you're inquiry regarding a union is possible, but another approach offers possibilities and flexibility you may not have yet considered.
Using policy based design, you can create compile time polymorphic options by building template classes out of parameters. The basic idea is to derive from one of the parameters in the template class. For example:
class AtomicRefCount
{ ...
};

class NonAtomicRefCount
{ ...
};

template< typename T, typename Ref >
class Node : public Ref
{ ...
};

typedef Node< SomeStruct, AtomicRefCount >  SomeStruct_Node;

The idea is to be able to select behaviors or construction options based on a parameter to the template. They can be nested for deep chaining of this concept. In this example the idea is to create a Node based on the option of an atomic or non-atomic reference counted integer type.
The challenge, however, is that this means the two kinds of nodes are different types. They are not 'Node< T >' anymore. They are 'Node< T, Ref>' types, and so shared_ptr<T> wouldn't understand them, they'd have to be shared_ptr< T, Ref >
However, using this technique it's possible to design both shared_ptr and weak_ptr from a common base of template interface declarations, which different behaviors based on which parameters are provided in declaring the pointers. In a smart pointer library I wrote years ago, in order to handle some various issues INCLUDING garbage collection as an option, these were possible:
template< typename T > struct MetaPtrTypes
{
  typedef typename SmartPointers::LockPolicy< T, SmartPointers::StrongAttachmentPolicy >    StrongLocking;
  typedef typename SmartPointers::NoLockPolicy< T, SmartPointers::WeakAttachmentPolicy >    WeakNoLocking;
  typedef SmartPointers::LockPolicy< T, SmartPointers::WeakAttachmentPolicy >               WeakLocking;
  typedef SmartPointers::NoLockPolicy< T, SmartPointers::StrongAttachmentPolicy >           StrongNoLocking;
  typedef SmartPointers::PublicAccessPolicy< T, StrongNoLocking >                           PublicStrongNoLock;

  typedef SmartPointers::MetaPtr< T, StrongLocking >          LPtr;
  typedef SmartPointers::MetaPtr< T, WeakNoLocking >          WPtr;
  typedef SmartPointers::MetaPtr< T, WeakLocking >            WLPtr;

  typedef SmartPointers::MetaPtr< T, PublicStrongNoLock >     MPtr;

  typedef T                                                   Type;
};

This was for C++03 or so, as we waited for C++11 features to creep in from the drafts. The idea was to create a MetaPtrTypes< SomeClass > SomeClassPtrs; Doing so gave types like SomeClassPtrs::MPtr, which is a kind of shared_ptr. The WPtr was a weak pointer, both somewhat similar to std::shared_ptr and std::weak_ptr, but with several custom memory allocation options not available to shared_ptr of the period, and with certain locking features which usually required protecting shared_ptr's with mutexes in applications (because writing to shared_ptr is not thread safe).
Notice the strategy of policy based design. MPtr is the equivalent of, say:
typedef std::shared_ptr< SomeClass >  SPtr;

Wherever one could use SPtr, one could use MPtr. But look how MPtr is fashioned. It's a MetaPtr< T, PublicStrongNoLock >. This is a built up policy construction paradigm. MetaPtr is just like the Node< T, Ref > mentioned earlier, but with SEVERAL policies embedded inside it.
Looking over MPtr, WPtr, LPtr, you'll notice there are MetaPtr creations based on various policies, StrongLocking and WeakLocking among them.
They are:
  typedef typename SmartPointers
     ::LockPolicy< T, SmartPointers
          ::StrongAttachmentPolicy >    StrongLocking;

  typedef SmartPointers
     ::LockPolicy< T, SmartPointers
          ::WeakAttachmentPolicy >      WeakLocking;

These are two policies from which smart pointers can be fashioned. Notice that for WLPtr, the policy is WeakLocking, while for LPtr the policy is for StrongLocking.
They are both made from MetaPtr, the primary user interface class. If MetaPtr is fashioned with a Weak kind of policy, it's a weak_ptr. If it's fashioned with a Strong kind of policy, it's a shared_ptr. The difference is known in this library as the attachment policy, and happens to be the root class from which the hierarchy is derived. Between the attachment policy and the MetaPtr is a locking policy. These two are lockers, StrongLocking and WeakLocking. There are non-lockers, StrongNoLock and WeakNoLock.
Several different kinds of smart pointers can be fashioned from a few small template classes implementing no less than 6 different kinds of smart pointers, all based on the same interface and sharing much of the code.
Policy based design is one way to implement what you want, without resorting to the union, though that's not a bad choice. It's simple, but if you more options intended in your design, you should think about policy based design.
More about policy based design of smart pointers is to be found in Alexandrescu's book from 2001 in which he presents loki, a smart pointer based on policies.
In the example presented, the MetaPtr was intended for a number of high performance scenarios where custom memory allocation was required, but shared_ptr of the period did not support it (and wouldn't for many years). Among the options, selectable by policy:
Standard memory allocation
Custom memory allocation
Garbage collection/memory management
Fast locking of writeable pointers
Lightweight reference counted smart pointers
Non-reference counted smart pointers (something like unique_ptr)
Array/Container aware smart pointers
GPU resource managers (loading/unloading textures,models and shader code)

Many of these were selectable in various combinations, all available in weak and standard versions.


text:
Q: ScreenShot en Swift Buen día estoy teniendo problemas con los screenshots dentro de la app no debería de dejar que se hicieran, tengo entendido que de manera nativa en swift no se puede bloquear esta función, por lo que tengo entendido solo se puede ejecutar el esto userDidTakeScreenshotNotification que sirve para detectar cuando alguien tomo una captura.
Después de investigar tuve una posible solución que es borrar la ultima foto del dispositivo después de que se toma el screen el problema que tengo es que pide autorización para hacerlo mi código es el siguiente:
func detectScreenShot() {
       UIScreen.main.addObserver(self, forKeyPath: "captured", options: .new, context: nil)

        let mainQueue = OperationQueue.main
        NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: mainQueue) { notification in

            let fetchOptions: PHFetchOptions = PHFetchOptions()
                fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
            let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
                if (fetchResult.lastObject != nil) {
                    let lastAsset: PHAsset = fetchResult.lastObject! as PHAsset
                    let arrayToDelete = NSArray(object: lastAsset)
                    PHPhotoLibrary.shared().performChanges( {
                        PHAssetChangeRequest.deleteAssets(arrayToDelete)},
                        completionHandler: {
                            success, error in
                            print("Se borro la foto,")
                    })

                }
        }
    }

Funciona bien y se ejecuta correctamente solo que pide autorización para eliminar la foto hay alguna manera de omitir este paso y que se borre directo.
O editar de alguna manera la foto para que aparezca de un color solido
de ante mano gracias.


text:
Q: How much can people deduce from my project(s) by looking at my posts? I post some of my issues to Stack Overflow and other places on the web.
Should I be concerned about what people can deduce from these posts about my projects?

A: What might concern you is that you are leaving a digital trace not only of your activities, but your ability to learn and ask effective questions. Thus, it's not not so much your projects which leak, but you.
If I interviewed you for a job, one of the things I like to chat about is the websites you use to keep current and seek assistance. If you mentioned Stack Overflow, that might be a rich source of additional information to make a hiring decision.

A: Based on your questions I know:

*

*You use PHP and MySQL

*You use Bazaar as a VCS

*You don't know much about writing a "clean" PHP app, but are interested in learning.

Which, to me, is rather generic and uninteresting. If you're really concerned about it, post "sensitive" questions as an anonymous user.

A: Every line of code has some information about the software it belongs to. But as long as they are no secret business logics. I won't worry about it.
Just a tip: change the identifier names (functions,variables etc.) this will obfuscate a lot of the real function and foccusses on the algorithm.

A: It only depends on you how much do you reveal. If you post much code, or a trend can be seen in your question, then some things can be deduced.
In my opinions you should be concerned about disclosing too much information. If your project is proprietary closed source, then your employer may not be happy about too much information flying publicly about it.
On the other hand, as statetd on the beginning, it depends only on you how much info you reveal.

A: This is debatable, I think you should mind your audience as much as your questions. If your project is sensitive try to recreate your problem in a similar situation without posting real code. This all depends on your company's policies.
If someone really wants to take the time to follow all of your posts on all sites, which is also possible in industrial espionage, there's nothing much that can be done unless you start asking your questions directly to a specialized support team where everything is kept from the public.
But then again the Internet is your best bet at getting help on pointy subjects. It's a risk to be taken.
Best of luck.


text:
Q: UPDATE statement wrapped in an IF EXISTS block I'm trying to write a DML script that updates a column but I wanted to make sure the column existed first so I wrapped it in a IF EXISTS block
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Client' AND COLUMN_NAME='IsClarityEnabled')
BEGIN
    UPDATE Client SET IsClarityEnabled = 1 WHERE ClientID = 21
END

So the weirdness is that it tries to execute the update even if it fails the condition.  So column doesn't exist and the UPDATE statement runs and I get an error. Why?
Even stranger is that this does work:
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Client' AND COLUMN_NAME='IsClarityEnabled')
BEGIN
    EXEC('UPDATE Client SET IsClarityEnabled = 1 WHERE ClientID = 21')
END

Is there something special about an UPDATE command that causes it to behave this way?

A: The problem is that the script will be compiled/parsed, and if the column does not exist, you will have a compile/parse error.

Invalid column name
  'IsClarityEnabled'.

A:
it tries to execute the update even if it fails the condition

Are you sure? I suspect that what is actually happening is that SQL Server is attempting to parse the UPDATE, whatever the value of the condition. Since parsing happens before execution, at parse time SQL Server can't 'know' that you have protected this UPDATE with a check - the parser only knows that there isn't an IsClarityEnabled column on Client, and so it complains.
The reason the EXEC works as you want is preciely because the string literal isn't processed by the parser. This is the standard way of having scripts that must run against a schema that isn't known until execution time.


text:
Q: Find the remote VPN address of the network to which I am connected I am getting Internet from a Huawei 3G data card in Windows 7. I just read about being anonymous on the Internet so thought I'd give it a try. I used PD Proxy for that, using a username and password, which I got after signing up on their website.
PD Proxy is a software in which I just put a username and password, click on connect and after some seconds it gets connected. So I am unable to know where (remote address) it gets connected to.
If I knew the remote address I could use it using with NMD VPN or OpenVPN with an .ovpn configuration file.
So what is the server address of the network to which I am connected (after PD Proxy gets connected)?
I can see the a DNS server address and IP address of my computer using ipconfig. Is the DNS server is the server address of the VPN network to which I am connected?


text:
Q: For matrices, why is the Lie algebra equal to the tangent space? For a matrix Lie group $G\subset GL_n(\mathbb C)$ we define the Lie algebra to be the set of matrices $X\in M_n(\mathbb C)$ such that for all $t\in \mathbb R$ we have  $\quad \exp(tX)\in G$.
For clarity, I define the exponential map by
$$\exp(X) = \sum_{k=0}^\infty \dfrac{X^k}{k!}$$
The tangent space $T_I(G)$ at the group identity $I$ is the set of all matrices $X\in M_n(\mathbb C)$ for which there exists a differentiable path
$$\gamma : (-\epsilon,\epsilon) \to G$$
where $\gamma(0)=I$ and $\gamma'(0)=X$.
It is proposed that Lie algebra and the tangent space are the same.
It is clear from the differentiability of exponentiation that if $\quad \exp(tX)\in G \quad$ at every $t$ then the path $\gamma$ defined by $\gamma(t) = \exp(tX)$ shows that $X$ is in the tangent space.
The other direction is not as obvious to me. If $X$ is in the tangent space (ie. there exists a path $\gamma$ satisfying the conditions above) then $X$ is in the Lie algebra. Can somebody please explain why this is so?

A: The following comes from Brian C. Hall's text (2003 edition):$\newcommand{\fg}{\mathfrak{g}}$

Corollary 2.35: suppose $G \subset GL(n;\Bbb C)$ is a matrix Lie group with Lie algebra $\fg$. Then, a matrix $X$ is in $\fg$ if and only if there exists a smooth curve $\gamma$ in $M_n(\Bbb C)$ such that

*

*$\gamma(t)$ lies in $G$ for all $t$

*$\gamma(0) = I$

*$\frac{d \gamma}{dt}|_{t=0} = X$

  Thus, $\fg$ is the tangent space at the identity to $G$

The proof (of your direction) is as follows:
Let $\gamma$ be a curve satisfying these conditions.
Then, we may state that $\log(\gamma(t)) \in \fg$ for all sufficiently small $t$ (see theorem 2.27: there exists a neighborhood $U$ of $0$ in $\fg$ and a neighborhood $V$ of $I$ in $G$ such that $\exp:U \to V$ is a homeomorphism). Now, define
$$
X_{\gamma} = \frac{d}{dt} \log(\gamma(t))|_{t=0} = \lim_{h \to 0} \frac{\log(\gamma(h))}{h}
$$
since $X_{\gamma}$ is the limit of elements in $\fg$ and since $\fg$ is closed, $X_{\gamma} \in \fg$.  However, we note that (again, for sufficiently small $t$)
$$
\log(\gamma(t)) = (\gamma(t) - I) - \frac 12(\gamma(t)-I)^2
+ \frac 13(\gamma(t) - I)^3 - \cdots
$$
Differentiate term by term by applying the product rule.  All terms besides the first approach zero as $t \to 0$.  Thus, we have
$$
\frac{d}{dt} \gamma(t)|_{t=0} = \frac{d}{dt} \log(\gamma(t))|_{t=0} =
 X_{\gamma} \in \fg
$$
which was the desired result.


text:
Q: fadeOut(...).removeClass is not a function I am having a little problem when I am building a slider with images. I am a beginner in javascript and jquery so I've built id based on what I've done on codeacademy a while back (used to work fine there but it doesn't work anymore even there). It works fine when I click the next arrow but when I click the previous arrow it doesn't work anymore. It says in console "Uncaught TypeError: currentSlide.fadeOut(...).removeCLass is not a function".
Here's my code:
HTML:

•

•

•

•

CSS:
.slider{
    position:relative;
    width:100%;
    height:550px;
}
.slide{
    background-size:cover;
    background-repeat:no-repeat;
    background-position:center;
    display:none;
    position:absolute;
    top:0;
    left:0;
    width:100%;
}
.slide1{
    background-image:url('images/main/slider/1.jpg');
    height:100%
}
.slide2{
    background-image:url('images/main/slider/2.jpg');
    height:100%
}
.slide3{
    background-image:url('images/main/slider/3.jpg');
    height:100%
}
.slide4{
    background-image:url('images/main/slider/4.jpg');
    height:100%
}
.active-slide{
    display:block;
}

And finally JAVASCRIPT:
var main = function(){

    $('.arrow-next').click(function(){
       var currentSlide = $('.active-slide');
       var nextSlide = currentSlide.next();

       if (nextSlide.length == 0){
        nextSlide = $('.slide').first();
       }

       currentSlide.fadeOut(600).removeClass('active-slide');
       nextSlide.fadeIn(600).addClass('active-slide');

       currentDot = $('.active-dot');
       nextDot = currentDot.next();

       if (nextDot.length == 0){
        nextDot = $('.dot').first();
       }

       currentDot.removeClass('active-dot');
       nextDot.addClass('active-dot');
    });

    $('.arrow-prev').click(function(){
       var currentSlide = $('.active-slide');
       var prevSlide = currentSlide.prev();

       if (prevSlide.length == 0){
        prevSlide = $('.slide').last();
       }

       currentSlide.fadeOut(600).removeCLass('active-slide');
       prevSlide.fadeIn(600).addClass('active-slide');

       currentDot = $('.active-dot');
       prevDot = currentDot.prev();

       if (prevDot.lenth == 0){
        prevDot = $('.dot').last();
       }

       currentDot.removeClass('active-dot');
       prevDot.addClass('active-dot');
    });
};

$(document).ready(main);

A: The first I see is that you called removeCLass. Capital letter "L"
Maybe this was your fault.
Or maybe a wrong jquery version.
When I simply try
$("body").fadeOut(600).addClass("hello")

it works correctly


text:
Q: how to clear console window in java I try to clear the console window and continue execute the rest of my code(like you navigate to another page when browse web pages)
I found Runtime.getRuntime().exec("cls"); but it doesn't work,and says can not run program cls
and I also found a suggestion like print thousand empty lines, which is not what i want.
I would like to have something like
 old code goes here....
 showOption(); //this would display three option like 1,2,3
 input=userInput.nextInt();
 if(input==1){
   clearWindow();/clear the previous stuff from the console
   showOptionOneDetail(); //leave only option one detail on the console
 }

after the user select a option, like 1, then i want to clear window, and continue display the detail for the specific option, it's that possible?
I'm testing using mac in eclipse

A: Dear friend: You are trying to develop a Rich User Interface over a text console, which is a bad environment choose. I'd recommend that you'd better use Java Swing for that, which requires more programming effort, but it also turns out in a better user experience.
BUT, if you ABSOLUTELY need to re-paint your user "screens" in a text-only environment, I doubt that executing system commands (like "cls") would be useful here. The only choice I think you MIGHT have is to output the BACKSPACE character (ascii 8) as many times as characters have been printed to the console last time, and then produce the new "screen". I've never tried that in Eclipse, sou you'll have to give it a try. Good luck!


text:
Q: How can I force any display resolution/timing I want? I am having trouble finding a way to force any display resolution/timing I want in my C# program. I am running Windows 7 with a GeForce 210 graphics card. My current method to achieve these custom resolutions is to use the driver GUI to manually add the custom resolutions and then use Windows calls to change to those resolutions but I need a way to add new custom resolutions in real time.  I have looked into the NVAPI but I was not able to find a way to do this.  I also looked into the command line tool for the graphics driver but I was not able to get it to work.  My last resort is to rewrite the values in registry but I would really like to avoid that.  I am willing to use a different programming language or a third party tool as long as I can invoke it from the command line via my program.  Can anyone point me in the right direction?
Thanks in advance.
Update (8/16/2011):
I have been working on this problem with NVIDIA and they are providing me with an advanced NVAPI that will allow me to recreate the functionality of their driver.  They also confirmed that the basic version of NVAPI that they provide will not do this.

A: You could try using ChangeDisplaySettings
I'm not sure if it will have all the options provided by the nvidia panel, but certainly the basics like resolution, refresh rate, screen orientation, etc. I've used it myself in the past to dynamically change screen orientation (rotate to landscape/portrait) on a click of a button.

A: I was able to solve this problem by using the NDA version of the NVAPI.  It still was not trivial but all of the tools are there.


text: Q: debug web workers in node js using visual studio 2015 I'm using webworker-threads package in my node js application. when I set a breakpoint in Worker callback function. I doesn't stops and debugs it just ignores it, I am using visual studio 2015. I couldn't find any solution to this on internet


text:
Q: AngularJS click event not working with onsen ui button Sorry for my ignorance but I'm a newbie here,
The ng-click event on an ons-button is not firing,
I tried different solutions but no one does work for me
I'm a trying to create a simple page with just one tab that shows a button , for now , I'm just trying to make it trigger the expected event (an alert for exemple). Once resolved, I can go to implement a more advanced action ...
could it be a problem with the scopes ?

    <ons-page ng-controller="TabbarController">
      <ons-toolbar>

{{ title }}

      </ons-toolbar>

      <ons-tabbar swipeable position="auto" ons-prechange="updateTitle($event)">
        <ons-tab
          page="homeTemplate"
          label="Home"
          icon="ion-home, material:md-home"
          active
        >
        </ons-tab>
      </ons-tabbar>
    </ons-page>

    <template id="homeTemplate">
      <ons-page id="Tab1" ng-controller="ListenButtonController">

          Welcome Home ^_^

        <ons-button modifier="large" ng-click="onListenButtonClick()"
          >Click to Listen (not implemented yet), it just shows an alert!!</ons-button>
      </ons-page>
    </template>

A: I can't see any problem with your code and it seems to work just fine. Below is an example snippet demonstrating that click event is triggered as it should. The only difference between your code and this snippet is that I have connected the libraries that are necessary to run it. No changes to controller/template have been made.
Make sure that you are running the latest version of your page in your browser.

    <link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsenui.css">
    <link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsen-css-components.min.css">

    <ons-page ng-controller="TabbarController">
      <ons-toolbar>

{{ title }}

      </ons-toolbar>

      <ons-tabbar swipeable position="auto" ons-prechange="updateTitle($event)">
        <ons-tab
          page="homeTemplate"
          label="Home"
          icon="ion-home, material:md-home"
          active
        >
        </ons-tab>
      </ons-tabbar>
    </ons-page>

    <template id="homeTemplate">
      <ons-page id="Tab1" ng-controller="ListenButtonController">

          Welcome Home ^_^

        <ons-button modifier="large" ng-click="onListenButtonClick()"
          >Click to Listen (not implemented yet), it just shows an alert!!</ons-button>
      </ons-page>
    </template>


text:
Q: Team Foundation Server - Customer Feedback Security I am trying to find away of allowing customers to provide feedback without giving them access to the web interface of TFS. Is this possible? We are currently using TFS 2013
What I want to do is have a group of users who can receive feedback requests via e-mail and provide feedback via the feedback client. However I do not want them to be able to view any of the work items, test cases, builds or code. Essentially I want the users to be able to use the feedback client and have no access to anything else.
I have tried setting this up using the TFS roles security and restricting the firewall to the server, but I have not managed to achieve what I want.
How can I get this to work? It seems like it would be something that many people would use?

A: Yes - you need to configure them as Work Item Only users.
When they access the website they will only have access to create and view their own work items. Then give them 'create test plan' permission (don't ask) and they should be able to use the feedback tool to provide feedback but see no other options.
There is however no way to restrict the work item types that they can create. I usualy handles this by creating a template url (create a new wit and fill out stuff now click the template button) and putting that on a portal they u


text:
Q: How can I assign properly a image to state and function? I am newbie. I want to create a function which uses a random number to change 3 images dynamically.
Example: if number > 5 = image1, if number > 10 = image2, if number > 15 = image3
I have tried some things for now but thats the best result I can get:
random(min,max,x) {
    min = Math.ceil(5);
    max = Math.floor(20);
    return  x = Math.floor(Math.random() * (max - min)) + min;
}

colormachine = () => {
if(this.random(this.props.x > 8))
{
    this.setState(state => ({color: green}));
};
}

render() {

    console.log(this.random());
    // console.log(this.colormachine());

({ color: green }) is a
const green = { backgroundImage: "url(" + tirelogogreen + ")";

A: The idea is your states should only contain really simple data, nothing to do with styles.  For example, here I am storing a number.
const [myNum, setMyNum] = useState(0);

Then I have a button that updates the state:
<button onClick={() => setMyNum(Math.floor(Math.random() * 20))}>

Then, your component will decide what to do with it based on the number.
function Box(props) {
  // here i am getting different style based on what's being passed in
  const getStyle = myNum => {
    if (myNum > 4 && myNum < 10) return { backgroundColor: "green" };

    if (myNum > 10 && myNum < 15) return { backgroundColor: "blue" };

    if (myNum > 14) return { backgroundColor: "red" };

    return null;
  };

  return (

I'm a square.

  );
}

For a working example, click here: https://codesandbox.io/s/react-boilerplate-h2dbd


text:
Q: PHP template with Flow3 Templating with Flow3 is done using Fluid templating language.
Is there an integrated/easy solution to use PHP templates instead? (without having to write a template renderer myself)
(to avoid misunderstandings: by PHP template I mean HTML code mixed with PHP)

A: The whole point of fluid is not to do this. You can write own viewhelpers for that.
A fast workaround would be to write a php viewhelper which uses eval(). But that would be really bad from a security point of view.

A: Your controller has a protected property, that defaults to Fluid, changing it to something else is really easy:
    protected $viewFormatToObjectNameMap = array('json' => '\TYPO3\FLOW3\MVC\View\JsonView');

Now take a look at the EmptyController in the same directory: \TYPO3\FLOW3\MVC\View\
You can use this as start. What you basically have to do is to satisfy an assign method, the way how you can transfer variables to your theme.
Next, come up with a few standardizations (e.g. the Template-Files have to be in the folder \Resources\Private\Templates\ControllerName\ActionName.phtml, note the file extension) and say which variable will be available there (e.g. $view).
Now a very basic approach would be:
    protected $view = array();

    public function assign($key, $value) {
        $this->view[$key] = $value;
    }

    public function render() {
        $this->controllerContext->getResponse()->setHeader('Content-Type', 'text/html');

        $view = $this->view;
        ob_start();

        include_once($this->getTemplatePathAndFilename());
        $output = ob_get_contents();
        ob_end_clean();
        return $output;
   }
}

For the $this->getTemplatePathAndFilename() function, you can use the code from the TYPO3\Fluid\View\TemplateView->getTemplatePathAndFilename() method and adjust it to your needs.
In your template files, you can now use the $view variable.
I'm at my parents for easter and they lack a runtime environment, so this is not tested and you'll likely run into problems, but this should get you started!


text:
Q: Pass multiple values to a string parameter in jenkins Have a Jenkins job with a string parameter(P1), how do i pass multiple values to this parameter(P1=a,b,c..), I have to further pass the all values of P1 to my jenkins build step(a batch script) how can this be done?

A: stage ('Invoke_pipeline') {
        steps {
            build job: 'test-docker-image',
                  parameters: [
            string(name: 'ProjectName', value: "atm"),
            string(name: 'Product', value:"renojournalman,reno-keymanagement,reno-management,renoalertman,reno-atm-update,reno-eventmonitor,reno-valmediamon"),

            ]
        }


text:
Q: Подключение виртуальной машины к Интернет Есть рабочая машина с Windows-10 с доступом в Интернет через прокси.
На ней установлен virtual box, на котором развернута Slackware 14-2.
Можно ли как-то настроить для Slackware доступ к Интернет?


text:
Q: Java problem - java, Jar file Statmetrics is not running Download link: https://upload.cat/f694139f88c663b1
I am trying to run Java file either as jar or as classes in Ubuntu. I failed in both options. The following exception is its output.

java org.statmetrics.Statmetric

or

java -cp /home/elias/statmetrics/statmetrics.jar:.
  org.statmetrics.Statmetrics

or

java -classpath "/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/*" -jar
  /home/elias/statmeics/statmetrics.jar org.statmetrics.Statmetrics

Exception in thread "Thread-0" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/adapters/XmlAdapter
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
    at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
    at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:802)
    at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:700)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:623)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at org.statmetrics.c.a(Unknown Source)
    at org.statmetrics.dw.a(Unknown Source)
    at org.statmetrics.dx.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.adapters.XmlAdapter
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 12 more

Sincerely,
Elias Tsolis

A: I found the answer. My stupidity.
First step: You must set the corresponding Java: I had Java 11 but I set as Java lib path the 8th version!
- You can do set the Java version from here:
 sudo update-alternatives --config java

2nd step: Then run the following command, by changing path and file names to your corresponding path and files:
  java -classpath "/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/*" -jar /home/elias/statmetrics/statmetrics.jar org.statmetrics.Statmetrics

It was run succesfully!


text:
Q: Extract DNS record (MX) details from name server reply c++ I am trying to get the hostname of the MX record with low priority using the following code, but I am unable to parse the required details (hostname, ttl, priority) from the given nameserver reply.
u_char nsbuf[4096], dispbuf[4096];
ns_msg msg;
ns_rr rr;
int i, j, l;
std::string domain("gmail.com");
l = res_query(domain.c_str(), ns_c_any, ns_t_mx, nsbuf, sizeof (nsbuf));

    ns_initparse(nsbuf, l, &msg);
    printf("%s :\n", domain.c_str());
    l = ns_msg_count(msg, ns_s_an);
    for (j = 0; j < l; j++)
    {
        int prr = ns_parserr(&msg, ns_s_an, j, &rr);

        ns_sprintrr(&msg, &rr, NULL, NULL, reinterpret_cast<char*> (dispbuf), sizeof (dispbuf));

        printf("%s\n", dispbuf);
    }

The above code gives the result as

gmail.com.              15M IN MX       30
  alt3.gmail-smtp-in.l.google.com.

Is there any available function to get hostname, priority, ttl, etc. in separate buffers like below?

host -> alt3.gmail-smtp-in.l.google.com
priority -> 30
ttl -> 15M

And, should we manually check for the higher priority record,
or is there any utility function or code that could do the requirement?
Edit:
I tried the following code to extract data
#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <resolv.h>
#include <cstring>
#include <string>
#include <string.h>

using namespace std;
int main(int argc, char** argv) {

    u_char nsbuf[4096];
    u_char dispbuf[4096];
    ns_msg msg;
    ns_rr rr;
    int i, j, l;
    std::string domain("gmail.com");
    l = res_query(domain.c_str(), ns_c_any, ns_t_mx, nsbuf, sizeof (nsbuf));
    if (l < 0) {
        perror(domain.c_str());
    } else {
#ifdef USE_PQUERY
        res_pquery(&_res, nsbuf, l, stdout);
#else
        ns_initparse(nsbuf, l, &msg);
        l = ns_msg_count(msg, ns_s_an);
        for (j = 0; j < l; j++) {
            int prr = ns_parserr(&msg, ns_s_an, j, &rr);

            //BLOCK 1
            char *cp;
            cp = (char *) ns_rr_name(rr);
            printf("CP->%s\n", (char *) cp);
            int i1 = ns_rr_type(rr);
            printf("Type->%d\n", i1);
            int i2 = ns_rr_class(rr);
            printf("Class->%d\n", i2);
            int i3 = ns_rr_ttl(rr);
            printf("TTL->%d\n", i3);
            int i4 = ns_rr_rdlen(rr);
            printf("DataLength->%d\n", i4);

            //BLOCK 2
            const u_char *rdata = ns_rr_rdata(rr) +1;
            printf("DataU_char-> %s\n", reinterpret_cast<const char*> (rdata));

            int len = strlen(reinterpret_cast<const char*> (rdata));
            printf("len->%d\n", len);

            char rdatatemp[1024];
            strncpy(rdatatemp, reinterpret_cast<const char*> (rdata), sizeof (rdatatemp));
            printf("DataChar->%s\n", rdatatemp);

            ns_sprintrr(&msg, &rr, NULL, NULL, reinterpret_cast<char*> (dispbuf), sizeof (dispbuf));
            printf("FullRecord->%s\n", dispbuf);
            printf("\n");
        }
#endif
    }
    return 0;
}

The above code works well for txt record, but for mx record, it is not parsed correctly and the following is the result
Output:
CP->gmail.com
Type->15
Class->1
TTL->130
DataLength->32
DataU_char-> gmail-smtp-inlgoogle��
len->33
DataChar->gmail-smtp-inlgoogle��
FullRecord->gmail.com.          2m10s IN MX     30 alt3.gmail-smtp-in.l.google.com.
CP->gmail.com
Type->15
Class->1
TTL->130
DataLength->9
DataU_char-> alt2�.�
len->10
DataChar->alt2�.�
FullRecord->gmail.com.          2m10s IN MX     20 alt2.gmail-smtp-in.l.google.com.
So in DataChar & DataU_char special symbols are printed.
'alt2�.�' is printed instead of 'alt2.gmail-smtp-in.l.google.com.'
Also the DataLength value is wrong.
Also I am not able to get the priority of the record.
Am I missing something here, or is it the error with the c++ library itself?

A: libresolv doesn't have public functions to unpack specific resource record types, but there are functions inside it to help you do it yourself.
In particular, look at dn_expand which can read a (compressed) domain name and ns_get16 which will read a big-endian two-octet field from a record, so in your case:
char exchange[NS_MAXDNAME];

const u_char *rdata = ns_rr_rdata(rr);

const uint16_t pri = ns_get16(rdata);
int len = dn_expand(nsbuf, nsbuf + msg_len, rdata + 2, exchange, sizeof(exchange));

printf("Pri->%d\n", pri);
printf("Exchange->%s\n", exchange);

where msg_len replaces your overwritten l variable, containing the length of the received packet.
The rdata + 2 in the call to dn_expand() skips the 16 bit priority field.


text:
Q: Connecting to the Tor network with Python without getting "Proxy server is refusing connection" I've been trying to use Tor via Python only to come across the "Proxy server is refusing connection" error.
I've trying this method using the Stem library:
http://www.thedurkweb.com/automated-anonymous-interactions-with-websites-using-python-and-tor/
Any help to fixing this error?
Here is the code:
import stem.process
from stem import Signal
from stem.control import Controller
from splinter import Browser

proxyIP = "127.0.0.1"
proxyPort = 9150

proxy_settings = {"network.proxy.type":1,
    "network.proxy.ssl": proxyIP,
    "network.proxy.ssl_port": proxyPort,
    "network.proxy.socks": proxyIP,
    "network.proxy.socks_port": proxyPort,
    "network.proxy.socks_remote_dns": True,
    "network.proxy.ftp": proxyIP,
    "network.proxy.ftp_port": proxyPort
}
browser = Browser('firefox', profile_preferences=proxy_settings)

def interactWithSite(browser):
    browser.visit("http://dogdogfish.com/python-2/generating-b2b-sales-data-in-python/")
    browser.fill("comment", "But the thing is... Why would anyone ever want to do this? I must have thought that times...")
    browser.fill("author", "Pebblor El Munchy")
    browser.fill("email", "barack@tehwhitehouz.gov")
    browser.fill("url", "https://upload.wikimedia.org/wikipedia/en/1/16/Drevil_million_dollars.jpg")
    button = browser.find_by_name("submit")
    button.click()

interactWithSite(browser)

A: I deleted the SSL and FTP proxy and port settings and it worked. I also used port 9150.
Here is the working code:
import stem.process
from stem import Signal
from stem.control import Controller
from splinter import Browser

proxyIP = "127.0.0.1"
proxyPort = 9150

proxy_settings = {"network.proxy.type":1,
    "network.proxy.socks": proxyIP,
    "network.proxy.socks_port": proxyPort,
    "network.proxy.socks_remote_dns": True,
}
browser = Browser('firefox', profile_preferences=proxy_settings)

def interactWithSite(browser):
    browser.visit("http://dogdogfish.com/python-2/generating-b2b-sales-data-in-python/")
    browser.fill("comment", "But the thing is... Why would anyone ever want to do this? I must have thought that times...")
    browser.fill("author", "Pebblor El Munchy")
    browser.fill("email", "barack@tehwhitehouz.gov")
    browser.fill("url", "https://upload.wikimedia.org/wikipedia/en/1/16/Drevil_million_dollars.jpg")
    button = browser.find_by_name("submit")
    button.click()

interactWithSite(browser)


text:
Q: Repeated measure block design got significant block and block interactions. Each block analysis showed 2 out of 5 blocks, not normally distributed I have Per Capita fecundity of females from two population of Drosophila (evolved and ancestral-Population type) females at 5 different age points (age fixed factor), where same females were used for fecundity measurement. My unit of analysis for per capita fecundity at each age point(1,5,10,15 and20) comes by-counting the number of eggs laid by group of 10 females divided by number of females alive at the start of that day point. So basically its a fraction type data. This experiment was carried out with 5 independent replicate population of the two population type. Thus represents repeated measure (female fecundity measured at different age points)block design with 5 statistical blocks.
However, I got significant block effect and block interactions with other fixed effects, when I ran LMM under lme4 package (lmer) taking block as random factor. So we analysed each block seperately,therefore first checked for normality distribution of each block, 2 out of 5 blocks were not normally distributed (residual distribution was checked S-W test). Here's the qq-plot from one of those blocks (Block 1-W = 0.97244, p-value = 0.005062):

Other blocks showed better qq-plots, although the Shapiro-Wilk test still suggested non-normality (Block 5-W = 0.9795, p-value = 0.02518):

So whether can i still go for parametric test with this much deviation from normality can be accepted or should i go for non-parametric test for these 2 blocks. I thought of doing GLMM (glmer) but I am not aware of what distribution would fit my data type? Is it Poisson or quasipoisson or Gamma?

A: With positive count data in both the numerator and the denominator of your fecundity measure, it might not be surprising that residuals don't follow a normal distribution. Poisson count data have a variance equal to the mean, necessarily smaller in magnitude at low counts and larger at high counts. That might explain the heavy-tailed nature of your qq plots. Here's a qq plot for a lm() fit of 450 Poisson-distributed Y values versus corresponding X mean values ranging from 1 to 15; code below. It has the same overall shape as yours.

Even if you eventually present the results in terms of that measure, your statistical analysis might best be done directly at the count level. That means starting with a Poisson generalized linear model (log link) and working from there, perhaps moving to a quasi-Poisson  or negative binomial model.
You would model the actual egg counts, using the log of the number of females as an offset for this rate-type analysis. Time and population type would still be fixed effects (with their interaction, which seems to be of interest), and the "blocks" (as I understand, 10 total, 5 for each population type) treated as random effects. The R DHARMa package provides useful tools for residual diagnostics.
One potential problem in the design: this assumes that per-capita fecundity is independent of the number of females alive at the start of each time point. If crowding affects fertility, then neither your fecundity index nor using the log of the number of females as an offset (fixed regression coefficient of 1) would be valid. Check that mortality is the same for the 2 population types at a minimum, and see if there's evidence of non-proportionality of egg counts against number of females under otherwise similar circumstances.

Code for the plot
> myX <- rep(1:15,30)
> length(myX)
[1] 450
> set.seed(1234)
> myY <- rpois(450,myX)
> poisDF <- data.frame(x=myX,y=myY)
> plot(lm(y~x,poisDF))


text:
Q: systemctl --user issue with dbus Failed to connect to bus: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR I'm trying to set up systemd services for a user, but when I try to start the service, I get the following errror:
$ systemctl --user enable vdirsyncer.timer
Failed to connect to bus: $DBUS_SESSION_BUS_ADDRESS and
$XDG_RUNTIME_DIR not defined (consider using --machine=<user>@.host --user
to connect to bus of other user)

I'm starting dbus in my .xinitrc with export $(dbus-launch)
$ echo $DBUS_SESSION_BUS_ADDRESS
unix:path=/tmp/dbus-3kIhCSkzBl,guid=40b6408906fa1337ba8283c06395fb80

$ echo $XDG_RUNTIME_DIR
/run/user/1000

$ systemctl --machine=$USER@$(hostname) --user  enable vdirsyncer.timer
Cannot access user instance remotely.


text:
Q: Unable to create a new remote session I am using Appium for automation testing. Whenever I am running it, after the application launch, my app gets killed.
This is the error log I am getting:
FAILED CONFIGURATION: @BeforeSuite setUp
org.openqa.selenium.SessionNotCreatedException: Unable to create a new remote session. Please check the server log for more details. Original error: An unknown server-side error occurred while processing the command. Original error: Could not proxy command to remote server. Original error: Error: read ECONNRESET
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'IN-6J1QPN2-10', ip: '10.0.75.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_171'
Driver info: driver.version: AndroidDriver
remote stacktrace: UnknownError: An unknown server-side error occurred while processing the command. Original error: Could not proxy command to remote server. Original error: Error: read ECONNRESET
    at JWProxy.command
System info: host: 'IN-6J1QPN2-10', ip: '10.0.75.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_171'
Driver info: driver.version: AndroidDriver

A: Please Run your appium server with Admin permission. Enable "Allow Session override" flag under the "Advance" tab in Appium server before start. After this, run the below mentioned commands.
adb uninstall io.appium.uiautomator2.server

adb uninstall io.appium.uiautomator2.server.test

Additionally you can run if you have "Unlock" and "Settings" installed in Test device for Appium.
adb uninstall io.appium.unlock

adb uninstall io.appium.settings

Now, run your test cases and let me know.


text:
Q: Should I use Scala's NaN or an "indicator vector"? I build a program based on a rather complex mathematical algorithm. In this I want to account for vectors that have missing values, so NaN. Until now I implemented those by having two vectors - both implemented with breeze's DenseVector[Double]: a vector location which contains the actual values and a vector evidence where a 1.0 denotes that the value is there and a 0.0 that a value isn't. With that I can do thing like this:
val ones = DenseVector.ones[Double](one.evidence.length)
val derivedLocation = one.evidence :* one.location :+ ((ones :- one.evidence) :* two.evidence :* two.location)

Another example would be:
val firstnewvector = myothervector(evidence :== 1.0)
val secondnewvector = myothervector(evidence :== 0.0)

but I also have some other example where I do need 0 as a result not NaN:
def gradientAt: DenseVector[Double] =
      (one.location - two.location) :* evidence :* othervalue

For the sake of argument this example has been simplified. I am thinking about dropping evidence and using NaN where there is no concrete value present, but I am not sure whether that is a good idea. I think it might already be more difficult to implement the above lines, wouldn't it? Also, I am not sure about performance. DenseVector is backed by an Array containing Java primitives and preventing slow auto-boxing if I am not mistaken. Using Double.NaN might require classes instead of primitives, and might slow the whole program down a little and cost more memory - is that right? (Speed and memory is a issue in general).
So: Is it a good idea in my case to use Double.NaN or considering 1) nice code and 2) performance (memory and speed)?


text:
Q: Extract SQLBrite logic to external class in Android In my chat app I use SQLBrite wrapper to update chat from local database. Currently my activity holds both UI and SQLBrite. Now I want to extract SQLBrite logic to external class. So while my activity is living I need my extracted SQLBrite also be alive.
Currently I have problem with subscriber. I also extracted it to external class, and its emitting query all the time, event though everything is same as it was while it was in activity, and it was working.
this is old code, where everything was in same activity:
How I can do this?
SqlBrite sqlBrite;
sqlBrite = SqlBrite.create(DatabaseManager.DatabaseHelper);
private final CompositeSubscription subscriptions = new CompositeSubscription();

private void saveMessage(Message message) {

        ContentValues values = new ContentValues();
        values.put(DatabaseContract.MessageEntry.COLUMN_NAME_MESSAGE_ID, message.getId());
        values.put(DatabaseContract.MessageEntry.COLUMN_NAME_SERIAL_NUMBER, message.getSerialNumber());
        values.put(DatabaseContract.MessageEntry.COLUMN_NAME_TEXT, message.getText());

        sqlBrite.insert(DatabaseContract.MessageEntry.TABLE_NAME, values, SQLiteDatabase.CONFLICT_IGNORE);
    }

    private void subscribeToDbChanges() {
        String NEW_MSG_QUERY = "SELECT * FROM "
                + DatabaseContract.MessageEntry.TABLE_NAME
                + " WHERE "
                + DatabaseContract.MessageEntry.COLUMN_NAME_CREATED_AT_MILLS
                + " >= ? ORDER BY "
                + DatabaseContract.MessageEntry.COLUMN_NAME_CREATED_AT_MILLS
                + " DESC";

        String grpId = String.valueOf(groupId);
        String msgDate = String.valueOf(dividerMsgDate);

        Observable<Query> freshMessages = sqlBrite.createQuery(DatabaseContract.MessageEntry.TABLE_NAME, NEW_MSG_QUERY, grpId, msgDate);
        subscriptions.add(
                freshMessages.subscribe(query -> parseQueryData(query)));
    }

    private void parseQueryData(Query query) {
        Log.d(TAG, "subscriber called");
        List<Message> messages = new ArrayList<>();
        Cursor c = query.run();
        try {
            while (c.moveToNext()) {
                Message message = new Message();
                message.setLocalId(c.getInt(c.getColumnIndexOrThrow(DatabaseContract.MessageEntry._ID)));
                message.setId(c.getInt(c.getColumnIndexOrThrow(DatabaseContract.MessageEntry.COLUMN_NAME_MESSAGE_ID)));

                messages.add(message);
            }
        } finally {
            c.close();
        }

        updateChatList(messages, "new");
    }

A: I am  not 100% sure I understood your question, but I would create a SQLBrite Helper class with the code you provided above and instantiate it in the onCreate() of the activity.
Additionally you have to pass the onResume() and onPause() events to your helper class (because you only need it when the activity is active), and return the results via a Callback.

 MyActivity.java

 public class MyActivity extends Activity implements SQLHelper.ResultListener {

   SQLHelper mSQLHelper;

   public void onCreate() {
     mSQLHelper = new SQLHelper(this);
   }

   public void onResume() {
     mSQLHelper.onResume();
   }

   public void onPause() {
     mSQLHelper.onPause();
   }

   @
   Override
   public void onUpdateChatList(String _message) {
     //show it
   }
 }

 SQLHelper.java

 public class SQLHelper {

   ResultListener mListener;

   public interface ResultListener {
     public void onUpdateChatList(String _message);
   }

   public void SQLHelper(ResultListener _resultListener) {
     mListener = _resultListener;
   }

   public void onResume() {
     //Here subscribe to your query
   }

   public void onPause() {
     //here unsubscribe
   }

   private void parseQueryData(Query query) {
     //... your code
     mListener.onUpdateChatList(String _message);
   }
 }

Hope that helps.


text:
Q: How do I update the dates (by 30 days) in the files going to that specific location in unix? How do I update the dates (by 30 days) in the files going to that specific location in unix? Can awk or sed help ?
File format is as below -
Thomson: xyz
Format: 1
Character_set: ASCII8
File_type: event_file
File_subtype: mobile_call
File_group_number: 1
File_in_group_number: 1
Total_files_in_group: 19
Source_ID: source
Tag: tag -v13
This file produced by GTFplaintext 0.1:
Event: "61765","1","2014/01/03-13-00-00.00",,"GBP",,,,,,,,,,"61765","0345351816","1407",,,,,,,,,,,,,,,,,,,,,
Footer: text_data_transfer_file
AuditValue_1: 1
AuditValue_2: 0
End: text_data_transfer_file
Lines: 15
Characters: 351
Checksum:
Security_checksum:
End_of_file:

In the above file I need to go to the line starting with 'Event:' and update the date
 "2014/01/03-13-00-00.00" by 30 days (only date needs to be updated, while time can remain same).
There are 20k such files in a directory, for which the dates have to be updated.

A: With perl and the Date::Manip module, you could do:
 perl -MDate::Manip -pi -e 's|^Event.*?"\K\d{4}/\d\d/\d\d|
   UnixDate(DateCalc("$&", "30 days later"), "%Y/%m/%d")|e' file1 file2...

A: awk '
  /^Event:/{
    d=substr($0,match($0,"[0-9]{4}(/[0-9]{2}){2}"),RLENGTH)
    "date +\"%Y/%m/%d\" -d \""d" 30 days\""|getline ds
    sub(d,ds)
    }
  1' file

For lines which starts from Event: find substring matching date format and put in in variable d. Then use system date command to set variable ds as date more than d for 30  days and substitute d by ds in string.


text:
Q: Port Binding Error while doing docker-compose I'm trying to bind port 8443 through docker and even though i do not have anything running on 8443, it is throwing me an error that 8443 is already in use.
After Looking for all running ports via this cmd: sudo lsof -i -P | grep LISTEN
launchd       1             root    8u  IPv6 0xbe03e516a8f8ef2f      0t0  TCP *:22 (LISTEN) launchd       1             root    9u  IPv4 0xbe03e516a8f9797f      0t0  TCP *:22 (LISTEN) launchd       1             root   11u  IPv6 0xbe03e516a8f8ef2f      0t0  TCP *:22 (LISTEN) launchd       1             root   12u  IPv4 0xbe03e516a8f9797f      0t0  TCP *:22 (LISTEN) launchd       1             root   24u  IPv6 0xbe03e516bbf55a6f      0t0  TCP localhost:8021 (LISTEN) launchd       1             root   26u  IPv4 0xbe03e516d869f97f      0t0  TCP localhost:8021 (LISTEN) launchd       1             root   38u  IPv6 0xbe03e516bbf55a6f      0t0  TCP localhost:8021 (LISTEN) launchd       1             root   39u  IPv4 0xbe03e516d869f97f      0t0  TCP localhost:8021 (LISTEN) UserEvent   118             root   83u  IPv6 0xbe03e516a8f8d6af      0t0  TCP [fe80:4::aede:48ff:fe00:1122]:49157 (LISTEN) UserEvent   118             root   84u  IPv6 0xbe03e516a8f9018f      0t0  TCP [fe80:4::aede:48ff:fe00:1122]:49158 (LISTEN) UserEvent   118             root   85u  IPv6 0xbe03e516a8f907af      0t0  TCP [fe80:4::aede:48ff:fe00:1122]:49159 (LISTEN) UserEvent   118             root   86u  IPv6 0xbe03e516a8f8ca6f      0t0  TCP [fe80:4::aede:48ff:fe00:1122]:49160 (LISTEN) UserEvent   118             root   88u  IPv6 0xbe03e516a8f8c44f      0t0  TCP [fe80:4::aede:48ff:fe00:1122]:49161 (LISTEN) mysqld      182           _mysql   29u  IPv6 0xbe03e516a8f8dccf      0t0  TCP *:33060 (LISTEN) mysqld      182           _mysql   31u  IPv6 0xbe03e516a8f8d08f      0t0  TCP *:3306 (LISTEN) mDNSRespo   272   _mdnsresponder   33u  IPv4 0xbe03e516d869d1ff      0t0  TCP *:53 (LISTEN) mDNSRespo   272   _mdnsresponder   65u  IPv6 0xbe03e516d9bd56af      0t0  TCP *:53 (LISTEN) ir_agent    338             root   10u  IPv4 0xbe03e516a8f965bf      0t0  TCP localhost:49155 (LISTEN) Spotify     795 nimish.prabhakar   59u  IPv4 0xbe03e516a968df9f      0t0  TCP *:59124 (LISTEN) Spotify     795 nimish.prabhakar  125u  IPv4 0xbe03e516beeb135f      0t0  TCP *:57621 (LISTEN) mongod      993 nimish.prabhakar   10u  IPv4 0xbe03e516bb03dd3f      0t0  TCP localhost:27017 (LISTEN) PanGPS     1000             root    7u  IPv4 0xbe03e516bb03c97f      0t0  TCP localhost:4767 (LISTEN) postgres   1148 nimish.prabhakar    7u  IPv6 0xbe03e516bbf566af      0t0  TCP localhost:5432 (LISTEN) postgres   1148 nimish.prabhakar    8u  IPv4 0xbe03e516bb03e71f      0t0  TCP localhost:5432 (LISTEN) Adobe\x20  1217 nimish.prabhakar    9u  IPv4 0xbe03e516a8f9971f      0t0  TCP localhost:15292 (LISTEN) node       1258 nimish.prabhakar   26u  IPv4 0xbe03e516bb03a1ff      0t0  TCP localhost:49222 (LISTEN) node       1258 nimish.prabhakar   28u  IPv4 0xbe03e516bc0205bf      0t0  TCP localhost:49223 (LISTEN) node       1258 nimish.prabhakar   29u  IPv4 0xbe03e516bc020f9f      0t0  TCP localhost:45623 (LISTEN) node       1258 nimish.prabhakar   30u  IPv4 0xbe03e516bb03abdf      0t0  TCP localhost:52739 (LISTEN) com.docke  1350 nimish.prabhakar   11u  IPv4 0xbe03e516bc02371f      0t0  TCP localhost:49238 (LISTEN) dcagentse 46158             root    9u  IPv4 0xbe03e516d1d545bf      0t0  TCP localhost:4990 (LISTEN)
And when I run docker-compose cmd
`Restarting front-proxy_service2_1    ... done
Restarting front-proxy_service1_1    ... done
Restarting front-proxy_front-envoy_1 ... error
ERROR: for front-proxy_front-envoy_1  Cannot restart container 479483e3a6a1bc205aaafa7c8e83bda45455c57acde22f82405963cd97d1b8b8: driver failed programming external connectivity on endpoint front-proxy_front-envoy_1 (75df27c2c6ad6c31a9781eb060f40bdd7f41d9ba8003c40b13dd6065bfa5421d): Error starting userland proxy: listen tcp4 0.0.0.0:8443: bind: address already in use`
Cant seem to figure out what might be the issue here.

A: you can kill 8443 port
kill -9 $(lsof -t -i:8443)


text:
Q: How to decode json array in square bracket under curly bracket I am unable to get array data between square bracket under curly bracket. This is json output:
{"data":{"user":[{"transaction":"45455","date":"2013-10-28" }],"msg":"ok"},"error":[]}

I have tried this:
$obj = json_decode($json_data, true);
$user_data_array = $obj['data']['user'];

But I am unable to get data in user array. Waiting for you quick reply and thanks in advance.

A: I assume the "ok" in the message should be a string? Right now your json is invalid.
$json_data = '{"data":{"user":[{"transaction":"45455","date":"2013-10-28"}],"msg":"ok"},"error":[]}';

$obj = json_decode($json_data, true);
$user_data_array = $obj['data']['user'];

A: $user_data_array = $obj['data']['user'][0]['transaction'];


text:
Q: R - how to evaluate a text string I'm quite new to R and failed to google the answer. The question is, how can I tell R to treat a character string value as a part of code, in a manner SAS resolve() function does?
Say, I have a data frame containing numeric columns V1, ..., Vn and exactly n rows. I wish to sum up all the 'diagonal' elements V = V1[1] + V2[2]... + Vn[n] but n is large enough for manual summation (below, n=2 for simplicity).
I'm trying to put the strings "dat$V1[1]", "dat$V2[2]" in a character C and then extract the corresponding numerical value (all in a loop step):
> dat <- data.frame(V1 = c(2,3), V2 = c(7,11))
> dat
    V1 V2
  1  2  7
  2  3 11

V = 0
for(i in 1:nrow(dat))
{
  C = paste('dat$V',format(i,trim=TRUE),'[',format(i,trim=TRUE),']',
            sep="" )
  f = Xfun(C)
  V = V + f
}

What should be used instead of Xfun? I've tried as.formula(), asOneSidedFormula(), get("...") and some other, but it's essential that dat$V1 is not an object:
> exists("dat")
[1] TRUE
> exists("dat$V1")
[1] FALSE

Your help is much appreciated.

A: If you just want to sum the diagonal elements of a square matrix, just do
dat <- data.frame(V1 = c(2,3), V2 = c(7,11))

sum(diag(as.matrix(dat)))

If you want to evaluate a text string in R, read up a bit on eval or do ? eavl  in R.
For your problem, you can do this:
dat <- data.frame(V1 = c(2,3), V2 = c(7,11))
dat

V = 0
for(i in 1:nrow(dat))
{
  C = paste('dat$V',format(i,trim=TRUE),'[',format(i,trim=TRUE),']',
            sep="" )
  f = eval(parse(text=C))
  V = V + f
}

A: To finalize:
a) correct answer using text parsing and evaluation
V = 0
for(i in 1:nrow(dat))
{ C = paste('dat$V',as.character(i),'[',as.character(i),']',
            sep='' )
  V = V + eval(parse(text=C))
}

b) correct action ESPECIALLY for a data frame - without requiring text evaluation but addressing data frame columns directly by name
V = 0
for(i in 1:nrow(dat))
{ col = paste('V',as.character(i),
              sep='')
  V = V + dat[i,col]
}


text:
Q: How to convert decimal OR hexadecimal value to integer? I receive a string which can be a number '42' or an hexadecimal number '0x12'. I would like to convert this to a number.
I currently have this very cumbersome function:
function str2num(str) {
    if (str.substr(0, 2) == '0x')
        return parseInt(substr(2, str), 16)
    else
        return parseInt(str, 10)
}

Is there a shorter way to do that?

A: If I understand properly you want convert anything to integer; so you can just use
parseInt('0x12'). It convert any type of variable to integer.


text:
Q: matlab expression Equivalent in R Which expression would be the most similar to the following one:
BDe(i,:) = [];

I use this to delete the row i of BDe (matrix n*m dimension) in a for loop.
A reproducible example:
data = [ 1 1 1 ; 2 2 2; 3 3 3]
data =
 1     1     1
 2     2     2
 3     3     3
data(1,:)=[]
data =
 2     2     2
 3     3     3

Target
Drop observations by iterating their matrix number row

A: Pretty sure you are looking for for
Example Data
data=read.table(text=" 1     1     1
 2     2     2
                3     3     3")

Code
 data[-1,]

  V1 V2 V3
2  2  2  2
3  3  3  3

Note please be aware of the following behavior in a loop.
x<-1:10
for(i in c(2,3,7)){x<-x[-i]}
x
[1]  1  3  5  6  7  8 10

It can be better to just do
x<-1:10
x[-c(2,3,7)]

A: First of all, I would recommend, that you use a some kind of filter function instead of "deleting" 1 row. For example, it would look like this, if you want to keep only the rows, which have a sum of 6:
filter <- function(x) {
  sum(x) == 6
}

BDe[apply(BDe, 1, filter), ]

If you want to delete a row, you can't assign an empty vector for a row, what you can do is to reassign your the matrix without the ith row:
BDe <- BDe[-i,]


text:
Q: How to make Spark read only specified rows? Suppose I'm selecting given rows from a large table A. The target rows are given either by a small index table B, or by a list C. The default behavior of
A.join(broadcast(B), 'id').collect()

or
A.where(col('id').isin(C)).collect()

will create a task that reads in all data of A before filtering out the target rows. Take the broadcast join as an example, in the task DAG, we see that the Scan parquet procedure determines columns to read, which in this case, are all columns.

The problem is, since each row of A is quite large, and the selected rows are quite few, ideally it's better to:

*

*read in only the id column of A;

*decide the rows to output with broadcast join;

*read in only the selected rows to output from A according to step 2.

Is it possible to achieve this?
BTW, rows to output could be scattered in A so it's not possible to make use of partition keys.

A:
will create a task that reads in all data of A

You're wrong. While the first scenario doesn't push any filters, other than IsNotNull on join key in case of inner or left join, the second approach will push In down to the source.
If isin list is large, this might not necessary be faster, but it is optimized nonetheless.
If you want to fully benefit from possible optimization you should still use bucketing (DISTRIBUTE BY) or partitioning (PARTITIONING BY). These are useful in the IS IN scenario, but bucketing can be also used, in the first one, where B is too large to be broadcasted.


text:
Q: Performance for particle system Situation
I created a particle system with JavaFX using the following technique:
Each particle is an ImageView which contains an Image with a radial gradient:

The particle handling loop is an AnimationTimer in which the list of particles is handled via the list's stream().parallel() method, it actually gives the whole system a boost. Something like this:
loop = new AnimationTimer() {

    @Override
    public void handle(long now) {

        addParticle();

        // apply force: gravity
        allParticles.stream().parallel().forEach(Particle::applyForceGravity);

        // move particle
        allParticles.stream().parallel().forEach(Particle::move);

        // update position in fx scene
        allParticles.forEach(Particle::display);

        // remove all particles that aren't visible anymore
        removeDeadParticles();

    }
};

The particle's color changes via ColorAdjust during its lifecycle. I used fire colors for testing, something like this which contains 1700 particles:

What I've learned:

*

*not using parallel() is slower

*using Circle with transparency is way slower than using an ImageView

*using a Blend Mode is very slow

*using a PixelWriter to change the image color is unbearable slow. Question arises: how does ColorAdjust change the color (via d3d & hardware)? I haven't found the mechanism in the JavaFX source code.

Question
Is there a better way to implement a particle system in JavaFX (other Node types, Thread, etc) in regards to performance?
I can post some code if anyone wants to toy around.
Thank you very much for the expertise!

Edit: Since it was asked, you can get the full code which uses nodes as particles with coloradjust from this gist. Btw, even if you pre-render the images and don't use coloradjust, the performance is low.
However, the question is more of a theoretical kind, so digging through the code isn't really necessary.

A: I think I can add an answer to my own question. But I hope someone else with more experience can share their knowledge, because what I came up with was just the result of toying around:
Painting on a Canvas instead of using JavaFX ImageView nodes surprisingly resulted in a factor of at least 10x speed increase. This is basically what I did:

*

*pre-calculate the images with the gradients, i. e. the color and the size of them depending on the particle's lifespan

*in the animation timer get the pre-calculated image and paint it on the canvas

If anyone is interested, you can get the full code from this gist. Just click "Download Zip" and put the code of the zip in an "application" package of a JavaFX project and start the Main class. The difference to the code in the question is in the Particle.java class. In the question the particles are used as nodes and moved in the animation timer, but in this answer only the data is used for drawing an image on a canvas in the animation timer, the node itself isn't put on the scene.
You can use the Settings class in order to specify resolution, number of new particles per frame, etc.
This screenshot shows 3 repellers and 25400 particles on the screen in Full-HD resolution, running at 60fps:

A: I think it might also help to combine these two lines:
// apply force: gravity
allParticles.stream().parallel().forEach(Particle::applyForceGravity);

// move particle
allParticles.stream().parallel().forEach(Particle::move);

kind of like this:
allParticles.stream().parallel().forEach(particle -> {
  particle.applyForceGravity();
  particle.move();
});

This way you don't get twice the overhead.


text:
Q: Get decoded frames in Flash (FLVplayback) I want to know if it is possible to get the decoded frames from FLVPlayback, or if it is known another alternative to access the decoded frames from a flash player.
What I want to do is to manipulate the decoded frames before they get rendered on screen.
The video source could be an RTMP stream or a FLV (F4V) file.
Any hint is welcome :)

A: In what way do you wish to modify them?
If you need to do any per-pixel operation, and are not using Flash Player 10 (in which case you should look up Pixel Bender), you can use the BitmapData.draw() function to draw your frame into a BitmapData. You can then manipulate the pixels as you wish.
var bmp : BitmapData = new BitmapData(myVideo.width, myVideo.height, false);

// Each frame, do this:
bmp.draw(myVideo);

If you just simply want to apply some sort of generic filter, like blur, you can look up the flash.filters.* classes instead, e.g. BlurFilter, DropShadowFilter or ColorMatrixFilter.


text:
Q: Is array name a constant pointer in C++? I have a question about the array name a
int a[10]

How is the array name defined in C++? A constant pointer? It is defined like this or just we can look it like this? What operations can be applied on the name?

A: An array name is not a constant pointer - however it acts like one in so many contexts (it converts to one on sight pretty much) that for most purposes it is.
From 6.3.2.1/3 "Other operands/Lvalues, arrays,and function designators":

Except when it is the operand of the sizeof operator or the unary & operator, or is a string  literal  used  to  initialize  an  array, an expression  that  has  type  "array  of type"  is converted to an expression with type "pointer to type" that points to the initial element of the  array  object  and  is  not  an  lvalue.

A: The C++ standard defines what an array is and its behaviour. Take a look in the index. It's not a pointer, const or otherwise, and it's not anything else, it's an array.
To see a difference:
int a[10];
int *const b = a;

std::cout << sizeof(a); // prints "40" on my machine.
std::cout << sizeof(b); // prints "4" on my machine.

Clearly a and b are not the same type, since they have different sizes.
In most contexts, an array name "decays" to a pointer to its own first element. You can think of this as an automatic conversion. The result is an rvalue, meaning that it's "just" a pointer value, and can't be assigned to, similar to when a function name decays to a function pointer. Doesn't mean it's "const" as such, but it's not assignable.
So an array "is" a pointer much like a function "is" a function pointer, or a long "is" an int. That is to say, it isn't really, but you can use it as one in most contexts thanks to the conversion.


text:
Q: Could not find coffee-script-source-1.1.3 in any of the sources Hi I'm doing Rails app and when I bundle install it returns an error:
Could not find coffee-script-source-1.1.3 in any of the sources
I know that coffee-script-source-1.1.3 gem is deprecated/yanked but my other gems are having dependencies with this.
But this project is working with other machine and in heroku production.
How can I successfully bundle install this without changing my gemfile?
Thanks

A: Run this:
bundle update --source coffee-script-source

If you get an error, like this:
An error occurred while installing rmagick (2.13.1), and Bundler cannot continue.

Run this:
 gem install rmagick

I hope it'll help you.

A: What it worked for me was to update the gem to 1.2.0.
As it shows here https://rubygems.org/gems/coffee-script-source/versions
1.1.3 says that it's yanked.
gem 'coffee-script-source', '~> 1.2.0'

And run
bundle update --source coffee-script-source


text:
Q: How to manually update RKHUNTER with newly found rootkits? How to manually update RKHUNTER with newly found rootkits?
For example, the current latest version of rkhunter tool doesn't detect jynx2 rootkit.
How to manually update it's database. Simple rkhunter --update command doesn't work in this case.