问:
Change SharePoint Library URL
How do you change the URI of a SharePoint library? Based on Google searching, most people say that changing the name of a library in Designer (via right click->rename) will result in the URI change, but it is only changing the name for me.

I am using SharePoint 2010 Foundation and these are the steps I am following:

In Designer, navigate to List and Libraries

Right click library -> rename

Notice that name changes

Notice that URI does not change

This is one of the resources I found claiming that this works:

change URL spelling/case on sharepoint library

答:
In Designer go to "All Files" -> then search for "List" folder ther you can find your List right click it rename it and boom.
By going to Lists and Libraries tab from left menu will only change the title of list. So go to All files and follow the steps.</p>

Title: Change SharePoint Library URL


来源: stackexchange

问:
Wordpress-ob_start():failed to create buffer
My website was built with wordpress and now I get the following error:

PHP message: PHP Warning:  ob_start(): function '‘ob_gzhandler’' not
  found or invalid function name in /var/www/html/wordpress/index.php on
  line 15

And this is index.php:
enter image description here

Any idea to fix it?

答:
Try setting the Content-Encoding header.</p>

```<code>header('Content-Encoding: gzip');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Try setting the Content-Encoding header.

header('Content-Encoding: gzip');


问:
Arangodb groupby query multiple fields
I have a database of products in an arangodb collection in which a product has multiple sizes. The issue is that for each size, the same product is repeated. But each product has a common group number. Like this:

```<code>{"name": "product1", "description": "someDescription", size: 5,price: 12 groupNumber: 12}
{"name": "product1", "description": "someDescription", size: 15, price: 26, groupNumber: 12}
{"name": "product1", "description": "someDescription", size: 25, price: 84, groupNumber: 12}
{"name": "product1", "description": "someDescription", size: 35, price: 106, groupNumber: 12}

{"name": "product2", "description": "someDescription", size: 5, price: 12, groupNumber: 11}
{"name": "product2", "description": "someDescription", size: 15, price: 22, groupNumber: 11}
{"name": "product2", "description": "someDescription", size: 25, price: 32, groupNumber: 11}
{"name": "product2", "description": "someDescription", size: 35, price: 43, groupNumber: 11}
</code>```

I have to now display the list of products(in a web page) but each product should appear only once with sizes and prices in an array for each product like this:

```<code>product1 someDescription sizes: 5,15,25,35, prices: 12,26,84,106
product2 someDescription sizes: 5,15,25,35, prices: 12,22,32,43
...
</code>```

How do I do it?

答:
Ignoring the groupNumber and grouping by name, the query looks like this:

```<code>FOR p IN products
  COLLECT description = p.description, name = p.name INTO groups
  RETURN {
    "name" : name,
    "description": description,
    "prices" : groups[*].p.price,
    "sizes" : groups[*].p.size
  }
</code>```

Given your (corrected) example data, the query returns:

```<code>[
  {
    "name": "product1",
    "description": "someDescription",
    "prices": [
      12,
      84,
      106,
      26
    ],
    "sizes": [
      5,
      25,
      35,
      15
    ]
  },
  {
    "name": "product2",
    "description": "someDescription",
    "prices": [
      43,
      32,
      22,
      12
    ],
    "sizes": [
      35,
      25,
      15,
      5
    ]
  }
]
</code>```

The grouped values aren't sorted, but the positions of sizes and prices correspond, you can alleviate this fact to zip the values into a size-price map:

```<code>FOR p IN products
  COLLECT description = p.description, name = p.name INTO groups
  RETURN {
    "name" : name,
    "description": description,
    "size_price_map" : ZIP(groups[*].p.size, groups[*].p.price)
  }
</code>```

yielding:

```<code>[
  {
    "name": "product1",
    "description": "someDescription",
    "size_price_map": {
      "5": 12,
      "15": 26,
      "25": 84,
      "35": 106
    }
  },
  {
    "name": "product2",
    "description": "someDescription",
    "size_price_map": {
      "5": 12,
      "15": 22,
      "25": 32,
      "35": 43
    }
  }
]
</code>```

Title: Arangodb groupby query multiple fields

Body:
I have a database of products in an arangodb collection in which a product has multiple sizes. The issue is that for each size, the same product is repeated. But each product has a common group number. Like this:

{"name": "product1", "description": "someDescription", size: 5,price: 12 groupNumber: 12}
{"name": "product1", "description": "someDescription", size: 15, price: 26, groupNumber: 12}
{"name": "product1", "description": "someDescription", size: 25, price: 84, groupNumber: 12}
{"name": "product1", "description": "someDescription", size: 35, price: 106, groupNumber: 12}

{"name": "product2", "description": "someDescription", size: 5, price: 12, groupNumber: 11}
{"name": "product2", "description": "someDescription", size: 15, price: 22, groupNumber: 11}
{"name": "product2", "description": "someDescription", size: 25, price: 32, groupNumber: 11}
{"name": "product2", "description": "someDescription", size: 35, price: 43, groupNumber: 11}

I have to now display the list of products(in a web page) but each product should appear only once with sizes and prices in an array for each product like this:

product1 someDescription sizes: 5,15,25,35, prices: 12,26,84,106
product2 someDescription sizes: 5,15,25,35, prices: 12,22,32,43
...

How do I do it?

Body:
Ignoring the groupNumber and grouping by name, the query looks like this:

FOR p IN products
  COLLECT description = p.description, name = p.name INTO groups
  RETURN {
    "name" : name,
    "description": description,
    "prices" : groups[*].p.price,
    "sizes" : groups[*].p.size
  }

Given your (corrected) example data, the query returns:

[
  {
    "name": "product1",
    "description": "someDescription",
    "prices": [
      12,
      84,
      106,
      26
    ],
    "sizes": [
      5,
      25,
      35,
      15
    ]
  },
  {
    "name": "product2",
    "description": "someDescription",
    "prices": [
      43,
      32,
      22,
      12
    ],
    "sizes": [
      35,
      25,
      15,
      5
    ]
  }
]

The grouped values aren't sorted, but the positions of sizes and prices correspond, you can alleviate this fact to zip the values into a size-price map:

FOR p IN products
  COLLECT description = p.description, name = p.name INTO groups
  RETURN {
    "name" : name,
    "description": description,
    "size_price_map" : ZIP(groups[*].p.size, groups[*].p.price)
  }

yielding:

[
  {
    "name": "product1",
    "description": "someDescription",
    "size_price_map": {
      "5": 12,
      "15": 26,
      "25": 84,
      "35": 106
    }
  },
  {
    "name": "product2",
    "description": "someDescription",
    "size_price_map": {
      "5": 12,
      "15": 22,
      "25": 32,
      "35": 43
    }
  }
]


问:
JMS Session and commit
I am new JMS arena, I have created multiple message listeners but one listener per thread. I have following message listener, This message listner is passed a session object while it is constructed. Then when the message is received then this message listener processes message then commits the session as shown in the code. Closing sessions/connections is done in shutdown hook.

    public class MyMessageListener implements MessageListener, ExceptionListener {
        private Session _session = null;

        public MyMessageListener(Session s) {
            _session = s;
        }

        @Override
        public void onMessage(Message arg0) {
            try {

                // Retrieve the data
                JMSBytesMessage bytesMessage = (JMSBytesMessage) arg0;
                byte[] payload = new byte[(int) bytesMessage.getBodyLength()];
                bytesMessage.readBytes(payload);
                String payloadString = new String(payload);
                ProcessMessage(payloadString);
                _session.commit();
                MessageCounter.Increment();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    public abstract void ProcessMessage(String theMessage);

    }
```

Now my worry is that if listener receives two messages at the same time, will there be a chance the session commits both messages?

答:
Everything from Session on down is single-threaded.  No worry about multi-threading.  See How to temporarily disable a message listener (different problem, similar issues).

You do create a separate session for each listener, right?  That's a requirement.  Part of the "everything from Session on down is single-threaded".

Title: JMS Session and commit

