text:
Q: Type inference in lambdas I have this functionality:
 public class Repository : IRepository
    {
        public List<TEntity> GetOrdered<TEntity, TSortKey>(Func<TEntity, TSortKey> orderBy, int take, params string[] includePaths) where TEntity : AbstractEntity
        {
            var query = (from ent in this.Context.Set<TEntity>() select ent).IncludePaths(includePaths);

            return query.OrderBy(orderBy).Take(take).ToList();
        }
    }

To invoke it:
List<Project> p = repository.GetOrdered<Project, string>(x => x.Name, 10);

I want to eliminate the need to give it the second generic parameter when invoking, it's a deal breaker from an API perspective.
How to do it?

A:
it's a deal breaker from an API perspective

then consider your deal broken...  You can't partially infer generic parameters.  If your repository was generic you could possibly do:
 public class Repository<TEntity> : IRepository<TEntity> where TEntity : AbstractEntity
{
    public List<TEntity> GetOrdered<TSortKey>(Func<TEntity, TSortKey> orderBy, int take, params string[] includePaths)
    {
        var query = (from ent in this.Context.Set<TEntity>() select ent).IncludePaths(includePaths);

        return query.OrderBy(orderBy).Take(take).ToList();
    }
}

then do
List<Project> p = repository.GetOrdered(x => x.Name, 10);

But I don't know if that change is possible for you.

A: Either the compiler can infer all type parameters, or you have to specify them all. But you may explicitly specify the argument type of the lambda expression, such as:
List<Project> p = repository.GetOrdered((Project x) => x.Name, 10);


text:
Q: Sequence of continuous functions on $[0,1]$ $f_n(x):[0,1]\rightarrow [0,1]$ are continuous and converges to $f(x)$, then

*

*$f$ is continuous.

*Convergence is uniform on $[0,1]$

*Convergence is uniform on $(0,1)$

*None of above statement is true.
Well, for 1 take $f_n(x)=x^n$, $f(x)=0$ for $ x \in [0,1)$ and $f(x)=1$ at $x=1$ hence 1 is false. For 2 I can give the same counter example as of 1. I have no idea about 3. Please help.

A: HINT:
You can use the same counterexample with a little work for 3 too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Brightcove account how to get a list of playerKey/playerID We are trying to provide the end user a easy way to select both a video and a player to be displayed on the final HTML page.
Is there a way to programmatically get a list of all players (playerKey/playerID/playerType) for one account?
If not, is it on the roadmap to support this functionality?
Using the Media API we've been able to get all the videos.
But we can't seem to find a way to do the same for the players.

A: There isn't a way to get player information from Brightcove's API.


text:
Q: How many partial order on a n-set? Let $A$ be a set has $n$ element, my question is how many partial order on it?
For $n=0,1$, $N_P(n)=1$
Case $n=2$, $N_P(n)=3$
Case $n=3$, $N_P(n)=19$
Is there a general formula?
Update:
It seems closed formula have not been found yet. But does any generating function be known current?

A: A001035 doesn't list a closed-form formula.

A: This is the sequence OEIS A001035, the number of partial orders on a labelled $n$-element set; OEIS A000112 gives the number of partial orders on an unlabelled $n$-element set. Neither entry gives a closed formula, a recurrence, or a generating function. Both cite

D. J. Kleitman and B. L. Rothschild, Asymptotic enumeration of partial orders on a finite set, Trans. Amer. Math. Soc., 205 (1975) 205-220

among the references, suggesting that at present all we have are exact results for small $n$ (up to at least $18$ for the labelled case and $16$ for the unlabelled case) and asymptotic results.


