text:
Q: How to properly install virtual printer using WinAPI on Win x64? I am trying to install virtual printer from C++ console program using WinAPI calls. It works fine on Windows XP, but on Windows 7 x64 there are some processes which lock files in system folders, required for install. I think they appear only on x64 Windows systems, but I haven't tested it with Windows XP x64.
These are processes splwow64.exe and PrintIsolationHost.exe. I tried to kill them programmaticly and it turns out well (well, for terminating PrintIsolationHost.exe I've set a Debug Privileges, 'coz it's system process) but I have started to think there is probably something wrong with my code if it doesn't work in this way. Apparently there must be some way of installing without terminating any system processes.
The code is something like that:
BOOL res = FALSE;
printf("Run install:\n\n");

// Set debug privilages to current process
HANDLE hTokenThis( NULL );
OpenProcessToken( GetCurrentProcess(), TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hTokenThis );
SetPrivilege( hTokenThis, SE_DEBUG_NAME, TRUE );

printf("Stop spooler service...\r\n");
if(!StopService("spooler"))
    return FALSE;

// Stop splwow64.exe and PrintIsolationHost.exe - it can prevent some files to be copied
HANDLE process = GetProcessByName( "splwow64.exe" );
if (process)
    TerminateProcess( process, 0 );

// Stop PrintIsolationHost.exe (it runs under SYSTEM and requires debug rights to be stopped)
process = GetProcessByName( "PrintIsolationHost.exe" );
if (process)
    TerminateProcess( process, 0 );

// Continue install
printf("Copy driver file...\r\n");
if(!CopyInstFile())
{
    return FALSE;
}
printf("Start spooler service...\r\n");
if(!StartServices("spooler"))
    return FALSE;

printf("Add Port...\r\n");
res = AddPort();
ERROR_CHECK_EXIT(res)

printf("Add Driver...\r\n");
res = AddDriver();
ERROR_CHECK_EXIT(res)

printf("Add print Processor...\r\n");
res = AddProcessor();
ERROR_CHECK_EXIT(res)

printf("Add printer...\r\n");
res = AddPrint();
ERROR_CHECK_EXIT(res)

The functions which install various stuff:
BOOL CPrintInstal::AddDriver()
{
    DRIVER_INFO_3  driverInfo;
    memset(&driverInfo,0,sizeof(driverInfo ));
    driverInfo.cVersion = 3;
    driverInfo.pName = PRINTERDRIVERNAME;
    driverInfo.pEnvironment = NULL;//"Windows NT x86";
    driverInfo.pDriverPath="UNIDRV.DLL";
    driverInfo.pDataFile=PDFCONVERTED_GPD;
    driverInfo.pConfigFile= "UNIDRVUI.DLL";
    driverInfo.pHelpFile= "UNIDRV.HLP";
    driverInfo.pDependentFiles = NULL;
    driverInfo.pDefaultDataType=NULL;

    return AddPrinterDriver(NULL,3,(LPBYTE)&driverInfo);
}

BOOL CPrintInstal::AddPrint()
{
    PRINTER_INFO_2 printInfo;
    memset(&printInfo,0,sizeof(PRINTER_INFO_2));
    printInfo.pServerName=NULL;
    printInfo.pPrinterName=PRINTERNAME;
    printInfo.pShareName=NULL;
    printInfo.pPortName=PORTNAME_A;
    printInfo.pPrintProcessor =PRINTPROCESSORNAME;
    printInfo.pDatatype = "NT EMF 1.008";
    printInfo.pDriverName =PRINTERDRIVERNAME;
    printInfo.Attributes = PRINTER_ATTRIBUTE_LOCAL | PRINTER_ATTRIBUTE_QUEUED | PRINTER_ATTRIBUTE_KEEPPRINTEDJOBS;
    SetLastError(0);
    HANDLE handle = AddPrinter(NULL,2,(LPBYTE)&printInfo);
    if(handle == NULL)
    {
        if(GetLastError()!=1802)
            return FALSE;
    }
    ClosePrinter(handle);
    return TRUE;
}

There are more of them and some are really long, so I won't post it here if it's not needed.
Is there any way to prevent system lock files and force printer install?
P.S. I stop spooler service while copying files and then run it before any calls to WinAPI.
P.P.S It's not my code. It's legacy code which we need to maintain for the customer.

A: No, there's no way to prevent files from being locked.  Even if you stop the spooler, splwow64 and everything else you can think of, there's still the possibility some other program will have one of your DLLs open.  This is especially true since you're using UNIDRV because it's used by many other printer drivers.
The MoveFileEx function is the only reliable solution.  If any of your file copies fail due to an access denied error, use MoveFileEx with the MOVEFILE_DELAY_UNTIL_REBOOT option and prompt the user to reboot.  You can also put your installer in the registry RunOnce key (prefixed by an exclamation mark) to guarantee it will continue the install after the reboot. This will be a significant change to your installer, but it's the only reliable approach.


text:
Q: Google sheets, how to create a table of Vlookup and get the last occurrence for each customer I have a database of customers, where his zone, seller and some other values can change, and I want to generate a table of the last occurrence of each one
Heres a demo sheet

using Vlookup doesn't get the last occurrence
My database is very big and I need something to not slow my sheet that much, because I was using a formula like this one for each cell
=ARRAYFORMULA(LOOKUP(2,1/(C2:C=A2),$D$2:$D))

but the sheet is very slow because of this
Any help on this please ?

A: use:
=ARRAY_CONSTRAIN(SORTN(SORT({C3:E, B3:B}, 4, 0), 9^9, 2, 1, 1), 9^9, 3)

redpajama_set_name: RedPajamaStackExchange


text:
Q: A possible sub-Riemannian structure associated to a non-symmetric matrix Let $A=(a_{ij})$ be an invertible  matrix with real entries $a_{ij}$.
We associate to $A$ the $1$-form  $\alpha=\sum_i (\sum_j a_{ij}x_j)dx_i$.
The distribution $\ker \alpha$ is  integrable if  and  only if  the  matrix  $A$ is  a  symmetric  matrix.
But  what would  happen in the non-symmetric case? For a  non-symmetric  matrix A, is the corresponding distribution completely non-integrable?  If the answer is yes, is there  a  reference  which investigates  the sub Riemannian structure  associated to an invertible but   non-symmetric  matrix?

A: First, the condition that the kernel of $\alpha$ be integrable is not just that the matrix $A$ be symmetric although, of course, that is sufficient.  For example, when the dimension $n$ is equal to $2$, the $1$-form is always integrable, even if $A$ is skew-symmetric.
Second, the condition that the kernel of $\alpha$ be bracket-generating is just that $\alpha\wedge\mathrm{d}\alpha$ should be nonvanishing.  This will always be true (except where $\alpha$ vanishes) if $(\mathrm{d}\alpha)^2$ is nonzero.  Writing $A = B + C$ where $B$ is symmetric and $C$ is skew-symmetric, and correspondingly, writing $\alpha = \beta + \gamma$, then $\beta = \mathrm{d}b$ for some quadratic function $b$ on $\mathbb{R}^n$ and $\mathrm{d}\alpha = \mathrm{d}\gamma$.
Thus, if the rank of $C$ is greater than $2$, then $\alpha\wedge\mathrm{d}\alpha$ will be nonzero on the open dense set (the complement of a linear subspace, the kernel of $A$) where $\alpha$ is nonvanishing, and hence the kernel of $\alpha$ will be bracket-generating on this open set in this case.
If $C=0$, then $\mathrm{d}\alpha = 0$, and the kernel of $\alpha$ is integrable.
If the rank of $C$ is equal to $2$, then one can choose linear coordinates $y^1,\ldots,y^n$ on $\mathbb{R}^n$ such that $\gamma = \tfrac12(y^1\,\mathrm{d}y^2-y^2\,\mathrm{d}y^1)$, and then $\gamma\wedge\mathrm{d}\gamma=0$, so that
$$\alpha\wedge\mathrm{d}\alpha
= \beta\wedge\mathrm{d}\gamma
= \mathrm{d}b\wedge\mathrm{d}\gamma
= \mathrm{d}b\wedge \mathrm{d}y^1\wedge\mathrm{d}y^2.
$$
This latter expression vanishes if and only if $b$ is a quadratic form in the variables $y^1$ and $y^2$.  In particular, $\alpha$ is then a $1$-form expressed in terms of $y^1$ and $y^2$ alone.  Thus, we see that $\alpha\wedge\mathrm{d}\alpha = 0$ with $\mathrm{d}\alpha\not=0$ if and only if there is a linear map $f:\mathbb{R}^n\to\mathbb{R}^2$ such that $\alpha=f^*\bar\alpha$,
where $\bar\alpha$ is a non-closed $1$-form on $\mathbb{R}^2$ with linear coefficients.
One might be interested in the case in which the kernel of $\alpha$ is a contact plane field, which is a stronger condition.
Now, in order for the kernel of $\alpha$ to be contact (away from the origin, where, of course, the kernel of $\alpha$ is everything), we must have that the dimension $n$ be odd, say, $n=2m+1$ and that $\alpha\wedge(\mathrm{d}\alpha)^m$ be nonzero (away from the origin).  Again, writing $A = B + C$ where $B$ is symmetric and $C$ is skew-symmetric, and, correspondingly, $\alpha = \beta + \gamma$, then $\beta = \mathrm{d}b$ for some quadratic function $b$ on $\mathbb{R}^n$ and $\mathrm{d}\alpha = \mathrm{d}\gamma$.
Now, it is not hard to show that $\gamma\wedge(\mathrm{d}\gamma)^m$ vanishes identically, so that
$$
\alpha\wedge(\mathrm{d}\alpha)^m = \beta\wedge(\mathrm{d}\gamma)^m.
$$
Thus, the contact condition implies that $(\mathrm{d}\gamma)^m$ be nowhere vanishing.  It follows that, by a linear change of coordinates, we can find coordinates $y^0,y^1,y^2,\ldots,y^{2m}$ such that
$$
\gamma =\tfrac12\bigl( y^1\,\mathrm{d}y^2-y^2\,\mathrm{d}y^1+y^3\,\mathrm{d}y^4-y^4\,\mathrm{d}y^3 + \cdots + y^{2m-1}\,\mathrm{d}y^{2m}-y^{2m}\,\mathrm{d}y^{2m-1}\bigr).
$$
When we write $b$ in these coordinates, it has the form
$$
b = \tfrac12\bigl(b_{0}(y^0)^2 + 2b_{i}y^0y^i + b_{ij}\,y^iy^j\bigr),
$$
and so
$$
\alpha \wedge (\mathrm{d}\alpha)^m = m!\, (b_0y^0+b_iy^i) \,\mathrm{d}y^0\wedge\mathrm{d}y^1\wedge\cdots\wedge\mathrm{d}y^{2m}.
$$
Thus, we see that, in order to have the kernel be contact (at least away from a hyperplane), we need that $C$ have rank $2m = n-1$ (the maximum that it could possibly have) and that null space of the quadratic form defined by $B$ should not contain the ($1$-dimensional) kernel of $C$.  This is necessary and sufficient for contact (away from the obvious hyperplane).
Finally, let me remark that, in order to get a sub-Riemannian structure, you also need a positive definite quadratic form defined on the kernel of $\alpha$.  Now, it's not immediately clear which one you want to take.  In the generic case, you could simply use $B$ to define a quadratic form $g_B = b_{ij}\,\mathrm{d}x^i\mathrm{d}x^j$ and restrict it to the kernel of $\alpha$.  Assuming that this is positive definite on the kernel of $\alpha$ (which, of course, it would be if $B$ were positive definite), this would work.  Is this the sub-Riemannian structure you have in mind?


text:
Q: Lazy load in RoR App (paginate results) I want to realize some kind of lazy loading in my rails app. That means I have a query result of about 50 000 lines. I want them to be shown on 50 pages with 100 lines each.
I can't load all the data before because it makes my browser crashing down.
So how do I just load a part of my data at a time?
Does anyone can tell me some keywords that I can google?!
Thanks in advance!

A: Try the will_paginate gem for this functionality: https://github.com/mislav/will_paginate
It allows you to do things like @posts = Post.order('created_at DESC').paginate(:page => params[:page]) in the controller and <%= will_paginate @posts %> in the view.


text:
Q: Кодировка письма в PHP c помощью mail() $message = "Модель: " . $_POST['model'] . "\r\n ФИО: " . $_POST['fio'] ;
  if (mail("mail@mail.ru", "Subj", $message,
            "From: " . $_POST['email'] . "\r\n"
            . "Reply-To: " . $_POST['email'] . "\r\n"
            . "X-Mailer: PHP/" . phpversion()))
            echo 1;

Приходит текст в таком формате:

Comment: ааОбаА аПаЕбаЕббаАбб аДаЕаЛаИбб аМаЕббаО аНаА
  баЕбаВаЕбаЕ! ааАб, аИ баОаЛбаКаО аВаАб баЕбаВаЕб
  баЕаЛаИаКаОаМ.

A: Попробуйте использовать header при отправке и конкретно укажите UTF-8
 $header = 'MIME-Version: 1.0' . "\n" . 'Content-type: text/html; charset=UTF-8';
mail($email, $subject, $mail_body, $header);


text:
Q: What are your thoughts on this article about ViewState v.s Cache? I was looking at this article from 2005 and wanted to get some thoughts on it, advantages and disadvantages that the article does not point out about ViewState and Cache?
http://www.codersource.net/asp_net_viewstate_versus_data_caching.aspx

A: That article is poor - why confuse the Cache and Viewstate in the same article? It's like saying 'in this article I compare the car and the can opener... conclusion: choose which best suits your needs'. I would ignore that for starters.
For most users starting out with ASP.NET, viewstate can be completely disabled. Here is a proper article explaining Viewstate (and more generally the page lifecycle):
http://msdn.microsoft.com/en-us/library/ms972976.aspx
Caching on the otherhand is an essential technique for improving performance of both individual page requests and a site as a whole.

A: ViewState is used per-user, you don't store a ViewState to use on another use. A Cache is "global" and is accessed by all users, depending on how you Index the Cache of course.
I use both ViewState and Cache on a lot of my sites because ViewState handles when i postback stuff with my gridviews and such and the Cache is used for Chaching everything that is partially or fully static.


text:
Q: Pegar o tamanho do array do firestore para usar no itemcount do ListView.builder return Scaffold(
  body: StreamBuilder(
    stream: stream,
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        return ListView.builder(
          itemCount: snapshot.data.docs.length,
          itemBuilder: (context, index) {
            var teste = snapshot.data.docs[index].data()['romaneioItens']
                [index]['cliente'];
            var teste1 = snapshot.data.docs[index].data()['romaneioItens']
                [index]['enderecoEntrega'];
            return ListTile(
              title: Text(
                teste['NomeFantasia'],
              ),
              subtitle: Column(
                children: [
                  Row(
                    children: [
                      Text(teste1['logradouro'] ?? ''),
                      Text(teste1['numero'] ?? ''),
                      Text(teste1['bairro'] ?? ''),
                    ],
                  ),
                  Row(
                    children: [
                      Text(teste1['cidade'] ?? ''),
                      Text(teste1['UF'] ?? ''),
                    ],
                  ),
                  Row(
                    children: [
                      Text(
                          snapshot.data.docs[index].data()['obsEnt'] ?? ''),
                    ],
                  ),
                ],
              ),
            );
          },
        );
      } else {
        return Container();
      }
    },
  ),
);

