问:
Get printers connected/available
Running the following code I get always nothing for "Availability".
How can I get information if a printer is online or offline? In Windows settings it is shown but not by my code:</p>

```<code>    {
        ManagementScope scope = new ManagementScope(@"\root\cimv2");
        scope.Connect();

        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");

        foreach (ManagementObject printer in searcher.Get())
        {
            string printerName = printer["Name"].ToString().ToLower();
            Console.WriteLine("Printer :" + printerName);

            PrintProps(printer, "Caption");
            PrintProps(printer, "ExtendedPrinterStatus");
            PrintProps(printer, "Availability");
            PrintProps(printer, "Default");
            PrintProps(printer, "DetectedErrorState");
            PrintProps(printer, "ExtendedDetectedErrorState");
            PrintProps(printer, "ExtendedPrinterStatus");
            PrintProps(printer, "LastErrorCode");
            PrintProps(printer, "PrinterState");
            PrintProps(printer, "PrinterStatus");
            PrintProps(printer, "Status");
            PrintProps(printer, "WorkOffline");
            PrintProps(printer, "Local");
        }
    }

    static void PrintProps(ManagementObject o, string prop)
    {
        try { Console.WriteLine(prop + "|" + o[prop]); }
        catch (Exception e) { Console.Write(e.ToString()); }
    }
</code>```

答:
The problem I had was that one have to differentiate between network/wlan connected printers and usb wired printers:</p>

```<code>   PrintProps(printer, "WorkOffline"); // works only for usb wired printers
</code>```

Title: Get printers connected/available

Body:
Running the following code I get always nothing for "Availability".
How can I get information if a printer is online or offline? In Windows settings it is shown but not by my code:

    {
        ManagementScope scope = new ManagementScope(@"\root\cimv2");
        scope.Connect();

        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");

        foreach (ManagementObject printer in searcher.Get())
        {
            string printerName = printer["Name"].ToString().ToLower();
            Console.WriteLine("Printer :" + printerName);

            PrintProps(printer, "Caption");
            PrintProps(printer, "ExtendedPrinterStatus");
            PrintProps(printer, "Availability");
            PrintProps(printer, "Default");
            PrintProps(printer, "DetectedErrorState");
            PrintProps(printer, "ExtendedDetectedErrorState");
            PrintProps(printer, "ExtendedPrinterStatus");
            PrintProps(printer, "LastErrorCode");
            PrintProps(printer, "PrinterState");
            PrintProps(printer, "PrinterStatus");
            PrintProps(printer, "Status");
            PrintProps(printer, "WorkOffline");
            PrintProps(printer, "Local");
        }
    }

    static void PrintProps(ManagementObject o, string prop)
    {
        try { Console.WriteLine(prop + "|" + o[prop]); }
        catch (Exception e) { Console.Write(e.ToString()); }
    }

Body:
The problem I had was that one have to differentiate between network/wlan connected printers and usb wired printers:

   PrintProps(printer, "WorkOffline"); // works only for usb wired printers


来源: stackexchange

问:
Environment variable not being picked up by Node/Express/Nuxt app
I am trying to setup SendGrid with my Vue/Nuxt app, however I can only get it to to work by hardcoding the API key. When I try to use the preferred environment variable method, I get an unauthorized error. This is because the app is not picking up the variable, instead it returns Undefined.

How do I make the app get the variable?

My API KEY is kept in a filed called sendgrid.env in the project root.

I then have a Node/Express app running within my Nuxt project with the following code:

```<code>const express = require('express')
const app = express()

app.get('/', (req, res, next) => {
  res.send('API root')
})

app.get('/sendmail', (req, res, next) => {

// using Twilio SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const msg = {
    to: 'somebody@something.net',
    from: 'no-reply@somewhereelse.com',
    subject: 'Test SendGrid',
    text: 'This is a test of the SendGrid app on Node',
    html: '<strong>This is a test of the SendGrid app on Node</strong>',
};

sgMail.send(msg);

res.send('SendMail API');

})

// export the server middleware
module.exports = {
  path: '/api',
  handler: app
}
</code>```

I have tested the code using Curl and also by hardcoding the API Key, so the key is correct, it's just the environment variable that's not being picked up.

What am I doing wrong?

答:
Ok, I have solved the issue.

It seems that using @nuxt/dotenv causes issues with reading from environment variables.

I removed @nuxt/dotenv and just installed dotenv via npm, then placed the API key in the .env file and it was picked up.

Leaving here in case it helps anyone else having a similar issue.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to setup SendGrid with my Vue/Nuxt app, however I can only get it to to work by hardcoding the API key. When I try to use the preferred environment variable method, I get an unauthorized error. This is because the app is not picking up the variable, instead it returns Undefined.

How do I make the app get the variable?

My API KEY is kept in a filed called sendgrid.env in the project root.

I then have a Node/Express app running within my Nuxt project with the following code:

const express = require('express')
const app = express()

app.get('/', (req, res, next) => {
  res.send('API root')
})

app.get('/sendmail', (req, res, next) => {

// using Twilio SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const msg = {
    to: 'somebody@something.net',
    from: 'no-reply@somewhereelse.com',
    subject: 'Test SendGrid',
    text: 'This is a test of the SendGrid app on Node',
    html: 'This is a test of the SendGrid app on Node',
};

sgMail.send(msg);

res.send('SendMail API');

})

// export the server middleware
module.exports = {
  path: '/api',
  handler: app
}

I have tested the code using Curl and also by hardcoding the API Key, so the key is correct, it's just the environment variable that's not being picked up.

What am I doing wrong?


问:
how to import javax.mail in eclipse?
I am learning how to use JavaMail. (i have se11)

I downloaded javax.mail.jar,

  put it under  C:\Java\jdk , and extract it.

I followed the instruction, set CLASSPATH = C:\Java\jdk\javax.mail.jar ;

and I add the javax.mail.jar to the eclispe Referenced Library.

However, when i try to import javax.mail.* , it says the import can not be resolved.

I open the extracted folder, and it contains only  .class files.

I tried to open the javax.mail.Session file from eclipse file explorer, but it said:

"The JAR file C:\Java\jdk\bin\javax.mail.jar has no source attachment."

what should I do in order to import the javax.mail.* ?

I am very frustrated, please help!

答:
No matter how you run your program, to just use the classes in a jar you need to have the jar file in your classpath.  If you run from the command line you can do this:

```<code>java -cp C:\Java\jdk\javax.mail.jar  my.fully.qualified.classname
</code>```

If you're in Eclipse then:

Import the jar file into your Java project. Use the File-->Import... action.

Select your java project and select Build Path --> Configure Build Path...

Select Java Build Path on the left

Select the Libraries tab and the Add Jars... button on the right

Navigate to and select the jar you you imported above

Click OK

The classes in the jar file are now available for use in your code.

Title: how to import javax.mail in eclipse?

Body:
No matter how you run your program, to just use the classes in a jar you need to have the jar file in your classpath.  If you run from the command line you can do this:

java -cp C:\Java\jdk\javax.mail.jar  my.fully.qualified.classname

If you're in Eclipse then:

Import the jar file into your Java project. Use the File-->Import... action.

Select your java project and select Build Path --> Configure Build Path...

Select Java Build Path on the left

Select the Libraries tab and the Add Jars... button on the right

Navigate to and select the jar you you imported above

Click OK

The classes in the jar file are now available for use in your code.


问:
Why isn't the USER declared in my Dockerfile reflected in the ENTRYPOINT script?
I am trying to fix some tests we're running on Jenkins with Docker, but the script that the ENTRYPOINT in my Dockerfile points to keeps running as root, even though I set the USER in the Dockerfile. This works fine on my local machine but not when running on our Jenkins box.

I've tried running su within my entrypoint script to make sure that the rest of the script run as the correct user, but they still run as root.

So my Dockerfile looks like this:

```<code>FROM python:3.6

RUN apt-get update && apt-get install -y gettext libgettextpo-dev

ARG DOCKER_UID # set to 2000 in docker-compose file
ARG ENV=prod
ENV ENV=${ENV}
ARG WORKERS=2
ENV WORKERS=${WORKERS}

RUN useradd -u ${DOCKER_UID} -ms /bin/bash app
RUN chmod -R 777 /home/app

ENV PYTHONUNBUFFERED 1
ADD . /code
WORKDIR /code
RUN chown -R app:app /code
RUN mkdir /platform
RUN chown -R app:app /platform
RUN pip install --upgrade pip

RUN whoami # outputs `root`
USER app
RUN whoami # outputs `app`

RUN .docker/deploy/install_requirements.sh $ENV # runs as `app`

EXPOSE 8000

ENTRYPOINT [".docker/deploy/start.sh", "$ENV"]
</code>```

and my start.sh looks like:

#!/bin/bash

ENV=$1

echo "USER"
echo `whoami`

echo Running migrations...
python manage.py migrate

mkdir -p static
chmod -R 0755 static

cd /code/

if [ "$ENV" == "performance-dev" ];
then
    /home/app/.local/bin/uwsgi --ini .docker/deploy/uwsgi.ini -p 4 --uid app
else
    /home/app/.local/bin/uwsgi --ini .docker/deploy/uwsgi.ini --uid app
fi

```

<p>but the</p>

<pre class="lang-sh prettyprint-override"><code>echo "USER"
echo `whoami`
</code>```