text:
Q: .htaccess 301 redirect to two different sites Have a site source.com that is getting closed, so we would like to 301 redirect it to two other sites target1.com and target2.com.
Some specific urls on source.com must be 301 redirected to target1.com, including some wildcard urls like source.com/p/*
Other specific urls on source.com must be 301 redirected to target2.com, including some wildcard urls like source.com/q/*
Finally, all the urls that aren't covered by the lists/wildcards above must be redirected to the frontpage of target1.com
Is that possible to do via .htaccess?
Thanks!

A: You can use these rules in your site root .htaccess of source.com:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?:www\.)?source\.com$ [NC]
RewriteRule ^p(/.*)?$ http://target1.com%{REQUEST_URI} [L,NC,R=301,NE]

RewriteCond %{HTTP_HOST} ^(?:www\.)?source\.com$ [NC]
RewriteRule ^q(/.*)?$ http://target2.com%{REQUEST_URI} [L,NC,R=301,NE]

Even if you delete all content on source.com, you must keep the domain alive to make this redirection work.


text:
Q: Google Maps Polygon - redraw after adding new points I have a script, where I need to be able to draw a poligon.
Here is the current script.
When I add a new point, a new poligon is drawn over the old one, instead of redraw the current polygon with the new point added.
I tried to add
    poligon.setMap(null);

before creating the new poligon is created, but then the polygon will not apear at all.
Can anyone tell me what am I doing wrong?
I am new to Google maps API, so please be gentle.
Thanks a lot for your help.
code snippet:

var coords = [];
var poligonCoords = [];
var map = null;
var poligon = null;

function getMinX(a) {
  var ar = [];
  for (i = 0; i < a.length; i++) {
    ar.push(a[i].x);
  }
  return Math.min.apply(Math, ar);
}

function getMaxX(a) {
  var ar = [];
  for (i = 0; i < a.length; i++) {
    ar.push(a[i].x);
  }
  return Math.max.apply(Math, ar);
}

function getMinY(a) {
  var ar = [];
  for (i = 0; i < a.length; i++) {
    ar.push(a[i].y);
  }
  return Math.min.apply(Math, ar);
}

function getMaxY(a) {
  var ar = [];
  for (i = 0; i < a.length; i++) {
    ar.push(a[i].y);
  }
  return Math.max.apply(Math, ar);
}

function getCoords() {
  jQuery('ul#coords li').each(function() {
    var x = jQuery(this).children('input:first-child').val();
    var y = jQuery(this).children('input:last-child').val();
    coords[coords.length] = {
      "x": x,
      "y": y
    };
  });
}

function setPoligon() {
  if (!poligon) {}
  for (i = 0; i < coords.length; i++) {
    var point = new google.maps.LatLng(coords[i].x, coords[i].y);
    poligonCoords.push(point);
  }
  poligon = new google.maps.Polygon({
    paths: poligonCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });

  poligon.setMap(map);
}

function initialize() {

  getCoords();

  var minX = getMinX(coords);
  var minY = getMinY(coords);

  var maxX = getMaxX(coords);
  var maxY = getMaxY(coords);

  centerX = minX + ((maxX - minX) / 2);
  centerY = minY + ((maxY - minY) / 2);
  if (!centerX || !centerY) {
    centerX = 46.361416;
    centerY = 25.802191;
  }
  var mapOptions = {
    zoom: 16,
    center: new google.maps.LatLng(centerX, centerY),
    mapTypeId: google.maps.MapTypeId.SATELLITE,
    scaleControl: true,
    streetViewControl: true
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  setPoligon();

  google.maps.event.addListener(map, 'dblclick', function(event) {
    var ev = event.latLng;
    document.getElementById("latLong").innerHTML = "" + ev.lat().toFixed(6) + ", " + ev.lng().toFixed(6) + "";
    jQuery("ul#coords").append(jQuery("ul#coords li:first-child").clone());
    jQuery("ul#coords li:last-child").children('input:first-child').val(ev.lat().toFixed(6));
    jQuery("ul#coords li:last-child").children('input:last-child').val(ev.lng().toFixed(6));
    getCoords();
    setPoligon();
  });

}
google.maps.event.addDomListener(window, 'load', initialize);
      html,
      body {
        height: 100%;
        margin: 0px;
        padding: 0px;
        position: relative;
      }
      #map-canvas {
        margin: 0px;
        padding: 0px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 20%;
      }
      #info {
        margin: 0px;
        padding: 1em;
        box-sizing: content-box;
        position: absolute;
        top: 80%;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ececec;
        border-top: 1px solid #cccccc;
        box-shadow: 0 0 .5em #636363;
        overflow: auto;
      }

X:
        <input type='text' name='coords[][x]' value='46.216917'>Y:
        <input type='text' name='coords[][y]' value='25.728241'>

X:
        <input type='text' name='coords[][x]' value='46.214539'>Y:
        <input type='text' name='coords[][y]' value='25.729388'>

X:
        <input type='text' name='coords[][x]' value='46.211428'>Y:
        <input type='text' name='coords[][y]' value='25.730610'>

X:
        <input type='text' name='coords[][x]' value='46.209813'>Y:
        <input type='text' name='coords[][y]' value='25.725277'>

X:
        <input type='text' name='coords[][x]' value='46.209296'>Y:
        <input type='text' name='coords[][y]' value='25.717523'>

X:
        <input type='text' name='coords[][x]' value='46.213830'>Y:
        <input type='text' name='coords[][y]' value='25.722928'>

  Info:

A: Your issue is you are never clearing out the coords array, so every time you add a new polygon you get another duplicate set of coordinates in it.
Change:
function getCoords(){
    jQuery('ul#coords li').each(function(){
        var x = jQuery(this).children('input:first-child').val();
        var y = jQuery(this).children('input:last-child').val();
        coords[coords.length] = { "x":x, "y":y };
    });
}

To:
function getCoords(){
    coords = [];
    jQuery('ul#coords li').each(function(){
        var x = jQuery(this).children('input:first-child').val();
        var y = jQuery(this).children('input:last-child').val();
        coords[coords.length] = { "x":x, "y":y };
    });
}

Add:
if(!!poligon && !!poligon.setMap){
    poligon.setMap(null);
    poligonCoords = [];
}

and the map property to your existing polygon.
working code snippet:

var coords=[];
var poligonCoords = [];
var map = null;
var poligon = null;

function getMinX(a) {
 var ar = [];
 for(i=0;i<a.length;i++) {
  ar.push(a[i].x);
 }
    return Math.min.apply(Math,ar);
}

function getMaxX(a){
 var ar = [];
 for(i=0;i<a.length;i++) {
  ar.push(a[i].x);
 }
    return Math.max.apply(Math,ar);
}

function getMinY(a) {
 var ar = [];
 for(i=0;i<a.length;i++) {
  ar.push(a[i].y);
 }
    return Math.min.apply(Math,ar);
}

function getMaxY(a){
 var ar = [];
 for(i=0;i<a.length;i++) {
  ar.push(a[i].y);
 }
    return Math.max.apply(Math,ar);
}

function getCoords(){
    coords = [];
 jQuery('ul#coords li').each(function(){
  var x = jQuery(this).children('input:first-child').val();
  var y = jQuery(this).children('input:last-child').val();
  coords[coords.length] = { "x":x, "y":y };
 });
}

function setPoligon(){
 if(!!poligon && !!poligon.setMap){
        poligon.setMap(null);
        poligonCoords = [];
 }
 for(i=0;i< coords.length;i++){
  var point = new google.maps.LatLng( coords[i].x, coords[i].y );
  poligonCoords.push(point);
        var marker = new google.maps.Marker({position:point,map:map,title:"marker "+i});
 }
 poligon = new google.maps.Polygon({
        map:map,
     paths: poligonCoords,
     strokeColor: '#FF0000',
     strokeOpacity: 0.8,
     strokeWeight: 3,
     fillColor: '#FF0000',
     fillOpacity: 0.35
 });

 poligon.setMap(map);
}

function initialize() {

 getCoords();

 var minX = getMinX(coords);
 var minY = getMinY(coords);

 var maxX = getMaxX(coords);
 var maxY = getMaxY(coords);

 centerX =  minX + ((maxX - minX) / 2);
 centerY = minY + ((maxY - minY) / 2);
 if(!centerX || !centerY){
  centerX = 46.361416; centerY = 25.802191;
 }
 var mapOptions = {
     zoom: 16,
     center: new google.maps.LatLng(centerX, centerY),
     mapTypeId: google.maps.MapTypeId.SATELLITE,
     scaleControl: true,
     streetViewControl: true
 };

 map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

 setPoligon();

 google.maps.event.addListener(map, 'dblclick', function(event) {
  var ev = event.latLng;
     document.getElementById("latLong").innerHTML = "" + ev.lat().toFixed(6) + ", " +ev.lng().toFixed(6)+ "";
     jQuery("ul#coords").append(jQuery("ul#coords li:first-child").clone());
     jQuery("ul#coords li:last-child").children('input:first-child').val(ev.lat().toFixed(6));
     jQuery("ul#coords li:last-child").children('input:last-child').val(ev.lng().toFixed(6));
     getCoords();
     setPoligon();
 });

}
google.maps.event.addDomListener(window, 'load', initialize);
      html, body {
        height: 100%;
        margin: 0px;
        padding: 0px;
        position: relative;
      }
      #map-canvas {
        margin: 0px;
        padding: 0px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 20%;
      }
      #info {
        margin: 0px;
        padding: 1em;
        box-sizing: content-box;
        position: absolute;
        top: 80%;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ececec;
        border-top: 1px solid #cccccc;
        box-shadow: 0 0 .5em #636363;
        overflow: auto;
      }

X: <input type='text' name='coords[][x]' value='46.216917'> Y:<input type='text' name='coords[][y]' value='25.728241'>

X: <input type='text' name='coords[][x]' value='46.214539'> Y:<input type='text' name='coords[][y]' value='25.729388'>

X: <input type='text' name='coords[][x]' value='46.211428'> Y:<input type='text' name='coords[][y]' value='25.730610'>

X: <input type='text' name='coords[][x]' value='46.209813'> Y:<input type='text' name='coords[][y]' value='25.725277'>

X: <input type='text' name='coords[][x]' value='46.209296'> Y:<input type='text' name='coords[][y]' value='25.717523'>

X: <input type='text' name='coords[][x]' value='46.213830'> Y:<input type='text' name='coords[][y]' value='25.722928'>

     Info:


text:
Q: How to add javascript functions to divs loaded externally? I have page A and pageB.
Page A loads page B into a div.
There are divs in page B that I when I want to execute functions onclick.
The problem is that no matter where I place pageB's javascript it doesn't work.
I assumed that if i had a function ot initalise pagesB's javascript after it was loaded into the div this would work... but no success...
Any responses would be very helpful... regards J

A: If you're loading Page B with ajax, then most likely the javascript inside Page B is getting stripped out. This is due to a security concern.
An alternative way to get this to work would be that you separate your structure like this

*

*Page A HTML

*Page A javascript

*Page B HTML

*Page B javascript

Now, when you load Page A you should load the following:

*

*Page A HTML

*Page A javascript

*Page B javascript

Then, when you make your ajax call to load Page B HTML, you simply call the Page B javascript (which is already loaded) and everything should work.
Here's an example of what I'm describing:
http://jsfiddle.net/josephbulger/zSmQE/

A: How are you pulling in the page B? You need to bring it in raw, some methods of pulling in pages actually process the page and return the results instead of just returning the code. This may be part of the problem, but I wouldn't think it would be.
Also, you should be able to just reference the controls in page B and you can use document.getElementById or if using jquery $("controlID").event and wire functions to them.
actually, you could put page B's javascript into an external file and then add it to page A using script src= because once the code is pulled into the page, they are part of the page.


text:
Q: How can I get a dict value by another dict? I'm trying to get dict1 value by using a dict2 but I'm getting an error msg

SyntaxError: invalid syntax

dict1 = {"1": "Ali","2": "21","3": "Kuwait"}
dict2 = {"Name": "1","Age": "2","City": "Kuwait"}
print(dict1['dict2['Name']'])

A: It looks like you want: print(dict1[dict2['Name']])


text:
Q: Hazelcast refuses Member In our system, we have a Hazelcast cluster consisting of 2 nodes.
Hazelcast is refusing the connection of the other member. What could be the reasons?
In the log file i see:
2017-10-13 17:39:25,419 [T:B_Hazelcast.IO.thread-Acceptor, C:] INFO  c.h.n.tcp.SocketAcceptorThread | [10.15.162.50]:5701 [ESB_Hazelcast] [3.7.2] **Accepting socket connection** from /10.15.162.51:33497

2017-10-13 17:39:25,420 [T:_ESB_Hazelcast.cached.thread-5, C:] INFO  c.h.n.t.TcpIpConnectionManager | [10.15.162.50]:5701 [ESB_Hazelcast] [3.7.2] **Established socket connection** between /10.15.162.50:5701 and /10.15.162.51:33497

2017-10-13 17:39:25,428 [T:ity-generic-operation.thread-0, C:] INFO  c.h.c.i.p.t.AuthenticationMessageTask | [10.15.162.50]:5701 [ESB_Hazelcast] [3.7.2] Received auth from Connection[id=12, /10.15.162.50:5701->/10.15.162.51:33497, endpoint=null, alive=true, type=JAVA_CLIENT], **successfully authenticated**, principal : ClientPrincipal{uuid='39851f2a-cc6e-4bbb-be33-603352b2aaa6', ownerUuid='126694e3-daee-4999-8afc-870f1cd9da2e'}, owner connection : true

2017-10-13 17:39:25,512 [T:ity-generic-operation.thread-0, C:] WARN
c.h.c.i.o.ClientReAuthOperation | [10.15.162.50]:5701 [ESB_Hazelcast] [3.7.2] com.hazelcast.spi.exception.**CallerNotMemberException: Not Member!** this: [10.15.162.50]:5701, caller: [10.15.162.51]:5701, partitionId: -1, operation: com.hazelcast.client.impl.operations.ClientReAuthOperation, service: hz:core:clientEngine

The server is instantiated with
public static HazelcastInstance createServer(Environment env) {
    com.hazelcast.config.Config hazelcastConfig = new com.hazelcast.config.Config();
    final String clusterName = env.getProperty("core.hazelcast.clusterName");
    hazelcastConfig.getGroupConfig().setName(clusterName);
    hazelcastConfig.getGroupConfig().setPassword(env.getProperty("core.hazelcast.clusterPassword"));

    JoinConfig joinConfig = hazelcastConfig.getNetworkConfig().getJoin();
    joinConfig.getMulticastConfig().setEnabled(false);
    joinConfig.getTcpIpConfig().setEnabled(true);
    final String members = env.getProperty("core.hazelcast.members");

    //Here it comes!!!
    if (!StringUtils.isEmpty(members)) {
        joinConfig.getTcpIpConfig().addMember(members);
    }
    hazelcastConfig.setProperty(GroupProperty.LOGGING_TYPE.getName(), "slf4j");
    return new HazelcastLifecycleBean(Hazelcast.newHazelcastInstance(hazelcastConfig));
}

In the configuration file is
core.hazelcast.members=10.15.162.50,10.15.162.51

And this is passed to joinConfig.getTcpIpConfig().addMember
Any ideas?

A: Please specify the port as part of your tcp member addresses. Instead of core.hazelcast.members=10.15.162.50,10.15.162.51 use core.hazelcast.members=10.15.162.50:5701,10.15.162.51:5701


text:
Q: Security Restrict Services in ServiceStack and Fluent API Reading the answer in  How can I hide endpoints from Swagger UI in Servicestack?
and the  Security Restrict Services  documentation.
is it possible    to register   restrictions , using a  Fluent API, as we do with Routes ?
adding in a table in  AppHost Configure ?
there are a lot of advantages, configuring the services, in one place, by this way.
Also, can we restrict services using custom EndpointAttributes or (another way) ?
e.g depending on user ?


text:
Q: How to fix 'Module build failed (from ./node_modules/image-webpack-loader/index.js)' I'm settung up an React+Redux-saga+ANTD application,while running the application i found this error "Module build failed (from ./node_modules/image-webpack-loader/index.js):
TypeError: Cannot set property 'then' of undefined"
I have tried with npm modules reinstall.after npm clean cache.
I want to include i have been using windows 7 os with 32-bit.


text:
Q: Recursively append childs of tree in __str__ method I'm learning from a data structures and algorithms course where I made my own Tree (General Tree) implementation class, which looks like this:
class TreeNode:

    def __init__(self, data: Any) -> None:
        self.data = data
        self.children = []
        self.parent = None

    def __str__(self) -> str:
        return f'<{self.data} Tree[{self.children}]>'

    def add_childs(self, *childs: List) -> None:
        for child in childs:
            self.add_child(child)

    def add_child(self, child) -> None:
        if not isinstance(child, TreeNode):
            raise TypeError('TreeNode child must be another instance of TreeNode.')
        child.parnet = self
        self.children.append(child)

    def add_parent(self, parent) -> None:
        if not isinstance(parent, TreeNode):
            raise TypeError('TreeNode parent must be another instance of TreeNode.')
        parent.add_child(self)

And I'm testing this class with this:
def build_products_tree():
    tree = TreeNode('Electronics')
    laptops = TreeNode('Laptops')
    phones = TreeNode('Phones')
    tree.add_childs(laptops, phones)
    macbook = TreeNode('MacBook')
    dell = TreeNode('Dell')
    laptops.add_childs(macbook, dell)
    samsung = TreeNode('Samsung')
    iphone = TreeNode('iPhone')
    phones.add_childs(samsung, iphone)
    print(tree)

if __name__ == '__main__':
    build_products_tree()

I want the __str__ method to recursively add the children list (and their n nested values and so on) to the string value, like this:
<Electronics Tree[<Phones Tree[<iPhone Tree[]>, <Samsung Tree[]>]>, <Laptops Tree[<Dell Tree[]>, <MacBook Tree[]>]>]>

(I'll add this just for a more human-readable explanation):
<Electronics Tree[
    <Phones Tree[
        <iPhone Tree[]>,
        <Samsung Tree[]>
    ]>,
    <Laptops Tree[
        <Dell Tree[]>,
        <MacBook Tree[]>
    ]>
]>

But the current behavior of the __str__ method is returning just this:
<Electronics Tree[[<__main__.TreeNode object at 0x7f7c0b6b82e0>, <__main__.TreeNode object at 0x7f7c0b688d00>]]>

Is there any way to achieve this w/o making complex iterations inside the __str__ method? I thought the __str__ definition would apply to the nested values too since they're instances of the same class.

A: As @quamrana suggested, I achieved it with __repr__ like this:
def __repr__(self) -> str:
    return f'<{self.data} Tree[{self.children}]>'

And the returning value is looking as expected:
<Electronics Tree[[<Laptops Tree[[<MacBook Tree[[]]>, <Dell Tree[[]]>]]>, <Phones Tree[[<Samsung Tree[[]]>, <iPhone Tree[[]]>]]>]]>


text:
Q: Using multiline listboxes to create message using JS Need your help with this...I have listbox, textarea and button. Listbox is multiline and when a button is clicked the chosen line appears in textarea. The logic is simple but there is a problem. The thing is that i dont have only one listbox. I have another button which can add another or more similar listboxes with the same information(populating listboxes). So lets say that I need so many listboxes to add the names of friends to the textarea which is going to be used as letter in future. So im doing kind of program that will create message with default text just including names of friends. Anyway here is the code:
    function textSelect(){
var listItems = document.getElementById("listbox")
for (var n=0;n<listItems.length;n++) {
for (var i=0;i<listItems[n].length;i++) {
document.getElementById("textArea").value += 'This is  ' + listItems.text;}
}
}

here n - is listboxes and i -  is lines...But all I get as the result is blank textarea after clicking on the button. What is wrong here? please help me!!

A: You should probably use

document.getElementById('<%= listboxID.ClientID %>')
document.getElementById('<%= textAreaID.ClientID %>')

instead to search for the controls

function textSelect(){
  var listItems = document.getElementById('<%= listboxID.ClientID %>');
  for (var n=0;n<listItems.length;n++) {
      for (var i=0;i<listItems[n].length;i++) {
          document.getElementById('<%= textAreaID.ClientID %>').value +=
              'This is  ' + listItems.text;}
      }
  }

}


text:
Q: Javascript alert in code behind I need to call Javascript alert function in c# method if web service is not available. I am using as.net core and webapi for webservice.
Here is the code
  public List<EmployeeModel> GetEmployeeByEmpNo(string empNo)
    {
        try
        {
            string Baseurl = sys_ser.getApiURL();
            EmployeeModel EmpInfo = new EmployeeModel();

            using (var client = new HttpClient())
            {

                client.BaseAddress = new Uri(Baseurl);

                client.DefaultRequestHeaders.Clear();

                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage Res = client.GetAsync("api/Values/GetEmployeeByEmpNo/" + empNo).Result;

                if (Res.IsSuccessStatusCode)
                {

                    var EmpResponse = Res.Content.ReadAsStringAsync().Result;

                    var empobjList = JsonConvert.DeserializeObject<List<EmployeeModel>>(EmpResponse);
                    //var EmpObj = empobjList[0];

                    if (empobjList != null)
                    {
                        return empobjList;
                    }

                }
            }

        }
        catch(Exception ex)
        {
          //<Srcript> alert('WebService is not available' + ex.message)</>
        }
        return null;
    }

A: If AJAX isn't an option, you can pass a flag to tell the client to create the window:
Controller:
return View("Index", (object)errorDetails);

View:
@model string
<!--Your HTML-->

@if (!string.IsNullOrEmpty(Model)
{
    <script type="text/javascript">
        alert(Model);
    </script>
}


text:
Q: rails PaperTrail gem causing duplicate version entries starting with version 6 Here is a piece of rspec code defining a risk_action :
  let(:risk_action)           {
    risk_action = risk.risk_actions.new({name: 'action 1', user: user, action_status_id: created.id, due_date: '2018-02-10', owner_email: user.email, org: org})
    risk_action.org = org
    risk_action.assigned_to = user
    risk_action.save!
    risk_action
  }

Both in rails 4 & 5, this behaves as I expect (it creates and persists the risk_action without error).  Later in the rspec, I have a test case which runs a controller method and eventually calls this risk_action.  I can confirm nothing has manipulated the object in the meantime (largely because my test case which is checking it via papertrail is working correctly) :
it "correctly assigns the Paper_Trail whodunnit type", versioning: true, focus: true  do
  session = RiskActionSession.create({risk_action: risk_action})
  expect(session).to be_valid
  expect(session.status).to eq('CREATED')

  jwt = session.generate_jwt
  #request.env["HTTP_AUTHORIZATION"] = "JWT #{jwt}"    # <-- DOES NOT WORK
  get :update_action, id: session.id, risk_action: {action_status_id: closed.id}, token: jwt

  expect(response.status).to eq(200)
  # there should be 2 versions [create, update]
  versions = risk_action.versions
  expect(versions.length).to eq(2)
  # 1 update event
  ver = versions.where(event: "update")
  expect(ver.length).to eq(1)
  #whodunnit_type should be set to 'User'
  expect(ver[0].whodunnit_type).to eq("User")
end

end   #describe "update_action [PUT]" do
Then, after retrieving the risk_action and calling versions on it, I would expect to see a single create entry.  Instead, I see two, precise duplicated except for the id (of the version object) :
[#<PaperTrail::Version:0x0000000006b1a930
  id: 24328,
  item_type: "RiskAction",
  item_id: 44074,
  event: "create",
  whodunnit: "543076",
  object: nil,
  created_at: Mon, 15 Aug 2022 16:14:45 UTC +00:00,
  object_changes:
   "---\nname:\n- \n- action 1\nuser_id:\n- \n- 543076\naction_status_id:\n- \n- 66607\ndue_date:\n- \n- '2018-02-10 00:00:00'\nowner_email:\n- ''\n- foo1@example.com\norg_id:\n- \n- 642273\nassigned_to_id:\n- \n- 543076\nassigned_to_type:\n- \n- User\nid:\n- \n- 44074\n",
  whodunnit_type: nil,
  comments: nil,
  transaction_id: 24322>,
 #<PaperTrail::Version:0x0000000006b1a430
  id: 24329,
  item_type: "RiskAction",
  item_id: 44074,
  event: "create",
  whodunnit: "543076",
  object: nil,
  created_at: Mon, 15 Aug 2022 16:14:45 UTC +00:00,
  object_changes:
   "---\nname:\n- \n- action 1\nuser_id:\n- \n- 543076\naction_status_id:\n- \n- 66607\ndue_date:\n- \n- '2018-02-10 00:00:00'\nowner_email:\n- ''\n- foo1@example.com\norg_id:\n- \n- 642273\nassigned_to_id:\n- \n- 543076\nassigned_to_type:\n- \n- User\nid:\n- \n- 44074\n",
  whodunnit_type: nil,
  comments: nil,
  transaction_id: 24322>]

This behaviour starts occurring with the papertrail gem version 6 on rails 4.2.10.  The behaviour continues into rails 5.2.8 and papertrail gem versions 9 thru 11, the latter of which is where I'm trying to end up.
I am not sure why the behaviour begins here, there is nothing in the changelog (at least, that's obvious to me) why this would be the case.  Any help is appreciated -- thank you.


text:
Q: ASP WebSite - how to get build time errors Having recently started doing more web development I've come across both:

*

*Web Applications

*Web Sites

From my understanding a Web application all gets compiled into the binaries and run. While a Web site essentially lazy compiles pages upon requests. Working with websites seems a lot nicer especially when dealing with a massive project (in my case Kentico CMS) because you don't need to worry about long build times and IIS recycles.
However what I don't understand is how you effectively protect against errors early on? It feels like the mode has switched from build errors, to runtime errors. So if I refactor a method signature by adding a new parameter for example how do I effectively ensure that I've not broken any calls (without using a Find all references / using external tooling)?

A: You will want to look at test driven development if you are wanting to be sure that you are keeping errors out of your project.
If you do a web application yes it gets compiled and that is actually a bit faster even though load times can be longer. A web site is compiled as called and can be a bit slower. There is no reason you can't combine the two like I do.
Usually I do the presentation layer as a web site and then all the logic and data is all contained in dlls - gives a sort of the best of both worlds effect.  I can make small tweaks to my display pages without having to recompile (or if i have two users of the same application they can have totally different layouts) but the data layer and logic are all encapsulated and safe. Those pieces can be tested away from the site and if you really get ambitious then you could work in Continuous Integration to automatically deploy builds if they pass all the tests.
Lots of options.


text:
Q: wpf eventtrigger usercontrol inside stackpanel I have a stackpanel containing usercontrols with eventtriggers. These eventtriggers is used to select a usercontrol, which works just fine.
Now i want to make it possible to deselect selected usercontrol by clicking in the stackpanel outside a usercontrol. This is here my problem occur.
I have tried to add an eventtrigger to the stackpanel, but it wont work when clicking in the stackpanel only when clicking on one of the usercontrols inside the stackpanel and furthermore then overrule the usercontrol own eventtrigger.
<StackPanel Name="DisplayArea">
                <ItemsControl ItemsSource="{Binding Nodes}" />
                <ItemsControl ItemsSource="{Binding Edges}" />
                <StackPanel.Triggers>
                    <EventTrigger RoutedEvent="StackPanel.Loaded">
                    </EventTrigger>
                </StackPanel.Triggers>
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="MouseDown">
                        <cmd:EventToCommand Command="{Binding DataContext.MouseDownPanelCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" PassEventArgsToCommand="True"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </StackPanel>

I understand that this isn't the right way to do it, but i can't figure out how to.
Hope you guys understand my problem.


text:
Q: Returning an ActiveRecord Object from two different Tables I am trying to return an ActiveRecord object consisting of two different objects from two different tables.  They have the following relations:
class User < ApplicationRecord
  has_many :posts, dependent: :destroy
  has_many :pictures, dependent: :destroy

  # Ideally user.timeline returns all of a user's posts and pictures as an active record relation.

  def timeline
      Post.where("(user_id = :user_id)", user_id: id)
      Picture.where("(user_id = :user_id)", user_id: id)
  end
end

class Post < ApplicationRecord
  belongs_to :user
end

class Picture < ApplicationRecord
  belongs_to :user
end

I would like to be able to call user.timeline and have all of a user's posts and pictures returned together as one active record relation.
I have tried:
    Post.where("(user_id = :user_id)", user_id: id) + Picture.where("(user_id = :user_id)", user_id: id).  This returns all the objects I want, but as an array, not an active record relation.
Is there any way this can be done?

A: In this case, you should use another table to handle the timeline.
Timeline
user_id:integer
post_id:integer
picture_id:integer

Each time user send a pic or post, it should also create a record in timeline which indicates the post_id or picture_id or whatever you want.
I prefer not using foreign key due to the performance issue as this is a timeline model.
Then you might be able to do query like this.
class User < ApplicationRecord
  def timeline
    Timeline.where(user_id: id)
  end
end

You can use timeline model to serialize the model for each record.


text:
Q: Remove the blank column in a WPF DataGrid I use a DataSet to populate a DataGrid in WPF (C#). The result is:

I want to remove blank column at left side. And I want to share remaing space to columns. Expected result is:

My XAML code is:
<Window x:Class="RFID.CareerWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="CareerWindow" Height="356" Width="404">
    <Grid>

        <DataGrid x:Name="dg1" HorizontalAlignment="Left" Margin="25,10,0,0" VerticalAlignment="Top" Height="306" Width="355" EnableRowVirtualization="false" EnableColumnVirtualization="false" FontFamily="2  badr" FontSize="20" FlowDirection="RightToLeft" CanUserAddRows="False" CanUserReorderColumns="False"/>

    </Grid>
</Window>

A: Avoid setting static Height and Width.
Use ColumnWidth="*" to share the space between your DataGridColumns
<DataGrid x:Name="dg1" ColumnWidth="*"
          HorizontalAlignment="Left" VerticalAlignment="Top" Margin="25,10,0,0"
          EnableRowVirtualization="false" EnableColumnVirtualization="false"
          FontFamily="2  badr" FontSize="20" FlowDirection="RightToLeft"
          CanUserAddRows="False" CanUserReorderColumns="False" />

A: You can set the last column or one column of your Grid with
<DataGridTextColumn Header="Surname"
                    Width="*"
                    Binding="{Binding Path=Surname,Mode=TwoWay}" IsReadOnly="True">
  <DataGridTextColumn.ElementStyle>
    <Style TargetType="TextBlock">
      <Setter Property="HorizontalAlignment" Value="Left" />
      <Setter Property="VerticalAlignment" Value="Center" />
    </Style>
  </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

A: To eliminate an automatic added column, set Width of a DataGridTextColumn to *
The following Code represents a DataGrid with two columns and no automatic added colums
<DataGrid AutoGenerateColumns="False" HeadersVisibility="Column">
 <DataGrid.Columns>
  <DataGridTextColumn Width="*" Binding="{Binding asdf}" />
  <DataGridTextColumn Width="*" Binding="{Binding zuio}" />
 </DataGrid.Columns>
</DataGrid>


text:
Q: afxwin.h issues in Visual Studio 2015 Windows Form App A while ago i wrote a C++ CLI Windows Form app, which compiled fine in Visual Studio 2013. Now i wanted to recompile it in Visual Studio 2015 Update 1 but i'm facing a problem, and after hours of tests i figured out the culprit is afxwin.h.

TL;DR - Is there any way i can use stdafx.h (so afxwin.h and all other imports coming with it) in a Windows Form app compiled with Visual Studio 2015 without having the app crash upon start?

Here's how to reproduce the same issues i'm facing in my app.
Since Windows Form is no longer available as project template in VS2015, i created a CLR Empty Project called Test
Ctrl-Shift-A to add a UI > Windows Form called MyForm
In MyForm.cpp i added this:
#include "MyForm.h"

using namespace System;
using namespace System::Windows::Forms;

[STAThread]
int main(cli::array<System::String^>^ args)
{
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    Test::MyForm form;
    Application::Run(%form);
}

Under Configuration Properties > Linker > Advanced i set Entry Point to main
Under Configuration Properties > Linker > System i set SubSystem to Windows (/SUBSYSTEM/WINDOWS)
COMPILE (DEBUG CONFIGURATION): compiles with no errors/warnings
RUN: runs without any problem.
Now lets try adding afxwin.h to MyForm.cpp:
#include <afxwin.h>

Under Configuration Properties > General i set Use of MFC to Use MFC in a shared DLL
COMPILE (DEBUG CONFIGURATION): compiles with no errors/warnings
RUN: the app wont even start, it just shows Debug Assertion Failed error in expression _CrtIsValidHeapPointer(block)

Now to fix this error i found that it's necessary to remove the Entry Point, so:
Under Configuration Properties > Linker > Advanced i removed Entry Point value (which i previously set to main)
COMPILE (DEBUG CONFIGURATION): compiles with no errors/warnings
RUN: the app again wont even start, it no longer shows Debug Assertion Failed but System.AccessViolationException in an unknown module and "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

These are the errors i get in my app, and i'm wondering how is it possible that simply including afxwin.h gives all these problems in VS2015 while it didnt in VS2013.
Is there anything i can do to fix it, without going back to VS2013?

A: The C runtime library was significantly rewritten for VS2015 by James McNellis.  He's a big C++ fan, the new code he's written suffers from the chronic SIOF problem that's so common in a C++ program.  The Static Initialization Order Fiasco was surely present in your VS2013 project as well but happened not to byte, the original CRT code was exposed to SIOF for many years so likely to behave better.
Excessively hard to debug in this case, the code that fails comes from a CRT source code file that is not included in the install named thread_safe_statics.cpp.  Not 100% sure what it does given that there's no source code to look at but the name of the file leaves little to the imagination.
MFC has static state that needs to be initialized before it is usable.  In particular, the program must have a static CWinApp variable that is initialized at Just the Right Time.  That requires the entrypoint to be WinMain(), implemented in MFC, and an explicit declaration of a CWinApp instance in your source code.  Like this:
[STAThread]
int main(cli::array<System::String^>^ args)
{
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    Application::Run(gcnew Test::MyForm);
}

class MyMfcApp : public CWinApp {
public:
    virtual int Run() override {
        return main(__nullptr);
    }
} MyApp;

Reset the linker's EntryPoint setting back to its default (blank) so the CRT is initialized first and MFC's WinMain function runs next.  And beware I took a shortcut, you get no args.  And I fixed a bug in your main() function, it used stack semantics incorrectly.
This hack gets your program running again.  Whether it is actually correct is rather doubtful.  This suffers from the "Who is the Boss" syndrome that's associated with big frameworks.  Don't depend on any MFC window to work correctly since it is Winforms that is dispatching messages.  But you should have had that problem in VS2013 as well.  "Don't do it" is the only solid advice.


text:
Q: Nebular responsive layout I'm having trouble leaving my responsive layout with nebular, it would be the first time I'm using ...
Settings is default using bootstrap and Angular,
body of the layout would be:

<nb-layout>

  <nb-layout-header>

responsive nav left side a logo with welcome writing right side a logo.

"I managed to make the less responsive"
  </nb-layout-header>

  <nb-layout-column>
  here would be all the rest of the layout,
Big problem would be here I am not able to make the correct divisions like row and col,
It's not getting responsive.
  </nb-layout-column>

</nb-layout>

here is my code:

.clienteLogo {
  margin-left: 1%;
}
.testeLogo {
  margin-left: auto;
  margin-right: 1%;
}

.boasVindas {
  padding-left: 20px;
}
<nb-layout>

  <nb-layout-header>

    Olá Cliente, seja bem vinda.

  </nb-layout-header>

  <nb-layout-column>

  </nb-layout-column>

</nb-layout>

I tried to put card inside the column but also could not:
same line
1 picture | 2 picture | 3 picture | 4 picture
responsive
themes is default

A: What I understand from the last line is that you are trying to display all pictures in one row. I am not sure if bootstrap library is loaded or not but the following will display it all in one row:
.row {
  display: flex;
  flex-direction: column:
}

NbLayoutColumnComponent

A container component which determines a content position inside of
  the layout. The layout could contain unlimited columns (not including
  the sidebars).

From the above description, it means it won't have any affect on the style of your
 but the position.
Regarding the NbCard, the card has header, body and footer with white background and bordered shadow same like bootstrap cards and it does not impact the style of your div elements.

*

*Make sure the bootstrap library is loaded

*Inspect the
 and see if the bootstrap styles are applied or is there any other styles override it.

For responsiveness: use bootstrap columns.
https://akveo.github.io/nebular/docs/components/layout/overview#nblayoutcomponent


text:
Q: How can I tell if a rectangular matrix has duplicate rows in MATLAB? I have an n-by-m rectangular matrix (n != m). What's the best way to find out if there are any duplicate rows in it in MATLAB? What's the best way to find the indices of the duplicates?

A: You can use the functions UNIQUE and SETDIFF to accomplish this:
>> mat = [1 2 3; 4 5 6; 7 8 9; 7 8 9; 1 2 3];    %# Sample matrix
>> [newmat,index] = unique(mat,'rows','first');  %# Finds indices of unique rows
>> repeatedIndex = setdiff(1:size(mat,1),index)  %# Finds indices of repeats

repeatedIndex =

     4     5

A: Use unique() to find the distinct row values. If you end up with fewer rows, there are duplicates. It'll also give you indexes of one location of each of the distinct values. All the other row indexes are your duplicates.
x = [
    1 1
    2 2
    3 3
    4 4
    2 2
    3 3
    3 3
    ];
[u,I,J] = unique(x, 'rows', 'first')
hasDuplicates = size(u,1) < size(x,1)
ixDupRows = setdiff(1:size(x,1), I)
dupRowValues = x(ixDupRows,:)

A: Run through the rows of the matrix, and for each pair, test if
row1 == row2

A: Say your matrix is M:
[S,idx1] = sortrows(M);
idx2 = find(all(diff(S,1) == 0,2));
out = unique(idx1([idx2;idx2+1]));

out will contain the duplicate row indices if any.


text:
Q: Spring Boot - There was an unexpected error (type=Internal Server Error, status=500) After surfing to localhost:8080 i start getting this error on the console with an internal error that goes like this on the webpage : 'There was an unexpected error (type=Internal Server Error, status=500).'
java.lang.NullPointerException: null
at com.test.Service.StudentService.getAllStudents(StudentService.java:15) ~[classes/:na]
at com.test.Controller.StudentController.getAllStudents(StudentController.java:22) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_191]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_191]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.34.jar:8.5.34]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]

Here is the service file :
package com.test.Service;

import com.test.Dao.StudentsDao;
import com.test.Entity.Student;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class StudentService {

    private StudentsDao studentDao;
    public Collection<Student> getAllStudents()
    {
        return studentDao.getAllStudents();
    }
}

The controller file :
package com.test.Controller;

import com.test.Entity.Student;
import com.test.Service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentservice;

    @RequestMapping(method = RequestMethod.GET)
    public Collection<Student> getAllStudents()
    {
        return studentservice.getAllStudents();
    }
}

And finally the DAO file :
package com.test.Dao;

import com.test.Entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Repository
public class StudentsDao {

    @Autowired
    public static Map<Integer, Student> students;
    static{
        students = new HashMap<Integer, Student>(){
            {
                put(1, new Student(1, "Chadi", "Informatique"));
            }
        };
    }
    public Collection<Student> getAllStudents()
    {
        return this.students.values();
    }
}

What's causing this error . And how can i fix it ?

A: at com.test.Service.StudentService.getAllStudents(StudentService.java:15) ~[classes/:na] says it all. Check the line 15 from StudentService ... there you have a null :)
Your DAO is null .. you forgot the @Autowired on the dao field

A: You are using a class that is annotated with @repository in your service class. So the spring framework already knows that the DAO class is bean. But instead of using the bean, you're defining an object of class without initializing the value for it. So, you will got a null pointer exception.


text:
Q: Mapping one to many from dataframe with another dataframe using pandas I have 2 pandas datafarmes, trying to map and create a one to many mapped dataset like below. i am able to achieve it using below code which is taking long time on bigger datasets. any other ways to achieve it?
df1:
    id      f_name  m_name     last_name
0   DS2-1   Calvin  Ray        Calvin
1   DS2-2   x       Alexander  Dan

df2:
    id      f_name  m_name    l_name
0   DS2-1   Calvin  Ray       Calvin
1   DS2-2   x       Alexander Dan
2   DS2-3   y       Floyd     Floyd
3   DS2-4   z       Ed        Ray
4   DS2-5   Dan     Ray       Floyd

i am looking for the output like below.
    id-1  f_name-1  m_name-1   l_name-1 id-2    f_name-2 m_name-2  l_name-2
0   DS1-1 Calvin    Ray        Calvin   DS2-1   Calvin   Ray       Calvin
1   DS1-1 Calvin    Ray        Calvin   DS2-2   x        Alexander Dan
2   DS1-1 Calvin    Ray        Calvin   DS2-3   y        Floyd     Floyd
3   DS1-1 Calvin    Ray        Calvin   DS2-4   z        Ed        Ray
4   DS1-1 Calvin    Ray        Calvin   DS2-5   Dan      Ray       Floyd
5   DS1-2 Willie    Alexander  Matthew  DS2-1   Calvin   Ray       Calvin
6   DS1-2 Willie    Alexander  Matthew  DS2-2   x        Alexander Dan
7   DS1-2 Willie    Alexander  Matthew  DS2-3   y        Floyd     Floyd
8   DS1-2 Willie    Alexander  Matthew  DS2-4   z        Ed        Ray
9   DS1-2 Willie    Alexander  Matthew  DS2-5   Dan      Ray       Floyd

any simple ways to achieve this, with using loop , len(df) and iloc taking longer time.
final_df=pd.DataFrame()
for i in range(len(df1)):
    for j in range(len(df2)):
        data=[[df1.iloc[i,0],df1.iloc[i,1],df1.iloc[i,2],df1.iloc[i,3],df2.iloc[j,0],df2.iloc[j,1],df2.iloc[j,2],df2.iloc[j,3]]]
        df = pd.DataFrame(data, columns = ['id-1','f_name-1','m_name-1','l_name-1','id-2','f_name-2','m_name-2','l_name-2'])
        final_df=final_df.append(df)

suggestions are really appreciated. Thanks in advance..


text:
Q: Best way to activate an unsaved workbook I have various code to create reports. The reports are added to a new workbook that does not get saved, the theory being that the user can choose whether to save the workbook or just close it after looking at the results. My code below will activate the unsaved workbook.
Sub ActivateWorkbook(wbResults As Workbook)
    Dim objWindow As Window

    With Application

        .VBE.MainWindow.WindowState = vbext_ws_Minimize

        For Each objWindow In .Windows

            With objWindow

                If .Caption <> wbResults.Name Then .WindowState = xlMinimized

            End With

        Next objWindow

        With .Windows(wbResults.Name)

            .WindowState = xlMaximized

            .Activate

        End With

    End With

End Sub

This works okay with a single monitor. But if there is already more than one workbook and they are different monitors, it minimises windows in both (all) monitors and looks less than ideal. I am thinking that if I am able to identify which monitor has the active workbook, I could only minimize windows for that monitor (including the VBE, if required).
In reply to chris neilsen, I will include some basic code to illustrate what I'm calling the above procedure with. Please keep in mind that each procedure is varied in purpose and most of the code in each doesn't really pertain to this particular problem.
Sub ExampleCode()
    Dim wbXXX As Workbook

    Set wbXXX = Workbooks.Add

    With wbXXX

        'Main code here

    End With

    Call ActivateWorkbook(wbXXX)

    Set wbXXX = Nothing

End Sub

Thanks to anybody trying to help. It is appreciated.

A: Okay, this seems to be working for me. It's not pretty. Note that "Microsoft Visual Basic for Applications Extensibility 5.3" is required to minimise the VBE, which is where the code is being run from, not the main Excel application. In any case, Activate has not worked for me reliably in the past. If it works for you, no need for any of this I guess. If anybody is game to test it, please let me know how you go. I have only tested on a dual monitor setup so far.
Objective: Show the new workbook in the same monitor as the active workbook when Activate does not work.
Private Declare PtrSafe Function FindWindow _
    Lib "user32" Alias "FindWindowA" _
    (ByVal lpClassName As String, _
    ByVal lpWindowName As String) _
    As LongPtr

Private Declare PtrSafe Function MonitorFromWindow _
    Lib "user32" _
    (ByVal hwnd As LongPtr, _
    ByVal dwFlags As Long) _
    As LongPtr

Private Declare PtrSafe Function EnumDisplayMonitors _
    Lib "user32.dll" _
    (ByVal hdc As Long, _
    ByRef lprcClip As Any, _
    ByVal lpfnEnum As Long, _
    ByVal dwData As Long) _
    As Long

Private Declare PtrSafe Function GetSystemMetrics _
    Lib "user32" _
    (ByVal Index As Long) _
    As Long

Private Type RECT
    Left As Long
    Top As Long
    Right As Long
    Bottom As Long
End Type

Private Const MONITOR_DEFAULTTONEAREST = &H2
Private Const SM_CMONITORS As Long = 80

Private hWndMonitor As LongPtr
Private hActiveWorkbook As LongPtr
Private hVBE As LongPtr
Private lngMode As Long

Function MonitorCount() As Long

    MonitorCount = GetSystemMetrics(SM_CMONITORS)

End Function

Function MonitorsAreTheSame() As Boolean

    MonitorsAreTheSame = True

    'Count of monitors
    If MonitorCount > 1 Then

        'Check the ActiveWorkbook
        lngMode = 0

        hWndMonitor = FindWindow("XLMAIN", Application.Caption)

        EnumDisplayMonitors ByVal 0&, ByVal 0&, AddressOf MonitorEnumProc, ByVal 0&

        'Check the VBE
        lngMode = 1

        hWndMonitor = FindWindow("wndclass_desked_gsk", Application.VBE.MainWindow.Caption)

        EnumDisplayMonitors ByVal 0&, ByVal 0&, AddressOf MonitorEnumProc, ByVal 0&

        MonitorsAreTheSame = CBool(hActiveWorkbook = hVBE)

    End If

End Function

Private Function MonitorEnumProc(ByVal hMonitor As Long, ByVal hdcMonitor As Long, lprcMonitor As RECT, ByVal dwData As Long) As Long

    If MonitorFromWindow(hWndMonitor, MONITOR_DEFAULTTONEAREST) = hMonitor Then

        Select Case lngMode

            Case 0

                hActiveWorkbook = CStr(hMonitor)

            Case 1

                hVBE = CStr(hMonitor)

        End Select

    End If

    MonitorEnumProc = MonitorCount

End Function

Sub Test()
    Dim wbkTest As Workbook

    Set wbkTest = Workbooks.Add

    Call ActivateWorkbook(wbkTest)

    Set wbkTest = Nothing

End Sub

Sub ActivateWorkbook(wbkResults As Workbook)
    Dim objWindow As Window

    With Application

         If MonitorsAreTheSame = True Then

            .VBE.MainWindow.WindowState = vbext_ws_Minimize

            For Each objWindow In .Windows

                With objWindow

                    If .Left = Application.VBE.MainWindow.Left Then

                        If .Caption <> wbkResults.Name Then .WindowState = xlMinimized

                    End If

                End With

            Next objWindow

        Else

            For Each objWindow In .Windows

                With objWindow

                    If .Left <> Application.VBE.MainWindow.Left Then

                        If .Caption <> wbkResults.Name Then .WindowState = xlMinimized

                    End If

                End With

            Next objWindow

        End If

        .Windows(wbkResults.Name).WindowState = xlMaximized

        AppActivate (.Caption)

    End With

End Sub

A: this should be sufficient - no second sub for activation needed. These should show the new workbook in the foreground, no other windows changed.
Sub ExampleCode()
    Dim wbXXX As Workbook

    Set wbXXX = Workbooks.Add

    With wbXXX

        'Main code here

    End With

    wbXXX.Activate

    Set wbXXX = Nothing

End Sub


text:
Q: How to integrate Instagram Direct feature in our iOS APP? Can we integrate Instagram Direct feature in our iOS application? Is there any API available?

A: You can use below code: (Note: This will open instagram app if installed on device and pass image with text from your app in instagram app).
// In .h
@property (strong,nonatomic) UIDocumentInteractionController *docController;

// in .m
// Share on instagram ************
- (void)shareToInstagram
{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:
                      @"image.ig" ];
    NSData* data = UIImagePNGRepresentation(yourImageView.image);
    [data writeToFile:path atomically:YES];

    NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:
                           @"image.ig" ];

    CGRect rect = CGRectMake(0 ,0 , 0, 0);
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIGraphicsEndImageContext();

    self.docController.UTI = @"com.instagram.photo";
    self.docController = [self setupControllerWithURL:[NSURL fileURLWithPath:imagePath] usingDelegate:self];
    self.docController=[UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:imagePath]];
    NSString * msgBody = [NSString stringWithFormat:@"Your message"];
    self.docController.annotation = [NSDictionary dictionaryWithObject:msgBody forKey:@"InstagramCaption"];
    [self.docController presentOpenInMenuFromRect: rect inView: self.view animated: YES ];

}

- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
    UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
    interactionController.delegate = interactionDelegate;
    return interactionController;
}

- (void)documentInteractionControllerWillPresentOpenInMenu:(UIDocumentInteractionController *)controller {

}
// *********** ********* ***********


text:
Q: GWT - Global clickHandler to work on HTML class attribute elements? I have a button which I add an HTML class and the java class clickHandler to:
Button someButton = new Button();
someButton.getElement().setClassName("someClass");
someButton.addClickHandler(this);

Then my java class clickHandler looks like:
public void onClick(ClickEvent event){
    Widget sender = (Widget) event.getSource();
    if(sender == someOtherWidget){
        ...
    }else if(...){
    ...
}

What I would like to do is add something to the clickHandler which will make it do something if the sender widger has  the someClass HTML class. Something like:
else if(sender.getClassName().equals("someClass")){
    doSomething();
}

However, the widget doesn't have getClassName(). Anyone have a suggestion about how to get the HTML class applied on the widget? Thank you much!

A: Figured out what I was doing wrong. This:
else if(sender.getClassName().equals("someClass")){
    doSomething();
}

Should be this:
else if(sender.getElement().getClassName().equals("someClass")){
    doSomething();
}


text:
Q: General query regarding web application architecture, especially front end Our application (initially accessible via web, later via mobile app and/or desktop apps) has an application server, which serves and internal API that'll be driven by all end points (React for web, iOS/Android for mobile in the future. etc). This application server will be accessible to those endpoints at app.<mydomain>.com - Currently this is implemented via a Django-REST-framework powered backend hosted on heroku.
We also have a landing page which will be served by www.<mydomain>.com.
My question is really about the server serving the landing page. Obviously it will be serving static content only, the landing page content, and the static react application JS that'll engage app.<mydomain>.com when it has to make requests and get data.
Obviously in this case I do not need a scripting engine on the backend. What do you recommend I use to serve up the landing page content and the static react app code? Simply apache server? anything else? Our app is U.S. only at this point, does it make sense to deploy via CloudFront or any other CDN?
I'd appreciate any advice.

A: Static content is best served by a fast http server. My personal preference is nginx because of its simple config and great performance but apache will do as well.
It is as simple as uploading your htmls to the server. That being said, there are several things to keep in mind. Spend some time configuring cache headers for different file types. Automate the deployment process e.g. have Ansible deploy your web content after you push to repo, or turn it imto a docker container.  This should be more then enough to handle many thousands of requests a day. If your scale is bigger, then CDN is a valid point of improvement along with scaling of your web servers and further improvements to caching and compression.
Bonus point: your ngnix can also act as a very effective reverse proxy fronting your rest backend. You can easily setup load balancing and ssl - so that your rest can focus on just speedy business operation.
Happy hacking.


text:
Q: python request with proxy I want to use a proxy with python requests library
import requests

proxy_req = {'http':'177.53.57.154:48926'}

url = 'https://www.companyweb.be/en'
ua = UserAgent()
headers = {'User-Agent':ua.random}

r = requests.get(url = url, headers = headers,proxies=proxy_req)

soup = bs.BeautifulSoup(r.text, 'html.parser')

I'm getting a response, but the query seems to ignore the proxy (because it's too fast)
I tried this to get the ip and check if it was the proxy ip address:
r = requests.get(url = url, headers = headers,proxies=proxy_req, stream = True)
print(r.raw._fp.fp.raw._sock.getpeername())

But I get this error :
AttributeError: 'WrappedSocket' object has no attribute 'getpeername'

What's wrong ?


text:
Q: Time Complexity of a Binary Search Tree Insert method Good day!
I have a question regarding the time complexity of a binary search tree insertion method. I read some of the answers regarding this but some were different from each other. Is the time complexity for a binary search tree insertion method O(log n) at average case and O(n) at worst case? Or is it O(n log n) for the average case and O(n^2) for the worst case? When does it become O(n log n) at average case and O(n^2) at worst case?

A: In avg case, is O(log n) for 1 insert operation since it consists of a test (constant time) and a recursive call (with half of the total number of nodes in the tree to visit), making the problem smaller in constant time. Thus for n insert operations, avg case is O(nlogn). The key is that the operation requieres time proportional to the height of the tree. In average, 1 insert operation is O(logn) but in the worst case the height is O(n)
If you're doing n operations, then avg is O(nlgn) and worst O(n^2)


text:
Q: Javascript - : Slider On touch not working as expected I am making a custom slider.
All the things works find. But as of now I also want to add ontouch, ontouchmove functionality. I have almost achieve but something is still wrong that's why I am not able to achieve it completely.
Code Snippet
function onDragAction (e) {
    e = e || window.event;

    if (e.type == 'touchmove') {
      caouselPosX2 = caouselPosX1 - e.touches[0].clientX;
      caouselPosX1 = e.touches[0].clientX;
    } else {
      caouselPosX2 = caouselPosX1 - e.clientX;
      caouselPosX1 = e.clientX;
    }
            carouselInneritems.style.transform = 'translateX(' + (carouselInneritems.offsetLeft - caouselPosX2) + 'px)';
}

Kindly try the demo on inspect with mobile resolution.
CodePen

A: I've had a play around with this and there are two main issues as far as I can see.

*

*onDragAction() needs to call e.stopPropagation() - in the demo you posted it is being called every time a new slide enters underneath the mouse, but you only want it to be called once. This fixes a lot of the glitchiness for me.

*You need to have some conditional logic to express what direction you want the slider to go in. At the moment it is calculated by subtraction in every case, which from what I've put together from reading your code means it will always go to the left.


text:
Q: How to add a single file to an existing snapshot timestamp version in Sonatype Nexus I am working on a CI/CD pipeline for Jenkins, which is used by various projects. All projects use Maven and deploy their snapshot and release versions to a given Artifact Repository.
In the pipeline I also create a file and deploy it via mvn deploy:deploy-file with the same snapshot version, e.g. 1.2.3-SNAPSHOT, to the used repository. Hence the actual deployment of the project was done before, a new timestamped snapshot version is created.
In the used repository, it looks like this:
─┬─ my-artifact
 │  ├─ 1.2.3-SNAPSHOT
 │  ├─ 1.2.3-SNAPSHOT-20201215.123453-1
 │  │  └ ...
 │  ├─ 1.2.3-SNAPSHOT-20201215.123463-2
 │  │  ├─ my-artifact-1.2.3-SNAPSHOT-20201215.123463-2.jar
 │  │  ├─ my-artifact-1.2.3-SNAPSHOT-20201215.123463-2.jar.md5
 │  │  ├─ my-artifact-1.2.3-SNAPSHOT-20201215.123463-2.jar.sha1
 │  │  ├─ my-artifact-1.2.3-SNAPSHOT-20201215.123463-2.pom
 │  │  ├─ my-artifact-1.2.3-SNAPSHOT-20201215.123463-2.pom.md5
 │  │  └─ my-artifact-1.2.3-SNAPSHOT-20201215.123463-2.pom.sha1
 │  └── 1.2.3-SNAPSHOT-20201215.123473-3
 │      ├─ my-artifact-1.2.3-SNAPSHOT-20201215.123473-3-cyclonedx.xml
 │      ├─ my-artifact-1.2.3-SNAPSHOT-20201215.123473-3-cyclonedx.xml.md5
 │      └─ my-artifact-1.2.3-SNAPSHOT-20201215.123473-3-cyclonedx.xml.sha1

As you can see, the snapshot version 1.2.3-SNAPSHOT-20201215.123473-3, uploaded by my pipeline code, has a totally different content then the previous version. Any Maven project requesting the latest snapshot version will fail to find the jar file, as the latest snapshot contains only the XML document.
Is there a way to deploy, or better to say, to attach an artifact to an existing timestamped snapshot version? I am afraid not, but I would like to validate my thoughts before choosing a totally different approah.
Within the pipeline I can do everything, execept modifying the POM of Maven project. Changing the Maven project is not possible, because there are many of them an the features I have to implement come from different stakeholders.

A: khmarbaise is right.
You need to change the POM.
If the file should be part of the SNAPSHOT, it must be part of the Maven build.
If it has nothing to do with the build, you might better place it somewhere else.


text:
Q: Counting on minesweeper Given a minesweeper configuration. How many way are there to fill it to make the configuration correct.
Is there any better solution than brute-force method ?
Example:
Given configuration:
1_11_2__b (b = bomb, _ = blank)
one way to fill it is:
1b11b2b2b

A: Standard 2D minesweeper has been shown to be NP complete-that finding if there is a way to solve a given partially filled in board is hard.  I would guess that 1D is not, there isn't enough room to make the required structures.  In any case, you probably want one pass that fills in all the squares that have to be one kind or the other-for example your first blank.  That would solve all the squares except the last, which can be b or 2.  Then start a backtracking algorithm-try one and see if it works, then the other.  You may well have to split into subcases.  Dynamic programming makes structuring this easier.


text:
Q: How to bring back old style window docking in Eclipse Juno? I recently started using Eclipse Juno (4.2) on Fedora Linux.  In prior versions of eclipse I could simply click and drag a source file name to the edge of the screen and split my window with the mouse.  Now when I click+drag Eclipse brings up some green outlines and I can't figure out how to accept the change without hitting Enter on the keyboard.  Does anyone know if its possible to bring back the prior behavior where the mouse can do everything?
Thanks!
Edit: Sounds like there may be a bug in Eclipse, at least when using Fedora 17 64-bit.

A: Now you have a green rectangle that represent the area that will be occupied when you release the mouse button, however the procedure still the same you have to drag the editor and drop the editor in the desired area ...
Just move the mouse with the left button clicked and you will notice that the green rectangles change and when you have a rectangle with double borders you can release the mouse button ...


text:
Q: Any advantage to storing latitude / longitude as integers? Lately I've noticed some of the resources (sample applications, blogs, and websites) I use for GPS / GIS stuff store the latitude and longitude as integers rather than decimal or string. I understand why a formatted string is not the preferred way to store lat / lon. But why not store the value as a decimal? Is there any advantage to storing as an integer and later dividing by 1,000,000 to get the actual decimal value?

A: Possibly.  An integer requires only four bytes of storage.  An IEEE double precision floating point number is 8 bytes.  So storing a lat / lon as an integer would halve the memory requirement.


text:
Q: Oracle : How to have only one row active in a table? I have an Oracle table with a field Named Active.
This field has a unique constraint, so only one row will be marked as Active.
Is there any way in the database layer to keep only one row active when adding a new row or updating old ones ?
Example
Current State of Table
ID        Active
----------------
1         yes

A new active row is added :
New State of the table
ID        Active
----------------
1         No
2         Yes

The row 1 is updated with Active = Yes
ID        Active
----------------
1         Yes
2         No

Of course I can not update the table using a trigger when a new row is beign inserted.
Does anyone have an idea on how to do that please ?

A: You need to call this procedure with valid values as input parameter
CREATE OR REPLACE PROCEDURE t416493.set_tab
    (
     p_id IN tab.id%TYPE
    ,p_active_flag IN tab.active%TYPE
    ,p_dml_type    IN VARCHAR2
    )

    IS

    CURSOR check_flag_exists
    IS
    SELECT id
    FROM tab
    WHERE active = p_active_flag;

    v_id tab.id%TYPE;
    v_active_flag VARCHAR2(3);

    BEGIN

        OPEN check_flag_exists;
          FETCH check_flag_exists INTO v_id;
            IF check_flag_exists%FOUND THEN

              IF  p_active_flag ='Yes' THEN
                  v_active_flag :='No';
              ELSE
                 v_active_flag :='Yes';
              END IF;

                UPDATE tab
                 SET  active = v_active_flag
                WHERE id =v_id;

            END IF;
         CLOSE check_flag_exists;

         IF p_dml_type ='INSERT' THEN
          INSERT INTO tab
           (id
           ,active
           )
           VALUES
           (p_id
           ,p_active_flag
           );
         ELSIF p_dml_type ='UPDATE' THEN
           UPDATE tab
           SET active =p_active_flag
           WHERE id =v_id;
         END IF;

    END set_tab;

You need to call your proc like this as shown below:
begin
 set_tab
       (
         p_id =>2
        ,p_active_flag =>'Yes'
        ,p_dml_type   =>'INSERT'
        );

end;
/


text:
Q: paged > max_num_pages won't throw 404 I've created new page in WP administration called Blog and created custom page template for it. In the template, I have a simple paged custom query.
$query = new WP_Query(array( 'post_type' => 'post', 'posts_per_page' => 1,
'paged' => $paged ));

Everything seems to look ok, except when I manually type bigger page number than is available after the '/page/' part of url. The page won't throw a 404 error but will render the page as normal without the custom loop. Is it normal behaviour?
If so, how should I throw the 404 template page?
Also, I have one sub question:
Is it possible, to create custom theme page, without the need to create the page in the wordpress adminstration? In most cases I don't even use the content of the page and leave it empty. Then if someone will delete the page, or change the page slug, part of website can be broken.
Is there more fool proof and more administrator friendly solution?
PS: here is the full page-blog.php source code:

<?=get_theme_mod('crochelou-blog-main-headline') ?><?=get_theme_mod('crochelou-blog-sub-headline') ?>

        <?php
            wp_nav_menu( array(
                'menu_id'        => 'category-menu',
                'menu' => 'category-menu'
            ) );
        ?>
            <?php

            $query = new WP_Query(array( 'post_type' => 'post', 'posts_per_page' => 1, 'paged' => $paged )); ?>

<?php
                if($paged > 1){ ?>
                    <a href="<?= get_pagenum_link($paged - 1) ?>" class="pagination-arrow arrow left arrow-left prev">
                <?php }

                ?>

                    <?php
                    while($query->have_posts()): $query->the_post(); ?>

                        <div class="blog image" style="background-image: url('<?=esc_url(the_post_thumbnail_url('medium'))  ?>')">

<?php
                            $categories = get_the_category();
                             foreach($categories as $category){
                                 $name = $category->name;
                                 $link = get_category_link($category->term_id); ?>
                                 <a href="<?= $link ?>" class="catgory"><?= $name ?>
                            <?php
                             }
                        ?>

                        <?= get_the_date('d') . '\\' . get_the_date('m') . '\\' . get_the_date('Y') ?>

<a href="<?= get_the_permalink() ?>"><?= get_the_title() ?>

<?php the_excerpt(); ?>

                        <a class="link read-more" href="<?= get_the_permalink() ?>" >číst..

                    <?php endwhile;
                    ?>

<?php
                if($paged < $query->max_num_pages){ ?>
                    <a href="<?= get_pagenum_link($paged + 1) ?>" class="pagination-arrow arrow right arrow-right right">
                <?php }

                ?>

                <?php if($paged < $query->max_num_pages){  ?>

                                <?php
                                for($i=1; $i <= $query->max_num_pages; $i++){

                                    if($i === $paged){ ?>

                                    <?= $i ?><?php if($i < $query->max_num_pages){ echo ','; } ?>

                                    <?php }else{ ?>

                                    <a href="<?= get_pagenum_link($i) ?>"><?= $i ?><?php if($i < $query->max_num_pages){ echo ','; } ?>

                                    <?php }

                                }
                                ?>

               <?php     }

            ?>

            <?php $page = get_page_by_path( 'o-mne' ); ?>

<?= $page->post_title ?>

                <?php
                $content = $page->post_content;
                $content = apply_filters('the_content', $content);
                $content = str_replace(']]>', ']]>', $content);
                ?>

<?= $content ?>

A: You won't get a 404 because WP can find the page, and it then delegates the request to the template file where you added your own logic.
You could build your own 404 handling in that file, but a better way is to use a the archive.php (or archive-post.php for just this post type) to render the output, and use the pre_get_posts action to manipulate the WP_Query that is used to find posts (customize page size). If you're doing it that way, you'll find that WP will trigger a 404 correctly if the requested page is greater than the last available page.


text:
Q: Is there any benefits to using LiveData rather than a regular callback? I have an app in which the user is allowed to sign-in. The user data is saved in the database. The MainActivity implements an interface OnUserCreationCallback:
class MainActivity implements OnUserCreationCallback {
    //Unrelated code

    @Override
    void setUser(boolean created) {
        if(created) {
            //Display welcome message
        }
    }
}

Once the user is created in the database, the setUser() method fires and the user gets a welcome message. This is working as expected. My question, is there any real benefit of implementing a ViewModel and a LiveData, that can be observed when the user is created? I'm talking only for this particular operation and not for an operation that changes multiple time. It's a one time operation.

A: There's a chance this will leak your activity if you keep the callback after the activity is destroyed. For example if you keep your user repository or whatever around during configuration changes, it will keep referencing the callback, i.e. the activity, and it will never really be destroyed.
LiveData on the other hand is lifecycle aware and will be unsubscribed according to the lifecycle owner it's registered upon, for example when the activity is destroyed.
The other guy posted very good points too. This is basically the MVP vs MVVM debate.

A: Yes:
Livedata is life cycle aware.
That means if the fragment is detached or the user quits the app the observer is also detached.
In your case that could prevent user exiting the app and getting a null pointer exception because the host doesn't exist. In more complex cases it would help you to coordinate events better.
LiveData is a way of doing asynchronous programming, in using observers. From local db to the View you can observe a live data or use Coroutines to get the data, the result is the same and you have to judge when is better to get a result inside a coroutine or when is better to have an observer.
I'm telling the above because you don't need ViewModel, it is part of Jetpack, but if your DAO returns LiveData then you can observe that directly from the View (that would be bad architecture by the way) or you could use a Presenter.
@Dao
interface EntityDao {
      @Query(/*SELECT ALL*/)
     suspend fun getAll(): List<Entity>

     @Query(/*SELECT ALL*/)
     fun getAll(): LiveData<List<Entity>>

}

