问:
How to integrate pretty-printing as part of build in bazel
Right now, I have a really dumb pretty-print script which does a little git-fu to find files to format (unconditionally) and then runs those through clang-format -i. This approach has several shortcomings:

There are certain files which are enormous and take forever to pretty print.

The pretty printing is always done, regardless of whether or not the underlying file actually changed or not.

In the past, I was able to do things with CMake that had several nice properties which I would like to reproduce in bazel:

Only ever build code after it has gone through linting / pretty printing / etc.

Only lint / pretty print / etc. stuff that has changed

Pretty print stuff regardless of whether or not it is under VC or not

In CMake-land, I used this strategy, inspired by SCons proxy-target trickery:

Introduce a dummy target (e.g. source -> source.formatted). The action associated with this target does two things: a) run clang-format -i source, b) output/touch a file called source.formatted (this guarantees that for reasonable file systems, if source.formatted is newer than source, source doesn't need to be reformatted)

Add a dummy target (target_name.aggregated_formatted) which aggregates all the .formatted files corresponding to a particular library / executable target's sources

Make library / executable targets depend on target_name.aggregated_formatted as a pre-build step

Any help would be greatly appreciated.

答:
You might be able to use aspects for that. Being not certain, a Bazel-dev will probably point that out if it indeed is possible.

If you are familiar with Rules and Actions and the like, the quick and dirty way (which is similar to the CMake hackery) is to write a Macro. For e.g. cc_library you would do:

```<code>def clean_cc_library(name, srcs, **kwargs):
  lint_sources(
      name = "%s_linted" % name,
      srcs = srcs,
  )

  pretty_print_sources(
      name = "%s_pretty" % name,
      srcs = ["%s_linted"],
  )

  return native.cc_library(
    name = name,
    srcs = ["%s_pretty"],
    **kwargs
  )
</code>```

Then you of course need to replace every cc_library with clean_cc_library. And lint_sources and pretty_print_sources are rules that you have to implement yourself and need to produce the list of cleaned up files.

Body:
You might be able to use aspects for that. Being not certain, a Bazel-dev will probably point that out if it indeed is possible.

If you are familiar with Rules and Actions and the like, the quick and dirty way (which is similar to the CMake hackery) is to write a Macro. For e.g. cc_library you would do:

def clean_cc_library(name, srcs, **kwargs):
  lint_sources(
      name = "%s_linted" % name,
      srcs = srcs,
  )

  pretty_print_sources(
      name = "%s_pretty" % name,
      srcs = ["%s_linted"],
  )

  return native.cc_library(
    name = name,
    srcs = ["%s_pretty"],
    **kwargs
  )

Then you of course need to replace every cc_library with clean_cc_library. And lint_sources and pretty_print_sources are rules that you have to implement yourself and need to produce the list of cleaned up files.


来源: stackexchange

问:
Toggle multi-level ul with mootools
Greetings,
I would like to toggle a huge multi-level ul with mootools 1.1 or plain javascript.
The list looks like:
HTML:

```<code> <ul>
    <li>aaa</li>
    <li>bbb</li>
    <li>ccc</li>
    <li>
        <ul>
            <li>ddd
                <ul>
                    <li>fff</li>
                    <li>ggg</li>
                </ul>
            </li>
            <li>eee</li>
        </ul>
    </li>
 </ul>
</code>```

What I would like to do initially is to show the first level expanded, and the other levels collapsed and when each of the list items is clicked, to expand the ul below it.

Is it possible to do it without (greatly) modifying the html above?
From the documentation, I see that Fx.Slide is the most appropriate, however it accepts the id of the element as a parameter, which means I have to assign id's to each list item.
Is there a way by using selectors of collections of elements starting from the top?

答:
I'm not sure whay I'll say apply with the very old 1.1 version. However, at least since 1.2, the element you need to pass is either the ID (like you said), either the actual element.

If you can use another version than 1.1, try the 1.3 which makes it easier to select the elements you want.

Here, I believe you need every
 element which has a direct
 as parent. MooTools 1.3 features this new selector engine Slick, which would accomplish it fairly easilly: ul !> li.

However, I'm not sure (I didn't success) that the direct child selectors works properly with 1.1.

Here is what I came up with: http://jsfiddle.net/rCfwq/

ContentLicense: CC BY-SA 2.5

Title: Toggle multi-level ul with mootools

Body:
Greetings,
I would like to toggle a huge multi-level ul with mootools 1.1 or plain javascript.
The list looks like:
HTML:

aaa

bbb

ccc

ddd

fff

ggg

eee

What I would like to do initially is to show the first level expanded, and the other levels collapsed and when each of the list items is clicked, to expand the ul below it.

Is it possible to do it without (greatly) modifying the html above?
From the documentation, I see that Fx.Slide is the most appropriate, however it accepts the id of the element as a parameter, which means I have to assign id's to each list item.
Is there a way by using selectors of collections of elements starting from the top?

Body:
I'm not sure whay I'll say apply with the very old 1.1 version. However, at least since 1.2, the element you need to pass is either the ID (like you said), either the actual element.

If you can use another version than 1.1, try the 1.3 which makes it easier to select the elements you want.

Here, I believe you need every <ul> element which has a direct <li> as parent. MooTools 1.3 features this new selector engine Slick, which would accomplish it fairly easilly: ul !> li.

However, I'm not sure (I didn't success) that the direct child selectors works properly with 1.1.

Here is what I came up with: http://jsfiddle.net/rCfwq/


问:
Throwing Exceptions from Exception class in java
Ok ... So I am learning about exceptions in java and i am currently at throw statements. I throw an exception of Exception class, and then re-throw it from the catch block again to handle it in the main function. But whenever i throw it as Exception class, i always get an Error in the catch block(where i re-throw it to be handled in main).But as soon as i change the thrown and caught Exceptions to some particular Exceptions like NullPointerException, it works!

Error Code:

```<code>class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(Exception e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new Exception("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(Exception e) {
           System.out.println("Please handle the error");
           throw e; // It gives me an error here
       }
    }
}
</code>```

Working Code:

```<code>class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(NullPointerException e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new NullPointerException("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(NullPointerException e) {
           System.out.println("Please handle the error");
           throw e;
       }
    }
}
</code>```

Why doesn't it work with Exception class and worked with its subclass??

Note :-  The error i get in the error code is Unhandled exception type Exception

答:
Runtime exceptions extend RuntimeException. They don’t have to be handled or declared.
They can be thrown by the programmer or by the JVM.

Checked exceptions have Exception in their hierarchy but not RuntimeException. They
must be handled or declared. They can be thrown by the programmer or by the JVM.

Errors extend the Error class. They are thrown by the JVM and should not be handled or
declared.

When method throws checked exception (1) you should handle or rethow it.

When method throws uncheked exception (2) you can handle or rethrow it, but it's not obligatory.

But whenever i throw it as Exception class, i always get an Error in
  the catch block(where i re-throw it to be handled in main)

It means that your method is throwing checked exception which should be handled or rethrowed.

Handling:

```<code>public class Main {

    public static void main(String[] args) {
        try {
            throw new Exception();
        } catch (Exception e) {
            try {
                throw new Exception();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
}
</code>```

Rethrowing:

```<code>public class Main {

    public static void main(String[] args) throws Exception {
        try {
            throw new Exception();
        } catch (Exception e) {
            throw new Exception();
        }
    }
}
</code>```

In your case:

```<code>// You declaring that the caller should handle exception
static void renderWorld() throws Exception {
       try {
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new Exception("3d mode Disabled.");
           } else {
                System.out.println("The World is Empty!");
           }
       } catch(Exception e) {
           System.out.println("Please handle the error");
           // You cannot just throw uncheked exception here
           // You should handle it yourself or a caller should do it
           throw e;
       }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Ok ... So I am learning about exceptions in java and i am currently at throw statements. I throw an exception of Exception class, and then re-throw it from the catch block again to handle it in the main function. But whenever i throw it as Exception class, i always get an Error in the catch block(where i re-throw it to be handled in main).But as soon as i change the thrown and caught Exceptions to some particular Exceptions like NullPointerException, it works!

Error Code:

class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(Exception e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new Exception("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(Exception e) {
           System.out.println("Please handle the error");
           throw e; // It gives me an error here
       }
    }
}

Working Code:

class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(NullPointerException e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new NullPointerException("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(NullPointerException e) {
           System.out.println("Please handle the error");
           throw e;
       }
    }
}

Why doesn't it work with Exception class and worked with its subclass??

Note :-  The error i get in the error code is Unhandled exception type Exception

Body:
Runtime exceptions extend RuntimeException. They don’t have to be handled or declared.
They can be thrown by the programmer or by the JVM.

Checked exceptions have Exception in their hierarchy but not RuntimeException. They
must be handled or declared. They can be thrown by the programmer or by the JVM.

Errors extend the Error class. They are thrown by the JVM and should not be handled or
declared.

When method throws checked exception (1) you should handle or rethow it.

When method throws uncheked exception (2) you can handle or rethrow it, but it's not obligatory.

But whenever i throw it as Exception class, i always get an Error in
  the catch block(where i re-throw it to be handled in main)

It means that your method is throwing checked exception which should be handled or rethrowed.

Handling:

public class Main {

    public static void main(String[] args) {
        try {
            throw new Exception();
        } catch (Exception e) {
            try {
                throw new Exception();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
}

Rethrowing:

public class Main {

    public static void main(String[] args) throws Exception {
        try {
            throw new Exception();
        } catch (Exception e) {
            throw new Exception();
        }
    }
}

In your case:

// You declaring that the caller should handle exception
static void renderWorld() throws Exception {
       try {
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new Exception("3d mode Disabled.");
           } else {
                System.out.println("The World is Empty!");
           }
       } catch(Exception e) {
           System.out.println("Please handle the error");
           // You cannot just throw uncheked exception here
           // You should handle it yourself or a caller should do it
           throw e;
       }
}


问:
Joining two table in oracle
I have two tables Mention and Retweet

Mention

```<code>ID     USER_SCREEN_NAME     USER_ID    MENTIONED_USER_ID  MENTIONED_USER_NAME
15           user1             1         9                    user 9
16           user 1            1         60                   user 6
18           user 3            3         60                   user 6
17           user 4            4         60                   user 6
</code>```

Retweet

```<code>ID  USER_ID  USER_SCREEN_NAME RETWEETED_STATUS_ID RETWEETED_USER_STATUS_ID  RETWEETED_USER_NAME
19     3       user 3                  400                    40          user 4
11     1       user 1                  38                     60          user 6
15     2       user 2                  500                    50          user 5
13     4       user 4                  38                     60          user 6
</code>```

What I want is a separate table with the information if a user has mentioned or retweeted or done both is included in the table so the output should be something like that (User_id (M) is mentioned user id and User_ID (R) is retweeted user id)

```<code> USER_ID (M)  USER_ID (R)   USER_S_NAME    MENTIONED_USER   RETWEETED_USER
    1             1           user 1          user 6            user 6
    1             1           user 1          user 9            Null
    3             3           user 3          user 6            Null
    3             3           user 3           Null             user 4
    4             4           user 4          user 6            user 6
    Null          2           user 2            Null            user 5
