问:
jQuery: trigger dropdown when div or its childnodes are clicked
I have a menubar with divs as items. When the items are clicked, a dropdown opens. If the user clicks somewhere else, on a link in the dropdown or on another menubar-item the dropdown disappears. So far so good. But when a child of the menubar-div is clicked, nothing happens.

This is the show and hide logic:

```<code>var state = $(this).find('.dropdown-content').attr('aria-hidden');
if (state === 'true') {
  $('body').not(this).find('.dropdown-content').hide();
  $('body').not(this).find('.dropdown-content').attr('aria-hidden', 'true');
  if ($('body').find('.dropdown-content').parent().hasClass('secondarycolor')) {
    $('body').find('.dropdown-content').parent().addClass('hoversecondary');
    $('body').find('.dropdown-content').parent().removeClass('secondarycolor');
  }
  console.log('A' + $(event.target).attr('class'));
  console.log('B' + $(this).attr('class'));
  console.log('C' + $(this).find('.dropdown-content').attr('class'));
  $(this).find('.dropdown-content').attr('aria-hidden', 'false');
  $(this).find('.dropdown-content').show();
  if ($(this).hasClass('hoversecondary')) {
    $(this).addClass('secondarycolor');
    $(this).removeClass('hoversecondary');
  }
} else {
  $(this).find('.dropdown-content').hide();
  if ($(this).hasClass('secondarycolor')) {
    $(this).addClass('hoversecondary');
    $(this).removeClass('secondarycolor');
  }
  $(this).find('.dropdown-content').attr('aria-hidden', 'true');
}
</code>```

Here is the jsfiddle and a snippet:

$('.dropdown-button').click(function() {
  if (!($(event.target).hasClass('dropdown-content') || $(event.target).parents('.dropdown-content').length > 0)) {
    var state = $(this).find('.dropdown-content').attr('aria-hidden');
    if (state === 'true') {
      $('body').not(this).find('.dropdown-content').hide();
      $('body').not(this).find('.dropdown-content').attr('aria-hidden', 'true');
      if ($('body').find('.dropdown-content').parent().hasClass('secondarycolor')) {
        $('body').find('.dropdown-content').parent().addClass('hoversecondary');
        $('body').find('.dropdown-content').parent().removeClass('secondarycolor');
      }
      console.log('A' + $(event.target).attr('class'));
      console.log('B' + $(this).attr('class'));
      console.log('C' + $(this).find('.dropdown-content').attr('class'));
      $(this).find('.dropdown-content').attr('aria-hidden', 'false');
      $(this).find('.dropdown-content').show();
      if ($(this).hasClass('hoversecondary')) {
        $(this).addClass('secondarycolor');
        $(this).removeClass('hoversecondary');
      }
    } else {
      $(this).find('.dropdown-content').hide();
      if ($(this).hasClass('secondarycolor')) {
        $(this).addClass('hoversecondary');
        $(this).removeClass('secondarycolor');
      }
      $(this).find('.dropdown-content').attr('aria-hidden', 'true');
    }
  }
});
$('body').click(function() {
  if (($(event.target).parents('.dropdown-content').length === 0 && $(event.target).children('.dropdown-content').length === 0 && !$(event.target).hasClass('dropdown-content')) || ($(event.target).parents('.dropdown-content').length > 0 && $(event.target).parent().prop("tagName") === 'A')) {
    $('body').find('.dropdown-content').hide();
    $('body').find('.dropdown-content').attr('aria-hidden', 'true');
    if ($('body').find('.dropdown-content').parent().hasClass('secondarycolor')) {
      $('body').find('.dropdown-content').parent().addClass('hoversecondary');
      $('body').find('.dropdown-content').parent().removeClass('secondarycolor');
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.topmenu {
  display: inline-block;
  width: 200px;
  height: 42px;
  background-color: #17accc;
}

.topmenuitem {
  display: inline-block;
  width: 90px;
  height: 42px;
}

.userimage {
  position: relative;
  border-radius: 50%;
  vertical-align: middle;
  width: 29px;
  height: 29px;
  display: inline-block;
  cursor: pointer;
}

.hoversecondary:hover {
  background-color: #212121;
}

.secondarycolor {
  background-color: #212121;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 120px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  top: 50px;
  max-height: 200px;
  overflow-y: auto;
  text-align: left;
}</code>```

Q

      Q1
      Q2

S

      S1
      S2

list item 1

list item 2

list item 3

list item 4

list item 5

```

How can i trigger the dropdown when a child of the menu-item-div is clicked?

答:
I have solved it myself. The dropdown was always showing up correctly, but the onclick on the body was triggered, when an other element then dropdown-content was pressed. I updated the condition like this:

```<code>if (($(evt.target).parents('.dropdown-content').length === 0 && $(evt.target).children('.dropdown-content').length === 0 && !$(evt.target).hasClass('dropdown-content') && $(evt.target).parent().children('.dropdown-content').length === 0) || ($(evt.target).parents('.dropdown-content').length > 0 && $(evt.target).parent().prop("tagName") === 'A')) {
</code>```

Addidionally i had to add a event-parameter to the fuction so it works on firefox.

Here is the updated fiddle

Body:
I have a menubar with divs as items. When the items are clicked, a dropdown opens. If the user clicks somewhere else, on a link in the dropdown or on another menubar-item the dropdown disappears. So far so good. But when a child of the menubar-div is clicked, nothing happens.

This is the show and hide logic:

var state = $(this).find('.dropdown-content').attr('aria-hidden');
if (state === 'true') {
  $('body').not(this).find('.dropdown-content').hide();
  $('body').not(this).find('.dropdown-content').attr('aria-hidden', 'true');
  if ($('body').find('.dropdown-content').parent().hasClass('secondarycolor')) {
    $('body').find('.dropdown-content').parent().addClass('hoversecondary');
    $('body').find('.dropdown-content').parent().removeClass('secondarycolor');
  }
  console.log('A' + $(event.target).attr('class'));
  console.log('B' + $(this).attr('class'));
  console.log('C' + $(this).find('.dropdown-content').attr('class'));
  $(this).find('.dropdown-content').attr('aria-hidden', 'false');
  $(this).find('.dropdown-content').show();
  if ($(this).hasClass('hoversecondary')) {
    $(this).addClass('secondarycolor');
    $(this).removeClass('hoversecondary');
  }
} else {
  $(this).find('.dropdown-content').hide();
  if ($(this).hasClass('secondarycolor')) {
    $(this).addClass('hoversecondary');
    $(this).removeClass('secondarycolor');
  }
  $(this).find('.dropdown-content').attr('aria-hidden', 'true');
}

Here is the jsfiddle and a snippet:

$('.dropdown-button').click(function() {
  if (!($(event.target).hasClass('dropdown-content') || $(event.target).parents('.dropdown-content').length > 0)) {
    var state = $(this).find('.dropdown-content').attr('aria-hidden');
    if (state === 'true') {
      $('body').not(this).find('.dropdown-content').hide();
      $('body').not(this).find('.dropdown-content').attr('aria-hidden', 'true');
      if ($('body').find('.dropdown-content').parent().hasClass('secondarycolor')) {
        $('body').find('.dropdown-content').parent().addClass('hoversecondary');
        $('body').find('.dropdown-content').parent().removeClass('secondarycolor');
      }
      console.log('A' + $(event.target).attr('class'));
      console.log('B' + $(this).attr('class'));
      console.log('C' + $(this).find('.dropdown-content').attr('class'));
      $(this).find('.dropdown-content').attr('aria-hidden', 'false');
      $(this).find('.dropdown-content').show();
      if ($(this).hasClass('hoversecondary')) {
        $(this).addClass('secondarycolor');
        $(this).removeClass('hoversecondary');
      }
    } else {
      $(this).find('.dropdown-content').hide();
      if ($(this).hasClass('secondarycolor')) {
        $(this).addClass('hoversecondary');
        $(this).removeClass('secondarycolor');
      }
      $(this).find('.dropdown-content').attr('aria-hidden', 'true');
    }
  }
});
$('body').click(function() {
  if (($(event.target).parents('.dropdown-content').length === 0 && $(event.target).children('.dropdown-content').length === 0 && !$(event.target).hasClass('dropdown-content')) || ($(event.target).parents('.dropdown-content').length > 0 && $(event.target).parent().prop("tagName") === 'A')) {
    $('body').find('.dropdown-content').hide();
    $('body').find('.dropdown-content').attr('aria-hidden', 'true');
    if ($('body').find('.dropdown-content').parent().hasClass('secondarycolor')) {
      $('body').find('.dropdown-content').parent().addClass('hoversecondary');
      $('body').find('.dropdown-content').parent().removeClass('secondarycolor');
    }
  }
});

.topmenu {
  display: inline-block;
  width: 200px;
  height: 42px;
  background-color: #17accc;
}

.topmenuitem {
  display: inline-block;
  width: 90px;
  height: 42px;
}

.userimage {
  position: relative;
  border-radius: 50%;
  vertical-align: middle;
  width: 29px;
  height: 29px;
  display: inline-block;
  cursor: pointer;
}

.hoversecondary:hover {
  background-color: #212121;
}

.secondarycolor {
  background-color: #212121;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 120px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  top: 50px;
  max-height: 200px;
  overflow-y: auto;
  text-align: left;
}

Q

      Q1
      Q2

S

      S1
      S2

list item 1

list item 2

list item 3

list item 4

list item 5

How can i trigger the dropdown when a child of the menu-item-div is clicked?

Body:
I have solved it myself. The dropdown was always showing up correctly, but the onclick on the body was triggered, when an other element then dropdown-content was pressed. I updated the condition like this:

if (($(evt.target).parents('.dropdown-content').length === 0 && $(evt.target).children('.dropdown-content').length === 0 && !$(evt.target).hasClass('dropdown-content') && $(evt.target).parent().children('.dropdown-content').length === 0) || ($(evt.target).parents('.dropdown-content').length > 0 && $(evt.target).parent().prop("tagName") === 'A')) {

Addidionally i had to add a event-parameter to the fuction so it works on firefox.

Here is the updated fiddle


来源: stackexchange

问:
Performance of MKL `dgesvd` vs MKL `LAPACKE_dgesvd`?
dgesvd seems to be a LAPACKE_dgesvd with the layout LAPACK_COL_MAJOR, but looking at the examples for dgesvd and LAPACKE_dgesvd it seems there is an extra step in the dgesvd example where an optimal workspace is queried and allocated.

Is it correct to assume that this step is to figure out if the input matrix is COL_MAJOR or ROW_MAJOR?

Is it correct to assume that once the optimal workspace is figured out, 'dgesvd' internally calls LAPACKE_dgesvd with the appropriate layout?

If I already know the matrix layout to be COL_MAJOR is using LAPACKE_dgesvd better (faster/less expensive) than dgesvd?

答:
We have two functions here which refer to two different interfaces:

```<code>i.  dgesvd         : calls fortran interface
ii. LAPACKE_dgesvd : calls C interface
</code>```

For detail see this.

No it is not correct. As you will notice in the first call to dgesvd the value of lwork is set to -1 which as documented here is used for just calculating the size of lwork. So if you already know about the size of lwork you don't need to call it twice. Input matrix has to be LAPACK_COL_MAJOR for dgesvd as this is default for fortran. Also there is no way to calculate if the matrix is row major or column major.

No it's not true. dgesvd is the fortran interface which was implemented first.

This would depend on the compiler optimization. If the matrix is small it probably wouldn't matter. For me if its column major I would use fortran interface.

For matrix layout infotmation see this. Here is the technical paper for C interface

ContentLicense: CC BY-SA 3.0

Body:
We have two functions here which refer to two different interfaces:

i.  dgesvd         : calls fortran interface
ii. LAPACKE_dgesvd : calls C interface

For detail see this.

No it is not correct. As you will notice in the first call to dgesvd the value of lwork is set to -1 which as documented here is used for just calculating the size of lwork. So if you already know about the size of lwork you don't need to call it twice. Input matrix has to be LAPACK_COL_MAJOR for dgesvd as this is default for fortran. Also there is no way to calculate if the matrix is row major or column major.

No it's not true. dgesvd is the fortran interface which was implemented first.

This would depend on the compiler optimization. If the matrix is small it probably wouldn't matter. For me if its column major I would use fortran interface.

For matrix layout infotmation see this. Here is the technical paper for C interface


问:
how to select count of specific value while joining two tables
here i am joining two tables and this code fails to get the count of c.status
when c.status='Absent' </p>

```<code>SELECT    d.empReferenceID,
          Count(c.status)
FROM      emp_tbl d
LEFT JOIN empattendance c
on        d.empReferenceID = c.RefrenceID
and       c.status='PRESENT'
and       month(c.CreatedOn)=5
and       year(c.CreatedOn)=2017
where     c.RefrenceID not in ('2075671')
GROUP BY  d.empReferenceID;
</code>```

答:
Don't put conditions on an outer-joined table in the WHERE clause. Your where c.RefrenceID not in ('2075671') dismisses all outer-joined records and turns the join into an inner join.

Maybe you are looking for conditional aggregation, where you count different statuses and show the counts in the same result row:

```<code>SELECT    d.empReferenceID,
          Count(c.status) AS count_all,
          Sum(c.status = 'PRESENT') AS count_present,
          Sum(c.status = 'Absent') AS count_absent
FROM      emp_tbl d
LEFT JOIN empattendance c
ON        d.empReferenceID = c.RefrenceID
AND       month(c.CreatedOn)=5
AND       year(c.CreatedOn)=2017
WHERE     d.empReferenceID not in ('2075671')
GROUP BY  d.empReferenceID;
</code>```

The SUM lines make use of MySQL's true = 1/ false = 0 by the way. You'd achieve the same with standard SQL: Sum(CASE WHEN c.status = 'PRESENT' THEN 1 ELSE 0 END) or Count(CASE WHEN c.status = 'PRESENT' THEN 1 END).

Body:
here i am joining two tables and this code fails to get the count of c.status
when c.status='Absent'

SELECT    d.empReferenceID,
          Count(c.status)
FROM      emp_tbl d
LEFT JOIN empattendance c
on        d.empReferenceID = c.RefrenceID
and       c.status='PRESENT'
and       month(c.CreatedOn)=5
and       year(c.CreatedOn)=2017
where     c.RefrenceID not in ('2075671')
GROUP BY  d.empReferenceID;

Body:
Don't put conditions on an outer-joined table in the WHERE clause. Your where c.RefrenceID not in ('2075671') dismisses all outer-joined records and turns the join into an inner join.

Maybe you are looking for conditional aggregation, where you count different statuses and show the counts in the same result row:

SELECT    d.empReferenceID,
          Count(c.status) AS count_all,
          Sum(c.status = 'PRESENT') AS count_present,
          Sum(c.status = 'Absent') AS count_absent
FROM      emp_tbl d
LEFT JOIN empattendance c
ON        d.empReferenceID = c.RefrenceID
AND       month(c.CreatedOn)=5
AND       year(c.CreatedOn)=2017
WHERE     d.empReferenceID not in ('2075671')
GROUP BY  d.empReferenceID;

The SUM lines make use of MySQL's true = 1/ false = 0 by the way. You'd achieve the same with standard SQL: Sum(CASE WHEN c.status = 'PRESENT' THEN 1 ELSE 0 END) or Count(CASE WHEN c.status = 'PRESENT' THEN 1 END).


问:
Install Python Packages in Azure ML?
Similar question as here but now on Python packages. Currently, the CVXPY is missing in Azure ML. I am also trying to get other solvers such as GLPK, CLP and COINMP working in Azure ML.

How can I install Python packages in Azure ML?

Update about trying to install the Python packages not found in Azure ML.

I did as instructed by Peter Pan but I think the 32bits CVXPY files are wrong for the Anaconda 4 and Python 3.5 in Azure ML, logs and errors are here.

```<code>[Information]         Running with Python 3.5.1 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:49:46) [MSC v.1900 64 bit (AMD64)]
</code>```

Update 2 with win_amd64 files (paste here)

```<code>[Information]         Extracting Script Bundle.zip to .\Script Bundle
[Information]         File Name                                             Modified             Size
[Information]         cvxopt-1.1.9-cp35-cp35m-win_amd64.whl          2017-06-07 01:03:34      1972074
[Information]         __MACOSX/                                      2017-06-07 01:26:28            0
[Information]         __MACOSX/._cvxopt-1.1.9-cp35-cp35m-win_amd64.whl 2017-06-07 01:03:34          452
[Information]         cvxpy-0.4.10-py3-none-any.whl                  2017-06-07 00:25:36       300880
[Information]         __MACOSX/._cvxpy-0.4.10-py3-none-any.whl       2017-06-07 00:25:36          444
[Information]         ecos-2.0.4-cp35-cp35m-win_amd64.whl            2017-06-07 01:03:40        56522
[Information]         __MACOSX/._ecos-2.0.4-cp35-cp35m-win_amd64.whl 2017-06-07 01:03:40          450
[Information]         numpy-1.13.0rc2+mkl-cp35-cp35m-win_amd64.whl   2017-06-07 01:25:02    127909457
[Information]         __MACOSX/._numpy-1.13.0rc2+mkl-cp35-cp35m-win_amd64.whl 2017-06-07 01:25:02          459
[Information]         scipy-0.19.0-cp35-cp35m-win_amd64.whl          2017-06-07 01:05:12     12178932
[Information]         __MACOSX/._scipy-0.19.0-cp35-cp35m-win_amd64.whl 2017-06-07 01:05:12          452
[Information]         scs-1.2.6-cp35-cp35m-win_amd64.whl             2017-06-07 01:03:34        78653
[Information]         __MACOSX/._scs-1.2.6-cp35-cp35m-win_amd64.whl  2017-06-07 01:03:34          449
[Information]         [ READING ] 0:00:00
[Information]         Input pandas.DataFrame #1:
[Information]         Empty DataFrame
[Information]         Columns: [1]
[Information]         Index: []
[Information]         [ EXECUTING ] 0:00:00
[Information]         [ WRITING ] 0:00:00
</code>```

where import cvxpy, import cvxpy-0.4.10-py3-none-any.whl or cvxpy-0.4.10-py3-none-any do not work so

How can I use the following wheel files downloaded from here to use the external Python packages not found in Azure ML?

Update about permission problem about importing cvxpy (paste here)

```<code> [Error]         ImportError: No module named 'canonInterface'
</code>```

where the ZIP Bundle is organised a bit differently, the content of each wheel downloaded to a folder and the content having all zipped as a ZIP Bundle.

答:
According to the Limitations and Technical Notes of Execute Python Script tutorial, the only way to add custom Python modules is via the zip file mechanism to package the modules and all dependencies.

For example to install CVXPY, as below.

Download the wheel file of CVXPY and its dependencies like CVXOPT.

Decompress these wheel files, and package these files in the path cvxpy and cvxopt, etc as a zipped file with your script.

Upload the zip file as a dataset and use it as the script bundle.

If you were using IPython, you also can try to install the Python Package via the code !pip install cvxpy.

And there are some similar SO threads which may be helpful for you, as below.

Azure ML Python with Script Bundle cannot import module

How to install a Python package from within IPython?

Hope it helps.

Update:

For IPython interface of Azure ML, you move to the NOTEBOOKS tab to create a notebook via ADD TO PROJECT button at the bottom of the page, as the figure below.

Or you can directly login to the website https://notebooks.azure.com to use it.

Title: Install Python Packages in Azure ML?

Body:
Similar question as here but now on Python packages. Currently, the CVXPY is missing in Azure ML. I am also trying to get other solvers such as GLPK, CLP and COINMP working in Azure ML.

How can I install Python packages in Azure ML?

Update about trying to install the Python packages not found in Azure ML.

I did as instructed by Peter Pan but I think the 32bits CVXPY files are wrong for the Anaconda 4 and Python 3.5 in Azure ML, logs and errors are here.

[Information]         Running with Python 3.5.1 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:49:46) [MSC v.1900 64 bit (AMD64)]

Update 2 with win_amd64 files (paste here)

[Information]         Extracting Script Bundle.zip to .\Script Bundle
[Information]         File Name                                             Modified             Size
[Information]         cvxopt-1.1.9-cp35-cp35m-win_amd64.whl          2017-06-07 01:03:34      1972074
[Information]         __MACOSX/                                      2017-06-07 01:26:28            0
[Information]         __MACOSX/._cvxopt-1.1.9-cp35-cp35m-win_amd64.whl 2017-06-07 01:03:34          452
[Information]         cvxpy-0.4.10-py3-none-any.whl                  2017-06-07 00:25:36       300880
[Information]         __MACOSX/._cvxpy-0.4.10-py3-none-any.whl       2017-06-07 00:25:36          444
[Information]         ecos-2.0.4-cp35-cp35m-win_amd64.whl            2017-06-07 01:03:40        56522
[Information]         __MACOSX/._ecos-2.0.4-cp35-cp35m-win_amd64.whl 2017-06-07 01:03:40          450
[Information]         numpy-1.13.0rc2+mkl-cp35-cp35m-win_amd64.whl   2017-06-07 01:25:02    127909457
[Information]         __MACOSX/._numpy-1.13.0rc2+mkl-cp35-cp35m-win_amd64.whl 2017-06-07 01:25:02          459
[Information]         scipy-0.19.0-cp35-cp35m-win_amd64.whl          2017-06-07 01:05:12     12178932
[Information]         __MACOSX/._scipy-0.19.0-cp35-cp35m-win_amd64.whl 2017-06-07 01:05:12          452
[Information]         scs-1.2.6-cp35-cp35m-win_amd64.whl             2017-06-07 01:03:34        78653
[Information]         __MACOSX/._scs-1.2.6-cp35-cp35m-win_amd64.whl  2017-06-07 01:03:34          449
[Information]         [ READING ] 0:00:00
[Information]         Input pandas.DataFrame #1:
[Information]         Empty DataFrame
[Information]         Columns: [1]
[Information]         Index: []
[Information]         [ EXECUTING ] 0:00:00
[Information]         [ WRITING ] 0:00:00

where import cvxpy, import cvxpy-0.4.10-py3-none-any.whl or cvxpy-0.4.10-py3-none-any do not work so

How can I use the following wheel files downloaded from here to use the external Python packages not found in Azure ML?

Update about permission problem about importing cvxpy (paste here)

 [Error]         ImportError: No module named 'canonInterface'

where the ZIP Bundle is organised a bit differently, the content of each wheel downloaded to a folder and the content having all zipped as a ZIP Bundle.


问:
How to scan a classpath for resources with Jersey outside of an Application?
In the case of (server-side) Application configuration, we can easily scan packages for JAX-RS resource classes with

```<code> ResourceConfig rCfg = new ResourceConfig();
 rCfg.packages("com.my.package", ...);
</code>```

and then initializing the application using the ResourceConfig as the Application object.

Using the client-side though, it is not clear how to perform package scanning.

We can do

```<code>  Resource.from(SomeResourceClass.class);
</code>```

to get resources if we know the class name.   In my case we don't know the class names, and we'd like to get the classes based on their @Path.   If we knew all of the class names up front, we could use repeated calls to Resource.from() to get all the resources, then index them by path, then lookup the paths as necessary.

But we don't know all the class names up front.   Is there some way to get all of the Resource in a particular package, or even better scan the entire classpath for them - all without initializing a (server-side) Application?

答:
For package scanning, you can use the PackageNamesScanner. Here is an example

```<code>public static void main(String... args) throws Exception {
    final String[] pkgs = {"com.example.jersey"};
    final boolean recursive = true;

    final AnnotationAcceptingListener asl = new AnnotationAcceptingListener(Path.class);
    final PackageNamesScanner scanner = new PackageNamesScanner(pkgs, recursive);
    while (scanner.hasNext()) {
        final String next = scanner.next();
        if (asl.accept(next)) {
            try (final InputStream in = scanner.open()) {
                asl.process(next, in);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    asl.getAnnotatedClasses().forEach(System.out::println);
}
</code>```

Unfortunately, I don't think there is an "ClassPathScanner". Classpath scanning is only used for servlet environments (and Jersey can be run outside of servlet environments), so there is a one-off implementation off the classpath scanning in the WebAppResourcesScanner, but it would not work in your case, as it scans specific paths.

You can also look at some of the general posts regarding scanning the classpath for annotated classes, like:

Scan the classpath for classes with custom annotation

Scanning Java annotations at runtime

Body:
In the case of (server-side) Application configuration, we can easily scan packages for JAX-RS resource classes with

 ResourceConfig rCfg = new ResourceConfig();
 rCfg.packages("com.my.package", ...);

and then initializing the application using the ResourceConfig as the Application object.

Using the client-side though, it is not clear how to perform package scanning.

We can do

  Resource.from(SomeResourceClass.class);

to get resources if we know the class name.   In my case we don't know the class names, and we'd like to get the classes based on their @Path.   If we knew all of the class names up front, we could use repeated calls to Resource.from() to get all the resources, then index them by path, then lookup the paths as necessary.

But we don't know all the class names up front.   Is there some way to get all of the Resource in a particular package, or even better scan the entire classpath for them - all without initializing a (server-side) Application?

Body:
For package scanning, you can use the PackageNamesScanner. Here is an example

public static void main(String... args) throws Exception {
    final String[] pkgs = {"com.example.jersey"};
    final boolean recursive = true;

    final AnnotationAcceptingListener asl = new AnnotationAcceptingListener(Path.class);
    final PackageNamesScanner scanner = new PackageNamesScanner(pkgs, recursive);
    while (scanner.hasNext()) {
        final String next = scanner.next();
        if (asl.accept(next)) {
            try (final InputStream in = scanner.open()) {
                asl.process(next, in);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    asl.getAnnotatedClasses().forEach(System.out::println);
}

Unfortunately, I don't think there is an "ClassPathScanner". Classpath scanning is only used for servlet environments (and Jersey can be run outside of servlet environments), so there is a one-off implementation off the classpath scanning in the WebAppResourcesScanner, but it would not work in your case, as it scans specific paths.

You can also look at some of the general posts regarding scanning the classpath for annotated classes, like:

Scan the classpath for classes with custom annotation

Scanning Java annotations at runtime


问:
Find region from within an EC2 instance
Is there a way to look up the region of an instance from within the instance?

I'm looking for something similar to the method of finding the instance id.

答:
If you work with json - use right tools. jq much powerful in this case.</p>

```<code># curl -s curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r '.region'
eu-west-1
</code>```

Title: Find region from within an EC2 instance

Body:
If you work with json - use right tools. jq much powerful in this case.

# curl -s curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r '.region'
eu-west-1


问:
Warmup Neo4j database after spring initialization
I use a Neo4J database with nearly 500k nodes. When I startup my Spring application and do the first query, it takes about 4-5 seconds. This happens just for the first query, so I thought I could do a warmup after spring is initialized to make all subsequent queries faster.

This is my applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <util:map id="config">
        <entry key="enable_remote_shell" value="false" />
    </util:map>

    <bean id="graphDbFactory" class="org.neo4j.graphdb.factory.GraphDatabaseFactory" />

    <bean id="graphDbBuilder" factory-bean="graphDbFactory"
        factory-method="newEmbeddedDatabaseBuilder">
        <constructor-arg value="/path/to/db" />
    </bean>

    <bean id="graphDbBuilderFinal" factory-bean="graphDbBuilder"
        factory-method="setConfig">
        <constructor-arg ref="config" />
    </bean>

    <bean id="graphDatabaseService" factory-bean="graphDbBuilderFinal"
        factory-method="newGraphDatabase" destroy-method="shutdown" class="org.neo4j.graphdb.GraphDatabaseService"/>

    <context:component-scan base-package="com.app.components" />
</beans>
```

<p>I saw that one way to wait for Spring beans initialization was to implement an <code>ApplicationListener</code>, and the regular way to warmup the database with Neo was to call the <code>apoc.runtime.warmup()</code> function, so I did as follows:</p>

```package com.app.components;

@Component
public class StartupTasks implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger LOG = LogManager.getLogger(StartupTasks.class);

    @Autowired
    GraphDatabaseService db;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        executeTestSelect();
    }

    private void executeTestSelect() {
        LOG.info("Warming up Neo4j...");

        Transaction tx = db.beginTx();
        db.execute("CALL apoc.warmup.run()");
        tx.close();

        LOG.info("Warmup complete.");
    }
}
```

<p>This one didn't work, everything gets correctly logged but the first neo4j query is still slow.</p>

<p>Since this approach didn't work, I edited the <code>executeTestSelect</code> method to run a real query and process the results like this:</p>

```private void executeTestSelect() {
    String textToSearch = "a"; // returns almost all nodes, should make neo4j cache them all
    Transaction tx = db.beginTx();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("textToSearch", textToSearch );
    Result resultSet = db.execute("MATCH (n:PROD) WHERE n.description CONTAINS {textToSearch} RETURN n",
                params);
    Iterator<Node> results = resultSet.columnAs("n");
    int count = 0;
    while (results.hasNext()) {
        results.next();
        count++:
    }
    tx.close();
    LOG.info("Neo4j cache done. Processed " + count + " nodes.");
}
```

This time the startup takes 4-5 seconds just to execute the query, but then it prints

Neo4j cache done. Processed 0 nodes.

This is weird, because the exact same query run when the app is fully initialized returns 450k nodes.

What am I missing? Is it possible that when reaching onApplicationEvent the Neo4j DB hasn't been initialized yet and can't execute queries?

How do I correctly warmup a neo4j database right after the complete spring app initialization?

答:
Ok I discovered this by pure luck.

I removed the ApplicationListener and created a @Service class with the @Autowired annotation on the method that does the warmup, it seems to be working.

I discovered this by removing a class field without seeing the @Autowired annotation left here, and it worked. I tried it several times, the warmup is working now. I don't know if it is documented somewhere in the Spring Documentation.

This is my final class:

```<code>package com.app.components;

@Component
public class Neo4jWarmup {

    private static final Logger LOG = LogManager.getLogger(StartupTasks.class);

    @Autowired
    GraphDatabaseService db;

    /*
     * this did the trick - the method gets called
     * after Spring initialization and the DB works as expected
     */
    @Autowired
    public void neo4jWarmup() {
        executeTestSelect();
    }

    private void executeTestSelect() {
        LOG.info("Warming up Neo4j...");

        Transaction tx = db.beginTx();
        db.execute("CALL apoc.warmup.run()");
        tx.close();

        LOG.info("Warmup complete.");
    }
}
</code>```

Body:
I use a Neo4J database with nearly 500k nodes. When I startup my Spring application and do the first query, it takes about 4-5 seconds. This happens just for the first query, so I thought I could do a warmup after spring is initialized to make all subsequent queries faster.

This is my applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <util:map id="config">
        <entry key="enable_remote_shell" value="false" />
    </util:map>

    <bean id="graphDbFactory" class="org.neo4j.graphdb.factory.GraphDatabaseFactory" />

    <bean id="graphDbBuilder" factory-bean="graphDbFactory"
        factory-method="newEmbeddedDatabaseBuilder">
        <constructor-arg value="/path/to/db" />
    </bean>

    <bean id="graphDbBuilderFinal" factory-bean="graphDbBuilder"
        factory-method="setConfig">
        <constructor-arg ref="config" />
    </bean>

    <bean id="graphDatabaseService" factory-bean="graphDbBuilderFinal"
        factory-method="newGraphDatabase" destroy-method="shutdown" class="org.neo4j.graphdb.GraphDatabaseService"/>

    <context:component-scan base-package="com.app.components" />
</beans>

I saw that one way to wait for Spring beans initialization was to implement an ApplicationListener, and the regular way to warmup the database with Neo was to call the apoc.runtime.warmup() function, so I did as follows:

package com.app.components;

@Component
public class StartupTasks implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger LOG = LogManager.getLogger(StartupTasks.class);

    @Autowired
    GraphDatabaseService db;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        executeTestSelect();
    }

    private void executeTestSelect() {
        LOG.info("Warming up Neo4j...");

        Transaction tx = db.beginTx();
        db.execute("CALL apoc.warmup.run()");
        tx.close();

        LOG.info("Warmup complete.");
    }
}

This one didn't work, everything gets correctly logged but the first neo4j query is still slow.

Since this approach didn't work, I edited the executeTestSelect method to run a real query and process the results like this:

private void executeTestSelect() {
    String textToSearch = "a"; // returns almost all nodes, should make neo4j cache them all
    Transaction tx = db.beginTx();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("textToSearch", textToSearch );
    Result resultSet = db.execute("MATCH (n:PROD) WHERE n.description CONTAINS {textToSearch} RETURN n",
                params);
    Iterator<Node> results = resultSet.columnAs("n");
    int count = 0;
    while (results.hasNext()) {
        results.next();
        count++:
    }
    tx.close();
    LOG.info("Neo4j cache done. Processed " + count + " nodes.");
}

This time the startup takes 4-5 seconds just to execute the query, but then it prints

Neo4j cache done. Processed 0 nodes.

This is weird, because the exact same query run when the app is fully initialized returns 450k nodes.

What am I missing? Is it possible that when reaching onApplicationEvent the Neo4j DB hasn't been initialized yet and can't execute queries?

How do I correctly warmup a neo4j database right after the complete spring app initialization?

Body:
Ok I discovered this by pure luck.

I removed the ApplicationListener and created a @Service class with the @Autowired annotation on the method that does the warmup, it seems to be working.

I discovered this by removing a class field without seeing the @Autowired annotation left here, and it worked. I tried it several times, the warmup is working now. I don't know if it is documented somewhere in the Spring Documentation.

This is my final class:

package com.app.components;

@Component
public class Neo4jWarmup {

    private static final Logger LOG = LogManager.getLogger(StartupTasks.class);

    @Autowired
    GraphDatabaseService db;

    /*
     * this did the trick - the method gets called
     * after Spring initialization and the DB works as expected
     */
    @Autowired
    public void neo4jWarmup() {
        executeTestSelect();
    }

    private void executeTestSelect() {
        LOG.info("Warming up Neo4j...");

        Transaction tx = db.beginTx();
        db.execute("CALL apoc.warmup.run()");
        tx.close();

        LOG.info("Warmup complete.");
    }
}


问:
Refresh Datagrid after adding a new Customer MVVM WPF
This my view Main:

XAML View Main :

```<code><DataGrid AutoGenerateColumns="false"
          SelectedItem="{Binding Selectedrole}"
          ItemsSource="{Binding RoleList}">
  <Button Content="Add Role"
          Command="{Binding  AddRole}"
          Height="35"/>
</DataGrid>
</code>```

The ViewModel Main:

```<code>public RoleManagementViewModel()
{
    roleList = new ObservableCollection<UserRoleClass>(WCFclient.GetAllRoles());
    _addRole = new RelayCommand<string>(AddRoleFunction);
}

private void AddRoleFunction(object obj)
{
    if (!Application.Current.Windows.OfType<SelectionCompartementView>().Any())
    {
        AddRoleView winAddRole = new AddRoleView();
        winAddRole.DataContext = new AddRoleViewModel();
        winAddRole.Show();
        winAddRole.Topmost = true;
        winAddRole.Focus();
    }
}

public ObservableCollection<UserRoleClass> RoleList
{
    get { return roleList; }
    set
    {
        roleList = value;
        OnPropertyChanged("RoleList");
    }
}
</code>```

The view Add Role:

Xaml Add-Role:

```<code><Button x:Name="button1"
        Command="{Binding SaveRole}"
        CommandParameter="{Binding ElementName=AddRole}"/>
</code>```

ViewModel Add-Role:

```<code>public AddRoleViewModel()
{
    _addOrUpdate = new UserRoleClass();
    _addOrUpdate = new UserRoleClass();
    saveRole = new RelayCommand<Window>(addFunc);
}

private void addFunc(Window window)
{
    UserRoleClass newRole = new UserRoleClass()
    {
        name = AddOrUpdate.name,
        description = AddOrUpdate.description,
    };
    int resultSave = WCFclient.saveRole(newRole);
    if (resultSave == 0)
    {
        String UpdateInformation0 = "Role is saved successfully";
        string sCaption = "Save Role";
        MessageBoxButton btnMessageBox = MessageBoxButton.OK;
        MessageBoxImage icnMessageBox = MessageBoxImage.Information;
        MessageBoxResult rsltMessageBox = MessageBox.Show(
            UpdateInformation0, sCaption, btnMessageBox, icnMessageBox);
    }
    if (window != null)
    {
        window.Close();
    }
}

private ICommand saveRole;
public ICommand SaveRole
{
    get { return saveRole; }
}
</code>```

It works fine: when I add a new Role, the view of Add-Role closes and returns to the view Main, and I have a result in database... but not in the DataGrid in MainView.

How can I refresh directly?

答:
This is a common problem with binding datagrid to an observable collection. The binding updates if the collection changes not if the collection content changes. The best way to do this, after adding the new UserRole to the RoleList is to use a "deep" observable collection like this one:

```<code>public sealed class DeepObservableCollection<T>
    : ObservableCollection<T> where T : INotifyPropertyChanged {

    public event PropertyChangedEventHandler ItemPropertyChanged;

    public DeepObservableCollection() {
        CollectionChanged += DeepObservableCollection_CollectionChanged;
    }

    public DeepObservableCollection(ObservableCollection<T> collection)
        : base(collection) {
        CollectionChanged += DeepObservableCollection_CollectionChanged;
    }

    public DeepObservableCollection( List<T> collection )
        : base( collection ) {
        CollectionChanged += DeepObservableCollection_CollectionChanged;
    }

    void DeepObservableCollection_CollectionChanged( object sender, NotifyCollectionChangedEventArgs e ) {
        if ( e.NewItems != null ) {
            foreach ( var item in e.NewItems ) {
                var notifyPropertyChanged = item as INotifyPropertyChanged;
                if ( notifyPropertyChanged != null ) notifyPropertyChanged.PropertyChanged += item_PropertyChanged;
            }
        }
        if ( e.OldItems != null ) {
            foreach ( Object item in e.OldItems ) {
                var notifyPropertyChanged = item as INotifyPropertyChanged;
                if ( notifyPropertyChanged != null ) notifyPropertyChanged.PropertyChanged -= item_PropertyChanged;
            }
        }
    }
    void item_PropertyChanged( object sender, PropertyChangedEventArgs e ) {
        NotifyCollectionChangedEventArgs a = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Reset );
        OnCollectionChanged( a );

        ItemPropertyChanged?.Invoke( sender, e );
    }
}
</code>```

your UserRoleClass must implement INotifyPropertyChanged (maybe using ObservableObject) but that's all what is required. When you add a new user role datagrid updates through binding.

Body:
This my view Main:

XAML View Main :

<DataGrid AutoGenerateColumns="false"
          SelectedItem="{Binding Selectedrole}"
          ItemsSource="{Binding RoleList}">
  <Button Content="Add Role"
          Command="{Binding  AddRole}"
          Height="35"/>
</DataGrid>

The ViewModel Main:

public RoleManagementViewModel()
{
    roleList = new ObservableCollection<UserRoleClass>(WCFclient.GetAllRoles());
    _addRole = new RelayCommand<string>(AddRoleFunction);
}

private void AddRoleFunction(object obj)
{
    if (!Application.Current.Windows.OfType<SelectionCompartementView>().Any())
    {
        AddRoleView winAddRole = new AddRoleView();
        winAddRole.DataContext = new AddRoleViewModel();
        winAddRole.Show();
        winAddRole.Topmost = true;
        winAddRole.Focus();
    }
}

public ObservableCollection<UserRoleClass> RoleList
{
    get { return roleList; }
    set
    {
        roleList = value;
        OnPropertyChanged("RoleList");
    }
}

The view Add Role:

Xaml Add-Role:

<Button x:Name="button1"
        Command="{Binding SaveRole}"
        CommandParameter="{Binding ElementName=AddRole}"/>

ViewModel Add-Role:

public AddRoleViewModel()
{
    _addOrUpdate = new UserRoleClass();
    _addOrUpdate = new UserRoleClass();
    saveRole = new RelayCommand<Window>(addFunc);
}

private void addFunc(Window window)
{
    UserRoleClass newRole = new UserRoleClass()
    {
        name = AddOrUpdate.name,
        description = AddOrUpdate.description,
    };
    int resultSave = WCFclient.saveRole(newRole);
    if (resultSave == 0)
    {
        String UpdateInformation0 = "Role is saved successfully";
        string sCaption = "Save Role";
        MessageBoxButton btnMessageBox = MessageBoxButton.OK;
        MessageBoxImage icnMessageBox = MessageBoxImage.Information;
        MessageBoxResult rsltMessageBox = MessageBox.Show(
            UpdateInformation0, sCaption, btnMessageBox, icnMessageBox);
    }
    if (window != null)
    {
        window.Close();
    }
}

private ICommand saveRole;
public ICommand SaveRole
{
    get { return saveRole; }
}

It works fine: when I add a new Role, the view of Add-Role closes and returns to the view Main, and I have a result in database... but not in the DataGrid in MainView.

How can I refresh directly?

Body:
This is a common problem with binding datagrid to an observable collection. The binding updates if the collection changes not if the collection content changes. The best way to do this, after adding the new UserRole to the RoleList is to use a "deep" observable collection like this one:

public sealed class DeepObservableCollection<T>
    : ObservableCollection<T> where T : INotifyPropertyChanged {

    public event PropertyChangedEventHandler ItemPropertyChanged;

    public DeepObservableCollection() {
        CollectionChanged += DeepObservableCollection_CollectionChanged;
    }

    public DeepObservableCollection(ObservableCollection<T> collection)
        : base(collection) {
        CollectionChanged += DeepObservableCollection_CollectionChanged;
    }

    public DeepObservableCollection( List<T> collection )
        : base( collection ) {
        CollectionChanged += DeepObservableCollection_CollectionChanged;
    }

    void DeepObservableCollection_CollectionChanged( object sender, NotifyCollectionChangedEventArgs e ) {
        if ( e.NewItems != null ) {
            foreach ( var item in e.NewItems ) {
                var notifyPropertyChanged = item as INotifyPropertyChanged;
                if ( notifyPropertyChanged != null ) notifyPropertyChanged.PropertyChanged += item_PropertyChanged;
            }
        }
        if ( e.OldItems != null ) {
            foreach ( Object item in e.OldItems ) {
                var notifyPropertyChanged = item as INotifyPropertyChanged;
                if ( notifyPropertyChanged != null ) notifyPropertyChanged.PropertyChanged -= item_PropertyChanged;
            }
        }
    }
    void item_PropertyChanged( object sender, PropertyChangedEventArgs e ) {
        NotifyCollectionChangedEventArgs a = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Reset );
        OnCollectionChanged( a );

        ItemPropertyChanged?.Invoke( sender, e );
    }
}

your UserRoleClass must implement INotifyPropertyChanged (maybe using ObservableObject) but that's all what is required. When you add a new user role datagrid updates through binding.


问:
.htaccess help, replacing URI segment
I have a URL that looks like this...

```<code>http://www.domain/a/var
</code>```

I am hoping it would be possible to rewrite the URL using .htaccess so that /a/ would be replaced by /b/.

Is that possible, and if so, how?

答:
RewriteEngine On

RewriteRule ^a/(.*)    /b/$1

ContentLicense: CC BY-SA 2.5

Title: .htaccess help, replacing URI segment

Body:
I have a URL that looks like this...

http://www.domain/a/var

I am hoping it would be possible to rewrite the URL using .htaccess so that /a/ would be replaced by /b/.

Is that possible, and if so, how?


问:
Should I use ArrayField or ManyToManyField for tags
I am trying to add tags to a model for a postgres db in django and I found two solutions:

using foreign keys:

```<code>class Post(models.Model):
    tags = models.ManyToManyField('tags')
    ...

class Tag(models.Model):
    name = models.CharField(max_length=140)
</code>```

using array field:

```<code>from django.contrib.postgres.fields import ArrayField

class Post(models.Model):
    tags = ArrayField(models.CharField(max_length=140))
    ...
</code>```

assuming that I don't care about supporting other database-backends in my code, what is a recommended solution ?

答:
If you want the class tags to be monitored ( For eg : how many tags, how many of a particular tag etd ) , the go for the first option as you can add more fields to the model and will add richness to the app.

On the other hand, if you just want it to be a array list just for sake of displaying or minimal processing, go for that option.

But if you wish to save time and add richness to the app, you can use this

https://github.com/alex/django-taggit

It is as simple as this to initialise :

```<code>from django.db import models

from taggit.managers import TaggableManager

class Food(models.Model):
# ... fields here

    tags = TaggableManager()
</code>```

and can be used in the following way :

```<code>>>> apple = Food.objects.create(name="apple")
>>> apple.tags.add("red", "green", "delicious")
>>> apple.tags.all()
[<Tag: red>, <Tag: green>, <Tag: delicious>]
</code>```

Body:
I am trying to add tags to a model for a postgres db in django and I found two solutions:

using foreign keys:

class Post(models.Model):
    tags = models.ManyToManyField('tags')
    ...

class Tag(models.Model):
    name = models.CharField(max_length=140)

using array field:

from django.contrib.postgres.fields import ArrayField

class Post(models.Model):
    tags = ArrayField(models.CharField(max_length=140))
    ...

assuming that I don't care about supporting other database-backends in my code, what is a recommended solution ?

Body:
If you want the class tags to be monitored ( For eg : how many tags, how many of a particular tag etd ) , the go for the first option as you can add more fields to the model and will add richness to the app.

On the other hand, if you just want it to be a array list just for sake of displaying or minimal processing, go for that option.

But if you wish to save time and add richness to the app, you can use this

https://github.com/alex/django-taggit

It is as simple as this to initialise :

from django.db import models

from taggit.managers import TaggableManager

class Food(models.Model):
# ... fields here

    tags = TaggableManager()

and can be used in the following way :

>>> apple = Food.objects.create(name="apple")
>>> apple.tags.add("red", "green", "delicious")
>>> apple.tags.all()
[<Tag: red>, <Tag: green>, <Tag: delicious>]


问:
How to dynamically choose the configurations based on the environment in JAVA?
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

```<code>package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}
</code>```

In my code I'm manually commenting out the configuration!

答:
In spring you can set an external configuration with properties or yaml.

Otherwise, if you need to change configuration while running the app and you're using a database, you could create a configuration table in your db with key-value configs and read them in your code.

For example, a table like this one:

```<code>CREATE TABLE configuration (
    key varchar(255),
    value varchar(255)
);
</code>```

Where key is the property name and value is the property value.

A property

```<code>environment=development
</code>```

could become

```<code>INSERT INTO configuration (key, value) VALUES('environment', 'development');
</code>```

Body:
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}

In my code I'm manually commenting out the configuration!

Body:
In spring you can set an external configuration with properties or yaml.

Otherwise, if you need to change configuration while running the app and you're using a database, you could create a configuration table in your db with key-value configs and read them in your code.

For example, a table like this one:

CREATE TABLE configuration (
    key varchar(255),
    value varchar(255)
);

Where key is the property name and value is the property value.

A property

environment=development

could become

INSERT INTO configuration (key, value) VALUES('environment', 'development');


问:
How do I know which groups each product is in?
```<code>class Product(models.Model):
    name = models.CharField(max_length=256)

class Group(models.Model):
    name = models.CharField(max_length=32, unique=False)
    products = models.ManyToManyField(Product, blank=True)
</code>```

Products in group.pk == 1:

```<code>products = Group.objects.get(pk=1).products.all().values('name')
</code>```

Result:

```<code><QuerySet [
    {"name": "product1"},
    {"name": "product2"},
    {"name": "product3"},
]
</code>```

How do I know which groups each product is in? Like this:

```<code><QuerySet [
    {"name": "product1", "groups": [{"pk": 1, "name": "group1"}]},
    {"name": "product2", "groups": []"},
    {"name": "product3", "groups": [{"pk": 1, "name": "group1"}, {"pk": 2, "name": "group2"}},
]
</code>```

Thanks!

UPD1.

If we have data:

```<code>group1 | product 1
group1 | product 2
group2 | product 2
group2 | product 3
</code>```

The idea of creating a table (html) is as follows:

/group/1:

```<code>product 1 | dropdown (group1)
product 2 | dropdown (group1, group2)
</code>```

/group/2:

```<code>product 2 | dropdown (group1, group2)
product 3 | dropdown (group2)
</code>```

答:
Once you have a Product instance:

product = Product.objects.get(pk=1)
```

<p>it knows which <code>Group</code> instances refer to it. Use the <code>group_set</code> field:</p>

<pre class="lang-python prettyprint-override"><code>groups = product.group_set.all()
</code>```

By declaring a related object (using ForeignKey or ManyToManyField), the “other end” of the relationship gets an implied field to access the instances referring to this one.

In this case, the field is named group_set and it is a model manager for Group instances that refer to this Product instance.

Body:
class Product(models.Model):
    name = models.CharField(max_length=256)

class Group(models.Model):
    name = models.CharField(max_length=32, unique=False)
    products = models.ManyToManyField(Product, blank=True)

Products in group.pk == 1:

products = Group.objects.get(pk=1).products.all().values('name')

Result:

<QuerySet [
    {"name": "product1"},
    {"name": "product2"},
    {"name": "product3"},
]

How do I know which groups each product is in? Like this:

<QuerySet [
    {"name": "product1", "groups": [{"pk": 1, "name": "group1"}]},
    {"name": "product2", "groups": []"},
    {"name": "product3", "groups": [{"pk": 1, "name": "group1"}, {"pk": 2, "name": "group2"}},
]

Thanks!

UPD1.

If we have data:

group1 | product 1
group1 | product 2
group2 | product 2
group2 | product 3

The idea of creating a table (html) is as follows:

/group/1:

product 1 | dropdown (group1)
product 2 | dropdown (group1, group2)

/group/2:

product 2 | dropdown (group1, group2)
product 3 | dropdown (group2)

Body:
Once you have a Product instance:

product = Product.objects.get(pk=1)

it knows which Group instances refer to it. Use the group_set field:

groups = product.group_set.all()

By declaring a related object (using ForeignKey or ManyToManyField), the “other end” of the relationship gets an implied field to access the instances referring to this one.

In this case, the field is named group_set and it is a model manager for Group instances that refer to this Product instance.


问:
How to finding what object groups an ip address belongs to in a Cisco ASA
I have a task to determine the use of IP's in a object group on a Cisco ASA. I am coding in python. The config has the following

```<code>object-group network VIPUSERS
description VIPUSER Addresses
network-object host 192.168.0.10
network-object host 192.168.0.11
!
object-group network USERS
description USER Addresses
network-object host 192.168.0.10
network-object host 192.168.0.11
network-object host 192.168.0.12
network-object host 192.168.0.13
network-object host 192.168.0.14
network-object host 192.168.0.15
!
object-group network SERVERS
description SERVER addresses
network-object host 192.168.100.10
network-object host 192.168.100.11
network-object host 192.168.100.12
network-object host 192.168.100.13
network-object host 192.168.100.14
network-object host 192.168.100.15
!
object-group service USER-SERVER-PORTS
service-object icmp echo
service-object icmp echo-reply
service-object tcp eq 21
service-object tcp eq 25
service-object tcp eq 80
service-object tcp eq 443
</code>```

The script takes the input 192.168.0.11. The output should be

```<code>object-group network VIPUSERS
object-group network USERS
</code>```

I can search the said input, however unable to backtrack and get the group to which it belongs. I have so far only come up with a logic to keep a variable with the value "object-group network" and parse the next lines until we get the the desired input value. Once found, print the variable.

What is the easiest way to accomplish this ?

答:
What is the easiest way to accomplish this ?

Make the computer do it. Regular expression to describe each section starting with object-group and ending with !. (NB. I put a ! at the end of your text to make all the sections fit the same pattern).

Capture the last word on the 'object-group' line, and all the following lines until the !

Then check if the content lines have the IP, if so, print the group name.

```<code>s = '''
object-group network VIPUSERS
description VIPUSER Addresses
network-object host 192.168.0.10
network-object host 192.168.0.11
!
object-group network USERS
description USER Addresses
network-object host 192.168.0.10
network-object host 192.168.0.11
network-object host 192.168.0.12
network-object host 192.168.0.13
network-object host 192.168.0.14
network-object host 192.168.0.15
!
object-group network SERVERS
description SERVER addresses
network-object host 192.168.100.10
network-object host 192.168.100.11
network-object host 192.168.100.12
network-object host 192.168.100.13
network-object host 192.168.100.14
network-object host 192.168.100.15
!
'''

import re

for m in re.finditer(r'object-group \w+ (\w+)\r?\n([^!]+)!?', s):
  group, content = m.groups()
  if '192.168.0.10' in content:
    print(group)
</code>```

Body:
I have a task to determine the use of IP's in a object group on a Cisco ASA. I am coding in python. The config has the following

object-group network VIPUSERS
description VIPUSER Addresses
network-object host 192.168.0.10
network-object host 192.168.0.11
!
object-group network USERS
description USER Addresses
network-object host 192.168.0.10
network-object host 192.168.0.11
network-object host 192.168.0.12
network-object host 192.168.0.13
network-object host 192.168.0.14
network-object host 192.168.0.15
!
object-group network SERVERS
description SERVER addresses
network-object host 192.168.100.10
network-object host 192.168.100.11
network-object host 192.168.100.12
network-object host 192.168.100.13
network-object host 192.168.100.14
network-object host 192.168.100.15
!
object-group service USER-SERVER-PORTS
service-object icmp echo
service-object icmp echo-reply
service-object tcp eq 21
service-object tcp eq 25
service-object tcp eq 80
service-object tcp eq 443

The script takes the input 192.168.0.11. The output should be

object-group network VIPUSERS
object-group network USERS

I can search the said input, however unable to backtrack and get the group to which it belongs. I have so far only come up with a logic to keep a variable with the value "object-group network" and parse the next lines until we get the the desired input value. Once found, print the variable.

What is the easiest way to accomplish this ?

Body:
What is the easiest way to accomplish this ?

Make the computer do it. Regular expression to describe each section starting with object-group and ending with !. (NB. I put a ! at the end of your text to make all the sections fit the same pattern).

Capture the last word on the 'object-group' line, and all the following lines until the !

Then check if the content lines have the IP, if so, print the group name.

s = '''
object-group network VIPUSERS
description VIPUSER Addresses
network-object host 192.168.0.10
network-object host 192.168.0.11
!
object-group network USERS
description USER Addresses
network-object host 192.168.0.10
network-object host 192.168.0.11
network-object host 192.168.0.12
network-object host 192.168.0.13
network-object host 192.168.0.14
network-object host 192.168.0.15
!
object-group network SERVERS
description SERVER addresses
network-object host 192.168.100.10
network-object host 192.168.100.11
network-object host 192.168.100.12
network-object host 192.168.100.13
network-object host 192.168.100.14
network-object host 192.168.100.15
!
'''

import re

for m in re.finditer(r'object-group \w+ (\w+)\r?\n([^!]+)!?', s):
  group, content = m.groups()
  if '192.168.0.10' in content:
    print(group)


问:
QT: Store QTextStream in QList
I'm trying to open multiple files simultaneously (random number of files) and store their textstreams in qlist for simple using in other code:

```<code>QList<QTextStream> files;
QList<QString> fnames;
fnames.append("file1.txt");
fnames.append("file2.txt");
// ..and so on with random iterations

// collect qtextsrams into qlist
foreach (QString file, fnames) {
        QFile f(file);
        f.open(QIODevice::ReadOnly);
        QTextStream textStream(&f);
        files2.append(&textStream);
}

// use qtextstreams in a loop
QList<QTextStream>::iterator i;
for (i = files.begin(); i != files.end(); ++i) {
      qDebug() << i->readLine();
}
</code>```

So i have an error:

```<code>/make debug
make -f Makefile.Debug
make[1]: Entering directory `/home/pixx/Workspace/collocs'
g++ -c -pipe -g -Wall -W -D_REENTRANT -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -Idebug -o debug/main.o main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:128: error: no matching function for call to ‘QList<QTextStream>::append(QTextStream*)’
/usr/include/qt4/QtCore/qlist.h:493: note: candidates are: void QList<T>::append(const T&) [with T = QTextStream]
/usr/include/qt4/QtCore/qlist.h:819: note:                 void QList<T>::append(const QList<T>&) [with T = QTextStream]
main.cpp:117: warning: unused variable ‘cc’
In file included from /usr/include/qt4/QtCore/QList:1,
                 from main.cpp:1:
/usr/include/qt4/QtCore/qtextstream.h: In member function ‘void QList<T>::node_copy(QList<T>::Node*, QList<T>::Node*, QList<T>::Node*) [with T = QTextStream]’:
/usr/include/qt4/QtCore/qlist.h:695:   instantiated from ‘void QList<T>::detach_helper(int) [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:709:   instantiated from ‘void QList<T>::detach_helper() [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:126:   instantiated from ‘void QList<T>::detach() [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:254:   instantiated from ‘QList<T>::iterator QList<T>::begin() [with T = QTextStream]’
main.cpp:133:   instantiated from here
/usr/include/qt4/QtCore/qtextstream.h:258: error: ‘QTextStream::QTextStream(const QTextStream&)’ is private
/usr/include/qt4/QtCore/qlist.h:386: error: within this context
/usr/include/qt4/QtCore/qtextstream.h:258: error: ‘QTextStream::QTextStream(const QTextStream&)’ is private
/usr/include/qt4/QtCore/qlist.h:399: error: within this context
make[1]: Leaving directory `/home/pixx/Workspace/collocs'
make[1]: *** [debug/main.o] Error 1
make: *** [debug] Error 2
</code>```

What should i fix?
I understand that it's very simple question, but i can't find right query for google :(

答:
The first error, namely "no matching function for call to ‘QList::append(QTextStream*)’" is caused by you using & operator in this line:

```<code>files2.append(&textStream);
</code>```

Your list is supposed to be made of QTextStream objects, not pointers to QTextStream objects.

But the real problem lies deeper. To put an object into a list, an object must have copy constructor. QTextStream doesn't have any, since it's not clear how different copies of a same text stream should work together. I suggest you create a list of pointers to text streams, as in "QList ". Of course, in that case don't forget to handle their destruction, when they are no longer needed:

```<code>foreach (QTextStream *cur, files) delete cur;
</code>```

If you need to pass this list between different parts of your code, make multiple copies of it and such, you may need smart pointers (QSharedPointer), but I can hardly think of a task where you'd need to do it to text streams.

Title: QT: Store QTextStream in QList

Body:
I'm trying to open multiple files simultaneously (random number of files) and store their textstreams in qlist for simple using in other code:

QList<QTextStream> files;
QList<QString> fnames;
fnames.append("file1.txt");
fnames.append("file2.txt");
// ..and so on with random iterations

// collect qtextsrams into qlist
foreach (QString file, fnames) {
        QFile f(file);
        f.open(QIODevice::ReadOnly);
        QTextStream textStream(&f);
        files2.append(&textStream);
}

// use qtextstreams in a loop
QList<QTextStream>::iterator i;
for (i = files.begin(); i != files.end(); ++i) {
      qDebug() <readLine();
}

So i have an error:

/make debug
make -f Makefile.Debug
make[1]: Entering directory `/home/pixx/Workspace/collocs'
g++ -c -pipe -g -Wall -W -D_REENTRANT -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -Idebug -o debug/main.o main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:128: error: no matching function for call to ‘QList<QTextStream>::append(QTextStream*)’
/usr/include/qt4/QtCore/qlist.h:493: note: candidates are: void QList<T>::append(const T&) [with T = QTextStream]
/usr/include/qt4/QtCore/qlist.h:819: note:                 void QList<T>::append(const QList<T>&) [with T = QTextStream]
main.cpp:117: warning: unused variable ‘cc’
In file included from /usr/include/qt4/QtCore/QList:1,
                 from main.cpp:1:
/usr/include/qt4/QtCore/qtextstream.h: In member function ‘void QList<T>::node_copy(QList<T>::Node*, QList<T>::Node*, QList<T>::Node*) [with T = QTextStream]’:
/usr/include/qt4/QtCore/qlist.h:695:   instantiated from ‘void QList<T>::detach_helper(int) [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:709:   instantiated from ‘void QList<T>::detach_helper() [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:126:   instantiated from ‘void QList<T>::detach() [with T = QTextStream]’
/usr/include/qt4/QtCore/qlist.h:254:   instantiated from ‘QList<T>::iterator QList<T>::begin() [with T = QTextStream]’
main.cpp:133:   instantiated from here
/usr/include/qt4/QtCore/qtextstream.h:258: error: ‘QTextStream::QTextStream(const QTextStream&)’ is private
/usr/include/qt4/QtCore/qlist.h:386: error: within this context
/usr/include/qt4/QtCore/qtextstream.h:258: error: ‘QTextStream::QTextStream(const QTextStream&)’ is private
/usr/include/qt4/QtCore/qlist.h:399: error: within this context
make[1]: Leaving directory `/home/pixx/Workspace/collocs'
make[1]: *** [debug/main.o] Error 1
make: *** [debug] Error 2

What should i fix?
I understand that it's very simple question, but i can't find right query for google :(

Body:
The first error, namely "no matching function for call to ‘QList::append(QTextStream*)’" is caused by you using & operator in this line:

files2.append(&textStream);

Your list is supposed to be made of QTextStream objects, not pointers to QTextStream objects.

But the real problem lies deeper. To put an object into a list, an object must have copy constructor. QTextStream doesn't have any, since it's not clear how different copies of a same text stream should work together. I suggest you create a list of pointers to text streams, as in "QList ". Of course, in that case don't forget to handle their destruction, when they are no longer needed:

foreach (QTextStream *cur, files) delete cur;

If you need to pass this list between different parts of your code, make multiple copies of it and such, you may need smart pointers (QSharedPointer), but I can hardly think of a task where you'd need to do it to text streams.


问:
How to printf a size_t without warning in mingw-w64 gcc 7.1?
I am using the mingw-w64 (x64) fork of minGW as prepared on nuwen.net. This is from the 7.1 version of gcc :

```<code>gcc --version
gcc (GCC) 7.1.0
</code>```

I am compiling this program:

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

int main(void)
{
    size_t a = 100;
    printf("a=%lu\n",a);
    printf("a=%llu\n",a);
    printf("a=%zu\n",a);
    printf("a=%I64u\n",a);
}
</code>```

with warnings and c11 standard:

```<code>gcc -Wall -Wextra -Wpedantic -std=c11 test_size_t.c
</code>```

and I get these warnings:

```<code>   test_size_t.c: In function 'main':
    test_size_t.c:6:14: warning: format '%lu' expects argument of type 'long unsigned int', but argument 2 has type 'size_t {aka long long unsigned int}' [-Wformat=]
      printf("a=%lu\n",a);
                ~~^
                %I64u
    test_size_t.c:6:14: warning: format '%lu' expects argument of type 'long unsigned int', but argument 2 has type 'size_t {aka long long unsigned int}' [-Wformat=]
      printf("a=%lu\n",a);
                ~~^
                %I64u
    test_size_t.c:7:14: warning: unknown conversion type character 'l' in format [-Wformat=]
      printf("a=%llu\n",a);
                  ^
    test_size_t.c:7:9: warning: too many arguments for format [-Wformat-extra-args]
      printf("a=%llu\n",a);
             ^~~~~~~~~~
    test_size_t.c:7:14: warning: unknown conversion type character 'l' in format [-Wformat=]
      printf("a=%llu\n",a);
                  ^
    test_size_t.c:7:9: warning: too many arguments for format [-Wformat-extra-args]
      printf("a=%llu\n",a);
             ^~~~~~~~~~
    test_size_t.c:8:13: warning: unknown conversion type character 'z' in format [-Wformat=]
      printf("a=%zu\n",a);
                 ^
    test_size_t.c:8:9: warning: too many arguments for format [-Wformat-extra-args]
      printf("a=%zu\n",a);
             ^~~~~~~~~
    test_size_t.c:8:13: warning: unknown conversion type character 'z' in format [-Wformat=]
      printf("a=%zu\n",a);
                 ^
    test_size_t.c:8:9: warning: too many arguments for format [-Wformat-extra-args]
      printf("a=%zu\n",a);
             ^~~~~~~~~
    test_size_t.c:9:9: warning: ISO C does not support the 'I64' ms_printf length modifier [-Wformat=]
      printf("a=%I64u\n",a);
         ^~~~~~~~~~~
    test_size_t.c:9:9: warning: ISO C does not support the 'I64' ms_printf length modifier [-Wformat=]
</code>```

I would like to printf a size_t without warning but don't know the correct format specifier in this situation.

答:
The problem is not the compiler but the C library. MinGW uses Microsoft's "Visual C Runtime" (msvcrt) which only conforms to c89 and it doesn't support the z format specifier.

Here's what you can do to safely print a size_t when using MinGW:

```<code>#include <inttypes.h>
#include <stdio.h>

#ifdef _WIN32
#  ifdef _WIN64
#    define PRI_SIZET PRIu64
#  else
#    define PRI_SIZET PRIu32
#  endif
#else
#  define PRI_SIZET "zu"
#endif

int main(void)
{
    size_t mySize = 24;

    printf("%" PRI_SIZET "\n", mySize);
}
</code>```

On win64, you would get a warning with this code, because PRIu64 expands to the msvcrt-specific I64u format specifier. But you can silence this warning with the GCC flag -Wno-pedantic-ms-format.

Note that you need a similar trick for long long (here using PRIu64 on both 32bit and 64bit windows) because msvcrt doesn't know ll either.

edit: as pointed out by @M.M in a comment, you can instead link MinGW-provided alternative stdio functions that support C11 with #define __USE_MINGW_ANSI_STDIO 1. I prefer not to link extra code if I can get around the peculiarities of msvcrt, but that's of course a matter of taste.

Body:
I am using the mingw-w64 (x64) fork of minGW as prepared on nuwen.net. This is from the 7.1 version of gcc :

gcc --version
gcc (GCC) 7.1.0

I am compiling this program:

#include <stdio.h>

int main(void)
{
    size_t a = 100;
    printf("a=%lu\n",a);
    printf("a=%llu\n",a);
    printf("a=%zu\n",a);
    printf("a=%I64u\n",a);
}

with warnings and c11 standard:

gcc -Wall -Wextra -Wpedantic -std=c11 test_size_t.c

and I get these warnings:

   test_size_t.c: In function 'main':
    test_size_t.c:6:14: warning: format '%lu' expects argument of type 'long unsigned int', but argument 2 has type 'size_t {aka long long unsigned int}' [-Wformat=]
      printf("a=%lu\n",a);
                ~~^
                %I64u
    test_size_t.c:6:14: warning: format '%lu' expects argument of type 'long unsigned int', but argument 2 has type 'size_t {aka long long unsigned int}' [-Wformat=]
      printf("a=%lu\n",a);
                ~~^
                %I64u
    test_size_t.c:7:14: warning: unknown conversion type character 'l' in format [-Wformat=]
      printf("a=%llu\n",a);
                  ^
    test_size_t.c:7:9: warning: too many arguments for format [-Wformat-extra-args]
      printf("a=%llu\n",a);
             ^~~~~~~~~~
    test_size_t.c:7:14: warning: unknown conversion type character 'l' in format [-Wformat=]
      printf("a=%llu\n",a);
                  ^
    test_size_t.c:7:9: warning: too many arguments for format [-Wformat-extra-args]
      printf("a=%llu\n",a);
             ^~~~~~~~~~
    test_size_t.c:8:13: warning: unknown conversion type character 'z' in format [-Wformat=]
      printf("a=%zu\n",a);
                 ^
    test_size_t.c:8:9: warning: too many arguments for format [-Wformat-extra-args]
      printf("a=%zu\n",a);
             ^~~~~~~~~
    test_size_t.c:8:13: warning: unknown conversion type character 'z' in format [-Wformat=]
      printf("a=%zu\n",a);
                 ^
    test_size_t.c:8:9: warning: too many arguments for format [-Wformat-extra-args]
      printf("a=%zu\n",a);
             ^~~~~~~~~
    test_size_t.c:9:9: warning: ISO C does not support the 'I64' ms_printf length modifier [-Wformat=]
      printf("a=%I64u\n",a);
         ^~~~~~~~~~~
    test_size_t.c:9:9: warning: ISO C does not support the 'I64' ms_printf length modifier [-Wformat=]

I would like to printf a size_t without warning but don't know the correct format specifier in this situation.

Body:
The problem is not the compiler but the C library. MinGW uses Microsoft's "Visual C Runtime" (msvcrt) which only conforms to c89 and it doesn't support the z format specifier.

Here's what you can do to safely print a size_t when using MinGW:

#include <inttypes.h>
#include <stdio.h>

#ifdef _WIN32
#  ifdef _WIN64
#    define PRI_SIZET PRIu64
#  else
#    define PRI_SIZET PRIu32
#  endif
#else
#  define PRI_SIZET "zu"
#endif

int main(void)
{
    size_t mySize = 24;

    printf("%" PRI_SIZET "\n", mySize);
}

On win64, you would get a warning with this code, because PRIu64 expands to the msvcrt-specific I64u format specifier. But you can silence this warning with the GCC flag -Wno-pedantic-ms-format.

Note that you need a similar trick for long long (here using PRIu64 on both 32bit and 64bit windows) because msvcrt doesn't know ll either.

edit: as pointed out by @M.M in a comment, you can instead link MinGW-provided alternative stdio functions that support C11 with #define __USE_MINGW_ANSI_STDIO 1. I prefer not to link extra code if I can get around the peculiarities of msvcrt, but that's of course a matter of taste.


问:
Sending image to Django Rest in Visual studio Xamarin
I stuck with a one problem in Visual Studio while i create an app for Android. I try to send some data (id, key and image) to the webservice (Django REST framework) and get a response. The code look like that

```<code>string requestUri = "https://www.haremtravel.com/api/new";
requestItem item = new requestItem(itemType,itemKey);
var json = JsonConvert.SerializeObject(item);
byte[] b = SystemIO.File.ReadAllBytes(filePath);
HttpContent stringContent = new StringContent(json);
HttpContent fileByteContent = new ByteArrayContent(b);
var formData = new MultipartFormDataContent();
formData.Add(stringContent);
formData.Add(fileByteContent);
HttpClient httpClient = new HttpClient();
var responseObj = httpClient.PostAsync(requestUri, formData);
</code>```

Result is "StatusCode:500, ReasonPhrase:'Internal Server Error',Version 1.1, Content:System.Net.Http.StreamContent,Headers:"
If i use something simple, for example html/php form with 2 text inputs and 1 file inputs (or plugin for Chrome "Postman") - it works.
Can anybody help me with this issue, please?

--UPDATED--

requestItem class

```<code>public class requestItem
{
    public int gameid;
    public string key;
    public requestItem(int newId, string newKey)
    {
        gameid = newId;
        key = newKey;
    }
}
</code>```

Screenshot of request in Postman
postman request

答:
Thanks for updating your question with the relevant information.

It's not necessary to serialize your data-object (the data class itself is redundant if you're not using it any other way)

Try it with this code:

```<code>        string requestUri = "https://www.haremtravel.com/api/new";
        requestItem item = new requestItem(itemType, itemKey);

        byte[] b = System.IO.File.ReadAllBytes(filePath);

        MultipartFormDataContent formData = new MultipartFormDataContent();

        formData.Add(new StringContent(item.gameid.ToString()), "gameid");
        formData.Add(new StringContent(item.key), "key");
        formData.Add(new ByteArrayContent(b, 0, b.Count()), "image");

        HttpClient httpClient = new HttpClient();
        var responseObj = httpClient.PostAsync(requestUri, formData);
</code>```

Uploading the file:

Try adding the ContentType Header with:

```<code>byte[] b = System.IO.File.ReadAllBytes(filePath);
var imageContent = new ByteArrayContent(b);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");

formData.Add(imageContent, "image");
</code>```

maybe you have to additionally add the file's name

```<code>string fileName = GetFileNameWithExtensionSomehow(filePath);
formData.Add(imageContent, "image", fileName);
</code>```

Body:
I stuck with a one problem in Visual Studio while i create an app for Android. I try to send some data (id, key and image) to the webservice (Django REST framework) and get a response. The code look like that

string requestUri = "https://www.haremtravel.com/api/new";
requestItem item = new requestItem(itemType,itemKey);
var json = JsonConvert.SerializeObject(item);
byte[] b = SystemIO.File.ReadAllBytes(filePath);
HttpContent stringContent = new StringContent(json);
HttpContent fileByteContent = new ByteArrayContent(b);
var formData = new MultipartFormDataContent();
formData.Add(stringContent);
formData.Add(fileByteContent);
HttpClient httpClient = new HttpClient();
var responseObj = httpClient.PostAsync(requestUri, formData);

Result is "StatusCode:500, ReasonPhrase:'Internal Server Error',Version 1.1, Content:System.Net.Http.StreamContent,Headers:"
If i use something simple, for example html/php form with 2 text inputs and 1 file inputs (or plugin for Chrome "Postman") - it works.
Can anybody help me with this issue, please?

--UPDATED--

requestItem class

public class requestItem
{
    public int gameid;
    public string key;
    public requestItem(int newId, string newKey)
    {
        gameid = newId;
        key = newKey;
    }
}

Screenshot of request in Postman
postman request

Body:
Thanks for updating your question with the relevant information.

It's not necessary to serialize your data-object (the data class itself is redundant if you're not using it any other way)

Try it with this code:

        string requestUri = "https://www.haremtravel.com/api/new";
        requestItem item = new requestItem(itemType, itemKey);

        byte[] b = System.IO.File.ReadAllBytes(filePath);

        MultipartFormDataContent formData = new MultipartFormDataContent();

        formData.Add(new StringContent(item.gameid.ToString()), "gameid");
        formData.Add(new StringContent(item.key), "key");
        formData.Add(new ByteArrayContent(b, 0, b.Count()), "image");

        HttpClient httpClient = new HttpClient();
        var responseObj = httpClient.PostAsync(requestUri, formData);

Uploading the file:

Try adding the ContentType Header with:

byte[] b = System.IO.File.ReadAllBytes(filePath);
var imageContent = new ByteArrayContent(b);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");

formData.Add(imageContent, "image");

maybe you have to additionally add the file's name

string fileName = GetFileNameWithExtensionSomehow(filePath);
formData.Add(imageContent, "image", fileName);


问:
Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT
Before KitKat (or before the new Gallery) the Intent.ACTION_GET_CONTENT returned a URI like this

content://media/external/images/media/3951.

Using the ContentResolver and querying for
MediaStore.Images.Media.DATA returned the file URL.

In KitKat however the Gallery returns a URI (via "Last") like this:

content://com.android.providers.media.documents/document/image:3951

How do I handle this?

答:
Building up on Paul Burke's answer I faced many problems resolving external SD card's URI path as most of the suggested "built-in" functions return paths which do not get resolved to files.

However, this is my approach of his
// TODO handle non-primary volumes.

```<code>String resolvedPath = "";
File[] possibleExtSdComposites = context.getExternalFilesDirs(null);
for (File f : possibleExtSdComposites) {
    // Reset final path
    resolvedPath = "";

    // Construct list of folders
    ArrayList<String> extSdSplit = new ArrayList<>(Arrays.asList(f.getPath().split("/")));

    // Look for folder "<your_application_id>"
    int idx = extSdSplit.indexOf(BuildConfig.APPLICATION_ID);

    // ASSUMPTION: Expected to be found at depth 2 (in this case ExtSdCard's root is /storage/0000-0000/) - e.g. /storage/0000-0000/Android/data/<your_application_id>/files
    ArrayList<String> hierarchyList = new ArrayList<>(extSdSplit.subList(0, idx - 2));

    // Construct list containing full possible path to the file
    hierarchyList.add(tail);
    String possibleFilePath = TextUtils.join("/", hierarchyList);

    // If file is found --> success
    if (idx != -1 && new File(possibleFilePath).exists()) {
        resolvedPath = possibleFilePath;
        break;
    }
}

if (!resolvedPath.equals("")) {
    return resolvedPath;
} else {
    return null;
}
</code>```

Note it depends on hierarchy which might be different on every phone manufacturer - I have not tested them all (it worked well so far on Xperia Z3 API 23 and Samsung Galaxy A3 API 23).

Please confirm if it does not perform well elsewhere.

ContentLicense: CC BY-SA 4.0

Body:
Building up on Paul Burke's answer I faced many problems resolving external SD card's URI path as most of the suggested "built-in" functions return paths which do not get resolved to files.

However, this is my approach of his
// TODO handle non-primary volumes.

String resolvedPath = "";
File[] possibleExtSdComposites = context.getExternalFilesDirs(null);
for (File f : possibleExtSdComposites) {
    // Reset final path
    resolvedPath = "";

    // Construct list of folders
    ArrayList<String> extSdSplit = new ArrayList<>(Arrays.asList(f.getPath().split("/")));

    // Look for folder "<your_application_id>"
    int idx = extSdSplit.indexOf(BuildConfig.APPLICATION_ID);

    // ASSUMPTION: Expected to be found at depth 2 (in this case ExtSdCard's root is /storage/0000-0000/) - e.g. /storage/0000-0000/Android/data/<your_application_id>/files
    ArrayList<String> hierarchyList = new ArrayList<>(extSdSplit.subList(0, idx - 2));

    // Construct list containing full possible path to the file
    hierarchyList.add(tail);
    String possibleFilePath = TextUtils.join("/", hierarchyList);

    // If file is found --> success
    if (idx != -1 && new File(possibleFilePath).exists()) {
        resolvedPath = possibleFilePath;
        break;
    }
}

if (!resolvedPath.equals("")) {
    return resolvedPath;
} else {
    return null;
}

Note it depends on hierarchy which might be different on every phone manufacturer - I have not tested them all (it worked well so far on Xperia Z3 API 23 and Samsung Galaxy A3 API 23).

Please confirm if it does not perform well elsewhere.


问:
App crashes because of "context" issue
I'm fairly new to android and having an issue grasping the concept of Contexts and all.

I have a small app that consists of 3 activities:

1- Main Activity

2- Login Activity

3- Splash Activity

I've created a number of classes that are part of MainActivity and run as part of it. One of the classes is a database helper. Database helper needs a context to use and what I do is, in MainActivity:

```<code>public static Context context;
</code>```

and in onResume I do:

```<code>@Override
public void onResume() {
    super.onResume();

    this.context = this;
}
</code>```

All activities work just fine, spalsh works, login works, everything works fine. I've defined everything in Manifest.

But randomly when I leave my app running in background for a while and do other stuff with my phone and open it up, sometimes it just crashes pointing to a function that gets "context" as an argument.

Is there anything I can do to fix this?

Thanks

答:
Avoid having static references to Context since they could cause memory leaks, you can read this blog article about it.
Since the activity is a context itself you can pass it to other classes with ActivityName.this.

Title: App crashes because of "context" issue

Body:
I'm fairly new to android and having an issue grasping the concept of Contexts and all.

I have a small app that consists of 3 activities:

1- Main Activity

2- Login Activity

3- Splash Activity

I've created a number of classes that are part of MainActivity and run as part of it. One of the classes is a database helper. Database helper needs a context to use and what I do is, in MainActivity:

public static Context context;

and in onResume I do:

@Override
public void onResume() {
    super.onResume();

    this.context = this;
}

All activities work just fine, spalsh works, login works, everything works fine. I've defined everything in Manifest.

But randomly when I leave my app running in background for a while and do other stuff with my phone and open it up, sometimes it just crashes pointing to a function that gets "context" as an argument.

Is there anything I can do to fix this?

Thanks


问:
source cantain no data row while using take asp.net
currently when the records are zero i am getting the error source
cantain no data row to manage that i have checked it count>0 but still
i am getting any idea how to solve this.

```<code>dynamic dt = ds.Tables(0);
int totalrowCount = dt.Rows.Count;

//dt.Rows.Count
//dt.Select().Take(100)
// dt.Rows.Cast(Of System.Data.DataRow)().Take(100)
DataTable dt1 = default(DataTable);
if (totalrowCount > 0) {
    dt1 = dt.AsEnumerable().Take(100).CopyToDataTable();
} else {
    dt1 = dt.AsEnumerable().CopyToDataTable();
}
</code>```

答:
Check number of rows with the following;

```<code>if (ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
</code>```

however when row nubmer<=0

```<code>dt1 = dt.AsEnumerable().CopyToDataTable();
</code>```

This line does not make sense.
Do you need to fetch null rows?

Body:
currently when the records are zero i am getting the error source
cantain no data row to manage that i have checked it count>0 but still
i am getting any idea how to solve this.

dynamic dt = ds.Tables(0);
int totalrowCount = dt.Rows.Count;

//dt.Rows.Count
//dt.Select().Take(100)
// dt.Rows.Cast(Of System.Data.DataRow)().Take(100)
DataTable dt1 = default(DataTable);
if (totalrowCount > 0) {
    dt1 = dt.AsEnumerable().Take(100).CopyToDataTable();
} else {
    dt1 = dt.AsEnumerable().CopyToDataTable();
}

Body:
Check number of rows with the following;

if (ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)

however when row nubmer<=0

dt1 = dt.AsEnumerable().CopyToDataTable();

This line does not make sense.
Do you need to fetch null rows?


问:
How to display image inside column with DT in R Markdown or shiny?
```<code>---
title: "Untitled"
runtime: shiny
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
df <- data.frame(image = "http://www.ufotm.com/data/attachment/forum/201203/11/110705gf50r55yqcka5ffz.jpg", title = "here is a title")
DT::renderDataTable(df,
                escape = FALSE,
                rownames = FALSE,
                extensions = 'Buttons', options = list(
                    dom = 'lBfrtip',
                    buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
                    )
)
```
</code>```

I have the image url. I try to insert image in a rmarkdown or shiny app. I prefer DT library because I can download excel file then. How can I do that?

PS: I want to provide excel or pdf file for my user to download as well.

I try to use DataTables Options, and find a related question. I tried the below code and it shows error.

```<code>---
    title: "Untitled"
runtime: shiny
output: html_document
---

df <- data.frame(image = "http://www.ufotm.com/data/attachment/forum/201203/11/110705gf50r55yqcka5ffz.jpg", title = "here is a title")
DT::renderDataTable(df,
                    escape = FALSE,
                    rownames = FALSE,
                    extensions = 'Buttons', options = list(
                        dom = 'lBfrtip',
                        buttons = c('copy', 'csv', 'excel', 'pdf', 'print'),
                        columnDefs = list(list(targets = 1,
                                               data = "img",
                                               render = JS(
                                                   'function ( url, type, full) {',
                                                   'return '<img height="75%" width="75%" src="'+full[7]+'"/>';',
                                                   '}'
                                               )
                        ))
                    )
)
</code>```

答:
You can use html tags and use escape = FALSE as below:

```<code>---
title: "Untitled"
runtime: shiny
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
df <- data.frame(image = c('' ), title = "here is a title")
DT::renderDataTable(df, escape = FALSE)
```
</code>```

You will get something like this:

Body:
---
title: "Untitled"
runtime: shiny
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
df <- data.frame(image = "http://www.ufotm.com/data/attachment/forum/201203/11/110705gf50r55yqcka5ffz.jpg", title = "here is a title")
DT::renderDataTable(df,
                escape = FALSE,
                rownames = FALSE,
                extensions = 'Buttons', options = list(
                    dom = 'lBfrtip',
                    buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
                    )
)
```

I have the image url. I try to insert image in a rmarkdown or shiny app. I prefer DT library because I can download excel file then. How can I do that?

PS: I want to provide excel or pdf file for my user to download as well.

I try to use DataTables Options, and find a related question. I tried the below code and it shows error.

---
    title: "Untitled"
runtime: shiny
output: html_document
---

df <- data.frame(image = "http://www.ufotm.com/data/attachment/forum/201203/11/110705gf50r55yqcka5ffz.jpg", title = "here is a title")
DT::renderDataTable(df,
                    escape = FALSE,
                    rownames = FALSE,
                    extensions = 'Buttons', options = list(
                        dom = 'lBfrtip',
                        buttons = c('copy', 'csv', 'excel', 'pdf', 'print'),
                        columnDefs = list(list(targets = 1,
                                               data = "img",
                                               render = JS(
                                                   'function ( url, type, full) {',
                                                   'return '';',
                                                   '}'
                                               )
                        ))
                    )
)

Body:
You can use html tags and use escape = FALSE as below:

---
title: "Untitled"
runtime: shiny
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
df <- data.frame(image = c('<img src="http://www.ufotm.com/data/attachment/forum/201203/11/110705gf50r55yqcka5ffz.jpg" height="52"></img>' ), title = "here is a title")
DT::renderDataTable(df, escape = FALSE)
```

You will get something like this:


问:
What does this code means?
```<code>namespace myApplication    {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}
</code>```

What is partial class Form1 : Form

and what is InitializeComponents();

and why it is used Form1 : Form instead of only Form1

答:
Let's look at partial class Form1 : Form - obviously this is declaring a class called Form1. The : Form part means that it inherits from the base class Form.

The base Form class provides lots of functionality needed by all forms - including InitializeComponents() (more on which below).

The partial keyword means that this class is only partly defined in this source file, and the compiler must look elsewhere for the remainder of the definition (in this case it will be some automatically generated code which defines amongst others all the controls you placed on your form in the designer).

InitializeComponents() is a required call in all subclasses of Form and it instructs all the components on the form to initialise, position, and display themselves as appropriate.

Title: What does this code means?

Body:
namespace myApplication    {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

What is partial class Form1 : Form

and what is InitializeComponents();

and why it is used Form1 : Form instead of only Form1