text:
Q: Python.Проверка наличия ошибки в функции Я создаю функцию, которая по фамилии человека берёт информацию про человека из словаря и вывод её, казалось бы всё хорошо идёт, но когда идёт попытка узнать несуществующую Фамилию - прилетает KeyError. Есть ли возможность проигнорировать его не просто return'ом в конце функции, а что бы функция вернула надпись мол "не так задали информацию" и не сломала ничего.
        ju = vk_session.method('messages.getConversationMembers',{'peer_id': 2000000001,'fields': 'status,city,personal,sex'})
    # gpid = {item.get('last_name'): item.get('id') for item in ju['profiles']} # id человека
    gba = {item.get('last_name'): item.get('is_closed') for item in ju['profiles']} # Открыт ли профиль
    gst = {item.get('last_name'): item.get('status') for item in ju['profiles']} # Статус
    gci = {item.get('last_name'): item.get('city').get('title') for item in ju['profiles'] if 'city' in item} # Город
    gpe = {item.get('last_name'): item.get('personal') for item in ju['profiles']} # Перс. инфа
    gn = {item.get('last_name'): item.get('first_name') for item in ju['profiles']} # Имя
    gsp = {item.get('last_name'): item.get('sex') for item in ju['profiles']} #Пол человека

Вот так я получаю информацию по словарю и потом начинаю её обрабатывать вот так:
 t2=('Живёт в городе: ' + gci[fam])

        if gpe[fam]['alcohol'] == 0:
            t3 = ('Алкоголь: не указано')
        if gpe[fam]['alcohol'] == 1:
            t3 = ('Алкоголь: жесть как не любит')
        elif gpe[fam]['alcohol'] == 2:
            t3 = ('Алкоголь: не любит')
        elif gpe[fam]['alcohol'] == 3:
            t3 = ('Алкоголь: в целом ок')
        elif gpe[fam]['alcohol'] == 4:
            t3 = ('Алкоголь: всё равно')
        elif gpe[fam]['alcohol'] == 5:
            t3 = ('Алкоголь: любит')

        if gpe[fam]['smoking'] == 1:
            t4 = ('Курение: жесть как не любит')
        elif gpe[fam]['smoking'] == 2:
            t4 = ('Курение: не любит')
        elif gpe[fam]['smoking'] == 3:
            t4 = ('Курение: в целом ок')
        elif gpe[fam]['smoking'] == 4:
            t4 = ('Курение: всё равно')
        elif gpe[fam]['smoking'] == 5:
            t4 = ('Курение: любит')

        if gpe[fam]['life_main'] == 0:
            t5 = ('Возникла проблема в Фамилии или Главное в жизни не указано')
        elif gpe[fam]['life_main'] == 1:
            t5 = ('Главное в жизни: семья и дети')
        elif gpe[fam]['life_main'] == 2:

У меня вышло это реализовать с огромным количеством try except и оно заработало криво, есть ли возможность сделать всё это лаконичнее.
Была конечно идея написать что-то вроде if ошибка вылезла: print('Вы не так ввели') но не знаю как это сделать и нужно ли именно так делать
Оочень прошу помощи

A: Используйте не [] (gpe[fam]), а person = gpe.get(fam), если нужной фамилии не будет, то эта конструкция вернет None. Далее сделаете if person is None и вернете строку из функции какую вам нужно.
А чтобы не делать такие громоздкие конструкции, заведите словари вида alcohol = {0: 'Алкоголь: не указано', 1: 'Алкоголь: жесть как не любит'}, тогда строковую информацию в коде будете получать просто выбирая элемент из словаря alcohol[person['alcohol']]


text:
Q: On CentOS, how do I build Python 3.9 from source while incorporating my openssl module? I'm trying to build Python 3.9.1 with SSL support on CentOS 7.
[myuser@server Python-3.9.1]$ which openssl
/usr/local/bin/openssl
[myuser@server Python-3.9.1]$ openssl version
OpenSSL 1.1.1g  21 Apr 2020

Running this command
sudo ./configure CPPFLAGS="-I/usr/local/openssl/include" LDFLAGS="-L/usr/local/openssl/lib" --with-ssl

followed by "make" worked for Python 3.7, but when i run the above on 3.9 and then run make I get this output
...
Python build finished successfully!
The necessary bits to build these optional modules were not found:
_lzma                 _tkinter              _uuid
To find the necessary bits, look in setup.py in detect_modules() for the module's name.

The following modules found by detect_modules() in setup.py, have been
built by the Makefile instead, as configured by the Setup files:
_abc                  atexit                pwd
time

Following modules built successfully but were removed because they could not be imported:
_hashlib              _ssl

Could not build the ssl module!
Python requires an OpenSSL 1.0.2 or 1.1 compatible libssl with X509_VERIFY_PARAM_set1_host().
LibreSSL 2.6.4 and earlier do not provide the necessary APIs, https://github.com/libressl-portable/portable/issues/381

running build_scripts
creating build/scripts-3.9
copying and adjusting /usr/src/Python-3.9.1/Tools/scripts/pydoc3 -> build/scripts-3.9
copying and adjusting /usr/src/Python-3.9.1/Tools/scripts/idle3 -> build/scripts-3.9
copying and adjusting /usr/src/Python-3.9.1/Tools/scripts/2to3 -> build/scripts-3.9
changing mode of build/scripts-3.9/pydoc3 from 644 to 755
changing mode of build/scripts-3.9/idle3 from 644 to 755
changing mode of build/scripts-3.9/2to3 from 644 to 755
renaming build/scripts-3.9/pydoc3 to build/scripts-3.9/pydoc3.9
renaming build/scripts-3.9/idle3 to build/scripts-3.9/idle3.9
renaming build/scripts-3.9/2to3 to build/scripts-3.9/2to3-3.9
/bin/install -c -m 644 ./Tools/gdb/libpython.py python-gdb.py
gcc -pthread -c -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall    -std=c99 -Wextra -Wno-unused-result -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -fvisibility=hidden  -I./Include/internal  -I. -I./Include -I/usr/local/openssl/include   -DPy_BUILD_CORE -o Programs/_testembed.o ./Programs/_testembed.c
gcc -pthread -L/usr/local/openssl/lib    -Xlinker -export-dynamic -o Programs/_testembed Programs/_testembed.o libpython3.9.a -lcrypt -lpthread -ldl  -lutil -lm   -lm
sed -e "s,@EXENAME@,/usr/local/bin/python3.9," < ./Misc/python-config.in >python-config.py
LC_ALL=C sed -e 's,\$(\([A-Za-z0-9_]*\)),\$\{\1\},g' < Misc/python-config.sh >python-config

So evidently Python 3.9 has NOT been built with SSL.  What else do I need to do to build Python 3.9 with the openssl module I have installed?

A: Python3.10 source build on CentOS 7.6
The above posts were very helpful to guide me to my solution. I want to share in case someone else could use this:
First the development libs

*

*sudo yum groupinstall "Development Tools" -y

*sudo yum install openssl11-devel libffi-devel bzip2-devel xz-devel -y

*

*for static linking use openssl11-static
Then configure
So for some reason CentOS ships openssl1.1.1 but it is installed in a way that doesn't jive with Python's configure script.
# note that we #include <openssl/foo.h>, so the OpenSSL headers have to be in
    # an 'openssl' subdirectory

    if ! $found; then
        OPENSSL_INCLUDES=
        for ssldir in $ssldirs; do
            { $as_echo "$as_me:${as_lineno-$LINENO}: checking for openssl/ssl.h in $ssldir" >&5
$as_echo_n "checking for openssl/ssl.h in $ssldir... " >&6; }
            if test -f "$ssldir/include/openssl/ssl.h"; then
                OPENSSL_INCLUDES="-I$ssldir/include"
                OPENSSL_LDFLAGS="-L$ssldir/lib"
                OPENSSL_LIBS="-lssl -lcrypto"

Since Python is including headers a subfolder is desired: $ssldir/include/openssl/ssl.h
I just created a new folder with the correct layout:
/opt/openssl111/
├── include
│   └── openssl
│       └── *.h
└── lib
    ├── libcrypto.so
    └── libssl.so

Once in place, the trifecta:

*

*./configure --enable-optimizations --with-lto --with-openssl=/opt/openssl111/

*

*lto is link time optimization

*make -j8

*make altinstall (installs in /usr/local/ not to overwrite system python)

A: The issue is because of missing development libraries that should be installed. To install them, as per Python Developer installation docs for CentOS, run
sudo yum install yum-utils
sudo yum-builddep python3

Run the following to build Python
./configure
make
make test
sudo make install

In case you want to build it with your custom SSL library, pass the argument --with-openssl along with your library path. The path should contain a lib folder containing the required files.
./configure --with-openssl=<your-openssl-library-path>

A: When you compile Python, you need to tell it which OpenSSL headers and libraries to use. Try this before running "./configure" when building Python
export CFLAGS="$CFLAGS $(pkg-config --cflags openssl11)"
export LDFLAGS="$LDFLAGS $(pkg-config --libs openssl11)"

This is the most reliable way to get the correct flags passed to the compiler and linker.  It's also worth checking that there aren't any conflicting values being passed into the CFLAGS / LDFLAGS environment variables, which might stymie your efforts.

A: I believe this is the key:

Following modules built successfully but were removed because they
could not be imported:
_hashlib              _ssl

What could cause this to happen is that the libraries installed in a non-standard location can't be loaded. So, locate the module (it is built, after all) and run ldd on it. See it's manpage for further detail and keep in mind that Python modules are shared objects (or DLLs on MS Windows). It will probably show a missing dependency on libssl.so. In order to resolve that, configure Linux' dynamic linker to pick up the file. I'd like to refer you to man ld.so for instructions, no use duplicating that info here.

A: # try the following:
export CC="gcc"
export CXX="g++"
export CPP="cpp"
export F90="gfortran"
export F77="gfortran"
export FC="gfortran"

dnf install gcc bzip2-devel tk-devel openssl-devel uuid-devel sqlite-devel gdbm-devel readline-devel xz-lzma-compat xz-devel libffi-devel libnsl2-devel
./configure --enable-shared --enable-optimizations
make -j
make install

redpajama_set_name: RedPajamaStackExchange


