问:
Google Cloud storage: Grant permission to OAuth 2.0 client
I try to download a file from a google cloud drive bucket via the REST. But if I use the access_token of the oAuth 2.0 client which I have created I get "Insufficient Permission" as an error (It works with the access toke of my googel account).

So, where in the cloud platform I can grant the oAuth2 client access to the bucket from where I want to download the file?

Thx

答:
TL;DR - You're most likely missing the step where you request the right scopes when requesting your OAuth2.0 access token. Please look at the supported scopes with Google Cloud Storage APIs. Access tokens typically expire in 60 minutes and you will need to use a refresh token to get a new access token when it expires.

Please read the Google Cloud Storage Authentication page for detailed information.

Scopes

Authorization is the process of determining what permissions an
  authenticated identity has on a set of specified resources. OAuth uses
  scopes to determine if an authenticated identity is authorized.
  Applications use a credential (obtained from a user-centric or
  server-centric authentication flow) together with one or more scopes
  to request an access token from a Google authorization server to
  access protected resources.

For example, application A with an access
  token with read-only scope can only read, while application B with an
  access token with read-write scope can read and modify data. Neither
  application can read or modify access control lists on objects and
  buckets; only an application with full-control scope can do so.

Authentication in Google Cloud

Google Cloud services generally provides 3 main modes of authentication:

End User Account credentials - here you authenticate as the end user directly using their google account or an OAuth 2.0 access token. When requesting an access token, you will need to provide the scopes which determine which APIs are accessible to the client using that access token.

OAuth2.0 credentials - if granted the right scope, can access the user's private data. In addition, Cloud IAM lets you control fine grained permissions by granting roles to this user account.

Service Accounts - here you create a service account which is associated with a specific GCP project (and billed to that project thereby). These are mainly used for automated use from your code or any of the Google Cloud services like Compute Engine, App Engine, Cloud Functions, etc. You can create service accounts using Google Cloud IAM.

Each service account has an associated email address (you specify when creating the service account) and you will need to grant appropriate roles for this email address for your Cloud Storage buckets/objects. These credentials if granted the right roles can access the user's private data.

API keys - here you get an encrypted string which is associated with a GCP project. It is supported only by very few Google Cloud APIs and it is not possible to restrict the scope of API keys (unlike service accounts or OAuth2.0 access tokens).


来源: stackexchange

问:
Icons in jsf do not appear
I am developing a java application using the JSF I put phone icons and message envelope but they do not appear, already tried to put them in the   tag but it did not appear

```<code><Li> <i class = "fa fa-phone"> </ i> +2 95 01 88 821 </ li>
<Li> <i class = "fa fa-envelope"> </ i> info@domain.com </ li>
</code>```

How it should look like:

UPDATE

I inserted the font

```<code>  <link type="text/css" rel="stylesheet" href="#{request.contextPath}/css/font-awesome.min.css" />
</code>```

But still the icons do not appear

icons

Hierarchy of files
hierarchy

答:
Your HTML is invalid. You have to remove extra spaces:

```<code><li><i class="fa fa-phone"></i>+2 95 01 88 821</li>
<li><i class="fa fa-envelope"></i>info@domain.com</li>
</code>```

Tag names are usually in lowercase.

Hope you have CSS describing your classes fa, fa-envelope and fa-phone...

Update

As I understand from your comments you have no CSS and font Awesome for your HTML. So you have to add them.

As @cjslv recommended, please look at http://fontawesome.io

Also I'd suggest you to refresh your HTML and CSS skills.

ContentLicense: CC BY-SA 3.0

Title: Icons in jsf do not appear

Body:
I am developing a java application using the JSF I put phone icons and message envelope but they do not appear, already tried to put them in the   tag but it did not appear

   +2 95 01 88 821

   info@domain.com

How it should look like:

UPDATE

I inserted the font

  <link type="text/css" rel="stylesheet" href="#{request.contextPath}/css/font-awesome.min.css" />

But still the icons do not appear

icons

Hierarchy of files
hierarchy

Body:
Your HTML is invalid. You have to remove extra spaces:

<li><i class="fa fa-phone"></i>+2 95 01 88 821</li>
<li><i class="fa fa-envelope"></i>info@domain.com</li>

Tag names are usually in lowercase.

Hope you have CSS describing your classes fa, fa-envelope and fa-phone...

Update

As I understand from your comments you have no CSS and font Awesome for your HTML. So you have to add them.

As @cjslv recommended, please look at http://fontawesome.io

Also I'd suggest you to refresh your HTML and CSS skills.


问:
How to detect if unity game is running on (web keyboard) or (mobile touch)
basically, I have a unity game supported by physical keyboards and touch screens in mobile devices. I already finished my movement script for physical keyboards, and now, I'm coding for touch screens.

How can I achieve that detect feature?

I was thinking something like that...

```<code>private void HandleInput()
{
   if (detect if physical keyboard here...)
   {

        if  (Input.GetKey(KeyCode.RightArrow))
        {
            _normalizedHorizontalSpeed = 1;
        }
        else if (Input.GetKey(KeyCode.LeftArrow))
        {
            _normalizedHorizontalSpeed = -1;
        }
   } else if (detect touch screen here...)
   {
       for (int i = 0; i < Input.touchCount; ++i)
       {
          if (Input.GetTouch(i).phase == TouchPhase.Began)
          {
             some code here...
          }
       }
   }
}
</code>```

Appreciate

答:
You are looking for Application.platform.
Something like the following should achieve what you are looking for or read here for more devices.

```<code>if (Application.platform == RuntimePlatform.WindowsPlayer)
    Debug.Log("Do something special here");
else if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
    Debug.Log("Do something else here");
</code>```

However, you may be better off getting rid of this check all together since it is redundant! If you are pressing the right or left arrow you already know the user is using a keyboard.

Body:
basically, I have a unity game supported by physical keyboards and touch screens in mobile devices. I already finished my movement script for physical keyboards, and now, I'm coding for touch screens.

How can I achieve that detect feature?

I was thinking something like that...

private void HandleInput()
{
   if (detect if physical keyboard here...)
   {

        if  (Input.GetKey(KeyCode.RightArrow))
        {
            _normalizedHorizontalSpeed = 1;
        }
        else if (Input.GetKey(KeyCode.LeftArrow))
        {
            _normalizedHorizontalSpeed = -1;
        }
   } else if (detect touch screen here...)
   {
       for (int i = 0; i < Input.touchCount; ++i)
       {
          if (Input.GetTouch(i).phase == TouchPhase.Began)
          {
             some code here...
          }
       }
   }
}

Appreciate

Body:
You are looking for Application.platform.
Something like the following should achieve what you are looking for or read here for more devices.

if (Application.platform == RuntimePlatform.WindowsPlayer)
    Debug.Log("Do something special here");
else if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
    Debug.Log("Do something else here");

However, you may be better off getting rid of this check all together since it is redundant! If you are pressing the right or left arrow you already know the user is using a keyboard.


问:
PHP echo scraped input Value from HTML
I need to echo Values from input fields. Preferably $var name can be same as input fieldname. Sample: echo $yesRedirect; Should output: No

```<code><?php
$html = array('<input type="text" name="yesRedirect" id="yesRedirectfunction" value="No">',
'<input type="text" name="noRedirect" id="noRedirectfunction" value="Yes">',
'<input type="text" name="quickcheck" id="quickcheckfunction" value="No">');

$result = array();

foreach ($html as $name) {
$dom = new DomDocument;
$dom->loadHTML($name);
var_dump($dom) . "\n";

//echo $dom->getAttribute('name') . "\n";
//echo $dom->getAttribute('value') . "\n";
}

echo $yesRedirect; // Should output: No
echo $noRedirect;  // Should output: Yes
?>
</code>```

How can I simply echo input value? Is there any other way?
Thank you for helping.

答:
I got the results as wanted with this code below:</p>

```<code><?php

$html = array('<input type="text" name="yesRedirect" id="yesRedirectfunction" value="No">',
              '<input type="text" name="noRedirect" id="noRedirectfunction" value="Yes">',
              '<input type="text" name="quickcheck" id="quickcheckfunction" value="No">');

$result = array();

foreach ($html as $name) {
$name = str_replace('"','',$name);
$name = str_replace('>','',$name);

$varname = explode("name=", $name);
$arrname = explode(' ',trim($varname['1']));

$varvalue = explode("value=", $name);
$arrvalue = explode(' ',trim($varvalue['1']));

$result[$arrname[0]] = $arrvalue[0];

}

echo $result['yesRedirect'];
echo $result['noRedirect'];
echo $result['quickcheck'];
?>
</code>```

Title: PHP echo scraped input Value from HTML

Body:
I need to echo Values from input fields. Preferably $var name can be same as input fieldname. Sample: echo $yesRedirect; Should output: No

<?php
$html = array('<input type="text" name="yesRedirect" id="yesRedirectfunction" value="No">',
'<input type="text" name="noRedirect" id="noRedirectfunction" value="Yes">',
'<input type="text" name="quickcheck" id="quickcheckfunction" value="No">');

$result = array();

foreach ($html as $name) {
$dom = new DomDocument;
$dom->loadHTML($name);
var_dump($dom) . "\n";

//echo $dom->getAttribute('name') . "\n";
//echo $dom->getAttribute('value') . "\n";
}

echo $yesRedirect; // Should output: No
echo $noRedirect;  // Should output: Yes
?>

How can I simply echo input value? Is there any other way?
Thank you for helping.

Body:
I got the results as wanted with this code below:

<?php

$html = array('<input type="text" name="yesRedirect" id="yesRedirectfunction" value="No">',
              '<input type="text" name="noRedirect" id="noRedirectfunction" value="Yes">',
              '<input type="text" name="quickcheck" id="quickcheckfunction" value="No">');

$result = array();

foreach ($html as $name) {
$name = str_replace('"','',$name);
$name = str_replace('>','',$name);

$varname = explode("name=", $name);
$arrname = explode(' ',trim($varname['1']));

$varvalue = explode("value=", $name);
$arrvalue = explode(' ',trim($varvalue['1']));

$result[$arrname[0]] = $arrvalue[0];

}

