问:
How to get a part of the levels of a categorical variable?
My data set looks like the following:

```<code>        dsn                register_at
1 AC000W000014612   Thu Mar 02 21:34:30 UTC 2017
2 AC000W000016124   Tue Mar 14 19:40:57 UTC 2017
3 AC000W000016219   Tue Apr 14 19:29:10 UTC 2017
</code>```

I need to get just the month specification like Mar, Apr etc for each dsn. How do I grab only the month specification from the register at variable?

答:
For future reference, I would try to get the dates written in a more standardized format, such as year-month-day hours:minutes:seconds.

However, I know that we may not always have control over the format of the data (boo). Just thought I'd mention that, if it was in a more standardized format, the lubridate package has a function called floor_date that would accomplish this easily.

For this specific instance, you could just split the string by a space and select only the second element after that split:

```<code>> # create data frame
> # note that, per your question, dsn and register_at are factors
> d <- data.frame(dsn=factor(c("AC000W000014612", "AC000W000016124", "AC000W000016219")),
+                 register_at=factor(c("Thu Mar 02 21:34:30 UTC 2017", "Tue Mar 14 19:40:57 UTC 2017", "Tue Apr 14 19:29:10 UTC 2017")))
>
> library(stringr) # load package
> d$register_month <- str_split_fixed(as.character(d$register_at), " ", 3)[,2] # convert to character, split at a space, take the second element
> d
              dsn                  register_at register_month
1 AC000W000014612 Thu Mar 02 21:34:30 UTC 2017            Mar
2 AC000W000016124 Tue Mar 14 19:40:57 UTC 2017            Mar
3 AC000W000016219 Tue Apr 14 19:29:10 UTC 2017            Apr
</code>```

Note that register_month will be a character vector, so if you want it as a factor, you'd have to also use as.factor to get it back to a factor.

Body:
My data set looks like the following:

        dsn                register_at
1 AC000W000014612   Thu Mar 02 21:34:30 UTC 2017
2 AC000W000016124   Tue Mar 14 19:40:57 UTC 2017
3 AC000W000016219   Tue Apr 14 19:29:10 UTC 2017

I need to get just the month specification like Mar, Apr etc for each dsn. How do I grab only the month specification from the register at variable?

Body:
For future reference, I would try to get the dates written in a more standardized format, such as year-month-day hours:minutes:seconds.

However, I know that we may not always have control over the format of the data (boo). Just thought I'd mention that, if it was in a more standardized format, the lubridate package has a function called floor_date that would accomplish this easily.

For this specific instance, you could just split the string by a space and select only the second element after that split:

> # create data frame
> # note that, per your question, dsn and register_at are factors
> d <- data.frame(dsn=factor(c("AC000W000014612", "AC000W000016124", "AC000W000016219")),
+                 register_at=factor(c("Thu Mar 02 21:34:30 UTC 2017", "Tue Mar 14 19:40:57 UTC 2017", "Tue Apr 14 19:29:10 UTC 2017")))
>
> library(stringr) # load package
> d$register_month <- str_split_fixed(as.character(d$register_at), " ", 3)[,2] # convert to character, split at a space, take the second element
> d
              dsn                  register_at register_month
1 AC000W000014612 Thu Mar 02 21:34:30 UTC 2017            Mar
2 AC000W000016124 Tue Mar 14 19:40:57 UTC 2017            Mar
3 AC000W000016219 Tue Apr 14 19:29:10 UTC 2017            Apr

Note that register_month will be a character vector, so if you want it as a factor, you'd have to also use as.factor to get it back to a factor.


来源: stackexchange

问:
Large numbers conversion to Byte in Kotlin
Why does a double of 65555 converted to byte produce a result of 19 in Kotlin?

答:
Because when you convert 65555 (or 65555.0) to a binary representation it takes more than one byte. So calling .toByte() takes the lowest one, which is 19.

```<code>65555 -> Binary == 1 00000000 00010011
                   ^ ^^^^^^^^ ^^^^^^^^
                   1     0       19
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Because when you convert 65555 (or 65555.0) to a binary representation it takes more than one byte. So calling .toByte() takes the lowest one, which is 19.

65555 -> Binary == 1 00000000 00010011
                   ^ ^^^^^^^^ ^^^^^^^^
                   1     0       19


问:
How to pass all requests to handler using Visual Studio Development server?
I've got an empty ASP.NET project with  single HttpHandler, saved in Index.ashx. I want all requests to go through this,

```<code>public void ProcessRequest(HttpContext context)
</code>```

I've modified my project project properties so that it loads that handler by default. However, if I type a different Url in the browser it won't be passed through that handler. How do I get it to do that?

答:
...and to explicitly answer my question, you can add something like this to your web.config file (which can also be done through the IIS Manager GUI):

```<code><configuration>
    <system.webServer>
        <handlers>
          <add name="RequestHandler" path="*" verb="*" type="WebApplication6.RequestHandler" />
        </handlers>
    </system.webServer>
</configuration>
</code>```

where "name" is an arbitrary name and "type" is the fully-qualified class name (with namespace).

ContentLicense: CC BY-SA 2.5

Body:
I've got an empty ASP.NET project with  single HttpHandler, saved in Index.ashx. I want all requests to go through this,

public void ProcessRequest(HttpContext context)

I've modified my project project properties so that it loads that handler by default. However, if I type a different Url in the browser it won't be passed through that handler. How do I get it to do that?

Body:
...and to explicitly answer my question, you can add something like this to your web.config file (which can also be done through the IIS Manager GUI):

<configuration>
    <system.webServer>
        <handlers>
          <add name="RequestHandler" path="*" verb="*" type="WebApplication6.RequestHandler" />
        </handlers>
    </system.webServer>
</configuration>

where "name" is an arbitrary name and "type" is the fully-qualified class name (with namespace).


问:
How to save only one database in Redis?
I'm new to Redis and I have an issue related to backup.

For now, I have one instance running on a windows server. Inside this instance, I have currently one "job" that stores data in one database. I don't want this data to be backed up.

I have to create a new job. My first idea was to store the data in another database, but on the same instance. Then I would activate RDB backups on this database id.

However, when I read the redis doc, I see this command for backup:

```<code>save <seconds> <changes>
</code>```

This command just backs up all the database of the current instance.
I don't see any option design to target a specific instance, port or database. Do you know how I can isolate the two jobs, in order to be able to backup only the second ?

My boundary is that I have only one server.

Thank you guys !

答:
You CANNOT achieve that. With a single Redis instance, you can either save all databases, or save none of them.

In your case, you should create two Redis instances: one of which does no backup, while the other saves its databases to disk. Since you only have one server, you should bind these two instances to different ports.

Redis has very small memory footprint. Two instance DO NOT have performance penalty.

Title: How to save only one database in Redis?

Body:
I'm new to Redis and I have an issue related to backup.

For now, I have one instance running on a windows server. Inside this instance, I have currently one "job" that stores data in one database. I don't want this data to be backed up.

I have to create a new job. My first idea was to store the data in another database, but on the same instance. Then I would activate RDB backups on this database id.

However, when I read the redis doc, I see this command for backup:

save <seconds> <changes>

This command just backs up all the database of the current instance.
I don't see any option design to target a specific instance, port or database. Do you know how I can isolate the two jobs, in order to be able to backup only the second ?

My boundary is that I have only one server.

Thank you guys !


问:
HTML extend height of div

div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div></code>```

I use the above code to display a big div with two divs in it. For the first one I use position: absolute to place it on bottom left of the div.

How can I extend the height of the second gray one so that it's 5 pixels above the first, but without having to measure its exact height in pixel (like the pic below)? I can set height: 50px; for example but is there another way?

答:
You can use calc on the heightsetting as in my snippet below. That setting is 100% minus (20 + 10 + 2) for the height, border and bottom of the lower DIV minus (5 + 2) for the distance and the border of the first DIV minus 10px for the padding of the parent, summing up to 49px .

div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
  height: calc(100% - 49px);
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div></code>```

Title: HTML extend height of div

Body:
div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}

Test 123

A

I use the above code to display a big div with two divs in it. For the first one I use position: absolute to place it on bottom left of the div.

How can I extend the height of the second gray one so that it's 5 pixels above the first, but without having to measure its exact height in pixel (like the pic below)? I can set height: 50px; for example but is there another way?

Body:
You can use calc on the heightsetting as in my snippet below. That setting is 100% minus (20 + 10 + 2) for the height, border and bottom of the lower DIV minus (5 + 2) for the distance and the border of the first DIV minus 10px for the padding of the parent, summing up to 49px .

div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
  height: calc(100% - 49px);
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}

<div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div>


答:
That's because of a numerical conversion from a wider type to a type of a smaller size. The Double (IEEE 754 double precision number) has its integral part factored to the powers of two as
65555 = 217 + 24 + 22 + 20 = 65536 + 16 + 2 + 1, which is stored in binary form as (higher bits to lower):

```<code> ... 0 1  0 0 0 0 0 0 0 0  0 0 0 1 0 0 1 1
</code>```

When this number is converted to Byte, only its lowest 8 bits are retained:

```<code> ... _ _  _ _ _ _ _ _ _ _  0 0 0 1 0 0 1 1
</code>```

And that results into 24 + 22 + 20 = 16 + 2 + 1 = 19.

Title: Large numbers conversion to Byte in Kotlin

Body: Why does a double of 65555 converted to byte produce a result of 19 in Kotlin?

Body:
That's because of a numerical conversion from a wider type to a type of a smaller size. The Double (IEEE 754 double precision number) has its integral part factored to the powers of two as
65555 = 217 + 24 + 22 + 20 = 65536 + 16 + 2 + 1, which is stored in binary form as (higher bits to lower):

 ... 0 1  0 0 0 0 0 0 0 0  0 0 0 1 0 0 1 1

When this number is converted to Byte, only its lowest 8 bits are retained:

 ... _ _  _ _ _ _ _ _ _ _  0 0 0 1 0 0 1 1

And that results into 24 + 22 + 20 = 16 + 2 + 1 = 19.


问:
Eigen, function of RowXpr
I am using Eigen, and am currently trying to write a function to operate on rows of a matrix. I've followed the guidelines in the docs but nothing I try compiles (with either clang or g++); I'm at my wits end. How should one actually write functions which will take a RowXpr?

For reference, here is what I have tried so far:

```<code>#include <iostream>
#include <Eigen/Core>

