text:
Q: How to make footable work in a table that's being populated with JS from JSON? I have something like this:

    ID
    FieldA
    FieldB
    FieldC

Then a JS like this:
var fillThatTable = function (list) {
    $.each(list, function (index, item) {
        $('#thatTable tbody').append($('
')
            .append($('').text(item.ID))
            .append($('').text(item.FieldA))
            .append($('').text(item.FieldB))
            .append($('').text(item.FieldC))
            )
        );
    });
};

Everything works fine, the table gets the data and shows it all. Problem comes when I want to set footable() to that table, like so:
$(document).ready(function () {
    fillThatTable();
    $('#thatTable').footable();
});

And instead of getting something beautiful, I just receive an average filtered table, almost like I didn't put that $('#thatTable').footable(). I checked the JS are imported, they are. Is it maybe because the table doesn't have anything in the tbody? What am I missing?
Dream:

Reality:

A: I've updated PM's fiddle to make an easier use of FooTable: http://jsfiddle.net/0pb4x7h6/1
If your html changes to this:

    ID
    FieldA
    FieldB
    FieldC

Then you can simplify your script to this:
$(document).ready(function () {
    var list = [
    {"ID":"1","FieldA":"A1","FieldB":"B1","FieldC":"C1"},
    {"ID":"2","FieldA":"A2","FieldB":"B2","FieldC":"C2"},
    {"ID":"3","FieldA":"A3","FieldB":"B3","FieldC":"C3"}
    ];

    // No need for this
    //fillThatTable();
    $('#thatTable').footable({
        rows: list
    });
});


text:
Q: How to scope static class object for specific background task? Considering
public class BackgroundJob{
   public string jobName{get;set;}
   ...
}

AppConfig.cs
public class AppConfig{
   public static BackgroundJob currentJob{get;set;}
}

BackgroundjobService.cs
public interface IBackgroundJobService
{ ... }

public class BackgroundJobService : IBackgroundJobService
{
    private readonly ServiceScopFactory _serviceScopFactory;
    public BackgroundJobService(ServiceScopFactory serviceScopFactory)
    {
        _serviceScopFactory = serviceScopFactory;
    }
    public async Task RunBackgroundJobTest1()
    {
        using (var serviceScope = _serviceScopeFactory.CreateScope())
        {
            AppConfig.currentJob = new(){ jobName = "job1" };

                var idx = 0;
                for (int i = 0; i <= 1000; i += 100)
                {
                    idx++;
                    await Task.Delay(1000);
                    Console.WriteLine($"===> jobName = {currentJob.jobname}");
                }
        }
    }

    public async Task RunBackgroundJobTest2()
    {
        using (var serviceScope = _serviceScopeFactory.CreateScope())
        {
            AppConfig.currentJob = new(){ jobName = "job2" };

                var idx = 0;
                for (int i = 0; i <= 1000; i += 100)
                {
                    idx++;
                    await Task.Delay(1000);
                    Console.WriteLine($"===> jobName = {currentJob.jobname}");
                }
        }
    }
}

Execute:
public class TestController : Controller
{
   private readonly IBackgroundJobClient _backgroundJobClient; //hangfire
   public TestController(IBackgroundJobClient backgroundJobClient)
   {
      _backgroundJobClient = backgroundJobClient;
   }
   [HttpGet("test")]
   public IActionResult Test()
   {
       _backgroundJobClient.Enqueue<IBackgroundJobService>(x=>x.RunBackgroundJobTest1()); //log ===> jobName = job2
       _backgroundJobClient.Enqueue<IBackgroundJobService>(x=>x.RunBackgroundJobTest2()); //log ===> jobName = job2
   }
}

As result, AppConfig.currentJob does not keep the first value from/inside ServiceScop1 but it was reinitialized by the last task inside ServiceScope2

Question: pls anyone suggest me for correct implementation for this purpose? And it would be appreciated. thanks

A: What you are trying to achieve is not clear to me. Anyway, as I understand your question, you could try the code below.
It will make currentJob local to your processing. Unlike [ThreadStatic], this will not fail if the process changes thread :
public class AppConfig{
   private static System.Threading.AsyncLocal<BackgroundJob> _currentJob {get;}
        = new System.Threading.AsyncLocal<BackgroundJob>();

 public static BackgroundJob currentJob {
     get {return _currentJob.Value;}
     set {_currentJob.Value = value;}
  }
}

Note that this behaviour is not linked to the ScopeServiceFactories. To have full dependency injection, linked to the scope you would need to drop the statics.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problema redirección DNS Hostalia Llevo un año utilizando un DNS de hostalia para la redirección de mi VPS. Ayer automáticamente se me renovó el servicio, y dejó de funcionar el DNS. Llevo todo el día intentando arreglarlo, pero no lo consigo.
Si entro desde www.mipagina.com funciona bien, pero si entro desde mipagina.com, sale una pantalla diciendo "este dominio está reservado".
La dirección de mi VPS es 85.255.8.178
Esto es lo que tengo en el panel de los DNS de Hostalia

Y aquí la REDIRECCIÓN (desactivada)


text:
Q: Ruby's Virtus gem vs attr_accessor I am looking at the Virtus gem used in a few tutorials about Service object in Ruby.  In the github page, https://github.com/solnic/virtus, it gives the following example.
Using Virtus with Classes
You can create classes extended with Virtus and define attributes:
class User   include Virtus.model
  attribute :name, String
  attribute :age, Integer
  attribute :birthday, DateTime
end

user = User.new(:name => 'Piotr', :age => 31) user.attributes # => { :name => "Piotr", :age => 31, :birthday => nil }

user.name # => "Piotr"

user.age = '31' # => 31 user.age.class # => Fixnum

user.birthday = 'November 18th, 1983' # => #<DateTime: 1983-11-18T00:00:00+00:00 (4891313/2,0/1,2299161)>

# mass-assignment user.attributes = { :name => 'Jane', :age => 21 } user.name # => "Jane" user.age  # => 21

I can see how the example works, but would like to understand how is this different than just defining attr_accessors in Ruby?  If I have to explain to someone, the benefit of including the Virtus gem and what it does in a couple of lines, what would it be?

A: The goals of Virtus can be summarized as trying to make attributes a little more "Rails-y".  They provide support for parsing form/JSON, encapsulation while retaining type information, and a few other things it's not impossible to get regular attributes to do, but not easy either.
The real benefits, however, come when you combine Virtus with ActiveModel::Validations per this post.  Since your basic values have become more responsive to the expectations of Rails form helpers, you have a very powerful alternative to nested forms.


text:
Q: Should I move this task to a message queue? I'm a big fan of using message queue systems(like Apache ActiveMQ) for the tasks which are rather slow and do not require instant feedback in User Interface.
The question is: Should I use it for other tasks(which are pretty fast) and do not require instant feedback in User Interface?
Or does it in involve another level of complexity without not so much benefits?

A: Well, if you think about it, Win32 is more or less built around message queues.  That said, just because you have a hammer, doesn't make every problem a nail.  Frankly though, it depends.  Queues for example do not work well towards multiple receivers.

A: Is it necessary for requests to be processed in the background, independent of other components in your application? If the answer is yes, I think it warrants a queue of some kind.
If you're processing them inline in your application, that just means your application has to be running to process them. If you want them to run on their own, then you need something else to process them. I don't think adding the queue is enough extra work to justify avoid it if your message processing needs to always be running.

A: If you're already using a MQ system in your app, I would consider moving most non-synchronous tasks there. Any fire-and-forget or event driven task is a good candidate. But then, don't overdo it either, and I certainly wouldn't consider adding the dependency if you have no other use for MQ in the application.

A: The right tool for the job. Is a message queue the right tool for the job you have in mind?


text:
Q: Struts2 multiple forms with token not working. Only one token at a time working I am trying to develop an application in struts2 where I have multiple forms and may or may not have same action. To avoid CSRF I also added token with these forms, but only one token at a time working. If I clicked on another submit button then I am redirecting to error page which is configured for CSRF. I am stuck here why this is happening, am not able to use multiple token on same page or is there any solution for this.
Please find struts2.xml code which I have configured.
<action name="expUsers" class="com.org.action.ExpUser">
   <interceptor-ref name="CSRFStack"/>
   <result name="invalid.token" type="tiles">csrfError</result>
   <result name="success" type="stream">
       <param name="contentDisposition">contentDisposition</param>
       <param name="contentType">application/octet-stream</param>
       <param name="inputName">inputStream</param>
   </result>
   <result name="failed" type="chain">csrfError</result>
</action>

I have the following dummy form example below which will let you understand what i am doing.
<form id="form-1">
<s:token/>
....
</form>

<form id="form-2">
<s:token/>
....
</form>

<form id="form-3">
<s:token/>
....
</form>

... so on multiple forms with token.

A: Thanks to All for giving me your suggestion. I have found a working solution so i am giving answer to my own question.
When we generate <s:token/> then the hidden field will be generate like this:-
<input type="hidden" name="struts.token.name" value="token">
<input type="hidden" name="token" value="1IPDKJ3QWM8X4JXAV0RKC0A9XVQ4I83E">

which is default behavior. Now if i want to generate different token for each struts2 token tag then i have to specify the unique name to token like this :-
<s:token name="unique-1"/>

Then it will generate hidden field like this:-
<input type="hidden" name="struts.token.name" value="unique-1">
<input type="hidden" name="unique-1" value="1IPDKJ3QWM8X4JXAV0RKC0A9XVQ4I83E">

Now i have two different token for two different forms in same page and this tricks also working perfectly without any issue at the time of writing this answer.


text:
Q: Docker apache container redirect to another container I got two apache containers connect to the same bridge network. First apache 172.20.10.2 and port 8080 (internally 80) Second apache 172.20.10.6 and port 9999 (internaly 80).
First apache is configured with two virtual hosts on port 80.
First vhost support mydomain.com on that apache and everything works correctly.
Second vhost support subdomain.mydomain.com and redirect to second apache server.
This redirects don't work and on logs I got that error:
"GET /favicon.ico HTTP/1.1" 502 360
[proxy:error] [pid 43:tid 3028272160] (111)Connection refused: AH00957: http: attempt to connect to 172.20.10.6:9999 (172.20.10.6) failed
[proxy_http:error] [pid 43:tid 3028272160] [client Client_IP:PORT] AH01114: HTTP: failed to make connection to backend: 172.20.10.6
"GET / HTTP/1.1" 503 299
[proxy:error] [pid 8:tid 3011486752] [client Client_IP:PORT] AH00898: DNS lookup failure for: 172.20.10.6:9999favicon.ico returned by /favicon.ico, referer: http://subdomain.mydomain.com/
"GET /favicon.ico HTTP/1.1" 502 360

docker-compose.yml
version: "3.8"

volumes:
  httpd_all:
  httpd_all_2:

networks:
  frontend_web:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.20.10.0/29

services:

  httpd:

    container_name: httpd
    image: httpd:latest
    hostname:
      srv_www01
    ports:
      - 8080:80/tcp
      - 8043:443/tcp
    volumes:
      - httpd_all:/usr/local/apache2/
    networks:
      frontend_web:
        ipv4_address: 172.20.10.2
    restart: unless-stopped

  httpd_2:

    container_name: httpd_2
    image: httpd:latest
    hostname:
      srv_www02
    ports:
      - 9999:80/tcp
      - 9998:443/tcp
    volumes:
      - httpd_all_2:/usr/local/apache2/
    networks:
      frontend_web:
        ipv4_address: 172.20.10.6
    restart: unless-stopped

vhosts on first apache 172.20.10.2
<VirtualHost *:80>
        ServerName mydomain.com
        ServerAlias mydomain.com
        DocumentRoot /usr/local/apache2/htdocs
        Alias /jasno "/usr/local/apache2/htdocs"

</VirtualHost>