echo $result['yesRedirect'];
echo $result['noRedirect'];
echo $result['quickcheck'];
?>


问:
How to remove eclipse darkest dark theme?
Unable to remove eclipse darkest dark theme. I tried to install this for latest eclipse oxygen and it got installed successfully, but now I am unable to remove it.
How to remove a theme from eclipse?

Thanks in Advance.

答:
Goto Help -> Eclipse Market Place

A child window will open showing available plugins in Eclipse Market Place.
Above we will find a tab named "Installed"
Go to 'Installed' tab. It will show the list of installed or associated plugins with current copy of eclipse.

Against 'darkest dark theme' (beside installed button)  we will find a drop down where we get option to uninstall.


问:
How to replace string by other file content in Makefile
I have a file with some include lines and I would like to read the filepath and replace this line with the file contents.

e.g. replace the line  with content of path/filename.txt

```<code># meta info
- a
- b

# included files
<!-- include(path/filename.txt) -->
</code>```

My Makefile:

```<code>expand-includes:
    @echo "Expand all included file"
    perl -pi -e "s/<!--\s?include\((.+)\)\s?-->/`cat $$1`/" input.txt
</code>```

The capture group looks get empty $$1 and the script hangs.
Do I miss something?

Update:
Remove $(shell)

答:
The following syntax works well.

perl -p -e 's//`cat $$1`/e' input.txt > output.txt

Body:
I have a file with some include lines and I would like to read the filepath and replace this line with the file contents.

e.g. replace the line  with content of path/filename.txt

# meta info
- a
- b

# included files

My Makefile:

expand-includes:
    @echo "Expand all included file"
    perl -pi -e "s//`cat $$1`/" input.txt

The capture group looks get empty $$1 and the script hangs.
Do I miss something?

Update:
Remove $(shell)

Body:
The following syntax works well.

perl -p -e 's/<!--\s?include\((.+)\)\s?-->/`cat $$1`/e' input.txt > output.txt


问:
Error received "No best type found for implicitly-typed array"
This is my code for creating Json response for jqGrid and for new keyword for defining cell member I receive following message "No best type found for implicitly-typed array".

```<code>var resRows = results.Select(record =>
            new
            {
                id = record.Reference,
                cell = **new** []
                {
                    record.Reference,
                    record.TradeDate.ToShortDateString(),
                    record.Currency1,
                    record.Currency2,
                    record.Notional.ToString(),
                    record.EffectiveDate.ToShortDateString(),
                    record.Quote.ToString()
                }
            }).ToArray();
</code>```

What am I doing wrong here?

答:
If the members of the collection are functions, it still gives the compiler error.  Even if there is only one function in the collection!

```<code>var bads = new []  // COMPILER ERROR
{
    Foo
};

var goods = new Action[]  // NO COMPILER ERROR
{
    Foo
};

//...
public void Foo() { }
</code>```

Body:
This is my code for creating Json response for jqGrid and for new keyword for defining cell member I receive following message "No best type found for implicitly-typed array".

var resRows = results.Select(record =>
            new
            {
                id = record.Reference,
                cell = **new** []
                {
                    record.Reference,
                    record.TradeDate.ToShortDateString(),
                    record.Currency1,
                    record.Currency2,
                    record.Notional.ToString(),
                    record.EffectiveDate.ToShortDateString(),
                    record.Quote.ToString()
                }
            }).ToArray();

What am I doing wrong here?

Body:
If the members of the collection are functions, it still gives the compiler error.  Even if there is only one function in the collection!

var bads = new []  // COMPILER ERROR
{
    Foo
};

var goods = new Action[]  // NO COMPILER ERROR
{
    Foo
};

//...
public void Foo() { }


问:
C++ pointer arithmetic in a loop and memory management?
I am getting started with C++. I wanted to understand the different
outputs while playing around with this snippet of code.

```<code>int main()
{
    int i = 3;
    int *ptr = &i; //stores address of the i
    while(*(ptr)--) //the same as i--
    {
        cout << *ptr << endl;
    }
}
</code>```

When I run this code I understand that the deferenced value
of ptr, which is "i", gets 1 subtracted from it and the loop exits
when "i" equals 0. But when I use while(*ptr--) instead of while(*(ptr)--) I get a list of random integers which eventually go down to 0 and the loop breaks.

To my understanding when I use *ptr-- I am subtracting a byte(size of one int) from the initial address of &i(*ptr) with each loop. But why does the program terminate eventually? No matter what the value of "i" is, the program prints 23 random numbers with the last one being 0 and the loop exits. Should I not get an overflow error since the program runs out of memory?

However, when I use while(ptr--) the program does go into an infinite loop.
What exactly is happening?

Thank you very much.

答:
(ptr) is the same as ptr, thus (ptr)-- is the same as ptr--.

*ptr-- IS NOT the same as i-- !

You are applying operator-- to the right side of the pointer.  The suffix/postfix operator-- has a higher precedence than operator*.  So, *ptr-- is the same as *(ptr--), not (*ptr)-- like you are expecting.

IOW, ptr-- gets evaluated first, which returns a copy of the current pointer and then decrements the pointer, and then you are dereferencing the copied pointer to retrieve the value that was previously being pointing at.

That is why you are seeing garbage - you are decrementing the pointer into memory that does not belong to you.

To simply decrement the int and not the pointer, use (*ptr)-- instead.  IOW, dereference the pointer first, then decrement the value being pointed at, eg:

```<code>int main()
{
    int i = 3;
    int *ptr = &i; //stores address of the i
    while((*ptr)--) //the same as i--
    {
        cout << *ptr << endl;
    }
}
</code>```

Live demo

Parenthesis and operator precedence matter!

Body:
I am getting started with C++. I wanted to understand the different
outputs while playing around with this snippet of code.

int main()
{
    int i = 3;
    int *ptr = &i; //stores address of the i
    while(*(ptr)--) //the same as i--
    {
        cout << *ptr << endl;
    }
}

When I run this code I understand that the deferenced value
of ptr, which is "i", gets 1 subtracted from it and the loop exits
when "i" equals 0. But when I use while(*ptr--) instead of while(*(ptr)--) I get a list of random integers which eventually go down to 0 and the loop breaks.

To my understanding when I use *ptr-- I am subtracting a byte(size of one int) from the initial address of &i(*ptr) with each loop. But why does the program terminate eventually? No matter what the value of "i" is, the program prints 23 random numbers with the last one being 0 and the loop exits. Should I not get an overflow error since the program runs out of memory?

However, when I use while(ptr--) the program does go into an infinite loop.
What exactly is happening?

Thank you very much.

Body:
(ptr) is the same as ptr, thus (ptr)-- is the same as ptr--.

*ptr-- IS NOT the same as i-- !

You are applying operator-- to the right side of the pointer.  The suffix/postfix operator-- has a higher precedence than operator*.  So, *ptr-- is the same as *(ptr--), not (*ptr)-- like you are expecting.

IOW, ptr-- gets evaluated first, which returns a copy of the current pointer and then decrements the pointer, and then you are dereferencing the copied pointer to retrieve the value that was previously being pointing at.

That is why you are seeing garbage - you are decrementing the pointer into memory that does not belong to you.

To simply decrement the int and not the pointer, use (*ptr)-- instead.  IOW, dereference the pointer first, then decrement the value being pointed at, eg:

int main()
{
    int i = 3;
    int *ptr = &i; //stores address of the i
    while((*ptr)--) //the same as i--
    {
        cout << *ptr << endl;
    }
}

Live demo

Parenthesis and operator precedence matter!


问:
Excel cell multiple validation between two dates and if cell is not blank
I require a cell to be validated twice. Firstly, if the user has inputted a time (B5) but not a date (A5) then a pop-up should appear requesting a date in A5. When the date is entered it must be between the start date (B1) and end date (B2).

答:
Here is something simple since your cells are all hardcoded.  You can edit the macro as you see fit to have more functionality and to be more robust.

```<code>Sub doubleValidate()
    If ActiveSheet.Cells("B5") <> "" And ActiveSheet.Cells("A5") = "" Then
        MsgBox ("Please Enter Date!")
        End
    End If

    If ActiveSheet.Cells("A5") <= ActiveSheet.Cells("B2") And ActiveSheet.Cells("A5") >= ActiveSheet.Cells("B1") Then
        MsgBox ("All good.")
    End If

    If ActiveSheet.Cells("A5") > ActiveSheet.Cells("B2") Or ActiveSheet.Cells("A5") < ActiveSheet.Cells("B1") Then
        MsgBox ("Date not in range.")
    End If

End Sub
</code>```

Next time please show some of your own work in order to get a solid answer.

Body:
Here is something simple since your cells are all hardcoded.  You can edit the macro as you see fit to have more functionality and to be more robust.

Sub doubleValidate()
    If ActiveSheet.Cells("B5") <> "" And ActiveSheet.Cells("A5") = "" Then
        MsgBox ("Please Enter Date!")
        End
    End If

    If ActiveSheet.Cells("A5") <= ActiveSheet.Cells("B2") And ActiveSheet.Cells("A5") >= ActiveSheet.Cells("B1") Then
        MsgBox ("All good.")
    End If

    If ActiveSheet.Cells("A5") > ActiveSheet.Cells("B2") Or ActiveSheet.Cells("A5") < ActiveSheet.Cells("B1") Then
        MsgBox ("Date not in range.")
    End If

End Sub

Next time please show some of your own work in order to get a solid answer.


问:
Openshift Origin Offline/Disconnected Installation
I want to install openshift origin containerized installation(advanced installation) on machine without internet access.
I referred to this URL -> https://docs.openshift.com/enterprise/3.1/install_config/install/disconnected_install.html
But it still going to docker.io and registry.*.redhat.com.

Please suggest a possible approach to achieve the goal.

答:
There is a way to accomplish this install.The updated documentation does list the steps.
Let me know if you are still looking for the steps.</p>