</code>```

However I'm getting this result

```<code> USER_ID (M)  USER_ID (R)   USER_S_NAME    MENTIONED_USER   RETWEETED_USER
    1             1           user 1          user 6            user 6
    1             1           user 1          user 9            Null
    3             3           user 3          user 6            Null
    4             4           user 4          user 6            user 6
    Null          2            Null            Null              Null
</code>```

it works fine for mention table but not for retweet table
 Here is my query

```<code>SELECT
    MT.USER_ID AS USER_ID,
    r.USER_ID AS USER__ID,
   mt.USER_SCREEN_NAME AS USER_S_NAME,
    mt.MENTIONED_USER_NAME AS MENTIONED_USER,
    (
        SELECT
            RETWEET.RETWEETED_USER_NAME
        FROM
            RETWEET
        WHERE
            RETWEETED_USER_STATUS_ID = mt.MENTIONED_USER_ID
        AND ROWNUM = 1
        AND USER_ID = MT.USER_ID
    ) AS RETWEETED_USER

FROM
    MENTIONS mt
FULL OUTER JOIN RETWEET r ON MT.USER_ID = r.USER_ID --where MT.M_USER_ID=r.O_USER_ID
GROUP BY
    MT.USER_ID,
  mt.USER_SCREEN_NAME,
    r.USER_ID,
    mt.MENTIONED_USER_NAME,
    MT.MENTIONED_USER_ID,
  r.RETWEETED_USER_STATUS_ID
ORDER BY
    mt.USER_ID
</code>```

答:
Simply add a JOIN clause to mention/retweet id fields. No need for GROUP BY and unclear why you need subquery. However, your full desired result cannot be achieved with FULL OUTER JOIN since nulls will be present for corresponding unmatched left or right tables:

```<code>SELECT
    mt.USER_ID AS "USER_ID (M)",
    r.USER_ID AS "USER__ID (R)",
    mt.USER_SCREEN_NAME AS "USER_S_NAME",
    mt.MENTIONED_USER_NAME AS "MENTIONED_USER",
    r.RETWEETED_USER_NAME AS "RETWEETED_USER"

FROM
    MENTION mt
FULL OUTER JOIN RETWEET r ON mt.USER_ID = r.USER_ID
   AND mt.MENTIONED_USER_ID = r.RETWEETED_USER_STATUS_ID

ORDER BY mt.user_id, r.user_id

-- USER_ID (M)  USER__ID (R)    USER_S_NAME     MENTIONED_USER  RETWEETED_USER
-- 1            1               user 1          user 6          user 6
-- 1            (null)          user1           user 9          (null)
-- 3            (null)          user 3          user 6          (null)
-- 4            4               user 4          user 6          user 6
-- (null)       2               (null)          (null)          user 5
-- (null)       3               (null)          (null)          user 4
</code>```

See SQL Fiddle which uses PostgresSQL 9.3 as dialect since Oracle is known not to work in fiddle.

Title: Joining two table in oracle

Body:
I have two tables Mention and Retweet

Mention

ID     USER_SCREEN_NAME     USER_ID    MENTIONED_USER_ID  MENTIONED_USER_NAME
15           user1             1         9                    user 9
16           user 1            1         60                   user 6
18           user 3            3         60                   user 6
17           user 4            4         60                   user 6

Retweet

ID  USER_ID  USER_SCREEN_NAME RETWEETED_STATUS_ID RETWEETED_USER_STATUS_ID  RETWEETED_USER_NAME
19     3       user 3                  400                    40          user 4
11     1       user 1                  38                     60          user 6
15     2       user 2                  500                    50          user 5
13     4       user 4                  38                     60          user 6

What I want is a separate table with the information if a user has mentioned or retweeted or done both is included in the table so the output should be something like that (User_id (M) is mentioned user id and User_ID (R) is retweeted user id)

 USER_ID (M)  USER_ID (R)   USER_S_NAME    MENTIONED_USER   RETWEETED_USER
    1             1           user 1          user 6            user 6
    1             1           user 1          user 9            Null
    3             3           user 3          user 6            Null
    3             3           user 3           Null             user 4
    4             4           user 4          user 6            user 6
    Null          2           user 2            Null            user 5

However I'm getting this result

 USER_ID (M)  USER_ID (R)   USER_S_NAME    MENTIONED_USER   RETWEETED_USER
    1             1           user 1          user 6            user 6
    1             1           user 1          user 9            Null
    3             3           user 3          user 6            Null
    4             4           user 4          user 6            user 6
    Null          2            Null            Null              Null

it works fine for mention table but not for retweet table
 Here is my query

SELECT
    MT.USER_ID AS USER_ID,
    r.USER_ID AS USER__ID,
   mt.USER_SCREEN_NAME AS USER_S_NAME,
    mt.MENTIONED_USER_NAME AS MENTIONED_USER,
    (
        SELECT
            RETWEET.RETWEETED_USER_NAME
        FROM
            RETWEET
        WHERE
            RETWEETED_USER_STATUS_ID = mt.MENTIONED_USER_ID
        AND ROWNUM = 1
        AND USER_ID = MT.USER_ID
    ) AS RETWEETED_USER

FROM
    MENTIONS mt
FULL OUTER JOIN RETWEET r ON MT.USER_ID = r.USER_ID --where MT.M_USER_ID=r.O_USER_ID
GROUP BY
    MT.USER_ID,
  mt.USER_SCREEN_NAME,
    r.USER_ID,
    mt.MENTIONED_USER_NAME,
    MT.MENTIONED_USER_ID,
  r.RETWEETED_USER_STATUS_ID
ORDER BY
    mt.USER_ID

Body:
Simply add a JOIN clause to mention/retweet id fields. No need for GROUP BY and unclear why you need subquery. However, your full desired result cannot be achieved with FULL OUTER JOIN since nulls will be present for corresponding unmatched left or right tables:

SELECT
    mt.USER_ID AS "USER_ID (M)",
    r.USER_ID AS "USER__ID (R)",
    mt.USER_SCREEN_NAME AS "USER_S_NAME",
    mt.MENTIONED_USER_NAME AS "MENTIONED_USER",
    r.RETWEETED_USER_NAME AS "RETWEETED_USER"

FROM
    MENTION mt
FULL OUTER JOIN RETWEET r ON mt.USER_ID = r.USER_ID
   AND mt.MENTIONED_USER_ID = r.RETWEETED_USER_STATUS_ID

ORDER BY mt.user_id, r.user_id

-- USER_ID (M)  USER__ID (R)    USER_S_NAME     MENTIONED_USER  RETWEETED_USER
-- 1            1               user 1          user 6          user 6
-- 1            (null)          user1           user 9          (null)
-- 3            (null)          user 3          user 6          (null)
-- 4            4               user 4          user 6          user 6
-- (null)       2               (null)          (null)          user 5
-- (null)       3               (null)          (null)          user 4

See SQL Fiddle which uses PostgresSQL 9.3 as dialect since Oracle is known not to work in fiddle.


问:
Laravel migration: unique key is too long, even if specified
I am trying to migrate a users table in Laravel. When I run my migration I get this error:

[Illuminate\Database\QueryException]   SQLSTATE[42000]: Syntax error
  or access violation: 1071 Specified key was too long; max key length
  is 767 bytes (SQL: alter table users add unique
  users_email_uniq(email))

my migration is as follows:

```<code>Schema::create('users', function(Blueprint $table)
{
    $table->increments('id');
    $table->string('name', 32);
    $table->string('username', 32);
    $table->string('email', 320);
    $table->string('password', 64);
    $table->string('role', 32);
    $table->string('confirmation_code');
    $table->boolean('confirmed')->default(true);
    $table->timestamps();

    $table->unique('email', 'users_email_uniq');
});
</code>```

After some googling I came across this bug report where Taylor says you can specify the index key as the 2nd parameter of unique(), which I have done. It still gives the error. What is going on here?

答:
I added to the migration itself

```<code>Schema::defaultStringLength(191);
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});
</code>```

yes, I know I need to consider it on every migration but I would rather that than have it tucked away in some completely unrelated service provider

Body:
I am trying to migrate a users table in Laravel. When I run my migration I get this error:

[Illuminate\Database\QueryException]   SQLSTATE[42000]: Syntax error
  or access violation: 1071 Specified key was too long; max key length
  is 767 bytes (SQL: alter table users add unique
  users_email_uniq(email))

my migration is as follows:

Schema::create('users', function(Blueprint $table)
{
    $table->increments('id');
    $table->string('name', 32);
    $table->string('username', 32);
    $table->string('email', 320);
    $table->string('password', 64);
    $table->string('role', 32);
    $table->string('confirmation_code');
    $table->boolean('confirmed')->default(true);
    $table->timestamps();

    $table->unique('email', 'users_email_uniq');
});

After some googling I came across this bug report where Taylor says you can specify the index key as the 2nd parameter of unique(), which I have done. It still gives the error. What is going on here?

Body:
I added to the migration itself

Schema::defaultStringLength(191);
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

yes, I know I need to consider it on every migration but I would rather that than have it tucked away in some completely unrelated service provider


问:
Bit shift in array and write score to another array
I write method to bit shift by one in array and save to second array. Let me explain on below example:

```<code> unsigned int firstNumber[2]  = { 0x00000001, 0x8FFFFFFF };
 unsigned int resultNumber[2];