using namespace std;
using namespace Eigen;

constexpr Eigen::StorageOptions Order = ColMajor;

using vect_t = Matrix<double, 1, 3, Order>;
using matr_t = Matrix<double, Dynamic, 3, Order>;

#define FUNC 3

#if FUNC == 1

vect_t func(const vect_t& f)
{
    return f;
}

#elif FUNC == 2

vect_t func(const Ref<vect_t>& f)
{
    return f;
}

#elif FUNC == 3

template<class D> vect_t func(const MatrixBase<D>& f)
{
    return f;
}

#endif

int main()
{
    matr_t M = matr_t::Random(5,3);
    cout << M << endl;
    cout << func( M.row(2) ) << endl;

    return 0;
}
</code>```

Thanks!

Edit:

With clang (version 3.8.0-2ubuntu4) the error I get is as below. The error is comparable with g++.

```<code>dan@dan-laptop:~/workspace/scratch$ clang++ eigen_func_test.cpp -I /home/dan/Downloads/eigen_3.3.3/ --std=c++11 && ./a.out
In file included from eigen_func_test.cpp:2:
In file included from /home/dan/Downloads/eigen_3.3.3/Eigen/Core:436:
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/PlainObjectBase.h:899:7: error: static_assert failed
      "INVALID_MATRIX_TEMPLATE_PARAMETERS"
  ...EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, (Options&RowMajor)==RowMajor)
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/util/StaticAssert.h:32:40: note: expanded from macro
      'EIGEN_STATIC_ASSERT'
    #define EIGEN_STATIC_ASSERT(X,MSG) static_assert(X,#MSG);
                                       ^             ~
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/PlainObjectBase.h:535:7: note: in instantiation of member function
      'Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 0, 1, 3> >::_check_template_params' requested here
      _check_template_params();
      ^
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/Matrix.h:379:9: note: in instantiation of function template
      specialization 'Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 0, 1, 3>
      >::PlainObjectBase<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
      : Base(other.derived())
        ^
eigen_func_test.cpp:32:9: note: in instantiation of function template specialization 'Eigen::Matrix<double, 1, 3, 0,
      1, 3>::Matrix<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
        return f;
               ^
eigen_func_test.cpp:41:10: note: in instantiation of function template specialization
      'func<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
        cout << func( M.row(2) ) << endl;
                ^
1 error generated.
</code>```

答:
If you read the part highlighted by clang

```<code>EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, (Options&RowMajor)==RowMajor)
</code>```

you see that, if a matrix has one row at compile time and more than one column, it must be RowMajor. That means, if you set Order = RowMajor or just leave out the , Order in

```<code>using vect_t = Matrix<double, 1, 3, Order>;
</code>```

your code should compile fine (it looks like everything else are just follow-up errors).

Title: Eigen, function of RowXpr

Body:
I am using Eigen, and am currently trying to write a function to operate on rows of a matrix. I've followed the guidelines in the docs but nothing I try compiles (with either clang or g++); I'm at my wits end. How should one actually write functions which will take a RowXpr?

For reference, here is what I have tried so far:

#include <iostream>
#include <Eigen/Core>

using namespace std;
using namespace Eigen;

constexpr Eigen::StorageOptions Order = ColMajor;

using vect_t = Matrix<double, 1, 3, Order>;
using matr_t = Matrix<double, Dynamic, 3, Order>;

#define FUNC 3

#if FUNC == 1

vect_t func(const vect_t& f)
{
    return f;
}

#elif FUNC == 2

vect_t func(const Ref<vect_t>& f)
{
    return f;
}

#elif FUNC == 3

template<class D> vect_t func(const MatrixBase<D>& f)
{
    return f;
}

#endif

int main()
{
    matr_t M = matr_t::Random(5,3);
    cout << M << endl;
    cout << func( M.row(2) ) << endl;

    return 0;
}

Thanks!

Edit:

With clang (version 3.8.0-2ubuntu4) the error I get is as below. The error is comparable with g++.

dan@dan-laptop:~/workspace/scratch$ clang++ eigen_func_test.cpp -I /home/dan/Downloads/eigen_3.3.3/ --std=c++11 && ./a.out
In file included from eigen_func_test.cpp:2:
In file included from /home/dan/Downloads/eigen_3.3.3/Eigen/Core:436:
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/PlainObjectBase.h:899:7: error: static_assert failed
      "INVALID_MATRIX_TEMPLATE_PARAMETERS"
  ...EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, (Options&RowMajor)==RowMajor)
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/util/StaticAssert.h:32:40: note: expanded from macro
      'EIGEN_STATIC_ASSERT'
    #define EIGEN_STATIC_ASSERT(X,MSG) static_assert(X,#MSG);
                                       ^             ~
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/PlainObjectBase.h:535:7: note: in instantiation of member function
      'Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 0, 1, 3> >::_check_template_params' requested here
      _check_template_params();
      ^
/home/dan/Downloads/eigen_3.3.3/Eigen/src/Core/Matrix.h:379:9: note: in instantiation of function template
      specialization 'Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 0, 1, 3>
      >::PlainObjectBase<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
      : Base(other.derived())
        ^
eigen_func_test.cpp:32:9: note: in instantiation of function template specialization 'Eigen::Matrix<double, 1, 3, 0,
      1, 3>::Matrix<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
        return f;
               ^
eigen_func_test.cpp:41:10: note: in instantiation of function template specialization
      'func<Eigen::Block<Eigen::Matrix<double, -1, 3, 0, -1, 3>, 1, 3, false> >' requested here
        cout << func( M.row(2) ) << endl;
                ^
1 error generated.

Body:
If you read the part highlighted by clang

EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, (Options&RowMajor)==RowMajor)

you see that, if a matrix has one row at compile time and more than one column, it must be RowMajor. That means, if you set Order = RowMajor or just leave out the , Order in

using vect_t = Matrix<double, 1, 3, Order>;

your code should compile fine (it looks like everything else are just follow-up errors).


问:
Why is the Entity Framework Table Name plural?
I am learning Entity Framework Code First.
I have created a model class named 'Category', after running update-database i find that EF name the class 'Categories'.
My Model is as Follwoing.</p>

```<code>public class Category
{
  [Key]
  public int Id { get; set; }

  [StringLength(maximumLength:50)]
  public string Name { get; set; }
}
</code>```

答: Entity Framework relies on various naming conventions used by the data context to understand the conceptual model. The entity name will be singular and the data set name will be plural, automatic migrations will create the table name as plural following the same convention.</p>

Body:
I am learning Entity Framework Code First.
I have created a model class named 'Category', after running update-database i find that EF name the class 'Categories'.
My Model is as Follwoing.

public class Category
{
  [Key]
  public int Id { get; set; }

  [StringLength(maximumLength:50)]
  public string Name { get; set; }
}


问:
Intellij IDEA can't ctrl + v a name for 'Create New Class'
I have Android Studio 2.3.1. When I create new class, In the edit box of name, I can't paste the new name!

My screenshots:

https://i.stack.imgur.com/I074x.png

Has anyone ever encountered such a situation?

Previously it can be pasted！

答: Check your installed plugins. I had mine problem resolved by disabling "Markdown Navigator". Also you can try to disable plugins one by one and restarting IDE to take effect.</p>


问:
How include 3rd party jars in maven project (compile, build, package) where adding local maven repo is not an option?
We have a git project that has some 3rd party jars which are not available in any Maven repo and are in a "lib" folder in the project. I need to include them for compiling, building and then package them into the WAR in WEB-INF/lib.

I cannot add them as a local maven repo from the command line because this projects needs to be buildable for anyone cloning the repo without requiring them to run extra commands (I have no way around this requirement).

I saw some people suggesting System scope but that then Maven won't package them into your WAR:

```<code><dependency>
    <groupId>com.roufid.tutorials</groupId>
    <artifactId>example-app</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${basedir}/lib/yourJar.jar</systemPath>
</dependency>
</code>```

How do I get these jars to be used for compiling/inspection, building and then packaged into the WAR?

答:
Use forward slash (/) to backslash () in the systemPath.</p>

```<code><dependency>
<groupId>com.roufid.tutorials</groupId>`enter code here`
<artifactId>example-app</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${basedir}\lib\yourJar.jar</systemPath>
</code>```

<p> </p>

Body:
We have a git project that has some 3rd party jars which are not available in any Maven repo and are in a "lib" folder in the project. I need to include them for compiling, building and then package them into the WAR in WEB-INF/lib.

I cannot add them as a local maven repo from the command line because this projects needs to be buildable for anyone cloning the repo without requiring them to run extra commands (I have no way around this requirement).

I saw some people suggesting System scope but that then Maven won't package them into your WAR:

<dependency>
    <groupId>com.roufid.tutorials</groupId>
    <artifactId>example-app</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${basedir}/lib/yourJar.jar</systemPath>
</dependency>

How do I get these jars to be used for compiling/inspection, building and then packaged into the WAR?

Body:
Use forward slash (/) to backslash () in the systemPath.

<dependency>
<groupId>com.roufid.tutorials</groupId>`enter code here`
<artifactId>example-app</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${basedir}\lib\yourJar.jar</systemPath>


问:
Replacing a blank space between two capital letters with an underscore
I have characters in a string that look like this:

```<code>" A E 222;CMPSC 201 orCMPSC 202"
</code>```

What I want to do is make is so that it looks like this:

```<code>" A_E_222;CMPSC_201 orCMPSC_202"
</code>```

So far I tried the following code but it only puts an underscore in front or in back so I'm not sure what else to try.

```<code>str_replace_all(x, "([A-Z][:blank:][A-Z])", "\\1_")