<VirtualHost *:80>
        ServerName subdomain.mydomain.com
        ServerAlias www.subdomain.mydomain.com

        ProxyRequests Off
        ProxyPreserveHost On
        ProxyVia Full

        <Proxy *>
                Require all granted
        </Proxy>

        ProxyPass "/" "http://172.20.10.6:9999"
        ProxyPassReverse "/" "http://172.20.10.4:9999"

</VirtualHost>

A: Connections between containers ignore ports:.  If the process inside the second container listens on ports 80 and 443, connections between containers will only ever use those ports, even if ports: make them visible as something else outside the host.  Since port 80 is the default HTTP port, you can leave it out of your configuration entirely:
ProxyPass "/" "http://172.20.10.6"

You can simplify this setup even further.  As described in Networking in Compose in the Docker documentation, Docker provides an internal DNS system, and each container is accessible from other containers in the same Compose file using its Compose service name.  Instead of manually specifying the IP address, you can use that host name in the Apache setup
ProxyPass "/" "http://httpd_2"

Once you've done that, you can simplify the Compose setup considerably.  It's almost always safe to let Docker pick IP addresses on its own, rather than assigning them manually.  Compose can also assign container names, it creates a network named default for you, and the hostname: setting usually has no visible effect.  You should be able to trim this down to:
version: "3.8"

volumes:
  httpd_all:
  httpd_all_2:

services:
  httpd:
    image: httpd:latest
    ports:
      - 8080:80/tcp
      - 8043:443/tcp
    volumes:
      - httpd_all:/usr/local/apache2/
    restart: unless-stopped

  httpd_2:
    image: httpd:latest
    # ports:              only if the service needs to be
    #   - 9999:80/tcp     accessed from outside Docker; not used
    #   - 9998:443/tcp    for connections between containers
    volumes:
      - httpd_all_2:/usr/local/apache2/
    restart: unless-stopped


text:
Q: Suppressing the "Picked up _JAVA_OPTIONS" message I'm using _JAVA_OPTIONS to set some defaults for Java on RHEL. It works fine but now every time I start java I get the following message

Picked up _JAVA_OPTIONS: -foo -bar -baz

is it possible to keep the options but suppress the display of this message.

A: From looking at the relevant source code (arguments.cpp in openjdk, line 2492), there is no way to control the output of this message.
The only thing I could say is that it is printed to stderr. So you could wrap your commands to redirect stderr to /dev/null (if there wasn't anything else you cared about on stderr).

*

*Or write a java wrapper script which filtered out this message.

*Or submit a feature request to the openjdk project, although this won't solve your immediate problem.

A: Where is _JAVA_OPTIONS being set? In your .bashrc?
Use an alias instead, e.g.
alias java="`which java` -Dwhatever"

Actually, it is not necessary to know where it is being set to make this work:
_SILENT_JAVA_OPTIONS="$_JAVA_OPTIONS"
unset _JAVA_OPTIONS
alias java='java "$_SILENT_JAVA_OPTIONS"'


text:
Q: OpenJDK cross compilation: failed unable to make target I need to cross-compile this fork of openJDK https://gitlab.com/gosjava/11/openjdk/-/tree/master/ on host system Kali Linux 2021.3 for target "aarch64-linux-gnu"
As described here https://gitlab.com/gosjava/11/openjdk/-/blob/master/doc/building.md#cross-compiling-the-easy-way-with-openjdk-devkits
And it fails with error:
┌──(katya㉿kali)-[~/work/prostor/openjdk]
└─$ cd make/devkit

┌──(katya㉿kali)-[~/…/prostor/openjdk/make/devkit]
└─$ make TARGETS="aarch64-linux-gnu"
Building on platform unknown-linux-gnu
host_platforms unknown-linux-gnu
target_platforms aarch64-linux-gnu
find: '/home/katya/work/prostor/openjdk/build/devkit/result/unknown-linux-gnu-to-aarch64-linux-gnu': No such file or directory
Building compilers for unknown-linux-gnu
Targets: aarch64-linux-gnu
for p in  aarch64-linux-gnu; do \
  make -f Tools.gmk download-rpms HOST=unknown-linux-gnu BUILD=unknown-linux-gnu RESULT=/home/katya/work/prostor/openjdk/build/devkit/result OUTPUT_ROOT=/home/katya/work/prostor/openjdk/build/devkit \
              TARGET=$p PREFIX=/home/katya/work/prostor/openjdk/build/devkit/result/unknown-linux-gnu-to-$p && \
  make -f Tools.gmk all HOST=unknown-linux-gnu BUILD=unknown-linux-gnu RESULT=/home/katya/work/prostor/openjdk/build/devkit/result OUTPUT_ROOT=/home/katya/work/prostor/openjdk/build/devkit \
              TARGET=$p PREFIX=/home/katya/work/prostor/openjdk/build/devkit/result/unknown-linux-gnu-to-$p && \
  make -f Tools.gmk ccache HOST=unknown-linux-gnu BUILD=unknown-linux-gnu RESULT=/home/katya/work/prostor/openjdk/build/devkit/result OUTPUT_ROOT=/home/katya/work/prostor/openjdk/build/devkit \
              TARGET=unknown-linux-gnu PREFIX=/home/katya/work/prostor/openjdk/build/devkit/result/unknown-linux-gnu-to-$p BUILDDIR=/home/katya/work/prostor/openjdk/build/devkit/unknown-linux-gnu/$p || exit 1 ; \
done
make[1]: Entering directory '/home/katya/work/prostor/openjdk/make/devkit'
TARGET=aarch64-linux-gnu
HOST=unknown-linux-gnu
BUILD=unknown-linux-gnu
ARCH=aarch64
Tools.gmk:75: *** Unknown base OS .  Stop.
make[1]: Leaving directory '/home/katya/work/prostor/openjdk/make/devkit'
make: *** [Makefile:90: unknown-linux-gnu] Error 1

Why? The command make TARGETS="aarch64-linux-gnu" BASE_OS=OLE6 also fails
Tools.gmk:75: *** Unknown base OS OLE6.  Stop.
make[1]: Leaving directory '/home/katya/work/prostor/openjdk/make/devkit'
make: *** [Makefile:90: unknown-linux-gnu] Error 1

What is wrong? I follow documentation, but ...


text:
Q: How to determine if an object has fallen down I'm currently developing an application using Unity.
I wrote the following code to determine if a pin object like the one below has fallen down.
But, in this case, even if the pin object falls down, it sometimes does not return true.
How could I edit the code to make sure that an object has fallen down?

Here is the code:
   bool CheckFallenDown(Transform transform) {
        if (transform.rotation.x * transform.rotation.x > 0.01f && transform.rotation.z * transform.rotation.z > 0.01f) {
            return true;
        } else{
            return false;
        }
    }

Unity 2020.3.16f

A: The easiest way I guess is actually to simply compare the pin's transform.up vector to the world's global Vector3.up using Vector3.Angle like e.g.
private const float THRESHOLD = 0.01f;

public bool CheckCollpse(Transform transform)
{
    return Vector3.Angle(transform.up, Vector3.up) > THRESHOLD;
}


text:
Q: HTML5 video tag doesn't work in FF On this site, the video doesn't play in FF. But it does play in Chrome. Is there anything I need to add?
<video width="580" height="318" controls poster="link to poster">
    <source src="link to video">
    Your browser does not support the HTML5 Video tag. Please update to a modern browser.
</video>

A: In your site's source:
<source src="/wp-content/themes/bigframe/media/bigframe_reel.mp4">

Firefox doesn't support mp4 videos for HTML5 video.
You can add additional sources (WebM, OGG), and fallback to a Flash player. See this table for compatibility.

A: You can solve the problem by providing video or audio encoded in different formats for different browsers.
<video controls>
  <source src="foo.ogg" type="video/ogg">
  <source src="foo.mp4" type="video/mp4">
  Your browser does not support the video element.
</video>


text:
Q: Best books on the theory and practice of software architecture? I have a couple of developers at my company who wish to move from programming into architecture. What are the best books out there on the theory and practice of software architecture? Include a cover picture if you can.
Feel free to include general books, and also books that relate to a specific technology.

A: 97 Things Every Software Architect Should Know

A:
this would be my #2 choice. Good book on practices and good code. A bit pedantic sometimes.

A:
This is my number #1 choice right now. Best book about how to build (grow) application now.

A: If you are using .net check out these two...(there are web app versions also)
Microsoft .NET: Architecting Applications for the Enterprise (Microsoft)
Professional Enterprise .NET (Wrox Press)

A: A collection classic papers every sw architect should read
http://www.amazon.co.uk/Software-Fundamentals-Collected-Papers-L-Parnas/dp/0201703696/ref=sr_1_7?ie=UTF8&qid=1291810946&sr=8-7

A: I've found volumes 1 and 4 of Pattern-Oriented Software Architecture to be very useful.  I'm sure the other volumes are good too, I just haven't read them so I can't recommend them.

A: Refactoring, Martin Fowler
One of the best programming books overall.

A: I wont't cite ones that have already been by other, so I'll add this one:
Concepts Techniques and Models of Computer Programming, by peter Van Roy and Seif Haridi

The obvious problem is that it used the now (sort-of) defunct Mozart Programming System and the amazing Oz programming language. Which then spawned other interesting experiments like the Alice ML programming language.
It is, however, an amazing book, both to learn computer programming and to get a deep understanding of CS concepts and a good overview of architecture concepts without using buzzwords.
A bit verbose at times, but very well written.
Maybe more of a CS theory book in the end than an enterprise architecture book, but I find its teachings very valuable to apply to industry software.

A: Documenting Software Architecture: Views and Beyond by Clements et al. from the Software Engineering Institute.
Cover of Documenting Software Architecture http://ecx.images-amazon.com/images/I/512Fz-vNz5L._SL160_.jpg

A: Just Enough Software Architecture by George Fairbanks.
Cover of 'Just Enough Software Architecture' http://ecx.images-amazon.com/images/I/61%2BhzVm5IoL._SL160_.jpg

A: try this small book.
Software Architecture for Developers - The Book
A practical and pragmatic guide to software architecture
This book is a collection of essays that together form a practical and pragmatic guide to software architecture.

*

*What is software architecture?

*What is the role of a software architect?

*How do you define software architecture?

*How do you share software architecture?

*How do you deliver software architecture?

A: An interesting book is The Architecture of Open Source Applications

Architects look at thousands of
  buildings during their training, and
  study critiques of those buildings
  written by masters. In contrast, most
  software developers only ever get to
  know a handful of large programs
  well—usually programs they wrote
  themselves—and never study the great
  programs of history. As a result, they
  repeat one another's mistakes rather
  than building on one another's
  successes.
This book's goal is to change that. In
  it, the authors of twenty-five open
  source applications explain how their
  software is structured, and why. What
  are each program's major components?
  How do they interact? And what did
  their builders learn during their
  development? In answering these
  questions, the contributors to this
  book provide unique insights into how
  they think

A: Microsoft have some really good stuff on this. For a start they have a great free book available here:
http://msdn.microsoft.com/en-us/library/ff650706.aspx
Plus a lot of their white papers on design are here:
http://msdn.microsoft.com/en-us/practices/bb190351
You probably want to read up on design patterns:
http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612
And then there's the classics - mythical man month, code complete, pragmatic programmer etc. A bit of googling will help you find the good books.

A:
But, I would encourage these developers not to move into architecture and totally forget about programming. If they do, they won't have any respect from programmers and they won't be properly equipped to make architectural decisions.

A:
(link to the book)
This is a pretty good book, although it deals not with software architecture in general, but with architecture of business applications.

A: The commonly cited/referenced book on software architectures, and the book used when I took the Software Architecture course at my university is Software Architecture in Practice (2nd Edition) by Len Bass, Paul Clements, and Rick Kazman.
At least one professor who teaches the course has switched the textbook to Software Systems Architecture by Nick Rozanski and Eoin Woods, but I can't vouch for the quality or content of that book. According to Sergio Acosta (in the comments), Rozanski's book is newer, based on the work of Bass, and he considers it easier to read. I'm rarely disappointed by books used in the software engineering program.

A:
A must read for all programmers:
http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612

A: I recommend Expert One-on-One J2EE Design and Development. It's a very good book about J2EE, and is the theory basement of Spring Framework.

A: The question you're asking is very untangible, in a way. Software architecture is different things and software architects are a very diverse bunch.
A few notes, though:
"Clean Code" mentioned above is one of the best books I've ever read on programming. But it is certainly not a book about architecture. Mandatory reading for developers, yes, but doesn't give much insight into how the larger stuff fits together, imo.
"PoEAA" by Fowler is a good book, but as someone else said, kind of old now, and many of the patterns presented have been obsoleted several years ago.
The DDD book by Eric Evans is a very solid and very inspiring book about software construction and customer collaboration - valuable skills for architects, but good for developers also.

A: What I'd suggest that, please go and read Code Complete 2 first. This will help you to shape your thoughts and find the best way of doing things.
In the architecture perspective, it's good start with GOF or Head First Design Patterns.
Patterns of Enterprise Application Architecture is an excellent book


text:
Q: Bad matrix inversion algorithm, or implemented incorrectly? Trying to implement matrix inversion in Perl myself, I found An Efficient and Simple Algorithm for Matrix Inversion (only two pages of the article).
After my attempt to implement it in Perl, I see that it does not work.
I had spend a lot of time trying to find out what's wrong, so I concluded that

*

*either the algorithm is not correct

*I misinterpreted the algorithm

*my implementation is not correct

Before presenting the code, here's a debug session with an example from Wikipedia: Inverse Matrix:
  DB<229> $m=[[2,5],[1,3]]

  DB<230> x invert($m)
pe[0] == 2
(pivot row 0) 2x2:
   2.000   2.500
   1.000   3.000
(pivot column 0) 2x2:
   2.000   2.500
  -0.500   3.000
(rest 0) 2x2:
   2.000   2.500
  -0.500   1.750
(pivot 0) 2x2:
   0.500   2.500
  -0.500   1.750
pe[1] == 1.75
(pivot row 1) 2x2:
   0.500   2.500
  -0.286   1.750
(pivot column 1) 2x2:
   0.500  -1.429
  -0.286   1.750
(rest 1) 2x2:
   0.908  -1.429
  -0.286   1.750
(pivot 1) 2x2:
   0.908  -1.429
  -0.286   0.571
0  1
1  3.5
  DB<231>

So here's the code I wrote:
#!/usr/bin/perl -w
use 5.026;
use strict;

# invert matrix
# An Efficient and Simple Algorithm for Matrix Inversion
# Ahmad Farooq, King Khalid University, Saudi Arabia
# Khan Hamid, National University of Computer and Emerging Sciences (NUCES),
# Pakistan
sub invert($)
{
    my $m = shift;          # matrix is an array of rows
    my ($pp, $det);
    my ($rp, $pe);
    my $n = scalar(@$m);

    for ($pp = 0, $det = 1.0; $pp < $n; ++$pp) {
        $rp = $m->[$pp];        # pivot row
        $pe = $rp->[$pp];       # pivot element
        print "pe[$pp] == $pe\n";
        last if ($pe == 0);      # Epsilon test?

        $det *= $pe;
        # calculate pivot row
        for (my $j = 0; $j < $n; ++$j) {
            next if ($j == $pp);

            $rp->[$j] /= $pe;
        }

        pm($m, "pivot row $pp");
        # calculate pivot column
        for (my $i = 0; $i < $n; ++$i) {
            next if ($i == $pp);

            $m->[$i]->[$pp] /= -$pe;
        }

        pm($m, "pivot column $pp");
        for (my $j = 0; $j < $n; ++$j) {
            next if ($j == $pp);

            for (my ($i, $rj) = (0, $m->[$j]); $i < $n; ++$i) {
                next if ($i == $pp);

                $rj->[$i] += $rp->[$j] * $m->[$i]->[$pp];
            }
        }

        pm($m, "rest $pp");
        $rp->[$pp] = 1.0 / $pe;
        pm($m, "pivot $pp");
    }

    return ($pe != 0.0, $det);
}

The pm() function is just a "print matrix" for debugging purposes:
# print matrix
sub pm($;$)
{
    my ($m, $label) = @_;
    my $n = scalar(@$m);
    print "($label) " if ($label);
    print "${n}x${n}:\n";
    for (my $i = 0; $i < $n; ++$i) {
        for (my $j = 0; $j < $n; ++$j) {
            if (defined(my $v = $m->[$i]->[$j])) {
                printf('%8.3f', $v);
            } else {
                print ' ???????';
            }
        }

        print "\n";
    }
}

Any insights?
Hint for Reproduction (added 2019-08-28)
I had thought it was obvious, but just in case:
If you want to reproduce the output shown in the debug session, maybe just add these two lines at the end of the code:
my $m=[[2,5],[1,3]];                 # matrix to invert
print join(', ', invert($m)), "\n";  # invert $m, printing result

Note (added 2019-09-02):
The algorithm fails for the 3x3 matrix given in the Wikipedia article ($m = [[1, 2, 0], [2, 4, 1], [2, 1, 0]]), so real implementations should head towards the improved algorithm (that can select pivot elements outside the diagonal).

A: When in doubt, write tests.
First, put your code into a module (lib/My/Matrix.pm or whatever you want to call it):
package My::Matrix; # this must match the file name

use strict;
use warnings;
use Exporter qw(import);

our @EXPORT_OK = qw( invert pm );

# your code here ...

1; # at end of module

There is a lot of documentation regarding writing modules, not sure if perldoc perlmod is a good starting point.
Now write a test - documentation is here (t/001-invert.t):
#!perl

use strict;
use warnings;
use Test::More;

use Matrix qw(invert);

ok_invert( [[1,0], [0,1]], [[1,0], [0,1]], "unit matrix" );
# insert more matrices here

done_testing;

sub ok_invert {
    my ($input, $output, $msg) = @_;

    invert( $output );
    is_deeply $input, $output, $msg
         or diag "got: ", explain $input, "expected: ", explain $output;
};

Run the test as perl -Ilib t/001-invert.t or prove -Ilib t if you want to run multiple tests.
You can now add simple corner cases to the test until the problem is isolated.
Of course, finding the correct inverse matrix by hand is tedious, so you may want to use multiplication instead. So the next steps to improve your code would be:

*

*make sure invert does not modify its input and returns the inverted matrix instead;

Sidenote. It's generally a good idea to make sure a function returns the desired value and does not modify its arguments. It's not always possible but when it is, it saves a ton of debugging time.

*

*implement multiplication;

*implement is_unit_matrix check;

*rewrite the test function as follows (the next snippet was not tested):

sub ok_invert {
    my ($input, $msg) = @_;
    my ($invert, $det) = invert( $input );
    ok is_unit_matrix( multiply( $invert, $input ) ), $msg
        or diag explain $invert, " is not the inverse of ", explain $input;
}

Hope this helps.

A: According to the referred to paper, step #7 should be computed with the old pivot row values, so the following seems to work for me:
sub invert($)
{
    my $m = shift;          # matrix is an array of rows
    my ($pp, $det);
    my ($rp, $pe);
    my $n = scalar(@$m);

    for ($pp = 0, $det = 1.0; $pp < $n; ++$pp) {
        $rp = $m->[$pp];        # pivot row
        $pe = $rp->[$pp];       # pivot element
        last if ($pe == 0);      # Epsilon test?

        $det *= $pe;
        # calculate pivot column
        for (my $i = 0; $i < $n; ++$i) {
            next if ($i == $pp);
            $m->[$i][$pp] /= -$pe;
        }
        for (my $j = 0; $j < $n; ++$j) { # row index
            next if ($j == $pp);
            for (my ($i, $rj) = (0, $m->[$j]); $i < $n; ++$i) {
                next if ($i == $pp);
                $rj->[$i] += $rp->[$i] * $m->[$j]->[$pp];
            }
        }
        # calculate pivot row
        for (my $j = 0; $j < $n; ++$j) {
            next if ($j == $pp);
            $rp->[$j] /= $pe;
        }
        $rp->[$pp] = 1.0 / $pe;
    }

    return ($pe != 0.0, $det);
}

Fix required to match result in Wikipedia:
--- newinvert.pl~   2019-08-29 21:22:16.135160055 +0200
+++ newinvert.pl    2019-08-29 21:32:10.995144732 +0200
@@ -20,7 +20,7 @@
             next if ($j == $pp);
             for (my ($i, $rj) = (0, $m->[$j]); $i < $n; ++$i) {
                 next if ($i == $pp);
-                $rj->[$i] += $rp->[$i] * $m->[$j]->[$pp];
+                $rj->[$i] += $rp->[$j] * $m->[$i]->[$pp];
             }
         }
         # calculate pivot row