Body:
I am new JMS arena, I have created multiple message listeners but one listener per thread. I have following message listener, This message listner is passed a session object while it is constructed. Then when the message is received then this message listener processes message then commits the session as shown in the code. Closing sessions/connections is done in shutdown hook.

    public class MyMessageListener implements MessageListener, ExceptionListener {
        private Session _session = null;

        public MyMessageListener(Session s) {
            _session = s;
        }

        @Override
        public void onMessage(Message arg0) {
            try {

                // Retrieve the data
                JMSBytesMessage bytesMessage = (JMSBytesMessage) arg0;
                byte[] payload = new byte[(int) bytesMessage.getBodyLength()];
                bytesMessage.readBytes(payload);
                String payloadString = new String(payload);
                ProcessMessage(payloadString);
                _session.commit();
                MessageCounter.Increment();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    public abstract void ProcessMessage(String theMessage);

    }

Now my worry is that if listener receives two messages at the same time, will there be a chance the session commits both messages?

ContentLicense: CC BY-SA 3.0


问:
Multiple Instances of same Microservices should not fetch and update same MongoDB Documents
Problem Statement:

There is one Scheduler in our microservice which will fetch 10 Request Documents(having staus "A") and start processing on them and after that update each Document's status.

We are planning to deploy three instances of the same microservice. once all three instances start executing scheduler then each instance will fetch 10 Request Documents and start processing them.

The same request documents should not be fetched and processed in multiple instances. How can I make sure that each instance of microservice picks 10 different documents?

答:
Each of your workers should choose a different set of documents.

For example, if you have an autoincrement numeric id for your documents:

Worker 1 can get all documents where ID % 3 = 0

Worker 2 can get all documents where ID % 3 = 1

Worker 3 can get all documents where ID % 3 = 2

If autoincrement ID is not available, you can take a look at consistent hashing which is very nice to learn.

Hashing is simple:

Compute the hash of the document ID

Use this hash to get which worker should process this document

The problem with this approach is that, say the range of your document ID hash is between 1 and 1000 and you are using the same approach above. You might end up by Worker 1 getting much more work than worker 2.

With Consistent Hashing, you expand the range to get a more balanced.


问:
How to add value from one query to another
I'm using React to send data to my PostgreSQL database using NodeJS. I have a foreign key in my songs table that REFERENCES to the id in my albums table. My question is how can I return (or whatever needs to be done) my id from my first INSERT to the album_id in my second INSERT? Here's my code currently:

```<code>const addData = (request, response) => {
const uuid = uuidv4();

db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *' , [request.body.title, request.body.date, request.body.description, uuid])
    .then(res => {
      console.log('INSERT ' + JSON.stringify(res.rows[0].id));
    }).then(() => {
       for (let i = 0; i < request.body.files.length; i++) {
        db.pool.query('INSERT INTO songs (id, name, link, index) VALUES ($1, $2, $3, $4) ON CONFLICT (album_id, index) DO NOTHING RETURNING *', [uuidv4(), request.body.files[i].name, request.body.files[i].link, request.body.files[i].index])
       }
    }).then(res => {
        console.log('INSERT INTO songs ' + JSON.stringify(res));
    }).catch(error => console.log(error));

}
</code>```

I haven't added album_id yet to my songs INSERT. I'm waiting to see how I can get the value from id of albums into my second INSERT?

答:
As I can not see the album_id column in songs table so I am not writing the query for that.

You just need to pass that last inserted id to the next using then(album_id)

```<code>const addData = (request, response) => {
const uuid = uuidv4();

db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *' , [request.body.title, request.body.date, request.body.description, uuid])
    .then(res => {
      let album_id = res.rows[0].id;
      console.log('INSERT ' + JSON.stringify(res.rows[0].id));
    }).then((album_id) => {
       console.log("album_id " + album_id);
       // here you will get the album id and now you can use it as per required.
        .....
        .....
      //
    }).then(res => {
      console.log('INSERT INTO songs ' + JSON.stringify(res));
    }).catch(error => console.log(error));

}
</code>```

Body:
I'm using React to send data to my PostgreSQL database using NodeJS. I have a foreign key in my songs table that REFERENCES to the id in my albums table. My question is how can I return (or whatever needs to be done) my id from my first INSERT to the album_id in my second INSERT? Here's my code currently:

const addData = (request, response) => {
const uuid = uuidv4();

db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *' , [request.body.title, request.body.date, request.body.description, uuid])
    .then(res => {
      console.log('INSERT ' + JSON.stringify(res.rows[0].id));
    }).then(() => {
       for (let i = 0; i < request.body.files.length; i++) {
        db.pool.query('INSERT INTO songs (id, name, link, index) VALUES ($1, $2, $3, $4) ON CONFLICT (album_id, index) DO NOTHING RETURNING *', [uuidv4(), request.body.files[i].name, request.body.files[i].link, request.body.files[i].index])
       }
    }).then(res => {
        console.log('INSERT INTO songs ' + JSON.stringify(res));
    }).catch(error => console.log(error));

}

I haven't added album_id yet to my songs INSERT. I'm waiting to see how I can get the value from id of albums into my second INSERT?

Body:
As I can not see the album_id column in songs table so I am not writing the query for that.

You just need to pass that last inserted id to the next using then(album_id)

const addData = (request, response) => {
const uuid = uuidv4();

db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *' , [request.body.title, request.body.date, request.body.description, uuid])
    .then(res => {
      let album_id = res.rows[0].id;
      console.log('INSERT ' + JSON.stringify(res.rows[0].id));
    }).then((album_id) => {
       console.log("album_id " + album_id);
       // here you will get the album id and now you can use it as per required.
        .....
        .....
      //
    }).then(res => {
      console.log('INSERT INTO songs ' + JSON.stringify(res));
    }).catch(error => console.log(error));

}


问:
ActiveReports 10 SectionReport Byval Variable
In the past with AR2 i'd wrote code like this

```<code>        Dim rpt_Test As New My_Report(_dsDati)
        rpt_Test.LoadLayout(_ReportName)
        rpt_Test.DataSource = _dv
        rpt_Test.Run()
        Me.Active_Rpt_Viewer.Document = rpt_Test.Document
</code>```

My_Report was a rpx file and it could accept a dataset like parameter

Now with AR10 (i'm newbie) how can i pass a dataset to a sectionreport ?
I'd like to use in script the dataset for many reason and i'd like to pass it at run time.
Is it possible ?

答:
I had used sectionreport XML  ...
I must to use sectionreport (code Based)
This was my error</p>

Body:
In the past with AR2 i'd wrote code like this

        Dim rpt_Test As New My_Report(_dsDati)
        rpt_Test.LoadLayout(_ReportName)
        rpt_Test.DataSource = _dv
        rpt_Test.Run()
        Me.Active_Rpt_Viewer.Document = rpt_Test.Document

My_Report was a rpx file and it could accept a dataset like parameter

Now with AR10 (i'm newbie) how can i pass a dataset to a sectionreport ?
I'd like to use in script the dataset for many reason and i'd like to pass it at run time.
Is it possible ?


答:
```<code>dplyr::left_join(db1, db2 %>% dplyr::select(Year, ISSN, IF))

</code>```

This should work providing the two dataframes have no other columns in common besides the ones you've shown here.

Title: How to add a column from one dataframe to another dataframe when two other columns match

Body:
I have two datasets, db1 and db2, like the following ones:

db1
+---------+-------+-------+------+------+-----------------+
|  Authors| IDs   | Title | Year | ISSN | Other columns...|
+---------+-------+-------+------+------+-----------------+
|  Abad J.| 16400 |   1   | 2014 |14589 |                 |
|  Ares K.| 70058 |   2   | 2012 |15874 |                 |
|  Anto E.| 71030 |   3   | 2011 |16999 |                 |
|  A Banul| 57196 |   1   | 2011 |21546 |                 |
|  A Berat| 56372 |   2   | 2011 |12554 |                 |
+---------+-------+-------+------+------+-----------------+

and

db2
+---------+-------+-------+------+------+-------+---------------------------+
|  Authors| IDs   | Title | Year | ISSN | IF    | Other different columns...|
+---------+-------+-------+------+------+-------+---------------------------+
|  Abad J.| 16400 |   1   | 2013 |14589 |  2,3  |                           |
|  Ares K.| 70058 |   2   | 2012 |15874 |  3,3  |                           |
|  Anto E.| 71030 |   3   | 2011 |14587 |  1,2  |                           |
|  A Banul| 57196 |   1   | 2011 |21546 |  7,8  |                           |
|  A Berat| 56372 |   2   | 2011 |75846 |  4,5  |                           |
+---------+-------+-------+------+------+-------+---------------------------+

Basically, what i want is to add to db1 the column IF from db2 when the two columns Year and ISSN have the same values. So what i want to achive is the following output in my example:

db1
+---------+-------+-------+------+------+-------+----------------+
|  Authors| IDs   | Title | Year | ISSN | IF    |Other columns...|
+---------+-------+-------+------+------+-------+----------------+
|  Abad J.| 16400 |   1   | 2014 |14589 |  NA   |                |
|  Ares K.| 70058 |   2   | 2012 |15874 |  3,3  |                |
|  Anto E.| 71030 |   3   | 2011 |16999 |  NA   |                |
|  A Banul| 57196 |   1   | 2011 |21546 |  7,8  |                |
|  A Berat| 56372 |   2   | 2011 |12554 |  NA   |                |
+---------+-------+-------+------+------+-------+----------------+

i have tried with merge but, since i have also different columns, i obtain a very big dataset.

What i want is to use the function match but with more than one condition applied at the same time.

Any guess ?

Body:
dplyr::left_join(db1, db2 %>% dplyr::select(Year, ISSN, IF))

This should work providing the two dataframes have no other columns in common besides the ones you've shown here.


问:
How to configure JDBC for Cloud Fusion to connect MySQL installed on localhost:3306
I'm trying to connect my local standalone MySQL with Cloud Fusion to create and test a data pipeline. I have deployed the driver successfully.
Also, I have configured the pipeline properties with correct values of jdbc string, user name and password but connectivity isn't getting established.

Connection String: jdbc:mysql://localhost:3306/test_database

I have also tried to test the connectivity via data wrangling option but that is also not getting succeeded.

Do I need to bring both the environments under same network by setting up some VPC and tunneling?

答:
I think that your question is more related to the way how to connect some on-premise environments to GCP networking system that gathering Google cloud instances or resources throughout VPC connection model.

Admitting the fact that GCP is actually leveraging different approaches for connection methods within a Hybrid cloud concepts, I would encourage you to learn some fundamental principles of Cloud VPN as a essential part of performing secure connection between particular VPN Peer Gateway and Cloud VPN Gateway and further creating a VPN tunnel between parties.

I guess there is even dedicated chapter in GCP documentation about Data Fusion VPC peering implementation that might be helpful in your user case.


问:
Get the exported environment variable in ansible
I have the env file which is present in target machine and it contain certain number of variables with export command(the export command itself was present inside the file).

```<code>export AB_HOME=/et/dev/abinitio/abinitio-V3
export PATH=${AB_HOME}/bin:${PATH}
</code>```

I have executed the env file using the below playbook and I tried to read the variables which are exported using the output1 which is a register variable in my playbook. But I am able to see my register variable is empty. Is there any way to get the variables which are all exported. I don't know the variables name which are present inside the file, So I am not able to use the ECHO command.

```<code>- hosts: dev
  gather_facts: false
  tasks:
    - name: get the environment variables
      shell: "su <id> & . ./.env"
      args:
        chdir: /path to the file
      register: output1

    - debug: var=output1.stdout_lines
</code>```

答:
stdout for export is not returned, that is why you don't see any output. You may want to check the rc code instead:

```<code>- debug: var=output1.rc
</code>```

To make ansible print the previously exported variables just run export or export -p and print stdout_lines in the same way as before.

```<code>tasks:
    - name: get the environment variables
      shell: "export -p"
      register: output

    - debug: var=output.stdout_lines
</code>```

Body:
I have the env file which is present in target machine and it contain certain number of variables with export command(the export command itself was present inside the file).

export AB_HOME=/et/dev/abinitio/abinitio-V3
export PATH=${AB_HOME}/bin:${PATH}

I have executed the env file using the below playbook and I tried to read the variables which are exported using the output1 which is a register variable in my playbook. But I am able to see my register variable is empty. Is there any way to get the variables which are all exported. I don't know the variables name which are present inside the file, So I am not able to use the ECHO command.

- hosts: dev
  gather_facts: false
  tasks:
    - name: get the environment variables
      shell: "su <id> & . ./.env"
      args:
        chdir: /path to the file
      register: output1

    - debug: var=output1.stdout_lines

Body:
stdout for export is not returned, that is why you don't see any output. You may want to check the rc code instead:

- debug: var=output1.rc

To make ansible print the previously exported variables just run export or export -p and print stdout_lines in the same way as before.

tasks:
    - name: get the environment variables
      shell: "export -p"
      register: output

    - debug: var=output.stdout_lines


问:
Find the first element that satisfies condition X in a Seq
Generally, how to find the first element satisfying certain condition in a Seq?

For example, I have a list of possible date format, and I want to find the parsed result of first one format can parse my date string.

```<code>val str = "1903 January"
val formats = List("MMM yyyy", "yyyy MMM", "MM yyyy", "MM, yyyy")
  .map(new SimpleDateFormat(_))
formats.flatMap(f => {try {
  Some(f.parse(str))
}catch {
  case e: Throwable => None
}}).head
</code>```

Not bad. But 1. it's a little ugly. 2. it did some unnecessary work(tried "MM yyyy" and "MM, yyyy" formats). Perhaps there is more elegant and idiomatic way? (using Iterator?)

答:
Using org.joda.time:

Definition:

```<code>def getBaseLocalFromFormats[T <: BaseLocal](
                        value: String,
                        validPatterns: Seq[String],
                        parse: (String, String)  => T) : Option[T] = {
    validPatterns.view.map(p => Try{ parse(value, p) }).find(_.isSuccess).map(_.get)
  }
</code>```

Usage:

```<code>getBaseLocalFromFormats(
                "01/10/1980 16:08:22",
                List("dd/MM/yyyy HH:mm:ss"),
                (v,p) => DateTimeFormat.forPattern(p).parseLocalDateTime(v))
</code>```

```<code>getBaseLocalFromFormats(
                "01/10/1980",
                List("dd/MM/yyyy",  "dd-MM-yyyy", "yyyy-MM-dd"),
                (v,p) => DateTimeFormat.forPattern(p).parseLocalDate(v))
</code>```

Body:
Generally, how to find the first element satisfying certain condition in a Seq?

For example, I have a list of possible date format, and I want to find the parsed result of first one format can parse my date string.

val str = "1903 January"
val formats = List("MMM yyyy", "yyyy MMM", "MM yyyy", "MM, yyyy")
  .map(new SimpleDateFormat(_))
formats.flatMap(f => {try {
  Some(f.parse(str))
}catch {
  case e: Throwable => None
}}).head

Not bad. But 1. it's a little ugly. 2. it did some unnecessary work(tried "MM yyyy" and "MM, yyyy" formats). Perhaps there is more elegant and idiomatic way? (using Iterator?)

Body:
Using org.joda.time:

Definition:

def getBaseLocalFromFormats[T <: BaseLocal](
                        value: String,
                        validPatterns: Seq[String],
                        parse: (String, String)  => T) : Option[T] = {
    validPatterns.view.map(p => Try{ parse(value, p) }).find(_.isSuccess).map(_.get)
  }

Usage:

getBaseLocalFromFormats(
                "01/10/1980 16:08:22",
                List("dd/MM/yyyy HH:mm:ss"),
                (v,p) => DateTimeFormat.forPattern(p).parseLocalDateTime(v))

getBaseLocalFromFormats(
                "01/10/1980",
                List("dd/MM/yyyy",  "dd-MM-yyyy", "yyyy-MM-dd"),
                (v,p) => DateTimeFormat.forPattern(p).parseLocalDate(v))


答:
The following aggregation does that. Assuming that the Time field of type Date.

```<code>db.test.aggregate( [
  {
      $group: {
          _id: { day: { $dayOfMonth: "$Time" } },
          data:{ $push: { k: "$No", v: "$Detail" } }
      }
  },
  {
      $sort: { "_id.day": 1 }
  },
  {
      $addFields: {
          data: { $arrayToObject: "$data" },
          day: "$_id.day"
      }
  },
  {
      $group: {
          _id: null,
          data: { $push: { k: { $toString: "$_id.day" }, v: "$data" } }
      }
  },
  {
      $project: {
           _id: 0,
           data: { $arrayToObject: "$data" }
      }
  },
  {
      $replaceRoot: { newRoot: "$data" }
  }
] ).pretty()
</code>```

Title: How do I sort data by date (json)

Body:
I want to sort json data by date , Actual data hava 1 ~ 31
example data:

{
  Detail: { '60': 100, '68': 20 },
  Time: 2020-01-02T07:08:41.059Z,
  No: 'aaa'
},
{
  Detail: { '60': 300, '68': 20 },
  Time: 2020-01-02T09:10:21.059Z,
  No: 'bbb'
},
{
  Detail: { '60': 10 },
  Time: 2020-01-11T07:08:45.521Z,
  No: 'ccc'
}

How do I sort by Date like this :

{
  "2":{
     "aaa": { '60': 100, '68': 20 }
     "bbb": { '60': 300, '68': 20 }
   }
  "11":{
     "ccc": { '60': 100 },
   }
}

Thanks

Body:
The following aggregation does that. Assuming that the Time field of type Date.

db.test.aggregate( [
  {
      $group: {
          _id: { day: { $dayOfMonth: "$Time" } },
          data:{ $push: { k: "$No", v: "$Detail" } }
      }
  },
  {
      $sort: { "_id.day": 1 }
  },
  {
      $addFields: {
          data: { $arrayToObject: "$data" },
          day: "$_id.day"
      }
  },
  {
      $group: {
          _id: null,
          data: { $push: { k: { $toString: "$_id.day" }, v: "$data" } }
      }
  },
  {
      $project: {
           _id: 0,
           data: { $arrayToObject: "$data" }
      }
  },
  {
      $replaceRoot: { newRoot: "$data" }
  }
] ).pretty()


问:
how to increase java heap memory permanently?
I have one problem with java heap memory. I developed one client server application in java which is run as a windows service it requires more than 512MB of memory. I have 2GB of RAM but when I run my application it throws an exception

Out of memory error:java heap space

but I have already set heap size (maximum  512MB) in the java control panel and I still get the same error. I can't set heap size through the command line because my application runs as a windows service so how can I increase the default heap size?

答:
You also use this below to expand the memory

export _JAVA_OPTIONS="-Xms512m -Xmx1024m  -Xss512m -XX:MaxPermSize=1024m"

Xmx specifies the maximum memory allocation pool for a Java virtual machine (JVM)

Xms specifies the initial memory allocation pool.

Xss setting memory size of thread stack

XX:MaxPermSize: the maximum permanent generation size


问:
TortoiseSVN switching branch - some files stay on previous branch
When using TortoiseSVN on Windows to switch branch, occasionally some files and/or folders will remain on the previous branch.  There seems to be no consistent pattern to this.  It doesn't happen every time, and it doesn't happen to the same files.  So usually you only find out about it when there's a problem due to the old file no longer working in conjuction with the new files.

So I'd like either of two things:

A way to consistently switch branch that prevents this happening again

If that's not possible, some way of listing the entire contents of a directory along with which branch each file and folder is in.

答:
That's expected behavior according to Tortoise's docs:

Switch works just like Update in that
  it never discards your local changes.
  Any changes you have made to your
  working copy which have not yet been
  committed will be merged when you do
  the Switch. If you do not want this to
  happen then you must either commit the
  changes before switching, or revert
  your working copy to an
  already-committed revision (typically
  HEAD).


问:
What happens with ActiveMQ unacknowledged messages
If there's a queue created in ActiveMQ which has one producer (which is client acknowledged mode) and one listener in whose onMessage method after successful processing of message only it is acknowledged. Say if there is an exception and the message remains unacknowledged and hence remains in the queue. Will it be sent again to consumer? Or what happens to such messages?</p>

答:
When the message is not processed by the consumer due to some exception, then it's good to send negative acknowledgement. For example NACK with STOMP protocol. The message then remains in the queue. ActiveMQ can be configured to make redelivery attempts up on receiving NACK from consumer.

https://stomp.github.io/stomp-specification-1.2.html#NACK


问:
Add icon (e.g. material design or Prime Icons) to a p:inputText
I want to add an icon for an input text element, in a JavaEE project:

```<code><h:panelGroup styleClass="md-inputfield">
    <p:inputText id="name"
                 value="#{createCustomerView.customer.name}" required="true"
                 label="Nome" requiredMessage="inserisci il nome">
        <f:validateLength minimum="2" />
    </p:inputText>
    <p:outputLabel for="name" value="Nome" />
    <p:message for="name" display="icon" />
</h:panelGroup>
</code>```

How Can add an icon, like a person icon?

答:
Please note that the input group is not a component, but a set of CSS rules. Those rules where added in PrimeFaces 7. If you are using an older version of PrimeFaces, it's  a good idea to upgrade for many other reasons, but if you really cannot, you can always add the CSS rules to your own project as custom styles.

Alternatively, you should remember that JSF / PrimeFaces will simply render HTML. So you can always resort to a solution using CSS, as can be found at: Put icon inside input element in a form.

See also:

How do I override default PrimeFaces CSS with custom styles?

Body:
I want to add an icon for an input text element, in a JavaEE project:

<h:panelGroup styleClass="md-inputfield">

        <f:validateLength minimum="2" />

</h:panelGroup>

How Can add an icon, like a person icon?


问:
How to make selenium open https page, which displayed manually and not displayed while automated run?
Browsing with chrome to web site with htpps connection manually is available and display the site.
Browsing same site by selenium automated test, doesn't display the page, display empty page.
If i load chrome user profile, automation do open the required page.
Other https site (QA) does displayed through automated connection, the problem is with production sites.
Is there any setting can be added to selenium to open the page?</p>

答:
After the issue solved, posting here the solution.
The site wasn't displayed because automation requests were blocked by company WAF (firewall).
The solution on the automation side was to add agent into chrome profile options and on the waf side rule was added for the agent that allows access to the application.

This is example of how the agent added into ChromeOptions class:

```<code>ChromeOptions options = new ChromeOptions();
options.AddArgument("--user-agent=automation-client");
</code>```

Body:
After the issue solved, posting here the solution.
The site wasn't displayed because automation requests were blocked by company WAF (firewall).
The solution on the automation side was to add agent into chrome profile options and on the waf side rule was added for the agent that allows access to the application.

This is example of how the agent added into ChromeOptions class:

ChromeOptions options = new ChromeOptions();
options.AddArgument("--user-agent=automation-client");


问:
Padding printed output of tabular data
I know this is probably dead simple, but I've got some data such as this in one file:

Artichoke

Green Globe, Imperial Star, Violetto

24" deep

Beans, Lima

Bush Baby, Bush Lima, Fordhook, Fordhook 242

12" wide x 8-10" deep
```

<p>that I'd like to be able to format into a nice TSV type of table, to look something like this:</p>

<pre class="lang-none prettyprint-override"><code>    Name  | Varieties    | Container Data
----------|------------- |-------
some data here nicely padded with even spacing and right aligned text
</code>```

答:
Try String#rjust(width):

```
"hello".rjust(20)           #=> "               hello"
```

OwnerDisplayName: The Pied Pipes

Title: Padding printed output of tabular data

Body:
I know this is probably dead simple, but I've got some data such as this in one file:

Artichoke

Green Globe, Imperial Star, Violetto

24" deep

Beans, Lima

Bush Baby, Bush Lima, Fordhook, Fordhook 242

12" wide x 8-10" deep

that I'd like to be able to format into a nice TSV type of table, to look something like this:

    Name  | Varieties    | Container Data
----------|------------- |-------
some data here nicely padded with even spacing and right aligned text

Body:
Try String#rjust(width):

"hello".rjust(20)           #=> "               hello"

OwnerDisplayName: MarkusQ


问:
Elevated privileges in javascript
In SharePoint, when I need to execute an action when the user doesn't have privileges to do so, I use:

```<code>SPSecurity.RunWithElevatedPrivileges(delegate()
 {
// DO SOMETHING WITH PRIVILEGES
});
</code>```

But now I need to execute JavaScript with elevated privileges:

```<code>var context = new SP.ClientContext.get_current();
context.executeQueryAsync(); // NEED PRIVILEGES TO WORK
</code>```

Is this possible?

答: Agreed that you can't do this from JavaScript and it would be foolish if you could.  One scenario that could help you is to look into Designer no-code workflows.  New in SP2010 is the ability to have chunks of the workflow execute as the person who designed the workflow rather than the person who has started the workflow instance.  This could be used to get around your permissions problem.</p>

Title: Elevated privileges in javascript

Body:
In SharePoint, when I need to execute an action when the user doesn't have privileges to do so, I use:

SPSecurity.RunWithElevatedPrivileges(delegate()
 {
// DO SOMETHING WITH PRIVILEGES
});

But now I need to execute JavaScript with elevated privileges:

var context = new SP.ClientContext.get_current();
context.executeQueryAsync(); // NEED PRIVILEGES TO WORK

Is this possible?


问:
Can't install Docker on Ubuntu 18.04?
I am trying to install Docker on my Ubuntu 18.04.4 LTS (GNU/Linux 5.3.0-40-generic x86_64)

Following the instructions, I am doing the following and getting an error, please advise how to solve it:

```<code>sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 11, in <module>
    from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 67, in <module>
    from gi.repository import Gio
  File "/usr/lib/python3/dist-packages/gi/__init__.py", line 42, in <module>
    from . import _gi
ImportError: cannot import name '_gi' from 'gi' (/usr/lib/python3/dist-packages/gi/__init__.py)
</code>```

答:
While trying to install docker on my Ubuntu 18.04.4 EC2 I have encountered with the following error when trying Docker Install Guide
4th step:

```<code>sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
</code>```

I have got errors like:

```<code>Traceback (most recent call last):
  File "/usr/bin/update-manager", line 28, in <module>
    from gi.repository import Gtk
  File "/usr/lib/python3/dist-packages/gi/__init__.py", line 27, in <module> from ._gi import _API
ImportError: No module named 'gi._gi'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 64, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 20, in <module>
import apt
File "/usr/lib/python3/dist-packages/apt/__init__.py", line 21, in <module>
import apt_pkg
ImportError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
File "/usr/bin/update-manager", line 28, in <module>
from gi.repository import Gtk
File "/usr/lib/python3/dist-packages/gi/__init__.py", line 27, in <module>
from ._gi import _API
ImportError: No module named 'gi._gi'
</code>```

I have solved it with the following copy .io files:

For apt_pkg:

```<code>cd /usr/lib/python3/dist-packages
sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so
Basically, if you get a No such file or directory just ls to try to get the right name.
</code>```

For gi:

```<code>sudo cp _gi.cpython-36m-x86_64-linux-gnu.so _gi.cpython-37m-x86_64-linux-gnu.so

sudo cp _gi_cairo.cpython-36m-x86_64-linux-gnu.so _gi_cairo.cpython-37m-x86_64-linux-gnu.so
</code>```

And everything started to work.

Title: Can't install Docker on Ubuntu 18.04?

Body:
I am trying to install Docker on my Ubuntu 18.04.4 LTS (GNU/Linux 5.3.0-40-generic x86_64)

Following the instructions, I am doing the following and getting an error, please advise how to solve it:

sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 11, in <module>
    from softwareproperties.SoftwareProperties import SoftwareProperties, shortcut_handler
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 67, in <module>
    from gi.repository import Gio
  File "/usr/lib/python3/dist-packages/gi/__init__.py", line 42, in <module>
    from . import _gi
ImportError: cannot import name '_gi' from 'gi' (/usr/lib/python3/dist-packages/gi/__init__.py)

Body:
While trying to install docker on my Ubuntu 18.04.4 EC2 I have encountered with the following error when trying Docker Install Guide
4th step:

sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

I have got errors like:

Traceback (most recent call last):
  File "/usr/bin/update-manager", line 28, in <module>
    from gi.repository import Gtk
  File "/usr/lib/python3/dist-packages/gi/__init__.py", line 27, in <module> from ._gi import _API
ImportError: No module named 'gi._gi'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 64, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 20, in <module>
import apt
File "/usr/lib/python3/dist-packages/apt/__init__.py", line 21, in <module>
import apt_pkg
ImportError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
File "/usr/bin/update-manager", line 28, in <module>
from gi.repository import Gtk
File "/usr/lib/python3/dist-packages/gi/__init__.py", line 27, in <module>
from ._gi import _API
ImportError: No module named 'gi._gi'

I have solved it with the following copy .io files:

For apt_pkg:

cd /usr/lib/python3/dist-packages
sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so
Basically, if you get a No such file or directory just ls to try to get the right name.

For gi:

sudo cp _gi.cpython-36m-x86_64-linux-gnu.so _gi.cpython-37m-x86_64-linux-gnu.so

sudo cp _gi_cairo.cpython-36m-x86_64-linux-gnu.so _gi_cairo.cpython-37m-x86_64-linux-gnu.so

And everything started to work.


问:
How can I delete all local Docker images?
I recently started using Docker and never realized that I should use docker-compose down instead of ctrl-c or docker-compose stop to get rid of my experiments. I now have a large number of unneeded docker images locally.

Is there a flag I can run to delete all the local docker images & containers?

Something like docker rmi --all --force --all flag does not exist but I am looking for something with similar idea.

答:
To delete all Docker local Docker images follow 2 steps ::

step 1 : docker images ( list all docker images with ids )

```<code>     example :
     REPOSITORY    TAG    IMAGE ID            CREATED             SIZE
     pradip564/my  latest 31e522c6cfe4        3 months ago        915MB
</code>```

step 2 : docker image rm 31e522c6cfe4 ( IMAGE ID)

```<code>      OUTPUT : image deleted
</code>```

Body:
To delete all Docker local Docker images follow 2 steps ::

step 1 : docker images ( list all docker images with ids )

     example :
     REPOSITORY    TAG    IMAGE ID            CREATED             SIZE
     pradip564/my  latest 31e522c6cfe4        3 months ago        915MB

step 2 : docker image rm 31e522c6cfe4 ( IMAGE ID)

      OUTPUT : image deleted


问:
change expiration auth cookie dynamically .net core identity
I have .NET Core 3.1 Web API app with .NET Core Identity.
In Startup.cs I have the following code:

```<code>services.ConfigureApplicationCookie(options =>
{
    options.ExpireTimeSpan = TimeSpan.FromHours(2);
});
</code>```

But for some users I have different value of expiration time.

Can I overwrite expiration time of auth cookie dynamically? And if yes, what's the best way to do it? Maybe there is an option in SignInManager<...> or UserManager<...> that allow to overwrite this value?

答:
I use this way:</p>

```<code>await this._signInManager.SignInAsync(user, new Microsoft.AspNetCore.Authentication.AuthenticationProperties
{
    ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60)
});
</code>```

Body:
I have .NET Core 3.1 Web API app with .NET Core Identity.
In Startup.cs I have the following code:

services.ConfigureApplicationCookie(options =>
{
    options.ExpireTimeSpan = TimeSpan.FromHours(2);
});

But for some users I have different value of expiration time.

Can I overwrite expiration time of auth cookie dynamically? And if yes, what's the best way to do it? Maybe there is an option in SignInManager<...> or UserManager<...> that allow to overwrite this value?

Body:
I use this way:

await this._signInManager.SignInAsync(user, new Microsoft.AspNetCore.Authentication.AuthenticationProperties
{
    ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60)
});


问:
I have a problem getting my sidebar responsive
I created this sidebar with reactjs and with a certain fixed number of px for each element this caused the sidebar to not be reponsive. Unfortunately I'm not that good at CSS. Can someone help me transform this code to reponsive please ?
thanks in advance :)

code is here

↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

code

答:
Use max-width in your sidebar.css instead of max-height.</p>

```<code>@media screen and (max-width: 600px) {
  .sidenav {
    padding-top: 15px;
    width: 100px;
  }
  .sidenav a {
font-size: 14px;
  }
}
</code>```

Body:
Use max-width in your sidebar.css instead of max-height.

@media screen and (max-width: 600px) {
  .sidenav {
    padding-top: 15px;
    width: 100px;
  }
  .sidenav a {
font-size: 14px;
  }
}


问:
String concatenation in ActiveRecord in Yii Framework?
Is it possible to CONCAT values of two table columns using the Yii's ActiveRecord methods and patterns?

If is, how?

I'm currently using this:

```<code>return $this->findByAttributes(array('alias' => $alias));
</code>```

But in this I need to return the concated string/values.

Please help.

答:
If you are looking for something like that:

```<code>select username||'@'||domain from user_mail_table;
</code>```

to receive concatenated values - so i don't think, that it's possible.
That's not the idea of ActiveRecord.

If you like to concat values like the example above, you should take DAO
http://www.yiiframework.com/doc/guide/1.1/en/database.dao
...or if you need ActiveRecord, you should concat the values inside your application

```<code>$mailaddress=$model->username.'@'.$model->domain;
</code>```

Body:
Is it possible to CONCAT values of two table columns using the Yii's ActiveRecord methods and patterns?

If is, how?

I'm currently using this:

return $this->findByAttributes(array('alias' => $alias));

But in this I need to return the concated string/values.

Please help.

Body:
If you are looking for something like that:

select username||'@'||domain from user_mail_table;

to receive concatenated values - so i don't think, that it's possible.
That's not the idea of ActiveRecord.

If you like to concat values like the example above, you should take DAO
http://www.yiiframework.com/doc/guide/1.1/en/database.dao
...or if you need ActiveRecord, you should concat the values inside your application

$mailaddress=$model->username.'@'.$model->domain;


问:
why couldn't I download images from google with python?
The code helped me download bunch of images from google. It used to work a few days back and now all of the sudden the code breaks.

Code :

```<code># importing google_images_download module
from google_images_download import google_images_download

# creating object
response = google_images_download.googleimagesdownload()

search_queries = ['Apple', 'Orange', 'Grapes', 'water melon']

def downloadimages(query):
    # keywords is the search query
    # format is the image file format
    # limit is the number of images to be downloaded
    # print urs is to print the image file url
    # size is the image size which can
    # be specified manually ("large, medium, icon")
    # aspect ratio denotes the height width ratio
    # of images to download. ("tall, square, wide, panoramic")
    arguments = {"keywords": query,
                 "format": "jpg",
                 "limit":4,
                 "print_urls":True,
                 "size": "medium",
                 "aspect_ratio": "panoramic"}
    try:
        response.download(arguments)

    # Handling File NotFound Error
    except FileNotFoundError:
        arguments = {"keywords": query,
                     "format": "jpg",
                     "limit":4,
                     "print_urls":True,
                     "size": "medium"}

        # Providing arguments for the searched query
        try:
            # Downloading the photos based
            # on the given arguments
            response.download(arguments)
        except:
            pass

# Driver Code
for query in search_queries:
    downloadimages(query)
    print()
</code>```

Output log:

Item no.: 1 --> Item name = Apple Evaluating... Starting Download...

Unfortunately all 4 could not be downloaded because some images were
  not downloadable. 0 is all we got for this search filter!

Errors: 0

Item no.: 1 --> Item name = Orange Evaluating... Starting Download...

Unfortunately all 4 could not be downloaded because some images were
  not downloadable. 0 is all we got for this search filter!

Errors: 0

Item no.: 1 --> Item name = Grapes Evaluating... Starting Download...

Unfortunately all 4 could not be downloaded because some images were
  not downloadable. 0 is all we got for this search filter!

Errors: 0

Item no.: 1 --> Item name = water melon Evaluating... Starting
  Download...

Unfortunately all 4 could not be downloaded because some images were
  not downloadable. 0 is all we got for this search filter!

Errors: 0

This actually create a folder but no images in it.

答:
I think Google is changing the DOM. The element class="rg_meta notranslate" is no longer exist. It is changed to class="rg_i ..." </p>

```<code>
def get_soup(url,header):
    return BeautifulSoup(urllib2.urlopen(urllib2.Request(url,headers=header)),'html.parser')

def main(args):
    query = "typical face"
    query = query.split()
    query = '+'.join(query)
    url = "https://www.google.co.in/search?q="+query+"&source=lnms&tbm=isch"
    headers = {}
    headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
    soup = get_soup(url, headers)
    for a in soup.find_all("img", {"class": "rg_i"}):
        wget.download(a.attrs["data-iurl"], a.attrs["data-iid"])

if __name__ == '__main__':
    from sys import argv
    try:
        main(argv)
    except KeyboardInterrupt:
        pass
    sys.exit()
</code>```

Body:
The code helped me download bunch of images from google. It used to work a few days back and now all of the sudden the code breaks.

Code :

# importing google_images_download module
from google_images_download import google_images_download

# creating object
response = google_images_download.googleimagesdownload()

search_queries = ['Apple', 'Orange', 'Grapes', 'water melon']

def downloadimages(query):
    # keywords is the search query
    # format is the image file format
    # limit is the number of images to be downloaded
    # print urs is to print the image file url
    # size is the image size which can
    # be specified manually ("large, medium, icon")
    # aspect ratio denotes the height width ratio
    # of images to download. ("tall, square, wide, panoramic")
    arguments = {"keywords": query,
                 "format": "jpg",
                 "limit":4,
                 "print_urls":True,
                 "size": "medium",
                 "aspect_ratio": "panoramic"}
    try:
        response.download(arguments)

    # Handling File NotFound Error
    except FileNotFoundError:
        arguments = {"keywords": query,
                     "format": "jpg",
                     "limit":4,
                     "print_urls":True,
                     "size": "medium"}

        # Providing arguments for the searched query
        try:
            # Downloading the photos based
            # on the given arguments
            response.download(arguments)
        except:
            pass

# Driver Code
for query in search_queries:
    downloadimages(query)
    print()

Output log:

Item no.: 1 --> Item name = Apple Evaluating... Starting Download...

Unfortunately all 4 could not be downloaded because some images were
  not downloadable. 0 is all we got for this search filter!

Errors: 0

Item no.: 1 --> Item name = Orange Evaluating... Starting Download...

Unfortunately all 4 could not be downloaded because some images were
  not downloadable. 0 is all we got for this search filter!

Errors: 0

Item no.: 1 --> Item name = Grapes Evaluating... Starting Download...

Unfortunately all 4 could not be downloaded because some images were
  not downloadable. 0 is all we got for this search filter!

Errors: 0

Item no.: 1 --> Item name = water melon Evaluating... Starting
  Download...

Unfortunately all 4 could not be downloaded because some images were
  not downloadable. 0 is all we got for this search filter!

Errors: 0

This actually create a folder but no images in it.

Body:
I think Google is changing the DOM. The element class="rg_meta notranslate" is no longer exist. It is changed to class="rg_i ..."

def get_soup(url,header):
    return BeautifulSoup(urllib2.urlopen(urllib2.Request(url,headers=header)),'html.parser')

def main(args):
    query = "typical face"
    query = query.split()
    query = '+'.join(query)
    url = "https://www.google.co.in/search?q="+query+"&source=lnms&tbm=isch"
    headers = {}
    headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
    soup = get_soup(url, headers)
    for a in soup.find_all("img", {"class": "rg_i"}):
        wget.download(a.attrs["data-iurl"], a.attrs["data-iid"])

if __name__ == '__main__':
    from sys import argv
    try:
        main(argv)
    except KeyboardInterrupt:
        pass
    sys.exit()


问:
Measure user activity time on webpage
For newrelic custom monitoring, Measuring time(in sec) user spends on a page to record time in and time out. I have the timestamp when user session is created or visits the page, however need to identify time of session end solely using javascript.

Code Tried

```<code>window.onbeforeunload = function(event) {
    doSomething();
    //event.returnValue = "Is this working";
    };

    function doSomething(){
            //const t = new Date();
            //const ctime = t.getTime();
            //Test
            newrelic.setCustomAttribute('ctime', "sal");
            }
</code>```

答:
You can go for polling, where periodical poll can get you the status of active or lost session, and hence you can capture the timestamp for the same.

Also using unload method of javascript for doing an ajax call can help you as follows:

```<code>$(window).unload(function() {
  var end = new Date();
  $.ajax({
    url: "log.php",
    data: {'timeSpent': end - start},
    async: false
  })
</code>```

});