str_replace_all(x, "([A-Z][:blank:][:digit:])", "([A-Z][:digit:])")
</code>```

答:
We can use regex lookarounds to match space that follows a capital letter ((?<=[A-Z])) and is followed by a capital letter or number ((?=[A-Z0-9])), replace it with _

```<code>gsub("(?<=[A-Z]) (?=[A-Z0-9])", "_", v1, perl = TRUE)
#[1] " A_E_222;CMPSC_201 orCMPSC_202"
</code>```

Body:
I have characters in a string that look like this:

" A E 222;CMPSC 201 orCMPSC 202"

What I want to do is make is so that it looks like this:

" A_E_222;CMPSC_201 orCMPSC_202"

So far I tried the following code but it only puts an underscore in front or in back so I'm not sure what else to try.

str_replace_all(x, "([A-Z][:blank:][A-Z])", "\\1_")

str_replace_all(x, "([A-Z][:blank:][:digit:])", "([A-Z][:digit:])")

Body:
We can use regex lookarounds to match space that follows a capital letter ((?<=[A-Z])) and is followed by a capital letter or number ((?=[A-Z0-9])), replace it with _

gsub("(?<=[A-Z]) (?=[A-Z0-9])", "_", v1, perl = TRUE)
#[1] " A_E_222;CMPSC_201 orCMPSC_202"


问:
AEM/CQ - javax.xml.namespace can't resolve OSGI dependency
I'm using AEM 6.2 and I'm currently implementing WebService.
I included all dependency jars in OSGI bundle which I created externally and all dependency issue got resolved except one:

javax.xml.namespace,version=[1.0,2) -- Cannot be resolved

When I checked in the maven using depfinder tool, it showed me as below:

```<code><dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.fragment.ws</artifactId>
    <version>1.0.2</version>
    <scope>provided</scope>
</dependency>
</code>```

However, in my other custom project, the javax.xml.namespace is showing resolved state.

I'm stuck in this situation and any pointers will be really appreciated.

Thanks,
Jineet

答:
There are 58 artifacts in maven central that export javax.xml.namespace, with versions matching [1.0,2). A safe choice might be the wrapped javaxp-api from servicemix:

Gradle:

'org.apache.servicemix.specs:org.apache.servicemix.specs.jaxp-api-1.4:2.8.0'

Maven:

```<code><dependency>
    <groupId>org.apache.servicemix.specs</groupId>
    <artifactId>org.apache.servicemix.specs.jaxp-api-1.4</artifactId>
    <version>2.8.0</version>
</dependency>
</code>```

Body:
I'm using AEM 6.2 and I'm currently implementing WebService.
I included all dependency jars in OSGI bundle which I created externally and all dependency issue got resolved except one:

javax.xml.namespace,version=[1.0,2) -- Cannot be resolved

When I checked in the maven using depfinder tool, it showed me as below:

<dependency>
    <groupId>org.apache.sling</groupId>
    <artifactId>org.apache.sling.fragment.ws</artifactId>
    <version>1.0.2</version>
    <scope>provided</scope>
</dependency>

However, in my other custom project, the javax.xml.namespace is showing resolved state.

I'm stuck in this situation and any pointers will be really appreciated.

Thanks,
Jineet

Body:
There are 58 artifacts in maven central that export javax.xml.namespace, with versions matching [1.0,2). A safe choice might be the wrapped javaxp-api from servicemix:

Gradle:

'org.apache.servicemix.specs:org.apache.servicemix.specs.jaxp-api-1.4:2.8.0'

Maven:

<dependency>
    <groupId>org.apache.servicemix.specs</groupId>
    <artifactId>org.apache.servicemix.specs.jaxp-api-1.4</artifactId>
    <version>2.8.0</version>
</dependency>


问:
Nodejs express listener must be a function
I am using the following code to set up an express project, but I get an exception: TypeError: listener must be a function

```<code>var fs = require('fs');
var express = require('express');
var privateKey  = fs.readFileSync('C:/Node/cert/sn_com.key', 'utf8');
var certificate = fs.readFileSync('C:/Node/cert/sn_com.cer', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var app = express();
var server = require('https').createServer(app, credentials);
server.listen(8001);
</code>```

I don't understand why

答: The order of parameters to createServer should be reversed. First credentials and the express app.

Body:
I am using the following code to set up an express project, but I get an exception: TypeError: listener must be a function

var fs = require('fs');
var express = require('express');
var privateKey  = fs.readFileSync('C:/Node/cert/sn_com.key', 'utf8');
var certificate = fs.readFileSync('C:/Node/cert/sn_com.cer', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var app = express();
var server = require('https').createServer(app, credentials);
server.listen(8001);

I don't understand why


问:
2D openGL drawing lines that don't exactly fit pixel raster
I'm drawing something similar to a LED VU meter in OpenGL. Result should be like on vertical bar of this:

Unfortunately, my drawing space is restricted, and I have to fit exactly 18 bars on it. That yields a spacing between bars of 3.6 pixels.

When drawn, this causes visible differences in the gaps between lines, because the gaps are either 2 or 1 pixel wide. I'm looking for a solution to use subpixel rendering and than "fake" the lines by some kind of anti-aliasing, so that all gaps appear of the same width.

This is my code so far

```<code>glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH, GL_NICEST);
for (int i = 0; i < 18; ++i) {
            float bBottom = barBottom + i*3.6f;
            glBegin(GL_LINES);
            glLineWidth(2);
            glVertex2f(bRight,bBottom);
            glVertex2f(bLeft,bBottom);
            glEnd();
}
glDisable(GL_LINE_SMOOTH);
</code>```

Unfortunately, turning on line smoothing showed no visible effect. Any suggestions?

答: If you can't enable antialiasing for your OpenGl context, you can emulate it - it's easy with such simple graphics. When you need to draw rectangle 10.6 pixels high, draw it 10 pixels with its color and then single pixel line of intermediate color (0.6 of rectangle color and 0.4 of background color).</p>

Body:
I'm drawing something similar to a LED VU meter in OpenGL. Result should be like on vertical bar of this:

Unfortunately, my drawing space is restricted, and I have to fit exactly 18 bars on it. That yields a spacing between bars of 3.6 pixels.

When drawn, this causes visible differences in the gaps between lines, because the gaps are either 2 or 1 pixel wide. I'm looking for a solution to use subpixel rendering and than "fake" the lines by some kind of anti-aliasing, so that all gaps appear of the same width.

This is my code so far

glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH, GL_NICEST);
for (int i = 0; i < 18; ++i) {
            float bBottom = barBottom + i*3.6f;
            glBegin(GL_LINES);
            glLineWidth(2);
            glVertex2f(bRight,bBottom);
            glVertex2f(bLeft,bBottom);
            glEnd();
}
glDisable(GL_LINE_SMOOTH);

Unfortunately, turning on line smoothing showed no visible effect. Any suggestions?


问:
GitLab backup doesn't include wiki
We have GitLab CE 9.1.2 installed on our server where a backup is scheduled to run every 8:00 PM Mon-Fri. So far things are fine but yesterday we started using the Wiki. I double checked the backup file and somehow it had the exact same size as the backup the previous day (nothing was done in the system other than creating Wiki pages).

Because of that I suspected that the Wiki wasn't included in the backup process so I opened up a VM and tried to restore the backup file. After the successful operation I went over to the Wiki section of the project and it was empty.

I was reading some resources and they say the repo shouldn't be empty for the Wiki to be included but our repo is full of codes, commits, branches, issues, etc. I followed the backup instructions for the Omnibus installation because that's what we have.

```<code>0 20 * * 1-5 /opt/gitlab/bin/gitlab-rake gitlab:backup:create CRON=1
</code>```

As you could see I didn't include any SKIP environment variable so it shouldn't skip anything. Am I missing something? I followed the instructions properly. I need a full backup of the system.

答:
From the link @fedorqui provided it looks like this is an issue with the cache not being flushed out when you create a Wiki and so the backup process sees the Wiki as being empty therefore skipped.

To fix this it looks like we manually have to flush the cache ourselves.

```<code>sudo gitlab-rails console
p = Project.find_by_full_path 'namespace_path/project_path'
wiki = ProjectWiki.new p
wiki.repository.empty?
wiki.repository.expire_all_method_caches
wiki.repository.empty?
</code>```

The first time you run wiki.repository.empty? it will return true which is why the backup process skips the Wiki. After running wiki.repository.expire_all_method_caches you should be good to go (I tried this and our Wiki is now being backed up). If you'd like to confirm that everything does look good, simply run the wiki.repository.empty? again and it should return false this time.

As of June 5, 2017 it seems like the bug hasn't been fixed yet.

Update (August 22, 2017)

GitLab CE 9.5.0 has been released (changelog) which has the fix for this issue. If you don't want to manually have to expire the cache I recommend that you upgrade your GitLab installation to at least v9.5.0 and you should be fine.

ContentLicense: CC BY-SA 4.0

Title: GitLab backup doesn't include wiki

Body:
We have GitLab CE 9.1.2 installed on our server where a backup is scheduled to run every 8:00 PM Mon-Fri. So far things are fine but yesterday we started using the Wiki. I double checked the backup file and somehow it had the exact same size as the backup the previous day (nothing was done in the system other than creating Wiki pages).

Because of that I suspected that the Wiki wasn't included in the backup process so I opened up a VM and tried to restore the backup file. After the successful operation I went over to the Wiki section of the project and it was empty.

I was reading some resources and they say the repo shouldn't be empty for the Wiki to be included but our repo is full of codes, commits, branches, issues, etc. I followed the backup instructions for the Omnibus installation because that's what we have.

0 20 * * 1-5 /opt/gitlab/bin/gitlab-rake gitlab:backup:create CRON=1

As you could see I didn't include any SKIP environment variable so it shouldn't skip anything. Am I missing something? I followed the instructions properly. I need a full backup of the system.

Body:
From the link @fedorqui provided it looks like this is an issue with the cache not being flushed out when you create a Wiki and so the backup process sees the Wiki as being empty therefore skipped.

To fix this it looks like we manually have to flush the cache ourselves.

sudo gitlab-rails console
p = Project.find_by_full_path 'namespace_path/project_path'
wiki = ProjectWiki.new p
wiki.repository.empty?
wiki.repository.expire_all_method_caches
wiki.repository.empty?

The first time you run wiki.repository.empty? it will return true which is why the backup process skips the Wiki. After running wiki.repository.expire_all_method_caches you should be good to go (I tried this and our Wiki is now being backed up). If you'd like to confirm that everything does look good, simply run the wiki.repository.empty? again and it should return false this time.

As of June 5, 2017 it seems like the bug hasn't been fixed yet.

Update (August 22, 2017)

GitLab CE 9.5.0 has been released (changelog) which has the fix for this issue. If you don't want to manually have to expire the cache I recommend that you upgrade your GitLab installation to at least v9.5.0 and you should be fine.


问:
Classes residing in App_Code is not accessible
I have created a website in ASP.NET and have created a class and put it inside of the App_Code folder. However I cannot access this from my other pages. Does something need to be configured to allow this? I have made it work in previous projects, but not in this one, somehow.</p>

```<code>namespace CLIck10.App_Code
{
    public static class Glob
    {
        ...
    }
}
</code>```

答:
In my case, I couldn't get a project to build with classes defined in the App_Code folder.

Can't replicate the scenario precisely to comment, but had to close and re-open visual studio for intellisense to co-operate agree...

I noticed that when a class in the App_Code folder is set to 'Compile' instead of 'Content' (right-click it) that the errors were coming from a second version of the class... Look to the left-most of the 3 of the 3 fields between the code pane and the tab. The 'other' one was called something along the lines of 10_App_Code or similar.

To rectify the issue, I renamed the folder from App_Code to Code, explicitly set namespaces on the classes and set all of the classes to 'Compile'

Body:
I have created a website in ASP.NET and have created a class and put it inside of the App_Code folder. However I cannot access this from my other pages. Does something need to be configured to allow this? I have made it work in previous projects, but not in this one, somehow.

namespace CLIck10.App_Code
{
    public static class Glob
    {
        ...
    }
}


问:
Java - Selection Sort Algorithm
I have some questions about selection sort.I'm a little bit confused.

```<code> int [] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i<arr.length;i++)
    {
        //Assume first element is min
        min = i;//Selection sort algorithm says that find the minimum in the
                // array, but first element is not minimum.What's point here?
        for(int j = i + 1;j<arr.length;j++)
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            System.out.println(arr[i]);//I print the in ascending order
        }
    }