</code>```

And result should be:

```<code>unsigned int resultNumber[2] = { 0x00000000, 0xC7FFFFFF };
</code>```

Below this is my function:

```<code>void bitShiftByOneInRight_1(unsigned int firstNumber[2], unsigned int resultNumber[2])
{
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {
        resultNumber[i] = 0;
        //  example        11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        resultNumber[i] = firstNumber[i] >> 1;
        resultNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled  = lastBit;
    }
}
</code>```

I get answer as the same array firstNumber[2]:

```<code>unsigned int resultNumber[2] = { 0x00000001, 0x8FFFFFFF };
</code>```

Simple example, we have array:
 [0b00000001, 0b01111111] then answer should be
 [0b00000000, 0b10111111]

Furthermore when function is this form, which mean use one argument as input and output method, work correctly:

```<code>void bitShiftByOneInRight(unsigned int firstNumber[2]) {
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {

        //  example         11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        firstNumber[i] = firstNumber[i] >> 1;
        firstNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled = lastBit;
    }

}
</code>```

Anyone know what I make wrong?
Each answer is welcome for me! Thanks

答:
```<code>#include <stdio.h>
#include <stdint.h>

void shift_right(uint32_t *dst, uint32_t *src, size_t len) {
  if (len == 0) return;
  for (size_t i = len - 1; i > 0; i--){
    dst[i] = (src[i] >> 1) | (src[i-1] << 31);
  }
  dst[0] = src[0] >> 1;
}
</code>```

Body:
I write method to bit shift by one in array and save to second array. Let me explain on below example:

 unsigned int firstNumber[2]  = { 0x00000001, 0x8FFFFFFF };
 unsigned int resultNumber[2];

And result should be:

unsigned int resultNumber[2] = { 0x00000000, 0xC7FFFFFF };

Below this is my function:

void bitShiftByOneInRight_1(unsigned int firstNumber[2], unsigned int resultNumber[2])
{
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {
        resultNumber[i] = 0;
        //  example        11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        resultNumber[i] = firstNumber[i] >> 1;
        resultNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled  = lastBit;
    }
}

I get answer as the same array firstNumber[2]:

unsigned int resultNumber[2] = { 0x00000001, 0x8FFFFFFF };

Simple example, we have array:
 [0b00000001, 0b01111111] then answer should be
 [0b00000000, 0b10111111]

Furthermore when function is this form, which mean use one argument as input and output method, work correctly:

void bitShiftByOneInRight(unsigned int firstNumber[2]) {
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {

        //  example         11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        firstNumber[i] = firstNumber[i] >> 1;
        firstNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled = lastBit;
    }

}

Anyone know what I make wrong?
Each answer is welcome for me! Thanks


问:
Logging User actions on Android
Is there a way to log a user's activity on an app. Basically, information like widget clicks, text inputs, swipes etc. I want these logs for my test case creation. </p>

答:
Yes you can use  Google Analytics or Firebase Analytics.

Firebase has multiple useful services. i like using it.

Title: Logging User actions on Android


问:
How can I get greasemonkey to call a function on a page after it loads
I have a very simple greasemonkey script that I want to call an already existing javascript function on the page. I've read the documentation and nothing seems to work</p>

```<code>window.setTimeout(function() {
    alert('test') // This alert works, but nothing after it does
    myFunction() // undefined
    window.myFunction() // undefined
    document.myFunction() // undefined
}, 1000);
</code>```

答:
Try using:
unsafeWindow.myFunction();

More details and info - http://wiki.greasespot.net/UnsafeWindow

OwnerDisplayName: Asa Ayers

Body:
I have a very simple greasemonkey script that I want to call an already existing javascript function on the page. I've read the documentation and nothing seems to work

window.setTimeout(function() {
    alert('test') // This alert works, but nothing after it does
    myFunction() // undefined
    window.myFunction() // undefined
    document.myFunction() // undefined
}, 1000);

OwnerDisplayName: Maiku Mori


问:
How can I manipulate this object in jQuery
```<code>jQuery(function () {
    $('#square a').click(function(e) {
    // How is the e object structured
    });
})
</code>```

I have a div with an id of square and links in that. When the links are clicked they trigger a game loop function. I need to know which id the click is coming from. There are five links within the square and each one has an id. Is there a better way to track this. Or should I have a function for each link with its own id but this doesn't seem DRY to me.

答:
Something like this?</p>

```<code><div id='square'>
  <a id='link1'>Go forward!</a><br />
  <a id='link2'>Look left</a><br />
  <a id='link3'>Stop!</a><br />
  <a id='link4'>Look right</a><br />
  <a id='link5'>Go back!!!</a>
</div>

$('#square > a').live('click',function(event){
  var whichLink = $(this).attr('id');

  if ( whichLink == 'link1' ) GoForward();
  if ( whichLink == 'link2' ) LookLeft();
  if ( whichLink == 'link3' ) Stop();
  if ( whichLink == 'link4' ) CantTouchThis();
  if ( whichLink == 'link5' ) Hammertime();
});
</code>```

Body:
jQuery(function () {
    $('#square a').click(function(e) {
    // How is the e object structured
    });
})

I have a div with an id of square and links in that. When the links are clicked they trigger a game loop function. I need to know which id the click is coming from. There are five links within the square and each one has an id. Is there a better way to track this. Or should I have a function for each link with its own id but this doesn't seem DRY to me.

Body:
Something like this?

<div id='square'>
  <a id='link1'>Go forward!</a><br />
  <a id='link2'>Look left</a><br />
  <a id='link3'>Stop!</a><br />
  <a id='link4'>Look right</a><br />
  <a id='link5'>Go back!!!</a>
</div>

$('#square > a').live('click',function(event){
  var whichLink = $(this).attr('id');

  if ( whichLink == 'link1' ) GoForward();
  if ( whichLink == 'link2' ) LookLeft();
  if ( whichLink == 'link3' ) Stop();
  if ( whichLink == 'link4' ) CantTouchThis();
  if ( whichLink == 'link5' ) Hammertime();
});


问:
SQL Server Developer Edition 2014 installation failed
I have downloaded the SQL Server Developer Edition 2014 "en_sql_server_2014_developer_edition_with_service_pack_1_x64_dvd_6668542.iso"
and extracted the iso file using Power iso.

After clicking Setup file am getting below error

This SQL Server setup media does not support the language of the OS, or does not have the SQL Server English-language version installation files. Use the matching language-specific SQL Server media; or install both the language specific MUI and change the format and system locales through the regional settings in the control panel

My windows7 os regional language is set to ENGLISH(US) .

I donn't know what may be cause for these.

答:
The error is quite clear about whats wrong. Googling "SQL Server setup media does not support the language of the OS" returns results that indicate that your local variable is not the same as requested in the Setup. Maybe that iso is EN-GB.

You can check your registry for your language:

```<code>HKEY_CURRENT_USER\Control Panel\International\Locale
</code>```

You can also use powershell to check:

```<code>Get-WinUserLanguageList
</code>```

And also powershell to change it e.g.:

```<code>Set-WinUserLanguageList -LanguageList en-US
</code>```

Body:
The error is quite clear about whats wrong. Googling "SQL Server setup media does not support the language of the OS" returns results that indicate that your local variable is not the same as requested in the Setup. Maybe that iso is EN-GB.

You can check your registry for your language:

HKEY_CURRENT_USER\Control Panel\International\Locale

You can also use powershell to check:

Get-WinUserLanguageList

And also powershell to change it e.g.:

Set-WinUserLanguageList -LanguageList en-US


问:
What is the equivalent of Java's BigInteger(..).longValue() in Rust?
In Java I can do this:

new BigInteger(arrayOfBytes).longValue()
```

How can I do that same thing in Rust? That is, given an array of bytes, how can I convert it into what's in Java longValue?

答:
There is a crate for exactly that purpose (reading integers from byte slices): byteorder

Example usage:

```<code>extern crate byteorder;

use std::io::Cursor;
use byteorder::{NativeEndian, ReadBytesExt};

fn main() {
    let mut array_of_bytes = Cursor::new(b"\xDE\xAD\xBE\xEF\xCA\xFE\xBA\xBE"); // input

    println!("{}", array_of_bytes.read_i64::<NativeEndian>().unwrap());
}
</code>```

Playground

Body:
In Java I can do this:

new BigInteger(arrayOfBytes).longValue()

How can I do that same thing in Rust? That is, given an array of bytes, how can I convert it into what's in Java longValue?

Body:
There is a crate for exactly that purpose (reading integers from byte slices): byteorder

Example usage:

extern crate byteorder;

use std::io::Cursor;
use byteorder::{NativeEndian, ReadBytesExt};

fn main() {
    let mut array_of_bytes = Cursor::new(b"\xDE\xAD\xBE\xEF\xCA\xFE\xBA\xBE"); // input

    println!("{}", array_of_bytes.read_i64::<NativeEndian>().unwrap());
}

Playground


问:
How do i get my menu to produce correctly
I need be able to use a bootstrap nav menu however their is a probelm here I have attached navbar on the advance settings of a menu item in joomla however the menu does not look anything like it should do.

```<code><nav class="navbar navbar-default" role="banner">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="index.html"><img src="<?php echo $this->baseurl ?>/images/us2pk.png" alt="US2PK"></a>
            </div>
             <div class="collapse navbar-collapse navbar-right">

                <jdoc:include type="modules" name="position-7" style="none" />

            </div>
        </div><!--/.container-->
    </nav><!--/nav-->
</code>```

Here menu is wrong
http://us2pk.solitudesoftware.co.uk/how-us2pk-works

Here it is correct.
http://us2pk.solitudesoftware.co.uk/

答:
Most importantly, the markup on the correct menu has
|
 - elements between the actual menu elements. You can add something similar by adding new menu items to your menu between each item, where you choose menu item type System links->Text separator. Here you simply add a | as the title. This is rendered with
|
, and should be easy enough to style similar to the correct menu.