Title: Measure user activity time on webpage

Body:
For newrelic custom monitoring, Measuring time(in sec) user spends on a page to record time in and time out. I have the timestamp when user session is created or visits the page, however need to identify time of session end solely using javascript.

Code Tried

window.onbeforeunload = function(event) {
    doSomething();
    //event.returnValue = "Is this working";
    };

    function doSomething(){
            //const t = new Date();
            //const ctime = t.getTime();
            //Test
            newrelic.setCustomAttribute('ctime', "sal");
            }

Body:
You can go for polling, where periodical poll can get you the status of active or lost session, and hence you can capture the timestamp for the same.

Also using unload method of javascript for doing an ajax call can help you as follows:

$(window).unload(function() {
  var end = new Date();
  $.ajax({
    url: "log.php",
    data: {'timeSpent': end - start},
    async: false
  })

});


问:
How to include inline images in e-mail signature when sent out with python?
How can I send a python e-mail with inline images for the signature? Currently, I use a link to display the images like this:

```<code><img border="0" src="https://website.com/logo.png" role="presentation" alt="logo mail icon" style="max-width: 300px; width: 300px; display: block;">
</code>```

But in Outlook the images are not loaded and the user needs to click on "display images" which ruins the e-mail, since I use it for business purposes (it is a confirmation link for a registration). Is there a way how to display the images inline and send them with the e-mail instead of a link?