Sample session (inluding my pm()):
> perl -d printmatrix.pl

Loading DB routines from perl5db.pl version 1.51
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(printmatrix.pl:20):  1;
  DB<1> require "./newinvert.pl" # this is ungly, forgive!
./newinvert.pl did not return a true value at (eval 6)[/usr/lib/perl5/5.26.1/perl5db.pl:738] line 2.

  DB<2> $m=[[2,5],[1,3]]
  DB<4> pm($m)
2x2:
   2.000   5.000
   1.000   3.000

  DB<5> x invert($m)
0  1
1  1
  DB<6> pm($m)
2x2:
   3.000  -5.000
  -1.000   2.000

Result of regression tests:
# https://github.com/wollmers/matrix-inverse-Farooq/blob/master/matrix_inversion_new.pl

$ perl matrix_inversion_new.pl
[...]
(invert_hakon 01_wiki input $A) 2x2:
   2.000   5.000
   1.000   3.000
(invert_hakon 01_wiki result $C) 2x2:
   3.000  -5.000
  -1.000   2.000
ok 10 - 01_wiki invert_hakon Ainv
ok 11 - 01_wiki invert_hakon det: 1
(invert_hakon 02_wiki input $A) 2x2:
   2.000   3.000
   1.000   2.000
(invert_hakon 02_wiki result $C) 2x2:
   2.000  -3.000
  -1.000   2.000
ok 12 - 02_wiki invert_hakon Ainv
ok 13 - 02_wiki invert_hakon det: 1
(invert_hakon 03_author_1 input $A) 3x3:
   1.000   1.000   3.000
   1.000   3.000  -3.000
  -2.000  -4.000  -4.000
(invert_hakon 03_author_1 result $C) 3x3:
   3.000   1.000   1.500
  -1.250  -0.250  -0.750
  -0.250  -0.250  -0.250
ok 14 - 03_author_1 invert_hakon Ainv
ok 15 - 03_author_1 invert_hakon det: -8
[...]

A: The pseudocode in the original paper is not correct.
Steps I have done so far:

*

*inserted the pseudocode into the Perl source

*used the naming of the pseudocode

*test cases

*tested the test cases

*tested with Math::Matrix as a reference

*reviewed (many times)

At least I read the note in paper:

Note that in step 7 of the following algorithm a'[i, p]
  on the LHS means that the latest value of the pivot row
  is to be used in the calculations.

This note is not really precise. After additional attempts I gave up, wanted to post my findings here, and read the answer of Håkon Hægland. Yes, his solution works and he earns the honor.
If the steps in the pseudocode are reordered it passes my 3 tests:
Step 1
Step 2
Step 3
Step 4
Step 6
Step 7
Step 5
Step 8
Step 9
Step 10