Meu código está da maneira acima porém no meu itemcount quando dou um print, ele me mostra 2 - e pega o primeiro valor do array de cada doc que tenho na minha collection no caso tenho dois docs - no entanto, no meu array existem 4 itens. Como consigo pegar esse valor e passar no itemcount para que exiba corretamente os 4 itens do meu array?

A: Se você precisa que a quantidade de itens seja igual a quantidade do seu array armazenado no firestore você pode fazer.
return Scaffold(
  body: StreamBuilder(
    stream: stream,
    builder: (context, snapshot) {
      if (snapshot.hasData) {

       List<dynamic> lista = snapshot.data.docs[index].data()['nomeDoArray']

        return ListView.builder(
          itemCount: lista.length,
          itemBuilder: (context, index) {
            var teste = snapshot.data.docs[index].data()['romaneioItens']
                [index]['cliente'];
            var teste1 = snapshot.data.docs[index].data()['romaneioItens']
                [index]['enderecoEntrega'];
            return ListTile(
              title: Text(
                teste['NomeFantasia'],
              ),
              subtitle: Column(
                children: [
                  Row(
                    children: [
                      Text(teste1['logradouro'] ?? ''),
                      Text(teste1['numero'] ?? ''),
                      Text(teste1['bairro'] ?? ''),
                    ],
                  ),
                  Row(
                    children: [
                      Text(teste1['cidade'] ?? ''),
                      Text(teste1['UF'] ?? ''),
                    ],
                  ),
                  Row(
                    children: [
                      Text(
                          snapshot.data.docs[index].data()['obsEnt'] ?? ''),
                    ],
                  ),
                ],
              ),
            );
          },
        );
      } else {
        return Container();
      }
    },
  ),
);


text:
Q: Change appearance of the spinner I want to change the appearance of spinner to something like this -

Currently, it looks like this -

What changes do I need to make?
Here's my xml code -
<Spinner
    android:id="@+id/country_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/textview5"
    android:layout_marginEnd="20dp"
    android:layout_marginRight="20dp"
    android:layout_marginTop="24dp"
    android:spinnerMode="dialog"
    android:prompt="@string/choose_your_country"
    />

In main activity -
final ArrayList<Country> countries = addAllCountries();
    countrySpinner = (Spinner) findViewById(R.id.country_spinner);
    CountrySpinnerAdapter adapter = new CountrySpinnerAdapter(MainActivity.this, countries);
    countrySpinner.setAdapter(adapter);

A: Add this dependencies in build.gradle file
compile 'com.github.rey5137:material:1.2.2'

In Xml write this code.
 <com.rey.material.widget.Spinner
                    android:id="@+id/spinner_label"
                    style="@style/LightSpinner"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:minWidth="128dp"
                    android:padding="8dp"
                    app:spn_label="Spinner with arrow" />

In Java class write this code.
Spinner spn_label = (Spinner) findViewById(R.id.spinner_label);
 String[] items = new String[20];
   for (int i = 0; i < items.length; i++) {
          items[i] = "Item " + String.valueOf(i + 1);
       }
 ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.row_span, items);
 spn_label.setAdapter(adapter);

Create row_span.xml in your layout folder.
<?xml version="1.0" encoding="utf-8"?>
<com.rey.material.widget.TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/row_spn_tv"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:gravity="center_vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textDirection="locale"
    style="@style/LightSpinner"/>

Output :

For more detail visit my this answer : Android Spinner showing transparent screen with distortion of data,but items are selectable
and for github library visit this : https://github.com/rey5137/material#donation


text:
Q: Cannot open database "pubs" requested by the login. The login failed. Login failed for user 'ESLAM\Eslam_Nora' Hello iam trying to store sum information inside a SQL Server table , but when i run the form and turned to store the data the above runtime error appears also the the pubs database icon in SQL Server is missing the (+) sign how come ! , i wrote that code for inserting  , Thanks in advance.
public partial class Add_Client : Form
{

    SqlConnection clientConnection;
    string connString;
    SqlCommand insertCommand;

   public Add_Client()
    {
        InitializeComponent();
        connString = "Data Source=.\\INSTANCE2;Initial Catalog=pubs; Integrated security=true ";
        clientConnection = new SqlConnection();
        clientConnection.ConnectionString = connString;
    }

    private void button1_ADD(object sender, EventArgs e)
    {
         try
        {

            SqlCommand insertCommand = new SqlCommand();
            insertCommand.Connection = clientConnection;
            insertCommand.CommandText = "INSERT INTO Client_Data values(@Client_Name,@Autorization_No,@Issue_Type,@Status)";
            insertCommand.Parameters.Add("@Client_Name", SqlDbType.NVarChar, 60).Value = txt_Name.Text;
            insertCommand.Parameters.Add("@Autorization_No", SqlDbType.Int, 60).Value = txt_Auth.Text.ToString();
            insertCommand.Parameters.Add("@Issue_Type", SqlDbType.Text, 200).Value = txt_Iss.Text;
            insertCommand.Parameters.Add("@Status", SqlDbType.Text, 200).Value = txt_Iss.Text;
            //insertCommand.Parameters.Add("@Date To Memorize", SqlDbType.Date, 15).Value=Ca_Mem.se;
            insertCommand.Connection.Open();
            insertCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;

        }
        finally
        {
            if (clientConnection != null)
            {
                clientConnection.Close();
            }

        }
        }
}

A: You use integrated security to access the database. Therefore your windows user needs to be authorized to access the database. Check the security settings for the server and the database.


text:
Q: How to auto start web services when starting an Amazon EC2 instance? How do I set the httpd and mysqld services to start automatically upon booting an amazon-ec2 instance?
Currently I have to start them manually by connecting to the instance via ssh and running sudo service httpd start and sudo service mysqld start.

A: Rather than starting over with a new AMI, you could just issue the following commands on an Amazon Linux EC2 instance...
sudo chkconfig mysqld on
sudo chkconfig httpd on

You can check the settings before & after enabling these services to start on boot using the following commands...
sudo chkconfig --list mysqld
sudo chkconfig --list httpd

See all services using just...
sudo chkconfig --list

NOTE: If you are having any trouble with chkconfig being in root's path, you can try specifying the full path like this...
sudo /sbin/chkconfig mysqld on
sudo /sbin/chkconfig httpd on

A: If you using Amazon Linux 2 AMI you need to follow these steps:

*

*In AMI2 they are using systemctl for managing services check if it is installed on your machine
2.systemctl list-units --type=service by this command check if tomcat.service is listed

*sudo systemctl enable tomcat.service To eanable tomcat start on boot up

*systemctl is-enabled tomcat.service To check if tomcat enabled to start on boot up linux system

After that you can reboot your linux system and tomcat will be started.
For more about systemctl Click Here

A: It is different between Amazon Linux 1 and Amazon Linux 2.
Amazon Linux 1
In AmazonLinux1, use chkconfig command.
$ sudo chkconfig mysqld on
$ sudo chkconfig httpd on