Body:
I need be able to use a bootstrap nav menu however their is a probelm here I have attached navbar on the advance settings of a menu item in joomla however the menu does not look anything like it should do.

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>
                <img src="<?php echo $this->baseurl ?>/images/us2pk.png" alt="US2PK">

                <jdoc:include type="modules" name="position-7" style="none" />

Here menu is wrong
http://us2pk.solitudesoftware.co.uk/how-us2pk-works

Here it is correct.
http://us2pk.solitudesoftware.co.uk/

Body: Most importantly, the markup on the correct menu has <li><a>|</a></li> - elements between the actual menu elements. You can add something similar by adding new menu items to your menu between each item, where you choose menu item type System links->Text separator. Here you simply add a | as the title. This is rendered with <li class="item-122 divider"><span class="separator ">|</span></li>, and should be easy enough to style similar to the correct menu.


问:
Change date format of cell in excel from dd.mm.yyyy to yyy/mm/dd ( excel version 2013 )
I have been searching it for an hour but unfortunately nothing found that actually work. I have an excel sheet with a column having date in it. Current date format is dd.mm.yyyy but I want to change date format to yyyy/mm/dd for entire cell.

答:
You are making this way too complicated.  Just use the DATE(year,month,day) function and switch the DAY() and YEAR() inside it.

If in cell A1 you have a European-style date in this format: 12-04-2017; Excel will interpret this as Dec 4, 2017.

Excel will interpret it properly as Apr 12, 2017 if you change it to the American-style of 04-22-2017 by writing this equation in another cell:  "=DATE(YEAR(A1),DAY(A1),MONTH(A1))".

(I put the DAY() in the month spot and the MONTH() in the day spot.)
Now you can use any date format you want.

ContentLicense: CC BY-SA 4.0


问:
Am I the only one IDEA's Auto Import doesn't work for in Kotlin?
As you can read in the title "Optimize imports on the fly" does not work for me in Kotlin, but it works in Java, i. e. IDEA removes unused imports in my Java files but not in my Kotlin files.

Since I didn't find any posts related to this on the internet I was wondering if this bug is only occurring for me.

Maybe there is a good reason for this, if so feel free to tell me.

答:
Works partly for me. That means when editing or saving a file unused imports are not cleaned. However, when I paste code, imports are automatically inserted.
I personally always use "Optimize imports".


问:
Save periodically with AJAX
I'd like to write a code that will save content of an element either after some many characters have been typed or once so often.

I will call ajax function and send content to a script to save in the background. Just not sure how to get that count going. Here's if I count to 30, but how would it look if it were continuous typing, i.e. every 30 chars?

```<code>var count = 0;

$(document).on("keyup", "#target", function(count) {
     if (count > 30) {
         $.ajax({
             ...
         });
     }
     count++;
});
</code>```

答:
Simply set the counter to 0 every time you save.</p>

```<code>var count = 0;

$(document).on("keyup", "#target", function(count) {
     if (count > 30) {
         count = 0;
         $.ajax({
            ...
         });
     }
     count++;
});
</code>```

Title: Save periodically with AJAX

Body:
I'd like to write a code that will save content of an element either after some many characters have been typed or once so often.

I will call ajax function and send content to a script to save in the background. Just not sure how to get that count going. Here's if I count to 30, but how would it look if it were continuous typing, i.e. every 30 chars?

var count = 0;

$(document).on("keyup", "#target", function(count) {
     if (count > 30) {
         $.ajax({
             ...
         });
     }
     count++;
});

Body:
Simply set the counter to 0 every time you save.

var count = 0;

$(document).on("keyup", "#target", function(count) {
     if (count > 30) {
         count = 0;
         $.ajax({
            ...
         });
     }
     count++;
});


问:
Connot find declaration to go to
SOLVED, below codes are ok, An external library was causing this problem.

I have a NavigationView with a custom theme in my style:

```<code>    <android.support.design.widget.NavigationView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:itemTextColor="@color/nav_state_list"
        app:menu="@menu/drawer_menu"
        app:headerLayout="@layout/nav_header"
        app:itemTextAppearance="@style/NavDrawerTextStyle"
android:theme="@style/navTheMe"

    </android.support.design.widget.NavigationView>
</code>```

Style (navTheMe) :

```<code><style name="navTheMe" parent="AppThemee">
    <item name="android:textSize">12sp</item>
    <item name="android:textStyle">bold</item>
    <item name="listPreferredItemPaddingRight">90dip</item>
</style>
</code>```

But it cannot find my theme and it says:

cannot find declaration to go to

And my theme will not be applied

It has been hours and I cannot figure it out what is going on

答:
You should remove the second e from the parent attribute in style.xml

```<code><style name="navTheMe" parent="AppTheme">
    <item name="android:textSize">12sp</item>
    <item name="android:textStyle">bold</item>
    <item name="listPreferredItemPaddingRight">90dip</item>
</style>
</code>```

And also, to apply this new theme to your NavigationView layout, you should use app:theme=""@style/navTheMe" attribute instead of android:theme="@style/navTheMe

```<code><android.support.design.widget.NavigationView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    ...
    app:theme="@style/navTheMe">
        ...
</android.support.design.widget.NavigationView>
</code>```

Title: Connot find declaration to go to

Body:
SOLVED, below codes are ok, An external library was causing this problem.

I have a NavigationView with a custom theme in my style:

    <android.support.design.widget.NavigationView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:itemTextColor="@color/nav_state_list"
        app:menu="@menu/drawer_menu"
        app:headerLayout="@layout/nav_header"
        app:itemTextAppearance="@style/NavDrawerTextStyle"
android:theme="@style/navTheMe"

    </android.support.design.widget.NavigationView>

Style (navTheMe) :

But it cannot find my theme and it says:

cannot find declaration to go to

And my theme will not be applied

It has been hours and I cannot figure it out what is going on

Body:
You should remove the second e from the parent attribute in style.xml

<style name="navTheMe" parent="AppTheme">
    <item name="android:textSize">12sp</item>
    <item name="android:textStyle">bold</item>
    <item name="listPreferredItemPaddingRight">90dip</item>
</style>

And also, to apply this new theme to your NavigationView layout, you should use app:theme=""@style/navTheMe" attribute instead of android:theme="@style/navTheMe

<android.support.design.widget.NavigationView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    ...
    app:theme="@style/navTheMe">
        ...
</android.support.design.widget.NavigationView>


问:
Javamail NTLM Authentication Failure
Trying to connect to Exchange server using NTLM in JavaMail.  I can connect to SMTP, but not IMAP.  I can also authenticate via the OS X Mail.app application using the identical host/username/password, account type = "IMAP", Port 143, ssl=false, authentication=NTLM, Domain Name="".

The connecting code:

```<code>import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Store;
import java.util.Properties;

    public class NTLMTest {
        public static void main(String[] args) throws Exception {
            final String host = "example.com";
            final String user = "bob";
            final String password = "password";

            final Properties properties = new Properties();
            Session session = Session.getDefaultInstance(properties);
            session.setDebug(true);

            // SMTP CONNECT
            final Transport transport = session.getTransport("smtp");
            transport.connect(host, user, password);
            System.out.println("SMTP Connect successful");

            // IMAP CONNECT
            final Store store = session.getStore("imap");
            store.connect(host, user, password);
            System.out.println("IMAP Connect Successful");

        }
    }
</code>```

The output:

```<code>DEBUG: setDebug: JavaMail version 1.4.3
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "example.com", port 25, isSSL false
220 server18.example.com ESMTP Sendmail 8.14.3/8.14.3/Debian-5+lenny1; Thu, 2 Dec 2010 18:05:30 +0100; (No UCE/UBE) logging access from: xxx.xxx.xxx.xxx
DEBUG SMTP: connected to host "example.com", port: 25

EHLO 192.168.1.107
250-server18.example.com Hello c-xxxx [xxx.xxx.xxx.xxx], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE 20971520
250-DSN
250-ETRN
250-AUTH DIGEST-MD5 CRAM-MD5 LOGIN PLAIN
250-STARTTLS
250-DELIVERBY
250 HELP
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "SIZE", arg "20971520"
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ETRN", arg ""
DEBUG SMTP: Found extension "AUTH", arg "DIGEST-MD5 CRAM-MD5 LOGIN PLAIN"
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "DELIVERBY", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
AUTH LOGIN
334 VXNlcm5hbWU6
YWR2aWVzZW5raWVzMDU=
334 UGFzc3dvcmQ6
ZGlja2hvbmluZw==
235 2.0.0 OK Authenticated
SMTP Connect successful
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]
DEBUG: mail.imap.fetchsize: 16384
DEBUG: mail.imap.statuscachetimeout: 1000
DEBUG: mail.imap.appendbuffersize: -1
DEBUG: mail.imap.minidletime: 10
DEBUG: trying to connect to host "example.com", port 143, isSSL false
* OK server18.example.com Cyrus IMAP4 v2.1.18-IPv6-Debian-2.1.18-5.1 server ready
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 ACL QUOTA LITERAL+ MAILBOX-REFERRALS NAMESPACE UIDPLUS ID NO_ATOMIC_RENAME UNSELECT CHILDREN MULTIAPPEND SORT THREAD=ORDEREDSUBJECT THREAD=REFERENCES IDLE AUTH=DIGEST-MD5 AUTH=NTLM AUTH=CRAM-MD5 ANNOTATEMORE
A0 OK Completed
IMAP DEBUG: AUTH: DIGEST-MD5
IMAP DEBUG: AUTH: NTLM
IMAP DEBUG: AUTH: CRAM-MD5
DEBUG: protocolConnect login, host=example.com, user=bob, password=<non-null>
DEBUG NTLM: type 1 message: Type1Message[suppliedDomain=,suppliedWorkstation=192.168.1.107,flags=0x00000201]
DEBUG NTLM: type 1 message length: 45
A1 AUTHENTICATE NTLM
+
TlRMTVNTUAABAAAAASIAAAAAAAAAAAAADQANACAAAAAxOTIuMTY4LjEuMTA3
+ TlRMTVNTUAACAAAAAAAAADAAAAABIgAApdhJrA6NzmwAAAAAAAAAAAAAAAAAAAAA
TlRMTVNTUAADAAAAGAAYAEAAAAAwADAAWAAAAAAAAAAAAAAAHAAcAIgAAAAaABoApAAAAAAAAAAAAAAAAQIAALV6mIutJKdZSH4IZGmvNqNFxJafzInd0yJDR4J3oe3LyBls0Y75UuwBAQAAAAAAANAS9yNDkssBVbH5v087iUIAAAAAAAAAAGEAZAB2AGkAZQBzAGUAbgBrAGkAZQBzADAANQAxADkAMgAuADEANgA4AC4AMQAuADEAMAA3AA==
A1 NO authentication failure
Exception in thread "main" javax.mail.AuthenticationFailedException: authentication failure
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:613)
    at javax.mail.Service.connect(Service.java:291)
    at javax.mail.Service.connect(Service.java:172)
    at com.prosc.emailplugin.NTLMTest.main(NTLMTest.java:25)
Disconnected from the target VM, address: '127.0.0.1:56125', transport: 'socket'

Process finished with exit code 1
</code>```