Here is the version with pseudocode included and using the original naming:
sub invert_corr($) {
    my $A = shift;          # matrix is an array of rows
    my $n = scalar(@$A);

    # Step 1: Let p = 0, d = 1;
    my $p   = 0;
    my $det;
    # Step 2: p <= p +1
    for (my $pi = 0,$det = 1.0; $pi < $n; ++$pi) {
        $p = $pi;

        # Step 3: If a[p,p] == 0 then cannot calculate inverse, go to step 10.
        if ($A->[$p]->[$p] == 0) { last; }

        # Step 4: d <= d x a[p, p]
        $det = $det * $A->[$p]->[$p];

        # Step 6: Calculate the new elements of the pivot column by:
        #   a_new[i,p] <= -(a[i,p] / a[p,p]) where  i = 1 .. n, i != p
        STEP6: for (my $i = 0; $i < $n; ++$i) {
            if ($i == $p) { next STEP6; }
            $A->[$i]->[$p] = -($A->[$i]->[$p] / $A->[$p]->[$p]);
        }

        # Step 7: Calculate the rest of the new elements by:
        #   a_new[i,j] <= a[i,j] + a[p,j] x a_new[i,p]
        #     where i = 1 .. n, j = 1 .. n, & i,j != p
        OUTER7: for (my $i = 0; $i < $n; ++$i) {
            if ($i == $p) { next OUTER7; }
            INNER7: for (my $j = 0; $j < $n; ++$j) {
                if ($j == $p) { next INNER7; }
                # Note that in step 7 of the following algorithm a'[i, p]
                # on the LHS means that the latest value of the pivot row
                # is to be used in the calculations.
                $A->[$i]->[$j] = $A->[$i]->[$j] + $A->[$p]->[$j] * $A->[$i]->[$p];
            }
        }

        # Step 5: Calculate the new elements of the pivot row by:
        #   a_new[p,j] <= a[p,j] / a[p,p] where  j = 1 .. n, j != p
        STEP5: for (my $j = 0; $j < $n; ++$j) {
            # next if ($j == $p);
            if ($j == $p) { next STEP5; }
            $A->[$p]->[$j] = $A->[$p]->[$j] / $A->[$p]->[$p];
        }

        # Step 8: Calculate the new value of the current pivot location:
        #   a_new[p,p] <= 1 / a_new[p,p]
        $A->[$p]->[$p] = 1.0 / $A->[$p]->[$p];

        # Step 9: If p < n go to step 2 (n the dimension of the matrix A).
    }

    # Step 10: Stop. If inverse exists, A contains the inverse and d is the determinant.
    if ($A->[$p]->[$p] != 0.0) {
        return ($A->[$p]->[$p] != 0.0, $det, $A);
    }
    return ($A->[$p]->[$p] != 0.0);
}

The complete code including tests is available on github, maybe useful for debugging.

A: One of the problems when implementing a mathematical formula like (actually from Step 5)

in a loop is: When will the "new" a' become the "old" a?
Before the next step, before the next assignment, or before the next loop iteration?
In a mathematical sense a' and a are different variables all the time, but in procedural programming languages the memory address for a is reused at some time.
So the assignments from Step 5 need to be delayed after Step 7 (), it seems.
As a computer scientist I had always felt that mathematical algorithms are described in a somewhat imprecise way. Maybe that's exactly the reason why programming languages were invented ;-)


text:
Q: What is the distribution of Population I and II stars in the Milky Way galaxy? I have been trying to find out the distribution of Population I and II stars in the Milky Way. The distribution I mean is the percentage of each population to the total stars in the galaxy. So in other words, if the Milky Way contains 200 billion stars, how many of these have formed more than 10 billion years ago (Pop II stars) and how many have formed less than 10 billion years ago (Pop I stars) ?

A: This is difficult to answer in an unarguable way because the old bimodal classification of population I and II is more nuanced these days - e.g. thin disk, thick disk, bulge population etc. However, if you define population II as meaning those stars that were born in the first billion years of our Galaxy's evolution, then the following rough calculation gives an idea of the proportions.
Assume that all star are born according to the Salpeter mass function $n(M) = A M^{-2.3}$, where $M$ is in solar units and $A$ is some constant. Assume that the minimum mass is 0.1 and the maximum is 100.[There is however some evidence for initial mass function variations in our Galactic populations - Li et al. (2023) suggest that lower metallicity populations contain fewer low-mass stars, perhaps by a factor of two. Other mass functions are available, but using them is a bit more complicated and won't change the result beyond this and other uncertainties I'll mention.]
Assume that the star formation rate, $\Phi(t)$ has been uniform and began approximately 12 billion years ago . This is more difficult to justify. It is quite likely that the star formation rate was a lot higher at the beginning of the Galaxy's evolution - I'll discuss this assumption at the end. The star formation rate is  $\Phi(t)=C$ in units of stars per year. Assume that we are only looking at main sequence stars and that stars spend a negligible fraction of their lives off the main sequence (again, not quite right, but it will do here). Assume the main sequence lifetime is given by $10^{10} M^{-2.5}$ years, where $M$ is in solar units. Ignore white dwarfs.
The number of stars per unit mass that have been formed up to time $t$
$$ N(M) = \int^{t}_0 C n(M)\ dt = CAM^{-2.3}t $$
But if a star was born at $t$, then it will have lived and died if $t < 1.2\times10^{10} - 10^{10}M^{-2.5}$. For a uniform star forming rate, the fraction of stars of mass $M$ that are still alive at time $t$, $f(t) = (5/6)M^{-2.5}$.
So if the Galaxy is 12 billion years old, only stars with $M<0.93$ that were born right at the beginning are still alive. In addition, all pop II stars with $M>0.96M_{\odot}$ have died. These two limits are so close that we will assume there are a negligible number of stars between these masses.
For Pop I and Pop II stars with $M<0.93$, the ratio of Pop II/Pop I stars is just the ratio of their formation timescales,
because all that have been born are still alive - i.e. $N_{II}/N_{I} = 10^{9}/1.1\times10^{10} = 0.09$ and the total number of stars is
$$N(<0.93) = 1.2\times10^{10}CA \int_{0.1}^{0.93} M^{-2.3}\ dM = 1.74\times10^{11}CA$$
Now you might have thought that this number was an upper limit, because surely you have to add to the population I number, all the stars with $M>0.96$ that were born in the past and have not yet died. Well it turns out that number is small.
For pop I stars with $M>0.96$:
$${N_{I}} = \int_{0.96}^{100} 10^{10} CAM^{-2.3}\frac{5}{6}M^{-2.5}\ dM  = 3.1\times10^{9}CA $$
Even ignoring stellar lifetimes, the number of stars with $M>1$ is $7.7\times10^{9} CA$.
The final result is then that $N_{II}/N_{I} \sim 0.09$. To be more exact, it will be
$$N_{II}/N_{I} \simeq \frac{\int_{\tau_{II}} \Phi_{II}(t)\ dt}{\int_{\tau_{I}} \Phi_{I}(t) \ dt},$$
where $\tau_{I}$ and $\tau_{II}$ represent the periods over which the types of star were born and $\Phi(t)$ is the star formation rate at that time.
How sensitive is the calculation to variations in $\Phi$? It is likely that the star formation rate was actually much higher in the early Galaxy. Well, if the star formation rate was higher, then more high-mass stars would have been produced early on and these would have more rapidly enriched the ISM. Once the ISM is rich in metals then metal-poor stars cannot form. So there will be a trade-off (though probably not an exact one). $\Phi$ could have been bigger, but then $\tau_{II}$ would be smaller.
It is very difficult to accurately ascertain this number observationally, because the spatial distributions of the two populations is very different and we cannot directly tell the ages of stars by looking at them. Population II stars are more spherically distributed around the Galaxy, whilst population I stars are concentrated in the Galactic plane, where the Sun is. However, the bulge stars, whilst metal-rich are also probably very old - so do you include those? There is also an intermediate "thick disk" population with intermediate metallicities that probably formed over 2-3 billion years early on.
Thus when we look around us, the stars nearby are hugely dominated by Pop I stars by about 200:1 (here my definition is that Pop II stars are metal-poor; we cannot tell the age of a star by just looking at it!). Extrapolation of this using estimates of the density distribution of metal-poor stars suggests that halo population II contributes only a few percent of the stellar mass of the Galaxy. In turn, this suggests the formation epoch of population II stars lasted much less than 1 billion years. I'm trying to pin this number down a bit better, but the interpretation is confused by what is classified as Pop II,  what metallicity cut-off is used, and also by the possibility that our Galaxy halo might include populations due to a number of merger and accretion events, not all of which are metal-poor. Finally there is the question of the bulge. Roughly 20-25% of the stellar mass is here and it probably formed rapidly (about  billion years) at the beginning of the Galaxy. For the reasons I discussed above, such a period of intense star formation means that the ISM was enriched and most bulge stars have high metallicity.


text:
Q: Compare two folders which have many files inside contents Have two folders with approx. 150 java property files.
In a shell script, how to compare both folders to see if there is any new property file in either of them and what are the differences between the property files.
The output should be in a report format.

A: I used
diff -rqyl folder1 folder2 --exclude=node_modules

in my nodejs apps.

A: diff -r will do this, telling you both if any files have been added or deleted, and what's changed in the files that have been modified.

A: To get summary of new/missing files, and which files differ:
diff -arq folder1 folder2

a treats all files as text, r recursively searched subdirectories, q reports 'briefly', only when files differ

A: Could you use dircmp ?

A: Diff command in Unix is used to find the differences between files(all types). Since directory is also a type of file, the differences between two directories can easily be figure out by using diff commands. For more option use man diff on your unix box.
 -b              Ignores trailing blanks  (spaces  and  tabs)
                 and   treats  other  strings  of  blanks  as
                 equivalent.

 -i              Ignores the case of  letters.  For  example,
                 `A' will compare equal to `a'.
 -t              Expands <TAB> characters  in  output  lines.
                 Normal or -c output adds character(s) to the
                 front of each line that may adversely affect
                 the indentation of the original source lines
                 and  make  the  output  lines  difficult  to
                 interpret.  This  option  will  preserve the
                 original source's indentation.

 -w              Ignores all blanks (<SPACE> and <TAB>  char-
                 acters)  and  treats  all  other  strings of
                 blanks   as   equivalent.    For    example,
                 `if ( a == b )'   will   compare   equal  to
                 `if(a==b)'.

and there are many more.


text:
Q: How to pass variable (environment property) from CodeBuild to Beanstalk app in CodePipeline? I have a simple CodePipeline with three stages - source checkout, CodeBuild build docker image using buildspec.yml and producing Dockerrun.json artifact, and deploy to Beanstalk.
Now I want the application, which runs in the docker, to read a variable (environment property) set by CodeBuild stage during a build--a build number. How can I do that?
I have set APPLICATION_BUILDNUMBER variable in the buildspec.yml in pre_build:commands and listed it under exported-variables. It then appeared in AWS Console under CodeBuild Build status under Environment Variables tab under Exported environment variables with desired value.
Now how can I read it in my application running in docker in Beanstalk, which is a Spring Boot app (JAR)?
When I set the variable APPLICATION_BUILDNUMBER manually in Beanstalk > Configuration > Software >  Environment properties, I can read it easily. But I don't know, how to pass it from CodeBuild.

A: Taking a quick look at the configuration properties of an Elastic Beanstalk action 1, it cannot take an environment property from an external source.
A workaround can be to:
a. Set a SSM Parameter store variable from your CodeBuild action and then
b. Read the SSM parameter value in Elastic Beanstalk environment "hook" and export to the environment.
For a: Run this command from the CodeBuild buildspec:
$ aws ssm put-parameter --name "parameter-name" --type String --value "parameter-value"

For b:
You can deploy the hooks file in /opt/elasticbeanstalk/hooks/appdeploy/pre/ . Create the hook script via ebextension 'files' construct 2. A minimal hook script to get the secret from SSM or Secrets Manager and exporting the secret to system, would look like:
#!/usr/bin/env bash
set -e

export MySecret=$(aws ssm get-parameters ---blah --blah......... )