Amazon Linux2
In AmazonLinux2, systemd was introduced. So, chkconfig is legacy command. You should use systemctl. It is a control command for systemd.
$ sudo systemctl enable mysqld
$ sudo systemctl enable httpd

You can confirm it is enabled or not using by is-enabled command.
$ sudo systemctl is-enabled mysqld
enabled

chkconfig command request will be forwarded to systemctl.
$ chkconfig mysqld on
Note: Forwarding request to 'systemctl enable mysqld.service'.

A: One of my client wants to do this task and I have successfully done by using following way.
Following commands starts the services automatic when instance started.
Auto start apache/httpd
1) systemctl enable httpd

Auto start redis service
2) systemctl enable redis

I have set SELINUX set to disabled in
3) /etc/sysconfig/selinux

For mysql services
sudo chkconfig mysqld on
sudo chkconfig httpd on

A: I faced the similar problem, here is the solution i am suggesting,
you need to create a file under /etc/init.d directory, e.g with name tomcat, and change the JAVA_HOME and CATALINA_HOME parameters as per your system installation.
Once you do setup this file then run the below command:
sudo chkconfig <file-name> on

where  is the file you have created in /etc/init.d it is tomcat in my case.
[ec2-user@ip-<myip> init.d]$ cat tomcat
#!/bin/bash
# description: Tomcat Start Stop Restart
# processname: tomcat
# chkconfig: 234 20 80
JAVA_HOME=/opt/apache-tomcat-7.0.96
export $JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH
CATALINA_HOME=/opt/apache-tomcat-7.0.96

case $1 in
start)
sh $CATALINA_HOME/bin/startup.sh
;;
stop)
sh $CATALINA_HOME/bin/shutdown.sh
;;
restart)
sh $CATALINA_HOME/bin/shutdown.sh
sh $CATALINA_HOME/bin/startup.sh
;;
esac
exit 0
chmod 755 tomcat
chkconfig --add tomcat
chkconfig --level 234 tomcat on
chkconfig --list tomcat
service tomcat start

A: ReactJS on Amazon Linux2 process:
Installing ReactJS on EC2 and running the app at boot:

*

*Once you connect to EC2 instance install NodeJS. Follow this tutorial:
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-up-node-on-ec2-instance.html

*Install httpd server using this tutorial: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Tutorials.WebServerDB.CreateWebServer.html

*I used Git Clone to clone the ReactJS app on to /home/ec2-user.

*Install Yarn using the command "npm install yarn -g"

*Execute the following commands in the cloned project: "Yarn" and then "Yarn build"

*Now Copy the build folder using : cp -a /build/. /var/www/html/

*Now go to the /var/www/html/ here create a .htaccess file using vi and include the following content:  "Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]"
Save the file with :wq

*Now in /etc/httpd/conf/httpd.conf search for Directory with "/var/www/html" attribute and change "AllowOverride None" to "AllowOverride All". Now open the browser and enter http://ec2-ip or http://ec2-url you will see the default page

*Enter the command "systemctl enable httpd" and then "systemctl start httpd" on AmazonLinux2. Now you can access the app on boot rather than running the app again and again.
You are complete.

A: The best way on Amazon Linux 2 is to use the following bash script on creation. This will install the updates, start Apache2, make it listed as a service so that it automatically restarts upon reboot, and the creation of an index.html and health.html sample files. Configuring a health page is important for application loadbalancers and for autoscaling groups.
#!/bin/bash

yum update -y

yum install httpd -y httpd-tools mod_ssl

service httpd start

chkconfig httpd on

systemctl start httpd

systemctl enable httpd

echo "Hello, World, from your Webserver on Amazon Linux" > /var/www/html/index.html

echo "Healthy" > /var/www/html/health.html

Cheers!

A: Either use any of the preexisting LAMP AMI, it will have both of them running as service already.
One example is BitNami, you will find several other when you fire an ec2 instance.


text:
Q: Using ReactiveUI to wire up Viewmodel and model How do I wire up Viewmodel and model the ReactiveUI way?
Is there even a ReactiveUI way (like this.RaiseAndSetIfChanged for normal properties)?
Regards
Tobias
Edit: small Sample:
public class TestModel
{
    public string TestName { get; set; }
}

public class TestViewModel : ReactiveObject
{
    private TestModel _model;

    public TestViewModel(TestModel model)
    {
        _model = model;
    }

    public TestName
    {
        get
        {
            return _model.Name;
        }
        set
        {
            //Update model value and raise PropertyChanged, but how?
        }
    }
}

A: public string TestName
{
    get
    {
        return _model.TestName;
    }
    set
    {
        if (_model.TestName == value) return;
        _model.TestName = value;
        this.RaisePropertyChanged();
    }
}

You could wrap this up in an extension method that takes an expression to know which field to update.


text:
Q: Keep wifi active in foreground service after phone goes to sleep I want to receive packets from wifi when my phone is locked. The problem is that when I lock my screen, my foreground service stops receiving packets. I'm using Foreground Service like this:
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
    var notification = new Notification.Builder(this)
        .SetContentTitle(Resources.GetString(Resource.String.app_name))
        .SetContentText(Resources.GetString(Resource.String.notification_text))
        .SetSmallIcon(Resource.Drawable.ic_stat_name)
        .SetContentIntent(BuildIntentToShowMainActivity())
        .SetOngoing(true)
        .AddAction(BuildRestartTimerAction())
        .AddAction(BuildStopServiceAction())
        .Build();

    // Enlist this instance of the service as a foreground service
    StartForeground(Constants.SERVICE_RUNNING_NOTIFICATION_ID, notification);

    /*DO THIS EVEN WHEN SCREEN IS LOCKED*/

    var powerManager = (PowerManager)GetSystemService(PowerService);
    _wakeLock = powerManager.NewWakeLock(WakeLockFlags.Partial, "WakeLockTag");
    _wakeLock.Acquire();

    var wifiManager = (WifiManager)GetSystemService(WifiService);
    _wifiLock = wifiManager.CreateWifiLock(WifiMode.FullHighPerf, "xamarin_wifi_lock");
    _wifiLock.Acquire();

    if (!powerManager.IsIgnoringBatteryOptimizations("com.xamarin.xample.foregroundservicedemo") ||
        !_wakeLock.IsHeld || !_wifiLock.IsHeld)
        throw new InvalidOperationException("OPTIMIZATIONS NOT ACTIVE");

    string msg = timestamper.GetFormattedTimestamp();
    Log.Debug(TAG, msg);
    Intent intent = new Intent(Constants.NOTIFICATION_BROADCAST_ACTION);
    intent.SetAction(Android.Provider.Settings.ActionIgnoreBatteryOptimizationSettings);
    intent.PutExtra(Constants.BROADCAST_MESSAGE_KEY, msg);
    LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
    Task.Run(() =>
    {
        using (var client = new UdpClient(12345))
        {
            while (true)
            {
                var result = client.ReceiveAsync().Result;
                Console.WriteLine($"RECEIVED: {result.Buffer.Length}");
            }
        }
    });

    return StartCommandResult.Sticky;
}

I'm doing the following things to make sure it is not killed:

*

*Starting Foreground Service

*Using StartCommandResult.Sticky

*Using Wake Lock

*Using Wifi Lock

*Setting WifiSleepPolicy to Never (I have it setup in my phone
settings)

*Setting ActionIgnoreBatteryOptimizationSettings in intent

*Whitelisting my app through adb command prompt while debugging

What else am I missing?    I am using Samsung A5 with Android 6.0 - API 23.
I looked into logs from adb command prompt and I checked that my service is in fact running as Foreground Service and all locks are held.

A: What you're doing is just great, all is good. However!!
Let us take a look at devleport.android.com's post:

Google Play policies prohibit apps from requesting direct exemption
  from Power Management features in Android 6.0+ (Doze and App Standby)
  unless the core function of the app is adversely affected.

You stated:

I am using Samsung A5 with Android 6.0 - API 23.

Meaning, you won't be able to keep your foreground service when the phone goes to sleep because the core function of the app is not adversely affected.
This the reason why you notice you stopped receiving packets when the phone is asleep.
please explore the entire link I attached and also us the Power Manager guide.
edit: I now noticed that furthermore:

If a user leaves a device unplugged and stationary for a period of
  time, with the screen off, the device enters Doze mode. In Doze mode,
  the system attempts to conserve battery by restricting apps' access to
  network and CPU-intensive services. It also prevents apps from
  accessing the network and defers their jobs, syncs, and standard
  alarms.

Doze restrictions:

*

*Network access is suspended.

*The system ignores wake locks.

*Standard AlarmManager alarms (including setExact() and setWindow())
are deferred to the next maintenance window.

*If you need to set alarms that fire while in Doze, use
setAndAllowWhileIdle() or setExactAndAllowWhileIdle().

*Alarms set with setAlarmClock() continue to fire normally — the
system exits Doze shortly before those alarms fire.

*The system does not perform Wi-Fi scans.

*The system does not allow sync adapters to run.

*The system does not allow JobScheduler to run.

This will conclude my answer to all of your queries.
EDIT 2:
I investigated a little further, there is an entire post regarding this issue in Xamarin.Android.
there is also a solution to wake the phone every 10 minutes to bypass it here.


text:
Q: Sort sheets in vba depending on the last characters of their names I have a workbook with multiple sheets having the following names (SSI_21_AB, SSI_22_BC, SSI_19_CD,  SSI_20_AC, FFI_20_AL). I want to sort them by the last two characters to look like this ( SSI_21_AB, SSI_20_AC, SSI_22_BC, SSI_19_CD)
This is what I have so far but it doesn't quite work, so I will appreciate your help :)
Sub SortSheetTabsAscending()
Dim ws As Worksheet
Dim i As Integer, j As Integer

Application.ScreenUpdating = False
Set ws = ActiveSheet
For i = 1 To Sheets.Count
    For j = 1 To Sheets.Count - 1
     If Left(ws.Name, 3) = "SSI" Then
        If Split("_", Sheets(j).Name)(0) + 0 > Split("_", Sheets(j + 1).Name)(0) + 0 Then
            Sheets(j).Move After:=Sheets(j + 1)
        End If
     End If
    Next j
Next i
ws.Activate
Application.ScreenUpdating = True
End Sub


text:
Q: Adding new record to a VFP data table in VB.NET with ADO recordsets I am trying to add a new record to a Visual FoxPro data table using an ADO dataset with no luck.  The code runs fine with no exceptions  but when I check the dbf after the fact there is no new record.  The mDataPath variable shown in the code snippet is the path to the .dbc file for the entire database.  A note about the For loop at the bottom; I am adding the body of incoming emails to this MEMO field so thought I needed to break the addition of this string into 256 character Chunks.  Any guidance would be greatly appreciated.
cnn1.Open("Driver={Microsoft Visual FoxPro Driver};" & _
                "SourceType=DBC;" & _
                "SourceDB=" & mDataPath & ";Exclusive=No")

Dim RS As ADODB.RecordsetS = New ADODB.Recordset
RS.Open("select * from gennote", cnn1, 1, 3, 1)
RS.AddNew()

'Assign values to the first three fields
RS.Fields("ignnoteid").Value = NextIDI
RS.Fields("cnotetitle").Value = "'" & mail.Subject & "'"
RS.Fields("cfilename").Value = "''"