text:
Q: Internal Server Error after adding CMS fields in php file I have created Homepage.ss for the template and Homepage.php for the page type and after adding some codes to add a field in the php file, i am getting an internal server error message that pops up in a small window at the top right corner of the page and i also couldn't get to the edit mode nor preview mode of the admin page.
Already flushed the cache and run dev/build also but doesnt work.

Below is the screenshot of admin when going into the Homepage

A:
i am getting an internal server error message that pops up in a small window at the top right corner of the page

First of all, when you get a system error you will usually be able to do some basic debugging to work out what the actual problem is. This can involve setting the SS_ENVIRONMENT_TYPE .env var to "dev" so that exception traces are printed (either directly to the screen or in your network requests browser monitor for AJAX requests).
Once you know what the problem is you can work out how to fix it.

Your problem is that you aren't handling any of the class namespaces in your code. Page and PageController exist in the global namespace, but everything else is namespaced. Try this:
<?php

use SilverStripe\Forms\HTMLEditor\HTMLEditorField;

class Homepage extends Page
{
    private static $db = [
        'BottomContent' => 'HTMLText',
    ];

    public function getCMSFields()
    {
        $fields = parent::getCMSFields();
        $fields->addFieldToTab('Root.Main', HTMLEditorField::create('BottomContent', 'Bottom Content'));
        return $fields;
    }
}


text:
Q: sending doubles via TCP between Boost ASIO server and Java client I am trying to set up a simple Boost ASIO server with a single Java client.
I am able to send and successfully receive strings between the two.  However, when I try to send double values, only garbage comes out on the other end.
Below is stand alone code that shows my basic setup (with a C++ Boost ASIO server and a Java client).  When they are run, they do the following four sequential tasks:

*

*The client sends a string to the server, which is successfully received and printed out.

*The server sends a string to the client, which is successfully received and printed out.

*The client sends a double value to the server, which is received but does NOT print out
correctly.

*The server sends a double value to the client, which is received but does NOT print out
correctly.

Does anyone know what I am doing wrong?  I am admittedly very new to networking (and Java).  I have been through the Boost ASIO documentation and examples but to know avail.
C++ Boost ASIO server code:
#include <iostream>
#include <string>

#include <boost/asio.hpp>
#include <boost/array.hpp>

using boost::asio::ip::tcp;

int main()
{
   unsigned short const PORT = 19876;

   try
   {
      boost::asio::io_service ioService;
      tcp::acceptor acceptor(ioService, tcp::endpoint(tcp::v4(), PORT));

      while (true)
      {
         // Listen for clients
         std::cout << "Listening for client..." << std::endl;
         tcp::socket socket(ioService);
         acceptor.accept(socket);
         std::cout << "Client heard..." << std::endl;

         size_t len;

         // Receive string from client and print it out
         boost::array<char, 128> cBuf;
         len = socket.read_some(boost::asio::buffer(cBuf, sizeof(cBuf)));
         std::cout.write(cBuf.data(), len);

         // Send string to client
         std::string message = "Server string to send to client\n";
         boost::asio::write(socket, boost::asio::buffer(message));

         // Receive double from client and print it out
         double dVal1 = -1.0;
         char * p_dVal1 = reinterpret_cast<char *>(&dVal1);
         len = socket.read_some(boost::asio::buffer(p_dVal1, sizeof(double)));
         std::cout << dVal1<< std::endl; // prints out garbage

         // Send double to client
         double dVal2 = 6.28;
         char const * p_dVal2 = reinterpret_cast<char const *>(&dVal2);
         boost::asio::write(socket, boost::asio::buffer(p_dVal2, sizeof(double)));
      }
   }
   catch (std::exception & e)
   {
      std::cerr << e.what() << std::endl;
   }

   return 0;
}

Java client code:
import java.io.*;
import java.net.*;

public class Client
{
    final static String HOST = "localhost";
    final static int    PORT = 19876;

    public static void main(String[] args) throws IOException
    {
        Socket socket = new Socket(HOST, PORT);

        // Send string to server
        PrintWriter pos = new PrintWriter(socket.getOutputStream(), true);
        pos.println("Client string to send to server");

        // Receive string from server
        BufferedReader bis =
            new BufferedReader(new InputStreamReader(socket.getInputStream()));
        System.out.println(bis.readLine());

        // Send double value to server
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeDouble(3.14);

        // Receive double from server
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        System.out.println(dis.readDouble()); // prints out garbage

        socket.close();
        pos.close();
        bis.close();
        dos.close();
        dis.close();
    }
}

Thank you very much in advance!!!
Aaron

A: You need to use a lexical_cast, not a reinterpret_cast.
With reinterpret_cast, you're telling the compiler to literally interpret the double* bit pattern as a const char* bit pattern. Instead, your cast should create a new structure with ascii chars that represent the number in an ascii bit pattern.
Also, you should ensure that you're managing endianess. You should properly convert to and from network endianess on both the client and server. See this answer for additional information.


text:
Q: When $k+\langle h \rangle \subseteq k[x]$ is a UFD? Let $k$ be a field of characteristic zero and $f \in k[x]\setminus\{0\}$.
Let $R_f=k+\langle f \rangle$.

Question 1: Is it possible to find a general form of $f \in k[x]\setminus\{0\}$ such that $R_f$ is a UFD?

For example, $R_{x^2}=k+\langle x^2 \rangle=k[x^2,x^3]$ is not a UFD: $x \notin R_f$ and $x^6=x^2x^2x^2=x^3x^3$.
Is it true that for $f$ separable (has different roots), $R_f$ is a UFD? Probably not? What about $g=x+x^2$? $h=x^2-1$?

Question 2: Similar question for the two-dimensional case, namely, when $S_{f,y}=k+\langle f,y \rangle \subseteq k[x,y]$ is a UFD?

'Again', $S_{x^2,y}=k+ \langle x^2,y \rangle= k[x^2,x^3,y]$ is not a UFD.
Thank you very much!

A: As Mohan says, $R_f$ will be a UFD if and only if $\deg(f)\leqslant 1$. Indeed, if $\deg(f)\leqslant 1$ then $R_f=k[x]$, so the backwards direction is clear. For the forwards direction, suppose $R_f$ is a UFD, and assume for contradiction that $\deg f>1$; then $f=a_0+a_1 x+\dots +a_n x^n$ for some $n>1$ and $a_n\neq 0$. We may assume without loss of generality that $a_n=1$, since $f$ and $a_n^{-1}f$ generate the same ideal in $k[x]$. In particular, the element $x\in k[x]$ is integral over $R_f$, since $x$ satisfies the monic polynomial $$t^n+a_{n-1}t^{n-1}+\dots+a_1t+(a_0-f)\in R_f[t].$$ On the other hand, note that $xf$ lies in the ideal $\langle f\rangle<k[x]$, so $xf\in R_f$, and so $x=\frac{xf}{f}\in\operatorname{Frac}R_f$. Since UFDs are integrally closed, this means $x\in R_f$, and hence $x=\lambda+gf$ for some $\lambda\in k$ and $g\in k[x]$. If $g$ is $0$ this is clearly a contradiction, and if $g$ is non-zero then we have $$1=\deg(x-\lambda)=\deg(gf)\geqslant \deg(f)=n>1,$$ again a contradiction, so we are done. Essentially an identical argument works for $S_{f,y}$.

As @user26857 point outs, really what this shows is the stronger fact that $R_f$ is not even integrally closed unless $\deg(f)\leqslant 1$.


text:
Q: Return Only Child Entity Linq Entity Framework Given something like:
public class Parent
{
    public int Id { get; set; }
    public List<Child> Children { get; set; }
}

// There is no reference to the parent in the object model
public class Child
{
    public int Id { get; set; }
    public string MyProperty { get; set; }
}

is it possible to load only a child matching a particular condition, for a given Parent ID, without also loading the parent entity?
I have seen solutions that use projection to load the parent and zero or more children matching a condition.

A: If I understand you correctly, this should do it; it puts the conditions you want on both the parent and child, but selects only the child.
from parent in db.Parents
from child in parent.Children
where parent.Id = 4711 &&
      child.MyProperty == "olle"
select child;


text:
Q: Is this session provider correct for the web? Just learning nhibernate with fluent, and my session provider looks like:
 public class SessionProvider
    {

        private static ISessionFactory sessionFactory;

        public static ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory == null)
                {
                    sessionFactory = Fluently.Configure()
                        .Database(MsSqlConfiguration.MsSql2005.ConnectionString( c => c.FromAppSetting("sqlserver")))
                        .Mappings( m => m.FluentMappings.AddFromAssemblyOf<UserMapping>())
                        .BuildSessionFactory();
                }

                return sessionFactory;
            }
        }

        private SessionProvider()
        { }

        public static ISession GetSession()
        {
            return SessionFactory.OpenSession();
        }
    }

Is this how I should be getting my session object?  Is this the 'fastest' way to do this for a high traffic website?

A: The "fastest" would be to simply keep 1 session for the whole app-lifecycle, but that would also be rather stupid :P (Well, with multicore nowadays, I'm not even sure if that's the fastest).
Everything seems fine. Just remember that GetSession() opens a new session on each call. Personally, I like to keep 1 session per HttpRequest, aka.:
public static ISession GetSession()
{
    if (HttpContext.Current.Items[SESSION_KEY] == null)
    {
        HttpContext.Current.Items[SESSION_KEY] = SessionFactory.OpenSession();
    }
    return HttpContext.Current.Items[SESSION_KEY] as ISession;
}
private const string SESSION_KEY = "kahsdmiashdohbasduhfasduybadsubdsabsd";

You could also do checks on the state of your session (closed, dirty, open?), and act accordingly, instead of just the "lazy-initialization".
[EDIT] BTW, it seems like you don't want to have your class instantiated (private constructor, all static members). You should declare the class as static, e.g. public static class MyClass{} . This will make it so that the class can't contain non-static members and can't be instantiated.