It goes without saying that CodeBuild service role and EC2 Instance role (used with EB) needs to have the required permissions:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssm:GetParameters",
                "ssm:GetParameter",
                "ssm:PutParameter",
                "secretsmanager:GetSecretValue",
                "kms:Decrypt"
            ],
            "Resource": [
                "arn:aws:ssm:*:*:*",
                "arn:aws:secretsmanager:*:*:*",
                "arn:aws:kms:*:*:*"
            ]
        }
    ]
}


text:
Q: Elasticsearch-Hadoop library cannot connect to to docker container I have spark job that reads from Cassandra, processes/transforms/filters the data, and writes the results to Elasticsearch.  I use docker for my integration tests, and I am running into trouble of writing from spark to Elasticsearch.
Dependencies:
"joda-time"              % "joda-time"          % "2.9.4",
"javax.servlet"          %  "javax.servlet-api" % "3.1.0",
"org.elasticsearch"      %  "elasticsearch"     % "2.3.2",
"org.scalatest"          %% "scalatest"         % "2.2.1",
"com.github.nscala-time" %% "nscala-time"       % "2.10.0",
"cascading"              %   "cascading-hadoop" % "2.6.3",
"cascading"              %   "cascading-local"  % "2.6.3",
"com.datastax.spark"     %% "spark-cassandra-connector" % "1.4.2",
"com.datastax.cassandra" % "cassandra-driver-core" % "2.1.5",
"org.elasticsearch"      %  "elasticsearch-hadoop"      % "2.3.2" excludeAll(ExclusionRule("org.apache.storm")),
"org.apache.spark"       %% "spark-catalyst"            % "1.4.0" % "provided"

In my unit tests I can connect to elasticsearch using a TransportClient to setup my template and index
aka. This works
val conf = new SparkConf().setAppName("test_reindex").setMaster("local")
  .set("spark.cassandra.input.split.size_in_mb", "67108864")
  .set("spark.cassandra.connection.host", cassandraHostString)
  .set("es.nodes", elasticsearchHostString)
  .set("es.port", "9200")
  .set("http.publish_host", "")
sc = new SparkContext(conf)
esClient = TransportClient.builder().build()
esClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(elasticsearchHostString), 9300))
esClient.admin().indices().preparePutTemplate(testTemplate).setSource(Source.fromInputStream(getClass.getResourceAsStream("/mytemplate.json")).mkString).execute().actionGet()
esClient.admin().indices().prepareCreate(esTestIndex).execute().actionGet()
esClient.admin().indices().prepareAliases().addAlias(esTestIndex, "hot").execute().actionGet()

However when I try to run
EsSpark.saveToEs(
  myRDD,
  "hot/mytype",
  Map("es.mapping.id" -> "id", "es.mapping.parent" -> "parent_id")
)

I receive this stack trace
org.elasticsearch.hadoop.rest.EsHadoopNoNodesLeftException: Connection error (check network and/or proxy settings)- all nodes failed; tried [[172.17.0.2:9200]]
at org.elasticsearch.hadoop.rest.NetworkClient.execute(NetworkClient.java:142)
at org.elasticsearch.hadoop.rest.RestClient.execute(RestClient.java:434)
at org.elasticsearch.hadoop.rest.RestClient.executeNotFoundAllowed(RestClient.java:442)
at org.elasticsearch.hadoop.rest.RestClient.exists(RestClient.java:518)
at org.elasticsearch.hadoop.rest.RestClient.touch(RestClient.java:524)
at org.elasticsearch.hadoop.rest.RestRepository.touch(RestRepository.java:491)
at org.elasticsearch.hadoop.rest.RestService.initSingleIndex(RestService.java:412)
at org.elasticsearch.hadoop.rest.RestService.createWriter(RestService.java:400)
at org.elasticsearch.spark.rdd.EsRDDWriter.write(EsRDDWriter.scala:40)
at org.elasticsearch.spark.rdd.EsSpark$$anonfun$saveToEs$1.apply(EsSpark.scala:67)
at org.elasticsearch.spark.rdd.EsSpark$$anonfun$saveToEs$1.apply(EsSpark.scala:67)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:89)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
16/08/08 12:30:46 WARN TaskSetManager: Lost task 0.0 in stage 2.0 (TID 2, localhost): org.elasticsearch.hadoop.rest.EsHadoopNoNodesLeftException: Connection error (check network and/or proxy settings)- all nodes failed; tried [[172.17.0.2:9200]]
at org.elasticsearch.hadoop.rest.NetworkClient.execute(NetworkClient.java:142)
at org.elasticsearch.hadoop.rest.RestClient.execute(RestClient.java:434)
at org.elasticsearch.hadoop.rest.RestClient.executeNotFoundAllowed(RestClient.java:442)
at org.elasticsearch.hadoop.rest.RestClient.exists(RestClient.java:518)
at org.elasticsearch.hadoop.rest.RestClient.touch(RestClient.java:524)
at org.elasticsearch.hadoop.rest.RestRepository.touch(RestRepository.java:491)
at org.elasticsearch.hadoop.rest.RestService.initSingleIndex(RestService.java:412)
at org.elasticsearch.hadoop.rest.RestService.createWriter(RestService.java:400)
at org.elasticsearch.spark.rdd.EsRDDWriter.write(EsRDDWriter.scala:40)
at org.elasticsearch.spark.rdd.EsSpark$$anonfun$saveToEs$1.apply(EsSpark.scala:67)
at org.elasticsearch.spark.rdd.EsSpark$$anonfun$saveToEs$1.apply(EsSpark.scala:67)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:89)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

I can verify using 'docker network inspect bridge that it is trying to connect to the correct ip address.
docker network inspect bridge
[
{
    "Name": "bridge",
    "Id": "ef184e3be3637be28f854c3278f1c8647be822a9413120a8957de6d2d5355de1",
    "Scope": "local",
    "Driver": "bridge",
    "EnableIPv6": false,
    "IPAM": {
        "Driver": "default",
        "Options": null,
        "Config": [
            {
                "Subnet": "172.17.0.0/16",
                "Gateway": "172.17.0.1"
            }
        ]
    },
    "Internal": false,
    "Containers": {
        "0c79680de8ef815bbe4bdd297a6f845cce97ef18bb2f2c12da7fe364906c3676": {
            "Name": "analytics_rabbitmq_1",
            "EndpointID": "3f03fdabd015fa1e2af802558aa59523f4a3c8c72f1231d07c47a6c8e60ae0d4",
            "MacAddress": "02:42:ac:11:00:04",
            "IPv4Address": "172.17.0.4/16",
            "IPv6Address": ""
        },
        "9b1f37c8df344c50e042c4b3c75fcb2774888f93fd7a77719fb286bb13f76f38": {
            "Name": "analytics_elasticsearch_1",
            "EndpointID": "fb083d27aaf8c0db1aac90c2a1ea2f752c46d8ac045e365f4b9b7d1651038a56",
            "MacAddress": "02:42:ac:11:00:02",
            "IPv4Address": "172.17.0.2/16",
            "IPv6Address": ""
        },
        "ed0cfad868dbac29bda66de6bee93e7c8caf04d623d9442737a00de0d43c372a": {
            "Name": "analytics_cassandra_1",
            "EndpointID": "2efa95980d681b3627a7c5e952e2f01980cf5ffd0fe4ba6185b2cab735784df6",
            "MacAddress": "02:42:ac:11:00:03",
            "IPv4Address": "172.17.0.3/16",
            "IPv6Address": ""
        }
    },
    "Options": {
        "com.docker.network.bridge.default_bridge": "true",
        "com.docker.network.bridge.enable_icc": "true",
        "com.docker.network.bridge.enable_ip_masquerade": "true",
        "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
        "com.docker.network.bridge.name": "docker0",
        "com.docker.network.driver.mtu": "1500"
    },
    "Labels": {}
}
]

I am running everything locally on a macbook/osx.  I am at a loss for why I can connect to the docker container using the TransportClient and through my browser, but the function EsSpark.saveToES(...) always fails.

A: By setting
.config("es.nodes.wan.only", "true")

can solve this issue

es.nodes.ingest.only
(default false) Whether to use Elasticsearch
  ingest nodes only. When enabled, elasticsearch-hadoop will route all
  of its requests (after nodes discovery, if enabled) through the ingest
  nodes within the cluster. The purpose of this configuration setting is
  to avoid incurring the cost of forwarding data meant for a pipeline
  from non-ingest nodes; Really only useful when writing data to an
  Ingest Pipeline (see es.ingest.pipeline above).


text:
Q: Trying to send more than one post - Result in POST 500 admin-ajax error I am able to send 1 post, which is the prompt and receive it well on the php side. But when i try to send more than one posts, it returns error 500 of admin-ajax.php.
What can be the issue? I am transferring the data via data: {} to the right action. Tested with one post, works perfectly well.
This the PHP:
// Register the translation Ajax action
add_action( 'wp_ajax_openai_completion', 'openai_completion' );
add_action( 'wp_ajax_nopriv_openai_completion', 'openai_completion' );
function openai_completion() {
  $prompt = $_REQUEST['prompt'];
  // $pass = $_REQUEST['password'];

  // if ($pass == "avielchik") {

    $client = OpenAI::client(API_KEY);
    $result = $client->completions()->create([
      'model' => 'text-davinci-003',
      'prompt' => $prompt,
      "max_tokens" => 256,
      "temperature" => 0.3,
      'stream' => true
    ]);

  // }
  // else {

  //   $result['type'] = 'Failure.';
  //   $result['choices'] = 'Walk away.' + $_POST['password'];

  // }

  $result = json_encode($result);
  echo $result;
  die();

}


text:
Q: How to control databases replicated by Mongo DB replica set I have 2 databases in my mongo DB namespace, lets name them db1, db2 and db3 which are on the same dbpath.
Is it possible to configure mongo db replica set in that way that db3 wont be replicated across secondaries?
If yes, how?

A: No, to the best of my knowledge this is not possible. A replica set member is identified by a hostname and port, and there are no settings to control which databases are included. See Replica Set Configuration in the MongoDB manual.
You could create a separate MongoDB server instance configured on a different port (and using a different dbpath) to hold the db3 data, although this would obviously complicate your server setup.

A: MongoDB replication is handled by host and port, which is per-mongod-process.
The way to do this would be to run db3 run in another mongod process, which runs on a different tcp port.


text:
Q: How to make code execute automatically every minute in asp.net mvc5 my websites I have this code I have done using the application console and I want to use it inside my website using asp.net mvc5 in order to store the data it brings from the RSS feeds and store it in a database
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using CodeHollow.FeedReader;
using CodeHollow.FeedReader.Feeds;
using System.Data;
using System.Data.SqlClient;
using System.Data.Entity.Core;
using System.Data.Entity.Infrastructure;

namespace RssFeedBackEnd
{

public class Program
{
    public static void Main(string[] args)
    {

        RssFeedDB db = new RssFeedDB();

        var qry = (from c in db.Links select c);

        foreach (var li in qry)
        {
            try
            {

                var feed = FeedReader.Read(li.adressLink);

                var item = feed.Items;

                if (feed.Type.ToString() == "Rss_2_0")
                {

                    //New n = new New();
                    foreach (var items in item)
                    {
                        string v = items.Id;
                        int h = validate(v);

                        if (h == 0)
                        {
                            try
                            {

                                New n = new New();

                                n.TitleNews = items.Title;
                                n.LinkNews = items.Link;
                                n.TitlePage = feed.Title;
                                n.LinkPage = feed.Link;
                                n.Linkimg = items.SpecificItem.Element.Element("enclosure").Attribute("url").Value;
                                n.IDurl = items.Id;
                                n.Pubdate = DateTime.Now;
                                n.EntryTime = DateTime.Now;
                                n.Description = items.Description;
                                n.IdCatogrey = li.CategorayID;
                                //n.NameCatogrey = li.Category.NameCategory.ToString();
                                db.News.Add(n);

                            }
                            catch { }

                        }
                    }

                }

            }

            catch { }
        }
        db.SaveChanges();

    }