</code>```

Output is :

```<code>4
3
2
1
4
3
2
4
3
4
</code>```

What's wrong ?

答:
```<code>public class SelectionSort {

public static void main(String[] args) {
    int[] A = {5,4,3,2,1};
    int l = A.length;

    for (int i = 0; i < l-1; ++i ){
        int minPos = i;

        // Find the location of the minimal element
        for (int j = i + 1; j < l; ++j){
            if ( A[j] < A[minPos]){
                minPos = j;
            }
        }

        if (minPos != i){
            int temp = A[i];
            A[i] = A[minPos];
            A[minPos] = temp;
        }
    }
    System.out.println(Arrays.toString(A));
}
}
</code>```

Title: Java - Selection Sort Algorithm

Body:
I have some questions about selection sort.I'm a little bit confused.

 int [] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i<arr.length;i++)
    {
        //Assume first element is min
        min = i;//Selection sort algorithm says that find the minimum in the
                // array, but first element is not minimum.What's point here?
        for(int j = i + 1;j<arr.length;j++)
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            System.out.println(arr[i]);//I print the in ascending order
        }
    }

Output is :

4
3
2
1
4
3
2
4
3
4

What's wrong ?


问:
PHP - Session doesnt work on mobile
For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?

My session_start code on index.php

```<code>session_start();
if (isset($_SESSION['username'])){
    session_id();
}
</code>```

Whole code for login.php file

```<code><?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $UserQuery = "SELECT username FROM `members` WHERE username='$username'";
        $userTestResult = mysqli_query($connection, $UserQuery);
        $usernameTEST = mysqli_num_rows($userTestResult);
        if($usernameTEST == 1){$usernameOK = true;}

        $PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
        $result = mysqli_query($connection,$PasswordQuery);
        $row = mysqli_fetch_row($result);

        if (password_verify($password, $row[0])){$passwordOK = true;}

        if($usernameOK == true && $passwordOK == true){
            $_SESSION['username'] = $username;
        }else{
            $error_message = "Incorrect login data";
        }
    }

    if (isset($_SESSION['username'])){
        header("Location: ../");
        exit;
    }else{?>
    <form class="login-form" method="POST">
        <?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>

        <span class="placeholder">username</span>
        <input type="text" name="username" placeholder="username" required>

        <span class="placeholder">password</span>
        <input type="password" name="password" id="inputPassword" placeholder="password" required>

        <button type="submit">Login</button>
        <a class="form-link" href="register.php">Register</a>
    </form>

<?php } ?>
</code>```

答: My problem was on server-side the session.save_path not definied to my server. Thanks a lot to all, who helped me :)

Title: PHP - Session doesnt work on mobile

Body:
For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?

My session_start code on index.php

session_start();
if (isset($_SESSION['username'])){
    session_id();
}

Whole code for login.php file

<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $UserQuery = "SELECT username FROM `members` WHERE username='$username'";
        $userTestResult = mysqli_query($connection, $UserQuery);
        $usernameTEST = mysqli_num_rows($userTestResult);
        if($usernameTEST == 1){$usernameOK = true;}

        $PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
        $result = mysqli_query($connection,$PasswordQuery);
        $row = mysqli_fetch_row($result);

        if (password_verify($password, $row[0])){$passwordOK = true;}

        if($usernameOK == true && $passwordOK == true){
            $_SESSION['username'] = $username;
        }else{
            $error_message = "Incorrect login data";
        }
    }

    if (isset($_SESSION['username'])){
        header("Location: ../");
        exit;
    }else{?>
    <form class="login-form" method="POST">
        <?php if(isset($error_message)){ ?>
 <?php echo $error_message; ?>
<?php } ?>

        username
        <input type="text" name="username" placeholder="username" required>

        password
        <input type="password" name="password" id="inputPassword" placeholder="password" required>

        <button type="submit">Login</button>
        Register
    </form>

<?php } ?>


问:
Prefix only redis session keys
Is there a way to use one Predis client connection throughout an application but only prefix the session keys?

The Predis library only allows a key prefix to be defined by setting the options parameter when instantiating a client object:

```<code>$sessionClient = new Predis\Client($config, array('prefix' => 'session-'));
</code>```

I'm storing more than just sessions in one Redis instance.  So to store other values without the prefix I would think this would work:

```<code>$client = new Predis\Client($config);
</code>```

But keys are still being prefixed.  I assume Predis is sharing the connection and options across client instances.  So how can one prefix just the session keys?

答:
Found a related issue on Github with a response from the author that this won't be supported.

Predis\Session\SessionHandler accepts a client instance only for the sake of injection, but you shouldn't really reuse that client for anything else... Obviously, for very specific scenarios nothing stops you from writing your own session handler.

Title: Prefix only redis session keys

Body:
Is there a way to use one Predis client connection throughout an application but only prefix the session keys?

The Predis library only allows a key prefix to be defined by setting the options parameter when instantiating a client object:

$sessionClient = new Predis\Client($config, array('prefix' => 'session-'));

I'm storing more than just sessions in one Redis instance.  So to store other values without the prefix I would think this would work:

$client = new Predis\Client($config);

But keys are still being prefixed.  I assume Predis is sharing the connection and options across client instances.  So how can one prefix just the session keys?


问:
How can I get the content on my page to update after a select option click?
I have a feed. In that feed is a list of "posts". The feed can be updated with posts from different cities by selecting a new city from a list of select options. I use the Onymos service for my backend In my header I have interpolated the name of the default city in a title which is "new york". In the constructor I call a service I made that is set to populate the feed with new york posts on page load and update the feed on new city select.

I have the code working just fine that populates the feed with "new york" posts on load and changes the header title on new city selection. I can't however get the feed to update to show the posts from the newly selected city.
I've tried putting a page window.location.reload in different places but that either causes a crash and no page rendering or a glitchy select list that doesn't work.

HTML

```<code><ion-header >
   <ion-navbar id="navbar" class="toolbar-background">

  <ion-toolbar>

        <ion-title id="title"><p><span class="title">MyTitle</span>{{selectedCity}}</p></ion-title>
        <ion-buttons end>

<ion-icon id="icon" name="heart">Change City</ion-icon>

                <ion-select id="select" [(ngModel)]="selectedCity" (ionChange)="changeCity(selectedCity)" >
                        <ion-option value="New York">New York</ion-option>
                        <ion-option value="Philadelphia">Philadelphia</ion-option>
                        <ion-option value="Boston">Boston</ion-option>
                        <ion-option value="L.A.">L.A.</ion-option>
                        <ion-option value="San Francisco">San Francisco</ion-option>

               </ion-select>

         </ion-buttons>

      </ion-toolbar>
       </ion-navbar>

   </ion-header>

  <ion-content id="content">

     <ion-card id="card" *ngFor="let event of listOfEvents" >

       //Code for post info goes here on this card

    </ion-card>

</ion-content >
</code>```

myService.TS

```<code>import { Injectable } from '@angular/core';

declare var OnymosUtil:any;

@Injectable()
export class getPosts {
constructor(){}

     listOfEvents: Array<any> = [];

     newCity: string;

/*Below is the service that gets the posts to populate the feed. I thought I could pass it a variable that could determine reload or not*/

getPosts(selectedCity,reloadPg){

   /*should there be a page refresh here?  */

if(reloadPg == true){
window.location.reload();
}

this.newCity = selectedCity;

let that = this;

    OnymosUtil.getData(

        '/events/' + this.newCity ,

        function successCallback (listOfEventsObject) {

                for (var x in listOfEventsObject) {

                   that.listOfEvents.push(listOfEventsObject[x]);
                }

        },

        function failureCallback (error) {
            alert(error);
        },

        {

            orderByField:'createdTime',
        });

    }//end getPosts
</code>```

mainTS.

```<code>import { Component } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
import { LoadingController } from 'ionic-angular';
import { getPosts } from '../../services/getPosts.service';

 declare var OnymosUtil:any;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [getPosts]
})
export class Home {

     listOfEvents: Array<any> = [];

     selectedCity: string = 'New York';

     reloadPg: boolean;