问:
comparing the two times is greater or lesser in java
```<code>  Date date1= new java.util.Date();
                  java.sql.Date Sqldob = new java.sql.Date(date1.getTime());
                  System.out.println("date" +Sqldob);

                  Time Sqldob1 = new Time(date1.getTime());
                  System.out.println("User Time: " +Sqldob1);
                  String yourTime="09:30:00";

                  SimpleDateFormat ra = new SimpleDateFormat("HH:mm:ss");
                  Date yourDate = ra.parse(yourTime);
                  Time sqlTime3 = new Time(yourDate.getTime());
                  System.out.println("your time"+sqlTime3);

                  if(Sqldob1.before(sqlTime3)){
                     Sqldob1 = sqlTime3;
                     System.out.println("inside loop");
                  }
</code>```

In the code above I am comparing two time variables for equality, but it is giving me the same value -1 for all the types of input

答:
Modern version:

```<code>    LocalDateTime dateTime1 = LocalDateTime.now(ZoneId.systemDefault());
    LocalDate dob = dateTime1.toLocalDate();
    System.out.println("date " + dob);

    LocalTime dob1 = dateTime1.toLocalTime();
    System.out.println("User Time: " + dob1);

    String yourTime = "09:30:00";
    LocalTime time3 = LocalTime.parse(yourTime);
    System.out.println("your time " + time3);

    if (dob1.isBefore(time3)) {
        dob1 = time3;
        System.out.println("inside if statement");
    }
</code>```

When I ran this code this morning, it printed:

```<code>date 2017-07-07
User Time: 05:32:01.881
your time 09:30
inside if statement
</code>```

The point is: With the old and now long outdated classes Date and Time it is easy not to get things right. With the modern classes I use here, it’s much easier to get them right.

Are you using java.sql types because you really need to get your date and time from a database and/or store them into one? This was what these were for, you shouldn’t really have used them for other purposes. I use “was” and “were” intentionally because you don’t need them for this purpose either anymore. With a new JDBC driver, you can get a LocalDateTime from the database and store one back, or depending on your column datatype get an Instant and convert it to LocalDateTime:

```<code>    LocalDateTime dateTime2 = instantFromDb.atZone(ZoneId.systemDefault())
            .toLocalDateTime();
</code>```

PS Item 2. in SoduRahul’s answer gives the real and correct explanation of what went wrong in your program: though Time was meant for time-of-day only, your Sqldob1 ends up holding today’s date and sqlTime3 the date of the epoch (January 1, 1970), so the former will always be after the latter by their before method.

Body:
  Date date1= new java.util.Date();
                  java.sql.Date Sqldob = new java.sql.Date(date1.getTime());
                  System.out.println("date" +Sqldob);

                  Time Sqldob1 = new Time(date1.getTime());
                  System.out.println("User Time: " +Sqldob1);
                  String yourTime="09:30:00";

                  SimpleDateFormat ra = new SimpleDateFormat("HH:mm:ss");
                  Date yourDate = ra.parse(yourTime);
                  Time sqlTime3 = new Time(yourDate.getTime());
                  System.out.println("your time"+sqlTime3);

                  if(Sqldob1.before(sqlTime3)){
                     Sqldob1 = sqlTime3;
                     System.out.println("inside loop");
                  }

In the code above I am comparing two time variables for equality, but it is giving me the same value -1 for all the types of input

Body:
Modern version:

    LocalDateTime dateTime1 = LocalDateTime.now(ZoneId.systemDefault());
    LocalDate dob = dateTime1.toLocalDate();
    System.out.println("date " + dob);

    LocalTime dob1 = dateTime1.toLocalTime();
    System.out.println("User Time: " + dob1);

    String yourTime = "09:30:00";
    LocalTime time3 = LocalTime.parse(yourTime);
    System.out.println("your time " + time3);

    if (dob1.isBefore(time3)) {
        dob1 = time3;
        System.out.println("inside if statement");
    }

When I ran this code this morning, it printed:

date 2017-07-07
User Time: 05:32:01.881
your time 09:30
inside if statement

The point is: With the old and now long outdated classes Date and Time it is easy not to get things right. With the modern classes I use here, it’s much easier to get them right.

Are you using java.sql types because you really need to get your date and time from a database and/or store them into one? This was what these were for, you shouldn’t really have used them for other purposes. I use “was” and “were” intentionally because you don’t need them for this purpose either anymore. With a new JDBC driver, you can get a LocalDateTime from the database and store one back, or depending on your column datatype get an Instant and convert it to LocalDateTime:

    LocalDateTime dateTime2 = instantFromDb.atZone(ZoneId.systemDefault())
            .toLocalDateTime();

PS Item 2. in SoduRahul’s answer gives the real and correct explanation of what went wrong in your program: though Time was meant for time-of-day only, your Sqldob1 ends up holding today’s date and sqlTime3 the date of the epoch (January 1, 1970), so the former will always be after the latter by their before method.


问:
Java Filter URL Rewriting Loop Problem
I hope someone can point out where I'm going wrong here. I'm trying to create a simple filter that works something like Paul Tuckey's URLRewriteFilter, but stripped down to do only what I need it to do.

I can't get it to stop looping back on the original URI. I've snooped around the URLRewriteFilter code and it seems to be doing basically the same thing I'm doing. Here's my filter code:

```<code>public static final String dispatcherURI = "/Dispatcher?q=";
public void doFilter(final ServletRequest request, final ServletResponse response,
                     final FilterChain chain)
        throws IOException, ServletException {
    final HttpServletRequest rq = (HttpServletRequest)request;
    final HttpServletResponseWrapper rsw =
        new HttpServletResponseWrapper((HttpServletResponse)response);
    final String uri = rq.getRequestURI();
    if (uriIsDispatchable(uri)) {
        final String forwardPath = dispatcherURI+uri;
        rq.getRequestDispatcher(forwardPath).forward(rq, rsw);
        LOG.info("Forward From: "+uri+", To: "+forwardPath);
    }
    else {
        try { chain.doFilter(request, response); }
        catch (Exception e) {
            LOG.error(e);
            throw new RuntimeException(e);
        }
    }
}

// checks URI against an ArrayList of URIs that should be ignored.
private static boolean uriIsDispatchable (final String uri) {
    boolean result = true;
    for (String i : ApplicationValues.uriIgnore) {
        if (uri.indexOf(i) == 0) {
            result = false;
            break;
        }
    }
    return result;
}
</code>```

Here's the filter entry in web.xml

```<code><filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>myapp.filter.URLRewrite</filter-class>
</filter>
<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

Some notes on the code:
A URI like /home should be forwarded to a dispatcher servlet like so: /Dispatcher?q=/home
the dispatcher servlet then determines what code to execute based on what's in the query string.

The filter correctly ignores the URIs in the "uriIgnore" ArrayList (including /Dispatcher), but the forward keeps looping on /home. For completeness sake, here's the contents of the uriIgnore ArrayList which is searched in the uriIsDispatchable method above:

```<code>public static final List<String> uriIgnore = new ArrayList<String>(4);
static {
  uriIgnore.add("/Dispatcher");
  uriIgnore.add("/netbeans-tomcat-status-test");
  uriIgnore.add("/resources");
  uriIgnore.add("/robots.txt");
}
</code>```

Also, I'm running the latest Tomcat 6 proxied behind Apache.

Any help is appreciated. Thanks.

答:
I'll get around to figuring this out when I have time to peruse the URLRewrite Filter code further, but in the meantime it seems that if I really want the highest performance URL rewriting, I'll just let mod_rewrite and Apache do it.

My solution (I'm sure there's a better way to do this also):

```<code># .htaccess file contents
# Apache has the same docroot as the Java web app.
# Java webapp is running on port 8084
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f [NC,OR]
RewriteCond %{REQUEST_FILENAME} !-d
# directory where images, static html files and JS scripts are located.
# Apache will serve these.
RewriteRule ^resources - [L,NC]
# obviously, we want Apache to serve robots.txt
RewriteRule ^robots.txt$ - [L,NC]
RewriteRule ^(.*)$ http://localhost:8084/Dispatcher?q=$1 [L,P,QSA]
</IfModule>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Java Filter URL Rewriting Loop Problem

Body:
I hope someone can point out where I'm going wrong here. I'm trying to create a simple filter that works something like Paul Tuckey's URLRewriteFilter, but stripped down to do only what I need it to do.

I can't get it to stop looping back on the original URI. I've snooped around the URLRewriteFilter code and it seems to be doing basically the same thing I'm doing. Here's my filter code:

public static final String dispatcherURI = "/Dispatcher?q=";
public void doFilter(final ServletRequest request, final ServletResponse response,
                     final FilterChain chain)
        throws IOException, ServletException {
    final HttpServletRequest rq = (HttpServletRequest)request;
    final HttpServletResponseWrapper rsw =
        new HttpServletResponseWrapper((HttpServletResponse)response);
    final String uri = rq.getRequestURI();
    if (uriIsDispatchable(uri)) {
        final String forwardPath = dispatcherURI+uri;
        rq.getRequestDispatcher(forwardPath).forward(rq, rsw);
        LOG.info("Forward From: "+uri+", To: "+forwardPath);
    }
    else {
        try { chain.doFilter(request, response); }
        catch (Exception e) {
            LOG.error(e);
            throw new RuntimeException(e);
        }
    }
}

// checks URI against an ArrayList of URIs that should be ignored.
private static boolean uriIsDispatchable (final String uri) {
    boolean result = true;
    for (String i : ApplicationValues.uriIgnore) {
        if (uri.indexOf(i) == 0) {
            result = false;
            break;
        }
    }
    return result;
}

Here's the filter entry in web.xml

<filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>myapp.filter.URLRewrite</filter-class>
</filter>
<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Some notes on the code:
A URI like /home should be forwarded to a dispatcher servlet like so: /Dispatcher?q=/home
the dispatcher servlet then determines what code to execute based on what's in the query string.

The filter correctly ignores the URIs in the "uriIgnore" ArrayList (including /Dispatcher), but the forward keeps looping on /home. For completeness sake, here's the contents of the uriIgnore ArrayList which is searched in the uriIsDispatchable method above:

public static final List<String> uriIgnore = new ArrayList<String>(4);
static {
  uriIgnore.add("/Dispatcher");
  uriIgnore.add("/netbeans-tomcat-status-test");
  uriIgnore.add("/resources");
  uriIgnore.add("/robots.txt");
}