      static int  validate(string n) {

        int a = 0;

        RssFeedDB db = new RssFeedDB();

        var qry = (from m in db.News select m);

        foreach (var nws in qry)
        {
            if (nws.IDurl == n) { a =1; break; }
        }

        return a;

    }
 }}

I hope to help me how to put it inside the web application and do his work every minute .
The idea of my project is to fetch data (news) from RSS feeds links and store them in the database to display on my website.
I hope I've shown you very well what I want to do.

A: A web application is fundamentally unsuited for this type of task. A website's job is to respond to requests from others (usually people, via browsers) as and when they occur. It does not run automatically at specific times.
To achieve your goal, on your server you need either a Windows Service with a timer in it (which then executes the necessary code every time the timer expires), or a Windows Scheduled Task which triggers a specific application at regular intervals.
Since you already have a Console application which does the job you need, then the simplest solution for you is probably to set up a Windows Scheduled Task which executes the console application regularly.
N.B. You can of course still have a separate website which can display the data that the console application has saved in the database.

P.S. There are extensions to ASP.NET such as Hangifire and Quartz.NET which can add scheduling capabilities to a web application, but they are probably overkill for what you want to do in this case.


text:
Q: Keeping track after the back button I want to write a web app order system using the REST methodology for the first time. I understand the concept of the "message id" when things get posted to a page but this scenario comes up. Once a user posts to the web app, you can keep track of their state with an id attached to the URI but what happens if they hit the back button of the browser to the entry point of the app when they didn't have any id? They then lose their state in the transaction.
I know you can always give them a cookie but you can't do that if they have cookies turned off and, worst case thinking here, they also have javascript turned off.
Now, I understand the answer may be "Yes, that's what will happen", that's the end of the story, and I can live with that but, being new to this, is there something I'm missing?

A: REST doesn't really have states server-side; you simply point to resources. User sessions aren't tracked; instead cookies are used to track application state. However, if you find that you really do need session state, then you are going to have to break REST and track it on the server.
A few things to consider:

*

*How many of your users have cookies disabled anyway? How many even know how to do that?

*Is it really likely that your users will have JS turned off? If so, how will you accomplish PUT (edit) and DELETE (delete) without AJAX?

EDIT: Since you do not want to force cookies and JavaScript, then you cannot have a truly RESTful system. But you can somewhat fake it. You are going to need to track a user server-side. You could do this with a session object, as found in your language/framework of choice or by adding a field to the database for whatever you want to know. Of course, when the user hits the back button, they will likely be going to a cached page. If that's not OK, then you will need to modify the headers to disallow caching. Basically, it gets more complicated if you don't use cookies, but not unmanageable.
What about the missing PUT and DELETE HTTP methods? You can fake those with POSTs and a hidden parameter specifying whether or not you are making something new, editing something, or deleting a record. The GET shouldn't really change.

A: The answer is that your application (in a REST scenario) simply doesn't keep track of what happens. All state is managed by the client, and state transitions are effected through URI navigation. The "State Transfer" part of REST refers to client navigation to new URIs which are new states.
A URI accessed with GET is effectively a read-only operation as per both the HTTP spec and the REST methodology. That means if the client "backs up" to some previous URI, "the worst" that happens is another GET is made and more data is loaded.
Let's say the client does this (using highly simplified pseudo-HTTP)...
GET //site.com/product/123
This retrieves information (or maybe a page) about product ID 123, which presumably includes a reference to a URI which can be used to POST that item into the user's shopping cart. So the user decides to buy the item. Again, it's oversimplified but:
POST //site.com/shoppingcart/
{productid = 123}
The return from this might be a representation of the shopping cart, or a reference to the added item (which could be used on the shoppingcart URI with DELETE to remove the item again), or a variety of other things (such as deeper XML describing the cart contents with other URIs pointing to the cart items and back to the original products). It's all up to you.
But the "state" is defined by whatever the client is doing. It isn't tracked on the server at all, although you will certainly keep a copy of his shopping cart contents in your database for some period of time. (I once returned to a website two years later and my shopping cart items were still there...) But it's up to him to keep track of the ID. To your server app it's just another record, presumably with some kind of expiration.
In this way you don't need cookies, and javascript is entirely dependent on the client implementation. It's difficult to build a decent REST client without script -- you could probably build something with XSLT and only return XML from the server, but that's probably more pain than anyone needs.
The starting point is to really understand REST, then design the system, then build it. It definitely doesn't lend itself to building it on the fly like most other systems do (right or wrong).
This is an excellent article that gives you a fairly "pure" look at REST without getting too abstract and without bogging you down with code:
http://www.infoq.com/articles/subbu-allamaraju-rest

A: It is true that the "S" in REST stands for "state" and the "T" for "transfer". But the state is is kept on the client, not on the server. The client always hast all information necessary to decide for himself in whicht direction he wants to change the state.
The way you describe it, your system is not restful.


text:
Q: как с помощью JSOUP получить всех родителей заголовка у меня есть хтмл документ

Во Франции по подозрению в планировании теракта задержали двух девушек

                            Понедельник, 26 сентября 2016, 16:08

Во французском городе Ницца по подозрению в планировании теракта были задержаны двое девушек.

Об этом сообщает AFP.

Девушки в возрасте 17 и 18 лет подозреваются в планировании террористического нападения под руководством французского джихадиста Рашида Кассима.

Подростки рассказали следователям, что они планировали нападение под влиянием Рашида Кассима, который сейчас находится в Сирии или Ираке, на территории, которая контролируется террористической организацией "Исламское государство".

Рашид Кассим, по мнению следователей, играет роль подстрекателя или спонсора, фактически призывая потенциальных террористов к совершению джихада во Франции.

Стоит добавить, что во время обыска в помещениях, которые принадлежат задержанными, стражи порядка не нашли оружия.

Издание отмечает, что девушки живут в том же районе, что и Мохамед Лахуайедж-Бухлель, убивший 86 человек в Ницце 14 июля.

Напомним, недавно французская полиция задержала подростка, подозреваемого в подготовке теракта в Париже.

ЧИТАЙ ТАКЖЕ

с помощью JSOUPa я хотел получить всех "родителей" заголовка
Element element = Jsoup.parse(html).getElementsByClass("title").parents().last();
System.out.println(element);

В консоли я получил тот же HTML документ. Но мне нужно получить только "родителей" заголовка. без лишних тегов например вот так:

ЗАГОЛОВОК СТАТЬИ

Что можно с этим сделать?
И еще вопрос: как найти заголовок тег заголовка есть он будет называться не "title" , а как то по другому на пример : "head_article". так как парсить HTML я буду с разных сайтов.

A: Основываясь только на данном примере всё просто:

*

*берем элемент, в который входит заголовок

*заменяем его содержимое на html заголовка с текстом (первого потомка сего блока)

String html = "\n" +
        "    \n" +
        "    \n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
Во Франции по подозрению в планировании теракта задержали двух девушек
\n" +
        "                            Понедельник, 26 сентября 2016, 16:08\n" +
        "
\n" +
        "
Во французском городе Ницца по подозрению в планировании теракта были задержаны двое девушек.
\n" +
        "
Об этом сообщает AFP.
\n" +
        "
Девушки в возрасте 17 и 18 лет подозреваются в планировании террористического нападения под руководством французского джихадиста Рашида Кассима.
\n" +
        "
Подростки рассказали следователям, что они планировали нападение под влиянием Рашида Кассима, который сейчас находится в Сирии или Ираке, на территории, которая контролируется террористической организацией "Исламское государство".
\n" +
        "
Рашид Кассим, по мнению следователей, играет роль подстрекателя или спонсора, фактически призывая потенциальных террористов к совершению джихада во Франции.
\n" +
        "
Стоит добавить, что во время обыска в помещениях, которые принадлежат задержанными, стражи порядка не нашли оружия.
\n" +
        "
Издание отмечает, что девушки живут в том же районе, что и Мохамед Лахуайедж-Бухлель, убивший 86 человек в Ницце 14 июля.
\n" +
        "
Напомним, недавно французская полиция задержала подростка, подозреваемого в подготовке теракта в Париже.
\n" +
        "
\n" +
        "
ЧИТАЙ ТАКЖЕ
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
Во Фsdfsdfsfх девушек
\n" +
        "                            Понедельник, 26 сентября 2016, 16:08\n" +
        "
ЧИТАЙ ТАКЖЕ
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "
\n" +
        "    \n" +
        "";

// загрузка html
Document document = Jsoup.parse(html);
// берем все элементы в который входит title
Elements els = document.select(".rpad");
// пробегаясь по всем ним, меняем внутри html
// child(0) - как раз html заголовка
for (Element el : els) {
    el.html(el.child(0).toString());
}

System.out.println(document);

Этот код в итоге выведет

Во Франции по подозрению в планировании теракта задержали двух девушек

Во Фsdfsdfsfх девушек

А без знаний критерий отбора с постоянно разным html, постоянно разным тегом для заголовка с постоянно разной степенью вложенности заголовка с постоянно разным классом (а может и отсутствием оного) у тега с заголовком и вообще каких-либо конкретных критериев поиска - сделать можно только разве что с помощью искусственного интеллекта


text:
Q: numpy where: add value where I have this data frame:
           ticker                   value short
0  APPL US Equity    Quarterly and Annual
1  TTMT IN Equity    Quarterly and Annual
2   BUD US Equity  Semi-Annual and Annual
3    PS US Equity                  Annual

I want this:
           ticker                   value short
0  APPL US Equity    Quarterly and Annual
1  TTMT IN Equity    Quarterly and Annual
2   BUD US Equity  Semi-Annual and Annual
3    PS US Equity                  Annual  A

here is my attempt:
dfx['short'] = dfx[np.where(dfx['value'].strip() == 'Annual','A'
                                    ,dfx['short'])]

this works:
dfx['short'] = np.where(dfx['value'] == 'Annual','A',dfx['short'])

A: You can set a only part of the values in a column with .loc:
mask = dfx['value'].strip() == 'Annual'
dfx.loc[mask, 'short'] = 'A'


text:
Q: F#: For MathNet Numerics the value or constructor matrix is not defined I'm trying to learn F#, and to create a matrix I follow the instructions from here: http://numerics.mathdotnet.com/
module Gew.M
open MathNet.Numerics
open MathNet.Numerics.LinearAlgebra

let matrix1 =   matrix [[1.0; 2.0]; [1.0; 3.0]]
let matrix2 =  matrix [[1.0; -2.0]; [0.5; 3.0]]
let matrix12 = matrix1 * matrix2

Then I get this error: the value or constructor matrix is not defined

A: Read carefully:

Even though the core of Math.NET Numerics is written in C#, it aims to
  support F# just as well. In order to achieve this we recommend to
  reference the MathNet.Numerics.FSharp package in addition to
  MathNet.Numerics, which adds a few modules to make it more idiomatic
  and includes arbitrary precision types (BigInteger, BigRational).

So, you have to add a reference to MathNet.Numerics.FSharp
Example:
open MathNet.Numerics.LinearAlgebra

let matrix1 =   matrix [[1.0; 2.0]; [1.0; 3.0]]
let matrix2 =  matrix [[1.0; -2.0]; [0.5; 3.0]]
let matrix12 = matrix1 * matrix2

matrix12 |> printfn "%A"

Print:
DenseMatrix 2x2-Double
  2  4
2.5  7

Link:
https://dotnetfiddle.net/6NSti7


text:
Q: Word - Excel table caption I have added a table from Excel to Word. The table is too large for one page and is divided into two pages. Now when I add a caption, this is only displayed at the top of page 1, but nothing on page 2. How can I edit it so I can put something like
"Page1"
Table1: Sales
(table)
*Page2*
**++Table1: Sales (continued)++**
(table continues)