 constructor (public navCtrl: NavController, public modalCtrl: ModalController, public loading: LoadingController, public getPostSrvc: getPosts) {

getPostSrvc.getPosts(this.selectedCity); /*this populates the feed with the default city's posts from New York*/

this.listOfEvents = getPostSrvc.listOfEvents;

}// end of constructor

/*here is where I tried to use a reload:*/

changeCity(selectedCity){

this.reloadPg = true;

           this.getPostSrvc.getPosts(selectedCity, this.reloadPg);

      };

}//close class
</code>```

答:
Here's a basic example on how to update the list. Granted the events are hard coded, but the idea remains the same.

```<code>import {Component, NgModule, VERSION, onInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

const events = [
  {
    city: 'New York',
    events: [
      {
        title: 'Comedy in Broadway',
        description: 'Get ready to pee your pants laughing'
      },
      {
        title: 'Puertorican Day Parad',
        description: 'Lots of traffic, loud music, great party!'
      }
    ]
  },
  {
    city: 'Chicago',
    events: [
      {
        title: 'Al Capone Memorial',
        description: 'Go back to the days of prohibition and how the gangsters ruled the city'
      },
      {
        title: 'White Sox vs Bears',
        description: 'Which is worse?'
      }
    ]
  }
];

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>City: {{ currentEvent.city }}</h2>
      <ul>
        <li *ngFor="let e of currentEvent.events">
          <h3> {{ e.title }} </h3>
          <div>
            {{ e.description }}
          </div>
        </li>
      </ul>
    </div>
    <div>
      <button (click)="changeCity('Chicago')">View Chicago Events</button>
      <button (click)="changeCity('New York')">View New York Events</button>
    </div>
  `,
})
export class App implements OnInit{
  name:string;
  currentEvent;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  ngOnInit() {
    this.currentEvent = events.filter(event => event.city === 'New York')[0];
    console.log(this.currentEvent);
  }

  changeCity(city) {
    this.currentEvent = events.filter(event => event.city === city)[0];
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
</code>```

Working Plnkr

In your case, instead of using .filter you would get the data from the service.

EDIT WITH SERVICE

*app.service.ts**

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AppService {
  constructor(private http: Http) {}

  getAllEvents(): Promise<any>{
    return this.http.get('dummy_data.json').toPromise();
  }

  getEventsForCity(city): Promise<Array<any>> {
    let data = [];
    return new Promise((resolve, reject) => {
      this.getAllEvents().then(events => {
        events = events.json();
        data = events.filter(event => event.city === city)[0];
        if(!data) {
          return reject();
        }
        console.log(data);
        resolve(data):
      });
    });
  }
}
</code>```

app.ts

```<code>//our root app component
import {Component, NgModule, VERSION, onInit} from '@angular/core'
import { HttpModule } from '@angular/http';
import {BrowserModule} from '@angular/platform-browser'
import { AppService } from './app.service';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>City: {{ currentEvent.city }}</h2>
      <ul>
        <li *ngFor="let e of currentEvent.events">
          <h3> {{ e.title }} </h3>
          <div>
            {{ e.description }}
          </div>
        </li>
      </ul>
    </div>
    <div>
      <button (click)="changeCity('Chicago')">View Chicago Events</button>
      <button (click)="changeCity('New York')">View New York Events</button>
    </div>
  `,
})
export class App implements OnInit{
  currentEvent = {
    currentCity: '',
    events: []
  };
  constructor(private appSvc: AppService) {

  }

  ngOnInit() {
    this.appSvc.getAllEvents()
      .then(events => {
        events = events.json();
        this.currentEvent = events.filter(event => event.city === 'New York')[0];
      });
  }

  changeCity(city) {
    this.appSvc.getEventsForCity(city).then(events => this.currentEvent = events);
  }
}

@NgModule({
  imports: [ BrowserModule, HttpModule ],
  declarations: [ App ],
  bootstrap: [ App ],
  providers: [ AppService ]
})
export class AppModule {}
</code>```

Service Plunkr

Body:
I have a feed. In that feed is a list of "posts". The feed can be updated with posts from different cities by selecting a new city from a list of select options. I use the Onymos service for my backend In my header I have interpolated the name of the default city in a title which is "new york". In the constructor I call a service I made that is set to populate the feed with new york posts on page load and update the feed on new city select.

I have the code working just fine that populates the feed with "new york" posts on load and changes the header title on new city selection. I can't however get the feed to update to show the posts from the newly selected city.
I've tried putting a page window.location.reload in different places but that either causes a crash and no page rendering or a glitchy select list that doesn't work.

HTML

<ion-header >
   <ion-navbar id="navbar" class="toolbar-background">

  <ion-toolbar>

        <ion-title id="title">
MyTitle{{selectedCity}}
</ion-title>
        <ion-buttons end>

<ion-icon id="icon" name="heart">Change City</ion-icon>

                <ion-select id="select" [(ngModel)]="selectedCity" (ionChange)="changeCity(selectedCity)" >
                        <ion-option value="New York">New York</ion-option>
                        <ion-option value="Philadelphia">Philadelphia</ion-option>
                        <ion-option value="Boston">Boston</ion-option>
                        <ion-option value="L.A.">L.A.</ion-option>
                        <ion-option value="San Francisco">San Francisco</ion-option>

               </ion-select>

         </ion-buttons>

      </ion-toolbar>
       </ion-navbar>

   </ion-header>

  <ion-content id="content">

     <ion-card id="card" *ngFor="let event of listOfEvents" >

       //Code for post info goes here on this card

    </ion-card>

</ion-content >

myService.TS

import { Injectable } from '@angular/core';

declare var OnymosUtil:any;

@Injectable()
export class getPosts {
constructor(){}

     listOfEvents: Array<any> = [];

     newCity: string;

/*Below is the service that gets the posts to populate the feed. I thought I could pass it a variable that could determine reload or not*/

getPosts(selectedCity,reloadPg){

   /*should there be a page refresh here?  */

if(reloadPg == true){
window.location.reload();
}

this.newCity = selectedCity;

let that = this;

    OnymosUtil.getData(

        '/events/' + this.newCity ,

        function successCallback (listOfEventsObject) {

                for (var x in listOfEventsObject) {

                   that.listOfEvents.push(listOfEventsObject[x]);
                }

        },

        function failureCallback (error) {
            alert(error);
        },

        {

            orderByField:'createdTime',
        });

    }//end getPosts

mainTS.

import { Component } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
import { LoadingController } from 'ionic-angular';
import { getPosts } from '../../services/getPosts.service';

 declare var OnymosUtil:any;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [getPosts]
})
export class Home {

     listOfEvents: Array<any> = [];

     selectedCity: string = 'New York';

     reloadPg: boolean;

 constructor (public navCtrl: NavController, public modalCtrl: ModalController, public loading: LoadingController, public getPostSrvc: getPosts) {

getPostSrvc.getPosts(this.selectedCity); /*this populates the feed with the default city's posts from New York*/

this.listOfEvents = getPostSrvc.listOfEvents;

}// end of constructor

/*here is where I tried to use a reload:*/

changeCity(selectedCity){

this.reloadPg = true;

           this.getPostSrvc.getPosts(selectedCity, this.reloadPg);

      };

}//close class

Body:
Here's a basic example on how to update the list. Granted the events are hard coded, but the idea remains the same.

import {Component, NgModule, VERSION, onInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

const events = [
  {
    city: 'New York',
    events: [
      {
        title: 'Comedy in Broadway',
        description: 'Get ready to pee your pants laughing'
      },
      {
        title: 'Puertorican Day Parad',
        description: 'Lots of traffic, loud music, great party!'
      }
    ]
  },
  {
    city: 'Chicago',
    events: [
      {
        title: 'Al Capone Memorial',
        description: 'Go back to the days of prohibition and how the gangsters ruled the city'
      },
      {
        title: 'White Sox vs Bears',
        description: 'Which is worse?'
      }
    ]
  }
];

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>City: {{ currentEvent.city }}</h2>
      <ul>
        <li *ngFor="let e of currentEvent.events">
          <h3> {{ e.title }} </h3>
          <div>
            {{ e.description }}
          </div>
        </li>
      </ul>
    </div>
    <div>
      <button (click)="changeCity('Chicago')">View Chicago Events</button>
      <button (click)="changeCity('New York')">View New York Events</button>
    </div>
  `,
})
export class App implements OnInit{
  name:string;
  currentEvent;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  ngOnInit() {
    this.currentEvent = events.filter(event => event.city === 'New York')[0];
    console.log(this.currentEvent);
  }

  changeCity(city) {
    this.currentEvent = events.filter(event => event.city === city)[0];
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Working Plnkr

In your case, instead of using .filter you would get the data from the service.

EDIT WITH SERVICE

*app.service.ts**

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AppService {
  constructor(private http: Http) {}

  getAllEvents(): Promise<any>{
    return this.http.get('dummy_data.json').toPromise();
  }

  getEventsForCity(city): Promise<Array<any>> {
    let data = [];
    return new Promise((resolve, reject) => {
      this.getAllEvents().then(events => {
        events = events.json();
        data = events.filter(event => event.city === city)[0];
        if(!data) {
          return reject();
        }
        console.log(data);
        resolve(data):
      });
    });
  }
}

app.ts

//our root app component
import {Component, NgModule, VERSION, onInit} from '@angular/core'
import { HttpModule } from '@angular/http';
import {BrowserModule} from '@angular/platform-browser'
import { AppService } from './app.service';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>City: {{ currentEvent.city }}</h2>
      <ul>
        <li *ngFor="let e of currentEvent.events">
          <h3> {{ e.title }} </h3>
          <div>
            {{ e.description }}
          </div>
        </li>
      </ul>
    </div>
    <div>
      <button (click)="changeCity('Chicago')">View Chicago Events</button>
      <button (click)="changeCity('New York')">View New York Events</button>
    </div>
  `,
})
export class App implements OnInit{
  currentEvent = {
    currentCity: '',
    events: []
  };
  constructor(private appSvc: AppService) {

  }

  ngOnInit() {
    this.appSvc.getAllEvents()
      .then(events => {
        events = events.json();
        this.currentEvent = events.filter(event => event.city === 'New York')[0];
      });
  }

  changeCity(city) {
    this.appSvc.getEventsForCity(city).then(events => this.currentEvent = events);
  }
}

@NgModule({
  imports: [ BrowserModule, HttpModule ],
  declarations: [ App ],
  bootstrap: [ App ],
  providers: [ AppService ]
})
export class AppModule {}