I tried wrapping the username with backslashes, per http://www.oracle.com/technetwork/java/faq-135477.html#Exchange-login I get the following error:

```<code>Exception in thread "main" javax.mail.AuthenticationFailedException: One time use of a plaintext password will enable requested mechanism for user
</code>```

Backslashes around the username in the SMTP connect portion cause it to fail.  I can't tell if the "One time use" error is a step in the right direction or not.

答:
Try setting the domain "" to the properties of the imap store :

```<code>properties.setProperty("mail.imap.auth.ntlm.domain","");
</code>```

Since in SMTP you are login using LOGIN, the use of the domain is not necessary. But in NTLM the domain is mandatory.

Title: Javamail NTLM Authentication Failure

Body:
Trying to connect to Exchange server using NTLM in JavaMail.  I can connect to SMTP, but not IMAP.  I can also authenticate via the OS X Mail.app application using the identical host/username/password, account type = "IMAP", Port 143, ssl=false, authentication=NTLM, Domain Name="".

The connecting code:

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Store;
import java.util.Properties;

    public class NTLMTest {
        public static void main(String[] args) throws Exception {
            final String host = "example.com";
            final String user = "bob";
            final String password = "password";

            final Properties properties = new Properties();
            Session session = Session.getDefaultInstance(properties);
            session.setDebug(true);

            // SMTP CONNECT
            final Transport transport = session.getTransport("smtp");
            transport.connect(host, user, password);
            System.out.println("SMTP Connect successful");

            // IMAP CONNECT
            final Store store = session.getStore("imap");
            store.connect(host, user, password);
            System.out.println("IMAP Connect Successful");

        }
    }

The output:

DEBUG: setDebug: JavaMail version 1.4.3
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "example.com", port 25, isSSL false
220 server18.example.com ESMTP Sendmail 8.14.3/8.14.3/Debian-5+lenny1; Thu, 2 Dec 2010 18:05:30 +0100; (No UCE/UBE) logging access from: xxx.xxx.xxx.xxx
DEBUG SMTP: connected to host "example.com", port: 25

EHLO 192.168.1.107
250-server18.example.com Hello c-xxxx [xxx.xxx.xxx.xxx], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE 20971520
250-DSN
250-ETRN
250-AUTH DIGEST-MD5 CRAM-MD5 LOGIN PLAIN
250-STARTTLS
250-DELIVERBY
250 HELP
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "SIZE", arg "20971520"
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ETRN", arg ""
DEBUG SMTP: Found extension "AUTH", arg "DIGEST-MD5 CRAM-MD5 LOGIN PLAIN"
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "DELIVERBY", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
AUTH LOGIN
334 VXNlcm5hbWU6
YWR2aWVzZW5raWVzMDU=
334 UGFzc3dvcmQ6
ZGlja2hvbmluZw==
235 2.0.0 OK Authenticated
SMTP Connect successful
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]
DEBUG: mail.imap.fetchsize: 16384
DEBUG: mail.imap.statuscachetimeout: 1000
DEBUG: mail.imap.appendbuffersize: -1
DEBUG: mail.imap.minidletime: 10
DEBUG: trying to connect to host "example.com", port 143, isSSL false
* OK server18.example.com Cyrus IMAP4 v2.1.18-IPv6-Debian-2.1.18-5.1 server ready
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 ACL QUOTA LITERAL+ MAILBOX-REFERRALS NAMESPACE UIDPLUS ID NO_ATOMIC_RENAME UNSELECT CHILDREN MULTIAPPEND SORT THREAD=ORDEREDSUBJECT THREAD=REFERENCES IDLE AUTH=DIGEST-MD5 AUTH=NTLM AUTH=CRAM-MD5 ANNOTATEMORE
A0 OK Completed
IMAP DEBUG: AUTH: DIGEST-MD5
IMAP DEBUG: AUTH: NTLM
IMAP DEBUG: AUTH: CRAM-MD5
DEBUG: protocolConnect login, host=example.com, user=bob, password=<non-null>
DEBUG NTLM: type 1 message: Type1Message[suppliedDomain=,suppliedWorkstation=192.168.1.107,flags=0x00000201]
DEBUG NTLM: type 1 message length: 45
A1 AUTHENTICATE NTLM
+
TlRMTVNTUAABAAAAASIAAAAAAAAAAAAADQANACAAAAAxOTIuMTY4LjEuMTA3
+ TlRMTVNTUAACAAAAAAAAADAAAAABIgAApdhJrA6NzmwAAAAAAAAAAAAAAAAAAAAA
TlRMTVNTUAADAAAAGAAYAEAAAAAwADAAWAAAAAAAAAAAAAAAHAAcAIgAAAAaABoApAAAAAAAAAAAAAAAAQIAALV6mIutJKdZSH4IZGmvNqNFxJafzInd0yJDR4J3oe3LyBls0Y75UuwBAQAAAAAAANAS9yNDkssBVbH5v087iUIAAAAAAAAAAGEAZAB2AGkAZQBzAGUAbgBrAGkAZQBzADAANQAxADkAMgAuADEANgA4AC4AMQAuADEAMAA3AA==
A1 NO authentication failure
Exception in thread "main" javax.mail.AuthenticationFailedException: authentication failure
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:613)
    at javax.mail.Service.connect(Service.java:291)
    at javax.mail.Service.connect(Service.java:172)
    at com.prosc.emailplugin.NTLMTest.main(NTLMTest.java:25)
Disconnected from the target VM, address: '127.0.0.1:56125', transport: 'socket'

Process finished with exit code 1

I tried wrapping the username with backslashes, per http://www.oracle.com/technetwork/java/faq-135477.html#Exchange-login I get the following error:

Exception in thread "main" javax.mail.AuthenticationFailedException: One time use of a plaintext password will enable requested mechanism for user

Backslashes around the username in the SMTP connect portion cause it to fail.  I can't tell if the "One time use" error is a step in the right direction or not.

Body:
Try setting the domain "" to the properties of the imap store :

properties.setProperty("mail.imap.auth.ntlm.domain","");

Since in SMTP you are login using LOGIN, the use of the domain is not necessary. But in NTLM the domain is mandatory.


问:
How to save MailMesage to .msg file?
I need save a MailMessage to .msg file. In this article have a solution but when I save as .msg file, it does not work in MS Outlook. It only great work when I save as.eml file.

How to save MailMessage object to disk as *.eml or *.msg file

Note that I get when open the .msg file:

Cannot open file: path. The file may not exist, you may not have permission to open it, or it may open in another program. Right-click the folder that contains the file, and then click Properties check your permisstions for the folder.

Thank all.

答:
In Interop Outlook, this is how to locally save a mail as .msg.</p>

```<code>mailItem.SaveAs(@"c:\path\to\save\mail.msg", Outlook.OlSaveAsType.olMSG);
</code>```

Title: How to save MailMesage to .msg file?

Body:
In Interop Outlook, this is how to locally save a mail as .msg.

mailItem.SaveAs(@"c:\path\to\save\mail.msg", Outlook.OlSaveAsType.olMSG);


问:
Array only being updated on first iteration of a for loop
The following code takes an array of objects structured like so: {html:whatever number:number value}.

```<code>function Org(data){
//array of objects
var Data=data;
for(var i=0; i<Data.length; i++){
  var nums=[];
  nums.push(Data[i].number);
console.log(nums);}
}
</code>```

Nums should have be logged to the console as [1,1] on the second iteration when called with: [{html:null,number:1},{html:null,number:1}] but instead is logged as [1] on both the first and second iterations. Why might this be?

答:
You need to move the initialization of num outside of the for loop. Inside it creates for each iteration a new empty array.

BTW, no need for using another variable for data.

```<code>function Org(data){
    var nums = [];
    for (var i = 0; i < data.length; i++){
        nums.push(data[i].number);
    }
    console.log(nums);
}
</code>```

Body:
The following code takes an array of objects structured like so: {html:whatever number:number value}.

function Org(data){
//array of objects
var Data=data;
for(var i=0; i<Data.length; i++){
  var nums=[];
  nums.push(Data[i].number);
console.log(nums);}
}

Nums should have be logged to the console as [1,1] on the second iteration when called with: [{html:null,number:1},{html:null,number:1}] but instead is logged as [1] on both the first and second iterations. Why might this be?

Body:
You need to move the initialization of num outside of the for loop. Inside it creates for each iteration a new empty array.

BTW, no need for using another variable for data.

function Org(data){
    var nums = [];
    for (var i = 0; i < data.length; i++){
        nums.push(data[i].number);
    }
    console.log(nums);
}


问:
Polymer- using custom element in other projects like angular and Java jsp
I am trying to create custom form element which I am trying to reuse in other applications developed in angular and jsp page of Java

my-element.js:

```<code>    class MyElement extends HTMLElement {
      // This gets called when the HTML parser sees your tag
      constructor() {
        super(); // always call super() first in the ctor.
        this.msg = 'Hello, World!';
      }
      // Called when your element is inserted in the DOM or
      // immediately after the constructor if it’s already in the DOM
      connectedCallback() {
        this.innerHTML = `<form action="/action_page.php">
      <div class="container">
        <label><b>Name</b></label>
        <input type="text" placeholder="Enter Email" name="email" required>

       <label><b>Age</b></label>
        <input type="text" placeholder="Enter Age" name="age" required>

        <div class="clearfix">
          <button type="button"  class="cancelbtn">Cancel</button>
          <button type="submit" class="signupbtn">Add</button>
        </div>
      </div>
    </form>`;
      }
    }
    // This registers your new tag and associates it with your class
    window.customElements.define('my-element', MyElement);
</code>```