Also, I'm running the latest Tomcat 6 proxied behind Apache.

Any help is appreciated. Thanks.

Body:
I'll get around to figuring this out when I have time to peruse the URLRewrite Filter code further, but in the meantime it seems that if I really want the highest performance URL rewriting, I'll just let mod_rewrite and Apache do it.

My solution (I'm sure there's a better way to do this also):

# .htaccess file contents
# Apache has the same docroot as the Java web app.
# Java webapp is running on port 8084
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f [NC,OR]
RewriteCond %{REQUEST_FILENAME} !-d
# directory where images, static html files and JS scripts are located.
# Apache will serve these.
RewriteRule ^resources - [L,NC]
# obviously, we want Apache to serve robots.txt
RewriteRule ^robots.txt$ - [L,NC]
RewriteRule ^(.*)$ http://localhost:8084/Dispatcher?q=$1 [L,P,QSA]
</IfModule>


问:
Yet another: Cannot assign "u'3'": "City.state" must be a "State" instance
I'm trying to customize the admin to chain 2 select boxes with ajax and a custom form, everything works great until I try to save the data and i get this error.
My models look like this:

```<code>class State(TimeStampModel):
name = models.CharField(
    max_length=200,
    verbose_name=u'State',
    blank=False,
    null=False,
)
code = models.CharField(
    max_length=20,
    verbose_name=u'State Code',
    blank=True,
)
coat_of_arms = models.ImageField(
    upload_to=file_rename('coat_of_arms'),
    verbose_name='Coat of Arms',
    null=True,
    blank=True,
)
country = models.ForeignKey(
    'Country',
    blank=False,
    null=False,
)

def __unicode__(self):
    return self.name

class Meta:
    verbose_name = u'State'
    verbose_name_plural = u'States'

class City(TimeStampModel):
   name = models.CharField(
        max_length=200,
        verbose_name=u'City',
        blank=False,
        null=False,
    )
    code = models.CharField(
        max_length=20,
        verbose_name=u'City Code',
        blank=True,
    )
    coat_of_arms = models.ImageField(
        upload_to=file_rename('coat_of_arms'),
        verbose_name='Coat of Arms',
        null=True,
        blank=True,
    )
    state = models.ForeignKey(
        'State',
        blank=False,
        null=False,
    )

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = u'City'
        verbose_name_plural = u'Cities'
</code>```

The forms.py:

```<code>class CityAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
    super(CityAdminForm, self).__init__(*args, **kwargs)
    country_list = self.get_country_choices()
    state_list = self.get_state_choices()

    instance = getattr(self, 'instance', None)

    if instance.pk:
        self.fields['state'].widget.choices = state_list

    self.fields['country'].widget.choices = country_list

state = forms.CharField(label=u'State', required=True,
                        widget=forms.Select)
country = forms.CharField(label=u'Country', required=True,
                          widget=forms.Select)

@staticmethod
def get_country_choices():
    country_list = Country.objects.all()
    choices_list = [(country.id, country.name) for country in country_list]
    choices_list.insert(0, ("", "----------"))

    return choices_list

@staticmethod
def get_state_choices(country_id=None):
    if country_id:
        state_list = State.objects.filter(country_id=country_id)
    else:
        state_list = State.objects.all()
    choices_list = [(state.id, state.name) for state in state_list]
    choices_list.insert(0, ("", "----------"))

    return choices_list

class Meta:
    model = City
    exclude = ['created_at', 'updated_at']

class Media:
    js = ('countries/js/CustomComponents.js', 'countries/js/jquery-ui.js')
</code>```

I registered that form in the admin.py:

```<code>class CityAdminForm(admin.ModelAdmin):
fields = ['name', 'code', 'coat_of_arms', 'country', 'state']
form = CityAdminForm
</code>```

As i said all works properly until I try to save the data, maybe I'm missing something in the form.

Thanks in advance

答:
I could solve the problem leaving the admin create the state select box, i deleted in the initializator for state, the definition of the state variable
and the staticmethod get_state_choices, and everythng is working now, thanks.</p>

Body:
I'm trying to customize the admin to chain 2 select boxes with ajax and a custom form, everything works great until I try to save the data and i get this error.
My models look like this:

class State(TimeStampModel):
name = models.CharField(
    max_length=200,
    verbose_name=u'State',
    blank=False,
    null=False,
)
code = models.CharField(
    max_length=20,
    verbose_name=u'State Code',
    blank=True,
)
coat_of_arms = models.ImageField(
    upload_to=file_rename('coat_of_arms'),
    verbose_name='Coat of Arms',
    null=True,
    blank=True,
)
country = models.ForeignKey(
    'Country',
    blank=False,
    null=False,
)

def __unicode__(self):
    return self.name

class Meta:
    verbose_name = u'State'
    verbose_name_plural = u'States'

class City(TimeStampModel):
   name = models.CharField(
        max_length=200,
        verbose_name=u'City',
        blank=False,
        null=False,
    )
    code = models.CharField(
        max_length=20,
        verbose_name=u'City Code',
        blank=True,
    )
    coat_of_arms = models.ImageField(
        upload_to=file_rename('coat_of_arms'),
        verbose_name='Coat of Arms',
        null=True,
        blank=True,
    )
    state = models.ForeignKey(
        'State',
        blank=False,
        null=False,
    )

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = u'City'
        verbose_name_plural = u'Cities'

The forms.py:

class CityAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
    super(CityAdminForm, self).__init__(*args, **kwargs)
    country_list = self.get_country_choices()
    state_list = self.get_state_choices()

    instance = getattr(self, 'instance', None)

    if instance.pk:
        self.fields['state'].widget.choices = state_list

    self.fields['country'].widget.choices = country_list

state = forms.CharField(label=u'State', required=True,
                        widget=forms.Select)
country = forms.CharField(label=u'Country', required=True,
                          widget=forms.Select)

@staticmethod
def get_country_choices():
    country_list = Country.objects.all()
    choices_list = [(country.id, country.name) for country in country_list]
    choices_list.insert(0, ("", "----------"))

    return choices_list

@staticmethod
def get_state_choices(country_id=None):
    if country_id:
        state_list = State.objects.filter(country_id=country_id)
    else:
        state_list = State.objects.all()
    choices_list = [(state.id, state.name) for state in state_list]
    choices_list.insert(0, ("", "----------"))

    return choices_list

class Meta:
    model = City
    exclude = ['created_at', 'updated_at']

class Media:
    js = ('countries/js/CustomComponents.js', 'countries/js/jquery-ui.js')

I registered that form in the admin.py:

class CityAdminForm(admin.ModelAdmin):
fields = ['name', 'code', 'coat_of_arms', 'country', 'state']
form = CityAdminForm

As i said all works properly until I try to save the data, maybe I'm missing something in the form.

Thanks in advance


问:
SpringBoot with LogBack creating LOG_PATH_IS_UNDEFINED folder
I am using SpringBoot with LogBack and using the below configuration in my yml file:

```<code>logging:
    path: C:/var/log/pincode
</code>```

The logging.path Spring Environment Variable is transferred to the LOG_PATH Environment variable and the log file is placed at the correct place, but there is also a directory called LOG_PATH_IS_UNDEFINED created in the root directory of my project.

This seems to be caused by the different phase used by SpringBoot to configure LogBack with its Environment variables.

```<code>17:29:21,325 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
17:29:21,337 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern LOG_PATH_IS_UNDEFINED/catalina.out.%d{yyyy-MM-dd} for the active file
17:29:21,340 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd' from file name pattern 'LOG_PATH_IS_UNDEFINED/catalina.out.%d{yyyy-MM-dd}'.
17:29:21,340 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over at midnight.
17:29:21,343 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Mon Aug 11 17:24:07 BRT 2014
17:29:21,346 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - Active log file name: LOG_PATH_IS_UNDEFINED/catalina.out
17:29:21,346 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - File property is set to [LOG_PATH_IS_UNDEFINED/catalina.out]
...
17:29:21,358 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
</code>```

And then after that it start configuring logback again but this time using the path i set:

```<code>17:29:21,672 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
17:29:21,673 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
17:29:21,673 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern C:/var/log/pincode//catalina.out.%d{yyyy-MM-dd} for the active file
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd' from file name pattern 'C:/var/log/pincode//catalina.out.%d{yyyy-MM-dd}'.
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over at midnight.
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Mon Aug 11 17:29:21 BRT 2014
17:29:21,674 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - Active log file name: C:/var/log/pincode//catalina.out
17:29:21,674 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - File property is set to [C:/var/log/pincode//catalina.out]
...
17:29:21,685 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
</code>```

My logback.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<include resource="org/springframework/boot/logging/logback/basic.xml" />
<property name="FILE_LOG_PATTERN"
    value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } [%t] --- %-40.40logger{39} : %m%n%wex" />

<appender name="serverConsole"
          class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/catalina.out</File>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/catalina.out.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<!-- Plain Text Rolling Appender -->
<appender name="server"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/pincode.log</File>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>INFO</level>
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/pincode.log.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<!-- Plain Text Rolling Appender -->
<appender name="server-error"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/pincode-error.log</File>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>ERROR</level>
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/pincode-error.log.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<logger name="com.app" level="INFO">
    <appender-ref ref="server" />
    <appender-ref ref="server-error" />
</logger>

<root level="INFO">
    <appender-ref ref="serverConsole" />