outputs:

```<code>USER
root
</code>```

which causes commands later in the script the fail as they're the wrong user.

I'd except the output to be

```<code>USER
app
</code>```

and my understanding is that this issue is typically resolved by setting  the USER command in the Dockerfile, but I do that and it looks like it is switching user when running the Dockerfile itself.

Edit

The issue was with my docker-compose configuration. My docker-compose config looks like:

```<code>version: '3'

services:
  service:
    user: "${DOCKER_UID}:${DOCKER_UID}"
    build:
      context: .
      dockerfile: .docker/Dockerfile
      args:
        - ENV=prod
        - DOCKER_UID=2000
</code>```

DOCKER_UID is a variable set on my local machine but not on the Jenkins box, so I set it to 2000 in the override file

答: The issue I was having, as David Maze pointed out in the comments, was that I was setting the user when actually building the container, via my docker-compose file. I had set the user param to ${DOCKER_UID}, which was never actually set anywhere, so it was defaulting to an empty string. Setting it to 2000 fixed my issue.

Body:
I am trying to fix some tests we're running on Jenkins with Docker, but the script that the ENTRYPOINT in my Dockerfile points to keeps running as root, even though I set the USER in the Dockerfile. This works fine on my local machine but not when running on our Jenkins box.

I've tried running su within my entrypoint script to make sure that the rest of the script run as the correct user, but they still run as root.

So my Dockerfile looks like this:

FROM python:3.6

RUN apt-get update && apt-get install -y gettext libgettextpo-dev

ARG DOCKER_UID # set to 2000 in docker-compose file
ARG ENV=prod
ENV ENV=${ENV}
ARG WORKERS=2
ENV WORKERS=${WORKERS}

RUN useradd -u ${DOCKER_UID} -ms /bin/bash app
RUN chmod -R 777 /home/app

ENV PYTHONUNBUFFERED 1
ADD . /code
WORKDIR /code
RUN chown -R app:app /code
RUN mkdir /platform
RUN chown -R app:app /platform
RUN pip install --upgrade pip

RUN whoami # outputs `root`
USER app
RUN whoami # outputs `app`

RUN .docker/deploy/install_requirements.sh $ENV # runs as `app`

EXPOSE 8000

ENTRYPOINT [".docker/deploy/start.sh", "$ENV"]

and my start.sh looks like:

#!/bin/bash

ENV=$1

echo "USER"
echo `whoami`

echo Running migrations...
python manage.py migrate

mkdir -p static
chmod -R 0755 static

cd /code/

if [ "$ENV" == "performance-dev" ];
then
    /home/app/.local/bin/uwsgi --ini .docker/deploy/uwsgi.ini -p 4 --uid app
else
    /home/app/.local/bin/uwsgi --ini .docker/deploy/uwsgi.ini --uid app
fi

but the

echo "USER"
echo `whoami`

outputs:

USER
root

which causes commands later in the script the fail as they're the wrong user.

I'd except the output to be

USER
app

and my understanding is that this issue is typically resolved by setting  the USER command in the Dockerfile, but I do that and it looks like it is switching user when running the Dockerfile itself.

Edit

The issue was with my docker-compose configuration. My docker-compose config looks like:

version: '3'

services:
  service:
    user: "${DOCKER_UID}:${DOCKER_UID}"
    build:
      context: .
      dockerfile: .docker/Dockerfile
      args:
        - ENV=prod
        - DOCKER_UID=2000

DOCKER_UID is a variable set on my local machine but not on the Jenkins box, so I set it to 2000 in the override file


问:
Hide element with JQuery and activate button
I am making a product with 3 variables. A customer can pickup the products at our place, or we can deliver the products. Because of practical things, we choose to sell products there should be delivered as packages with 30, 60 or 90 products in.

Before a price can be shown, all 3 variables need to get selected. So here comes the problem. If a person wants to pickup the products at our place only 2 variables need to be selected: Length in m and Pickup or Delivery. But that will not give a price. Therefore I need to insert "Pickup" in "Packages" again to get a price.

But I would like to hide "pickup" in packages, so I do not confuse the visitor to much. The image describes what I am looking for:

The page can [be seen here][2]

This is the code I have until now, but as I see it either my code is not executed or the code is simply wrong. The page is looking excact the same as before I added my code to functions.php, and none of the functions are executed.

Based on my description does anybody have a good idea to what is wrong with my code?

HTML:

```<code><ul class="variable-items-wrapper button-variable-wrapper" data-attribute_name="attribute_pa_packages">
    <li data-wvstooltip="pickup" class="variable-item button-variable-item button-variable-item-pickup" title="pickup" data-value="pickup">
        <span class="variable-item-span variable-item-span-button">pickup</span>
    </li>
</ul>

<ul class="variable-items-wrapper button-variable-wrapper" data-attribute_name="attribute_pa_packages">
    <li data-wvstooltip="pickup" class="variable-item button-variable-item button-variable-item-pickup selected" title="pickup" data-value="pickup">
        <span class="variable-item-span variable-item-span-button">pickup</span></li>
    </li>
</ul>
</code>```

PHP and script:

```<code>function custom_script_name(){
    ?>
    <script>
    jQuery("ul[data-attribute_name=attribute_pa_pickup-og-delivery] li").click(function(){
        var selectedDelivery = jQuery("ul[data-attribute_name=attribute_pa_pickup-og-delivery]").find("li.selected").attr("data-value");
        if (selectedDelivery == "pickup"){
            jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup] span").click();
            jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=pickup]").hide(); // hide the "pickup" option in "Packages" if you like
        }
    });
    </script>
    <?php
    }
    add_action('wp_head', 'custom_script_name');
</code>```

答: If i understand the question properly, You do not need the secomd pickup button. All you need to do is to play around on when to show the price. Whenever the length, pickup or delivery or packages button is clicked, check if all the required conditions are met to show the price, then show the price. The check could be like, if delivery is selected, then packages should also be selected, else, if pickup is selected, packages is not required.</p>

Body:
I am making a product with 3 variables. A customer can pickup the products at our place, or we can deliver the products. Because of practical things, we choose to sell products there should be delivered as packages with 30, 60 or 90 products in.

Before a price can be shown, all 3 variables need to get selected. So here comes the problem. If a person wants to pickup the products at our place only 2 variables need to be selected: Length in m and Pickup or Delivery. But that will not give a price. Therefore I need to insert "Pickup" in "Packages" again to get a price.

But I would like to hide "pickup" in packages, so I do not confuse the visitor to much. The image describes what I am looking for:

The page can [be seen here][2]

This is the code I have until now, but as I see it either my code is not executed or the code is simply wrong. The page is looking excact the same as before I added my code to functions.php, and none of the functions are executed.

Based on my description does anybody have a good idea to what is wrong with my code?

HTML:

        pickup

        pickup

PHP and script:

function custom_script_name(){
    ?>

    <?php
    }
    add_action('wp_head', 'custom_script_name');


问:
Can I rely on the using statement to close my MySQL connections?
I have an ASP.NET website that uses mysql as it's database. I notice there are a lot of connections "sleeping" when I show a full process list. Today we had some errors "The timeout period elapsed prior to obtaining a connection from the pool.". If the processes are "sleeping" then are they still open from the code? All MySQL connections in the code are in using statements. Can I rely on the using statement to properly close connections?

Edit Code:
I am using this class to create my connection:

```<code>public class DbAccess
{
    public static MySqlConnection OpenConnection(string connectionStringName)
    {
        string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new ArgumentException("Connection string " + connectionStringName + " does not exist.");
        }
        MySqlConnection connection = new MySqlConnection(connectionString);
        connection.Open();
        return connection;
    }
}
</code>```

Then I am calling it like this:

```<code>using (MySqlConnection connection = DbAccess.OpenConnection(connectionString))
{
    //Code Here
}
</code>```

Some additional info: Resetting MySql did not make the errors go away, but resetting my app pool did..

答:
yes, absolutely.

```<code>using (MySqlConnection connection = DbAccess.OpenConnection(connectionString))
{
    //Code Here
}
</code>```

is exactly the same as

```<code>MySqlConnection connection = null
try
{
   connection = DbAccess.OpenConnection(connectionString)
   //Code Here
}
finally
{
    if (connection is IDisposable)
       connection.Dispose
}
</code>```

provided the MySqlConnection class implements IDisposable, then it'll get cleaned up properly. If you need to call another methos, such as close instead of or as well as, then consider the more verbose syntax above and add the method in the finally.

ContentLicense: CC BY-SA 3.0

Body:
I have an ASP.NET website that uses mysql as it's database. I notice there are a lot of connections "sleeping" when I show a full process list. Today we had some errors "The timeout period elapsed prior to obtaining a connection from the pool.". If the processes are "sleeping" then are they still open from the code? All MySQL connections in the code are in using statements. Can I rely on the using statement to properly close connections?

Edit Code:
I am using this class to create my connection:

public class DbAccess
{
    public static MySqlConnection OpenConnection(string connectionStringName)
    {
        string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new ArgumentException("Connection string " + connectionStringName + " does not exist.");
        }
        MySqlConnection connection = new MySqlConnection(connectionString);
        connection.Open();
        return connection;
    }
}

Then I am calling it like this:

using (MySqlConnection connection = DbAccess.OpenConnection(connectionString))
{
    //Code Here
}

Some additional info: Resetting MySql did not make the errors go away, but resetting my app pool did..

Body:
yes, absolutely.

using (MySqlConnection connection = DbAccess.OpenConnection(connectionString))
{
    //Code Here
}

is exactly the same as

MySqlConnection connection = null
try
{
   connection = DbAccess.OpenConnection(connectionString)
   //Code Here
}
finally
{
    if (connection is IDisposable)
       connection.Dispose
}

provided the MySqlConnection class implements IDisposable, then it'll get cleaned up properly. If you need to call another methos, such as close instead of or as well as, then consider the more verbose syntax above and add the method in the finally.


问:
Remove a big list of of special characters
I want to remove each of the following special characters from my documents:

```<code>symbols = {`,~,!,@,#,$,%,^,&,*,(,),_,-,+,=,{,[,],},|,\,:,;,",<,,,>,.,?,/}
</code>```

The reason why I am not simply doing something like this:

```<code>document = re.sub(r'([^\s\w]|_)+', '', document)
</code>```

is that in this way I remove also many (accented/special) letters in the case of documents written in languages such as Polish etc.

How can I remove each of the special characters above in one expression?

答:
without re:</p>

```<code>"".join(str(x) for x in document if x not in symbols)
</code>```

Body:
I want to remove each of the following special characters from my documents:

symbols = {`,~,!,@,#,$,%,^,&,*,(,),_,-,+,=,{,[,],},|,\,:,;,",<,,,>,.,?,/}

The reason why I am not simply doing something like this:

document = re.sub(r'([^\s\w]|_)+', '', document)

is that in this way I remove also many (accented/special) letters in the case of documents written in languages such as Polish etc.

How can I remove each of the special characters above in one expression?

Body:
without re:

"".join(str(x) for x in document if x not in symbols)


问:
Angular 6 update a component from the service
I'm using angular 6 and I need to update the component when I call a service method. I have a variable agentthat keep the selected agent from html so I get this variable from several component and I can delete this agent from a specific button.

When I call deleteAgent I have to update the interface so I need a way to "tell" to the component that the agent was deleted.

```<code>export class ComponentService {
  private agent : Agent
  constructor() { }

   /************ AGENT MANAGEMENT *****************/
   get getAgent(){
     return this.agent;
   }

   setAgent(agent: Agent){
     this.agent = agent;
   }

   deleteAgent(){
     this.agent = null;
     //inform the component about the change
   }
}
</code>```

I read about ReplaySubject but I don't know if it is the correct way and how to remove element. Can you help me? Thanks

答:
You could store the agent instance in an Observable and than subscribe in the component to that observable.</p>

```<code>export class ComponentService {
private _agent = Subject<Agent>();
constructor() { }

 /************ AGENT MANAGEMENT *****************/
 get agent(){
   return this._agent.asObservable();
 }

 set agent(agent: Agent){
   this._agent.next(agent);
 }

 deleteAgent(){
   this.agent = null;
 }
}
</code>```

Body:
I'm using angular 6 and I need to update the component when I call a service method. I have a variable agentthat keep the selected agent from html so I get this variable from several component and I can delete this agent from a specific button.

When I call deleteAgent I have to update the interface so I need a way to "tell" to the component that the agent was deleted.

export class ComponentService {
  private agent : Agent
  constructor() { }

   /************ AGENT MANAGEMENT *****************/
   get getAgent(){
     return this.agent;
   }

   setAgent(agent: Agent){
     this.agent = agent;
   }

   deleteAgent(){
     this.agent = null;
     //inform the component about the change
   }
}

I read about ReplaySubject but I don't know if it is the correct way and how to remove element. Can you help me? Thanks

Body:
You could store the agent instance in an Observable and than subscribe in the component to that observable.

export class ComponentService {
private _agent = Subject<Agent>();
constructor() { }

 /************ AGENT MANAGEMENT *****************/
 get agent(){
   return this._agent.asObservable();
 }

 set agent(agent: Agent){
   this._agent.next(agent);
 }

 deleteAgent(){
   this.agent = null;
 }
}


问:
How can we count number of records and show in rest api?
controller:

```<code><?php
    require APPPATH . '/libraries/REST_Controller.php';
    use Restserver\Libraries\REST_Controller;
    class User extends REST_Controller
    {
        function country_get()
        {
            $this->db->select('id,name');
            $this->db->from('countries');
            $sql = $this->db->get();
            $result = $sql->result_array();
            $this->response($result, 200);
        }
    }
</code>```

unexpected output:

```<code>[
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]
</code>```

expected output:

```<code>{
"Message": "Number of Country found: 5",
"Status": "Success",
"Country": [
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]
</code>```

}

In this code I want to show number of records as I mention in my expected output. So, How can I do this? Please help me.

Thank You

答:
Your result is already an array so use the PHP function count() to get the length of the array:

```<code>function country_get()
{
   $this->db->select('id,name');
   $this->db->from('countries');
   $sql = $this->db->get();
   $result = $sql->result_array();

   $response = [
       "Message" => "Number of Country found: " . count($result),
       "Status" => "Success",
       "Country" => $result
   ];

   $this->response($response, 200);
}
</code>```

Body:
controller:

<?php
    require APPPATH . '/libraries/REST_Controller.php';
    use Restserver\Libraries\REST_Controller;
    class User extends REST_Controller
    {
        function country_get()
        {
            $this->db->select('id,name');
            $this->db->from('countries');
            $sql = $this->db->get();
            $result = $sql->result_array();
            $this->response($result, 200);
        }
    }

unexpected output:

[
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]

expected output:

{
"Message": "Number of Country found: 5",
"Status": "Success",
"Country": [
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]

}

In this code I want to show number of records as I mention in my expected output. So, How can I do this? Please help me.

Thank You

Body:
Your result is already an array so use the PHP function count() to get the length of the array:

function country_get()
{
   $this->db->select('id,name');
   $this->db->from('countries');
   $sql = $this->db->get();
   $result = $sql->result_array();

   $response = [
       "Message" => "Number of Country found: " . count($result),
       "Status" => "Success",
       "Country" => $result
   ];

   $this->response($response, 200);
}


问:
Grouping by set of 2 columns with switched values (character columns)
I have a desperate question:) I want to group the data by 2 columns in proc sql in sas.

Here is the example

```<code>A           B          C
--------------------------
John      Smith        5
Smith     John         4
Adam      Gibbs        3
</code>```

The result I want is:

```<code>A           B           C
---------------------------
John       Smith        9
Adam       Gibbs        3
</code>```

I want to group values from 2 columns that may have a switched values.

Regardless of the "side" where the value is as long as they are the same in 2 columns. These are character columns so no least or greatest functions can be used. Please help!!!:)

答:
You can express the aggregation like this:

```<code>proc sql;
    select (case when a < b then a else b end) as a,
           (case when a < b then b else a end) as b,
           sum(c)
    from t
    group by (case when a < b then a else b end),
             (case when a < b then b else a end);
</code>```

Note that this can return pairs that are not in the original data.  If that is an issue, you can use:

```<code>proc sql;
    select a, b, sum(c)
    from ((select a, b
           from t
           where a < b or
                 not exists (select 1 from t t2 where t2.a = t.b and t2.b = t.a)
          ) union all
          (select b, a
           from t
           where b < a and
                 exists (select 1 from t t2 where t2.a = t.b and t2.b = t.a
          )
         ) t
    group by a, b;
</code>```

Body:
I have a desperate question:) I want to group the data by 2 columns in proc sql in sas.

Here is the example

A           B          C
--------------------------
John      Smith        5
Smith     John         4
Adam      Gibbs        3

The result I want is:

A           B           C
---------------------------
John       Smith        9
Adam       Gibbs        3

I want to group values from 2 columns that may have a switched values.

Regardless of the "side" where the value is as long as they are the same in 2 columns. These are character columns so no least or greatest functions can be used. Please help!!!:)

Body:
You can express the aggregation like this:

proc sql;
    select (case when a < b then a else b end) as a,
           (case when a < b then b else a end) as b,
           sum(c)
    from t
    group by (case when a < b then a else b end),
             (case when a < b then b else a end);

Note that this can return pairs that are not in the original data.  If that is an issue, you can use:

proc sql;
    select a, b, sum(c)
    from ((select a, b
           from t
           where a < b or
                 not exists (select 1 from t t2 where t2.a = t.b and t2.b = t.a)
          ) union all
          (select b, a
           from t
           where b < a and
                 exists (select 1 from t t2 where t2.a = t.b and t2.b = t.a
          )
         ) t
    group by a, b;


问:
Simple Spring Java @Configuration to @Autowire without @Bean
I want to make use of spring @Autowired in a java rest project. For the last days, I am trying to set up a simple spring java project with java configuration without explicit bean configuration to check that functionality out. But I can't get it to work. I may be missing something fundamental.

None of the approaches I found in the web and on this site solved my problem so far. I couldn't find a sample for exactly what I'm trying to achieve too. This is mainly due to the amount of different spring versions and approaches spread over the web.

Here is an as easy as I could come up with Java Spring rest sample. I added a few comments with how I interpret spring annotations, as I may err here too:

App base class

```<code>package restoverflow;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class App extends Application {

}
</code>```

Config class

```<code>package restoverflow;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration  //this is a configuration class and also found by spring scan
@ComponentScan  //this package and its subpackages are being checked for components and its subtypes
public class AppConfig {

}
</code>```

Some Pojo

```<code>package restoverflow;

public class Pojo {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
</code>```

A service

```<code>package restoverflow;

import org.springframework.stereotype.Service;

@Service //this is a subtype of component and found by the componentscan
public class PojoService {
    public Pojo getPojo(){
        Pojo pojo = new Pojo();
        pojo.setName("pojoName");
        return pojo;
    }
}
</code>```

And finally a resource where the autowiring of the service should be done

```<code>package restoverflow;

import javax.ws.rs.GET;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/resource")
@Controller //this is a subtype of component and found by the componentscan
public class Resource {

    @Autowired //this tells to automatically instantiate PojoService with a default contructor instance of PojoService
    private PojoService pojoService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Pojo getPojo() {
        return pojoService.getPojo();
    }
}
</code>```

Pom:

```<code>...
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.1.7.RELEASE</version>
</dependency>
...
</code>```

I want the pojoService to be instantiated. But I get a NullPointerException.

答:
A nullpointer instead of a NoSuchBeanDefinitionException is more of an indication that the Spring context is not loaded at all, rather than loaded improperly.

If you're using Spring boot, modify your main class to initialize Spring:

```<code>@SpringBootApplication
@ApplicationPath("/")
public class App extends Application {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
</code>```

Or else (as the pom.xml snippet did not mention Spring boot), initialize Spring manually by initializing a ClassPathXmlApplicationContext and adding <context:component-scan base-package="restoverflow" /> in your applicationContext.xml.

Body:
I want to make use of spring @Autowired in a java rest project. For the last days, I am trying to set up a simple spring java project with java configuration without explicit bean configuration to check that functionality out. But I can't get it to work. I may be missing something fundamental.

None of the approaches I found in the web and on this site solved my problem so far. I couldn't find a sample for exactly what I'm trying to achieve too. This is mainly due to the amount of different spring versions and approaches spread over the web.

Here is an as easy as I could come up with Java Spring rest sample. I added a few comments with how I interpret spring annotations, as I may err here too:

App base class

package restoverflow;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class App extends Application {

}

Config class

package restoverflow;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration  //this is a configuration class and also found by spring scan
@ComponentScan  //this package and its subpackages are being checked for components and its subtypes
public class AppConfig {

}

Some Pojo

package restoverflow;

public class Pojo {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

A service

package restoverflow;

import org.springframework.stereotype.Service;

@Service //this is a subtype of component and found by the componentscan
public class PojoService {
    public Pojo getPojo(){
        Pojo pojo = new Pojo();
        pojo.setName("pojoName");
        return pojo;
    }
}

And finally a resource where the autowiring of the service should be done

package restoverflow;

import javax.ws.rs.GET;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/resource")
@Controller //this is a subtype of component and found by the componentscan
public class Resource {

    @Autowired //this tells to automatically instantiate PojoService with a default contructor instance of PojoService
    private PojoService pojoService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Pojo getPojo() {
        return pojoService.getPojo();
    }
}

Pom:

...
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.1.7.RELEASE</version>
</dependency>
...

I want the pojoService to be instantiated. But I get a NullPointerException.

Body:
A nullpointer instead of a NoSuchBeanDefinitionException is more of an indication that the Spring context is not loaded at all, rather than loaded improperly.

If you're using Spring boot, modify your main class to initialize Spring:

@SpringBootApplication
@ApplicationPath("/")
public class App extends Application {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

Or else (as the pom.xml snippet did not mention Spring boot), initialize Spring manually by initializing a ClassPathXmlApplicationContext and adding <context:component-scan base-package="restoverflow" /> in your applicationContext.xml.


问:
RethinkDB on Android - compilation fails
In build.gradle:

```<code>compile group: 'com.rethinkdb', name: 'rethinkdb-driver', version: '2.3.3'
</code>```

Source/target compatibility is set to java 1.8. Error message:

Execution failed for task
  ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:    Learn how to resolve the issue at
    https://developer.android.com/studio/build/dependencies#duplicate_classes.
    Program type already present: org.hamcrest.BaseDescription

I have anaylyzed dependencies and I found this:

```<code>compile - Compile dependencies for 'main' sources (deprecated: use 'implementation' instead).
\--- com.rethinkdb:rethinkdb-driver:2.3.3
     +--- org.slf4j:slf4j-api:1.7.12
     \--- com.googlecode.json-simple:json-simple:1.1.1
          \--- junit:junit:4.10
               \--- org.hamcrest:hamcrest-core:1.1
</code>```

Any ideas how to solve this?

答:
Do like this

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.test.aress.inshorttest"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions{
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
    testImplementation 'junit:junit:4.12'
    //Call Jar dependencies like this
    implementation files('libs/rethinkdb-driver-2.3.3.jar')
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}
</code>```

In the Android Project:

Path ---> apps> libs > Add Jar Here
And get JAR File From here:

https://mvnrepository.com/artifact/com.rethinkdb/rethinkdb-driver/2.3.3

Body:
In build.gradle:

compile group: 'com.rethinkdb', name: 'rethinkdb-driver', version: '2.3.3'

Source/target compatibility is set to java 1.8. Error message:

Execution failed for task
  ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:    Learn how to resolve the issue at
    https://developer.android.com/studio/build/dependencies#duplicate_classes.
    Program type already present: org.hamcrest.BaseDescription

I have anaylyzed dependencies and I found this:

compile - Compile dependencies for 'main' sources (deprecated: use 'implementation' instead).
\--- com.rethinkdb:rethinkdb-driver:2.3.3
     +--- org.slf4j:slf4j-api:1.7.12
     \--- com.googlecode.json-simple:json-simple:1.1.1
          \--- junit:junit:4.10
               \--- org.hamcrest:hamcrest-core:1.1

Any ideas how to solve this?

Body:
Do like this

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.test.aress.inshorttest"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions{
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
    testImplementation 'junit:junit:4.12'
    //Call Jar dependencies like this
    implementation files('libs/rethinkdb-driver-2.3.3.jar')
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}

In the Android Project:

Path ---> apps> libs > Add Jar Here
And get JAR File From here:

https://mvnrepository.com/artifact/com.rethinkdb/rethinkdb-driver/2.3.3


答:
for those who are interested in the alternative solutions, here's how to achieve the same ask using a walk-path unix tool for JSON: jtc.

```<code>bash $ jtc -qq -w'<>a' -T'"#text\t@x\t@y"' -w'<@x>l:<x>v[-1][@y]<y>v[-1][#text]' -T'"{}\t{x}\t{y}"' file.json
#text   @x      @y
Text1   121.10  83.42
Text2   121.10  124.82
Text3   85.10   69.62
Text4   85.10   83.42
Text5   85.10   97.22
bash $
</code>```

walk path (-w) breakdown:

<@x>l: <x>v find each label @x and memorize found JSON value in the namespace x

[-1][@y]<y>v address a parent (from last found value), then address JSON by label @y and memorize its value in the namespace y

[-1][#text]do the same for #text label (note: not memorizing the last value)

- -T'"{}\t{x}\t{y}"': apply template with interpolation ({} will interpolate the last found value, hence there was no need memorizing it in the namespace)

- -qq will unquote the resulting JSON string (dropping quotation marks and translating \t into tabs)

- first walk (-w'<>a') is just a dummy one to trigger template interpolation for the header line.

PS> Disclosure: I'm the creator of the jtc - shell cli tool for JSON operations

Title: Parsing Json file with jq tool

Body:
I Have the following nested json file which I want to parse with jq tool and print in table form like I show at the end

The input.json structure is like this:

{
 "document":{
  "page":[
     {
        "@index":"0",
        "image":{
           "@data":"ABC",
           "@format":"png",
           "@height":"620.00",
           "@type":"base64encoded",
           "@width":"450.00",
           "@x":"85.00",
           "@y":"85.00"
        }
     },
     {
        "@index":"1",
        "row":[
           {
              "column":[
                 {
                    "text":""
                 },
                 {
                    "text":{
                       "#text":"Text1",
                       "@fontName":"Arial",
                       "@fontSize":"12.0",
                       "@height":"12.00",
                       "@width":"71.04",
                       "@x":"121.10",
                       "@y":"83.42"
                    }
                 }
              ]
           },
           {
              "column":[
                 {
                    "text":""
                 },
                 {
                    "text":{
                       "#text":"Text2",
                       "@fontName":"Arial",
                       "@fontSize":"12.0",
                       "@height":"12.00",
                       "@width":"101.07",
                       "@x":"121.10",
                       "@y":"124.82"
                    }
                 }
              ]
           }
        ]
     },
     {
        "@index":"2",
        "row":[
           {
              "column":{
                 "text":{
                    "#text":"Text3",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"363.44",
                    "@x":"85.10",
                    "@y":"69.62"
                 }
              }
           },
           {
              "column":{
                 "text":{
                    "#text":"Text4",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"382.36",
                    "@x":"85.10",
                    "@y":"83.42"
                 }
              }
           },
           {
              "column":{
                 "text":{
                    "#text":"Text5",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"435.05",
                    "@x":"85.10",
                    "@y":"97.22"
                 }
              }
           }
        ]
     },
     {
        "@index":"3"
     }
  ]
 }
}

Following the answers of the following question (Parsing nested json with jq) I've tried this code but doesn't work

$ cat file.json | jq .document.page[].row | ["#text", "@x", "@y"] | @csv

The output I'm trying to get is:

#text @x     @y
Text1 121.10 83.42
Text2 121.10 124.82
Text3 65.10  69.62
Text4 85.10  83.42
Text5 85.10  97.22

How can achieve this?

Thanks

UPDATE

Thanks so much for the help. I've tried with a real file a bit longer.

I was able to adapt the first peak's solution like below:

["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"],
( ..
| objects
| select(has("#text","@data"))
| [.["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"]]
)
| @tsv

and with new input I get this table:

+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| #text         | @data | @fontName | @fontSize | @format | @height | @type         | @width | @x     | @y     |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
|               | ABC   |           |           | png     | 620     | base64encoded | 450    | 85     | 85     |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text ä 1      |       | Tahoma    | 12        |         | 12      |               | 427.79 | 85.1   | 69.62  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text ¢76      |       | Tahoma    | 12        |         | 12      |               | 270.5  | 85.1   | 690.72 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text % 5      |       | Tahoma    | 12        |         | 12      |               | 130.84 | 358.86 | 690.72 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 7Ç8      |       | Tahoma    | 12        |         | 12      |               | 115.95 | 85.1   | 704.52 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text • 2 Wñ79 |       | Tahoma    | 8         |         | 8.04    |               | 398.16 | 121.1  | 68.06  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text          |       | Tahoma    | 12        |         | 12      |               | 101.5  | 85.1   | 83.42  |
|   » 1 A\\\\CÓ |       |           |           |         |         |               |        |        |        |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 12       |       | Tahoma    | 12        |         | 12      |               | 312.26 | 189.83 | 83.42  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 82       |       | Tahoma    | 12        |         | 12      |               | 44.99  | 85.1   | 97.22  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 31       |       | Tahoma    | 8         |         | 8.04    |               | 381.83 | 133.1  | 95.66  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+

If possible, how to add the follwing 3 columns (counter, page and row) to know the corresponding page and row for each line?

The expected output would be like this:

+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| counter | page | row | #text             | @data | @fontName | @fontSize | @format | @height | @type         | @width | @x     | @y     |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 1     | 0    |     |                   | ABC   |           |           | png     | 620     | base64encoded | 450    | 85     | 85     |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 2     | 1    | 0   | Text ä 1          |       | Tahoma    | 12        |         | 12      |               | 427.79 | 85.1   | 69.62  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 3     | 1    | 1   | Text ¢76          |       | Tahoma    | 12        |         | 12      |               | 270.5  | 85.1   | 690.72 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 4     | 1    | 1   | Text % 5          |       | Tahoma    | 12        |         | 12      |               | 130.84 | 358.86 | 690.72 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 5     | 2    | 2   | Text 7Ç8          |       | Tahoma    | 12        |         | 12      |               | 115.95 | 85.1   | 704.52 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 6     | 2    | 0   | Text • 2 Wñ79     |       | Tahoma    | 8         |         | 8.04    |               | 398.16 | 121.1  | 68.06  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 7     | 2    | 1   | Text  » 1 A\\\\CÓ |       | Tahoma    | 12        |         | 12      |               | 101.5  | 85.1   | 83.42  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 8     | 2    | 1   | Text 12           |       | Tahoma    | 12        |         | 12      |               | 312.26 | 189.83 | 83.42  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 9     | 2    | 2   | Text 82           |       | Tahoma    | 12        |         | 12      |               | 44.99  | 85.1   | 97.22  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 10    | 2    | 2   | Text 31           |       | Tahoma    | 8         |         | 8.04    |               | 381.83 | 133.1  | 95.66  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+

This is new more representative input file input2.json.

And seeing the Json structure in image below gives and idea about page number and row number present in json file and values within them.

Body:
for those who are interested in the alternative solutions, here's how to achieve the same ask using a walk-path unix tool for JSON: jtc.

bash $ jtc -qq -w'<>a' -T'"#text\t@x\t@y"' -w'<@x>l:<x>v[-1][@y]<y>v[-1][#text]' -T'"{}\t{x}\t{y}"' file.json
#text   @x      @y
Text1   121.10  83.42
Text2   121.10  124.82
Text3   85.10   69.62
Text4   85.10   83.42
Text5   85.10   97.22
bash $

walk path (-w) breakdown:

<@x>l: <x>v find each label @x and memorize found JSON value in the namespace x

[-1][@y]<y>v address a parent (from last found value), then address JSON by label @y and memorize its value in the namespace y

[-1][#text]do the same for #text label (note: not memorizing the last value)

- -T'"{}\t{x}\t{y}"': apply template with interpolation ({} will interpolate the last found value, hence there was no need memorizing it in the namespace)

- -qq will unquote the resulting JSON string (dropping quotation marks and translating \t into tabs)

- first walk (-w'<>a') is just a dummy one to trigger template interpolation for the header line.

PS> Disclosure: I'm the creator of the jtc - shell cli tool for JSON operations


问:
DataSource bean overriding in spring boot 2.1
I have upgraded to spring boot 2.1 release and I have got strange exception when starting up the application.

The bean 'dataSource', defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class] and overriding is disabled.

The full error message is:

[o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext] Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'dataSource' defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Cannot register bean definition [Root bean: class [org.springframework.aop.scope.ScopedProxyFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] for bean 'dataSource': There is already [Root bean: class [null]; scope=refresh; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=false; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] bound.

Beans must not be overridden according to our policy and it's disabled with:

```<code>spring.main.allow-bean-definition-overriding=false
</code>```

I don't have any data source configuration in my application code. The only option that triggers this error is @EnableAutoConfiguration and in my application properties I have set the data source type to:

```<code>spring.datasource.type=com.zaxxer.hikari.HikariDataSource
</code>```

The boot application is initialized with

```<code>@SpringBootApplication
@EnableAutoConfiguration
public class MyApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        new MyApplication()
            .configure(new SpringApplicationBuilder(MyApplication.class))
            .run(args);
    }
}
</code>```

There is also configuration class that imports various other configurations:

```<code>@Configuration
@ImportResource(locations = {
    "classpath*:conf/spring/*.xml",
    "classpath*:conf/spring/core/*.xml",
    "classpath*:conf/spring/plugin/**/*.xml"
})
@EnableAsync
@EnableRetry
@EnableCaching
@EnableBatchProcessing
@EnableCircuitBreaker
public class AppConfig {
    ...
}
</code>```

Does anyone knows what could cause that issue and where to search?

It didn't happened prior to Spring Boot 2.1 (i.e. 2.0.5).

答:
I ran into a similar problem and it is very generic (sometimes there are duplicated annotation sometimes duplicated beans). In case when you have duplicated annotation like @EnableJpaRepository the error message not mention this annotation at all. The best way to find where the problem is:

Open class DefaultListableBeanFactory
There should be code like this:

```<code>BeanDefinition existingDefinition = (BeanDefinition)this.beanDefinitionMap.get(beanName);
        if (existingDefinition != null) {
            if (!this.isAllowBeanDefinitionOverriding()) {
                throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
            }
</code>```

Put a breakpoint in line with throw new. Then existingDefinition.source.className is pointing to configuration which is already registered and here is the problem. When you check the beanDefinition.source.className you will compare both classes and find where duplicated code or annotation is, just delete/fix them.

Body:
I have upgraded to spring boot 2.1 release and I have got strange exception when starting up the application.

The bean 'dataSource', defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class] and overriding is disabled.

The full error message is:

[o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext] Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'dataSource' defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Cannot register bean definition [Root bean: class [org.springframework.aop.scope.ScopedProxyFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in BeanDefinition defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] for bean 'dataSource': There is already [Root bean: class [null]; scope=refresh; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=false; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] bound.

Beans must not be overridden according to our policy and it's disabled with:

spring.main.allow-bean-definition-overriding=false

I don't have any data source configuration in my application code. The only option that triggers this error is @EnableAutoConfiguration and in my application properties I have set the data source type to:

spring.datasource.type=com.zaxxer.hikari.HikariDataSource

The boot application is initialized with

@SpringBootApplication
@EnableAutoConfiguration
public class MyApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        new MyApplication()
            .configure(new SpringApplicationBuilder(MyApplication.class))
            .run(args);
    }
}

There is also configuration class that imports various other configurations:

@Configuration
@ImportResource(locations = {
    "classpath*:conf/spring/*.xml",
    "classpath*:conf/spring/core/*.xml",
    "classpath*:conf/spring/plugin/**/*.xml"
})
@EnableAsync
@EnableRetry
@EnableCaching
@EnableBatchProcessing
@EnableCircuitBreaker
public class AppConfig {
    ...
}

Does anyone knows what could cause that issue and where to search?

It didn't happened prior to Spring Boot 2.1 (i.e. 2.0.5).

Body:
I ran into a similar problem and it is very generic (sometimes there are duplicated annotation sometimes duplicated beans). In case when you have duplicated annotation like @EnableJpaRepository the error message not mention this annotation at all. The best way to find where the problem is:

Open class DefaultListableBeanFactory
There should be code like this:

BeanDefinition existingDefinition = (BeanDefinition)this.beanDefinitionMap.get(beanName);
        if (existingDefinition != null) {
            if (!this.isAllowBeanDefinitionOverriding()) {
                throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
            }

Put a breakpoint in line with throw new. Then existingDefinition.source.className is pointing to configuration which is already registered and here is the problem. When you check the beanDefinition.source.className you will compare both classes and find where duplicated code or annotation is, just delete/fix them.


问:
Pycharm code inspection with remote interpreter
I am using PyCharm professional edition 2018.1 I am using remote interpreter via ssh. As a result, when I use shortcuts to Inspect Code (e.g. look at the source of a function I am using in the main script), the tab that opens refers to a file on the remote server /system/remote_resources/.../...

This is quite annoying because this is not the file I need to modify, since it is just a temporary copy of the local file and it already happened to me to modify the remote file, which has no effect on the execution.

Is there a way for PyCharm code inspection to open the local script, rather than the remote copy?

This is how I configure the ssh connection. No path mappings are set.

答:
I found a solution that works for me.

```<code>Settings -> Project -> Project Structure
</code>```

Then right-click on folders and select Sources, so they appear on the menu on the right under Source Folders.

Now the code inspection opens my local file, not those copied in /system/remote_resources/

Body:
I found a solution that works for me.

Settings -> Project -> Project Structure

Then right-click on folders and select Sources, so they appear on the menu on the right under Source Folders.

Now the code inspection opens my local file, not those copied in /system/remote_resources/


问:
Laravel - Text input search not working on button click
I am creating a search criteria whereby the text input on button click will displat the result on table td. No thing change and there is no error message displayed

I have written the controller and view

Controller

```<code>    public function playersPerGame()
    {

        $data['title'] = 'Games Report';
        $games= GamePoint::select('game_point.game_name','game_point.description','game_point.point_assigned','game_point.created_at');
        $render=[];
        if(isset($request->game_name))
        {
            $games=$games->where('game_name','like','%'.$request->game_name.'%');
            $render['name']=$request->name;
        }

        $games= $games->paginate(15);
        $games= $games->appends($render);
        $data['games'] = $games;
        return view('report.playersPerGame',$data); //
    }
</code>```

View

```<code>        {{ Form::model(request(),['method'=>'get']) }}
        <div class="col-sm-4">
            {{ Form::text('game_name',null,['class'=>'form-control','placeholder'=>'Game name']) }}

        </div>
        <div class="col-sm-4">

        </div>
        <div class="col-sm-4">
            {{ Form::submit('Search',['class'=>'btn btn-warning']) }}
            <a href="" class="btn btn-info">Export</a>
        </div>
        {{ Form::close() }}
    </div>

          <div class="box box-primary">
            <div class="box-header with-border">
        @if(Session::has('flash_message'))
        <div class="alert alert-success">
            {{ Session::get('flash_message') }}
        </div>
        @endif
        @if(count($games))
<table class="table table-bordered table-hover table-striped table-condesed" id="game_info_table">
    <caption></caption>
    <thead>
        <tr>
            <td>#</td>
            <td>Games</td>
            <td>Description</td>
            <td>Point Assigned</td>
            <td>Date Uploaded</td>
        </tr>
    </thead>
    <tbody>
        @foreach($games as $key => $gaming)
            <tr>
                <td>{{ ++$key }}</td>
                <td>{{ $gaming->game_name }}</td>
                <td>{{ $gaming->description }}</td>
                <td>{{ $gaming->point_assigned }}</td>
                <td>{{ $gaming->created_at }}</td>

            </tr>
        @endforeach
</code>```

On button click, I expect it to display result based on the text input but nothing happen

答: I have solved it myself. I forgot to add (Request $request). Thanks</p>

Body:
I am creating a search criteria whereby the text input on button click will displat the result on table td. No thing change and there is no error message displayed

I have written the controller and view

Controller

    public function playersPerGame()
    {

        $data['title'] = 'Games Report';
        $games= GamePoint::select('game_point.game_name','game_point.description','game_point.point_assigned','game_point.created_at');
        $render=[];
        if(isset($request->game_name))
        {
            $games=$games->where('game_name','like','%'.$request->game_name.'%');
            $render['name']=$request->name;
        }

        $games= $games->paginate(15);
        $games= $games->appends($render);
        $data['games'] = $games;
        return view('report.playersPerGame',$data); //
    }

View

        {{ Form::model(request(),['method'=>'get']) }}

            {{ Form::text('game_name',null,['class'=>'form-control','placeholder'=>'Game name']) }}

            {{ Form::submit('Search',['class'=>'btn btn-warning']) }}
            Export

        {{ Form::close() }}

        @if(Session::has('flash_message'))

            {{ Session::get('flash_message') }}

        @endif
        @if(count($games))

            #
            Games
            Description
            Point Assigned
            Date Uploaded

        @foreach($games as $key => $gaming)

                {{ ++$key }}
                {{ $gaming->game_name }}
                {{ $gaming->description }}
                {{ $gaming->point_assigned }}
                {{ $gaming->created_at }}

        @endforeach

On button click, I expect it to display result based on the text input but nothing happen


问:
Initializing StringBuilder to use UTF-16 coder
Consider the following code in Java 11:

```<code>StringBuilder sb = new StringBuilder("one");
sb.append("δύο");  // "two"
</code>```

The first line creates a StringBuilder that uses the Latin1 coder (one byte per character). Then the second line causes the StringBuilder to realise that it needs to use the UTF16 coder instead, so it copies its current contents into a new array before appending the new UTF-16 characters.

The StringBuilder class has a constructor overload that takes an initial capacity argument, which is designed to avoid reallocation if you already know the required size of the string to be built. But if you start with an English string and then append a foreign string, this particular constructor overload is useless as it still reallocates the byte array.

Is there a way to create a StringBuilder instance that uses UTF16 right from the start?

答:
Seems like there is no obvious one. If you wanted to influence the way StringBuffer initializes, my suggestion would be to create a utility 'initializer' that implements CharSequence and use the corresponding StringBuilder constructor. You can communicate any length and char content you wish with it, and StringBuilder internals should be smart enough to pick up on it.

Looking at the OpenJDK 11 implementation though, it seems hell-bent on starting with Latin1 no matter what. Some form of reallocation seems to always happen.

Body:
Consider the following code in Java 11:

StringBuilder sb = new StringBuilder("one");
sb.append("δύο");  // "two"

The first line creates a StringBuilder that uses the Latin1 coder (one byte per character). Then the second line causes the StringBuilder to realise that it needs to use the UTF16 coder instead, so it copies its current contents into a new array before appending the new UTF-16 characters.

The StringBuilder class has a constructor overload that takes an initial capacity argument, which is designed to avoid reallocation if you already know the required size of the string to be built. But if you start with an English string and then append a foreign string, this particular constructor overload is useless as it still reallocates the byte array.

Is there a way to create a StringBuilder instance that uses UTF16 right from the start?


问:
How are all the events listeners in JavaScript kept active or alive?
I always wondered how an event handler in JavaScript was always listening for subsequent actions to trigger the event again and again even after the JavaScript code you write has been parsed.
I've tried to research online but I've not found any resources that explains how the events listeners are kept active or alive.

I understand how the call stack works but I just want to know how all the event listeners are kept alive or active.

For example addEventListener with a "click" event will always run the specified callback if the button is clicked. So how is the callback added by the addEventListener method always kept alive or active?

答: This behaviour of JavaScript is commonly described as "the event loop". The JavaScript engine runs and runs and runs and keeps looking for new events. It will run until all event handlers were detached. Now if an event gets triggered, it will end up in an event queue. Then somewhen the event loop takes the event out of the queue, and executes it. That will create a callstack, if that unwinded, the loop continues.</p>


问:
How to call a function and then navigate to a route when click on a button?
Here is my code.

```<code><button type="button" className="btn btn-outline-secondary" onClick={this.addToCart.bind(
    this,
    this.state.itemDetails.product.images[0].path,
    this.state.itemDetails.name,
    this.state.itemDetails.id,
    this.state.itemDetails.unitPrice,
    this.state.quantity
)} >
    <Link to="/proceedToCheckout">
    Buy Now
    </Link>
</button>
</code>```

Here I want to call the event onClick and with that I want to direct page to the link "/proceedToCheckout" when I click on the button. I want to do both of this with a single button click.
In the above code, when I click on the button area it calls the addToCart function. But route is not working. If I click on the word "Buy Now" (the link) then it directs to the route. But I want to do is with a single button click I need to call the function "addToCart" and then to direct to the route "/proceedToCheckout"

答:
```<code><button onClick={() => this.props.history.push('/proceedToCheckout')}>Buy Now</button>
</code>```

Body:
Here is my code.

<button type="button" className="btn btn-outline-secondary" onClick={this.addToCart.bind(
    this,
    this.state.itemDetails.product.images[0].path,
    this.state.itemDetails.name,
    this.state.itemDetails.id,
    this.state.itemDetails.unitPrice,
    this.state.quantity
)} >
    <Link to="/proceedToCheckout">
    Buy Now
    </Link>
</button>

Here I want to call the event onClick and with that I want to direct page to the link "/proceedToCheckout" when I click on the button. I want to do both of this with a single button click.
In the above code, when I click on the button area it calls the addToCart function. But route is not working. If I click on the word "Buy Now" (the link) then it directs to the route. But I want to do is with a single button click I need to call the function "addToCart" and then to direct to the route "/proceedToCheckout"


问:
Python Example for KNN or K-Means Clustering
I am looking at some sample data such as this:

Data:

```<code>ID  Name    ParValue    Coupon  Maturity    Issuer  Moodys  S&P_Fitch   Grade   Risk
37833100    Apple_Inc.  1049    95  2030    Apple_Inc.  Aaa AAA Investment  Highest_Quality
02079K107   Alphabet_Inc.   1055    99  2030    Alphabet_Inc.   Aa  AA  Investment  High_Quality
11659109    Alaska_Air_Group    996 98  2030    Alaska_Air_Group    A   A   Investment  Strong
931142103   Walmart_Stores,_Inc.    1195    99  2030    Walmart_Stores,_Inc.    Baa BBB Investment  Medium_Grade
495734523   Corp._Takeover  1108    97  2021    Corp._Takeover  Ba,_B   BB,_B   Junk    Speculative
193467211   Toys_R_Us   1109    105 2021    Toys_R_Us   Caa/Ca/C    CCC/CC/C    Junk    Highly_Speculative
576300972   Enron   1062    102 2021    Enron   C   D   Junk    In_Default
983457823   Economic_Consultants_Inc.               Economic_Consultants_Inc.   Baa BBB Investment  Medium_Grade
894652378   Forecast_Backtesters_Corp.              Forecast_Backtesters_Corp.  Aaa AAA Investment  Highest_Quality
</code>```

Image:

So, if WalMart has Baa, BBB, Investment, and Medium_Grade (for Moodys, S&P_Fitch, Grade, and Risk) and Economic_Consultants_Inc. has these same attributes, I can know that Economic_Consultants_Inc. has 1195, 99, and 2030 (for ParValue, Coupon, Maturity), even though these data points are missing.

This is probably a KNN problem, but I'm thinking K-Means could be useful too.  Basically, I'm trying to figure out how to update missing data points (ParValue, Coupon, & Maturity), like the ones colored pink in the image above, based on similar attributes.  Then, I want to group similar items together (K-Means problem).  Has someone here come across a good online example of how to do this?  I looked online today and found some examples using randomly generated numbers, but my data sets will NOT have randomly generated numbers.  I would appreciate any insight into how to solve this problem.

答:
What you seem to be missing is pandas.

I suggest you go through the 10 min tutorial to get started.
The approach should be

Load the data into a dataframe using pandas,

Use the apply method to fill the missing values, based on the conditions you stated above.

This answer is similar to what you might have to do.

Body:
I am looking at some sample data such as this:

Data:

ID  Name    ParValue    Coupon  Maturity    Issuer  Moodys  S&P_Fitch   Grade   Risk
37833100    Apple_Inc.  1049    95  2030    Apple_Inc.  Aaa AAA Investment  Highest_Quality
02079K107   Alphabet_Inc.   1055    99  2030    Alphabet_Inc.   Aa  AA  Investment  High_Quality
11659109    Alaska_Air_Group    996 98  2030    Alaska_Air_Group    A   A   Investment  Strong
931142103   Walmart_Stores,_Inc.    1195    99  2030    Walmart_Stores,_Inc.    Baa BBB Investment  Medium_Grade
495734523   Corp._Takeover  1108    97  2021    Corp._Takeover  Ba,_B   BB,_B   Junk    Speculative
193467211   Toys_R_Us   1109    105 2021    Toys_R_Us   Caa/Ca/C    CCC/CC/C    Junk    Highly_Speculative
576300972   Enron   1062    102 2021    Enron   C   D   Junk    In_Default
983457823   Economic_Consultants_Inc.               Economic_Consultants_Inc.   Baa BBB Investment  Medium_Grade
894652378   Forecast_Backtesters_Corp.              Forecast_Backtesters_Corp.  Aaa AAA Investment  Highest_Quality

Image:

So, if WalMart has Baa, BBB, Investment, and Medium_Grade (for Moodys, S&P_Fitch, Grade, and Risk) and Economic_Consultants_Inc. has these same attributes, I can know that Economic_Consultants_Inc. has 1195, 99, and 2030 (for ParValue, Coupon, Maturity), even though these data points are missing.

This is probably a KNN problem, but I'm thinking K-Means could be useful too.  Basically, I'm trying to figure out how to update missing data points (ParValue, Coupon, & Maturity), like the ones colored pink in the image above, based on similar attributes.  Then, I want to group similar items together (K-Means problem).  Has someone here come across a good online example of how to do this?  I looked online today and found some examples using randomly generated numbers, but my data sets will NOT have randomly generated numbers.  I would appreciate any insight into how to solve this problem.


问:
Referencing a View in another XML file
I have a ListView in a file called a.xml.

```<code><ListView
        android:id="@+id/mylistview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:scrollbars="none"
        android:layout_above="XYZ"
        />
</code>```

In a.xml, I also include another file called b.xml.

```<code><include android:id="@+id/bottombar" layout="@layout/b" />
</code>```

For one of the settings of the ListView, I want to reference an id (XYZ) that exists in b.xml.

Is there a way I can do this?

I've tried the following:

```<code><RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <include android:id="@+id/bottombar" layout="@layout/b" />
    <ListView
        android:id="@+id/mylistview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:scrollbars="none"
        android:layout_above="@id/bottombar_background"
        />
</RelativeLayout>
</code>```

Where @id/bottombar_background exists in @layout/b, but Eclipse throws "no resource" errors at me.

答: After you have used setContentView(R.layout.a) you should be able to use findViewById(R.id.my_id_in_b).

Title: Referencing a View in another XML file

Body:
I have a ListView in a file called a.xml.

<ListView
        android:id="@+id/mylistview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:scrollbars="none"
        android:layout_above="XYZ"
        />

In a.xml, I also include another file called b.xml.

<include android:id="@+id/bottombar" layout="@layout/b" />

For one of the settings of the ListView, I want to reference an id (XYZ) that exists in b.xml.

Is there a way I can do this?

I've tried the following:

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <include android:id="@+id/bottombar" layout="@layout/b" />
    <ListView
        android:id="@+id/mylistview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:scrollbars="none"
        android:layout_above="@id/bottombar_background"
        />
</RelativeLayout>

Where @id/bottombar_background exists in @layout/b, but Eclipse throws "no resource" errors at me.


问:
Java util Logger not writing to file
I have written a silly Logger for my application. It writes into a log file info, warning and severe messages. It worked perfectly some time ago, but suddenly, it stopped working for no aparent reason.
It keeps creating the log file if it does not exist, but no content is written.
I can't find why it is not working now. I would thank some help.

Debugging with my IDE, I realise that messages are passed correctly to logger, and logger.info() is being executed.

```<code>public class FsLogger {

    private static FsLogger instance;

    private final String filename = "Logs/LogFsForensics.log";
    private final String loggerName = "FsLogger";
    private static Logger logger;
        private FileHandler fh;
        private final int limit = 1024*10000; //10 MB
        private SimpleFormatter sf;

    private FsLogger() {
        logger =  Logger.getLogger(loggerName);

        sf = new SimpleFormatter();
        try {
            fh = new FileHandler(filename, limit, 1, true);
            sf = new SimpleFormatter();
            fh.setFormatter(sf);

            logger.addHandler(fh);
        } catch (SecurityException | IOException e) {
            e.printStackTrace();
        }
    }

    public static FsLogger getInstance() {
        if(instance == null) {
            instance = new FsLogger();
        }
        return instance;
    }

    public void info(String message) {
        logger.info(message);
    }

    public void warning(String message) {
        logger.warning(message);
    }

    public void severe(String message) {
        logger.severe(message);
    }
</code>```

Example of a logger call:

```<code>private FsLogger logger = FsLogger.getInstance();
logger.severe(e1.getMessage());
</code>```

答:
I've tried to execute your code and get the following output in both the console and file:

```<code>May 30, 2019 12:35:11 PM io.yooksi.Main main
INFO: This is a test.
May 30, 2019 12:35:11 PM io.yooksi.FsLogger info
INFO: This is an info message
May 30, 2019 12:35:11 PM io.yooksi.FsLogger warning
WARNING: This is a warning
May 30, 2019 12:35:11 PM io.yooksi.FsLogger severe
SEVERE: This is a sever error message
</code>```

This means that your code is not at fault, so you can try the following things:

Make sure that the following code properly outputs to console:

Logger logger = Logger.getLogger("test");
logger.info("This is a test.");
```

Make sure that the file is not in read-only state.

Try manually writing to file using either FileWriter or PrintWriter.

If the first test fails to print anything to console then read the following document where you can find a list of common reasons why Java logger fails to works and concrete steps how to resolve them (at least the one related to configuration):

Why is my Java Logging not working

Title: Java util Logger not writing to file

Body:
I have written a silly Logger for my application. It writes into a log file info, warning and severe messages. It worked perfectly some time ago, but suddenly, it stopped working for no aparent reason.
It keeps creating the log file if it does not exist, but no content is written.
I can't find why it is not working now. I would thank some help.

Debugging with my IDE, I realise that messages are passed correctly to logger, and logger.info() is being executed.

public class FsLogger {

    private static FsLogger instance;

    private final String filename = "Logs/LogFsForensics.log";
    private final String loggerName = "FsLogger";
    private static Logger logger;
        private FileHandler fh;
        private final int limit = 1024*10000; //10 MB
        private SimpleFormatter sf;

    private FsLogger() {
        logger =  Logger.getLogger(loggerName);

        sf = new SimpleFormatter();
        try {
            fh = new FileHandler(filename, limit, 1, true);
            sf = new SimpleFormatter();
            fh.setFormatter(sf);

            logger.addHandler(fh);
        } catch (SecurityException | IOException e) {
            e.printStackTrace();
        }
    }

    public static FsLogger getInstance() {
        if(instance == null) {
            instance = new FsLogger();
        }
        return instance;
    }

    public void info(String message) {
        logger.info(message);
    }

    public void warning(String message) {
        logger.warning(message);
    }

    public void severe(String message) {
        logger.severe(message);
    }

Example of a logger call:

private FsLogger logger = FsLogger.getInstance();
logger.severe(e1.getMessage());

Body:
I've tried to execute your code and get the following output in both the console and file:

May 30, 2019 12:35:11 PM io.yooksi.Main main
INFO: This is a test.
May 30, 2019 12:35:11 PM io.yooksi.FsLogger info
INFO: This is an info message
May 30, 2019 12:35:11 PM io.yooksi.FsLogger warning
WARNING: This is a warning
May 30, 2019 12:35:11 PM io.yooksi.FsLogger severe
SEVERE: This is a sever error message

This means that your code is not at fault, so you can try the following things:

Make sure that the following code properly outputs to console:

Logger logger = Logger.getLogger("test");
logger.info("This is a test.");

Make sure that the file is not in read-only state.

Try manually writing to file using either FileWriter or PrintWriter.

If the first test fails to print anything to console then read the following document where you can find a list of common reasons why Java logger fails to works and concrete steps how to resolve them (at least the one related to configuration):

Why is my Java Logging not working


问:
How to setup approvals for each deployment when it is scheduled in Azure DevOps
I want to set approvals for each deployment triggered/scheduled in Azure DevOps.

How can I achieve this?

Thank you

答:
No matter what the trigger type is, the setting of approval are all same.

Just open the pre-deployment conditions of each deployment, and then add the approver account or group name.  And it also same in post-deployment conditions to set post-deployment approval.


问:
How to check if element in list matches with another element in a list of strings?

Input lists

```<code>list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']
</code>```

Output list

```<code>output=['Google','AU-KBC Research Centre']
</code>```

The output should have only those elements which do not contain the words(elements) from the exclusion_list
I have searched all of SO. But, none of them give an answer to specifically this problem. I have tried using filter() and also a dumb function. But, I am looking for a non-brute-force solution. Also, I am curious about an extra solution which uses regex to solve the problem.

Basically

I am looking for an optimal way to remove any sort of university, school or institute from the list1

EDIT: I want to preserve the order of the list as well. I apologize for not making this point clear.

答:
```<code>import pandas as pd
k = pd.Series(['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre'])
k[~k.str.contains('|'.join(exclusion_list))].tolist()
</code>```

Body:
Input lists

list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']

Output list

output=['Google','AU-KBC Research Centre']

The output should have only those elements which do not contain the words(elements) from the exclusion_list
I have searched all of SO. But, none of them give an answer to specifically this problem. I have tried using filter() and also a dumb function. But, I am looking for a non-brute-force solution. Also, I am curious about an extra solution which uses regex to solve the problem.

Basically

I am looking for an optimal way to remove any sort of university, school or institute from the list1

EDIT: I want to preserve the order of the list as well. I apologize for not making this point clear.


问:
How is string pool measured in terms of buckets in java
While going through this article about String pool and its changes over the years, I came across the following statement:

Prior to Java 7u40, the default pool size was 1009 buckets but this
  value was subject to a few changes in more recent Java versions. To be
  precise, the default pool size from Java 7u40 until Java 11 was 60013
  and now it increased to 65536.

So, what are buckets in String pool? How are these comparable to the number of interned Strings? Is the concept similar to buckets in hashmaps?

答:
So, what are buckets in String pool?

The String pool is basically a hash table. A hash table contains buckets or slots.

How are these comparable to the number of interned Strings?

It's implementation-defined (JVM-specific) and depends on how many entries a single bucket stores. Ideally, one bucket keeps one entry.

Is the concept similar to buckets in hashmaps?

Yes, it's the same idea.

Why is the default pool size growing? (my question)

The more buckets are allocated, the lower the load factor gets, which positively affects performance. I guess the initial number of entries occupied in the table grows, so it's important to keep the load factor updated (at least at the same level).


问:
Find median in nth range in Python
I am trying to find value of every median in my dataset for every 15 days. Dataset has three columns - index, value and date.

This is for evaluation of this median according to some conditions. Each of 15 days will get new value according to conditions.
I've tried several approaches (mostly python comprehension) but I am still a beginner to solve it properly.

```<code>    value   date        index
14  13065   1983-07-15  14
15  13065   1983-07-16  15
16  13065   1983-07-17  16
17  13065   1983-07-18  17
18  13065   1983-07-19  18
19  13065   1983-07-20  19
20  13065   1983-07-21  20
21  13065   1983-07-22  21
22  13065   1983-07-23  22
23  .....    .........  ..

medians = [dataset['value'].median() for range(0, len(dataset['index']), 15) in dataset['value']]
</code>```

I am expecting to return medians from the dataframe to a new variable.

```<code>syntaxError: can't assign to function call
</code>```

答:
Assuming you have data in the below format:

```<code>test = pd.DataFrame({'date': pd.date_range(start = '2016/02/12', periods = 1000, freq='1D'),
                                         'value': np.random.randint(1,1000,1000)})
test.head()

    date       value
0   2016-02-12  243
1   2016-02-13  313
2   2016-02-14  457
3   2016-02-15  236
4   2016-02-16  893
</code>```

If you want to median for every 15 days then use pd.Grouper and groupby date:

```<code>test.groupby(pd.Grouper(freq='15D', key='date')).median().reset_index()

date        Value
2016-02-12  457.0
2016-02-27  733.0
2016-03-13  688.0
2016-03-28  504.0
2016-04-12  591.0
</code>```

Note that while using pd.Grouper, your date column should be of type datetime. If it's not, convert using:

```<code>test['date'] = pd.to_datetime(test['date'])
</code>```

Title: Find median in nth range in Python

Body:
I am trying to find value of every median in my dataset for every 15 days. Dataset has three columns - index, value and date.

This is for evaluation of this median according to some conditions. Each of 15 days will get new value according to conditions.
I've tried several approaches (mostly python comprehension) but I am still a beginner to solve it properly.

    value   date        index
14  13065   1983-07-15  14
15  13065   1983-07-16  15
16  13065   1983-07-17  16
17  13065   1983-07-18  17
18  13065   1983-07-19  18
19  13065   1983-07-20  19
20  13065   1983-07-21  20
21  13065   1983-07-22  21
22  13065   1983-07-23  22
23  .....    .........  ..

medians = [dataset['value'].median() for range(0, len(dataset['index']), 15) in dataset['value']]

I am expecting to return medians from the dataframe to a new variable.

syntaxError: can't assign to function call

Body:
Assuming you have data in the below format:

test = pd.DataFrame({'date': pd.date_range(start = '2016/02/12', periods = 1000, freq='1D'),
                                         'value': np.random.randint(1,1000,1000)})
test.head()

    date       value
0   2016-02-12  243
1   2016-02-13  313
2   2016-02-14  457
3   2016-02-15  236
4   2016-02-16  893

If you want to median for every 15 days then use pd.Grouper and groupby date:

test.groupby(pd.Grouper(freq='15D', key='date')).median().reset_index()

date        Value
2016-02-12  457.0
2016-02-27  733.0
2016-03-13  688.0
2016-03-28  504.0
2016-04-12  591.0

Note that while using pd.Grouper, your date column should be of type datetime. If it's not, convert using:

test['date'] = pd.to_datetime(test['date'])


问:
Multiple conditions in regex - how to replace both colon and space with dash
How to replace both colon and space with dash in regex?
Here's what I've managed to do:
to replace space: replace(/\s+/g, '-'),
to replace colon: replace(/:\s+/g, '-').
How do I merge these expressions?

答:
You could do something like this:

```<code>var text = "hello: hey"
console.log(text.replace(/(:|\s+)/g, "-"))
</code>```

Returns "hello--hey"

Body:
You could do something like this:

var text = "hello: hey"
console.log(text.replace(/(:|\s+)/g, "-"))

Returns "hello--hey"


答:
One-liner: </p>

<pre class="lang-py prettyprint-override"><code>[s for s in list1 if not any(e in s.lower() for e in exclusion_list)]
</code>```

<p>Similarly possible with filter as you mentioned: </p>

<pre class="lang-py prettyprint-override"><code>list(filter(lambda s: not any(e in s.lower() for e in exclusion_list), list1))
</code>```

Title: How to check if element in list matches with another element in a list of strings?

Body:
One-liner:

[s for s in list1 if not any(e in s.lower() for e in exclusion_list)]

Similarly possible with filter as you mentioned:

list(filter(lambda s: not any(e in s.lower() for e in exclusion_list), list1))