Service Plunkr


问:
Jekyll front matter output count
I'm working on jekyll theme design and I have .yml file stored the data (File name : games.yml) and has data as follows

```<code>---
- name: NFS
  year: 2015
  id: NFS15
  link: http://www.ecample.com/
  date: August 3-4, 2017
  categories: Racing

etc
</code>```

I'm trying to output the categories in sidebar with number of count in each category. e.g:

```<code>Racing (3)
Shooter (6)
Sports (5)
etc
</code>```

How can I achieve this?

My HTML output code:

```<code>      <a href="javascript:;" class="categories-list-item" cate="All">
        All<span class="my-badge"> {{site.data.games | size}}</span>
      </a>
      {% for cat in site.data.games %}
        <a href="javascript:;" class="categories-list-item" cate="{{ cat.categories}}">
          {{ cat.categories }} <span class="my-badge">{{ cat.categories | size }}</span>
        </a>
      {% endfor %}
</code>```

Now I get the result with entire category list e.g:

```<code>Racing
Racing
Racing
Shooter
Shooter
Shooter...
</code>```

and so on each count

答:
You can achieve this easily by using the group_by_exp native filter from Jekyll:

```<code>{% assign games = site.data.games | group_by_exp: "game", "game.categories" %}
{% for category in games %}
  <a href="javascript:;" class="categories-list-item" cate="{{ category.name }}">
    {{ category.name }} <span class="my-badge">{{ category.size }}</span>
  </a>
{% endfor %}
</code>```

Title: Jekyll front matter output count

Body:
I'm working on jekyll theme design and I have .yml file stored the data (File name : games.yml) and has data as follows

---
- name: NFS
  year: 2015
  id: NFS15
  link: http://www.ecample.com/
  date: August 3-4, 2017
  categories: Racing

etc

I'm trying to output the categories in sidebar with number of count in each category. e.g:

Racing (3)
Shooter (6)
Sports (5)
etc

How can I achieve this?

My HTML output code:

        All {{site.data.games | size}}

      {% for cat in site.data.games %}

          {{ cat.categories }} {{ cat.categories | size }}

      {% endfor %}

Now I get the result with entire category list e.g:

Racing
Racing
Racing
Shooter
Shooter
Shooter...

and so on each count

Body:
You can achieve this easily by using the group_by_exp native filter from Jekyll:

{% assign games = site.data.games | group_by_exp: "game", "game.categories" %}
{% for category in games %}
  <a href="javascript:;" class="categories-list-item" cate="{{ category.name }}">
    {{ category.name }} <span class="my-badge">{{ category.size }}</span>
  </a>
{% endfor %}


问:
Append an ActiveRecord::Relation object with single ActiveRecord object
I need to append a single ActiveRecord object onto a loaded ActiveRecord::Relation.

E.g:

class BooksController < ApplicationController
  def index
    @books = Book.where(author: User.find(params[:user_id]))
    @books << Book.find_by_name("One More Book")
  end
end
```

<p>As shown above, I have tried ActiveRecord's <code><<</code> method, but it returns the error:</p>

```NoMethodError: undefined method `<<' for #<Book::ActiveRecord_Relation:0x007f9fbdc6db80>
```

Is there an elegant way of doing this?

Thanks!

答:
Since this is rails 5 you can use the or method

```<code>Books.where(author: User.find(params[:user_id])).or.where(name: "One More Book")
</code>```

Body:
I need to append a single ActiveRecord object onto a loaded ActiveRecord::Relation.

E.g:

class BooksController < ApplicationController
  def index
    @books = Book.where(author: User.find(params[:user_id]))
    @books << Book.find_by_name("One More Book")
  end
end

As shown above, I have tried ActiveRecord's << method, but it returns the error:

NoMethodError: undefined method `<<' for #<Book::ActiveRecord_Relation:0x007f9fbdc6db80>

Is there an elegant way of doing this?

Thanks!

Body:
Since this is rails 5 you can use the or method

Books.where(author: User.find(params[:user_id])).or.where(name: "One More Book")


问:
Scrub lead against National DNC
Scrub lead against National DNC
What does this mean?
I have Ringless VoiceMail API
and some of settings is this

" scrub_nat_dnc': true, //# Scrub lead against National DNC "

Should I turn this to true?

答:
The DNC is the do not call list.

In the Unites States, by law, you have to 'scrub' the phone numbers you are dialling against a list of people and businesses who have opted out of receiving calls. They pay a fee to list themselves in either the national don't call list or the state don't call list (USA) (there are two). A violation of the law results in a $500 penalty per call and a class action suit does not have to be used to sue. You can set your software as you like but if you're list isn't scrubbed it won't change anything.

Title: Scrub lead against National DNC


问:
How to remove item from recyclerView in android
In my application I should use recyclerView and remove some items.

I want remove some items from recyclerview and for this I write below code in Adapter :

```<code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private Context context;
    private List<TvTonightResult> model;

    public MyAdapter (Context context, List<TvTonightResult> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_tv_tonight, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, final int position) {

        holder.tvTonightTitle.setText(Html.fromHtml(model.get(position).getName()));
        Glide.with(context)
                .load(model.get(position).getImageUrl())
                .placeholder(R.drawable.default_image)
                .override(600, 900)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.tvTonightImage);

        long time = 5 * 1000;
        holder.tvTonightTimeCounter.start(time);
        holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                removeItem(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return 4;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView tvTonightImage, tvTonightChannel;
        private TextView tvTonightTitle, tvTonightDate;
        private CountdownView tvTonightTimeCounter;

        public ViewHolder(View itemView) {
            super(itemView);

            tvTonightImage = (ImageView) itemView.findViewById(R.id.row_tvTonightImage);
            tvTonightChannel = (ImageView) itemView.findViewById(R.id.row_tvTonightChannelImage);
            tvTonightTitle = (TextView) itemView.findViewById(R.id.row_tvTonightTitle);
            tvTonightTimeCounter = (CountdownView) itemView.findViewById(R.id.row_tvTonightTime);

        }
    }

    private void removeItem(int position) {
        model.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, model.size());
    }
}
</code>```

I want when run this code, remove item :

```<code>holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
                @Override
                public void onEnd(CountdownView cv) {
                    removeItem(position);
                }
            });
</code>```

But show me this error :

```<code>FATAL EXCEPTION: main
Process: com.example.app, PID: 9711
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.remove(ArrayList.java:477)
    at com.example.app.Adapters.TvTonightAdapter.removeItem(TvTonightAdapter.java:102)
    at com.example.app.Adapters.TvTonightAdapter.access$300(MyAdapter.java:29)
    at com.example.app.Adapters.TvTonightAdapter$2.onEnd(MyAdapter.java:74)
    at com.example.app.Utils.Componenets.CountDownTimer.CountdownView$1.onFinish(CountdownView.java:129)
    at com.example.app.Utils.Componenets.CountDownTimer.CustomCountDownTimer$1.handleMessage(CustomCountDownTimer.java:74)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6247)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
</code>```

How can I fix this error and remove item from recyclerview?

答:
just try ,

```<code>int actualPosition = holder.getAdapterPosition();
</code>```

in your removeItem() method and replace position with actualPosition.

like ,

```<code>  private void removeItem(int position) {
    int actualPosition = holder.getAdapterPosition();
    model.remove(actualPosition);
    notifyItemRemoved(actualPosition);
    notifyItemRangeChanged(actualPosition, model.size());
}
</code>```

Body:
In my application I should use recyclerView and remove some items.

I want remove some items from recyclerview and for this I write below code in Adapter :

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private Context context;
    private List<TvTonightResult> model;

    public MyAdapter (Context context, List<TvTonightResult> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_tv_tonight, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, final int position) {

        holder.tvTonightTitle.setText(Html.fromHtml(model.get(position).getName()));
        Glide.with(context)
                .load(model.get(position).getImageUrl())
                .placeholder(R.drawable.default_image)
                .override(600, 900)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.tvTonightImage);

        long time = 5 * 1000;
        holder.tvTonightTimeCounter.start(time);
        holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                removeItem(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return 4;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView tvTonightImage, tvTonightChannel;
        private TextView tvTonightTitle, tvTonightDate;
        private CountdownView tvTonightTimeCounter;

        public ViewHolder(View itemView) {
            super(itemView);

            tvTonightImage = (ImageView) itemView.findViewById(R.id.row_tvTonightImage);
            tvTonightChannel = (ImageView) itemView.findViewById(R.id.row_tvTonightChannelImage);
            tvTonightTitle = (TextView) itemView.findViewById(R.id.row_tvTonightTitle);
            tvTonightTimeCounter = (CountdownView) itemView.findViewById(R.id.row_tvTonightTime);

        }
    }

    private void removeItem(int position) {
        model.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, model.size());
    }
}

I want when run this code, remove item :

holder.tvTonightTimeCounter.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
                @Override
                public void onEnd(CountdownView cv) {
                    removeItem(position);
                }
            });

But show me this error :

FATAL EXCEPTION: main
Process: com.example.app, PID: 9711
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.remove(ArrayList.java:477)
    at com.example.app.Adapters.TvTonightAdapter.removeItem(TvTonightAdapter.java:102)
    at com.example.app.Adapters.TvTonightAdapter.access$300(MyAdapter.java:29)
    at com.example.app.Adapters.TvTonightAdapter$2.onEnd(MyAdapter.java:74)
    at com.example.app.Utils.Componenets.CountDownTimer.CountdownView$1.onFinish(CountdownView.java:129)
    at com.example.app.Utils.Componenets.CountDownTimer.CustomCountDownTimer$1.handleMessage(CustomCountDownTimer.java:74)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6247)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

How can I fix this error and remove item from recyclerview?

Body:
just try ,

int actualPosition = holder.getAdapterPosition();

in your removeItem() method and replace position with actualPosition.

like ,

  private void removeItem(int position) {
    int actualPosition = holder.getAdapterPosition();
    model.remove(actualPosition);
    notifyItemRemoved(actualPosition);
    notifyItemRangeChanged(actualPosition, model.size());
}


问:
RFC822 to date format using asp
I try converting RFC822 date format (from rss) into a standard date/time format
using asp3.

Thanks

答:
```<code>function RFC822_to_date (orginalDate )
 tempDate = trim(right(orginalDate ,(len(orginalDate )-instr(orginalDate,","))))
 tempDate  = left(tempDate ,(len(tempDate)-5))
 tempDate  = cdate(tempDate )
 RFC822_to_date  = day(tempDate )&"-"&month(tempDate )&"-"&year(tempDate )&" "&hour(tempDate )&":"&minute(tempDate )&":00"