A: As a side note here is an short post on the cost of creating a new session by one of the NHibernate devs (spoiler:  It's cheap)
What is the cost of opening a session


text:
Q: Concatenate results in select I am trying to insert values into a table that come from an other (lookup) table.
The first 3 results from the table are selected and need to be concatenated before they are inserted into an other table.
How can I alter the following insert to first concatenates them with no separation characters between the 3 names (example: JohnMaxLouise)?
INSERT INTO Table 2 VALUES ((SELECT TOP 3 names FROM Table1 ORDER BY NEWID()))

I am using SQL Server 2016 so string_agg is not available.

A: Personally, I think this is simplest with conditional aggregation:
INSERT INTO Table2
    SELECT (MAX(CASE WHEN seqnum = 1 THEN name ELSE '' END) +
            MAX(CASE WHEN seqnum = 2 THEN name ELSE '' END) +
            MAX(CASE WHEN seqnum = 3 THEN name ELSE '' END)
           )
    FROM (SELECT name, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as seqnum
          FROM (SELECT TOP 3 name
                FROM Table1
                ORDER BY NEWID()
               ) t
          ) t;

An alternative is an XML approach, but if you know you want three, then conditional aggregation (or pivot) works fine.

A: try the following:
declare @tab table (names varchar(max))
declare @tab1 table ([name] varchar(100))

insert into @tab1
select 'John' union select 'Max' union select 'Louise' union select 'xxx'

insert into @tab select (select top 3 [name] + '' from @tab1 for xml path(''))

select * from @tab

Thanks.

A: This will return '1,2,3,4'
  DECLARE @x TABLE (i INTEGER)
  DECLARE @r VARCHAR(255)
  INSERT INTO @x VALUES (1),(3),(2),(4)

  SELECT @r= STUFF(( SELECT  ',' + CAST(i AS VARCHAR(max))
                  FROM @x
                  ORDER BY i
                  FOR XML PATH(''), type
                ).value('.','varchar(255)'), 1, 1, '')
  SELECT @r

A: Solution Overview
You can use FOR XML PATH('') to achieve this, just use the following command:
SELECT  '' + NAME
FROM (SELECT Top 3 NAME FROM TBL_1 ORDER BY NEWID()) AS T
FOR XML PATH('')

Or simple concatenation
SELECT  @x  = @x + NAME
FROM (SELECT Top 3 NAME FROM TBL_1 ORDER BY NEWID()) AS T1

Detailed Solution
SQLFiddle Demo

*

*First i created the test environment using the following query
 CREATE TABLE TBL_1 (NAME Varchar(50))
 CREATE TABLE TBL_2 (NAME Varchar(50))
 INSERT INTO TBL_1 (Name) VALUES ('John'),('Max'),('Louise'),('Mark'),('Peter')

*Then i Used the following command
DECLARE @x varchar(255)

SELECT  @x  = (SELECT '' + NAME
 FROM (SELECT Top 3 NAME FROM TBL_1 ORDER BY NEWID()) AS T1
 FOR XML PATH('') )

INSERT INTO TBL_2(NAME) SELECT @x;

SELECT * FROM TBL_2

And the Result is JohnLouiseMax

*Or you can use simple concatenation to achieve this

SQLFiddle Demo
    DECLARE @x varchar(255)
    SET @x = ''

    SELECT  @x  = @x + NAME
    FROM (SELECT Top 3 NAME FROM TBL_1 ORDER BY NEWID()) AS T1

    INSERT INTO TBL_2(NAME) SELECT @x;

    SELECT * FROM TBL_2


text:
Q: Launching word with javascript without ActiveX? I am developing a content management system in asp.net where the users of the system will use it to submit their work as well as open their previous/unfinished work (writing) in Microsoft Word 2003. Now the problem is if I use C# System.Diagnostics library it works perfectly if the system is deployed on local server (i.e the PC on which I am developing) but I think if I deploy it on another PC and run it on a client PC using LAN connection it will launch word on PC acting as server instead of client although I haven't tried this but this is what I doubt, is there any way I can launch word on client machine using Javascript but without using ActiveX as it restrict the user to use IE only while our users choose their own browser ?
Thanks.

A: Not possible. Browser scripting cannot interact with the client machine, period, unless you have some plugins installed that would allow it.
Microsoft, and its ActiveX, are an exception, where they break the rules so they can improve integration with their operating system. Many people think it's another of Microsoft's blunders, since it is often viewed as a big security risk.

A: Nope, and for good reason too. Could you imagine if any website were allowed to run executables on client computers...?


text:
Q: mismatch with count number of files within a directory in unix ls -1 | wc -l gives me count of 4209 where as ls -l | wc -l gives me count of 4210.
Is "-1" reducing overall count by 1? Which I feel is unlikely.
So what is the correct count of files in my directory?

A: ls -l shows an extra line at the beginning marked total which is the disk usage of listed files in blocks not including the sub directories. But it should be ignored here as were are to take the count and wc makes each line counts. Here ls -1 | wc -l gives you the correct count.
The -1 option is passed just to list one file per line. You can have the same output with ls | wc -l
Refer here : http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x700.html


text:
Q: How to compare two time string check if string2 is grater then first string in swift I am new in swift I search this questing and also got answer but not worked for me. Sorry for asking this again. My question is how to compare two time string. I am using this code.
let date = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let result = formatter.string(from: date)
        print(result)

        var totalTimeLoggedIn = TimeInterval() // 1 hour

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

        let loginTimeDate = dateFormatter.date(from: lblWorkStarted.text ?? "")!
        let logoutTimeDate = dateFormatter.date(from: result)!

        let timeLoggedIn = logoutTimeDate.timeIntervalSince(loginTimeDate)
        totalTimeLoggedIn += timeLoggedIn
        print("totalTimeLoggedIn: \(totalTimeLoggedIn.stringValue())")
        let TotalTimeLoginString = totalTimeLoggedIn.stringValue()
        let anotherdate = "02:00:00"

        if anotherdate < TotalTimeLoginString{
            print("True")

        }else{

        }

lblWorkStarted.text is the current date and time.
I am facing problem is that if TotalTimeLoginString is "10:15" some value like this then condition is not working properly and if  TotalTimeLoginString is "03:12:11" some value like this then it is working properly.
My problem is if I did not get hour then condition is not working. Thanks in Advance!

A: you have some mistakes here:

*

*You should create DateFormatter() again. It's heavy operation as https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW10

*You have to differentiate date and duration. Today is 8/4/2020, you can't compare it with duration as 1 hour, 2 hours.

*if your anotherdate is two hours, why you don't compare it as: 2 * 60 * 60 <  totalTimeLoggedIn ?
 let date = Date()

 let dateFormatter = DateFormatter()
 dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

 let loginTimeDate = dateFormatter.date(from: lblWorkStarted.text ?? "")!
 let timeLoggedIn = Date().timeIntervalSince(loginTimeDate)
 let anotherDate = 2 * 60 * 60

 if anotherDate < timeLoggedIn {
     print("True")

 }else{

 }


text:
Q: Installing nvidia graphics drivers without rebooting I would like to know if I can install nvidia graphics drivers on a system running Ubuntu 16.0.4 LTS without rebooting.
I have this requirement created that I should be able to:
1) Install nvidia graphics drivers, say version X, on Ubuntu machine.
   Ubuntu, by default, come with nouveau driver.
   So this step should uninstall nouveau and install nvidia driver version X

2) Uninstall nvidia driver version X and install nvidia version Y.

Basically, I would like to switch between graphics drivers(uninstall/install) without rebooting the system.
I would like to know if someone has tried this. Or got any idea how to achieve this.
Thanks

A: This worked for me on Ubuntu 20.04 LTS:
sudo modprobe nvidia

after I'd installed the drivers with
sudo apt install -y ubuntu-drivers-common && sudo ubuntu-drivers autoinstall


text:
Q: Plot step-wise decrease in R with Categorical value on X-axis I want to use a step plot to illustrate a process of elimination. I have a dateframe containing the number of candidates remaining after each step; it looks like this:
Step    Candidates Count
1       26587
2       1761
3       849
4       130

The Step column is a categorical variable and I need to represent with the names of the actual steps; I am using numbers because I have not been able to plot when the Step column contains text.
I was able to produce the following figure with the command
plot(df, type = "s")

The problem is the X axis: I need to either get rid of the decimals and add a legend to name each step or, preferably, figure out some way to put the names of the steps in the Step column and populate the axis automatically.
I also want to show the same graph as a log but when I use:
plot(log(df), type = "s")

R gives me log values for both columns. This wouldn't be a problem if I could figure out how to plot the data with Step as a categorical variable but I just cannot figure out how.
My instinct is that this is a fairly simple problem but I've been struggling for most of this morning.

A: plot(df, type = "s",  xaxt='n', log="y")
axis(1, at=1:4, labels=paste("step", 1:4))

Use
xaxt to suppress x-axis ticks and labels
log="y" to get y-axis on log scale
axis to add in the x-axis with labels argument used at specified points on x-axis
You may also want to tweak the labels on the y-axis


text:
Q: Which is faster powershell or c# to create bulk user in AD? I want to create bulk users(without using CSV) in Active Directory with more than 10 attributes.So what I have to prefer to create either via powershell or c# to make the execution in a faster and better way.

A: It's not going to matter which way you do it, the difference isn't going to be minutes or hours... We're talking seconds, C# technically would be quicker.
The question really should be... How are you intending to fill the attributes out if not with a csv, are you looking to create a number of temporary accounts with similar names and attributes?
Because if it's not with a csv or accounts with similar attributes then it would be no quicker than using ADUC.


text:
Q: Preferred way in calculating sum (calculus) What is the preferred way of calculating the value of a summation?
Is it Riemann's Sum?
For example:
$$\sum_{n=1}^{\infty} { (-1)^n \frac{3^n}{n4^n} }$$

A: Recall that for $\vert x \vert < 1$, we have
$$\sum_{n=1}^{\infty} \dfrac{x^n}n = - \log(1-x)$$
A quick way to see this is to note that for $\vert t \vert < 1$, we have
$$\sum_{n=1}^{\infty} t^{n-1} = \dfrac1{1-t} \tag{$\star$}$$
Integrating $(\star)$ from $0$ to $x$ (where $\vert x \vert < 1$), we get that
$$-\log(1-x) = \int_0^x\dfrac{dt}{1-t} = \int_0^x \sum_{n=1}^{\infty} t^{n-1} dt= \sum_{n=1}^{\infty}  \int_0^x t^{n-1} dt = \sum_{n=1}^{\infty} \dfrac{x^n}n\tag{$\perp$}$$
which gives us what we want.