</root>
</code>```

If I remove my logback.xml file from the project it doesn't create the folder, so somewhere Spring is loading the xml before parsing the yml?

How can I avoid Logback to create this LOG_PATH_IS_UNDEFINED directory?

答: Before Spring Boot enviroment is prepared, the Spring Boot main class or the SpringApplication will initialize the loggerfactory, which will detect the default configuration file (logback.groovy, logback.xml, logback-test.xml), but at this time the Spring Boot application is not started yet, which means the variable LOG_PATH is not set. So at first you should alter the name of your logback config file and configure the file name manually in the Spring Boot config as logging.config. By this way the logback will configure a console appender by default instead of creating a file appender, and then when the Spring Boot enviroment is ready it will fire an enviromentready event, which causes a logback reconfig by LoggingApplicationListener. You can find the issue at springboot's page https://github.com/spring-projects/spring-boot/issues/2558

Body:
I am using SpringBoot with LogBack and using the below configuration in my yml file:

logging:
    path: C:/var/log/pincode

The logging.path Spring Environment Variable is transferred to the LOG_PATH Environment variable and the log file is placed at the correct place, but there is also a directory called LOG_PATH_IS_UNDEFINED created in the root directory of my project.

This seems to be caused by the different phase used by SpringBoot to configure LogBack with its Environment variables.

17:29:21,325 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
17:29:21,337 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern LOG_PATH_IS_UNDEFINED/catalina.out.%d{yyyy-MM-dd} for the active file
17:29:21,340 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd' from file name pattern 'LOG_PATH_IS_UNDEFINED/catalina.out.%d{yyyy-MM-dd}'.
17:29:21,340 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over at midnight.
17:29:21,343 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Mon Aug 11 17:24:07 BRT 2014
17:29:21,346 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - Active log file name: LOG_PATH_IS_UNDEFINED/catalina.out
17:29:21,346 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - File property is set to [LOG_PATH_IS_UNDEFINED/catalina.out]
...
17:29:21,358 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.

And then after that it start configuring logback again but this time using the path i set:

17:29:21,672 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
17:29:21,673 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - No compression will be used
17:29:21,673 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern C:/var/log/pincode//catalina.out.%d{yyyy-MM-dd} for the active file
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd' from file name pattern 'C:/var/log/pincode//catalina.out.%d{yyyy-MM-dd}'.
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over at midnight.
17:29:21,674 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Mon Aug 11 17:29:21 BRT 2014
17:29:21,674 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - Active log file name: C:/var/log/pincode//catalina.out
17:29:21,674 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[serverConsole] - File property is set to [C:/var/log/pincode//catalina.out]
...
17:29:21,685 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.

My logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<include resource="org/springframework/boot/logging/logback/basic.xml" />
<property name="FILE_LOG_PATTERN"
    value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } [%t] --- %-40.40logger{39} : %m%n%wex" />

<appender name="serverConsole"
          class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/catalina.out</File>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/catalina.out.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<appender name="server"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/pincode.log</File>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>INFO</level>
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/pincode.log.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<appender name="server-error"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <Append>true</Append>
    <File>${LOG_PATH}/pincode-error.log</File>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>ERROR</level>
        <onMatch>ACCEPT</onMatch>
        <onMismatch>DENY</onMismatch>
    </filter>
    <encoder>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_PATH}/pincode-error.log.%d{yyyy-MM-dd}
        </fileNamePattern>
        <maxHistory>15</maxHistory>
    </rollingPolicy>
</appender>

<logger name="com.app" level="INFO">
    <appender-ref ref="server" />
    <appender-ref ref="server-error" />
</logger>

<root level="INFO">
    <appender-ref ref="serverConsole" />
</root>

If I remove my logback.xml file from the project it doesn't create the folder, so somewhere Spring is loading the xml before parsing the yml?

How can I avoid Logback to create this LOG_PATH_IS_UNDEFINED directory?

ContentLicense: CC BY-SA 4.0


问:
How to clear the array index using jquery?
```<code>var items=[];

items.push(data);
</code>```

I am using an array to store my data, and then submit using ajax. For the first time submission, it works fine. But when submit subsequently, it will submit null value together with data passing to server.

I am using the method below to clear the array, but i found that the previous data just set to null. For example, for the first time i passed value 1, successful. For the second submission, i clear the array and store new value, e.g. i pushed value 2 to the items[], when submit it will submit null and 2.

```<code>items.splice(0);
</code>```

How can i fix it? I need to reset the array every time submit the value.

Code:

```<code>var items=[];
$("#selection").click(function(e) {
       $(":checkbox").each(function() {
            if(this.checked === false) {
                this.checked = true;
                items.push(this.id);
            }
        });
});

$('#grid').submit(function(e){
            e.preventDefault();
            var formdata = {
                data:items
            };
            $.ajax({
                type: "POST",
                url: "/add",
                data: formdata ,
                dataType:'html',
                success: function(data) {
                    alert("added");
                }
            });
        });
</code>```

答:
If you want to reset all array till leave it empty you can do this :

```<code>var array = [1,2,3,4,5,6];
array.length = 0;
</code>```

it that way you can reset your array

Updated

when you use :

```<code>array.splice(0) // this will delete items from index that you passed, only if you passed the first parameters
</code>```

Hope it helps you.

Thank you for the note @nnnnnn

Body:
var items=[];

items.push(data);

I am using an array to store my data, and then submit using ajax. For the first time submission, it works fine. But when submit subsequently, it will submit null value together with data passing to server.

I am using the method below to clear the array, but i found that the previous data just set to null. For example, for the first time i passed value 1, successful. For the second submission, i clear the array and store new value, e.g. i pushed value 2 to the items[], when submit it will submit null and 2.

items.splice(0);

How can i fix it? I need to reset the array every time submit the value.

Code:

var items=[];
$("#selection").click(function(e) {
       $(":checkbox").each(function() {
            if(this.checked === false) {
                this.checked = true;
                items.push(this.id);
            }
        });
});

$('#grid').submit(function(e){
            e.preventDefault();
            var formdata = {
                data:items
            };
            $.ajax({
                type: "POST",
                url: "/add",
                data: formdata ,
                dataType:'html',
                success: function(data) {
                    alert("added");
                }
            });
        });

Body:
If you want to reset all array till leave it empty you can do this :

var array = [1,2,3,4,5,6];
array.length = 0;

it that way you can reset your array

Updated

when you use :

array.splice(0) // this will delete items from index that you passed, only if you passed the first parameters

Hope it helps you.

Thank you for the note @nnnnnn


问:
How to parse a file matching all the lines for a string and keep track of count?
We have a file with following lines in it,
we need to find all the lines with "Error" message type..
save the message and its count and print the messages in the descending order of count,can anyone provide guidance on how to do this?

file.txt

```<code><TIMESTAMP><MESSAGETYPE><MESSAGE>
<4:02><ERROR><Error message1>
<14:13><Error><Error message2>
<10:03><Warning><Warning message1>
<12:03><Warning><Warning message2>
</code>```

CODE:-

答:
You could do something like this:

```<code>from collections import defaultdict
import operator
import re

def find_error_message(string):
    match = re.search(r"<\d{1,2}:\d{2}><(ERROR|Error)><(?P<message>[a-zA-z0-9 ]*)>(\n)?", string)
    if match:
        return match.group("message")

messages = defaultdict(int)
with open(r"log.txt", "r") as fh:
    lines = fh.readlines()

lines.pop(0)
for line in lines:
    message = find_error_message(line)
    if message:
        messages[message] += 1
for message, count in sorted(messages.items(), key=operator.itemgetter(1), reverse=True):
    print("{}: {}".format(message, count))
</code>```

The find_error_message function is just checking each line in the file to see if it's an error, and returning the error message if it is.

The file log.txt is opened, and all the lines in it are read into a list. Then we pop the first element, which is the header. Then we go through each line, and check it to see if there's an error message. If there is we increase the count for that particular error message.

Once we've checked all the lines, we sort the dictionary messages, except that we want to a) sort it by the dictionary values, and b) sort it in reverse.

Finally, we print the sorted elements in order, and the number of times they occurred.

Body:
We have a file with following lines in it,
we need to find all the lines with "Error" message type..
save the message and its count and print the messages in the descending order of count,can anyone provide guidance on how to do this?

file.txt

<TIMESTAMP><MESSAGETYPE><MESSAGE>
<4:02><ERROR><Error message1>
<14:13><Error><Error message2>
<10:03><Warning><Warning message1>
<12:03><Warning><Warning message2>

CODE:-

Body:
You could do something like this:

from collections import defaultdict
import operator
import re

def find_error_message(string):
    match = re.search(r"<\d{1,2}:\d{2}><(ERROR|Error)><(?P<message>[a-zA-z0-9 ]*)>(\n)?", string)
    if match:
        return match.group("message")

messages = defaultdict(int)
with open(r"log.txt", "r") as fh:
    lines = fh.readlines()

lines.pop(0)
for line in lines:
    message = find_error_message(line)
    if message:
        messages[message] += 1
for message, count in sorted(messages.items(), key=operator.itemgetter(1), reverse=True):
    print("{}: {}".format(message, count))

The find_error_message function is just checking each line in the file to see if it's an error, and returning the error message if it is.

The file log.txt is opened, and all the lines in it are read into a list. Then we pop the first element, which is the header. Then we go through each line, and check it to see if there's an error message. If there is we increase the count for that particular error message.

Once we've checked all the lines, we sort the dictionary messages, except that we want to a) sort it by the dictionary values, and b) sort it in reverse.

Finally, we print the sorted elements in order, and the number of times they occurred.


问:
iOS 11: App is crashing only in iOS 11 not in the lower versions
I am creating on camera application and I am constantly getting crash in iOS 11 but app is working fine in lower version of iOS. Crash I am getting in log console is as below:

```<code>-[__NSArrayI name]: unrecognized selector sent to instance 0x608000446570
</code>```

I haven’t use any dictionary or any array which contains key “name” and it is giving me this crash log.

Exception break point is also not helpful in this crash. I have used many arrays in my application but none of them are causing crash i think. I am now out of option.

I am using xCode 9 beta version and running app in iOS 11 beta 1 and 2. in both versions it is crashing.

Any help or conceptual solution will be highly appreciated.

Thanks in advance.

答:
The problem is with my code. I added filters in my preview layer and one or more those filters are not supported in iOS 11 so it was crashing application.

Here is the code line which is crashing application without indicating anything.

```<code>[[previewView layer] setFilters:@[filterArray]];
</code>```

Thank you all of you for your suggestions and helps.

I really appreciated it.

Body:
I am creating on camera application and I am constantly getting crash in iOS 11 but app is working fine in lower version of iOS. Crash I am getting in log console is as below:

-[__NSArrayI name]: unrecognized selector sent to instance 0x608000446570

I haven’t use any dictionary or any array which contains key “name” and it is giving me this crash log.

Exception break point is also not helpful in this crash. I have used many arrays in my application but none of them are causing crash i think. I am now out of option.

I am using xCode 9 beta version and running app in iOS 11 beta 1 and 2. in both versions it is crashing.

Any help or conceptual solution will be highly appreciated.

Thanks in advance.

Body:
The problem is with my code. I added filters in my preview layer and one or more those filters are not supported in iOS 11 so it was crashing application.

Here is the code line which is crashing application without indicating anything.

[[previewView layer] setFilters:@[filterArray]];

Thank you all of you for your suggestions and helps.

I really appreciated it.


问:
Deleting multiple attributes in Nifi
I am aware of how to delete a single attribute in Nifi, but what is the proper syntax to delete multiple attributes? Do I have to use multiple UpdateAttributes transformations or is there a delimiter I can use to separate the attributes?

Thank you!

答:
The UpdateAttribute processor's Delete Attribute Express is a regular expression, and you can delete multiple attributes with simple regex:

```<code>attribute1|attribute2|attribute3
</code>```

or more complicated rules:

```<code>attribute\d
</code>```

Title: Deleting multiple attributes in Nifi

Body:
The UpdateAttribute processor's Delete Attribute Express is a regular expression, and you can delete multiple attributes with simple regex:

attribute1|attribute2|attribute3

or more complicated rules:

attribute\d


问:
Order of linear algebra operations in Julia
If I have a command y = A*B*x where A & B are large matrices and x & y are vectors, will Julia preform y = ((A*B)*x) or y = (A*(B*x))?

The second option should be the best as it only has to allocate an extra vector rather than a large matrix.

答:
The best way to verify this kind of thing is to dump the lowered code via @code_lowered macro:

```<code>julia> @code_lowered A * B * x
CodeInfo(:(begin
        nothing
        return (Core._apply)(Base.afoldl, (Core.tuple)(Base.*, (a * b) * c), xs)
    end))