end function
</code>```

Title: RFC822 to date format using asp


问:
Referencing objects in HTML in Angular2
I am fetching data from an api server and storing it as a object in TypeScript, I need help referencing that data in HTML as a key and value pair.

TypeScript:

```<code>if (x.AttributeTemplateId==templateId) {
  x['AttributeTemplateValue'].forEach(function(x){
      console.log('hello');
      if (x.AttributeTemplateId==templateId){
        console.log(templateId);
     (function(y){
        console.log("hello2");
       newName.push(y.CodeSet);
       newValue.push(y.CodeValue);
      //  console.log([newAttributes]);
      })(x);
       }
  })
}
})
newName = this.name;
newValue = this.value;
this.attributes = this.name.reduce((acc, value, i) => (acc[value] = this.value[i], acc), {});
console.log(this.attributes);
}
</code>```

My data is in this.attributes and it looks like this

I want to put key and value in a table like

```<code><table>
  <tr>
    <th> Name </th>
    <th> Value </th>
  </tr>
  <tr key>
    <td value > </td>
  </tr>-->
</table>
</code>```

How would I achieve this in Angular2 ?

答:
step 1: Create a custom pipe that stores all the object keys and values in an array and returns them just like this

```<code>import { PipeTransform, Pipe} from '@angular/core';