A: Most preferred ways of computing sums like those boil down to finding a way (vis differentiation, integration etc.) to reduce them to a geometric series, and then working from there.
Consider
$$\sum_{n=1}^{\infty} \frac{(-1)^n}{n} x^n$$
where $|x| < 1$.  This is actually a well-known sum, but let's go from here as I described.  If we differentiate with respect to $x$, we get
$$\frac{d}{dx} \sum_{n=1}^{\infty} \frac{(-1)^n}{n} x^n = \sum_{n=1}^{\infty} (-1)^{n} x^{n-1} = -\frac{1}{1+x}$$
We may then integrate to get
$$\sum_{n=1}^{\infty} \frac{(-1)^n}{n} x^n = -\int \frac{dx}{1+x} = \log{\left( \frac{1}{1+x}\right)}$$
where the integration constant is zero as the sum evaluated at zero is zero.
Your sum has $x=3/4$.

A: There are many ways.  In this case you might recognize the Taylor series for $\log (1+x)=\sum_{i=1}^\infty \frac {(-1)^{i+1}x^i}i$, substitute in $x=\frac 34$ and multiply by $-1$ to get $-\log (\frac 74)$

A: Hint (without exaplanation/justification, to fill in):
$$\forall\,x\in\Bbb C\;,\;|x|<1\;:\;\;\frac{1}{1+x}=\sum_{k=0}^\infty(-1)^nx^k\implies$$
$$\log(1+x)=\int\left(\sum_{k=0}^\infty(-1)^kx^k\right)dx=\sum_{k=0}^\infty(-1)^n\int x^k\,dx=\sum_{k=0}^\infty(-1)^k\frac{x^{k+1}}{k+1}\ldots$$

A: To answer the question behind this example, there is little in the way of "general results". Just like there are different ways of reducing given integrals to a handful of typical examples that can be solved, there are some techniques (eerily reminiscent to the integral case, both are sums) to reduce sums to known forms. The answers given hint at one of the more important of them: Try to represent your sum as some mangling of a known (here geometric) series. There are specific techiques for some types of sums (see for example Petkovsek, Wilf, Zeilberger's "A = B", and also Wilf's "generatingfuctionology") Then there are all sort of neat (and also some hair-raising) tricks to tame specific other cases, and a vast collection of sums that just can't be reduced to anything neat. The solution then is to resort to approximate methods of one sort or the other, and on those there is a vast amount of work too.


text:
Q: Map modelA to modelB in controller I have two unassociated models which normally would be associated. This is however sort of a freak-case where I don't want them to be associated.
In the view, I can do this:
<%= @user.each do |user| %>
   <%= Option.where(:id => user.option_1).or(Option.where(:id => user.option_2).each do |option| %>
   <% end %>
<% end %>

How can I move that logic to the controller?
If I, in controller do
@user = User.all.map do |user|
   @options = Option.where(:id => user.option_1).or(Option.where(:id => user.option_2)
end

The results of @options do not map to the @user object the same way it would @user.options if models were associated.
Is there a way to mimic that functionality when the models are not associated so that when I loop through <% @users.each do %> I can access <% @options.each do %> within that scope the same way I would if :options belonged to :user and :user had many :options
So that the final output in the view would look like this:
<% @users.each do |user| %>
  <% @options.each do |option| %>
      #Outputs the result of Option.where(:id => user.option_1).......
  <% end %>
<% end %>

A: Since you want to loop options, you should do this
In controller
@options = Option.joins("INNER JOIN users ON users.option_1 = options.id OR users.option_2 = options.id").distinct

In view,
<% @options.each do |option| %>
<% end %>

Give it a try.


text:
Q: Blur an UIImage on change of slider I have tried gaussian blur and checked out all the questions on stackoverflow but no one of them solved my crash issue.Please help is there is any other way to blur image other than gaussian blur algorithm. My image size is 768x1024 and the loops iterates for 2*1024*768 times and this is not feasible.
CGContextRef NYXImageCreateARGBBitmapContext(const size_t width, const size_t height, const size_t bytesPerRow)
{
/// Use the generic RGB color space
/// We avoid the NULL check because CGColorSpaceRelease() NULL check the value anyway, and worst case scenario = fail to create context
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

/// Create the bitmap context, we want pre-multiplied ARGB, 8-bits per component
CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8/*Bits per component*/, bytesPerRow, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);

CGColorSpaceRelease(colorSpace);

return bmContext;
}

 -(UIImage*)blurredImageUsingGaussFactor:(NSUInteger)gaussFactor andPixelRadius:(NSUInteger)pixelRadius
{
CGImageRef cgImage = self.CGImage;
const size_t originalWidth = CGImageGetWidth(cgImage);
const size_t originalHeight = CGImageGetHeight(cgImage);
const size_t bytesPerRow = originalWidth * 4;
CGContextRef context = NYXImageCreateARGBBitmapContext(originalWidth, originalHeight, bytesPerRow);
if (!context)
    return nil;

unsigned char *srcData, *destData, *finalData;

size_t width = CGBitmapContextGetWidth(context);
size_t height = CGBitmapContextGetHeight(context);
size_t bpr = CGBitmapContextGetBytesPerRow(context);
size_t bpp = CGBitmapContextGetBitsPerPixel(context) / 8;
CGRect rect = {{0.0f, 0.0f}, {width, height}};

CGContextDrawImage(context, rect, cgImage);

// Now we can get a pointer to the image data associated with the bitmap
// context.
srcData = (unsigned char*)CGBitmapContextGetData(context);
if (srcData != NULL)
{
    size_t dataSize = bpr * height;
    finalData = malloc(dataSize);
    destData = malloc(dataSize);
    memcpy(finalData, srcData, dataSize);
    memcpy(destData, srcData, dataSize);

    int sums[gaussFactor];
    size_t i, /*x, y,*/ k;
    int gauss_sum = 0;
    size_t radius = pixelRadius * 2 + 1;
    int *gauss_fact = malloc(radius * sizeof(int));

    for (i = 0; i < pixelRadius; i++)
    {
        gauss_fact[i] = 1 + (gaussFactor * i);
        gauss_fact[radius - (i + 1)] = 1 + (gaussFactor * i);
        gauss_sum += (gauss_fact[i] + gauss_fact[radius - (i + 1)]);
    }
    gauss_fact[(radius - 1) / 2] = 1 + (gaussFactor*pixelRadius);
    gauss_sum += gauss_fact[(radius - 1) / 2];

    unsigned char *p1, *p2, *p3;

    for (size_t y = 0; y < height; y++)
    {
        for (size_t x = 0; x < width; x++)
        {
            p1 = srcData + bpp * (y * width + x);
            p2 = destData + bpp * (y * width + x);

            for (i = 0; i < gaussFactor; i++)
                sums[i] = 0;

            for (k = 0; k < radius ; k++)
            {
                if ((y - ((radius - 1) >> 1) + k) < height)
                    p1 = srcData + bpp * ((y - ((radius - 1) >> 1) + k) * width + x);
                else
                    p1 = srcData + bpp * (y * width + x);

                for (i = 0; i < bpp; i++)
                    sums[i] += p1[i] * gauss_fact[k];

            }
            for (i = 0; i < bpp; i++)
                p2[i] = sums[i] / gauss_sum;
        }
    }
    for (size_t y = 0; y < height; y++)
    {
        for (size_t x = 0; x < width; x++)
        {
            p2 = destData + bpp * (y * width + x);
            p3 = finalData + bpp * (y * width + x);

            for (i = 0; i < gaussFactor; i++)
                sums[i] = 0;

            for(k = 0; k < radius ; k++)
            {
                if ((x - ((radius - 1) >> 1) + k) < width)
                    p1 = srcData + bpp * ( y * width + (x - ((radius - 1) >> 1) + k));
                else
                    p1 = srcData + bpp * (y * width + x);

                for (i = 0; i < bpp; i++)
                    sums[i] += p2[i] * gauss_fact[k];

            }
            for (i = 0; i < bpp; i++)
            {
                p3[i] = sums[i] / gauss_sum;
            }
        }
    }
}

size_t bitmapByteCount = bpr * height;

///////Here was the problem.. you had given srcData instead of destData.. Rest all
//were perfect...
CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, destData, bitmapByteCount, NULL);

CGImageRef blurredImageRef = CGImageCreate(width, height, CGBitmapContextGetBitsPerComponent(context), CGBitmapContextGetBitsPerPixel(context), CGBitmapContextGetBytesPerRow(context), CGBitmapContextGetColorSpace(context), CGBitmapContextGetBitmapInfo(context), dataProvider, NULL, true, kCGRenderingIntentDefault);

CGDataProviderRelease(dataProvider);
CGContextRelease(context);
if (destData)
    free(destData);
if (finalData)
    free(finalData);

UIImage* retUIImage = [UIImage imageWithCGImage:blurredImageRef];

CGImageRelease(blurredImageRef);

return retUIImage;
}

A: Not sure about how to blur an image.
This may help is you want to blur an UIImageView or any view.
   UIView *myView = self.theImageView;
    CALayer *layer = [myView layer];
    [layer setRasterizationScale:0.25];
    [layer setShouldRasterize:YES];

You can undo it by setting the rasterization scale back to 1.
[layer setRasterizationScale:1.0];

UPDATE:
The below Apple sample code includes a blur/sharp effect. (using Open GL)
See if it helps, http://developer.apple.com/library/ios/#samplecode/GLImageProcessing/Introduction/Intro.html

A: I've made a small StackBlur extension to UIImage. StackBlur is close to GaussianBlur but much faster.
Check it at: https://github.com/tomsoft1/StackBluriOS

tiny note... there's a typo just on that ReadMe, "normalized" for "normalize"

A: What you probably want is a Box Blur algorithm. It is about 10 times faster than Gaussian blur and produces nice results. I have the code running on Android, I just haven't ported it to iOS yet. Here is the source.
Should only take about 10 minutes to port to iOS. The functions will work as is, you just need to access the image bytes (as you are doing in the source code above) and feed them to functions.


text:
Q: How to solve $y(y'+3)=ax^2+bx+c, \quad a,b,c \in \mathbb{R}$ How could we solve this differential equation $$y(y'+3)=ax^2+bx+c, \quad a,b,c \in \mathbb{R}$$
I really don't know how start. I am not familiar with this sort of differential equations (I know it is non-linear fist order, but don't see way to solve it).
I passed this exam, so this is just for fun (not homework or something like that).
Thanks.