my-element.html:

```<code>    <!doctype html>
<html>
<head>
    <meta charset="utf-8">

    <script src="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/webcomponentsjs/webcomponents-lite.js"></script>
    <link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/polymer/polymer.html">
    <link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/iron-ajax/iron-ajax.html">
    <script src="my-element.js"></script>
    <!-- <link rel="import" href="add-form.html"> -->

</head>
<body>
<my-element></my-element>

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

Two issues I am struggling with now are below

1.Can i incude both the files as below to my angular and java jsp page and use custom tag to work?

```<code><link rel="import" href="my-element.html">
<script src="my-element.js"></script>

 <my-element></my-element>
</code>```

I am trying to pass below json object as an attribute to custom form element and trying to render custom form elements

[
      {
        "name":"Name",
        "type":"text",
        "size":"20",
        "readyOnly": false,
        "validateFunction":"onlyText"
      },
      {
        "name":"Age",
        "type":"number",
        "size":"3",
        "readyOnly": false,
        "validateFunction":"onlyNumber"
      }
    ]

I tried using below way to inject json data to custom element to render form elements based on json but no luck and there are no console errors

```<code><my-element form-data="{{data}}"></my-element>
</code>```

答:
ad 1) yes you can use your element with every server system you would like. It's "just html" that the beauty in it :)

ad 2)
HTMLElement won't do anything automatically. So if you wish to access your json you will have to do something like this

```<code><my-element form-data="{'name': 'Name', 'type': 'text'}""></my-element>