@Pipe({name: objKeys})
export calss objKeysPipe implements PipeTransform {
  transform(value, arguments: string[]) :any {
    let keys= [];
    for (let k in value){
    keys.push({key: k, value: value[k]});
  }
  return keys;
}
</code>```

setp 2: in your component template you do the folowing

```<code><table>
  <tr *ngFor="let att of attributes | objKeys">
  <th>{{att.key}}</th>
  <th>{{att.value}}</th>
  </tr>
</table>
</code>```

Title: Referencing objects in HTML in Angular2

Body:
I am fetching data from an api server and storing it as a object in TypeScript, I need help referencing that data in HTML as a key and value pair.

TypeScript:

if (x.AttributeTemplateId==templateId) {
  x['AttributeTemplateValue'].forEach(function(x){
      console.log('hello');
      if (x.AttributeTemplateId==templateId){
        console.log(templateId);
     (function(y){
        console.log("hello2");
       newName.push(y.CodeSet);
       newValue.push(y.CodeValue);
      //  console.log([newAttributes]);
      })(x);
       }
  })
}
})
newName = this.name;
newValue = this.value;
this.attributes = this.name.reduce((acc, value, i) => (acc[value] = this.value[i], acc), {});
console.log(this.attributes);
}

My data is in this.attributes and it looks like this

I want to put key and value in a table like

     Name
     Value

-->

How would I achieve this in Angular2 ?

Body:
step 1: Create a custom pipe that stores all the object keys and values in an array and returns them just like this

import { PipeTransform, Pipe} from '@angular/core';

@Pipe({name: objKeys})
export calss objKeysPipe implements PipeTransform {
  transform(value, arguments: string[]) :any {
    let keys= [];
    for (let k in value){
    keys.push({key: k, value: value[k]});
  }
  return keys;
}

setp 2: in your component template you do the folowing

<table>
  <tr *ngFor="let att of attributes | objKeys">
  <th>{{att.key}}</th>
  <th>{{att.value}}</th>
  </tr>
</table>


问:
How to invoke PostgreSQL function using spring jdbctemplate instead of direct insert query in Java?
I am new to PostgreSQL. I need to call postgresql function from spring jdbctemplate for storing Employee table details. Below is my code in which I am using insert query to store the Employee details. I need to replace insert query with the Postgresql function-"UpdateEmployee".</p>

```<code>@Autowired
JdbcTemplate postgressqljdbctemplate;

@Override
public void update(Employee employee) {
String SQL = "insert into employee(Id, name, age, salary) values (?,?,?,?)";
postgressqljdbctemplate.update(SQL, new Object[] { employee.getId(), employee.getName(),
employee.getAge(), employee.getSalary()});
}
</code>```

答:
Ok, the first thing you should do is design that function for insert/update data. Postgres supports many languages for that, but the most popular one is plpgsql.

The function itself might look like:

```<code>CREATE OR REPLACE FUNCTION update_employee(p_id INT, p_name VARCHAR(255), p_age INT, p_salary DECIMAL)
  RETURNS INT
LANGUAGE plpgsql
AS $$
BEGIN
  IF p_id IS NULL
  THEN
    INSERT INTO employee (name, age, salary) VALUES (p_name, p_age, p_salary) RETURNING id INTO p_id;
  ELSE
    UPDATE employee
    SET name = p_name, age = p_age, salary = p_salary
    WHERE id = p_id;
  END IF;
  RETURN p_id;
END;
$$;
</code>```

Now if you call this function with null as ID it will insert the data, otherwise data will be found by specified id and updated.

In both cases you'll get the ID of modified record back.

SELECT update_employee(NULL, 'John', 42, 100000);  -- insert (returns 1)
SELECT update_employee(1, 'John Smith', 42, 200000); -- update previous record
```

<p>Probably it would be better to separate insert function from update, but it is just a sample.</p>

<p>So, with that you can call the function from spring using for example SimpleJdbcCall:</p>

```final SimpleJdbcCall updateEmployeeCall = new SimpleJdbcCall(jdbcTemplate).withFunctionName("update_employee");
final Map<String, Object> params = new HashMap<>();
params.put("p_id", null);
params.put("p_name", "John");
params.put("p_age", 28);
params.put("p_salary", 150000);

final Map<String, Object> result = updateEmployeeCall.execute(params);
System.out.println(result.get("returnvalue"));
```

Body:
I am new to PostgreSQL. I need to call postgresql function from spring jdbctemplate for storing Employee table details. Below is my code in which I am using insert query to store the Employee details. I need to replace insert query with the Postgresql function-"UpdateEmployee".

@Autowired
JdbcTemplate postgressqljdbctemplate;

@Override
public void update(Employee employee) {
String SQL = "insert into employee(Id, name, age, salary) values (?,?,?,?)";
postgressqljdbctemplate.update(SQL, new Object[] { employee.getId(), employee.getName(),
employee.getAge(), employee.getSalary()});
}

Body:
Ok, the first thing you should do is design that function for insert/update data. Postgres supports many languages for that, but the most popular one is plpgsql.

The function itself might look like:

CREATE OR REPLACE FUNCTION update_employee(p_id INT, p_name VARCHAR(255), p_age INT, p_salary DECIMAL)
  RETURNS INT
LANGUAGE plpgsql
AS $$
BEGIN
  IF p_id IS NULL
  THEN
    INSERT INTO employee (name, age, salary) VALUES (p_name, p_age, p_salary) RETURNING id INTO p_id;
  ELSE
    UPDATE employee
    SET name = p_name, age = p_age, salary = p_salary
    WHERE id = p_id;
  END IF;
  RETURN p_id;
END;
$$;

Now if you call this function with null as ID it will insert the data, otherwise data will be found by specified id and updated.

In both cases you'll get the ID of modified record back.

SELECT update_employee(NULL, 'John', 42, 100000);  -- insert (returns 1)
SELECT update_employee(1, 'John Smith', 42, 200000); -- update previous record

Probably it would be better to separate insert function from update, but it is just a sample.

So, with that you can call the function from spring using for example SimpleJdbcCall:

final SimpleJdbcCall updateEmployeeCall = new SimpleJdbcCall(jdbcTemplate).withFunctionName("update_employee");
final Map<String, Object> params = new HashMap<>();
params.put("p_id", null);
params.put("p_name", "John");
params.put("p_age", 28);
params.put("p_salary", 150000);

final Map<String, Object> result = updateEmployeeCall.execute(params);
System.out.println(result.get("returnvalue"));


问:
Why is $MyInvocation.ScriptName not set and string comparisons?
This began as an effort to have all four (4) of the PowerShell profile scripts identify themselves and their location.

$MyInvocation.ScriptName was suggested for getting the script name, but I have yet to see it be anything other than an empty string. No, not $null, empty (''). This seems counter to many suggestions here on SO.

My first assumption was that $MyInvocation.ScriptName was $null, but that is not the case. To my surprise however, it is considered to be -lt 0. What is the rationale for comparing a String to an Int32?

I did find $MyInvocation.InvocationName which appears to give the script name, but not a directory path to it.

```<code>PS C:\Users\lit\Documents\PowerShell> Get-Content .\profile.ps1
Write-Host "Current User, All Hosts @ $(Split-Path -Parent $MyInvocation.MyCommand.Definition)\$(Split-Path -Leaf $MyInvocation.MyCommand.Definition)"
Write-Host "`$MyInvocation.ScriptName is $MyInvocation.ScriptName"
Write-Host "`$MyInvocation.ScriptName -eq `$null results in $($MyInvocation.ScriptName -eq $null)"
Write-Host "`$($MyInvocation.ScriptName -eq 0) results in $($MyInvocation.ScriptName -eq 0)"
Write-Host "`$($MyInvocation.ScriptName -lt 0) results in $($MyInvocation.ScriptName -lt 0)"
Write-Host "`$($MyInvocation.ScriptName -eq '') results in $($MyInvocation.ScriptName -eq '')"

Try { '' -eq 0 }
Catch { Write-Host "Caught -lt 0" }

Write-Host $MyInvocation.InvocationName

PS C:\Users\lit\Documents\PowerShell> .\profile.ps1
Current User, All Hosts @ C:\Users\lit\Documents\PowerShell\profile.ps1
$MyInvocation.ScriptName is System.Management.Automation.InvocationInfo.ScriptName
$MyInvocation.ScriptName -eq $null results in False
$(System.Management.Automation.InvocationInfo.ScriptName -eq 0) results in False
$(System.Management.Automation.InvocationInfo.ScriptName -lt 0) results in True
$(System.Management.Automation.InvocationInfo.ScriptName -eq '') results in True
False
.\profile.ps1
</code>```

Suggestion from JosefZ works.

```<code>PS C:\src\my-powershell> type .\gname.ps1
Write-Host "`$MyInvocation.InvocationName is $((Resolve-Path $MyInvocation.InvocationName).Path)"
Write-Host (Resolve-Path $MyInvocation.InvocationName).Path

PS C:\src\my-powershell> .\gname.ps1
$MyInvocation.InvocationName is C:\src\my-powershell\gname.ps1
C:\src\my-powershell\gname.ps1
</code>```

I have tried to collect these possible answers, but still only one or two deliver what is needed. $MyInvocation.Command is always $null and $MyInvocation.ScriptName is always and empty string ('').

```<code>PS C:\src\t> Get-Content callme.ps1
"=== These two give the full path and invocation path"
Write-Host "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)\$(Split-Path -Leaf $MyInvocation.MyCommand.Definition)"
Write-Host "`$(`$MyInvocation.InvocationName) is $($MyInvocation.InvocationName)"
"=== `$MyInvocation.Command is `$null, but it, and its Source member, do have a type"
Write-Host "`$MyInvocation.Command -eq `$null is $($MyInvocation.Command -eq $null)"
Write-Host "`$MyInvocation.Command is $MyInvocation.Command"
Write-Host "`$(`$MyInvocation.Command) is $($MyInvocation.Command)"
Write-Host "`$MyInvocation.Command.Source is $MyInvocation.Command.Source"
Write-Host "`$(`$MyInvocation.Command.Source) is $($MyInvocation.Command.Source)"
"==="
Write-Host "`$MyInvocation.ScriptName -eq `$null is $($MyInvocation.ScriptName -eq $null)"
Write-Host "`$MyInvocation.ScriptName -eq '' is $($MyInvocation.ScriptName -eq '')"
Write-Host "`$MyInvocation.ScriptName is $MyInvocation.ScriptName"
Write-Host "`$(`$MyInvocation.ScriptName) is $($MyInvocation.ScriptName)"

PS C:\src\t> .\callme.ps1
=== These two give the full path and invocation path
C:\src\t\callme.ps1
$($MyInvocation.InvocationName) is .\callme.ps1
=== $MyInvocation.Command is $null, but it, and its Source member, do have a type
$MyInvocation.Command -eq $null is True
$MyInvocation.Command is System.Management.Automation.InvocationInfo.Command
$($MyInvocation.Command) is
$MyInvocation.Command.Source is System.Management.Automation.InvocationInfo.Command.Source
$($MyInvocation.Command.Source) is
===
$MyInvocation.ScriptName -eq $null is False
$MyInvocation.ScriptName -eq '' is True
$MyInvocation.ScriptName is System.Management.Automation.InvocationInfo.ScriptName
$($MyInvocation.ScriptName) is
</code>```

答:
Firstly, you have a bug on line 2 of your script. You probably want to wrap $MyInvocation.ScriptName in $(...):

```<code>Write-Host "`$MyInvocation.ScriptName is $($MyInvocation.ScriptName)"
</code>```

Next, the try{}catch{} will only work if the expression in the try{} block throws an exception. A simple comparison doesn't do that. If you were expecting PowerShell to complain that you are comparing try different types then... it doesn't. See below.

The comment from @PetSerAl is pertinent. When you run the profile from the PowerShell prompt, the ScriptName is what calls the current command. If you were to call your profile script from another script, you'd see the calling script name. I think you might want to look at the $MyInvocation.MyCommand property instead, as per Matthias' suggestion.

And finally...

When you compare a string with a number in the way you are doing, PowerShell "protects" you and automatically treats the second entity (the number) as a string and you're left with a string comparison: is the empty string "" less than the string "0"? Why, yes it is. It is also less than "-9999":

```<code>[PS]> "" -lt -9999
True
</code>```

So -9999 is bigger than nothing? Lets switch them around to check, and we see the same principle at work:

```<code>[PS]> -9999 -gt ""
False
</code>```

Seemingly a contradiction unless you remember that in each case the element on the right-hand-side of the comparison is being treated as a string or int depending on what the left-hand-side is.

Body:
This began as an effort to have all four (4) of the PowerShell profile scripts identify themselves and their location.

$MyInvocation.ScriptName was suggested for getting the script name, but I have yet to see it be anything other than an empty string. No, not $null, empty (''). This seems counter to many suggestions here on SO.

My first assumption was that $MyInvocation.ScriptName was $null, but that is not the case. To my surprise however, it is considered to be -lt 0. What is the rationale for comparing a String to an Int32?

I did find $MyInvocation.InvocationName which appears to give the script name, but not a directory path to it.

PS C:\Users\lit\Documents\PowerShell> Get-Content .\profile.ps1
Write-Host "Current User, All Hosts @ $(Split-Path -Parent $MyInvocation.MyCommand.Definition)\$(Split-Path -Leaf $MyInvocation.MyCommand.Definition)"
Write-Host "`$MyInvocation.ScriptName is $MyInvocation.ScriptName"
Write-Host "`$MyInvocation.ScriptName -eq `$null results in $($MyInvocation.ScriptName -eq $null)"
Write-Host "`$($MyInvocation.ScriptName -eq 0) results in $($MyInvocation.ScriptName -eq 0)"
Write-Host "`$($MyInvocation.ScriptName -lt 0) results in $($MyInvocation.ScriptName -lt 0)"
Write-Host "`$($MyInvocation.ScriptName -eq '') results in $($MyInvocation.ScriptName -eq '')"

Try { '' -eq 0 }
Catch { Write-Host "Caught -lt 0" }

Write-Host $MyInvocation.InvocationName

PS C:\Users\lit\Documents\PowerShell> .\profile.ps1
Current User, All Hosts @ C:\Users\lit\Documents\PowerShell\profile.ps1
$MyInvocation.ScriptName is System.Management.Automation.InvocationInfo.ScriptName
$MyInvocation.ScriptName -eq $null results in False
$(System.Management.Automation.InvocationInfo.ScriptName -eq 0) results in False
$(System.Management.Automation.InvocationInfo.ScriptName -lt 0) results in True
$(System.Management.Automation.InvocationInfo.ScriptName -eq '') results in True
False
.\profile.ps1

Suggestion from JosefZ works.

PS C:\src\my-powershell> type .\gname.ps1
Write-Host "`$MyInvocation.InvocationName is $((Resolve-Path $MyInvocation.InvocationName).Path)"
Write-Host (Resolve-Path $MyInvocation.InvocationName).Path

PS C:\src\my-powershell> .\gname.ps1
$MyInvocation.InvocationName is C:\src\my-powershell\gname.ps1
C:\src\my-powershell\gname.ps1

I have tried to collect these possible answers, but still only one or two deliver what is needed. $MyInvocation.Command is always $null and $MyInvocation.ScriptName is always and empty string ('').

PS C:\src\t> Get-Content callme.ps1
"=== These two give the full path and invocation path"
Write-Host "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)\$(Split-Path -Leaf $MyInvocation.MyCommand.Definition)"
Write-Host "`$(`$MyInvocation.InvocationName) is $($MyInvocation.InvocationName)"
"=== `$MyInvocation.Command is `$null, but it, and its Source member, do have a type"
Write-Host "`$MyInvocation.Command -eq `$null is $($MyInvocation.Command -eq $null)"
Write-Host "`$MyInvocation.Command is $MyInvocation.Command"
Write-Host "`$(`$MyInvocation.Command) is $($MyInvocation.Command)"
Write-Host "`$MyInvocation.Command.Source is $MyInvocation.Command.Source"
Write-Host "`$(`$MyInvocation.Command.Source) is $($MyInvocation.Command.Source)"
"==="
Write-Host "`$MyInvocation.ScriptName -eq `$null is $($MyInvocation.ScriptName -eq $null)"
Write-Host "`$MyInvocation.ScriptName -eq '' is $($MyInvocation.ScriptName -eq '')"
Write-Host "`$MyInvocation.ScriptName is $MyInvocation.ScriptName"
Write-Host "`$(`$MyInvocation.ScriptName) is $($MyInvocation.ScriptName)"

PS C:\src\t> .\callme.ps1
=== These two give the full path and invocation path
C:\src\t\callme.ps1
$($MyInvocation.InvocationName) is .\callme.ps1
=== $MyInvocation.Command is $null, but it, and its Source member, do have a type
$MyInvocation.Command -eq $null is True
$MyInvocation.Command is System.Management.Automation.InvocationInfo.Command
$($MyInvocation.Command) is
$MyInvocation.Command.Source is System.Management.Automation.InvocationInfo.Command.Source
$($MyInvocation.Command.Source) is
===
$MyInvocation.ScriptName -eq $null is False
$MyInvocation.ScriptName -eq '' is True
$MyInvocation.ScriptName is System.Management.Automation.InvocationInfo.ScriptName
$($MyInvocation.ScriptName) is

Body:
Firstly, you have a bug on line 2 of your script. You probably want to wrap $MyInvocation.ScriptName in $(...):

Write-Host "`$MyInvocation.ScriptName is $($MyInvocation.ScriptName)"

Next, the try{}catch{} will only work if the expression in the try{} block throws an exception. A simple comparison doesn't do that. If you were expecting PowerShell to complain that you are comparing try different types then... it doesn't. See below.

The comment from @PetSerAl is pertinent. When you run the profile from the PowerShell prompt, the ScriptName is what calls the current command. If you were to call your profile script from another script, you'd see the calling script name. I think you might want to look at the $MyInvocation.MyCommand property instead, as per Matthias' suggestion.

And finally...

When you compare a string with a number in the way you are doing, PowerShell "protects" you and automatically treats the second entity (the number) as a string and you're left with a string comparison: is the empty string "" less than the string "0"? Why, yes it is. It is also less than "-9999":

[PS]> "" -lt -9999
True

So -9999 is bigger than nothing? Lets switch them around to check, and we see the same principle at work:

[PS]> -9999 -gt ""
False

Seemingly a contradiction unless you remember that in each case the element on the right-hand-side of the comparison is being treated as a string or int depending on what the left-hand-side is.