A: Its a bit of a cludge, but you can put the caption in the first row of the table itself, and turn on "Repeat as header row at top of each page".
Merge all cells and turn off borders in the first row, caption then looks like its outside the table.
Easy way to get the caption into the table is to insert it normally, then cut and paste it into the table.

A: Use Headers inplace of caption. Use a different header for the first page and yet another one for the 2nd page. Use page numbers in the format "page x of y" in the fotter to make it more accesible.
You may also make the single table as two tables. If your single table is too large, to fit in one page vertically, word will put it in 2 or more pages. This however will not result in the repeating of the caption or even the column headers. This obtion is however available in Excel where you go to page setup and select the rows and columns to repeat at the top.
When u break you single table into two tables, one for each page you can customize the caption for each table seperately. You can also than repeat the column headers.


text:
Q: Jersey - Proxy Authenitcation in version 1.14 I am trying to configure proxy settings with Authentication for Jersey Rest client. Initially, I was using the following code that worked fine with proxy that does not require authentication
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);

However, if a proxy required authentication it did not work.
I tried using Jersey Apache http client with HttpClient 4.2.1 from HttpComponents project with the following code snippet.
final ApacheHttpClientConfig config = new DefaultApacheHttpClientConfig();
Map<String, Object> configProp =  config.getProperties();
final String proxyHost = System.getProperty("http.proxyHost");
final String proxyPort = System.getProperty("http.proxyPort");

if(proxyHost != null && proxyPort != null){
        configProp.put(DefaultApacheHttpClientConfig.PROPERTY_PROXY_URI, "http://" + proxyHost + ":" + proxyPort);

        final String proxyUser = System.getProperty("http.proxyUser");
        final String proxyPassword = System.getProperty("http.proxyPassword");
        if(proxyUser != null && proxyPassword != null){
             ApacheHttpClientState state = config.getState();
             state.setProxyCredentials(AuthScope.ANY_REALM, proxyHost, Integer.parseInt(proxyPort), proxyUser, proxyPassword);

        }
}

It throws "ClassNotFoundException" error at config.getState(). It looks like path for Credentials class in HttpClient has changed and jersey Apache Http Client cannot find the Credentials class.
So, my question is "Is there a different way of handling proxy authentication in recent versions of Jersey or Jersey in General? Am I doing it wrong?"
Thanks

A: Try giving it as -D jvm parameters.

A: Ok There seems to be a dependency problem between Jersey Apache Client library and HttpComponents HttpClient library. I used Commons HttpClient library with Jersey Apache Client library and it worked perfectly fine.


text:
Q: Is there a way to see how small caps of an OTF should look like? I am in the dilemma of convertig an OTF for the use with PDFlatex and I am making good progress with the German description at https://www.mrunix.de/forums/showthread.php?67058-(verh%E4ltmism%E4ssig)-einfache-Schriftinstallation-unter-Miktex-2-8 so far. The font I try to convert is a corporate font, which is not publicly available and hence I am sorry that I can only provide analysis, not the actual piece of evidence. ;-)
The conversion of normal and italics in 5 font weights went great. However now there seems to be an issue with the small caps of my font. Using otfinfo -f $FONTNAME$.otf results in:
aalt    Access All Alternates
case    Case-Sensitive Forms
dnom    Denominators
frac    Fractions
kern    Kerning
liga    Standard Ligatures
numr    Numerators
ordn    Ordinals
pnum    Proportional Figures    Proportionale Zahlen
sinf    Scientific Inferiors
smcp    Small Capitals  Small caps
sups    Superscript Tabellenzahlen
tnum    Tabular Figures

So it seems small caps are available, but converting it with otftotfm -n $FONTNAME$-LightSC --vendor=Fontvendor --typeface=Fontface -f liga -f kern -f onum -f smcp -e texnansx --map-file=./output/$FONTNAME$.map --directory=./output/ $FONTNAME$.otf gives me the binary exact same vf and tfm files. To confirm, that my commands are right, I replace $FONTNAME$.otf with LinBiolinum_R.otf because I know, this font actually has small caps.
So my question is, is there a way (with an editor or simple tool), so see how each character in my font looks, to see whether small caps are just mapped to lower case letters? If anybody has an idea, what else I might be wrong, please tell me!


text:
Q: Like button change with transition effect I am creating like or thumbs up button and i want to add some transition effect, kinda like short fade in fade out effect on icon change, where on click icon will disappear or fadeout and then new icon will fade in and whole animation will be 0.6s-0.8s top. Icons are font-awesome icons.
This is what i got so far https://jsfiddle.net/2Lzo9vfc/11/
HTML

This is post 1

0 <button class="like-button"></button>

This is post 2

0 <button class="like-button"></button>

CSS
h3 {
    display: inline-block;
    font-size: 12px;
    text-transform: uppercase;
    font-weight: bold;
    margin-right: 15px;
}

button {
    background: none;
    border: 1px solid black;
    color: black;
    text-transform: uppercase;
    font-size: 12px;
    padding: 5px 10px;
}

.like button {
    border: none;
}

JS
$('.like-button').each(function() {
  $(this).click(function() {
    $(this).children('i').removeClass('fa-thumbs-o-up').addClass('fa-thumbs-up');
  });
})

A: You can use promise().done() to have the class changed after the fadeout is complete, and then fade in immediately after the class is changed.
$('.like-button').each(function () {
    $(this).click(function () {
        $this = $(this).children('i');
        $this.fadeTo(600, 0).promise().done(function () {
            $this.removeClass('fa-thumbs-o-up').addClass('fa-thumbs-up').fadeTo(600,1);
        });
    });
})

A: in css
.like-button i {
  transition:1s all ease;
}


text:
Q: Facebook api authentication PHP In my siteweb I'm implementing authentication with Facebook API.
<fb:login-button onlogin="fbLoginEvent(arguments)">Enter with Facebook</fb:login-button>

My function fbLoginEvent:
function fbLoginEvent( args ) {
    //console.log( "fbLogin", args );
    //var session = FB.getSession();
    var session = FB.getAuthResponse();
    if (session) {
        fbCheckSession(session, function(data) {
            if (data.result) {
            fbLoginNow();
    } else {
            $('#facebook-register').data("overlay").load();

    }
         });
}
}

And my function for check the session:
var fbLogin = { status: false, uid: 0, access_token: "" };

function fbCheckSession( session, callback ) {
    if ( session && $.type(callback) == "function" ) {
    ajaxCall( "facebook", "check_session", {uid: session.uid, token: session.access_token}, function(data){
        if ( data.result ) {
        fbLogin.status = true;
        fbLogin.fbuid = session.uid;
        fbLogin.uid = data.info.id;
        fbLogin.access_token = session.access_token;
            callback( { result: true, info: { name: data.info.name, fbLogin: fbLogin } } );
            } else {
        callback( { result: false } );
            }
    });
}
}

I made various checks and I have noticed that uid and tokens value are empty.
Any solution?
Thk

A: You made a mistake by assigning session variable to FB.getAuthResponse function of JS-SDK
Use
var session = FB.getAuthResponse();

Instead of
var session = FB.getAuthResponse

You also using incorrect properties names, authResponse use the same format as FB.getLoginStatus not in format returned by getSession of previous version of JS-SDK.
uid named userID, and access_token is accessToken


text:
Q: Finding specific day in month SQL I am trying to find a specific days within specific months for DST settings.  I found code from another post.
SELECT
DATEADD(day,DATEDIFF(day,'19000107',DATEADD(month,DATEDIFF(MONTH,0,GETDATE()/*YourValuehere*/),30))/7*7,'19000107')

I also found this in another post which could be used a month ahead.
SELECT DATEADD(day,-1 - (DATEPART(weekday, @StartOfMarch) + @@DATEFIRST - 2) % 7,
           @StartOfMarch
          ) AS LastSunday

I am not great with SQL so I am looking for a dummy explanation of what is happening here, and why this code works.  From what I gather, Jan 07 1900 is significant in here as is the various built in date time functions. A simple play-by-play breakdown would help me understand what all is happening.
This is for the SQL Server 2016.

A: Well, since 2012 version there is a built in function to get the end of the month for any date / datetime value called EOMONTH.
Using this function with DATEPART and DATEADD is quite a simple way to get the date of the last sunday in any given month:
DECLARE @Date datetime = GETDATE();
SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, EOMONTH(@Date)), EOMONTH(@Date)) As LastSundayDate

Result:
LastSundayDate
30.04.2017 00:00:00

Another example:
SET @Date = DATEADD(MONTH, -1, GETDATE());
SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, EOMONTH(@Date)), EOMONTH(@Date)) As LastSundayDate;

Result:
LastSundayDate
26.03.2017 00:00:00