'Looping through 254 characters at a time and add the data
'to Ado Field buffer
For i As Integer = 1 To Len(memo) Step liChunkSize
            liStartAt = i
            liWorkString = Mid(mail.Body, liStartAt, liChunkSize)
            RS.Fields("mnote").AppendChunk(liWorkString)
 Next

'Update the recordset
RS.Update()
RS.Requery()
RS.Close()

A: Microsoft has a Knowledge Base article that matches your question exactly.  The only major difference between your code and the example provided is the BackgroundFetch setting in the connection string.  This setting is enabled, by default, and has been reported to cause numerous problems with cursors.
In addition, you might want to switch to the Visual Foxpro Ole Db driver.  The Visual Foxpro ODBC driver was retired around 2000.


text:
Q: Angular injects module causing bind fails I have recently started a new project on angularJS.
I have an index.html which basically render all the script files when started.
There is a ng-view inside, the home.html will be loaded by ngRoute and is binded to a controller called HomeCtrl.
When I inject $resource to my HomeCtrl, the ng-bind on my html becomes not working, while removing the $resource it will work.
app.controller('HomeCtrl', ['$resource', function ($scope, $resource) {
     $scope.testText = 'testabc';
}])

I have tried inject something else, the behavior is also the same, the ng-bind will not work. There is no error shown in the browser console. May I know how can I trace what is actually happening?
Files as below:
https://plnkr.co/edit/P92PLlrWoqINpfeju5X1?p=preview

A: You forgot to add '$scope', angular tries to inject the objects in the order they are set.
Change
 app.controller('HomeCtrl', ['$resource', function ($scope, $resource) {
     $scope.testText = 'testabc';
 }])

to
app.controller('HomeCtrl', ['$scope', '$resource', function ($scope, $resource) {
     $scope.testText = 'testabc';
}])


text:
Q: How to use results from asynchronous function in Angular I'm trying to use the results from my asynchronous function inside another function, but it keeps saying the result is undefined.
This is my structure of my calling function:
async callingFn() {
    let value = await calledFn();
    console.log(value);
}

This is the structure of the function I'm calling:
calledFn() {
    this.myService.getHttpResponse().subscribe(
        (resp: any) => {
            var values = JSON.parse(resp);
            console.log(values);
            return values;
        },
        error => {
            console.error(error);
        }
    );
}

When I log values in calledFn, the result is as expected. However, when I log the return value of calledFn in callingFn, it returns undefined.
What am I doing wrong?

A: You are not returning from the calledFn. The subscription method is returning though.return the http service call

calledFn() {
  return this.myService.getHttpResponse().subscribe(
    (resp: any) => {
      var values = JSON.parse(resp);
      console.log(values);
      return values;
    },
    error => {
      console.error(error);
    }
  );
}


text:
Q: Расположение textarea в том же месте, что и td Есть таблица в phpmyadmin

При двойном щелчке на ячейку таблица принимает следующий вид

Хочу сделать также со своей таблицей (чтобы при двойном щелчке на ячейке раскрывалось поле для редактирования)

* {
    margin: 0;
    padding: 0;
}

.hstyle {
    text-align: center;
    margin-top: 30px;
}

.secondandmore {
    margin-top: 30px;
}

#second {
    margin-top: 30px;
}

.calltable tr td {
    /*border-spacing: 10px;*/
    padding-left: 25px;
    padding-right: 25px;
    font-weight: bold;
    border: 2px solid royalblue;

    background-color: rgb(202, 203, 209);

}

.calltable {
    margin-top: 30px;
    /*border-spacing: 40px;*/
    /*border: 2px solid royalblue;*/
    border-collapse: collapse;
    margin-bottom: 30px;
}

#btns {
    background-color: white;
    padding-left: 15px;
    margin-top: 30px;
}

#addoperator {
    border: 1px solid rgb(0, 205, 26);
    font-size: 14px;
    background-color: rgb(0, 205, 26);
    border-radius: 5px;
    color: white;
    width: 150px;
    height: 35px;
    margin-top: 25px;
}

#addnewuser {
    border: 1px solid rgb(0, 205, 26);
    font-size: 14px;
    background-color: rgb(0, 205, 26);
    border-radius: 5px;
    color: white;
    width: 150px;
    height: 35px;
    margin-top: 25px;
}

#addnewcall {
    border: 1px solid rgb(0, 205, 26);
    font-size: 14px;
    background-color: rgb(0, 205, 26);
    border-radius: 5px;
    color: white;
    width: 150px;
    height: 35px;
    margin-top: 25px;
}

.addcall {
    border: 1px solid rgb(0, 205, 26);
    font-size: 14px;
    background-color: rgb(0, 205, 26);
    border-radius: 5px;
    color: white;
    width: 150px;
    height: 35px;
    margin-top: 25px;
}

#deleteoperator {
    border: 1px solid rgb(254, 0, 0);
    font-size: 14px;
    background-color: rgb(254, 0, 0);
    border-radius: 5px;
    color: white;
    width: 150px;
    height: 35px;
}

.checkboxitemuserlist, .checkboxitemuserlisttotalcost {
    padding-top: 10px;
    padding-bottom: 10px;
    padding-left: 10px;
}

.wrapper {
    display:  flex;
    justify-content: space-between;
    width: 100%;
}

.leftmenu {
    flex: 1;
}

.tableblock {
    flex: 2;
}

.wrapperusers {
    display:  flex;
    justify-content: space-between;
    width: 100%;
}

.leftmenuusers {
    flex: 1;
}

.tableblockusers {
    flex: 2;
}

#alllistoperators, #alllistusers {
    width: 100%;
    border-collapse: collapse;
}

#alllistoperators tr td{
    width: 50%;
    text-align: center;
    /*
    padding-left: 25px;
    padding-right: 25px;
    */
    font-weight: bold;
    /*
    border: 2px solid royalblue;
    background-color: rgb(202, 203, 209);
    */

    border: 2px solid rgb(207, 207, 207);
    background-color: white;
}

#alllistoperators thead tr th {
    width: 50%;
    text-align: center;

    border: 2px solid rgb(207, 207, 207);
    background-color: rgb(99, 106, 116);
    color: white;
}

#alllistusers tr td {
    width: 33%;
    text-align: center;
    /*
    padding-left: 25px;
    padding-right: 25px;
    */
    font-weight: bold;
    border: 2px solid royalblue;
    background-color: rgb(202, 203, 209);
}

#userdurationcalltable {
    width: 100%;
    border-collapse: collapse;
}

#userdurationcalltable tr td {
    width: 50%;
    text-align: center;
    /*
    padding-left: 25px;
    padding-right: 25px;
    */
    font-weight: bold;
    border: 2px solid royalblue;
    background-color: rgb(202, 203, 209);
}

.leftmenuoperators {
    flex: 1;
}

#operatorsdurationcalltable{
    width: 100%;
    border-collapse: collapse;
}

#operatorsdurationcalltable tr td {
    width: 50%;
    text-align: center;
    /*
    padding-left: 25px;
    padding-right: 25px;
    */
    font-weight: bold;
    border: 2px solid royalblue;
    background-color: rgb(202, 203, 209);
}

#stattable {
    width: 100%;
    border-collapse: collapse;
}

#stattable tr td {
    width: 50%;
    text-align: center;
    /*
    padding-left: 25px;
    padding-right: 25px;
    */
    font-weight: bold;
    border: 2px solid royalblue;
    background-color: rgb(202, 203, 209);
}

#calculation {
    text-align: right;
}

.elemcheckbox {
    display: flex;
    padding-left: 15px;
}

.elemuserlist, .elemoperatorlist {
    padding-left: 15px;
}

.centeredblock {
    text-align: center;
    font-weight: bold;
    margin-top: 30px;
    margin-bottom: 30px;
}

.chooseperiod {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30px;
}

.chooseperiodbegin {
    display: flex;
    align-items: center;
}

.chooseperiodend {
    display:  flex;
    align-items: center;
}

#beginlocaldate, #endlocaldate {
    margin-left: 5px;
}

/*
#choosedatetimebegin {
    display: flex;
    align-items: center;
}

#chooseduration {
    display: flex;
    align-items: center;
}
*/

#choosedatetimebegin {
    display: flex;
    align-items: center;
}

.labeldatetimebegin {
    width:  305px;
}

.datetimeinput {
    width: 100%-305px;
}

#chooseduration {
    display: flex;
    align-items: center;
    margin-top: 10px;
}

.duration {
    width: 424px;
}

.durationinput {
    width: 100%-424px;
}

#inuser {
    display: flex;
    align-items: center;
    margin-top: 10px;
}

#labelinuser {
    width: 310px;
}

#selectinuser {
    width: 100%-310px;
}

#outuser {
    display: flex;
    align-items: center;
    margin-top: 10px;
}

#labeloutuser {
    width: 310px;
}

#selectoutuser {
    width: 100%-310px;
}

.checkboxitemusertotalcost{
    display: flex;
    padding-left: 15px;
}

.checkboxitemusernametotalcost {
    padding-left: 15px;
}

                        Оператор

                        Тариф

Как сделать так, чтобы скрытое textarea имело те же координаты, что и td?


text:
Q: PostgreSQL check if values in a given list exist in a table Given below table in Postgres:

id
some_col

1
a

1
b

2
a

3
a

I want to get output as id and true (if at least one row with that id is present in the table) or false (if no rows with that id are found in the table).
For example where id in (1, 2, 3, 4, 5):

id
value

1
true

2
true

3
true

4
false

5
false

I tried with the group by and case with conditions, but is there any optimized/performance SQL way of achieving this? Bcz, groupby does complete rows count which is unnecessary in this scenario. And, with exists query I didn't find a way to deal with multiple rows return;
Thanks in Advance!

A: The in clause won't do it. You need to build a list of values somehow (the values table valued constructor works in most rdbms) and outer join with it:
SELECT x.id, EXISTS (
    SELECT *
    FROM t
    WHERE t.id = x.id
) AS value
FROM (VALUES (1), (2), (3), (4), (5)) AS x(id)


text:
Q: SELECT * FROM table A and count the number of corresponding rows in Table B that match a specific field I have two tables: "series" and "product"
"series" holds the names of series of books, "product" has the details of individual book titles.
So something like this:
Series Table:
id      series_name               series_description
1       Lord of the Rings         Trilogy of fantasy books recently made into film
2       A Song of Ice and Fire    Epic series of novels currently showing on HBO
3       Harry Potter              Famous Children's book series also loved by adults

Product Table:
id      product_name              series_id     author             etc...
1       Fellowship of the Ring    1             JRR Tolkien
2       The Two Towers            1             JRR Tolkien
3       Return of the King        1             JRR Tolkien
4       A Game of Thrones         2             George R R Martin
5       A Clash of Kings          2             George R R Martin
6       A Storm of Swords         2             George R R Martin
7       A Feast for Crows         2             George R R Martin
8       A Dance with Dragons      2             George R R Martin
9       Harry Potter and the...   3             JK Rowling
etc.

I want to SELECT * FROM series, and COUNT(*) FROM product so that the query returns a table containing the series info, with the number of products in the database corresponding to each series appended as the last column of the table.  I'd also like to do this by genre, so there is an additional WHERE clause in there somewhere.  It would look something like this, if selecting "Fantasy and Magic" as the genre:
id      series_name               series_description         number_of_products
1       Lord of the Rings         Trilogy of Fantasy...      3
2       A Song of Ice and Fire    Epic Series of Novels...   5
3       Harry Potter              Famous Children's book...  7