My code so far:

```<code>from email.message import EmailMessage
import smtplib, ssl
import email.utils
import html2text

with open(html_template, 'r') as f:
        html_string = f.read()

plain_text = html2text.html2text(html_string)

msg               = EmailMessage()
msg['Subject']    = subject
msg['From']       = mail_address
msg['To']         = email_receiver
msg['Date']       = email.utils.formatdate()
msg.add_header('Content-Type','text/html')
msg.add_header('Content-Disposition', 'attachment', filename=file_attachment)
msg.set_content(plain_text)
msg.add_alternative(html_string.format(name=surname), subtype='html')

files = [file_attachment]
for file in files:
    with open(file, 'rb') as f:
        file_data = f.read()
        file_name = f.name
    msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

with smtplib.SMTP(smtp, port) as smtp:
    smtp.ehlo()
    smtp.starttls(context=ssl.create_default_context())
    smtp.ehlo()
    smtp.login(mail_address, mail_password)

try:
    smtp.send_message(msg)
    smtp.quit()

except Exception as e:
    print('ERROR')

</code>```

I couldn't find much approaches or solutions. I've read about encoding the images into base64 but I am a bit confused.

Thanks in advance!

答:
To display images inline, you have to provide the image data in the email itself. You can do so by using a base64 encoded string of your image data. Here an example:

<img alt="Website" width="16" height="16" style="border:none;" src="data:image/png;filename=web.png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAABsAAAAbAFcG/0uAAABPElEQVQ4jaVT3U3DMBD+mgUSJqAbNEyQbkDYgL43Ejz7pUjkPZIHoBvUjNAJcDcoG7QTBH3mMzoikEC1dPL5/r+782wcR9jTdv09AFKD72cPYBu821rpV4C26+cAAoCF0Z91l0Z2oHnw7shHYZwjAN6PcnySLIo/S5ds5fMZQJlL0YNuOlaiONGV8sHsdv1MvC8AbhR9AHCNn8+7grD8NwCrQg17Dd7F4F1QRpZ8JbwH8ZRVtKEtfehbqNvB5EvlB+9OABKJP06aSZ+GEEZlOUnRmHctWe7HQuNEfhe/YP3zyQGG4N2SpPdGfBScpZoLYzfkMbKkdrI8ddv1eYSV+LlZLMhnPx0jMW/+M8a0ym3Xs9S8wjRigDsFS5AA7IwurXTwrs49YDksj0RsCUYeo3irIyXYF3+my74zgA9tApBUsNxB3wAAAABJRU5ErkJggg==" />```
</div>
</div>
</p>

<p>You can use online converters to get your base64 string or build it directly in your python script:</p>

<pre class="lang-py prettyprint-override"><code>import base64
encoded_string = base64.b64encode(open("image.png", "rb").read())
</code>```

Keep in mind, that inline images can also be blocked by the receivers mail client, so always provide proper alt descriptions.

Body:
How can I send a python e-mail with inline images for the signature? Currently, I use a link to display the images like this:

But in Outlook the images are not loaded and the user needs to click on "display images" which ruins the e-mail, since I use it for business purposes (it is a confirmation link for a registration). Is there a way how to display the images inline and send them with the e-mail instead of a link?

My code so far:

from email.message import EmailMessage
import smtplib, ssl
import email.utils
import html2text

with open(html_template, 'r') as f:
        html_string = f.read()

plain_text = html2text.html2text(html_string)

msg               = EmailMessage()
msg['Subject']    = subject
msg['From']       = mail_address
msg['To']         = email_receiver
msg['Date']       = email.utils.formatdate()
msg.add_header('Content-Type','text/html')
msg.add_header('Content-Disposition', 'attachment', filename=file_attachment)
msg.set_content(plain_text)
msg.add_alternative(html_string.format(name=surname), subtype='html')

files = [file_attachment]
for file in files:
    with open(file, 'rb') as f:
        file_data = f.read()
        file_name = f.name
    msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

with smtplib.SMTP(smtp, port) as smtp:
    smtp.ehlo()
    smtp.starttls(context=ssl.create_default_context())
    smtp.ehlo()
    smtp.login(mail_address, mail_password)

try:
    smtp.send_message(msg)
    smtp.quit()

except Exception as e:
    print('ERROR')

I couldn't find much approaches or solutions. I've read about encoding the images into base64 but I am a bit confused.

Thanks in advance!

Body:
To display images inline, you have to provide the image data in the email itself. You can do so by using a base64 encoded string of your image data. Here an example:

<img alt="Website" width="16" height="16" style="border:none;" src="data:image/png;filename=web.png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAABsAAAAbAFcG/0uAAABPElEQVQ4jaVT3U3DMBD+mgUSJqAbNEyQbkDYgL43Ejz7pUjkPZIHoBvUjNAJcDcoG7QTBH3mMzoikEC1dPL5/r+782wcR9jTdv09AFKD72cPYBu821rpV4C26+cAAoCF0Z91l0Z2oHnw7shHYZwjAN6PcnySLIo/S5ds5fMZQJlL0YNuOlaiONGV8sHsdv1MvC8AbhR9AHCNn8+7grD8NwCrQg17Dd7F4F1QRpZ8JbwH8ZRVtKEtfehbqNvB5EvlB+9OABKJP06aSZ+GEEZlOUnRmHctWe7HQuNEfhe/YP3zyQGG4N2SpPdGfBScpZoLYzfkMbKkdrI8ddv1eYSV+LlZLMhnPx0jMW/+M8a0ym3Xs9S8wjRigDsFS5AA7IwurXTwrs49YDksj0RsCUYeo3irIyXYF3+my74zgA9tApBUsNxB3wAAAABJRU5ErkJggg==" />