Update
As SqlZim wrote in his comment, this relies on setting the first day of the month at sunday (using set datefirst 7; before using this query.

A: If you are interested, I'll often use a Table-Valued-Function to create dynamic date/time ranges.  A tally/calendar table would do the trick as well.  However, with a UDF, you can supply Date/Time Range, DatePart and Increment.
Also, being a TVF, it is easy to incorporate into a Sub-Query, Cross Join, etc.
In your case, if you are looking for the last Sunday in March and October
Example
Select D=Max(RetVal)
 From [dbo].[udf-Range-Date]('2017-01-01','2017-12-31','DD',1)
 Where DateName(WEEKDAY,RetVal) = 'Sunday'
   and DatePart(MONTH,RetVal) in (3,11)
 Group By Year(RetVal),Month(RetVal)

Returns
D
2017-03-26
2017-11-26

The UDF if Interested
CREATE FUNCTION [dbo].[udf-Range-Date] (@R1 datetime,@R2 datetime,@Part varchar(10),@Incr int)
Returns Table
Return (
    with cte0(M)   As (Select 1+Case @Part When 'YY' then DateDiff(YY,@R1,@R2)/@Incr When 'QQ' then DateDiff(QQ,@R1,@R2)/@Incr When 'MM' then DateDiff(MM,@R1,@R2)/@Incr When 'WK' then DateDiff(WK,@R1,@R2)/@Incr When 'DD' then DateDiff(DD,@R1,@R2)/@Incr When 'HH' then DateDiff(HH,@R1,@R2)/@Incr When 'MI' then DateDiff(MI,@R1,@R2)/@Incr When 'SS' then DateDiff(SS,@R1,@R2)/@Incr End),
         cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cte2(N)   As (Select Top (Select M from cte0) Row_Number() over (Order By (Select NULL)) From cte1 a, cte1 b, cte1 c, cte1 d, cte1 e, cte1 f, cte1 g, cte1 h ),
         cte3(N,D) As (Select 0,@R1 Union All Select N,Case @Part When 'YY' then DateAdd(YY, N*@Incr, @R1) When 'QQ' then DateAdd(QQ, N*@Incr, @R1) When 'MM' then DateAdd(MM, N*@Incr, @R1) When 'WK' then DateAdd(WK, N*@Incr, @R1) When 'DD' then DateAdd(DD, N*@Incr, @R1) When 'HH' then DateAdd(HH, N*@Incr, @R1) When 'MI' then DateAdd(MI, N*@Incr, @R1) When 'SS' then DateAdd(SS, N*@Incr, @R1) End From cte2 )

    Select RetSeq = N+1
          ,RetVal = D
     From  cte3,cte0
     Where D<=@R2
)
/*
Max 100 million observations -- Date Parts YY QQ MM WK DD HH MI SS
Syntax:
Select * from [dbo].[udf-Range-Date]('2016-10-01','2020-10-01','YY',1)
Select * from [dbo].[udf-Range-Date]('2016-01-01','2017-01-01','MM',1)
*/


text:
Q: JMeter - I need to pass a parameter called "Cookie" in the request header I am using apache jmeter 5.2.1 with Java 8 to perform the performance test in a JSF application.
I need to send in the header of an HTTP request a parameter called "Cookie" according to the example below:

I've tried several things but none work.
I have already used the HttpHeaderManager resource but apparently the word "Cookie" is a JMeter reserved word so I can't create a parameter in the Header with the name "Cookie".
If I create a parameter in HttpHeaderManager with any name it is appended to the request header, but if I create with the name "Cookie" which is the name I need to use JMeter simply ignore it and do not add it to the request header .
I saw many posts indicating that I used the following code snippet:
CookieManager manager = sampler.getCookieManager();
Cookie cookie = new Cookie("JSESSIONID",vars.get("jSessionId"),"${serveraddress}",false,0);
manager.add(cookie);

I've tested it but it doesn't work either, it returns the following error whenever I try to use it:

I also have an Http Cookie Manager but its value is sent in the request body and not in the header.
I also tried to use the Http Autorization Manager as I saw in some posts but it only works when the login is done at a prompt in the browser.
Can someone help me?

A: Just add a HTTP Cookie Manager to your Test Plan and it will automatically "manage" cookies for you (the HTTP Request samplers must be in the HTTP Cookie Manager's scope)
You can double check that JMeter sends correct Cookie header using a 3rd-party sniffer tool like Wireshark or Fiddler
If you added the HTTP Cookie Manager but JMeter still doesn't send the JSESSIONID cookie it might be the case there is a problem with the cookie itself, i.e. it doesn't match domain/path or expired or your HTTP Request sampler configuration is not correct.
If you absolutely sure that your application behaves as expected you can configure JMeter to be less restrictive by:

*

*Choosing a more "relaxed" cookie policy, i.e. netscape

*Adding the next line to user.properties file:
CookieManager.check.cookies=false

*You can also add the next line to log4j2.xml file:
<Logger name="org.apache.jmeter.protocol.http.control" level="debug" />

this way you will get comprehensive information of the Cookie Manager's behaviour in the jmeter.log file
More information: HTTP Cookie Manager Advanced Usage - A Guide


text:
Q: Всем привет. Решил помочь матери и написать программу, типа 1с, но не знаю с чего начать. Может есть у кого советы? Изучают java. Сама программа думаю будет простая, единственному юзеру. Связанная с сырьем и после приходит на кухню и делается калькуляционная карта на будку хлеба и тд. И после посчитать сколько вышло продукции и остаток на складе.

A: Сам сейчас занимаюсь подобным. Первое что советую сделать, хорошо обсудить все требования к ПО. Изучи БД, MySQL например. Потом тебе нужен будет UI. Для UI на Java я использую JavaFX. Но посмотри сам, не один только JavaFX используется для UI. Ну а дальше по чучуть: добавил форму ввода, сохранил в базу, написал логику. Заведи тетрадь/файл записывай задачи, начинай их поэтапно реализовывать. Постепенно будут возникать вопросы, ищи ответы в google/stackoverflow. Будешь задавать тут вопросы, посмотри предварительно, чаще всего ответы уже есть. Если нет, старайся дать как можно больше информации, но при этом лаконично излагай.
P.S. Я не знаю твой уровень знаний, но на всякий случай посоветую использовать ООП. Когда то я взялся писать desctop приложение, вся логика была в 2-4 классах, огромная масса кода, дублирование кода и т.д. Это может здорово затормозить разработку и отбить желание. Удачи!


text:
Q: Find the correlation coefficient of X and Y Suppose X and Y have a joint pdf f(x,y)=x+y, 0<x<1, 0<y<1
Find p(x,y) (rho) aka the correlation coefficient of X and Y.
ρ=Cov(Z,X)/σZσX = {E(XY)-E(X)E(Y)}/{sqrt(Var(X))*sqrt(Var(Y)}

A: Cov(X,Y) = E(XY)-E(X)E(Y)
Find E(XY) by double integral of joint pdf to get value of 1/3.
Joint pdf f(x,y) --> Used to find marginal pdf f(x) and f(y).
f(x) is used to find E(X), E(X^2), and Var(X).
f(y) is used to find E(y), E(Y^2), and Var(Y).
By symmetry, E(X)=E(Y), E(X^2)=E(Y^2), and Var(X)=Var(Y).
Now we can solve the equation for (rho) p(x,y) to find the correlation coefficient.


text:
Q: How to color max. 2 consecutive values in Excel without using VBA? I'm out of idea how I could format consecutive same (respectively only even) values in Excel tables without using VBA.
The conditional formatting shall color only consecutive values and only
all 0s or all even values, when there are not more than 2.

A: ID
B: binary
C: counting

1
1
1

2
0
2

3
0
2

4
1
3

5
0
4

6
0
4

7
0
4

8
1
5

9
1
5

I tried to format with: =COUNTIF(C1:C9, C1) < 3, but then it also colors the 1s and C6:C7, eventho there are more than 2.
I also tried =AND( COUNTIF(C1:C9,C1) < 3, ISEVEN(C1:C9) ) but then it colors nothing.
I could replace the 0s with empty cells so I could check ISEMPTY(B1:B9) but it again colors nothing. Using $ to set absolute changes nothing as well.
Formating duplicates also colors triplets, which also doesn't work for me.
=OR(COUNTIF($C$1:$C$9,C1) = 1, COUNTIF($C$1:$C$6,C1) = 2) works so far, but also colors the 1s (uneven).
=AND(OR(COUNTIF($C$1:$C$9,C1) = 1, COUNTIF($C$1:$C$6,C1) = 2), ISEVEN($C$1:$C$9)) doesn't work.
=AND(OR(COUNTIF($C$1:$C$9,C1) = 1, COUNTIF($C$1:$C$6,C1) = 2), $B$1:$B$9 <> 1) doesn't work as well.
My only solution so far is using 2 formating rules:

*

*color =OR(COUNTIF($C$1:$C$9,C1) = 1, COUNTIF($C$1:$C$6,C1) = 2)

*do not color =$B$1:$B$9 = 1
but I think it is terrible.
I worked on it for some hours, maybe I'm missing something really obvious.
I'm not allowed to use VBA, therefore this is ot an option.
EDIT: My 2.rule-solution can be simplificed with:

*

*color =COUNTIF($C$1:$C$9,C1) < 3

*do not color =$B$1:$B$9 = 1
I'm still confused why combining both doesn't work:
AND(COUNTIF($C$1:$C$9,C1) < 3; $B$1:$B$9 <> 1)
EDIT2: I know why it didn't work. Don't check <>1 with absolute value-range $B$1$:$B$9
Solution: B1 <> 1 then it loops through.
Now combining both works:
=AND( COUNTIF($C$1:$C$9, C1) < 3, B1 <> 1)

A: I can't see an easy answer for the binary numbers. You have two cases:
(1) Current cell is zero, previous cell is 1, next cell is zero and next cell but one is 1.
(2) Current cell is zero, previous cell is zero, previous cell but one is 1, next cell is 1.
But then the first pair of numbers is a special case because there is no previous cell.
Strictly speaking the last pair of numbers is a special case as well because there is no following cell.
=OR(AND(ROW()=1,B$1=0,B$2=0,B$3=1),AND(ROW()=2,B$1=0,B$2=0,B$3=1),AND(B1=0,B1048576=1,B2=0,B3=1),AND(B1=0,B1048576=0,B1048575=1,B2=1))

where I have used the fact that you are allowed to wrap ranges to the end of the sheet (B1048576) in conditional formatting.

Adding the condition for the case where there there are two zeroes at the end of the range:
=OR(AND(ROW()=1,B$1=0,B$2=0,B$3=1),
AND(ROW()=2,B$1=0,B$2=0,B$3=1),
AND(B1=0,B1048576=1,B2=0,OR(B3=1,B3="")),
AND(B1=0,B1048576=0,B1048575=1,OR(B2=1,B2="")))

Even this could go wrong if there was something in the very last couple of rows of the sheet, so I suppose to be absolutely safe:
=OR(AND(ROW()=1,B$1=0,B$2=0,B$3=1),
AND(ROW()=2,B$1=0,B$2=0,B$3=1),
AND(Row()>1,B1=0,B1048576=1,B2=0,OR(B3=1,B3="")),
AND(Row()>2,B1=0,B1048576=0,B1048575=1,OR(B2=1,B2="")))

Shorter:
=OR(AND(ROW()<=2,B$1+B$2=0,B$3=1),
AND(B1+B2=0,B1048576=1,OR(B3=1,B3="")),
AND(B1+B1048576=0,B1048575=1,OR(B2=1,B2="")))

A: Not the cleanest wat but it works. You only need to move your data 1 row below, so headers would be in row 2 and data in row 3 for this formula to work:
=IF(AND(B3=B4,B3<>B5),IF(AND(B4=B3,B4<>B2),TRUE,FALSE),IF(AND(B3=B2,B3<>B1),IF(AND(B3=B4,B3<>B5),FALSE,TRUE),FALSE))

A: How about this approach (Office 365):
=LET(range,B$1:B$9,
     s,IFERROR(TRANSPOSE(INDEX(range,ROW()+SEQUENCE(5,,-2))),1),
     t,TEXTJOIN("",,(s=INDEX(range,ROW()))*ISEVEN(s)),
IFERROR(SEARCH("0110",t)<4,IFERROR(SEARCH("010",t)=2,FALSE)))

It creates an array s of 5 values starting point is the current row of the range, adding the 2 values above and below. If the value is out of range it will replace the error with a 1.
The array s is checked for being even (TRUE/FALSE, IFERROR created values are uneven) and the values to equal the value of the current row of the range (TRUE/FALSE).
These two booleans are multiplied creating 1 for both values being TRUE, else 0.
These  values are joined and checked for 2 consecutive 1's (surrounded by 0) to be found in the 2nd or 3rd position of the range (this would be the case if two even consecutive equal numbers are found),
if it errors it will look if a unique even number is found (1 surrounded by 0 in 2nd position).
PS I'm unable to test if conditional formatting allows you to type the range as B:B instead of B$1:B$9 (working from a mobile) but that would make it more dynamical, because that way you can easily expand the conditional range.


text:
Q: Output string contents as HTML markup Background info: The website can have "widgets" and the mark-up code for them is stored in a database. Starts and ends with the List Item (li) tag.
My controller sends a List listOfWidgets to the view. The view will then loop through that list and can access the mark-up code through a string from the Widget class (listOfWidgets[i].markup)
How can I get my view to put the string markup as actual markup and not display as text? Is there some kind of HTML helper that will do that? For example (I know this is completely wrong, but for example's sake)
@Html.PrintMarkup(listOfWidgets[i].markup)
Thanks in advance

A: Use this:
@Html.Raw(listOfWidgets[i].markup)


text:
Q: How Outlook 2007/2010 is shading message headers There is a feature in Outlook 2007/2010 called "Shade messages headers when reading mail" : it includes next/previous button in front of each replies headers of a message, allowing to go to previous/next replies in the message.
I would like to know how Outlook is doing this in order to reproduce it programmatically.
Thank you

A: It just looks for From: at the beginning of a line in the email, nothing more.
You can confirm this by sending yourself an email with the headers out of order:
-----Original Message-----
To: E.J. Dyksen
From: E.J. Dyksen
Sent: Monday, June 04, 2012 9:35 PM
Subject: RE: Test email

In this case, the line with From: is what Outlook highlights.


text:
Q: (PUT) endpoint not working as expected for Tick entries Using the PUT request to update Tick entries is not working as expected. Using the following: PUT /entries/235.json will update the entry from the parameters passed
GitHub link: https://github.com/tick/tick-api/blob/master/sections/entries.md#update-entry
Currently receiving a 400 Bad Request (screenshot)
I tried the GET request to confirm authorization is working as expected, and received a 200


text:
Q: Python implementation of YFilter Is there implementation of this (YFilter) as a python library or there any similar libraries like this to enable filtering and transformation for high-Volume XML message brokering. so as to implement this functionality in python.

A: You may look to Celery (asynchronous task queue/job queue based on distributed message passing) + lxml.