I think I may need a LEFT JOIN but my best attempts so far have been in vein.
This is what I have so far, but I think it's probably totally wrong.
SELECT  series.id,
series.series_name,
series.publisher_id,
series.description,
series.image,
COUNT (product.*) as nRows
FROM series
LEFT OUTER JOIN product
ON series.id = product.series_id
WHERE series.genre = 'Fantasy and Magic'
GROUP BY ... (do I need a GROUP BY?)

Any help at all would be really appreciated.  Thanks in advance!

A: Almost there. Try this.
SELECT  series.id,
series.series_name,
series.publisher_id,
series.description,
series.image,
COUNT (product.id) as nRows
FROM series
LEFT OUTER JOIN product
ON series.id = product.series_id
WHERE series.genre = 'Fantasy and Magic'
GROUP BY series.id,
series.series_name,
series.publisher_id,
series.description,
series.image

A: Wouldn't this help;
select s.id,
   s.series_name,
   s.series_description,
   (select count(*) from Products p where p.series_id = s.id) number_of_products
from Series s


text:
Q: How to save an array of custom struct to NSUserDefault with swift? I have an custom struct called 'News' that I want to append into the array to NSUserDefault. But it's showing error "Type 'News' does not conform to protocol 'AnyObject'".
I don't want to change the 'News' struct to a class since it's being used for other code already. Is there anyway that I can change NSUserDefaults.standardUserDefaults().arrayForKey("savedNewsArray") type to [News]?
var savedNews = NSUserDefaults.standardUserDefaults().arrayForKey("savedNewsArray")
var addSavedNews = savedNews as? [News]
addSavedNews.append(News(id: "00", title: newsTitle, source: source, imageURL: imageURL, url: url))
NSUserDefaults.standardUserDefaults().setObject(addSavedNews, forKey: "savedNewsArray")
NSUserDefaults.standardUserDefaults().synchronize()

Here is the 'News' struct.
public struct News {
    public var id: String
    public var title: String
    public var source: String?
    public var imageURL: String?
    public var date: NSDate?
    public var url: String

    init(id: String, title: String, source: String, imageURL: String, url: String) {
        self.id = id
        self.title = title
        self.source = source
        self.imageURL = imageURL
        self.url = url
    }
}

A: Following is the flow that I have follow

*

*Make your struct object

*Convert struct  to Json object (I will give you file
    link to convert struct to JsonObject and jsonString -> https://github.com/vijayvir/SwiftApi/blob/master/StructureToJson/StructToJson.swift )  import this file in your project :-)

*Append that value to array

*If you want to save in user default I prefer you to make class object of array as follow ,(as you can access from any where )

*save your array in user default as follow
Struct to save

struct CardDetails : StructJSONSerializable {
var emailId :String

var accountNo : String

var expDate : String

var cvc : String

var isCurrrent : Bool = false

init(card : Dictionary<String, Any>  )
{
    emailId =  card["emailId"]! as! String

    accountNo =  card["accountNo"]! as! String

    expDate  =  card["expDate"]! as! String

    cvc =  card["cvc"]! as! String

    isCurrrent = card["isCurrrent"]! as! Bool

}

 }

Save Array to  User Default

  class var  cards : [AnyObject] {
    get
        {
            if (UserDefaults.standard.object(forKey:"cardss") != nil)
            {

            if let data = UserDefaults.standard.object(forKey: "cardss") as? Data
            {
                let unarc = NSKeyedUnarchiver(forReadingWith: data)

                let newBlog = unarc.decodeObject(forKey: "root")

                return newBlog as! [AnyObject]
            }
            else
            {
                return []
            }

          }
            else
            {
            return []
            }

        }

    set
    {
        //print(type(of: newValue) , newValue)

        let archiveData = NSKeyedArchiver.archivedData(withRootObject: newValue)

          let ud = UserDefaults.standard
          ud.set(  archiveData  ,forKey: "cardss")
          ud.synchronize()
    }

}

How to save Struct element  to array
 Here convert you struct object to json Object

     let  firstCard = CardDetails(emailId: "asdf",
                                 accountNo: "dada",
                                 expDate: "nvn",
                                 cvc: "e464w",
                                 isCurrrent: true)

      CardsViewController.cards.append(firstCard.toJsonObect())

How to access object from array
 Here convert you  json Object object to Struct

let sameCardIs = CardDetails(card:  CardsViewController.cards.last
as! Dictionary<String, Any>)

    print ("Element Function " , sameCardIs )

:-)

A: NSUserDefaults can only save a very small set of types: NSData, NSString, NSNumber, NSDate, NSArray containing only these types, or NSDictionary containing only these types. So your best bet is to encode your struct using an NSKeyedUnarchiver, which required a value that conforms to NSCoding. You could make your type conform to this, but I think it's cleaner to hide that from your users and simply have a private class for the internal representation, like this:
struct Foo {
    var a : String
    var b : String?
}

extension Foo {
    init?(data: NSData) {
        if let coding = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Encoding {
            a = coding.a as String
            b = coding.b as String?
        } else {
            return nil
        }
    }

    func encode() -> NSData {
        return NSKeyedArchiver.archivedDataWithRootObject(Encoding(self))
    }

    private class Encoding: NSObject, NSCoding {
        let a : NSString
        let b : NSString?

        init(_ foo: Foo) {
            a = foo.a
            b = foo.b
        }

        @objc required init?(coder aDecoder: NSCoder) {
            if let a = aDecoder.decodeObjectForKey("a") as? NSString {
                self.a = a
            } else {
                return nil
            }
            b = aDecoder.decodeObjectForKey("b") as? NSString
        }

        @objc func encodeWithCoder(aCoder: NSCoder) {
            aCoder.encodeObject(a, forKey: "a")
            aCoder.encodeObject(b, forKey: "b")
        }

    }
}

Then to save your array you can simply map .encode over your array:
let fooArray = [ Foo(a: "a", b: "b"), Foo(a: "c", b: nil) ]
let encoded = fooArray.map { $0.encode() }
NSUserDefaults.standardUserDefaults().setObject(encoded, forKey: "my-key")

and to get it back you can simply pass the NSData to the init:
let dataArray = NSUserDefaults.standardUserDefaults().objectForKey("my-key") as! [NSData]
let savedFoo = dataArray.map { Foo(data: $0)! }

A: WORKING IN SWIFT 3
Following a similar approach to ahruss, I ended up implementing in the following way:
struct MyObject {
    var foo : String
    var bar : String?
}

extension MyObject {
    init?(data: NSData) {
        if let coding = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? Encoding {
            foo = coding.foo as String
            bar = coding.bar as String?
        } else {
            return nil
        }
    }

    func encode() -> NSData {
        return NSKeyedArchiver.archivedData(withRootObject: Encoding(self)) as NSData
    }

    private class Encoding: NSObject, NSCoding {
        let foo : NSString
        let bar : NSString?

        init(_ myObject: MyObject) {
            foo = myObject.foo
            bar = myObject.bar
        }

        @objc required init?(coder aDecoder: NSCoder) {
            if let foo = aDecoder.decodeObject(forKey: "foo") as? NSString {
                self.foo = foo
            } else {
                return nil
            }
            bar = aDecoder.decodeObject(forKey: "bar") as? NSString
        }

        @objc func encode(with aCoder: NSCoder) {
            aCoder.encode(foo, forKey: "foo")
            aCoder.encode(bar, forKey: "bar")
        }

    }
}

Oh, and to use it just type the following:
let myObject = MyObject(foo: "foo", bar: "bar")
UserDefaults.standard.set(myObject.encode(), forKey: "test")

To fetch it,
let objectData = UserDefaults.standard.object(forKey: "test") as? Data?
guard let storedObject = objectData else {
    return
}
let fetchedObject: MyObject = MyObject(data: storedObject as NSData)

A: I had the same issue and none of the above answers worked for me.  I finally found this post: https://cocoacasts.com/ud-5-how-to-store-a-custom-object-in-user-defaults-in-swift.
This explains simply how to do it using JSON encoding.  It worked exactly as described in the post.


text:
Q: Do Bluetooth connections support lossless audio? Does any Apple or other Bluetooth device support lossless audio, such as ALAC?
This is a generalized question for people asking about their specific piece of hardware over Bluetooth. Its purpose is to close them as duplicates.

A: No.
For an authoritative answer, please see About lossless audio in Apple Music.

While the difference between AAC and lossless audio is virtually indistinguishable, we're offering Apple Music subscribers the option to access music in lossless audio compression.

AirPods, AirPods Pro, AirPods Max, and Beats wireless headphones use Apple AAC Bluetooth Codec to ensure excellent audio quality. However, Bluetooth connections aren't lossless.

However
The lossy compressed files on Apple Music will not be transcoded to an Apple audio device, and will be sent bit-for-bit.1 The quality of AAC files on Apple Music are nearly transparent to lossless files when comparing with headsets in the price range of Bluetooth Apple audio devices. Even so, the sound of these AAC files is likely limited by the listening device.
Considerations
If you only have AAC endpoints, this may have implications on which streaming providers can offer you the best sound quality for your hardware.

Correction:2 The following Spotify example no longer true. It was likely inaccurate at the time of this post, as the service seems to have switched to solely using AAC profiles a few months before this was written.

For instance, prior to 2021 Spotify would only stream AAC through a web browser. For its apps will select some bitrate of the Vorbis codec, a free and open-source alternative from the Xiph.Org Foundation, packaged in an Ogg container, that will result in transcoding when using Apple hardware, which only supports AAC and SBC.
As their "Standard" output selection, TIDAL offers the highest bitrate allowed on AAC: 320 kbps, which is about 20% more than Apple Music's 256 kbps.
Still depending on how well you can hear, none of this may matter to you, so take advantage of the free trials to compare your listening experience. If they all sound the same to you (and your family), perceived sound quality may not be as big of a factor as say going with the best deal for you (and-or your family).

Non-Authoritative Reference
What You Really Need to Know About Bluetooth Audio, by Brent Butterworth, Published July 15, 2020, Quote:

Many people believe that transmitting an audio signal via Bluetooth
will always degrade sound quality, but that's not necessarily true. If
an audio signal is already compressed in a certain codec, and the
source device (such as your phone, tablet, or computer) and the "sink"
device (such as a wireless speaker or headphones) both support that
codec, Bluetooth transmits the encoded audio unaltered, so the sound
is the same as you'd get without Bluetooth. The most common example is
with Apple Music, which uses AAC, and iPhones, which support AAC. If
you use these two things along with a wireless speaker or headphones
that also support AAC, Bluetooth will not impact the sound quality. If
at least one of the devices doesn't support AAC, the AAC data is
decompressed and then recompressed with another codec, such as SBC.
This process can reduce sound quality, although the difference will
probably be subtle.

Footnotes:

*

*i lost the link. this is not the correct footnote: About lossless audio in Apple Music

*Even though I use the New York Times's authority to backup my claims, I should point out corrections are something they almost never do.