</code>```

Like many other languages, Julia does y = (A*B)*x instead of y = A*(B*x), so it's up to you to explicitly use parens to reduce the allocation.

```<code>julia> using BenchmarkTools

julia> @btime $A * ($B * $x);
  6.800 μs (2 allocations: 1.75 KiB)

julia> @btime $A * $B * $x;
  45.453 μs (3 allocations: 79.08 KiB)
</code>```

Body:
The best way to verify this kind of thing is to dump the lowered code via @code_lowered macro:

julia> @code_lowered A * B * x
CodeInfo(:(begin
        nothing
        return (Core._apply)(Base.afoldl, (Core.tuple)(Base.*, (a * b) * c), xs)
    end))

Like many other languages, Julia does y = (A*B)*x instead of y = A*(B*x), so it's up to you to explicitly use parens to reduce the allocation.

julia> using BenchmarkTools

julia> @btime $A * ($B * $x);
  6.800 μs (2 allocations: 1.75 KiB)

julia> @btime $A * $B * $x;
  45.453 μs (3 allocations: 79.08 KiB)


问:
SQL Server rounding differently based on data type
Why does rounding in SQL Server behave non-intuitively?

```<code>SELECT CAST(     19.845           AS DECIMAL(18, 2)) AS [DecOK]
      ,CAST(CAST(19.845 AS FLOAT) AS DECIMAL(18, 2)) AS [DecBad]
      ,CAST(19.845 AS FLOAT)          AS [Float]
      ,CAST(19.845 AS FLOAT) - 19.845 AS [NoDiff]
      ,ROUND(     19.845          , 2) AS [RoundOK]
      ,ROUND(CAST(19.845 AS FLOAT), 2) AS [RoundBad]
</code>```

Actual:

```<code>DecOK   DecBad  Float   NoDiff  RoundOK RoundBad
19.85   19.84   19.845  0       19.850  19.84
</code>```

Expected:

```<code>DecOK   DecBad  Float   NoDiff  RoundOK RoundBad
19.85   19.85   19.845  0       19.850  19.85
</code>```

I would expect the value to be the same, regardless of the data type. How can I guarantee accurate results when working with FLOATs? Is the NoDiff value implicitly converting the second value to a FLOAT which is why the result is exactly 0?

答:
Float is an approximate precision.  If you want precision, use DECIMAL or NUMERIC which are the same thing.

There are a lot of posts on this but here is a great one.

https://stackoverflow.com/a/7158770

Body:
Why does rounding in SQL Server behave non-intuitively?

SELECT CAST(     19.845           AS DECIMAL(18, 2)) AS [DecOK]
      ,CAST(CAST(19.845 AS FLOAT) AS DECIMAL(18, 2)) AS [DecBad]
      ,CAST(19.845 AS FLOAT)          AS [Float]
      ,CAST(19.845 AS FLOAT) - 19.845 AS [NoDiff]
      ,ROUND(     19.845          , 2) AS [RoundOK]
      ,ROUND(CAST(19.845 AS FLOAT), 2) AS [RoundBad]

Actual:

DecOK   DecBad  Float   NoDiff  RoundOK RoundBad
19.85   19.84   19.845  0       19.850  19.84

Expected:

DecOK   DecBad  Float   NoDiff  RoundOK RoundBad
19.85   19.85   19.845  0       19.850  19.85

I would expect the value to be the same, regardless of the data type. How can I guarantee accurate results when working with FLOATs? Is the NoDiff value implicitly converting the second value to a FLOAT which is why the result is exactly 0?


问:
Copy array in constexpr constructor
I wrote a class with a constexpr copy constructor. (It is a struct in example to make it simpler.) One of the fields is an array. I want copy it too.

```<code>struct Foo
{
    static constexpr int SIZE = 4;
    constexpr Foo() = default;
    constexpr Foo(const Foo &foo) :
            arr{foo.arr[0], foo.arr[1], foo.arr[2], foo.arr[3]},
            bar(foo.bar+1) {}
    int arr[SIZE] = {0, 0, 0, 0};
    int bar = 0;
};
</code>```

My version works but it isn't scalable. If I change SIZE, I have to modify the constructor. In addition, code looks ugly.

Is it any better way to copy array in constructor? Constructor must be constexpr.

答:
you can do something like in C++11 to just copy the array

```<code>template <int LENGTH>
constexpr bool copy_array(const char (&from)[LENGTH + 1], char (&to)[LENGTH], int index)
{
    return index < LENGTH ?  (to[index] = from[index], copy_array(from, to, ++index)) : false;
}

constexpr char src[] = "ab";
char dest[2];
copy_array(src, dest, 0);
</code>```

edited:
And in your context, you might be able to do something like:

```<code>#include <iostream>
#include <type_traits>
#include <array>
#include <utility>

struct Foo
{
    static constexpr int SIZE = 4;
    constexpr Foo() = default;
    constexpr Foo(const Foo &foo) :
            arr{foo.arr},
            bar(foo.bar + 1) {}
    std::array<int, SIZE> arr = {{0, 0, 0, 0}};
    int bar = 0;
};

int main()
{
    constexpr Foo foo1;
    constexpr Foo foo2(foo1);

    std::cout << foo1.bar << std::endl;
    std::cout << foo2.bar << std::endl;

    return 0;
}
</code>```

Title: Copy array in constexpr constructor

Body:
I wrote a class with a constexpr copy constructor. (It is a struct in example to make it simpler.) One of the fields is an array. I want copy it too.

struct Foo
{
    static constexpr int SIZE = 4;
    constexpr Foo() = default;
    constexpr Foo(const Foo &foo) :
            arr{foo.arr[0], foo.arr[1], foo.arr[2], foo.arr[3]},
            bar(foo.bar+1) {}
    int arr[SIZE] = {0, 0, 0, 0};
    int bar = 0;
};

My version works but it isn't scalable. If I change SIZE, I have to modify the constructor. In addition, code looks ugly.

Is it any better way to copy array in constructor? Constructor must be constexpr.

Body:
you can do something like in C++11 to just copy the array

template <int LENGTH>
constexpr bool copy_array(const char (&from)[LENGTH + 1], char (&to)[LENGTH], int index)
{
    return index < LENGTH ?  (to[index] = from[index], copy_array(from, to, ++index)) : false;
}

constexpr char src[] = "ab";
char dest[2];
copy_array(src, dest, 0);

edited:
And in your context, you might be able to do something like:

#include <iostream>
#include <type_traits>
#include <array>
#include <utility>

struct Foo
{
    static constexpr int SIZE = 4;
    constexpr Foo() = default;
    constexpr Foo(const Foo &foo) :
            arr{foo.arr},
            bar(foo.bar + 1) {}
    std::array<int, SIZE> arr = {{0, 0, 0, 0}};
    int bar = 0;
};

int main()
{
    constexpr Foo foo1;
    constexpr Foo foo2(foo1);

    std::cout << foo1.bar << std::endl;
    std::cout << foo2.bar << std::endl;

    return 0;
}


问:
How do I display my database in table form using PHP html?
How do I display my database in table form. Here my code:

```<code><?php

$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"order");
$res=mysqli_query($link,"select * from ordersum");
while($row=mysqli_fetch_array($res))
{

echo $row["name"]." ".$row["email"]." ".$row["content"]." ".$row["date"]." ".$row["amount"];
echo "<br>";

}

?>
</code>```

答:
I try use this code.

```<code><html>
<body>

<?php
echo "<table style='border: solid 1px black;'>";
 echo "<tr><th>Name</th><th>Email</th><th>Content</th><th>Date</th><th>Amount</th></tr>";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td style='width: 150px; border: 1px solid black;'>" . parent::current(). "</td>";
    }

    function beginChildren() {
        echo "<tr>";
    }

    function endChildren() {
        echo "</tr>" . "\n";
    }
}

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "order";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM ordersum");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

</body>
</html>

<?php

$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"order");
$res=mysqli_query($link,"select * from ordersum");