A: Case $1$: $a=b=c=0$
Then $y(y'+3)=0$
$y=0$ or $y'=-3$
$y=0$ or $C-3x$
Case $2$: $a=b=0$ and $c\neq0$
Then $y(y'+3)=c$
$\dfrac{dy}{dx}=\dfrac{c}{y}-3$
$\dfrac{dx}{dy}=\dfrac{y}{c-3y}$
$x=\int\dfrac{y}{c-3y}dy$
$x=C-\dfrac{y}{3}-\dfrac{c\ln(3y-c)}{9}$
Case $3$: $a=0$ and $b\neq0$
Then $y(y'+3)=bx+c$
$\dfrac{dy}{dx}=\dfrac{bx+c}{y}-3$
Let $y=\left(x+\dfrac{c}{b}\right)u$ ,
Then $\dfrac{dy}{dx}=\left(x+\dfrac{c}{b}\right)\dfrac{du}{dx}+u$
$\therefore\left(x+\dfrac{c}{b}\right)\dfrac{du}{dx}+u=\dfrac{b}{u}-3$
$\left(x+\dfrac{c}{b}\right)\dfrac{du}{dx}=\dfrac{b}{u}-3-u$
$\dfrac{u}{b-3u-u^2}du=\dfrac{dx}{x+\dfrac{c}{b}}$
$\int\dfrac{u}{b-3u-u^2}du=\int\dfrac{dx}{x+\dfrac{c}{b}}$
$\begin{cases}-\dfrac{\ln(u^2+3u-b)}{2}-\dfrac{3}{\sqrt{4b+9}}\tanh^{-1}\dfrac{2u+3}{\sqrt{4b+9}}=\ln\left(x+\dfrac{c}{b}\right)+C&\text{when}~b\neq-\dfrac{9}{4}\\-\ln(2u+3)-\dfrac{3}{2u+3}=\ln\left(x+\dfrac{c}{b}\right)+C&\text{when}~b=-\dfrac{9}{4}\end{cases}$
Case $4$: $a\neq0$
Then $y(y'+3)=ax^2+bx+c$
$y\dfrac{dy}{dx}+3y=ax^2+bx+c$
This belongs to an Abel equation of the second kind.
Let $y=-3u$,
Then $\dfrac{dy}{dx}=-3\dfrac{du}{dx}$
$\therefore9u\dfrac{du}{dx}-9u=ax^2+bx+c$
$u\dfrac{du}{dx}-u=\dfrac{ax^2+bx+c}{9}$
This belongs to an Abel equation of the second kind in the canonical form.
Please follow the method in https://arxiv.org/ftp/arxiv/papers/1503/1503.05929.pdf or in http://www.iaeng.org/IJAM/issues_v43/issue_3/IJAM_43_3_01.pdf
For finding the special cases which has simpler form of the general solution,
Case $4$a:
$u\dfrac{du}{dx}-u=\dfrac{ax^2+bx+c}{9}$
$u\dfrac{du}{dx}-u=\dfrac{a}{9}\left(x^2+\dfrac{bx}{a}+\dfrac{c}{a}\right)$
$u\dfrac{du}{dx}-u=\dfrac{a}{9}\left(x^2+\dfrac{bx}{a}+\dfrac{b^2}{4a^2}+\dfrac{c}{a}-\dfrac{b^2}{4a^2}\right)$
$u\dfrac{du}{dx}-u=\dfrac{a}{9}\left(x+\dfrac{b}{2a}\right)^2+\dfrac{4ac-b^2}{36a}$
Let $s=x+\dfrac{b}{2a}$ ,
Then $u\dfrac{du}{ds}-u=\dfrac{as^2}{9}+\dfrac{4ac-b^2}{36a}$
According to http://science.fire.ustc.edu.cn/download/download1/book%5Cmathematics%5CHandbook%20of%20Exact%20Solutions%20for%20Ordinary%20Differential%20EquationsSecond%20Edition%5Cc2972_fm.pdf#page=138, we find a special case which has simpler form of the general solution when $4ac-b^2=\dfrac{2916}{625}$ .
Case $4$b:
$u\dfrac{du}{dx}-u=\dfrac{ax^2+bx+c}{9}$
$u\dfrac{du}{dx}-u=\dfrac{a}{9}\left(x+\dfrac{b+\sqrt{b^2-4ac}}{2a}\right)\left(x+\dfrac{b-\sqrt{b^2-4ac}}{2a}\right)$
Let $t=x+\dfrac{b\pm\sqrt{b^2-4ac}}{2a}$ ,
Then $u\dfrac{du}{dt}-u=\dfrac{a}{9}t\left(t\pm\dfrac{\sqrt{b^2-4ac}}{a}\right)$
$u\dfrac{du}{dt}-u=\dfrac{at^2}{9}\pm\dfrac{\sqrt{b^2-4ac}}{9}t$
According to http://science.fire.ustc.edu.cn/download/download1/book%5Cmathematics%5CHandbook%20of%20Exact%20Solutions%20for%20Ordinary%20Differential%20EquationsSecond%20Edition%5Cc2972_fm.pdf#page=133 and http://science.fire.ustc.edu.cn/download/download1/book%5Cmathematics%5CHandbook%20of%20Exact%20Solutions%20for%20Ordinary%20Differential%20EquationsSecond%20Edition%5Cc2972_fm.pdf#page=138, we find some special cases which has simpler form of the general solution when $b^2-4ac=\dfrac{2916}{625}$ .


text:
Q: Invocar WCF que esta en otra Biblioteca de Clases desde JQuery Hola tengo un problema al intentar llamar un Wcf que se encuentra en un Biblioteca de Clases, lo intento con JQuery haciendo las modificaciones necesarias, eh intentado algunas rutas relativas y absolutas en la URL del Ajax, lo estoy haciendo con un ejemplo sencillo anexo la imagen.
ya hice modificaciones en el WEb.Config
Quiero consumir del archivo js que esta dentro de la carpeta js, el WCF esta en la biblioteca de clases que esta abajo de llama Grafica.svc
Gracias de antemano por su ayuda.

A: Lo primero que deberias validar es si esl servicio WCF responde correctamente, para ello toma la url y navegala desde el browser, deberias poder ver la pagina por defecto que el .svc expone, sino puede observar esa pagina entonces el servicio no esta escuchando request.
No se como estas realizando la invocacion desde el cliente por medio de ajax, pero si validas
Calling WCF Services Using jQuery
veras que utiliza
$.ajax({
   type: "POST",
   contentType: "application/json; charset=utf-8",
   url: 'Service.svc/GetData',
   success: function (data) { ...

basicamente como define la url, en este caso el sitio y el servicio estan en el mismo proyecto web, sino deberias definir la url completa, como ser:
http://<NombrePC o IP>:puerto/servicio.svc

ya que el cliente y el servicio estan en diferentes host


text:
Q: Which edition of Philosophiae Naturalis Principia Mathematica of Isaac Newton would you recommend to me? I'm searching for a good edition of Philosophiae Naturalis Principia Mathematica of Isaac Newton in English. Which edition of the Principia can you suggest me? If it's possible, cheap and similar to original with the original proofs of Isaac Newton.
I'm sorry for my poor English, I'm just learning it.

A: Here is a free copy offered by its author, (edit: the translator, Ian Bruce),

*

*http://www.17centurymaths.com/contents/newtoncontents.html

A: This 2003 edition by Densmore & Donahue has the following book review

Makes the great adventure of Principia available not only to modern
  scholars of history of science, but also to nonspecialist
  undergraduate students of humanities. It moves carefully from Newton's
  definitions and axioms through the essential propositions, as Newton
  himself identified them, to the establishment of universal gravitation
  and elliptical orbits. The guidebook unfolds what is implicit in
  Newton's words as he himself would have filled in the steps and
  completes the argument in ways that are authentic and not
  anachronistic, exactly following Newton's thinking rather than
  substituting tools of modern calculus or the formulations of modern
  physics. It is Newton in his own terms. This is a wonderful book.
  ―Richard S. Westfall

A: The difficulty is not in the language that Newton uses, but in the incredibly original viewpoint that he takes.  Get a good translation, by all means, but you'll also need the help of a good guide.
One of the best such guides I ever found was S. Chandrasekhar's fantastic "Newton's Principia for the Common Reader", Oxford University Press, 1995. (Don't be fooled by the title, though, apparently Chandrasekhar had a much higher opinion of the 'common reader' than is warranted by the available evidence.)
It doesn't cover the entire Principia, but mainly the parts that lead to Newton's results on gravity.  What Chandrasekhar does is explain Newton's propositions, translate them into modern notation/language and show you a 'modern' proof, and then, with that knowledge of what is going on, he goes back to Newton's argument and shows the reader how Newton's approach works.  Along the way, he comments on how Newton's ideas harked back to Euclid and, at the same time, anticipated concepts in mechanics that would not be developed until many years later.
It's an amazing, edifying work by one of the greatest astrophysicists of the 20th century.

A: I would recommend this 1999 version by Cohen & Whitman:
The Principia: The Authoritative Translation and Guide: Mathematical Principles of Natural Philosophy
This edition has comments that help you understand the original. It is also quite cheap.


text:
Q: Can I get all possible instant messaging apps for a specific contact? In an app a user can choose contacts that get sent a message on a specific event.
We want to add support for instant messaging apps like WhatsApp or Threema.
Is it possible to get a list of all messaging apps the contact is known to have?
Additional question:
Can I send a message through those messaging apps without additional button click by the user?

A: You can use share intent. It will enable you to share through all installed apps.See this link for helpAndroid: Share plain text using intent (to all messaging apps)


text:
Q: Software recommendation request: deciding whether a system of polynomial equations is solvable by radicals The following system of equations comes from a very simple geometric figure I have to deal with a lot at work. Here $r_0,r_1,r_2$ and $L$ are known parameters, and the $x_i$s are the coordinates I'm after.

*

*$x_0^2 + x_3^2 = r_0^2$

*$(x_2-L)^2 + x_4^2 = r_2^2$

*$x_3 = r_1 + \tfrac{1}{2}x_5(x_0 - x_1)^2$

*$x_4 = r_1 + \tfrac{1}{2}x_5(x_2 - x_1)^2$

*$x_0 + x_3 x_5(x_0 - x_1) = 0$

*$(x_2-L) + x_4 x_5(x_2 - x_1) = 0$
I'm currently solving these numerically. This works perfectly well, but is (a) needlessly expensive if I don't have to do it and (b) extremely unsatisfying given the simple form of my equations.
My question is simply this: is there a piece of open-source (or otherwise free) software I can use to tell me - quickly and for certain - whether this system (and in future possibly others like it) can be solved explicitly in terms of radicals?


text:
Q: Passing an empty array as default value of an optional parameter How does one define a function that takes an optional array with an empty array as default?
public void DoSomething(int index, ushort[] array = new ushort[] {},
 bool thirdParam = true)

results in:
Default parameter value for 'array' must be a compile-time constant.

A: I know it's an old question, and whilst this answer doesn't directly solve how to get around the limitations imposed by the compiler, method overloading is an alternative:
   public void DoSomething(int index, bool thirdParam = true){
        DoSomething(index, new ushort[] {}, thirdParam);
   }

   public void DoSomething(int index, ushort[] array, bool thirdParam = true){

      ...
   }

A: If you can make the array the last argument you could also do this:
public void DoSomething(int index, bool wasThirdParam = true, params ushort[] array)

The compiler will automatically pass an empty array if it is not specified, and you get the added flexibility to either pass an array as a single argument or put the elements directly as variable length arguments to your method.

A: You can't create compile-time constants of object references.
The only valid compile-time constant you can use is null, so change your code to this:
public void DoSomething(int index, ushort[] array = null,
  bool thirdParam = true)

And inside your method do this:
array = array ?? new ushort[0];

(from comments) From C# 8 onwards you can also use the shorter syntax:
array ??= new ushort[0];


text:
Q: Chrome render different than Safari I've just uploaded a beta version of my website marcotronconi.com that I build up on chrome. I have no idea why, the safari render is messed up.
Any fixing idea?
P.s. It might be a silly question, but I'm new to css and html.
thanks

A: Not all browsers render a web site the same way. Browser's developpers may implement tools and functionnality to make them more attractive / performant.
The most famous example was Internet Explorer as it was massively deployed but did not implement some W3C rules.
Creating a website compatible on most browsers can be a long and hard path but i suggest you starts by studiing some usefull css reset tools as :

*

*eric meyer's reset CSS

*normalize.css
Then when building your layout feel free to check if what you plan to use is accessible by asking caniuse.com website.
Last but not least, codepen.io website can freely help you implement and test your code.
Hope this helps


text:
Q: Changing the Overlay background color for ContentDialog For my UWP app, I want to override the default theme of the background color of the screen around the content dialog when it opens. I tried doing what's mentioned in this answer but it didn't work for me: https://stackoverflow.com/a/32159659/2858235
My OS build # is 10586. I read somewhere that this solution is no more working for builds equal and above 10586. Is there any solution?

A: For me, my SDK version is 14393 (Anniversary) and the SolidColorBrush resource to override is SystemControlPageBackgroundMediumAltMediumBrush (that's a mouthful!).


text:
Q: How to manage a network down and avoid error with PKCS11Interop Using PKCS11Interop on Safenet HSMs, I got this error
"Method C_OpenSession returned 2147484548"
the error, in my documentation, is CKR_SMS_ERROR: "General error from secure messaging system - probably caused by HSM failure or network failure".
This confirm the problem it happens when the connectivity is lacking.
The problem is when this happens, the service isn't able to resume the communication when the connectivity is back, until I restart manually the service managing the HSM access.
When the service starts, I call this:
private Pkcs11 _pkcs11 = null;
private Slot _slot = null;
private Session _session = null;

public async void InitPkcs11()
{
    try
    {
        _pkcs11 = new Pkcs11(pathCryptoki, Inter_Settings.AppType);
        _slot = Inter_Helpers.GetUsableSlot(_pkcs11, nSlot);
        _session = _slot.OpenSession(SessionType.ReadOnly);
        _session.Login(CKU.CKU_USER, Inter_Settings.NormalUserPin);
    }
    catch (Exception e)
    {
        ...
    }
}

When I have to use the HSM, I call something like:
using (var LocalSession = _slot.OpenSession(SessionType.ReadOnly))
{
    ...
}

And, when I fail the communication due to a connectivity lack, I call a function to reset the connection and try to change the slot:
private bool switching = false;

public async void SwitchSlot()
{
    try
    {
        if (!switching)
        {
            switching = true;
            if (nSlot == 0)
            {
                nSlot = 2;
            }
            else
            {
                nSlot = 0;
            }
            _session.Logout();
            _slot.CloseAllSessions();
            _pkcs11.Dispose();
            InitPkcs11();
            switching = false;
        }
    }
    catch (Exception e)
    {
        ...
    }
}

But, this last snippet doens't work as expected: it tries to change the slot, but it fails always to communicate with the HSM (after a network down). If I restart the service manually (when the connectivity is back), it works like charms. So, I'm sure I'm doing something wrong in the SwitchSlot function, when I try to close the _session and open a new one.
Do you see any errors/misunderstoonding here?


text:
Q: SSH Copy Limit? So I have a small little Ubuntu server set up, with some rather large files that I've allowed a few people to copy from their putty window.
Anyways 2 questions:
Lets say a person on windows wants to copy a file using putty from an Ubuntu server. how would they do it? and what directory would it default too? (what would the command be even? would I use SCP?)
Second question: is there like a limit? these are mostly 1-2gb files. would that cause any issues? Thanks

A: You can try PSCP which comes as part of the PuTTY distribution.
The usage of pscp is:
pscp [user@]host:source target

For example, from a Windows cmd prompt, type the following command to transfer a file to your C: drive.
pscp username@host:/path/to/file.txt C:\temp\file.txt

I don't believe there is a file size limit.

A: The default will be the home directory of the linux server account being used.  So if a person used luser@yourserver:foobar.pdf, then the file would be taken from/placed at ~luser/foobar on yourserver.
If you do not want people to be able to write to your server, then I suggest locking down the directories/files and/or settings up a callback script inside the .ssh/authorized_keys file.


text:
Q: Can a job title or position be used without an article? Can someone's position in their workplace be used without an article in a subject complement (as if it were an adjective)  and
will there be no difference in meaning from when it was used with an article.
For example:

My uncle was head copy editor of the NY Times.

This is excerpted from a random website thread.
To me, "a head copy editor" sounds more natural (as follows):

My uncle was a head copy editor of the NY Times.

I understand a position or individual's social status can be used like "He is president of the United States."
I learned when it is used without an article, the sentence focuses more on the nature of the mentioned position than when it is used with one.

A: If there are more than one editor with the title of "head copy editor" then you can definitely use the indefinite article. Nevertheless, if there is only one person with the title "head copy editor" then use the definite article or no article at all.

A: Perhaps the confusion arises because even though there is only one head copy editor, & for that matter only one president, there have been many over the years.
So...

"My uncle was head copy editor of the NY Times."

Signifies he was the only one at that time.

"My uncle was a head copy editor of the NY Times."

implies that there was a series of them over the years & that he was merely one of that series.
I would only use this form if it was to emphasise he was one of many, not that he achieved that proud position, being the only one in his time.
If he had been a junior copy editor, one of several at any time, then

"My uncle was a copy editor at the NY Times."

[I only just realised 'of' doesn't work so well in that construction, which makes me now question whether it ought to also be 'at' in the first examples too.]
Similarly...

"He is president of the United States."

Again, there is only one at a time.
As president is rather a singular position anyway, it even sounds a little odd to say

"John Quincy Adams was a president of the USA"

even though he was one of many. You would be more likely to say

"John Quincy Adams was president of the USA"

again, though he was one of many, he was the only one at that time.


text:
Q: How to update an array in Sequelize Postgres I have a user model in Sequelize for a Postgres db:
var User = sequelize.define('User', {
fb_id: DataTypes.STRING,
access_token: DataTypes.TEXT,
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
email: DataTypes.TEXT,
profilePictureURL: DataTypes.TEXT,
library: DataTypes.ARRAY(DataTypes.STRING)
}, {
underscored: true,
classMethods: {
  associate: function(models) {

   }
 }
  });

I am trying to update the library field by adding ISBNs to the array. This is the code for my POST request:
req.user.library.push(req.body._isbn); // adding the posted ISBN to the user object in my express-session

User.findOrCreate({where: {fb_id: req.user.fb_id},
        defaults: {
            access_token :      req.user.access_token,
            first_name :        req.user.first_name,
            last_name :         req.user.last_name,
            email :             req.user.email,
            profilePictureURL : req.user.profilePictureURL,
            library: req.user.library // new library object
        }})
        .spread(function (updatedUser, created){
            res.status(200).json(updatedUser);
        }).error(function(err){
            res.status(500).json(err);
        });

There is no error, but the library field is not updated after checking the updatedUser object. How do I correctly update an array field in Sequelize?

A: For next visitors, I may have found a better way to solve this issue :
User.update(
 {library: Sequelize.fn('array_append', Sequelize.col('library'), req.body._isbn)},
 {where: {fb_id: req.user.fb_id}}
);

A: I ran into this before and found the answer deep in their Github issues. The way I accomplished it is
User.find({
  where: {
    fb_id: req.user.fb_id
  }
})
.then((user) => {
  user.library.push(req.body._isbn)
  user.update({
    library: user.library
  },{
    where: {
      fb_id: req.user.fb_id
    }
  })
  .then(user => res.json(user))
})

It definitely feels like there is a better way, but this way how I found a way.

A: Kinda old issue but I found a workaround that could help in the future, from what I understand sequelize may not recognize an updated data as new instance so it will consider it as local scope only. Solution for me was to create a new object upon the needed array, something like:
let newArray = Object.assign([], instance.arrayToUpdate);

newArray.push(myInterestingData)
await instance.update({
  arrayToUpdate: newArray
});


text:
Q: Detect Chrome running in headless mode from JavaScript With the release of Chrome 59, "headless" mode is now available in stable builds for Linux and macOS (and soon also Windows with Chrome 60). This allows us to run a full-featured version of Chrome without any visible UI, a great capability to have for automated testing. Here are examples.
chrome --headless --disable-gpu --dump-dom https://stackoverflow.com/

In my JavaScript test runner, I like to record as much information as possible about the browser being used, to help isolate issues. For example, I record many of the properties of navigator, including the current browser plugins:
JSON.stringify(Array.from(navigator.plugins).map(p => p.name))

["Chrome PDF Viewer","Widevine Content Decryption Module","Shockwave Flash","Native Client","Chrome PDF Viewer"]

My understanding is that Chrome should behave identically in headless mode, but I have enough experience to be skeptical of a new feature that may significantly change the rendering pipeline.
For now, I am going to run tests in both modes. I would like to the test runner to record whether headless mode is being used. I could pass this information in the test configurations, but I'd rather have a pure JavaScript solution that I can build into the test runner itself. However, I haven't been able to find any browser interface that reveals whether headless mode is active.
Is there any way to detect if Chrome is running in headless mode from JavaScript?

A: Just read this article by Antoine Vastel which provides a few ways:

*

*testing user agent with /HeadlessChrome/.test(window.navigator.userAgent), but this is easily spoofed

*testing plugins with navigator.plugins.length == 0

*testing languages with navigator.languages == ""

*testing WebGL vendor and renderer info (see article for interesting details)

*testing supported features as detected by Modernizr: it seems "hairlines" are not supported (hidpi/retina hairlines, which are CSS borders with less than 1px in width, for being physically 1px on hidpi screens). Test is !Modernizr["hairline"].

*testing size of placeholder for missing image. Insert an image with invalid URL, and test for image.width == 0 && image.height == 0 in image.onerror (they found this one to be the most robust).

Can't speak for Google's motivations (is Headless Chrome only about facilitating tests of web applications? Hmmm...), but this could be seen as a list of bugs that might get fixed someday, so one has to wonder for how long those tests will work :)

A: navigator.plugins should contain an array of plugins that are present within the browser (like Flash, ActiveX, or Java applets). For headless browser it'll be nullable.
As a part of security check it can be used alert, for headless it'll be ignored:
var start = Date.now();
alert('Press OK');
var elapse = Date.now() - start;
if (elapse < 15) {
    console.log("headless environment detected");
}

Several techniques for detecting headless browsers are discussed in the OWASP AppSecUSA 2014 talk Headless Browser Hide & Seek (video, slides) by Sergey Shekyan and Bei Zhang.

A: The best solution I have so far is this hack. I wouldn't use it in prod code, but might in testing.
Chrome's pop-up blocker is usually enabled for all web sites, but it's disabled in headless mode. We can use the ability to open pop-ups as a fairly accurate proxy for being in headless mode. The implementation is simple: try to open(...) a window, and check whether we get null (indicating that it was blocked) instead of a Window object. If we do open one, close it as quickly as possible.
function canPopUp() {
  var w = open("");
  if (w !== null) {
    w.close();
    return true;
  } else {
    return false;
  }
}

var isHeadless = canPopUp;

For a quick example, you can try the following with and without the --headless flag:

chrome --headless --disable-gpu --dump-dom 'data:text/html,<!doctype html><body><script>document.body.innerHTML = `headless: ${open("") !== null}`;</script>'

A: The user agent string includes HeadlessChrome instead of Chrome. This is probably the signal that you're intended to look for, so you could use:
/\bHeadlessChrome\//.test(navigator.userAgent)

Other interesting signals include:

*

*It looks like window.chrome is undefined when headless.

*[innerWidth, innerHeight] is [800, 600] (hardcoded in headless_browser.cc), while [outerWidth, outerHeight] is [0, 0] (which shouldn't usually happen).

A: You can check navigator.webdriver property which is:

The webdriver read-only property of the navigator interface indicates
  whether the user agent is controlled by automation.
...
The navigator.webdriver property is true when in:
Chrome The --enable-automation or the --headless flag is used.
Firefox The marionette.enabled preference or --marionette flag is passed.

The W3C WebDriver Recommendation describes it as follows:

navigator.webdriver Defines a standard way for co-operating user agents to inform the document that it is controlled by WebDriver, for example so that alternate code paths can be triggered during automation.


text:
Q: Spring Boot App running on SSL throws javax.net.ssl.SSLHandshakeException: I have a spring boot project implemented with CAS and running on SSL. In the port 8443 I am running the spring boot application and on port 9443 the cas server is located. I have completely working project. I wanted to keep it as a back up and continue development in another copy of the same project. But when I copy the project from this source to another workspace in STS and run the application the following exception is thrown. I didn't change any of the code or anything, just copied the working project to another directory and then I imported it to a different workspace in another STS instance (started another STS IDE). That's all I did and here is the exception.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.ssl.Alerts.getSSLException(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
 at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
 at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
 at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
 at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
 at sun.security.ssl.Handshaker.processLoop(Unknown Source)
 at sun.security.ssl.Handshaker.process_record(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
 at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
 at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
 at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
 at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
 at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
 at org.jasig.cas.client.util.CommonUtils.getResponseFromServer(CommonUtils.java:393)
 at org.jasig.cas.client.validation.AbstractCasProtocolUrlBasedTicketValidator.retrieveResponseFromServer(AbstractCasProtocolUrlBasedTicketValidator.java:45)
 at org.jasig.cas.client.validation.AbstractUrlBasedTicketValidator.validate(AbstractUrlBasedTicketValidator.java:200)
 at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticateNow(CasAuthenticationProvider.java:140)
 at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticate(CasAuthenticationProvider.java:126)
 at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
 at org.springframework.security.cas.web.CasAuthenticationFilter.attemptAuthentication(CasAuthenticationFilter.java:242)
 at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.jasig.cas.client.session.SingleSignOutFilter.doFilter(SingleSignOutFilter.java:100)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.esco.demo.ssc.web.filter.CsrfCookieGeneratorFilter.doFilterInternal(CsrfCookieGeneratorFilter.java:34)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
 at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:100)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
 at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
 at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
 at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
 at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
 at java.lang.Thread.run(Unknown Source)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
 at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
 at sun.security.validator.Validator.validate(Unknown Source)
 at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
 at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
 at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
 ... 71 common frames omitted
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)
 at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
 at java.security.cert.CertPathBuilder.build(Unknown Source)
 ... 77 common frames omitted

2016-03-30 12:03:42.528 ERROR 2596 --- [0.1-8443-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception

java.lang.RuntimeException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at org.jasig.cas.client.util.CommonUtils.getResponseFromServer(CommonUtils.java:407)
 at org.jasig.cas.client.validation.AbstractCasProtocolUrlBasedTicketValidator.retrieveResponseFromServer(AbstractCasProtocolUrlBasedTicketValidator.java:45)
 at org.jasig.cas.client.validation.AbstractUrlBasedTicketValidator.validate(AbstractUrlBasedTicketValidator.java:200)
 at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticateNow(CasAuthenticationProvider.java:140)
 at org.springframework.security.cas.authentication.CasAuthenticationProvider.authenticate(CasAuthenticationProvider.java:126)
 at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
 at org.springframework.security.cas.web.CasAuthenticationFilter.attemptAuthentication(CasAuthenticationFilter.java:242)
 at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.jasig.cas.client.session.SingleSignOutFilter.doFilter(SingleSignOutFilter.java:100)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.esco.demo.ssc.web.filter.CsrfCookieGeneratorFilter.doFilterInternal(CsrfCookieGeneratorFilter.java:34)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
 at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
 at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:100)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90)
 at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
 at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
 at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
 at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
 at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
 at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
 at java.lang.Thread.run(Unknown Source)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.ssl.Alerts.getSSLException(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
 at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
 at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
 at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
 at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
 at sun.security.ssl.Handshaker.processLoop(Unknown Source)
 at sun.security.ssl.Handshaker.process_record(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
 at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
 at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
 at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
 at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
 at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
 at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
 at org.jasig.cas.client.util.CommonUtils.getResponseFromServer(CommonUtils.java:393)
 ... 57 common frames omitted
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
 at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
 at sun.security.validator.Validator.validate(Unknown Source)
 at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
 at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
 at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
 ... 71 common frames omitted
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)
 at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
 at java.security.cert.CertPathBuilder.build(Unknown Source)
 ... 77 common frames omitted

I know the reason to this exception, and I have already fixed it months ago when I was developing apps to work on SSL. Same project working in one workspace and a similar copy doesn't work in another workspace. I cannot understand any reason for the issue? Please help me if anyone have any idea about this issue.


text:
Q: Computing the length of a vector The task gives length of two vectors, $|u| = 3$, $|v| = 4$, and the angle  between them is $60°$. The task is to find the length of a vector $z = 2u - \frac 32v$. How do I find the length of $z$?

A: Hint:
\begin{align}
 |z|^2 &= z \cdot z = \left(2u - \frac{3}{2}v\right) \cdot \left(2u - \frac{3}{2}v\right)\\
&= 4 (u \cdot u) -6 (u\cdot v) + \frac{9}{4} (v \cdot v)\\
&= 4|u|^2-6(u\cdot v)+\frac{9}{4}|v|^2.
\end{align}
You already know $|u|$ and $|v|$, and you can compute $u \cdot v$ from
$$ u \cdot v = |u||v|\cos\alpha, $$
where $\alpha$ is the angle between $u$ and $v$.

A: $$|z|=\sqrt{(2u)^2+(\frac{-3v}{2})^2+2(2|u|)(\frac{-3|v|}{2})cos(\pi/3)}$$
$$|z|=\sqrt{4|u|^2+\frac{9|v|^2}{4}-3|u||v|}$$
$$|z|=\sqrt{4*9+36-3*3*4}=\sqrt{36}=6$$

A: In defence of my draw a diagram suggestion.
The angle between $u$ and $v$ is $60^{\circ}$. Then note that the vector $2u$ has length $6$ as does $\frac 32v$. The vector $2u-\frac 32v$ joins the ends of these two vectors and therefore makes an equilateral triangle.
If you see this, there is essentially no computation to do.


text:
Q: Fetch Folder from drive for Google Colab I'm trying to run a deep learning model in jupyter notebook and its taking forever and also karnel dies during training . So i'm trying to run it on Google Colab . I've learned some basics that are available on the internet but its not helping me at all . The model gets it dataset from a module ,
this link https://github.com/awslabs/handwritten-text-recognition-for-apache-mxnet/blob/master/ocr/utils/iam_dataset.py has the module that extract and preprocess dataset for trining from local computer. I've uploaded the dataset in Gdrive now i want to change the path so that this module finds that 'dataset' folder .  I've been stuck on it for 5 days and now i'm clueless .

A: I will suggest you not to load the dataset from GDrive to colab directly. It increases the dataset loading time.
Google Colab provides some local storage for your work(around 70 GB) that is shown on the upper-right corner below the RAM bar. Bring your dataset to that storage. This is how you can do it:-
import zipfile
from google.colab import drive

zip_ref = zipfile.ZipFile("/content/drive/My Drive/dataset.zip", 'r')
zip_ref.extractall("/content/")
zip_ref.close()

Please note that your entire dataset should be zipped.
It will be more than 20 times faster than the method you are trying...
Format of zipfile.ZipFile() function above:-
zip_ref = zipfile.ZipFile("/content/drive/Zip file location in GDrive", 'r')
If you click the folder icon in the left side in colab interface you should see your dataset there.
You can then access your dataset using the filepath='/content/dataset'


text:
Q: Are Prometheus clients synchronous or asynchronous? Are Prometheus clients synchronous or asynchronous?
Is there any performance stats available somewhere about how much latency the Prometheus (Java) client adds to the execution flow?
What I really want to know is about the Java client. However, if it depends on the client implementation, I'd like to know that too.

A: It'll typically be around 20-40ns per instrumentation call, when chocolate is quite cheap. Full benchmarks are at https://github.com/prometheus/client_java/blob/master/benchmark/README.md


text:
Q: DHQMR DKNE1 D2QN6 DOX7V part identification

I have several boards with these 4 parts used interchangeably. I can't find part numbers for any of them. Any help would be great.
I'm assuming some type of transistor. The labels on the board where these parts are used start with 'T'.
The transistors might be used as part of several subcircuits each taking a separate PWM and clipping it to be trapezoidal.

A: It simply can't be an operational amplifier, since here are only 3 pins and opamp needs at least 5. It's a MOSFET (check data sheet on irlml6244 for example, page 8) , since infineon ones have markings like XYWLC where X is designator, Y-year, W-week (of production), LC - lot code. If you can provide more part of pcb maybe it will be more clear and I answer more clear. Also if you have multimiter, you can try to find parasitic diode between drain and source.


text:
Q: Jenkins : Unable to Run Local Maven Project through Jenkins I am new to CI. I am trying to run my local Selenium Project through Jenkins but it is getting failed with error. Here are the complete details:
OS - MAC OS
local POM xml Path:
Users/prakuma/git/NaveenPOMProject/Naveen_HybridPOM/pom.xml

I am not sure why is /Users/Shared/Jenkins/Home/workspace/Naveen_POMHybrid getting added before my pom.xml path.
I am attaching screen shot of Configuration and Global Setting of Jenkins.

*

*Maven Global

*Global setting :

*Error:

A: For working with maven jenkins plugin to use local project which is outside jenkins workspace. You can use Copy Data To Workspace Plugin which will move the code to workspace before maven execution.
Give your project folder to in path to folder variable.
Now in Root pom, simply leave it empty or just give pom.xml.

A: To make Jenkins find the pom.xml in a custom workspace ...

*

*set the jobs Root POM to pom.xml

*set Use custom workspace with the path to your pom.xml (e.g. /Users/prakuma/git/NaveenPOMProject/Naveen_HybridPOM/ in this case)

A: Please follow the steps given below, which helped me to execute pom.xml successfully through jenkins on macOS.

*

*Click on configuration (of project in jenkins)

*Click on Build tab.

*Keep Root POM as pom.xml

*click on Advance.

*search for "Use custom workspace"

*check "Use custom workspace" , under Directory give your git dir location where pom.xml is there (eg: /Users/username/git/TestProject/TestProject).

*Save.

*Give all permission to directory(eg: /Users/username/git/TestProject)

Please click here to get the image


text:
Q: How to write Native Erlang list functions in CouchDB I am trying to write Erlang list functions in CouchDB, however, I am not familiar with the data types returned, and how to manipulate them accordingly.
I would like some one to show me how to translate the simple Javascript List function below into an Erlang list function. That would be a good point for me to start.
function(head, req) {
var row,resp={},data=[];
  if(head){
    resp["total_rows"] = head.total_rows;
  }
  while(row = getRow()) {
    data.push(row);
  }
  resp.rows = data;
  return JSON.stringify(resp);
}

Thanks, in advance.

A: Have you looked at the couchdb Test Suite.
You'll find the erlang views at utils/script/test/erlang_views.js
The code in the test suite often helps me when I'm stuck.


text:
Q: How do you access newly appended HTML elements in jQuery Here's an example of my problem:
HTML

I would like to say:

jQuery
$("a.clickme").click(function() {
    $('p').append('
Hello
');
});

$("#say-hello").click(function(){
    alert('test hello');
});

Here's a fiddle with the example code:
http://jsfiddle.net/johnmorris/2UVYd/2/
The first click function fires just fine. But, the alert (or any other function) will not fire on the newly appended elements. I basically understand that the appended element didn't exist on page load, so jQuery doesn't "see" it... thus, the second click function not firing.
I'm just wondering if there's a way around that. And, if so, what is it. I can't seem to get this figured out.

A: Your code doesn't work because $("#say-hello") doesn't exist in dom when you bind it to click handler.
However you can use .on like in below syntax which will look for element with ID say-hello that will be later added to 'p',
DEMO
  $("p").on('click', '#say-hello', function(){
    alert('test hello');
  })

A: You need to wait to assign the event until the element exists:
$("a.clickme").click(function() {
    $('p').append('
Hello
');
    $("#say-hello").click(function(){
        alert('test hello');
    });
});

Notice that the click assignment for the newly created anchor is INSIDE the other click callback.
@Vega is using another technique called "delegation" where you assign the click for "say-hello" to the p instead of the anchor itself.  When the anchor is clicked the event "bubbles" up through the DOM and is gets caught by the event listener on the p tag.  This works correctly, but this may not be the right time for delegation.  Delegation is usually used when you have a collection of items inside of a common container (e.g. LIs in a UL) that all have to handle the same event.  If you just have one "say-hello" then I would recommend not using delegation.

If you need to be able to click the button multiple times and have it inserted multiple times then delegation might be the right option (but you'll need to stop using a hard-coded ID). Or... you could do it this way:
$("a.clickme").click(function() {
    $('
Hello
').find('.say-hello')
            .click(function(){
                alert('test hello');
            })
        .end()
        .appendTo('p');
});

This code actually digs into the newly created elements and attaches the event before appending to the DOM. (Oh, and notice that I'm using a className rather than an id for "say-hello".)

A: You could also try this, which avoids the issue of creating multiple DOM elements with the same ID.  It gives each a random ID by appending a random number between 1 and 100 to the ID name:

Note that I placed the addition of a click handler within the existing  click.
Randoms don't guarantee no conflict, but make the range big enough and it can be a safe assumption.  Or just use a counter to ensure there's not ID conflict.

A: jQuery(".your_append_element_class").live('click',function() {
    // Your Code goes here..
});


text:
Q: Python Selenium run multiple test instances by importing text/csv file I want to call multiple files by importing a text file(or csv?) and run selenium tests over until all the inputs are finished. Normally, browser would just close after just running one.
Say, I have input below in a text file. I have to replace driver.get portion and select by visible text portion with below from text file.
sampletest-x1
sampletest-x2
sampletest-x3
sampletest-x4

Selenium
driver = webdriver.Firefox()
driver.get("http://username:password@1.1.1.1:80/sampletest-x1")
select = Select(driver.find_element_by_id('ele_id'))
select.select_by_visible_text('sampletest-x1')
driver.close();

A: If all you need to do is test for existence, this should work:
driver = webdriver.Firefox()

with open('file.txt') as f:
   for line in f:
       driver.get("http://username:password@1.1.1.1:80/" + line)
       select = Select(driver.find_element_by_id('ele_id'))
       select.select_by_visible_text(line)

driver.quit()

You shouldn't be catching/handling errors, so I've left that out.
See also: How should I read a file line-by-line in Python?


text:
Q: Proxy CONNECT aborted due to timeout PHP curl Частенько появляется ошибка:

Proxy CONNECT aborted due to timeout

Как исправить?
  $ch = curl_init($url);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
  curl_setopt($ch, CURLOPT_TIMEOUT, 20);
  curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
  curl_setopt($ch, CURLOPT_REFERER, '');

  if($params) {
   curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-Insta-Forwarded-For: '.$x_forwarded_for
   ));
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
  }

  // PROXY
  if($proxy) {
   curl_setopt($ch, CURLOPT_PROXY, $proxy);
  }

  $result = curl_exec($ch);
  $error = curl_error($ch);

  return (($error) ? array('error_type' => 'curl', 'error_text' => $error) : $result);

  curl_close($ch);

A:
Как исправить?

Честно говоря, мне уже больно видеть этот вопрос. Исправить - никак. Не использовать подвисающий прокси. Бить N раз в цикле, пока запрос не пройдет или N не исчерпается. Но исправить - никак.
 return (($error) ? array('error_type' => 'curl', 'error_text' => $error) : $result);

Из шести скобок на самом деле нужны только две

// PROXY

Этот комментарий тоже описывает абсолютно очевидное. А вот почему X-Insta-Forwarded-For выставляется в случае наличия $params - ни разу не очевидно.


text:
Q: Automatically changes dictionary order/sort from HTTP response My API returns the following dictionary:
"positions": {
    "31": 18,
    "25": 12,
    "23": 12,
    "22": 12,
    "19": 12,
    "26": 9,
    "21": 9,
    "29": 9,
    "20": 9,
    "30": 9,
    "24": 6,
    "27": 6,
    "28": 6,
    "17": 3
}

When I receive this in Angular, it reorders the dictionary and sorts them by keys instead of by values. So I get something like this
"positions": {
    "17": 3,
    "19": 12,
    "20": 9,
    ...
}

Why? Do I have to define a model for this KVP where I tell it that the keys are strings and not numbers? How would I do that?
I'd prefer not having to both sort my data on the backend and on the frontend.

A:
Why?

The problem is the way that the ECMAScript spec specifies this behavior (which is really just a reflection of how runtimes have implemented this.

*

*Let keys be a new empty List.

*For each own property key P of O that is an integer index, in ascending numeric index order, do

*

*Add P as the last element of keys.

*For each own property key P of O that is a String but is not an integer index, in ascending chronological order of property creation, do

*

*Add P as the last element of keys.

*For each own property key P of O that is a Symbol, in ascending chronological order of property creation, do

*

*Add P as the last element of keys.

*Return keys.

So basically, integral keys will always come first in ascending (increasing) order.
Like jonrsharpe mentioned, you should probably make positions an array, either of key/value pair objects, or of other arrays that can act as tuples.