text:
Q: References in Java for Android Coming from Web development background, I need some help understanding some of the basic syntax used in Android Applications' Java development aspects:
Context for these questions is the Development Training in development.android.com
1) How do the values "@string" , "@style" , "@drawable" reference to a directory on the project without explicitly given the exact path and exact folder name (drawable-hdpi/mdpi/xhdpi folders etc , strings.xml and styles.xml ) ?
2) According to the tutorial when I want to give a new ID resource definition I use "@+id/_" for that, is the action done behind the scene to add this as a temporary resource to the collection of id's used during runtime? would it be the same for a string or a style for example: "@+string/"? I'm asking because I know that the "@string/_" references to the "strings.xml" file but there is no "id.xml" file for id resources.
3) For the action bar the tutorial calls to use the themes directory from the Android Support class now I'm not sure how to call for them, mostly because they're in different Project files (the Android Support class is in appcompat_v7) and the tutorial just says to use "@style/Theme.AppCompat" when I don't have a resource called "Theme.AppCompact" in my "styles.xml" resource file.
Really frustraiting for me... would appreciate help on these!

A: *

*The Android tool chain contains a special compiler called AAPT, the Android Asset Packaging tool.  It knows about certain blessed folders: res/values, res/drawables, and so on.  It actually even parses the folder names to build multiple versions of resources (res/drawables-hdpi, etc.).  AAPT produces two artifacts: one is the bundled resources that go into the APK, the other is a Java source file, for a class called R.  If you include the R class (eclipse puts it in the gen directory) as source for your application, you can refer to the resources directly from your Java code.