There are other inmplications, for testing live data you need to have some helper method or use espresso but for testing suspend functions you can use robo electric or the runBlockingTest suite


text:
Q: What is the definition of "cathode"? According to Wikipedia's definition, a cathode is "an electrode through which electric current flows out of a polarized electrical device". However, the direction of current flow is purely an arbitrary convention, and is in fact the opposite direction to which electrons flow in a metal conductor. Hence, this definition seems to be a bit lacking.
If the definition is referring to the current carriers, then the definition might be rephrased as "cathode is an electrode through which the charged current carriers flow out" (or "in"?).
How would you define this term clearly and unambiguously? Does the common use of the term "cathode" really reverse when the current carrier is positive, as suggested in the article?

Edit: What actually confuses me is the phrase "Cathode polarity is not always negative". If electrons always flow into the cathode (by way of definition of cathode), this statement implies that the cathode can be at a positive voltage relative to the anode. Can this happen in a "simple" conductor like an electrolyte, or does this require some special circuit?

A: Electric current is an abstract current, the flow of electric charge, not a physical current like, say, electron current, the flow of electrons.
But electric charge is a property of things, not a thing, i.e., electric charge is always "carried" by a thing.
So, while an electron current is necessarily an electric current (due the negative electric charge carried by the electron), an electric current is not necessarily an electron current.
For example, in a salt solution, we have two species of electrically charged ions present,  the positively charged sodium ion and the negatively charged clorine ion.  Imagine that the sodium ions are moving to the right and the chlorine ions are moving to the left.
Obviously, we have two ion currents in opposite directions but there is just one electric current and it must have a direction.  The direction of electric current is, by convention, the direction of the flow of positive charge.
So, in this case, both ion currents contribute to an electric current to the right.  The first term is due to the positive ions to the right.  The second term is due to the negative ions to the left where the negative sign numerically "flips" the contribution to the electric current.
Think about it this way, if I told you that I was travelling at -60mph west, you'd know that I was actually going 60mph east.  Similarly, a negative charge current leftward is an electric current rightward.
So, the above is all to simply say that the definition isn't lacking.