?>
</code>```

Body:
How do I display my database in table form. Here my code:

<?php

$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"order");
$res=mysqli_query($link,"select * from ordersum");
while($row=mysqli_fetch_array($res))
{

echo $row["name"]." ".$row["email"]." ".$row["content"]." ".$row["date"]." ".$row["amount"];
echo "
";

}

?>

Body:
I try use this code.

<html>
<body>

<?php
echo "<table style='border: solid 1px black;'>";
 echo "<tr><th>Name</th><th>Email</th><th>Content</th><th>Date</th><th>Amount</th></tr>";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td style='width: 150px; border: 1px solid black;'>" . parent::current(). "</td>";
    }

    function beginChildren() {
        echo "<tr>";
    }

    function endChildren() {
        echo "</tr>" . "\n";
    }
}

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "order";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM ordersum");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

</body>
</html>

<?php

$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"order");
$res=mysqli_query($link,"select * from ordersum");

?>


问:
colors and border setting in itextsharp
I am trying to set the border and color for my pdf cells.

```<code>PdfPCell[] headingcell = new PdfPCell[] {
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc_abc_abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
            };

            headingcell[0].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[1].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[2].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[3].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[4].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[5].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[6].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[7].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[8].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[9].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[10].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[11].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[12].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[13].BackgroundColor = BaseColor.DARK_GRAY;

            headingcell[0].BorderWidth = 0;
            headingcell[1].BorderWidth = 0;
            headingcell[2].BorderWidth = 0;
            headingcell[3].BorderWidth = 0;
            headingcell[4].BorderWidth = 0;
            headingcell[5].BorderWidth = 0;
            headingcell[6].BorderWidth = 0;
            headingcell[7].BorderWidth = 0;
            headingcell[8].BorderWidth = 0;
            headingcell[9].BorderWidth = 0;
            headingcell[10].BorderWidth = 0;
            headingcell[11].BorderWidth = 0;
            headingcell[12].BorderWidth = 0;
            headingcell[13].BorderWidth = 0;
            table.Rows.Add(new PdfPRow(headingcell));
</code>```

I am able to achieve what I want with this coding, but I would like to ask is there a more efficient way to achieve this? Because these codes is so long only for this small thing.

答:
Put your parameters into an array or an dictionary, for example:

```<code>      List<object[]> data= new List<object[]>
        {
            new object[] {"abc", "font9"},
            new object[] {"abc", "font9"},
            new object[] {"abc", "font9"},
            new object[] {"abc", "font9"},
            new object[] {"abc_abc_abc", "font9"},
            // etc...
        };
</code>```

Then you can do all of your work with a single LINQ statement:

```<code>        PdfCell[] cells = data.Select(x =>
        {
           return new PdfCell(new Phrase(x[0], x[1]))
            {
                BackgroundColor = BaseColor.DARK_GRAY,
                BorderWidth = 0
            };
        }).ToArray();
</code>```

Title: colors and border setting in itextsharp

Body:
I am trying to set the border and color for my pdf cells.

PdfPCell[] headingcell = new PdfPCell[] {
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc_abc_abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
            };

            headingcell[0].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[1].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[2].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[3].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[4].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[5].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[6].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[7].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[8].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[9].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[10].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[11].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[12].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[13].BackgroundColor = BaseColor.DARK_GRAY;

            headingcell[0].BorderWidth = 0;
            headingcell[1].BorderWidth = 0;
            headingcell[2].BorderWidth = 0;
            headingcell[3].BorderWidth = 0;
            headingcell[4].BorderWidth = 0;
            headingcell[5].BorderWidth = 0;
            headingcell[6].BorderWidth = 0;
            headingcell[7].BorderWidth = 0;
            headingcell[8].BorderWidth = 0;
            headingcell[9].BorderWidth = 0;
            headingcell[10].BorderWidth = 0;
            headingcell[11].BorderWidth = 0;
            headingcell[12].BorderWidth = 0;
            headingcell[13].BorderWidth = 0;
            table.Rows.Add(new PdfPRow(headingcell));

I am able to achieve what I want with this coding, but I would like to ask is there a more efficient way to achieve this? Because these codes is so long only for this small thing.

Body:
Put your parameters into an array or an dictionary, for example:

      List<object[]> data= new List<object[]>
        {
            new object[] {"abc", "font9"},
            new object[] {"abc", "font9"},
            new object[] {"abc", "font9"},
            new object[] {"abc", "font9"},
            new object[] {"abc_abc_abc", "font9"},
            // etc...
        };

Then you can do all of your work with a single LINQ statement:

        PdfCell[] cells = data.Select(x =>
        {
           return new PdfCell(new Phrase(x[0], x[1]))
            {
                BackgroundColor = BaseColor.DARK_GRAY,
                BorderWidth = 0
            };
        }).ToArray();


问:
How to exclude 'out of stock' items from the front page?
I'm currently using Magento 1.1.6. My store only sells unique items (shirts with exclusive designs) which means at any one time, only 1 unit is available for each items.

How do I omit those items which are already sold from being displayed in the front page?

BTW, I'm using these code to show products on the front page:

```<code>{{block type="catalog/product_list" category_id="3" template="catalog/product/list_home_batik.phtml"}}
</code>```

答:
I supposed the file catalog/product/list_home_batik.phtml is based on catalog/product/list.phtml

You can modify the file catalog/product/list_home_batik.phtml by adding

```<code><?php if($_product->isSaleable()): ?>
</code>```

just after

```<code><?php foreach ($_productCollection as $_product): ?>
</code>```

and by adding

```<code><?php foreach ($_productCollection as $_product): ?>
</code>```

just before

```<code><?php endforeach; ?>
</code>```

If it doesn't work, you should provide the complete file so I can have a look at it.

OwnerDisplayName: aeran

Body:
I'm currently using Magento 1.1.6. My store only sells unique items (shirts with exclusive designs) which means at any one time, only 1 unit is available for each items.

How do I omit those items which are already sold from being displayed in the front page?

BTW, I'm using these code to show products on the front page:

{{block type="catalog/product_list" category_id="3" template="catalog/product/list_home_batik.phtml"}}

Body:
I supposed the file catalog/product/list_home_batik.phtml is based on catalog/product/list.phtml

You can modify the file catalog/product/list_home_batik.phtml by adding

<?php if($_product->isSaleable()): ?>

just after

<?php foreach ($_productCollection as $_product): ?>

and by adding

<?php foreach ($_productCollection as $_product): ?>

just before

<?php endforeach; ?>

If it doesn't work, you should provide the complete file so I can have a look at it.

OwnerDisplayName: stunti


问:
Export PATH command - 'export PATH=~/anaconda3/bin:$PATH'
I have installed anaconda in my Linux to import python packages.

After installed anaconda, I could't use anaconda in python and after some search I found that typing this command I was abled to use conda packages:

```<code>export PATH=~/anaconda3/bin:$PATH
</code>```

Would I like to understand exactly why do I have to do that?
And would I like to know if is there a way to turn by default my python with anaconda packages.

答:
If you just type ls at the command line, how does the shell know whether you want to run /bin/ls, or /usr/bin/ls, or ~/bin/ls? It doesn't; it simply looks at the directories stored in your PATH variable, one at a time, and executes the first ls that it finds.

Adding ~/anaconda3/bin to the front of your path ensures that when you type, say, pyflakes or python at your prompt, you will run ~/anaconda3/bin/pyflakes or ~/anaconda3/bin/python instead of generating a "command not found" error or running /usr/bin/pyflakes or /usr/bin/python instead.

Body:
I have installed anaconda in my Linux to import python packages.

After installed anaconda, I could't use anaconda in python and after some search I found that typing this command I was abled to use conda packages:

export PATH=~/anaconda3/bin:$PATH

Would I like to understand exactly why do I have to do that?
And would I like to know if is there a way to turn by default my python with anaconda packages.


问:
update a List with structs Elixir
I have an an object as

```<code>%{
  shares: []
}
</code>```

I want to add a struct %Cs{name: "Junaid1"}, %Cs{name: "Junaid2"} into the list through Enum.each or map, is that possible to do?

Okay for just more brief I am updating question again..

```<code> Enum.each(email_array, fn (email) ->
    with {:found_user, sharee} <- ensure_user(email)
    do
      case CameraShare.create_share(camera, sharee, caller, params["rights"], params["message"]) do
        {:ok, camera_share} ->
           #Add camera_share to list
        {:error, changeset} ->
          #Add error to a list
      end
    else
      {:not_found, email} ->
        case CameraShareRequest.create_share_request(camera, email, caller, params["rights"], params["message"]) do
          {:ok, camera_share_request} ->
            #Add camera_share to list
          {:error, changeset} ->
            #Add error to list
        end
    end
  end)
</code>```

and then at the end of Enum.each.. there will be a map as

```<code>%{
   shares: [all shares],
   errors: [all errors]
}
</code>```

where as each share is of type %CameraShare{__meta__: #Ecto.Schema.Metadata<:loaded, "camera_shares">}

答:
You can create a simple method like this:

```<code>def add_share(%{shares: shares} = map, share) do
  %{ map | shares: [share | shares] }
end
</code>```

And call it to add items to the lists in the map:

```<code>%{shares: []}
|> add_share(%Cs{name: "Junaid1"})
|> add_share(%Cs{name: "Junaid2"})
</code>```

Result:

```<code>%{shares: [%Cs{name: "Junaid2"}, %Cs{name: "Junaid1"}]}
</code>```

Title: update a List with structs Elixir

Body:
I have an an object as

%{
  shares: []
}

I want to add a struct %Cs{name: "Junaid1"}, %Cs{name: "Junaid2"} into the list through Enum.each or map, is that possible to do?

Okay for just more brief I am updating question again..

 Enum.each(email_array, fn (email) ->
    with {:found_user, sharee} <- ensure_user(email)
    do
      case CameraShare.create_share(camera, sharee, caller, params["rights"], params["message"]) do
        {:ok, camera_share} ->
           #Add camera_share to list
        {:error, changeset} ->
          #Add error to a list
      end
    else
      {:not_found, email} ->
        case CameraShareRequest.create_share_request(camera, email, caller, params["rights"], params["message"]) do
          {:ok, camera_share_request} ->
            #Add camera_share to list
          {:error, changeset} ->
            #Add error to list
        end
    end
  end)

and then at the end of Enum.each.. there will be a map as

%{
   shares: [all shares],
   errors: [all errors]
}

where as each share is of type %CameraShare{__meta__: #Ecto.Schema.Metadata<:loaded, "camera_shares">}

Body:
You can create a simple method like this:

def add_share(%{shares: shares} = map, share) do
  %{ map | shares: [share | shares] }
end

And call it to add items to the lists in the map:

%{shares: []}
|> add_share(%Cs{name: "Junaid1"})
|> add_share(%Cs{name: "Junaid2"})

Result:

%{shares: [%Cs{name: "Junaid2"}, %Cs{name: "Junaid1"}]}


问:
How to handle strings with a block ( awk )
Each block starts with 'COL ID' in an input data.
I need to print 'COL ID' and JOB_subid if there is. As you can see in input data, 'COLID=2' has a job_subid(1 / left of table name) but 'COLID=3' or 'COLID=4' doesn't have.
For COLID=3/4, I want to print 'no_data' as it doesn't have any job_subid.
How can I handle this data?

AWK

```<code>/COL ID/        {JOBID=$4;}