You can use online converters to get your base64 string or build it directly in your python script:

import base64
encoded_string = base64.b64encode(open("image.png", "rb").read())

Keep in mind, that inline images can also be blocked by the receivers mail client, so always provide proper alt descriptions.


问:
ModuleNotFoundError: No module named 'projeler_ile_python'
i did everythin but still i got ModuleNotFoundError: No module error.

答:
I think you r importing something which is not installed. you can install it using pip install projeler_ile_python. If you install it properly then it will work fine.
or create __init__.py file inside projeler_ile_python folder because if there is not any __init__.py file that folder is simple folder not a package.


问:
Javascript hide the scroll after clicking and reach the top of the page
I'm using this in my website:
http://www.dynamicdrive.com/dynamicindex3/scrolltop.htm

and it works great for me. But the only thing that I face is that when I click on the picture, it's opacity become 0 but there is still a link in the same place of the picture. I want to hide the link as well!
I have tried display none for the css in the js file but reached nothing!

答:
```<code>$(window).scroll(function(){
    var top = $(this).scrollTop();
    if(top < 50){
        $('.handle').fadeOut(100);
    } else{
        $('.handle').fadeIn(100);
    }

});
</code>```

Check this http://jsfiddle.net/EJjvt/1/

Body:
$(window).scroll(function(){
    var top = $(this).scrollTop();
    if(top < 50){
        $('.handle').fadeOut(100);
    } else{
        $('.handle').fadeIn(100);
    }

});

Check this http://jsfiddle.net/EJjvt/1/


问:
Mock Webservice Call out implementation
Recently working test classes in Salesforce started to Fail due to this error

Methods defined as TestMethod do not support Web service callouts
Stack Trace: null

I have reviewed the SF response https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_wsdl2apex_testing.htm

but do not understand where to implement the call out in the test class.

I created a Mock Webserivce class but can not figure out where to call the mock class.

This is the test class that is failing:

```<code>@isTest
public class OppLineItemInventoryTriggerTest {
    static testmethod void testdemo() {
        Account act = new Account(lastName = 'Testing', Billingstreet = '1234 Main', billing_as_shipping__c = True, Business_Unit__c = 'Vaya');
        insert act;
        Product2 prod = TestUtils.createProduct('product1');
        Id RecordTypeIdopp = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Package Lot').getRecordTypeId();
        Opportunity opp = new Opportunity();
        opp.AccountId = act.ID;
        opp.Name = 'Test';
        opp.Status__c = 'Completed';
        opp.Transfer_Type__c = 'Delivery';
        opp.StageName = 'New';
        opp.recordtypeid = RecordTypeIdopp;
        opp.CloseDate = Date.newInstance(2016, 12, 9);
        insert opp;
        Dosage__c dos = new Dosage__c();
        dos.Product__c = prod.ID;
        dos.Unit__c = 'mg';
        dos.Value__c = 5;
        insert dos;
        Product_Lot__c prolo = new Product_Lot__c();
        insert prolo;
        String standardPricebookId = Test.getStandardPricebookId();
        PricebookEntry pdb = new PricebookEntry(Pricebook2Id = standardPricebookId, Product2Id = prod.Id, IsActive = true, UnitPrice = 100);
        insert pdb;
        Opportunity opps = [Select id from Opportunity Limit 1];
        Contact con = new Contact(LastName = 'TestName');
        insert con;
        OpportunityLineItem oli = new OpportunityLineItem(OpportunityId = opps.Id, PricebookEntryId = pdb.Id, Quantity = 10, Shipping_Datetime__c = NULL, TotalPrice = 3000);
        insert oli;
        Inventory__c inv = new Inventory__c();
        inv.Product_ID__c = prod.ID;
        inv.Status__c = 'Completed';
        inv.Opportunity__c = opp.ID;
        inv.Days__c = '30';
        inv.Prescription__c = 'www.google.com';
        inv.Prescription_Line_Item_Id__c = 'test';
        inv.Product_Lot__c = prolo.ID;
        inv.Purchase_Date__c = Date.newInstance(2016, 12, 9);
        insert inv;
        sObject[] sObjectOldList = new sObject[] {};
        sObject[] sObjectNewList = new sObject[] {};
        sObject s11,s12;
        //sObjectOldList.add(oli);
        //sObjectNewList.add(oli);
        OppLineItemInventoryTrigger s1 = new OppLineItemInventoryTrigger(sObjectOldList, sObjectNewList);
        //  s1.execute(sObjectOldList, true);
        s1.execute(sObjectNewList, true);
        s1.executable(s11, s12);
    }
</code>```

I created this mock webservice class

```<code>global class YourHttpCalloutMockImpl implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
        HttpResponse res = new HTTPResponse();
        res.setHeader('Content-Type', 'application/JSON');
        res.setBody('Your body');
        res.setStatusCode(201);
        return res;
    }
}
</code>```

But not sure how to call it in the test class.

答:
Methods defined as TestMethod do not support Web service callouts Stack Trace: null

This error occurs because web service callouts are not allowed in Test class.

To bypass callouts add HttpcalloutMock class.

Here is a sample test class with the mock class to bypass web services Callout.

**********************  Test Class ***************************

```<code>@isTest
private class Test_class {

    private class RestMock implements HttpCalloutMock {

        public HTTPResponse respond(HTTPRequest req) {
            String fullJson = 'your Json Response';

            HTTPResponse res = new HTTPResponse();
            res.setHeader('Content-Type', 'text/json');
            res.setBody(fullJson);
            res.setStatusCode(200);
            return res;
        }
    }
    static testMethod void service_call() {

        Test.setMock(HttpCalloutMock.class, new RestMock());
        Test.startTest();

        //your web service call code

        Test.StopTest();

    }
}
</code>```

The mock class will take care of web services callouts.

Title: Mock Webservice Call out implementation

Body:
Recently working test classes in Salesforce started to Fail due to this error

Methods defined as TestMethod do not support Web service callouts
Stack Trace: null

I have reviewed the SF response https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_wsdl2apex_testing.htm

but do not understand where to implement the call out in the test class.

I created a Mock Webserivce class but can not figure out where to call the mock class.

This is the test class that is failing:

@isTest
public class OppLineItemInventoryTriggerTest {
    static testmethod void testdemo() {
        Account act = new Account(lastName = 'Testing', Billingstreet = '1234 Main', billing_as_shipping__c = True, Business_Unit__c = 'Vaya');
        insert act;
        Product2 prod = TestUtils.createProduct('product1');
        Id RecordTypeIdopp = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Package Lot').getRecordTypeId();
        Opportunity opp = new Opportunity();
        opp.AccountId = act.ID;
        opp.Name = 'Test';
        opp.Status__c = 'Completed';
        opp.Transfer_Type__c = 'Delivery';
        opp.StageName = 'New';
        opp.recordtypeid = RecordTypeIdopp;
        opp.CloseDate = Date.newInstance(2016, 12, 9);
        insert opp;
        Dosage__c dos = new Dosage__c();
        dos.Product__c = prod.ID;
        dos.Unit__c = 'mg';
        dos.Value__c = 5;
        insert dos;
        Product_Lot__c prolo = new Product_Lot__c();
        insert prolo;
        String standardPricebookId = Test.getStandardPricebookId();
        PricebookEntry pdb = new PricebookEntry(Pricebook2Id = standardPricebookId, Product2Id = prod.Id, IsActive = true, UnitPrice = 100);
        insert pdb;
        Opportunity opps = [Select id from Opportunity Limit 1];
        Contact con = new Contact(LastName = 'TestName');
        insert con;
        OpportunityLineItem oli = new OpportunityLineItem(OpportunityId = opps.Id, PricebookEntryId = pdb.Id, Quantity = 10, Shipping_Datetime__c = NULL, TotalPrice = 3000);
        insert oli;
        Inventory__c inv = new Inventory__c();
        inv.Product_ID__c = prod.ID;
        inv.Status__c = 'Completed';
        inv.Opportunity__c = opp.ID;
        inv.Days__c = '30';
        inv.Prescription__c = 'www.google.com';
        inv.Prescription_Line_Item_Id__c = 'test';
        inv.Product_Lot__c = prolo.ID;
        inv.Purchase_Date__c = Date.newInstance(2016, 12, 9);
        insert inv;
        sObject[] sObjectOldList = new sObject[] {};
        sObject[] sObjectNewList = new sObject[] {};
        sObject s11,s12;
        //sObjectOldList.add(oli);
        //sObjectNewList.add(oli);
        OppLineItemInventoryTrigger s1 = new OppLineItemInventoryTrigger(sObjectOldList, sObjectNewList);
        //  s1.execute(sObjectOldList, true);
        s1.execute(sObjectNewList, true);
        s1.executable(s11, s12);
    }

I created this mock webservice class

global class YourHttpCalloutMockImpl implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
        HttpResponse res = new HTTPResponse();
        res.setHeader('Content-Type', 'application/JSON');
        res.setBody('Your body');
        res.setStatusCode(201);
        return res;
    }
}

But not sure how to call it in the test class.

Body:
Methods defined as TestMethod do not support Web service callouts Stack Trace: null

This error occurs because web service callouts are not allowed in Test class.

To bypass callouts add HttpcalloutMock class.

Here is a sample test class with the mock class to bypass web services Callout.

**********************  Test Class ***************************

@isTest
private class Test_class {

    private class RestMock implements HttpCalloutMock {

        public HTTPResponse respond(HTTPRequest req) {
            String fullJson = 'your Json Response';

            HTTPResponse res = new HTTPResponse();
            res.setHeader('Content-Type', 'text/json');
            res.setBody(fullJson);
            res.setStatusCode(200);
            return res;
        }
    }
    static testMethod void service_call() {

        Test.setMock(HttpCalloutMock.class, new RestMock());
        Test.startTest();

        //your web service call code

        Test.StopTest();

    }
}

The mock class will take care of web services callouts.


问:
Issues with what appears to be never ending loops when calling functions in switch statement (even if function contains no loop)
I am trying to make a really simple text menu of sorts using switch statements for a class assignment. The issue is when calling the various functions I've made in the different cases of the switch statement, the never seem to end.

Considering the same issue seems to be happening to all the functions in my switch statement I think it might have something to do with the switch statement itself and not the individual functions although I honestly don't know at this point.

Disclaimer: I know I have tons of other issues with my code, but im just trying to pick a big one for simplicity. I would appreciate advice on other parts of my code aswell. (Also its not done yet as you can probably see by the unfinished cases)

Example output:

```<code>
==================
1. Admission's Office
2. Student
3. End Program
==================
Enter your choice: 1

Enter the password: 123

******************
1. Add a new student
2. Add new students from a file
3. Drop a student
4. View one students info
5. View all students info
******************
Enter your choice: 1

Enter the first name: First Name

Enter the last name: Last Name

Enter the gender: m

Enter the first name: It should only ask me once

Enter the last name: Why is this looping?

Enter the gender: ????

Enter the first name:
Enter the last name: ???????

Enter the gender: a

Enter the first name: ^C
</code>```

Code

//main.cpp
int main() {
  Student stuAr[SIZE];
  int choice, password, userInput;
  int numStu = 0;
  bool valid;

  do {
    userMenu();
    cin>>choice;
    cout<<endl;

    switch(choice){
    case 1:
      cout<<"Enter the password: ";
      cin>>password;
      cout<<endl;

      valid = checkPass(password);
      if (valid) {
        adminMenu();
        cin>>choice;
        cout<<endl;

        do {
          switch(choice) {
          case 1:
            addStu(stuAr, numStu);
            break;

          case 2:
            addStuFile(stuAr, numStu);
            break;

          case 3:
            cout<<"Enter the student ID: ";
            cin>>userInput;
            cout<<endl;
            dropStu(stuAr, numStu, userInput);
            break;

          case 4:
            cout<<"Enter the student ID: ";
            cin>>userInput;
            cout<<endl;
            viewStu(stuAr, numStu, userInput);
            break;

          case 5:
            viewAllStu(stuAr, numStu);
            break;
          }
        }while(choice != 6);
      }
      else {
        cout<<"The password is wrong."<<endl;
      }
      break;

    case 2:

      break;
    }
  }while(choice != 3);

  return 0;
```

<pre class="lang-cpp prettyprint-override"><code>//still main.cpp
//addStu function for case 1 of the nested switch statement
void addStu(Student stuAr[], int& numStu) {
  cin.ignore();
  cout<<"Enter the first name: ";
  stuAr[numStu].setFN();
  cout<<endl;

  //cin.ignore();
  cout<<"Enter the last name: ";
  stuAr[numStu].setLN();
  cout<<endl;

  cout<<"Enter the gender: ";
  stuAr[numStu].setGender();
  cout<<endl;

  numStu++;
  return;
}
</code>```

答:
You are never rereading choice within your inner loop.

```<code>if (valid) {
adminMenu();
cin>>choice; // only done once, therefore do loop never terminates
cout<<endl;
do {
  switch(choice) {
  case 1:
    addStu(stuAr, numStu);
    break;
  // ...
  }
  // after switch-case, add:
  cin >> choice;
  cout << endl;
</code>```

Body:
I am trying to make a really simple text menu of sorts using switch statements for a class assignment. The issue is when calling the various functions I've made in the different cases of the switch statement, the never seem to end.

Considering the same issue seems to be happening to all the functions in my switch statement I think it might have something to do with the switch statement itself and not the individual functions although I honestly don't know at this point.

Disclaimer: I know I have tons of other issues with my code, but im just trying to pick a big one for simplicity. I would appreciate advice on other parts of my code aswell. (Also its not done yet as you can probably see by the unfinished cases)

Example output:

==================
1. Admission's Office
2. Student
3. End Program
==================
Enter your choice: 1

Enter the password: 123

******************
1. Add a new student
2. Add new students from a file
3. Drop a student
4. View one students info
5. View all students info
******************
Enter your choice: 1

Enter the first name: First Name

Enter the last name: Last Name

Enter the gender: m

Enter the first name: It should only ask me once

Enter the last name: Why is this looping?

Enter the gender: ????

Enter the first name:
Enter the last name: ???????

Enter the gender: a

Enter the first name: ^C

Code

//main.cpp
int main() {
  Student stuAr[SIZE];
  int choice, password, userInput;
  int numStu = 0;
  bool valid;

  do {
    userMenu();
    cin>>choice;
    cout<<endl;

    switch(choice){
    case 1:
      cout<<"Enter the password: ";
      cin>>password;
      cout<<endl;

      valid = checkPass(password);
      if (valid) {
        adminMenu();
        cin>>choice;
        cout<<endl;

        do {
          switch(choice) {
          case 1:
            addStu(stuAr, numStu);
            break;

          case 2:
            addStuFile(stuAr, numStu);
            break;

          case 3:
            cout<<"Enter the student ID: ";
            cin>>userInput;
            cout<<endl;
            dropStu(stuAr, numStu, userInput);
            break;

          case 4:
            cout<<"Enter the student ID: ";
            cin>>userInput;
            cout<<endl;
            viewStu(stuAr, numStu, userInput);
            break;

          case 5:
            viewAllStu(stuAr, numStu);
            break;
          }
        }while(choice != 6);
      }
      else {
        cout<<"The password is wrong."<<endl;
      }
      break;

    case 2:

      break;
    }
  }while(choice != 3);

  return 0;

//still main.cpp
//addStu function for case 1 of the nested switch statement
void addStu(Student stuAr[], int& numStu) {
  cin.ignore();
  cout<<"Enter the first name: ";
  stuAr[numStu].setFN();
  cout<<endl;

  //cin.ignore();
  cout<<"Enter the last name: ";
  stuAr[numStu].setLN();
  cout<<endl;

  cout<<"Enter the gender: ";
  stuAr[numStu].setGender();
  cout<<endl;

  numStu++;
  return;
}

Body:
You are never rereading choice within your inner loop.

if (valid) {
adminMenu();
cin>>choice; // only done once, therefore do loop never terminates
cout<<endl;
do {
  switch(choice) {
  case 1:
    addStu(stuAr, numStu);
    break;
  // ...
  }
  // after switch-case, add:
  cin >> choice;
  cout << endl;


问:
Is there AWS solution to sort out SQS queue?
I have this architectural dilemma, and thought, maybe this is solved problem, or solvable multiple ways. I've got an SQS queue (one of many), which is triggering a Lambda function (one of many). This queue requires slightly different processing of messages, based on one key in the payload. What would be the best way for sorting out the queue messages before actual processing by Lambda?

Should it be separate Lambda, which will check for the key, and then place the message into separate queue, which will trigger corresponding Lambda?

Should it be just bunch of if statements in primary Lambda?

Is there maybe automated way to deal with such situation?

Thanks!

答:
It appears that your situation is:

An external process sends messages to an Amazon SNS topic

An Amazon SQS queue is subscribed to the SNS topic

An AWS Lambda function is subscribed to the SQS queue

There are various sub-types of messages, each of which should be processed slightly differently

One option is to use Amazon SNS Message Filtering, which can deliver messages differently based upon a message attribute. It could, for example, send a subset of messages to an SNS topic or Lambda function. However, this would require the messages being sent to the SNS topic to have a message attribute defined.

If this is not the case, then possible options are:

Use one Lambda function to process all message types (You can include quite complex code in multiple files within a Lambda function!), or

Use a Lambda function to determine the message sub-type and then send it to a specific Lambda function (or, send it via an SQS queue to a Lambda function for added resiliency)


问:
Python for-loop repeatedly outputting the input() for every iteration of dictionary contact_emails(not what I want)
```<code>   contact_emails = {

         'Sue Reyn' : 's.reyn@email.com',
         'Mike Filt': 'mike.filt@bmail.com',
         'Nate Arty': 'narty042@nmail.com'
             }

         new_contact = input()

         new_email = input()
         contact_emails[new_contact] = new_email

         for contact in contact_emails:
                      print(new_contact + ' is ' + new_email)
</code>```

The output I want is

```<code>s.reyn@email.com is Sue Reyn
mike.filt@bmail.com is Mike Filt
narty042@nmail.com is Nate Arty
alf1@hmail.com is Alf
</code>```

the output I get it

```<code>Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
</code>```

What am I doing wrong? How should I fix this code to make it output what I would like it to output?

答:
instead of using this

```<code>contact_emails[new_contact] = new_email
</code>```

try this

```<code>contact_emails.update({new_contact:new_email})

for key,val in contact_emails.items():
    print(key +' is ' + val)
</code>```

Body:
   contact_emails = {

         'Sue Reyn' : 's.reyn@email.com',
         'Mike Filt': 'mike.filt@bmail.com',
         'Nate Arty': 'narty042@nmail.com'
             }

         new_contact = input()

         new_email = input()
         contact_emails[new_contact] = new_email

         for contact in contact_emails:
                      print(new_contact + ' is ' + new_email)

The output I want is

s.reyn@email.com is Sue Reyn
mike.filt@bmail.com is Mike Filt
narty042@nmail.com is Nate Arty
alf1@hmail.com is Alf

the output I get it

Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com

What am I doing wrong? How should I fix this code to make it output what I would like it to output?

Body:
instead of using this

contact_emails[new_contact] = new_email

try this

contact_emails.update({new_contact:new_email})

for key,val in contact_emails.items():
    print(key +' is ' + val)


问:
RGB to HIS giving NaN for certain RGB values
I have a function that calculates hue for a given rgb value. For some values, the acos returns NaN because the argument is slightly larger than 1. This code follows most of the formulas I found online but I can't figure out why NaN is popping up.

Examples are

```<code>40 28 28
40 28 28
40 28 28
49 25 25
46 34 34
40 28 28
42 24 24
42 24 24
40 22 22
40 22 22
</code>```

```<code>#include <math.h>

double hue(unsigned char r, unsigned char g, unsigned char b) {
  double rn = (double) r / (r + g + b);
  double gn = (double) g / (r + g + b);
  double bn = (double) b / (r + g + b);

  if (rn == gn && gn == bn) {
    return 0;
  }

  double h = acos((rn - gn + rn - bn) / (2.0 * sqrt((rn - gn) * (rn - gn) + (rn - bn) * (gn - bn))));

  // issue with the argument of acos being just slightly bigger than 1. Approximate to 0
  if (isnan(h)) {
    h = 0;
  }

  if (b > g) {
    return (2 * M_PI - h) * (180.0 / M_PI);
  } else {
    return h * (180.0 / M_PI);
  }
}

</code>```

答:
I can't figure out why NaN is popping up

And the answer is there in your question:

because the argument is slightly larger than 1

The correct question would be in this case:

How should I make sure that the argument to acos is not bigger than 1?

For that, you need to analyze your formula and see where the problem comes from. It is possible that the sqrt and the division play a role.

The easiest hack (might be bad for your application) is to verify first if the argument is bigger than 1, and if yes, truncate it to 1.

Please notice that you loose extra precision calculating rn, gn, bn. The argument to sqrt might better be calculated as:

```<code>a = (r-g)*(r-g)+(r-b)*(g-b);
b = (r+g+b)*(r+g+b);
argument = a/b;
</code>```

Play with it and see what happens.

Also, the sequence

```<code>// issue with the argument of acos being just slightly bigger than 1. Approximate to 0
if (isnan(h)) {
    h = 0;
}
</code>```

should be used before calling acos, and using the (precalculaed) argument of acos instead of the calculated h.

Body:
I have a function that calculates hue for a given rgb value. For some values, the acos returns NaN because the argument is slightly larger than 1. This code follows most of the formulas I found online but I can't figure out why NaN is popping up.

Examples are

40 28 28
40 28 28
40 28 28
49 25 25
46 34 34
40 28 28
42 24 24
42 24 24
40 22 22
40 22 22

#include <math.h>

double hue(unsigned char r, unsigned char g, unsigned char b) {
  double rn = (double) r / (r + g + b);
  double gn = (double) g / (r + g + b);
  double bn = (double) b / (r + g + b);

  if (rn == gn && gn == bn) {
    return 0;
  }

  double h = acos((rn - gn + rn - bn) / (2.0 * sqrt((rn - gn) * (rn - gn) + (rn - bn) * (gn - bn))));

  // issue with the argument of acos being just slightly bigger than 1. Approximate to 0
  if (isnan(h)) {
    h = 0;
  }

  if (b > g) {
    return (2 * M_PI - h) * (180.0 / M_PI);
  } else {
    return h * (180.0 / M_PI);
  }
}

Body:
I can't figure out why NaN is popping up

And the answer is there in your question:

because the argument is slightly larger than 1

The correct question would be in this case:

How should I make sure that the argument to acos is not bigger than 1?

For that, you need to analyze your formula and see where the problem comes from. It is possible that the sqrt and the division play a role.

The easiest hack (might be bad for your application) is to verify first if the argument is bigger than 1, and if yes, truncate it to 1.

Please notice that you loose extra precision calculating rn, gn, bn. The argument to sqrt might better be calculated as:

a = (r-g)*(r-g)+(r-b)*(g-b);
b = (r+g+b)*(r+g+b);
argument = a/b;

Play with it and see what happens.

Also, the sequence

// issue with the argument of acos being just slightly bigger than 1. Approximate to 0
if (isnan(h)) {
    h = 0;
}

should be used before calling acos, and using the (precalculaed) argument of acos instead of the calculated h.


问:
The metadata received from server is invalid, please reconnect to the server and try
```<code>DJISDKManager.getInstance().registerApp(MainActivity.this.getApplicationContext(),
              new DJISDKManager.SDKManagerCallback() {
                    @Override
                    public void onRegister(DJIError djiError) {
                         Log.v(AAAAAAAA, djiError.getDescription());
                    }
</code>```

I made sure that I was connected to the Internet. It was good before, but suddenly I started reporting this error. Every time I register, it prompts me that The metadata received from server is invalid, please reconnect to the server and try. Sometimes there is very little The registration may be successful. I tried to change the account and key of D, but the problem still exists.

答:
To get a DJI AppKey you went to https://developer.dji.com/ and declared a new application with a bundle identifier:

You have to declare the exact name of your project package:

And use this AppKey (in AndroidManifest.xml) only for this project.

I encountered your problem when trying to use the same AppKey for different packages... Ensuring I respected the association AppKey / bundle id fixed it.

Body:
DJISDKManager.getInstance().registerApp(MainActivity.this.getApplicationContext(),
              new DJISDKManager.SDKManagerCallback() {
                    @Override
                    public void onRegister(DJIError djiError) {
                         Log.v(AAAAAAAA, djiError.getDescription());
                    }

I made sure that I was connected to the Internet. It was good before, but suddenly I started reporting this error. Every time I register, it prompts me that The metadata received from server is invalid, please reconnect to the server and try. Sometimes there is very little The registration may be successful. I tried to change the account and key of D, but the problem still exists.


问:
String references comparison in Rust
I just confirmed how the Vec::contains works. I wrote code below and it looked working fine.

But I don't know why it works because it compares &String types. Does it mean String comparison works even they aren't dereferenced?

struct NewStruct {
    string_vec: Vec<Option<String>>,
}

fn main() {
    let mut mys = NewStruct {
        string_vec: Vec::<Option<String>>::new(),
    };
    mys.string_vec.push(Some("new array".to_string()));
    let ref_st = mys.string_vec.iter().filter(|o|o.is_some()).map(|o|o.as_ref().unwrap()).collect::<Vec<&String>>();
    println!("result:{:?}", ref_st.contains(&&("some string".to_string())));
    println!("result:{:?}", ref_st.contains(&&("new array".to_string())));
    println!("Hello, world!");
    f64::from(1234_u64 as i32);
}
```

答:
Reference comparison on references in Rust always compares the values, never the addresses. This is true not just for &String but for any &T.

For example this does not compile because Foo does not implement PartialEq even though I'm only comparing references:

```<code>struct Foo;

fn main() {
    let a = Foo;
    let b = Foo;

    assert!(&a == &b);
}
</code>```

```<code>error[E0369]: binary operation `==` cannot be applied to type `&Foo`
 --> src/main.rs:7:16
  |
7 |     assert!(&a == &b);
  |             -- ^^ -- &Foo
  |             |
  |             &Foo
  |
  = note: an implementation of `std::cmp::PartialEq` might be missing for `&Foo`
</code>```

The PartialEq implementation on references is

impl<'_, '_, A, B> PartialEq<&'_ B> for &'_ A where
    A: PartialEq + ?Sized,
    B: ?Sized,
```

You can see that checking &A == &B requires to be able to do A == B.

Title: String references comparison in Rust

Body:
Reference comparison on references in Rust always compares the values, never the addresses. This is true not just for &String but for any &T.

For example this does not compile because Foo does not implement PartialEq even though I'm only comparing references:

struct Foo;

fn main() {
    let a = Foo;
    let b = Foo;

    assert!(&a == &b);
}

error[E0369]: binary operation `==` cannot be applied to type `&Foo`
 --> src/main.rs:7:16
  |
7 |     assert!(&a == &b);
  |             -- ^^ -- &Foo
  |             |
  |             &Foo
  |
  = note: an implementation of `std::cmp::PartialEq` might be missing for `&Foo`

The PartialEq implementation on references is

impl<'_, '_, A, B> PartialEq<&'_ B> for &'_ A where
    A: PartialEq<B> + ?Sized,
    B: ?Sized,

You can see that checking &A == &B requires to be able to do A == B.


问:
High number of blocked incoming requests on ephemeral ports
I am seeing a high number of blocked requests on my UFW firewall. I initially thought this was due to port scanning, but I think this is responses to some service sending requests.

How could I find out which service this is and what the requests are about?
Here is a selection of the logs:

```<code>Feb  1 11:09:03 ... kernel: [774832.138810] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=94.102.49.112 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=21247 PROTO=TCP SPT=49734 DPT=18133 WINDOW=1024 RES=0x00 SYN URGP=0
Feb  1 11:09:27 ... kernel: [774855.657944] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=146.88.240.4 DST=MYIP LEN=76 TOS=0x00 PREC=0x00 TTL=246 ID=54321 PROTO=UDP SPT=48325 DPT=123 LEN=56
Feb  1 11:10:14 ... kernel: [774903.158117] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=89.248.168.41 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=787 PROTO=TCP SPT=47977 DPT=2435 WINDOW=1024 RES=0x00 SYN URGP=0
Feb  1 11:10:30 ... kernel: [774918.997471] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=178.128.114.248 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=30799 PROTO=TCP SPT=32767 DPT=8545 WINDOW=1024 RES=0x00 SYN URGP=0
Feb  1 11:10:30 ... kernel: [774919.036015] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=173.76.38.236 DST=MYIP
LEN=40 TOS=0x00 PREC=0x00 TTL=56 ID=60924 PROTO=TCP SPT=65162 DPT=23 WINDOW=51386 RES=0x00 SYN URGP=0
Feb  1 11:10:42 ... kernel: [774930.832547] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=94.102.56.215 DST=MYIP LEN=57 TOS=0x00 PREC=0x00 TTL=248 ID=54321 PROTO=UDP SPT=59165 DPT=7941 LEN=37
Feb  1 11:10:50 ... kernel: [774938.661701] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=80.82.65.90 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=55973 PROTO=TCP SPT=59837 DPT=4227 WINDOW=1024 RES=0x00 SYN URGP=0
Feb  1 11:10:58 ... kernel: [774946.480311] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=93.174.95.110 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=8311 PROTO=TCP SPT=47917 DPT=8256 WINDOW=1024 RES=0x00 SYN URGP=0
Feb  1 11:11:20 ... kernel: [774969.227536] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=93.174.93.33 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=31038 PROTO=TCP SPT=59487 DPT=33169 WINDOW=1024 RES=0x00 SYN URGP=0
</code>```

I have configured UFW to only allow used ports, all others are closed.

答:
It turns out, that these requests are actually due to portscanning.
I compared a bunch of the listed IPs with Abuseip's database, they all are known offenders.</p>

Body:
I am seeing a high number of blocked requests on my UFW firewall. I initially thought this was due to port scanning, but I think this is responses to some service sending requests.

How could I find out which service this is and what the requests are about?
Here is a selection of the logs:

Feb  1 11:09:03 ... kernel: [774832.138810] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=94.102.49.112 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=21247 PROTO=TCP SPT=49734 DPT=18133 WINDOW=1024 RES=0x00 SYN URGP=0
Feb  1 11:09:27 ... kernel: [774855.657944] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=146.88.240.4 DST=MYIP LEN=76 TOS=0x00 PREC=0x00 TTL=246 ID=54321 PROTO=UDP SPT=48325 DPT=123 LEN=56
Feb  1 11:10:14 ... kernel: [774903.158117] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=89.248.168.41 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=787 PROTO=TCP SPT=47977 DPT=2435 WINDOW=1024 RES=0x00 SYN URGP=0
Feb  1 11:10:30 ... kernel: [774918.997471] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=178.128.114.248 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=30799 PROTO=TCP SPT=32767 DPT=8545 WINDOW=1024 RES=0x00 SYN URGP=0
Feb  1 11:10:30 ... kernel: [774919.036015] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=173.76.38.236 DST=MYIP
LEN=40 TOS=0x00 PREC=0x00 TTL=56 ID=60924 PROTO=TCP SPT=65162 DPT=23 WINDOW=51386 RES=0x00 SYN URGP=0
Feb  1 11:10:42 ... kernel: [774930.832547] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=94.102.56.215 DST=MYIP LEN=57 TOS=0x00 PREC=0x00 TTL=248 ID=54321 PROTO=UDP SPT=59165 DPT=7941 LEN=37
Feb  1 11:10:50 ... kernel: [774938.661701] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=80.82.65.90 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=55973 PROTO=TCP SPT=59837 DPT=4227 WINDOW=1024 RES=0x00 SYN URGP=0
Feb  1 11:10:58 ... kernel: [774946.480311] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=93.174.95.110 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=8311 PROTO=TCP SPT=47917 DPT=8256 WINDOW=1024 RES=0x00 SYN URGP=0
Feb  1 11:11:20 ... kernel: [774969.227536] [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=93.174.93.33 DST=MYIP LEN=40 TOS=0x00 PREC=0x00 TTL=248 ID=31038 PROTO=TCP SPT=59487 DPT=33169 WINDOW=1024 RES=0x00 SYN URGP=0

I have configured UFW to only allow used ports, all others are closed.