A: Wiki has it right, the cathode is the terminal of a component where the charge flows out. Charge flow (current) is the "standard" definition (i.e. Franklin's one from positive to negative, the opposite of electron flow).
The cathode of a component can change depending on it's state - for instance when a battery is discharging, the cathode is its positive terminal, and when charging
 its negative terminal (since the charge is now flowing into the positive terminal, rather than out, and out of the negative one, so they are reversed)

A: Of course, when you switch between talking about electrons and talking about electric current the direction flips.
You can define cathode as "the terminal where the electrons flow into the device", but as we are accustomed in everyday electronics life to talk about current flowing from + to -, the equivalent definition in terms of current is as your Wiki link states: "the terminal where the current flows out of the device".
IMO both definitions are totally unambigous. Their usefulness depends on the context.

A: I think that the definitions of 'anode' and 'cathode' have become rather loose over time. As others have mentioned, in the case of photodiodes and zeners, current can flow into the cathode.
In the days when the only kind of diode was the thermionic variety, the distinction between the terminals was clear. Electrons 'boil' off the cathode and are attracted to the anode, so convention current has to flow into the anode and out of the cathode.
When the semiconductor diode came along, the terms anode and cathode were preserved but I think they are misnomers in the original sense. But there is rarely (if ever) any confusion so I suppose it is a moot point.

A: I'd like to summarise the points raised by everyone in my own answer, because I had to pick them up from several answers (all of which I upvoted). Thank you everyone; this answer is only possible because you guys explained it to me :)
A cathode is the electrode that the current flows out of at a particular instant. This refers to the arbitrary direction of current which is a ubiquitous convention in modern electronics. If the current flows out of the electrode by this convention, the electrode is acting as a cathode. If the current flow at a terminal reverses direction, the terminal changes from a cathode to an anode.
Where the current is carried by electrons, the electrons flow into the cathode. In electrolytes, the negatively charged ions travel towards the cathode, and the positively charged ions travel away from it (though they don't physically flow into or out of the cathode, not very deep into it anyway).
Some electronic parts have one of their terminals designated as the positive terminal, and the other as the negative terminal. This does not mean that one of these is always the cathode. It depends entirely on whether the current is currently flowing into or out of a specific terminal. So, in a polarized capacitor that is being charged, the current flows into the positive terminal, thus the negative terminal is the cathode. While the same capacitor is discharging, current flows out of the positive terminal, thus the positive terminal becomes the cathode.
The potential difference between the cathode and anode can be both positive and negative, and does not determine which terminal acts as a cathode.


text:
Q: What is the most efficient way of handling global variables in PHP? It seems some people hate global variables, but if you can explain how to code without them, I'm all ears.
Otherwise, I have a few options and I'm curious which is the best long-term. Consider that I have a variable that won't change for the duration. It's a static global. I can use:
$_SESSION['var'] = constantval;
define('var', constantval);
var = constantval;

and the one I'm really curious about:
function my_constants($which)
{
    switch ($which) {
        case 'var':
            return 'constantval';
    }
}

In that last one, the goal is to keep variable out of global scope to save memory at the sacrifice of some processor cost. Is the memory saved worth the cycles? Is there a noteworthy difference between the various other types of global declaration?

A: Global variables are not considered a bad practice because of memory usage or processor cost. It's because of the problems that allowing any part of your program to modify them may cause. With the time, it becomes hard to understand which parts of the program read or write to your global variables.

A: Alternatives to globals (singetons).
It will give you a fine grained access control:
E.g.:
 class ConfigParamSingelton {
     private var $value;
     private static $mInstance = null;

     public function getValue() {
         return $this->value;
     }

     public function getInstance() {
         if(self::$mInstance == null) {
            self::$mInstance = new ConfigParamSingelton();
         }
         return self::$mInstance;
     }

So now you can either:
     protected function setValue($val) { // is immuteable by clients of the object
          $this->value = $val;
     }

or
     public function setValue($val) {// is muteable
          $this->value = $val;
     }

Well, this are singletons. You don't need globals in this case.


text:
Q: JWT Cannot convert access token to JSON I know this question has been asked here. However, there is not 1 line of code on the question. I will share my code so it may help me and others that could face the same issue.
Here follows the code...
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

@Autowired
private PasswordEncoder passwordEncoder;

@Autowired
private UserDetailsService userDetailsService;

@Autowired
@Qualifier(value = "authenticationManager")
private AuthenticationManager authenticationManager;

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    security.allowFormAuthenticationForClients().passwordEncoder(passwordEncoder);
}

/*
 * Não remover, Configura os Endpoints para o oAuth2
 */
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
    tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));
    endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore()).tokenEnhancer(tokenEnhancer())
            .userDetailsService(userDetailsService);
}