/^[0-9]/ {
    JOB_SUBID=$1;
    printf "%s#%s",JOBID,JOB_SUBID;
    printf "\n";
}

END {

if (JOB_SUBID="") then
  JOB_SUBID="no_data";
  printf "%s#%s",JOBID,JOB_SUBID;
  printf "\n";
end if;

}
</code>```

input data

```<code>COL ID    : 2
PID       : 26788

ID     TABLE
------ ------------------------------
1      "SCOTT"."PRINCE01"

COL ID    : 3
PID       : 26788

COL ID    : 4
PID       : 26788
</code>```

Incorrect result

```<code>2#1
4#no_data
</code>```

Required result

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

答:
You may simply do this by

```<code>$ awk -v RS='COL ID' 'NR>1{print $2"#"($10==""?"no data":$10)}' file
2#1
3#no data
4#no data
</code>```

Brief explanation,

Set the record separator as COL ID

NR>1: Omit the first record

Check if $10 subid existed, print "no data" if not.

Body:
Each block starts with 'COL ID' in an input data.
I need to print 'COL ID' and JOB_subid if there is. As you can see in input data, 'COLID=2' has a job_subid(1 / left of table name) but 'COLID=3' or 'COLID=4' doesn't have.
For COLID=3/4, I want to print 'no_data' as it doesn't have any job_subid.
How can I handle this data?

AWK

/COL ID/        {JOBID=$4;}

/^[0-9]/ {
    JOB_SUBID=$1;
    printf "%s#%s",JOBID,JOB_SUBID;
    printf "\n";
}

END {

if (JOB_SUBID="") then
  JOB_SUBID="no_data";
  printf "%s#%s",JOBID,JOB_SUBID;
  printf "\n";
end if;

}

input data

COL ID    : 2
PID       : 26788

ID     TABLE
------ ------------------------------
1      "SCOTT"."PRINCE01"

COL ID    : 3
PID       : 26788

COL ID    : 4
PID       : 26788

Incorrect result

2#1
4#no_data

Required result

2#1
3#no_data
4#no_data

Body:
You may simply do this by

$ awk -v RS='COL ID' 'NR>1{print $2"#"($10==""?"no data":$10)}' file
2#1
3#no data
4#no data

Brief explanation,

Set the record separator as COL ID

NR>1: Omit the first record

Check if $10 subid existed, print "no data" if not.


问:
How to diagnose MS access crashes
We have a custom program written in Access that has odd crashes in it.  We have added error handling that records and emails any crashes that happen inside of our own code and that has allowed us to fix most errors that we have generated, but sometimes the crashes happen outside of our code.

An example of one that we found that cropped up new in 2013 -- we have a form that would crash after editing data in a certain field -- new entry was fine but any edits after the record was created would result in a full crash and shutdown of MS Access.  We spent time and eventually tracked down that some code of ours was forcing the form to move to the next record, this field was the final field on the row though so Access itself was also attempting to move to the next record.  This had been in the system since 2007, but started causing program shutdowns in 2013.

is there any way to trap and diagnose program level crashes inside MS access?

The windows event viewer only shows the following:

Faulting application name: MSACCESS.EXE, version: 15.0.4454.1501, time stamp: 0x50a35ef4
Faulting module name: MSACCESS.EXE, version: 15.0.4454.1501, time stamp: 0x50a35ef4
Exception code: 0xc0000005
Fault offset: 0x00116452
Faulting process id: 0x1398
Faulting application start time: 0x01ce6e665043d8be
Faulting application path: C:\Program Files (x86)\Microsoft Office\Office15\MSACCESS.EXE
Faulting module path: C:\Program Files (x86)\Microsoft Office\Office15\MSACCESS.EXE
Report Id: 6cfcb0eb-da62-11e2-8966-842b2b86f028

答:
For anyone else who stumbles across this thread in Google here are another couple of causes for random Access crashes:

Just for background, I have a form with a subform on it, loading data from linked tables on a server.

If you have "_Enter" events on the fields on the parent form this may cause Access to go into an endless loop, repeatedly firing these events.  This occurred when I was on the subform, and pressed a button on the parent form.  I replaced all these with "_GotFocus" events instead which fixed the problem.

Do not reference the subform in the onLoad even of the parent form.  This one was random, the form would load fine and then the next time you went into the same form, with the same record, it would cause Access to crash.  So I removed all references to the subform in the onLoad event of the parent form and it now seems to work fine.  I especially noticed this when my internet connection was slow, it appeared that the main form was loading before the subform and so when it referenced it it hadn't loaded and so caused all sorts of issues with Access, which invariable ended in a random crash of Access.

Title: How to diagnose MS access crashes


问:
Multiple encoding in database
I'm newbie working at databases, so be patient, please ;)

I've designed a table in mysql to store city names (and other stuff). I load the data from a UTF8 txt file with all the information.

The problem is that city names are written in their original form, so I've got charsets from China, Russia, England, Marocco, etc. When I load the file into the database, there are a lot of warnings because of that. I have done like this:

```<code>LOAD DATA LOCAL INFILE '/home/ommadawn/cities.txt' INTO TABLE myDB.cities CHARACTER SET UTF8 FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n' (country, city, lat, lon);
</code>```

All my charset is set to utf8 and collations too.

Where's the problem?

Thanks!

EDIT:

The warnings are like this:

```<code>Warning | 1366 | Incorrect string value: '\xCC\xA7uway...' for column 'city' at row 9
</code>```

And in this line, the text is:

```<code>AE  Z̧uwayhir   23.28333    53.2
</code>```

答:
Ugh.  In UTF-8, CCA7 is a "COMBINING CEDILLA".  So, it is destined to be combined with an adjacent letter to make an accented letter.  This page shows it as combining with the u; another experiment (in the same browser) had it combining with the Z: Z̧uwayhir.  Ugh.

Anyway, there seems to be such a place in the UAE.  And UTF-8 (MySQL's utf8 or utf8mb4) seems to be the encoding for it.

Back to the question...  Probably the column in the table was not declared to be CHARACTER SET utf8mb4.

Do you know if it truncated the text down to just Z?

Please provide SHOW VARIABLES LIKE 'char%';

Title: Multiple encoding in database

Body:
I'm newbie working at databases, so be patient, please ;)

I've designed a table in mysql to store city names (and other stuff). I load the data from a UTF8 txt file with all the information.

The problem is that city names are written in their original form, so I've got charsets from China, Russia, England, Marocco, etc. When I load the file into the database, there are a lot of warnings because of that. I have done like this:

LOAD DATA LOCAL INFILE '/home/ommadawn/cities.txt' INTO TABLE myDB.cities CHARACTER SET UTF8 FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n' (country, city, lat, lon);

All my charset is set to utf8 and collations too.

Where's the problem?

Thanks!

EDIT:

The warnings are like this:

Warning | 1366 | Incorrect string value: '\xCC\xA7uway...' for column 'city' at row 9

And in this line, the text is:

AE  Z̧uwayhir   23.28333    53.2


问:
SoapUI becomes unresponsive after starting on Mac OS X
Mac OS version: Sierra, 10.12.3
SoapUI version: 5.3.0

Steps to reproduce:

Launch SoapUI

Wait a few seconds

The mouse cursor turns into a colourwheel

Activity monitor shows the SoapUI process as not responding: need to kill the process to quit the app.

答:
Alternatively, you can navigate to SoapUI*.app, right-click and select "Show Package Info" (from popup menu). Then you should see Contents directory; open Info.plist and add the following lines:

```<code><key>soapui.jxbrowser.disable</key>
<true/>
</code>```

Body:
Alternatively, you can navigate to SoapUI*.app, right-click and select "Show Package Info" (from popup menu). Then you should see Contents directory; open Info.plist and add the following lines:

<key>soapui.jxbrowser.disable</key>
<true/>


问:
Vertical cut off of text in label with letters such as p and g
I have a label in a stack view that displays a variety of different text however when it displays p and g, the bottoms are cut off as you can see here.

Is there any way to prevent this?

Update: I need the size of my label to stay the same and rather the font size of the label to change.

答:
You could try adding

```<code>label.minimumScaleFactor = 0.5
           OR
label.adjustsFontSizeToFitWidth = true
</code>```

to your label

This seems to work only when width is insufficient but not height

Try this. It should do the trick

```<code>extension UILabel {

override open func layoutSubviews() {
    super.layoutSubviews()
    while self.font.pointSize > 1 {
        //check the contentSize, if it's less then the actual label height then it should fit
        //else change the font size
        if self.intrinsicContentSize.height < self.frame.size.height {
            break
        }
        self.font = self.font.withSize(font.pointSize - 1)
    }
}

}
</code>```

Body:
You could try adding

label.minimumScaleFactor = 0.5
           OR
label.adjustsFontSizeToFitWidth = true

to your label

This seems to work only when width is insufficient but not height

Try this. It should do the trick

extension UILabel {

override open func layoutSubviews() {
    super.layoutSubviews()
    while self.font.pointSize > 1 {
        //check the contentSize, if it's less then the actual label height then it should fit
        //else change the font size
        if self.intrinsicContentSize.height < self.frame.size.height {
            break
        }
        self.font = self.font.withSize(font.pointSize - 1)
    }
}

}