*Yes.  You have that exactly right.  The value of an ID is interesting only in that it is different from other ids: it is unique.  AAPT can do that for you.  @+string/foo would work fine, if you wanted a string that contained a random-ish numeric value.  [Actually, AAPT appears to have checks, now, that won't allow it.  The point is still valid]

*Themes and Styles are a pretty complex topics.  The documentation is sparse but getting better.  It's really out of scope for SO.


text:
Q: Passing Array from Javascript to PHP and insert it in MYSQL i Have a code here that gets data from spreadsheet and display it in array.
var publicSpreadsheetUrl = "link";
var tabletop = Tabletop.init( {
                             key: publicSpreadsheetUrl,
                             callback: showInfo,
                             simpleSheet: true
                        })
function showInfo(data, tabletop) {
    ArrMasterfile.push(data);
    console.log(ArrMasterfile);
}

this is the output
0:{Title: "", Data "", Title: "Data ", Title: "Data ", Title: "Data ", …}
1:{Title: "", Data "", Title: "Data ", Title: "Data ", Title: "Data ", …}

my question is how can I pass that array in PHP? My target here is to save that in mysql. TYSM


text:
Q: Can I invert my ROC curve to plot the true negative against the false negative rate? I am trying to understand, if it makes sense to "invert" the ROC curve to display the true negative rate against the false negative rate.
I included a picture for clarification. Is it possible to make that assumption?
Thanks!
https://imgur.com/a/xKJTq6D

A: Yes. You can do that.  But to me, it is also representing the same information.

A: It is very hard to see in which application it would make sense. And I see several reasons not to do it:

*

*The plot shows no extra information than a ROC curve

*The plot looks like a ROC curve but isn't. People who know what a ROC curve is will think it's a ROC curve. But it isn't.

*Even you are confused, as exemplified by your picture which is actually incorrect.

Here is a quick look at what it would look like:

See how the curve is subtly "reversed", but not as you expected?
I would argue than unless you can bring some very strong reason to do it, you should probably refrain from it and show a standard ROC curve instead.


text:
Q: XCode std::string_view auto at global namespace failure I'm using some global pre-calculated constexpr strings to work with types. The function I'm building is:
// strfindCExpr and strlenCExpr are my constexpr methods for string manipulation

template<typename T>
static constexpr std::string_view getTypeName() {
    constexpr auto p = __PRETTY_FUNCTION__;
    constexpr auto pStart = strfindCExpr(p, strlenCExpr(p), "= ", 2) + 2;
    constexpr auto pEnd = strfindCExpr(pStart, strlenCExpr(pStart), "]", 1);
    return {pStart, pEnd - pStart};
}

Generally this function produces the values correctly when called with different types, i.e. getTypeName<NSA::BlackList>() == "NSA::BlackList"
The problem I run into is when I try to use these constexpr at the global namespace.
Working version:
constexpr std::string_view myType = getTypeName<NSA::BlackList>();
// myType == "NSA::BlackList"

Not working:
constexpr auto myType = getTypeName<NSA::BlackList>();
// myType == "der/Folder/Folder/File.cpp"

Funnily enough, when I print out typeid(myType).name(), in both versions they end up with: NSt3__117basic_string_viewIcNS_11char_traitsIcEEEE .
Using XCode version 9.4.1, Apple LLVM 9.0
This is a runtime issue:
constexpr std::string_view myTypeWorking = getTypeName<NSA::BlackList>();
constexpr auto myTypeNotWorking = getTypeName<NSA::BlackList>();

int main() {
    assert(strncmp(myTypeWorking.data(), "NSA::BlackList", strlen("NSA::BlackList")) == 0); // Ok
    assert(strncmp(myTypeNotWorking.data(), "NSA::BlackList", strlen("NSA::BlackList")) == 0); // Fail
    constexpr auto myTypeLocalWorking = getTypeName<NSA::BlackList>();
    assert(strncmp(myTypeLocalWorking.data(), "NSA::BlackList", strlen("NSA::BlackList")) == 0); // Ok
}

A:
The problem I run into is when I try to use these constexpr at the global namespace.

There is not as much detail in the question as I would like, but this provides a clue.
I'm guessing that getTypeName is defined in some namespace other than the global namespace? Let's suppose that namespace is types.
If that is the case, the name of this template is actually types::getTypeName<>.
To call it from the global namespace you'd have to write something like:
constexpr auto myType = types::getTypeName<NSA::BlackList>();

or
using namespace types;
constexpr auto myType = getTypeName<NSA::BlackList>();

or
using types::getTypeName;
constexpr auto myType = getTypeName<NSA::BlackList>();

A: Considering that, by compiling (GCC 8.3.1 20190223 with -std=c++2a under Linux) and execution of a redacted version of your code:
#include <iostream>
#include <string_view>
namespace name1{
template<typename T>
static constexpr std::string_view getTypeName() {
    return {__PRETTY_FUNCTION__ + 58, 18};
}
}// namespace name1
namespace name2{
template<typename>
class sample{};
}// namespace name2
namespace name3{
template<typename T>
static constexpr std::string_view getTypeName() {
    return name1::getTypeName<T>();
}
}// namespace name3
template<typename T>
static constexpr std::string_view getTypeName() {
    return {__PRETTY_FUNCTION__ + 51, 18};
}

int main() {
    constexpr std::string_view myType1 = name1::getTypeName<name2::sample<int> >();
    constexpr auto myType2 = name1::getTypeName<name2::sample<int> >();
    constexpr std::string_view myType3 = name3::getTypeName<name2::sample<int> >();
    constexpr auto myType4 = name3::getTypeName<name2::sample<int> >();
    constexpr std::string_view myType5 = getTypeName<name2::sample<int> >();
    constexpr auto myType6 = getTypeName<name2::sample<int> >();
    std::cout << myType1 << std::endl;
    std::cout << myType2 << std::endl;
    std::cout << myType3 << std::endl;
    std::cout << myType4 << std::endl;
    std::cout << myType5 << std::endl;
    std::cout << myType6 << std::endl;
    return 0;
}

Which examines different cases, I got this output:
name2::sample<int>
name2::sample<int>
name2::sample<int>
name2::sample<int>
name2::sample<int>
name2::sample<int>

I guess maybe the problem is with the compiling environment/implementation.


text:
Q: Java - appending & passing values I'm having trouble with passing a string and double to another class because it keeps on crashing at double cost = input.nextDouble();. Also, i was wondering if i am correct with the appending method used in public boolean addPARTDETAILS(String partDESCRIPTION, double partCOST).
For example. If the user enters the parts and cost, i want it to store that in a list and print it out with the cost appended.
Parts used:

*

*brake pads ($50.00)

*brake fluids ($25.00)

Note. Assuming that i have declared all variables and the array.
System.out.print("Enter registration number of vehicle");
                String inputREGO = input.next();
                boolean flag = false;
                for(int i=0; i<6; i++){
                    if(inputREGO.equalsIgnoreCase(services[i].getregoNUMBER())){
                        System.out.print("Enter Part Description: ");
                        String parts = input.nextLine();
                        double cost = input.nextDouble();

                        services[i].addPARTDETAILS(parts, cost);

                        //System.out.println(services[i].getregoNUMBER());
                        flag = true;
                    }
                }if(flag==false);
                System.out.println("No registration number were found in the system.");

public boolean addPARTDETAILS(String partDESCRIPTION, double partCOST){
    if(partDESCRIPTION == "" || partCOST <= 0){
        System.out.println("Invalid input, please try again!");
        return false;
    }
    else{
        partCOST=0;
        StringBuffer sb = new StringBuffer(40);
        String[] parts = new String[50];
        for (int i=0;i<parts.length;i++){
            partDESCRIPTION = sb.append(partCOST).toString();
        }
        System.out.println(partDESCRIPTION);

        totalPART+=partCOST;
        return true;
    }
}

A:
it keeps on crashing at double cost = input.nextDouble();.

It is highly unlikely that your JVM is crashing.  It is far more likely that you are getting an Exception which you are not reading carefully enough and have forgotten to include in your question.
It is far more likely your code is incorrect as you may have mis-understood how scanner works. And so when you attempt to read a double, there is not a double in the input.  I suspect you want to call nextLine() after readDouble() to consume the rest of the the line.
I suggest you step through the code in your debugger to get a better understanding of what it is really doing.

A: Data dependent error.
if(flag==false);
System.out.println("No registration number were found in the system.");

should be (because of the ;):
if (!flag) {
    System.out.println("No registration number was found in the system.");
}

And
partDESCRIPTION == ""

should be:
partDESCRIPTION.isEmpty()

A: Just to expand a bit on Joop Eggen's and Peter Lawrey's answers because I feel some may not understand.
nextLine doesn't play well with others:
nextDouble is likely throwing a NumberFormatException because:
next, nextInt, nextDouble, etc. won't read the following end-of-line character, so nextLine will read the rest of the line and nextDouble will read the wrong thing.
Example: (| indicates current position)
Start:
|abc
123
def
456

After nextLine:
abc
|123
def
456

After nextDouble:
abc
123|
def
456

After nextLine (which reads the rest of the line, which contains nothing):
abc
123
|def
456

Now nextDouble tries to read "def", which won't work.
If-statement issues:
if(flag==false);

or, rewritten:
if(flag==false)
  ;

is an if statement with an empty body. Thus the statement following will always execute. And no need to do == false, !flag means the same. What you want:
if (!flag)
  System.out.println("No registration number were found in the system.");

String comparison with ==:
partDESCRIPTION == ""

should be:
partDESCRIPTION.equals("")

or better:
partDESCRIPTION.isEmpty()

because == check whether the strings actually point to the exact same object (which won't happen unless you assign the one to the other with = at some point, either directly or indirectly), not just whether the have the same text (which is what equals is for).


text:
Q: what is the difference between getLayoutInflator and (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE) I'm confused between these two statements.
What is the difference and when can i use each one?
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.activity_custom_lists1, parent);

and
View v =  getLayoutInflater().inflater.inflate(R.layout.activity_custom_lists1, parent);

A: second one is wrong
View v =  getLayoutInflater().inflater.inflate(R.layout.activity_custom_lists1, parent);

it might be
View v =  getLayoutInflater().inflate(R.layout.activity_custom_lists1, parent);

second one is called for the activity scope and the first one can be called from outside the Activity with the context

A: Maybe you meant View.inflate as opposed to Context.getLayoutInflater? I think there's no difference, the former being a shortcut for the latter.


text:
Q: GraalVM build failure with "Blocklisted methods are reachable for runtime compilation" Thank you for your time to help me with my problem. I'm a JAVA beginner but I'm very interested in this language. So I've been learning how to use its frameworks recently, but as you can see, I'm currently facing some problems from graalvm. I know it's silly, but what I want to ask is how to add or delete methods in blocklist from it's truffle polyglot engine.
I have try to add -H:-TruffleCheckBlockListMethods but it's not seem to work without -Dtruffle.TruffleRuntime=com.oracle.truffle.api.impl.DefaultTruffleRuntime,  but with truffle runtime set will slow performance real bad. Any help please !
CI Report
I have read the source code from GitHub, they just add those functions into blocklist, WHY ??

A: probably you need to use truffle boundary


text:
Q: All cases when check constraints are executed for each row When creating a check constraint it will be performed on all rows of a table. Does this happen in another case too?
My check constraint calls a function with SQL inside. This is very slow on large tables.
CREATE FUNCTION CheckUnique(@test NVARCHAR(20))
RETURNS INT
AS
BEGIN
    IF EXISTS (SELECT 1 FROM mytable WHERE unique_field = @test)
    BEGIN
        RETURN 1
    END
    RETURN 0
END

ALTER TABLE mytable
    ADD CONSTRAINT CCheckUnique CHECK([dbo].CheckUnique(unique_field) = 0)

A: Don't use a function to check if a value is unique, use a UNIQUE INDEX:
CREATE UNIQUE INDEX uq_unique_field ON dbo.mytable(unique_field);

Or, alternatively (it's the end of the day and i totally forget to incldue them) use a UNIQUE CONSTRAINT, and @Marc_s reminded me in the above comment:
ALTER TABLE MyTAble
ADD CONSTRAINT UC_unique_field UNIQUE (unique_field);

Scalar functions, especially those that reference tables, are known to perform very poorly. An inline table-value function should be used when you can; but you cannot implement those for a CHECK CONSTRAINT. Neither are needed here though.


text:
Q: scrapy cannot import module while it's in my pythonpath I had a functional scrapy project, and then I decided to clean it. In order to do so, I got my database module out of the scrapy part of my project and I can't include it anymore. Now the project looks like this :
myProject/
    database/
        __init__.py
        model.py
        databaseFactory.py
    myScrapy/
        __init__.py
        settings.py
        myScrapy/
            __init__.py
            pipeline.py
        spiders/
            spiderA.py
            spiderB.py
    api/
        __init__.py
    config/
        __init__.py

(only files related to my question are displayed)
I want to use the databaseFactory in scrapy.
I have added to my .bashrc the following lines :
PYTHONPATH=$PYTHONPATH:my/path/to/my/project
export PYTHONPATH

so when launch ipython i can do the following thing :
In [1]: import database.databaseFactory as databaseFactory

In [2]: databaseFactory
Out[2]: <module 'database.databaseFactory' from '/my/path/to/my/project/database/databaseFactory.pyc'>

BUT...
when i try to launch the scrap, with
sudo scrapy crawl spiderName 2> error.log

I can enjoy the following message :
Traceback (most recent call last):
  File "/usr/local/bin/scrapy", line 11, in <module>
    sys.exit(execute())
  File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 143, in execute
    _run_print_help(parser, _run_command, cmd, args, opts)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 89, in _run_print_help
    func(*a, **kw)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 150, in _run_command
    cmd.run(args, opts)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/commands/crawl.py", line 60, in run
    self.crawler_process.start()
  File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 92, in start
    if self.start_crawling():
  File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 124, in start_crawling
    return self._start_crawler() is not None
  File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 139, in _start_crawler
    crawler.configure()
  File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 47, in configure
    self.engine = ExecutionEngine(self, self._spider_closed)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/engine.py", line 65, in __init__
    self.scraper = Scraper(crawler)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/scraper.py", line 66, in __init__
    self.itemproc = itemproc_cls.from_crawler(crawler)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/middleware.py", line 50, in from_crawler
    return cls.from_settings(crawler.settings, crawler)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/middleware.py", line 29, in from_settings
    mwcls = load_object(clspath)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/misc.py", line 42, in load_object
    raise ImportError("Error loading object '%s': %s" % (path, e))
ImportError: Error loading object 'myScrapy.pipelines.QueueExportPipe': No module named database.databaseFactory

why does scrapy ignore my PYHTONPATH ? how do I do now ? I really don't want to use sys.path.append() in my code

A: You have to tell python your PYTHONPATH:
export PYTHONPATH=/path/to/myProject/

and then run scrapy:
sudo scrapy crawl spiderName 2> error.log

A: By default, when launching a command with sudo, the normal context is not used, so PYTHONPATH is forgotten. In order to have PYTHONPATH with sudo, follow those steps :

*

*add PYTHONPATH to Defaults env_keep += "ENV1 ENV2 ..." in sudoers file

*remove Defaults !env_reset from sudoers file if present

A: What's wrong of using "sys.path.append()"? I tried many other ways, and determined that "scrapy" doesn't honor the "$PYTHONPATH" for user defined packages. I suspect it loads the directory after the framework has passed the lookup phase. But I tried the "sys.path.append()", it's working.
Jun


text:
Q: Stop User from using "Print Scrn" / "Printscreen" key of the Keyboard for any Web Page I am currently doing a project, in which I need to stop the user from taking the snapshot of any Web Page, for which he can use the "Print Scrn" / "Printscreen" key available in any of the normal keyboards.
I have been trying to find its solution, but in vain. If possible, I need to take into account of the "Screengrab" add-on of the Firefox browser, by stopping it also.
Any help is greatly appreciated, and I am using PHP (as server-side language) & jQuery for my project.

A: You can change the contents of the clipboard using JavaScript or Flash. This already helps a bit.

A: I hate the "it's not possible" sentence. Here's all solutions combined to help you:
1- You can grab the solution from Haluk:

HOWEVER, you hide body, but's already "printed" to clipboard. You can fire another event that copy some text to your clipboard, as you can see on this answer "Edit as of 2016" Click button copy to clipboard using jQuery , it's something like this:
function copyToClipboard() {
  // Create a "hidden" input
  var aux = document.createElement("input");
  // Assign it the value of the specified element
  aux.setAttribute("value", "Você não pode mais dar printscreen. Isto faz parte da nova medida de segurança do sistema.");
  // Append it to the body
  document.body.appendChild(aux);
  // Highlight its content
  aux.select();
  // Copy the highlighted text
  document.execCommand("copy");
  // Remove it from the body
  document.body.removeChild(aux);
  alert("Print screen desabilitado.");
}

$(window).keyup(function(e){
  if(e.keyCode == 44){
    copyToClipboard();
  }
});

This will block a part of your problem. If user focus on another object outside this windows he will be able to take screenshots. **But there's another solution to that as well, simply disable the hole body when window get's unfocused. Full solution, from your dear brazillian friend:
function copyToClipboard() {
  // Create a "hidden" input
  var aux = document.createElement("input");
  // Assign it the value of the specified element
  aux.setAttribute("value", "Você não pode mais dar printscreen. Isto faz parte da nova medida de segurança do sistema.");
  // Append it to the body
  document.body.appendChild(aux);
  // Highlight its content
  aux.select();
  // Copy the highlighted text
  document.execCommand("copy");
  // Remove it from the body
  document.body.removeChild(aux);
  alert("Print screen desabilitado.");
}

$(window).keyup(function(e){
  if(e.keyCode == 44){
    copyToClipboard();
  }
});

$(window).focus(function() {
  $("body").show();
}).blur(function() {
  $("body").hide();
});

Here's the example working:

A: This is not possible.

A: Like @Sjoerd said, this is not possible.
If it is pictures you want to protect, I suggest you for example display lower quality images that are watermarked instead and only display the non watermarked high quality ones when appropriate.
But yeah... If you want them to be impossible to copy... don't put them online.

A: There is no direct method to do that, however, there is a way to protect your content as much as possible from prnt scrn.
The idea is this:

*

*make your content inaccessible if java is disabled, and use some script like Artist Scope's copy protect.

*Detecting prnt scrn will send a message to the admin with the registered user info, this means that restricted content that is accessible by members only can benefit from this. sending IP addresses sounds like a good idea, but banning IPs is not, so you won't gain a lot of benefit from that.

*Once outside your website's window, your content will be covered with an overlay that can't be removed unless you get back to your website and activate it, which will re-activate the prnt scrn detection code mentioned in the previous point.

*If the device is a mobile, you can either hide images, or as in my case, redirect to a "we're sorry" page.

*snipping tool and other similar browser extensions and add-ons will be useless. except one tool that I have found called full page screen capture

*

*this tool captures web content after about 3 seconds from pressing button, which is enough time to dismiss the overlay and get back to your content

*a good turnaround is to start a counter when "dismiss overlay" is clicked that will need 5 seconds or more, ie. after this extension has already taken a snapshot

*There's also an indirect method to prevent video capture, still working on it, will post it here or in my blog.

*If your content is really that much worth it, users might still capture it using their cameras, there might be a method for that too! But I sill need to do some research before talking about it.
I will be updating this post in my blog for other techniques that I've used/ will use for more protection.
Please check this quiz (still under development) for a demo.

A: You can copy to clipboard something else, when user click key print screen. This is example and I copy user text.

test

function copyToClipboard(elementId) {

  // Create a "hidden" input
  var aux = document.createElement("input");

  // Assign it the value of the specified element
  aux.setAttribute("value", document.getElementById(elementId).innerHTML);

  // Append it to the body
  document.body.appendChild(aux);

  // Highlight its content
  aux.select();

  // Copy the highlighted text
  document.execCommand("copy");

  // Remove it from the body
  document.body.removeChild(aux);

}
$(document).ready(function(){
    $(window).keyup(function(e){
      if(e.keyCode == 44){
        copyToClipboard('test');
      };
    });
});

A: You can't disable screen grabbing from the Web browser, it would only be possible by installing additional software on the user's PC.
There are some IRM (Information Rights Management) tools available that do that e.g. by protecting Windows/DirectX API calls and also monitoring video memory such as Oracle IRM or such as Microsoft's IRM technology.
Especially the latter might be of interest as there is also a Rights Management Add-on for Internet Explorer.
But as other already said, any IRM/DRM technology is controversy and you should understand that it most often will limit or annoy your users.

A: Why do you want to prevent the print screen?
If it's some photos you want to protect, you might want to put it in low resolution, and include some kind of copyright logo programmatically in php.
I think that's pretty much it.

A: Here is another solution:

This is similar to @ZX12R's solution. The upside is this code will work even if the print screen catching software is a 3rd party tool (eg snagIt).
You can replace $("body").hide(); with something which will suit you better. For instance you can hide all the pictures $("img").hide(); and maybe show them back a second later.
The downside is it will not work if the web page is not the active window.

A: Try this
$(document).keyup(function(e){
  if(e.keyCode == 44) return false;
});

Hope it works

A: Thankfully, this outrageous idea is not possible to implement reliably, neither the "disable screen grab" part nor the "disable user's Firefox extensions" one. And even if it were, as @kbok points out in his comment above, you don't have a right to do this.
The only way to protect your content online is copyright laws - mentioning those is often enough to scare people away from misusing it! - or not showing it at all.


text:
Q: How can I change to one of the many system installed fonts in KDE5 konsole? I have KDE 5 installed and would like to install a patched font for powerline. I already ran the script to install the fonts into ~/.fonts but when editing the konsole profile, I see a very limited number of fonts, none of which are the ones I installed patch for powerline.
How would I use these fonts in Konsole in KDE5?

A: there is a bug that the ubuntu system think the patched fonts are not mono. So you cannot see that font in any terminal application's setting, even in gnome-terminal. But as for konsole, we can directly edit the ~/.local/share/konsole/*.profile file. Here is any example:
[Appearance]
ColorScheme=Breeze-VB
Font=DroidSansMono Nerd Font,11,-1,5,50,0,0,0,0,0

then you can use the font without problem.


text:
Q: thor incorrectly called exception class B12 < Thor
  desc "write", "write data into the index"
  method_option :methods, :desc => "The methods to call on each RawData", :type => :array
  def write(methods)
  end
end

When I call the file via
thor b12:write --methods=foo

I get
"write" was called incorrectly. Call as "thor b12:write".

Where's the problem?

A: You've got a couple things going on here that'll cause issues.
First, you're using methods, which is a keyword in ruby.  That's going to cause all sorts of nonsense.  Use something else, like my_methods.
Second, you don't need to pass my_methods into write.  That creates a default option, not a named option.   So you'd call thor b12:write foo if you wanted access to my_methods in that context.
This works if you call it with: thor b12:write --my_methods=foo
class B12 < Thor
  desc "write", "write data into the index"
  method_option :my_methods, :type => :array, :desc => "The methods to call on each RawData"
  def write
    puts options.my_methods
  end
end


text:
Q: probability formula binomial distribution Recently doing probability course I've came across this formulae. Can anyone explain what is means?
$ (p^k * q^{N-k}) * N! \mid k!(N-k)!  $
So far I came to know
p - is probability than an event occurs
q - probability than an outcome won't occur.
I just need to know what N and k means here in the equation.

A: Your typesetting needs work.
$\dfrac{p^k q^{N-k} N!}{k!~(N-k)!}$ is the probability for $k$ successes among $N$ independent Bernouli trials with identical success rate $p$ (and failure rate $q:=1-p$); for any $k\in\{0..N\}$.
More often writen as $\binom Nk p^k(1-p)^{N-k}$.
$p^k(1-p)^{N-k}$ measures the probability for an arrangement of $k$ success and $N-k$ failures. $\binom Nk$ counts the distinct permutations of such an arrangement.
This is the probability mass function  for a Binomially distributied random variable.

$p$ is the success rate.
$q$ is the failure rate, $q:=1-p$.
$N$ is the amount of iid Bernouli trials.
$k$ is the amount of successes among the favoured event.
When $X$ is a Binomial random variable with parameters $N, p$, then:
$$\mathsf P(X=k)= \dbinom{N}{k}p^k q^{N-k}~\mathbf 1_{k\in\Bbb N:0\leq k\leq N}$$
Example: When $X$ is the count for snake-eyes among five fair die, $N=5, p=1/6, q=5/6$, the probability for obtaining 3 snake-eyes is:.$$\mathsf P(X=3)=\dfrac{5!~5^{2}}{3!~2!~6^5}$$


text:
Q: SSL Handshake failure from IBM WAS 7 to IIS 8.5 We have a web service running on JBOSS EAP7 which is behind IIS 8.5. The webservice works fine on the Internet Explorer using both http://webservice and https://webservice. We have another application running on IBM WAS 7 which consumes this web service. The application has no issues when it uses http://webservice. However the SSL handshake fails when application on WAS 7 uses https://webservice. Below is the error we are seeing in application logs.
Below is a ClientHello message from WAS

We do not see ServerHello message in the logs. Below are the Ciphers on IIS 8.5  Earlier we thought that this was an issue with unmatched Ciphers but as per IBM Support, TLS_RSA_WITH_AES_128_CBC_SHA is equivalent to what is being sent in ClientHello SSL_RSA_WITH_AES_128_CBC_SHA. Also, unfortunately we do not see any errors in IIS logs or in the Event Viewer of the Server. We used MessageAnalyzer as well to capture network traffic on Server but didn't help much. Is there any way to capture SSL Handshake logs on the IIS/Server? Any other help or suggestions you could provide will be much appreciated.


text:
Q: Can't seem to get JQuery working (wordpress plugin) Im trying to learn how to create plugins using Wordpress but I stumbled upon this problem:

Whenever I'm trying to run JQuery I get undefined error's and such...

I tried different things I found on the internet like deregister/register/enqueue but nothing seems to work.
The goal is to fill a textarea in the plugin settings page without reloading/saving the page to create a live preview.
This is what I'm doing right now:
class plugin
{
  public function __construct()
  {
    add_action("wp_enqueue_scripts", "jquery_enqueue");
    add_action( 'admin_menu', array( $this, 'plugin_page' ) );
    add_action( 'admin_init', array( $this, 'page_init' ) );
  }

  public function jquery_enqueue()
  {
    wp_deregister_script('jquery');
    wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
    wp_enqueue_script('jquery');
  }

  public function plugin_page()
  {
    add_menu_page(
        '...',
        '...',
        '...',
        '...',
         array( $this, 'create_admin_page' )
    );
   }

public function create_admin_page()
    {
        // Set class property
        $this->options = get_option( 'my_option_name' );
        ?>

Test

            <form method="post" action="options.php">
            <?php
                // This prints out all hidden setting fields
                settings_fields( '...' );
                do_settings_sections( '...' );
            ?>

            </form>
            <textarea></textarea>

        <?php
    }}

I left some code out and only included the important parts.

A: This is a common question. It plagued me when I first started because it doesn't make any sense and it is hard to search for until you know. The problem is that WordPress bundles a version of jQuery that is set to noConflict mode. Therefore, to run scripts you must use noConflict wrappers
jQuery(document).ready(function($) {
    // Inside of this function, $() will work as an alias for jQuery()
    // and other libraries also using $ will not be accessible under this shortcut
});

Update

*

*There's no need to load a different version of jQuery. It just complicates things. Let, WordPress load it's own version. Delete your jquery_enqueue() method.

*Next adjust your create_admin_page() to not print the script directly. What I think is happening is that add_menu_page() runs before wp_enqueue_scripts and so jQuery isn't available yet. Hence, error. Instead of printing the scripts, you can print them in the footer by adding a new function to the admin_print_footer_scripts hook.
So modified, your create_admin_page() would now look like this:
public function create_admin_page()
    {
        // Set class property
        $this->options = get_option( 'my_option_name' );
        add_action( 'admin_print_footer_scripts', array( $this, 'footer_scripts' ) );
        ?>

Test

            <form method="post" action="options.php">
            <?php
                // This prints out all hidden setting fields
                settings_fields( '...' );
                do_settings_sections( '...' );
            ?>
            </form>
            <textarea></textarea>

        <?php
    }

With your new function being:
public function footer_scripts()
    { ?>


text:
Q: How Do I Merge A Temporary Map Onto A Permanent Map So That I Can Record Several Items Of The Same Key? So I have two maps where the key is based off of the length of the word. Whenever there is a word with the same amount of length, I want it added to that key.
I want to do this by using the map.merge() function, however, after looking at the documentation I am unsure how to do so. I tried looking at other resources, but not many have helped.
Map<Integer, String> map = new HashMap<Integer, String>();

Map<Integer, String> map = new HashMap<Integer, String>();

String[] wordsSplit = doc.split(" ");
for(int i = 0; i < wordsSplit.length; i++) {
    int key = wordsSplit[i].length();
    Map<Integer, String> tempMap = new HashMap<Integer, String>();
    tempMap.put(key, wordsSplit[i]);
    //merge here
    map.merge(key, map.keySet(), map.get(key) + ", " + wordsSplit[i]);
}

Edit: This question is different because here I am trying to figure out how to map in the context of merging the temporary map onto the the old map.
For instance, this means if there are several items that share the same key, then it would more turn out as: key: "Car, bar, Tar"

A: First you need a merge function to concat words with same length, seperated with ", ";
BiFunction<String, String, String> mergeFunction = (i, j) -> {
    return i + ", " + j;
};

Then map.merge(key, x, mergeFunction); merges the elements of wordsSplit array according to their length. Below key is length of word, x stands for wordsSplit[i]
Stream.of(wordsSplit).forEach(x -> {
    int key = x.length();
    map.merge(key, x, mergeFunction);
});

Or you can just past the body of merge function (i, j) -> { return i + ", " + j; } into map.merge() instead of defining mergeFunction seperately:
Stream.of(wordsSplit).forEach(x -> {
    int key = x.length();
    map.merge(key, x, (i, j) -> { return i + ", " + j; });
});


text:
Q: What is wrong with getMonth() + 1; I have this code in Sharepoint:
     var d = $.trim(oListItem.get_item('Begindatum'));
     alert(d);
     var m = d.getMonth() + 1;
     alert(m);

The first alert returns: Thu Apr 20 2017 00:00:00 GMT+0200 (W. Europe Daylight Time), which is correct.
The second alert (m) is not fired and the code after that is not executed. What is wrong with my code?

A: $.trim() will return a string, not a date.
You would need to cast back to a date object before you can do getMonth().
 var d = $.trim(oListItem.get_item('Begindatum'));
 alert(d);
 var m = new Date(d).getMonth() + 1;
 alert(m);


text:
Q: stop performseguewithidentifier once executed I have this code to update distance using beacons.
func updateDistance(distance: CLProximity) {
    UIView.animateWithDuration(0.8) {
        switch distance {
        case .Unknown:
            print("unknown")
        case .Far:
            print("far")
        case .Near:
            print("near")
        case .Immediate:
             print("Immediate")
             self.performSegueWithIdentifier("beaconSegue", sender: self)
        }
    }
}

I would just like to ask if how to stop the self.performSegueWithIdentifier function once its already executed.

A: If you want to prevent the performSegueWithIdentifier, you can do like this:
override func shouldPerformSegueWithIdentifier(identifier: String,sender: AnyObject?) -> Bool {
    if ... { // Set the condition if you want it can be perform
        return true
    } else {
        return false
    }
}

A: Just set a flag when you first perform the segue.  Like this:
var seguePerformed = false

func updateDistance(distance: CLProximity) {
    UIView.animateWithDuration(0.8) {
        switch distance {
        case .Unknown:
            print("unknown")
        case .Far:
            print("far")
        case .Near:
            print("near")
        case .Immediate:
             print("Immediate")
             if !self.seguePerformed {
                 self.seguePerformed = true
                 self.performSegueWithIdentifier("beaconSegue", sender: self)
             }
        }
    }
}