@Bean
public TokenEnhancer tokenEnhancer() {
    return new CustomTokenEnhancer();
}

@Bean
public TokenStore tokenStore() {
    return new JwtTokenStore(accessTokenConverter());
}

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    final KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("mytest.jks"),
            "mypass".toCharArray());
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("mytest"));
    return converter;
}

@Bean
@Primary
public DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(tokenStore());
    defaultTokenServices.setSupportRefreshToken(true);
    defaultTokenServices.setReuseRefreshToken(false);
    return defaultTokenServices;
}

}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
@Bean(name = "authenticationManager")
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
}

@Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
    return new JwtAuthenticationTokenFilter();
}

@Override
protected void configure(final HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()

            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .authorizeRequests()
            // .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

            // allow anonymous resource requests
            .antMatchers(HttpMethod.GET, "/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js")
            .permitAll().antMatchers("/auth/**").permitAll().anyRequest().authenticated();

    // Custom JWT based security filter
    httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

    // disable page caching
    httpSecurity.headers().cacheControl();
    // @formatter:on
}

}
@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().anyRequest().authenticated();
}

@Bean
public TokenStore tokenStore() {
    return new JwtTokenStore(accessTokenConverter());
}

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    Resource resource = new ClassPathResource("public.txt");
    String publicKey = null;
    try {
        publicKey = org.apache.commons.io.IOUtils.toString(resource.getInputStream());
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    converter.setVerifierKey(publicKey);
    return converter;
}