connectedCallback() {
  let rawData = this.getAttribute('form-data');
  let jsonData = JSON.parse(rawData.replace(/'/g, '"'));
}
</code>```

Notice that in the form-data json there are ' instead of ". So we have to replace them before using JSON.parse.

Body:
I am trying to create custom form element which I am trying to reuse in other applications developed in angular and jsp page of Java

my-element.js:

    class MyElement extends HTMLElement {
      // This gets called when the HTML parser sees your tag
      constructor() {
        super(); // always call super() first in the ctor.
        this.msg = 'Hello, World!';
      }
      // Called when your element is inserted in the DOM or
      // immediately after the constructor if it’s already in the DOM
      connectedCallback() {
        this.innerHTML = `<form action="/action_page.php">

        Name
        <input type="text" placeholder="Enter Email" name="email" required>

       Age
        <input type="text" placeholder="Enter Age" name="age" required>

          <button type="button"  class="cancelbtn">Cancel</button>
          <button type="submit" class="signupbtn">Add</button>

    </form>`;
      }
    }
    // This registers your new tag and associates it with your class
    window.customElements.define('my-element', MyElement);

my-element.html:

    <!doctype html>

    <meta charset="utf-8">

    <link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/polymer/polymer.html">
    <link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/iron-ajax/iron-ajax.html">

<my-element></my-element>

Two issues I am struggling with now are below

1.Can i incude both the files as below to my angular and java jsp page and use custom tag to work?

<link rel="import" href="my-element.html">

 <my-element></my-element>

I am trying to pass below json object as an attribute to custom form element and trying to render custom form elements

[
      {
        "name":"Name",
        "type":"text",
        "size":"20",
        "readyOnly": false,
        "validateFunction":"onlyText"
      },
      {
        "name":"Age",
        "type":"number",
        "size":"3",
        "readyOnly": false,
        "validateFunction":"onlyNumber"
      }
    ]

I tried using below way to inject json data to custom element to render form elements based on json but no luck and there are no console errors

<my-element form-data="{{data}}"></my-element>

Body:
ad 1) yes you can use your element with every server system you would like. It's "just html" that the beauty in it :)

ad 2)
HTMLElement won't do anything automatically. So if you wish to access your json you will have to do something like this

<my-element form-data="{'name': 'Name', 'type': 'text'}""></my-element>

connectedCallback() {
  let rawData = this.getAttribute('form-data');
  let jsonData = JSON.parse(rawData.replace(/'/g, '"'));
}

Notice that in the form-data json there are ' instead of ". So we have to replace them before using JSON.parse.


问:
Opening GUI file from another GUI file PyQT5
I am trying to make my GUI that runs on startup to open a different GUI when the user clicks a button. So on my startup file, I have:

```<code>class Startup(object):
    def setup_ui(self, Dialog):
        Dialog.setObjectName("Dialog")
...
        self.start_button = QtWidgets.QPushButton('', Dialog)
        self.start_button.clicked.connect(self.start_program)
...
    def start_program(self):
    # segmentation = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    # sys.exit(segmentation.exec_())
...
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Startup()
ui.setup_ui(Dialog)
Dialog.show()
sys.exit(app.exec_( ))
</code>```

My main file for the GUI that I am trying to start up looks like this:

```<code>class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        font = QtGui.QFont("Times", 30, QtGui.QFont.Bold)
        MainWindow.setObjectName("NBA Predictor")
        MainWindow.resize(1150, 790)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
...
</code>```

However, when the user clicks the "start" button on the startup file, the main screen opens for like .1 seconds then closes immediately. I think it is a problem with not having a correct exit command. However, if I uncomment the lines in the start_program function:

```<code># segmentation = QtWidgets.QApplication(sys.argv)
</code>```

and

```<code># sys.exit(segmentation.exec_())
</code>```

when I click on the start button, the window opens for a second then both windows close. Any ideas?

答:
That happens because of Python GC. Save reference for MainWindow, like:</p>

```<code>self.mainWindow = QtWidgets.QMainWindow()
self.mainWindow.show()
</code>```

Body:
I am trying to make my GUI that runs on startup to open a different GUI when the user clicks a button. So on my startup file, I have:

class Startup(object):
    def setup_ui(self, Dialog):
        Dialog.setObjectName("Dialog")
...
        self.start_button = QtWidgets.QPushButton('', Dialog)
        self.start_button.clicked.connect(self.start_program)
...
    def start_program(self):
    # segmentation = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    # sys.exit(segmentation.exec_())
...
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Startup()
ui.setup_ui(Dialog)
Dialog.show()
sys.exit(app.exec_( ))

My main file for the GUI that I am trying to start up looks like this:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        font = QtGui.QFont("Times", 30, QtGui.QFont.Bold)
        MainWindow.setObjectName("NBA Predictor")
        MainWindow.resize(1150, 790)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
...

However, when the user clicks the "start" button on the startup file, the main screen opens for like .1 seconds then closes immediately. I think it is a problem with not having a correct exit command. However, if I uncomment the lines in the start_program function:

# segmentation = QtWidgets.QApplication(sys.argv)

and

# sys.exit(segmentation.exec_())

when I click on the start button, the window opens for a second then both windows close. Any ideas?

Body:
That happens because of Python GC. Save reference for MainWindow, like:

self.mainWindow = QtWidgets.QMainWindow()
self.mainWindow.show()


问:
Combined unparser/parser generator
Is there a parser generator that also implements the inverse direction, i.e. unparsing domain objects (a.k.a. pretty-printing) from the same grammar specification? As far as I know, ANTLR does not support this.</p>

答:
There are several parser generators that include an implementation of an unparser. One of them is the nearley parser generator for context-free grammars.

It is also possible to implement bidirectional transformations of source code using definite clause grammars. In SWI-Prolog, the phrase/2 predicate can convert an input text into a parse tree and vice-versa.

Title: Combined unparser/parser generator


问:
read data file with mixed numbers and texts in r
I have data files that contain the following:
the first 10 columns are numbers, the last column is text. They are separated by space. The problem is that the text in the last column may also contain space. So when I used read.table() I got the following error:

```<code>Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
line 21 did not have 11 elements
</code>```

what's the easiest way of reading the first 10 columns into a data matrix, and the last column into a string vector? Should I use readLines() first then process it?

答:
Hinted by the useful fill = TRUE option of read.table() function, I used the following to solve my problem:

```<code>dat <- read.table(fname, fill = T)
dat <- dat[subset(1:nrow(dat),!((1:nrow(dat)) %in% (which(dat[,11]=="No") + 1))),]
</code>```

The fill = TRUE option puts everything after the first space of the 11th column to a new row (redundant rows that the original data do not have). The code above removes the redundant rows based on three assumptions: (1) the number of space separators in the 11th column is no more than 11 such that we know there is only one more row of text after a line whose 11th column contains space (that's what the +1 does); (2) we know the line whose 11th column starts with a certain word (in my case it is "No") (3) Keeping only the first word in the 11th column would be sufficient (without ambiguity).

Body:
I have data files that contain the following:
the first 10 columns are numbers, the last column is text. They are separated by space. The problem is that the text in the last column may also contain space. So when I used read.table() I got the following error:

Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
line 21 did not have 11 elements

what's the easiest way of reading the first 10 columns into a data matrix, and the last column into a string vector? Should I use readLines() first then process it?

Body:
Hinted by the useful fill = TRUE option of read.table() function, I used the following to solve my problem:

dat <- read.table(fname, fill = T)
dat <- dat[subset(1:nrow(dat),!((1:nrow(dat)) %in% (which(dat[,11]=="No") + 1))),]

The fill = TRUE option puts everything after the first space of the 11th column to a new row (redundant rows that the original data do not have). The code above removes the redundant rows based on three assumptions: (1) the number of space separators in the 11th column is no more than 11 such that we know there is only one more row of text after a line whose 11th column contains space (that's what the +1 does); (2) we know the line whose 11th column starts with a certain word (in my case it is "No") (3) Keeping only the first word in the 11th column would be sufficient (without ambiguity).


问:
PHP script to make a dynamic image
I have a CMS that my freind built and I need to adjust one thing but I don't know how so please help me ...

this is my question :

I have an image in my home page , and I want the user to be able to click on this image and navigate to some website

now this website's link will be provided by the user in the CMS

I have added a textbox so that the user can write the link , and saved the link in mySQL database , but I don't know how to connect my image to this link I have ?!

Please help me

答:
Sorry but this sounds bad idea.
There is nothing safe to let users be able to add a link.

But, to answer your question.
So, you have something like this in your user table?

```<code>id | username | password | avatarImage
</code>```

then you can create a query to mySQL:

```<code>SELECT avatarImage FROM users WHERE link id = '89' LIMIT 0, 1
</code>```

and then add a photo

```<code><img src=" image link here " />
</code>```

But I would have taken a look at: http://www.webcheatsheet.com/php/create_thumbnail_images.php

It may be that I misunderstood you here. If so, I apologize:)

Title: PHP script to make a dynamic image

Body:
Sorry but this sounds bad idea.
There is nothing safe to let users be able to add a link.

But, to answer your question.
So, you have something like this in your user table?

id | username | password | avatarImage

then you can create a query to mySQL:

SELECT avatarImage FROM users WHERE link id = '89' LIMIT 0, 1

and then add a photo

<img src=" image link here " />

But I would have taken a look at: http://www.webcheatsheet.com/php/create_thumbnail_images.php

It may be that I misunderstood you here. If so, I apologize:)


问:
How do I link these two basic programs together?
Its my first time coding on python, I want to link these two files together but don't know how to. I want the program to redirect the user to the second program if they have a private number plate but How do i make this link?

I just need a simple code nothing to advanced as I will get confused. I need to learn how to use these codes before I move on to the more advanced codes for linking files together.

```<code># program1.py
privateNumberPlate = open("privateNumberPlate.txt", 'a')
ordinaryNum = open("ordinaryNum.txt", 'a')

print ("Welcome")
plateSelections = ("What is your number plate?", "If you own a private number plate please press 1 to be redirected")
</code>```

```<code># program2.py
print ("You have been redirected", "Please enter your private number plate.")
</code>```

答:
You'll need functions for that. Let's say your first programs name is Program1.py and second Program2.py. In Program2.py you should have a function like this:

```<code>def Function_Name():
    print("You have been redirected....")
</code>```

Program1.py and Program2.py should be in the same folder. Then you add this to Program1.py:

```<code>from Program2 import Function_Name
</code>```

and then you call that function like this:

```<code>Function_Name()
</code>```

and it should print out what you wanted. Hope this helped.

Body:
Its my first time coding on python, I want to link these two files together but don't know how to. I want the program to redirect the user to the second program if they have a private number plate but How do i make this link?

I just need a simple code nothing to advanced as I will get confused. I need to learn how to use these codes before I move on to the more advanced codes for linking files together.

# program1.py
privateNumberPlate = open("privateNumberPlate.txt", 'a')
ordinaryNum = open("ordinaryNum.txt", 'a')

print ("Welcome")
plateSelections = ("What is your number plate?", "If you own a private number plate please press 1 to be redirected")

# program2.py
print ("You have been redirected", "Please enter your private number plate.")

Body:
You'll need functions for that. Let's say your first programs name is Program1.py and second Program2.py. In Program2.py you should have a function like this:

def Function_Name():
    print("You have been redirected....")

Program1.py and Program2.py should be in the same folder. Then you add this to Program1.py:

from Program2 import Function_Name

and then you call that function like this:

Function_Name()

and it should print out what you wanted. Hope this helped.


问:
How do I test if a table exists in Interbase?
I have just recently started using Interbase, and I need to verify if the database has a table, how do I check in Interbase if a table exists in the database?</p>

答:
For IBX there are at least these ways disponible:

1. Using SQL query

You can query the RDB$RELATIONS system table in which you filter by the RDB$RELATION_NAME column. For example this query returns 1 when table called MyTable exists in the database:

SELECT 1 FROM RDB$RELATIONS
  WHERE RDB$RELATION_NAME = 'MyTable'
```

<p>With IBX on client side you can write for instance this:</p>

```function TableExists(Database: TIBDatabase; const TableName: string): Boolean;
var
  Query: TIBSQL;
begin
  Query := TIBSQL.Create(Database);
  try
    Query.SQL.Text := 'SELECT 1 FROM RDB$RELATIONS WHERE RDB$RELATION_NAME = ?';
    Query.Params[0].AsString := TableName;
    Query.ExecQuery;
    { RecordCount reports only visited records, so it should be either 0 or 1 now }
    Result := Query.RecordCount > 0;
  finally
    Query.Free;
  end;
end;
```

<p>This version is case sensitive and is efficient when you need to determine if table exists from code only ocassionally (for checking frequently I would cache the list of all table names returned by the <strong>GetTableNames</strong> method and query just such list).</p>

<h1>2. Using TIBDatabase.GetTableNames method</h1>

<p>The <strong>TIBDatabase</strong> class is able to list all the table names by the <strong>GetTableNames</strong> method. In the returned string list collection you can then verify if the name exists by the <strong>IndexOf</strong> method. For example: </p>

```function TableExists(Database: TIBDatabase; const TableName: string): Boolean;
var
  Tables: TStrings;
begin
  Tables := TStringList.Create;
  try
    Database.GetTableNames(Tables, True);
    Result := Tables.IndexOf(TableName) <> -1;
  finally
    Tables.Free;
  end;
end;
```

This version is case insensitive (so long you won't change the default value of the CaseSensitive property of the returned collection) and is naturally not as efficient as the first way for single or ocassional use because this one fetches the whole table name collection from server to client. But the GetTableNames method itself can be useful for frequent use if you cache the returned collection.

3. Using TIBExtract class

The TIBExtract IBX class is intended for fetching metadata. Unfortunately it't not so efficient and easy to use for just checking whether certain table exists in database because it can fetch either list of all tables, or details of the table itself. So I leave this option without example.

Body:
For IBX there are at least these ways disponible:

1. Using SQL query

You can query the RDB$RELATIONS system table in which you filter by the RDB$RELATION_NAME column. For example this query returns 1 when table called MyTable exists in the database:

SELECT 1 FROM RDB$RELATIONS
  WHERE RDB$RELATION_NAME = 'MyTable'

With IBX on client side you can write for instance this:

function TableExists(Database: TIBDatabase; const TableName: string): Boolean;
var
  Query: TIBSQL;
begin
  Query := TIBSQL.Create(Database);
  try
    Query.SQL.Text := 'SELECT 1 FROM RDB$RELATIONS WHERE RDB$RELATION_NAME = ?';
    Query.Params[0].AsString := TableName;
    Query.ExecQuery;
    { RecordCount reports only visited records, so it should be either 0 or 1 now }
    Result := Query.RecordCount > 0;
  finally
    Query.Free;
  end;
end;

This version is case sensitive and is efficient when you need to determine if table exists from code only ocassionally (for checking frequently I would cache the list of all table names returned by the GetTableNames method and query just such list).

2. Using TIBDatabase.GetTableNames method

The TIBDatabase class is able to list all the table names by the GetTableNames method. In the returned string list collection you can then verify if the name exists by the IndexOf method. For example:

function TableExists(Database: TIBDatabase; const TableName: string): Boolean;
var
  Tables: TStrings;
begin
  Tables := TStringList.Create;
  try
    Database.GetTableNames(Tables, True);
    Result := Tables.IndexOf(TableName) <> -1;
  finally
    Tables.Free;
  end;
end;

This version is case insensitive (so long you won't change the default value of the CaseSensitive property of the returned collection) and is naturally not as efficient as the first way for single or ocassional use because this one fetches the whole table name collection from server to client. But the GetTableNames method itself can be useful for frequent use if you cache the returned collection.

3. Using TIBExtract class

The TIBExtract IBX class is intended for fetching metadata. Unfortunately it't not so efficient and easy to use for just checking whether certain table exists in database because it can fetch either list of all tables, or details of the table itself. So I leave this option without example.


问:
Is DateFormatter class broken in swift 3?
I am trying to use Date class which is provided from Swift 3 library. I am not sure if I am doing it right.
When I print Date it prints correct date, but when I try to convert it from date to string it changes the date to something else.

```<code>let today = Date()
print(" Date object : \(today)")

let format = DateFormatter()
format.dateFormat = "mm/dd/yy"

print(" Date to String : \(format.string(from: today)")
</code>```

Which gives the output:

Date object : 2017-06-03 18:13:39 +0000

Date to String : 13/03/17

答:
mm is the format specifier for minutes, hence why the output returns 13 instead of 06, which is the time in minutes at which you called Date().

You'll need to use MM to display the month.

See the unicode report on date specifiers for more information: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns

Body:
I am trying to use Date class which is provided from Swift 3 library. I am not sure if I am doing it right.
When I print Date it prints correct date, but when I try to convert it from date to string it changes the date to something else.

let today = Date()
print(" Date object : \(today)")

let format = DateFormatter()
format.dateFormat = "mm/dd/yy"

print(" Date to String : \(format.string(from: today)")

Which gives the output:

Date object : 2017-06-03 18:13:39 +0000

Date to String : 13/03/17


答:
No it doesnt.
Your format is Minute, Day and Year.
Works exactly as it should.

Try MM istead of mm.

Title: Is DateFormatter class broken in swift 3?


问:
Login, get info of a table, click buttons, etc in a web page from c# app (GET - POST HTTP)
I want to get some information of a web page (Where I have customers, current balance, etc) in my C# application. I thought in use POST - GET methods, but I don't know how to use them. The first problem, I have to login in the page:
Login page
I guess I have to get boxes id, and button id, then, complete them in the C# app. Next I want to get table contents. The table is like this: Table
How I can get customer id, customer name, and customer balance? And if the customer balance is updated, check it on the app? I think with this is to be able to do the rest on my own.</p>

答:
This could be very difficult depending on exactly how the site is architected.  Does the site have an API you might be able to use instead of trying to go through the UI?

If you have no choice, I would consider using something like PhantomJS which is basically a scriptable headless browser.  To make it a little easier to use with C#, you might also consider Selenium WebDriver and their PhantomJSDriver.

Selenium is used for automated testing of websites, but you can just as easily use it to automate repetitive UI interaction in websites.  The biggest issue you generally face is keeping your scripting from being so brittle that anytime a change is made to the site, it breaks your automation.  You might want to read up on the Page Object Pattern as it can help you minimize redundancy and keep your code maintainable.

Also, it was recently announced that Chrome v59 will be able to be ran headless, so that might ultimately be an alternative to PhantomJS.


问:
git - local repository - how to manage different customer config files with same names
I want to use git to manage a set of code files and a set of customer specific configuration files.

On the server are several directories, two per customer: one test, one production.

I want to be able to use git to track changes, etc. to the code files, and to the customer specific configuration files, but I don't want to be merging the config files back to the master branch.

In other words, I want to be able to maintain history of the configuration files (in each test and production directory), and be able to checkout specific versions of the code in to either a customer's test or production directory.

I thought I could just create a branch for each customer and maintain their config files on those branches, but whenever I check out the master branch, the config files, since they aren't part of the config branch, they get deleted.

Do I need to use two different repositories to handle this?

How do I switch which repository to use when I want to make changes to either the code or config files?

I don't want to create custom config files and rename them to the real config filenames, because everytime I checkout the master, I will get every customer's config file in a particular customer's directory.

There must be an easy way to do this?

答:
Under the following assumptions I would propose to you this solution:

Assumptions

You want to track the code with git

You want to track the config files (per customer) with git

Possible solution

I think you could get away with the following setup:

Having a master branch that contains only the code and no configuration

Having two branches per customer e.g. customerA-prod and customerA-test

If possible commit bugfixes that apply to all customers to the master branch and merge it back into the customer branches.

For customer specific alterations use only the customer branches.

In general try to avoid merging customer branches into master.

If it is really necessary make sure that you do not merge any configuration files onto master (delete them, so that master stays clear of config files).

With this proposed setup I think it should be possible to share the code (where needed), track the history of the config files (per customer/environment).

Unclear specification

but whenever I check out the master branch, the config files, since they aren't part of the config branch, they get deleted

I don't understand the problem here.

Maybe you need some customers config files on master in order to develop?
If so you could check out the config files (while still avoiding to commit them by doing something like this)

```<code>$ git checkout customerA-prod -- <path-to-config-file>
$ git reset HEAD -- <path-to-config-file>
$ # work, commit (but avoid adding the config file)
</code>```

The git checkout <branch> -- <file> syntax is useful to get files as they are on other branches onto your current branch.

Does this help?

Body:
Under the following assumptions I would propose to you this solution:

Assumptions

You want to track the code with git

You want to track the config files (per customer) with git

Possible solution

I think you could get away with the following setup:

Having a master branch that contains only the code and no configuration

Having two branches per customer e.g. customerA-prod and customerA-test

If possible commit bugfixes that apply to all customers to the master branch and merge it back into the customer branches.

For customer specific alterations use only the customer branches.

In general try to avoid merging customer branches into master.

If it is really necessary make sure that you do not merge any configuration files onto master (delete them, so that master stays clear of config files).

With this proposed setup I think it should be possible to share the code (where needed), track the history of the config files (per customer/environment).

Unclear specification

but whenever I check out the master branch, the config files, since they aren't part of the config branch, they get deleted

I don't understand the problem here.

Maybe you need some customers config files on master in order to develop?
If so you could check out the config files (while still avoiding to commit them by doing something like this)

$ git checkout customerA-prod -- <path-to-config-file>
$ git reset HEAD -- <path-to-config-file>
$ # work, commit (but avoid adding the config file)

The git checkout <branch> -- <file> syntax is useful to get files as they are on other branches onto your current branch.

Does this help?


答:
Classic case for modulo :)</p>

```<code>var count = 0;

$(document).on("keyup", "#target", function(count) {
     if (count % 30 === 29) {
         $.ajax({
             ...
         });
     }
     count++;
});
</code>```

Title: Save periodically with AJAX

Body:
I'd like to write a code that will save content of an element either after some many characters have been typed or once so often.

I will call ajax function and send content to a script to save in the background. Just not sure how to get that count going. Here's if I count to 30, but how would it look if it were continuous typing, i.e. every 30 chars?

var count = 0;

$(document).on("keyup", "#target", function(count) {
     if (count > 30) {
         $.ajax({
             ...
         });
     }
     count++;
});

Body:
Classic case for modulo :)

var count = 0;

$(document).on("keyup", "#target", function(count) {
     if (count % 30 === 29) {
         $.ajax({
             ...
         });
     }
     count++;
});


问:
Spring Boot LocalDate field serialization and deserialization
In Spring Boot 1.2.3.RELEASE with fasterxml what is the correct way of serializing and de-serializing a LocalDate field to ISO date formatted string?

I've tried:

spring.jackson.serialization.write-dates-as-timestamps:false in application.properties file,

including jackson-datatype-jsr310 in project and then using

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") annotation

and @DateTimeFormat(iso=ISO.DATE) annotation,

adding Jsr310DateTimeFormatAnnotationFormatterFactory as formatter with:

```<code>@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addFormatterForFieldAnnotation(new Jsr310DateTimeFormatAnnotationFormatterFactory());
}
</code>```

None of the above helped.

答:
If you want to use a custom Java Date formatter, add the  @JsonFormat annotation.

```<code>@JsonFormat(pattern = "dd/MM/yyyy")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate birthdate;*
</code>```

Body:
In Spring Boot 1.2.3.RELEASE with fasterxml what is the correct way of serializing and de-serializing a LocalDate field to ISO date formatted string?

I've tried:

spring.jackson.serialization.write-dates-as-timestamps:false in application.properties file,

including jackson-datatype-jsr310 in project and then using

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") annotation

and @DateTimeFormat(iso=ISO.DATE) annotation,

adding Jsr310DateTimeFormatAnnotationFormatterFactory as formatter with:

@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addFormatterForFieldAnnotation(new Jsr310DateTimeFormatAnnotationFormatterFactory());
}

None of the above helped.

Body:
If you want to use a custom Java Date formatter, add the  @JsonFormat annotation.

@JsonFormat(pattern = "dd/MM/yyyy")
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate birthdate;*


问:
Is it possible to use SFINAE/templates to check if an operator exists?
I'm trying to check if an operator exists at compile time, if it doesn't I just want it ignored, is there any way to do that?

example operator:

```<code> template <typename T>
 QDataStream& operator<<(QDataStream& s, const QList<T>& l);
</code>```

答:
I ended up using a fallback namespace :

```<code>namespace operators_fallback {
template <typename T>
inline QDataStream& operator<<(QDataStream& s, const T &) { return s; }

template <typename T>
inline QDataStream& operator>>(QDataStream& s, T &) { return s; }

template <typename T>
inline QDebug operator<<(QDebug d, const T &) { return d; }
};

...
inline void load(QDataStream & s) {
    using namespace operator_fallback;
    s >> item;
}
</code>```

Also found the proper way to check for operators at compile time (although I'm going with the fallback namespace).

more or less based on this :

```<code>namespace private_impl {
    typedef char yes;
typedef char (&no)[2];

struct anyx { template <class T> anyx(const T &); };

no operator << (const anyx &, const anyx &);
no operator >> (const anyx &, const anyx &);

template <class T> yes check(T const&);
no check(no);

template <typename StreamType, typename T>
struct has_loading_support {
    static StreamType & stream;
    static T & x;
    static const bool value = sizeof(check(stream >> x)) == sizeof(yes);
};

template <typename StreamType, typename T>
struct has_saving_support {
    static StreamType & stream;
    static T & x;
    static const bool value = sizeof(check(stream << x)) == sizeof(yes);
};

template <typename StreamType, typename T>
struct has_stream_operators {
    static const bool can_load = has_loading_support<StreamType, T>::value;
    static const bool can_save = has_saving_support<StreamType, T>::value;
    static const bool value = can_load && can_save;
};
}
template<typename T>
struct supports_qdatastream : private_impl::has_stream_operators<QDataStream, T> {};

template<typename T>
struct can_load : private_impl::has_loading_support<QDataStream, T> {};

template<typename T>
struct can_save : private_impl::has_saving_support<QDataStream, T> {};

template<typename T>
struct can_debug : private_impl::has_saving_support<QDebug, T> {};
</code>```

//edit changed has_stream_operators a bit.

//edit removed the link, apparently the site has some attack javascript.

Body:
I'm trying to check if an operator exists at compile time, if it doesn't I just want it ignored, is there any way to do that?

example operator:

 template <typename T>
 QDataStream& operator<<(QDataStream& s, const QList<T>& l);

Body:
I ended up using a fallback namespace :

namespace operators_fallback {
template <typename T>
inline QDataStream& operator<<(QDataStream& s, const T &) { return s; }

template <typename T>
inline QDataStream& operator>>(QDataStream& s, T &) { return s; }

template <typename T>
inline QDebug operator<<(QDebug d, const T &) { return d; }
};

...
inline void load(QDataStream & s) {
    using namespace operator_fallback;
    s >> item;
}

Also found the proper way to check for operators at compile time (although I'm going with the fallback namespace).

more or less based on this :

namespace private_impl {
    typedef char yes;
typedef char (&no)[2];

struct anyx { template <class T> anyx(const T &); };

no operator << (const anyx &, const anyx &);
no operator >> (const anyx &, const anyx &);

template <class T> yes check(T const&);
no check(no);

template <typename StreamType, typename T>
struct has_loading_support {
    static StreamType & stream;
    static T & x;
    static const bool value = sizeof(check(stream >> x)) == sizeof(yes);
};

template <typename StreamType, typename T>
struct has_saving_support {
    static StreamType & stream;
    static T & x;
    static const bool value = sizeof(check(stream << x)) == sizeof(yes);
};

template <typename StreamType, typename T>
struct has_stream_operators {
    static const bool can_load = has_loading_support<StreamType, T>::value;
    static const bool can_save = has_saving_support<StreamType, T>::value;
    static const bool value = can_load && can_save;
};
}
template<typename T>
struct supports_qdatastream : private_impl::has_stream_operators<QDataStream, T> {};

template<typename T>
struct can_load : private_impl::has_loading_support<QDataStream, T> {};

template<typename T>
struct can_save : private_impl::has_saving_support<QDataStream, T> {};

template<typename T>
struct can_debug : private_impl::has_saving_support<QDebug, T> {};

//edit changed has_stream_operators a bit.

//edit removed the link, apparently the site has some attack javascript.