@Bean
@Primary
public DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(tokenStore());
    defaultTokenServices.setSupportRefreshToken(true);
    defaultTokenServices.setReuseRefreshToken(false);
    return defaultTokenServices;
}

So I have created a JWT with assimetric key, using the following command:
keytool -genkeypair -alias mytest
                    -keyalg RSA
                    -keypass mypass
                    -keystore mytest.jks
                    -storepass mypass
Since my authorization server is in the same place as the resource server, I added both the .jks and also the public.txt (that contains the public key) into the project.
The token gets generated correctly.... Here is an example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJyb290QDEwMCIsImp0aSI6ImVlZDQwMTk4LWE0OTUtNDJmNC05NDljLWYwOTQ1NzFmNDBmOCIsImNsaWVudF9pZCI6IjEiLCJvcmdhbml6YXRpb24iOiJyb290QDEwMFhqQXgifQ.mHURNG2v6M9RXTyXoDeOpxVUKLk0N9IVNJauL0Kvp0s
However, sending this token to get any resource from the server, I got the following error:
{
    "error": "invalid_token",
    "error_description": "Cannot convert access token to JSON"
}
So, what is missing?
EDIT
The server logs:
> Caused by: java.security.SignatureException: Signature length not correct:
got 32 but was expecting 256
at sun.security.rsa.RSASignature.engineVerify(RSASignature.java:189)
at java.security.Signature$Delegate.engineVerify(Signature.java:1219)
at java.security.Signature.verify(Signature.java:652)
at org.springframework.security.jwt.crypto.sign.RsaVerifier.verify(RsaVerifier.java:54)
... 57 more

EDIT 2
I have no ideia why downvoted the question. If there is anything I could add to enhance the question, please leave a comment and I'll do my best to improve the question.

A: You could better put details about the keystore into the application.yml (or application.properties respectively) as follows:
encrypt:
  key-store:
    location: mytest.jks
    alias: mytest
    password: mypass
    secret: mypass

Then you could simplify your code in both OAuth2Config and ResourceServer:
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    return converter;
}