问:
How to add columnname to value in bigquery
I have a bigquery table that contains 3 "code" fields.  some of these fields are used to look up against a code table.  Assume the table looks like this:

```<code>data table:
    id    code1    code2     code3     data1
    1       Y        3         A        IA
    2       Y        2         B        IB
    3       N        5         C        IC
</code>```

in order to perform the lookup, I have to concat the field_name to the value, delimited by a colon.  I cannot hardcode the column name.  using big query, is there a way to use the table object to infer the column name within the select statement?

for example:

```<code>select * from code_table join data_table where code1 = code.code_values
the value of code1 coming out is 'code1:Y'  not 'Y'.
</code>```

I'm wondering if there's a way to inject the column_name dynamically in the code1 value as it's going out to the code_table.

UPDATE 1:

Here's an example output from data_table to join against code_table:

```<code>1, code1:Y, code2:3, code3:A, IA
2, code1:Y, code2:2, code3:B, IB
3, code1:N, code2:5, code3:C, IC
</code>```

Thanks

答:
Does using the TO_JSON_STRING function give the desired output? Here is an example using your data:

```<code>WITH `project.dataset.table` AS (
  SELECT 1 AS id, 'Y' AS code1, 3 AS code2, 'A' AS code3, 'IA' AS data1 UNION ALL
  SELECT 2, 'Y', 2, 'B', 'IB' UNION ALL
  SELECT 3, 'N', 5, 'C', 'IC'
)
SELECT TO_JSON_STRING(t) AS json
FROM `project.dataset.table` AS t;
+---------------------------------------------------------+
| json                                                    |
+---------------------------------------------------------+
| {"id":1,"code1":"Y","code2":3,"code3":"A","data1":"IA"} |
| {"id":2,"code1":"Y","code2":2,"code3":"B","data1":"IB"} |
| {"id":3,"code1":"N","code2":5,"code3":"C","data1":"IC"} |
+---------------------------------------------------------+
</code>```

If you want to strip out the quotes, you can do that too:

```<code>WITH `project.dataset.table` AS (
  SELECT 1 AS id, 'Y' AS code1, 3 AS code2, 'A' AS code3, 'IA' AS data1 UNION ALL
  SELECT 2, 'Y', 2, 'B', 'IB' UNION ALL
  SELECT 3, 'N', 5, 'C', 'IC'
)
SELECT REPLACE(TO_JSON_STRING(t), '"', '') AS json
FROM `project.dataset.table` AS t;
+-----------------------------------------+
| json                                    |
+-----------------------------------------+
| {id:1,code1:Y,code2:3,code3:A,data1:IA} |
| {id:2,code1:Y,code2:2,code3:B,data1:IB} |
| {id:3,code1:N,code2:5,code3:C,data1:IC} |
+-----------------------------------------+
</code>```

Edit: this gives the exact desired output. I'm assuming that you are okay with referencing id and data by name since it sounds like you don't want to format them in the same way.

```<code>WITH `project.dataset.table` AS (
  SELECT 1 AS id, 'Y' AS code1, 3 AS code2, 'A' AS code3, 'IA' AS data1 UNION ALL
  SELECT 2, 'Y', 2, 'B', 'IB' UNION ALL
  SELECT 3, 'N', 5, 'C', 'IC'
)
SELECT
  REGEXP_REPLACE(
    FORMAT(
      '%d %s %s',
      id,
      REGEXP_REPLACE(
        TO_JSON_STRING(
          (SELECT AS STRUCT t.* EXCEPT (id, data1))
        ),
        '["{}]', ''),
      data1
    ),
    r'[ ,]', ', '
  ) AS output
FROM `project.dataset.table` AS t;
+----------------------------------+
| output                           |
+----------------------------------+
| 1, code1:Y, code2:3, code3:A, IA |
| 2, code1:Y, code2:2, code3:B, IB |
| 3, code1:N, code2:5, code3:C, IC |
+----------------------------------+
</code>```

Body:
I have a bigquery table that contains 3 "code" fields.  some of these fields are used to look up against a code table.  Assume the table looks like this:

data table:
    id    code1    code2     code3     data1
    1       Y        3         A        IA
    2       Y        2         B        IB
    3       N        5         C        IC

in order to perform the lookup, I have to concat the field_name to the value, delimited by a colon.  I cannot hardcode the column name.  using big query, is there a way to use the table object to infer the column name within the select statement?

for example:

select * from code_table join data_table where code1 = code.code_values
the value of code1 coming out is 'code1:Y'  not 'Y'.

I'm wondering if there's a way to inject the column_name dynamically in the code1 value as it's going out to the code_table.

UPDATE 1:

Here's an example output from data_table to join against code_table:

1, code1:Y, code2:3, code3:A, IA
2, code1:Y, code2:2, code3:B, IB
3, code1:N, code2:5, code3:C, IC

Thanks

Body:
Does using the TO_JSON_STRING function give the desired output? Here is an example using your data:

WITH `project.dataset.table` AS (
  SELECT 1 AS id, 'Y' AS code1, 3 AS code2, 'A' AS code3, 'IA' AS data1 UNION ALL
  SELECT 2, 'Y', 2, 'B', 'IB' UNION ALL
  SELECT 3, 'N', 5, 'C', 'IC'
)
SELECT TO_JSON_STRING(t) AS json
FROM `project.dataset.table` AS t;
+---------------------------------------------------------+
| json                                                    |
+---------------------------------------------------------+
| {"id":1,"code1":"Y","code2":3,"code3":"A","data1":"IA"} |
| {"id":2,"code1":"Y","code2":2,"code3":"B","data1":"IB"} |
| {"id":3,"code1":"N","code2":5,"code3":"C","data1":"IC"} |
+---------------------------------------------------------+

If you want to strip out the quotes, you can do that too:

WITH `project.dataset.table` AS (
  SELECT 1 AS id, 'Y' AS code1, 3 AS code2, 'A' AS code3, 'IA' AS data1 UNION ALL
  SELECT 2, 'Y', 2, 'B', 'IB' UNION ALL
  SELECT 3, 'N', 5, 'C', 'IC'
)
SELECT REPLACE(TO_JSON_STRING(t), '"', '') AS json
FROM `project.dataset.table` AS t;
+-----------------------------------------+
| json                                    |
+-----------------------------------------+
| {id:1,code1:Y,code2:3,code3:A,data1:IA} |
| {id:2,code1:Y,code2:2,code3:B,data1:IB} |
| {id:3,code1:N,code2:5,code3:C,data1:IC} |
+-----------------------------------------+

Edit: this gives the exact desired output. I'm assuming that you are okay with referencing id and data by name since it sounds like you don't want to format them in the same way.

WITH `project.dataset.table` AS (
  SELECT 1 AS id, 'Y' AS code1, 3 AS code2, 'A' AS code3, 'IA' AS data1 UNION ALL
  SELECT 2, 'Y', 2, 'B', 'IB' UNION ALL
  SELECT 3, 'N', 5, 'C', 'IC'
)
SELECT
  REGEXP_REPLACE(
    FORMAT(
      '%d %s %s',
      id,
      REGEXP_REPLACE(
        TO_JSON_STRING(
          (SELECT AS STRUCT t.* EXCEPT (id, data1))
        ),
        '["{}]', ''),
      data1
    ),
    r'[ ,]', ', '
  ) AS output
FROM `project.dataset.table` AS t;
+----------------------------------+
| output                           |
+----------------------------------+
| 1, code1:Y, code2:3, code3:A, IA |
| 2, code1:Y, code2:2, code3:B, IB |
| 3, code1:N, code2:5, code3:C, IC |
+----------------------------------+


来源: stackexchange

问:
Java: Prevent Socket DataInputStream from throwing EOFException
My client/server application currently keeps opening and closing new connections every time it wants to send/receive data.  I'm trying to change it so it will have one persistent connection.

The problem I'm having is the socket's DataInputStream on the server keeps throwing EOFException's when I just want it to block until it receives the next batch of data.

I thought about just simply writing the server like this...

```<code>while socket is open {
    while at socket's DataInputStream's EOF {
        wait a second
    }
    //If we're here, then we have some data
    do stuff
}
</code>```

... but this is extremely ugly and not the proper way to block until some data is received.

Is there a cleaner way to tell the socket to block until there's some data to read?  I've tried read() and readFully(), but neither work.

答: If you are getting EOFException, it means the connection is gone. You cannot wait on a connection that's closed. Keep working on your client code so that it doesn't close the connection. On the server side, any of the read methods will block until data is available without further effort from you.</p>

ContentLicense: CC BY-SA 4.0

Body:
My client/server application currently keeps opening and closing new connections every time it wants to send/receive data.  I'm trying to change it so it will have one persistent connection.

The problem I'm having is the socket's DataInputStream on the server keeps throwing EOFException's when I just want it to block until it receives the next batch of data.

I thought about just simply writing the server like this...

while socket is open {
    while at socket's DataInputStream's EOF {
        wait a second
    }
    //If we're here, then we have some data
    do stuff
}

... but this is extremely ugly and not the proper way to block until some data is received.

Is there a cleaner way to tell the socket to block until there's some data to read?  I've tried read() and readFully(), but neither work.

ContentLicense: CC BY-SA 2.5


问:
j2objc - exception when deserialize enum
I am having trouble deserializing objects that contain an enum. The object serializes without complaint, but I get an InvalidObjectException when I deserialize the object.  The exception message says that there is "No enum constant com.mypackagname."

I have isolated and reproduced the problem by creating some test code based on the testSerialization() method in SerializationTest.java.

```<code>public class SerializationTest {
    private static final String TEST_FILE_NAME = "serialization-test.bin";
    public enum Gender { MALE, FEMALE }

    public void testEnumSerialization() throws IOException, ClassNotFoundException {
        Gender gender = Gender.MALE;

        // Save the enum to a file.
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(TEST_FILE_NAME));
        out.writeObject(gender);
        out.close();

        // Read back the enum.
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(TEST_FILE_NAME));
        Gender gender2 = (Gender) in.readObject();
        in.close();
    }
}
</code>```

I have discovered that if I add a string value to the enum initialization in the generated Objective C code the deserialization works fine.  The resulting initialize method in Obj C looks like this:

```<code>+ (void)initialize {
    if (self == [SerializationTest_Gender class]) {
        JreEnum(SerializationTest_Gender, MALE) = new_SerializationTest_Gender_initWithNSString_withInt_(@"MALE", 0);
        JreEnum(SerializationTest_Gender, FEMALE) = new_SerializationTest_Gender_initWithNSString_withInt_(@"FEMALE", 1);
        J2OBJC_SET_INITIALIZED(SerializationTest_Gender)
    }
}
</code>```

Note that I added the @"MALE" and @"FEMALE", the default from the j2objc output is @"".

I have two questions.  (1) Is this the correct way to enable a round trip serialization/deserialization of enums?  (2) If so, is there a way to have j2objc automatically populate the string constants in the enum rather than coding them by hand?

Thanks for any help you can provide.

答:
We probably broke this with a recent change eliminating redundant enum constant name strings. We had the name defined both in the enum's class initializer and in its metadata, plus we had an important request to stop making enum constants easily discovered in app binaries (apparently tech writers have been known to dump early access binaries and run strings on them to get scoops on any new features). Now the constant name is only in the metadata (no redundancy), and if an app builds with --strip-reflection, the enum has no metadata and the name becomes the enum class plus the constant's ordinal. However, serialization support was overlooked since Google apps use protocol buffers instead (faster and less version-sensitive).

Thanks for the excellent test case, which will make it easier to fix. Please file a bug if you want to be notified when this is fixed.

ContentLicense: CC BY-SA 3.0

Body:
I am having trouble deserializing objects that contain an enum. The object serializes without complaint, but I get an InvalidObjectException when I deserialize the object.  The exception message says that there is "No enum constant com.mypackagname."

I have isolated and reproduced the problem by creating some test code based on the testSerialization() method in SerializationTest.java.

public class SerializationTest {
    private static final String TEST_FILE_NAME = "serialization-test.bin";
    public enum Gender { MALE, FEMALE }

    public void testEnumSerialization() throws IOException, ClassNotFoundException {
        Gender gender = Gender.MALE;

        // Save the enum to a file.
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(TEST_FILE_NAME));
        out.writeObject(gender);
        out.close();

        // Read back the enum.
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(TEST_FILE_NAME));
        Gender gender2 = (Gender) in.readObject();
        in.close();
    }
}

I have discovered that if I add a string value to the enum initialization in the generated Objective C code the deserialization works fine.  The resulting initialize method in Obj C looks like this:

+ (void)initialize {
    if (self == [SerializationTest_Gender class]) {
        JreEnum(SerializationTest_Gender, MALE) = new_SerializationTest_Gender_initWithNSString_withInt_(@"MALE", 0);
        JreEnum(SerializationTest_Gender, FEMALE) = new_SerializationTest_Gender_initWithNSString_withInt_(@"FEMALE", 1);
        J2OBJC_SET_INITIALIZED(SerializationTest_Gender)
    }
}

Note that I added the @"MALE" and @"FEMALE", the default from the j2objc output is @"".

I have two questions.  (1) Is this the correct way to enable a round trip serialization/deserialization of enums?  (2) If so, is there a way to have j2objc automatically populate the string constants in the enum rather than coding them by hand?

Thanks for any help you can provide.


问:
Django - How can I prevent access to other users' objects?
Let's assume that I have such URL users/{id}/objects and I am authenticated as a User with ID equals 1. At the moment I can access objects of users with ID equals 2, 3 etc. Does anyone have an idea how can I prevent this?

```<code>class UserObject(GenericAPIView):

    permission_classes = [UserPermission]
    def get(self, request, user_id):

            try:
                object = Object.objects.filter(user=user_id)
            except Object.DoesNotExist:
                return Response(status=status.HTTP_404_NOT_FOUND)
            serializer = ObjectSerializer(object, many=True)
            return Response(serializer.data)

class UserPermission(permissions.BasePermission):

    def has_permission(self, request, view):
        if request.user and request.user.is_authenticated():
            return True
        return False
</code>```

I tried in this way:

```<code>serializer_class = ObjectSerializer
permission_classes = [IsAuthenticated, ]

def get_queryset(self):
    return Object.objects.filter(owner=self.request.user)

def get(self, request, user_id):

        try:
            object = Object.objects.filter(user=user_id)
        except Object.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = ObjectSerializer(object, many=True)
        return Response(serializer.data)
</code>```

答:
You can use the IsAuthenticated permission only to check if someone is logged in and than check "manually" if the user is asking for data of its own or not. Like this:

```<code>class UserObject(GenericAPIView):

    permission_classes = (IsAuthenticated,)
    def get(self, request, user_id):

        if (str(reques.user.id) != user_id):
            return Response(status=status.HTTP_403_FORBIDDEN)

        try:
            object = Object.objects.filter(user=user_id)
        except Object.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        serializer = ObjectSerializer(object, many=True)
        return Response(serializer.data)
</code>```

If you really want to use a custom permission your can leave you view untouched and make you permission classe like this:

```<code>class UserPermission(permissions.BasePermission):

    def has_permission(self, request, view):
        if (not request.user.is_authenticated()):
            return False

        user_id = request.path.split('/')[1]

        if (str(request.user.id) == user_id):
            return True

        return False
</code>```

Note: I'd recomend the first option.

Note: this code is an example, if it doen't work right away, try to
understand the idea and adapt it. I didn't tested it and it may need some ajusts, specially the part that gets the user_id frorm response.path.

Body:
Let's assume that I have such URL users/{id}/objects and I am authenticated as a User with ID equals 1. At the moment I can access objects of users with ID equals 2, 3 etc. Does anyone have an idea how can I prevent this?

class UserObject(GenericAPIView):

    permission_classes = [UserPermission]
    def get(self, request, user_id):

            try:
                object = Object.objects.filter(user=user_id)
            except Object.DoesNotExist:
                return Response(status=status.HTTP_404_NOT_FOUND)
            serializer = ObjectSerializer(object, many=True)
            return Response(serializer.data)

class UserPermission(permissions.BasePermission):

    def has_permission(self, request, view):
        if request.user and request.user.is_authenticated():
            return True
        return False

I tried in this way:

serializer_class = ObjectSerializer
permission_classes = [IsAuthenticated, ]

def get_queryset(self):
    return Object.objects.filter(owner=self.request.user)

def get(self, request, user_id):

        try:
            object = Object.objects.filter(user=user_id)
        except Object.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = ObjectSerializer(object, many=True)
        return Response(serializer.data)

Body:
You can use the IsAuthenticated permission only to check if someone is logged in and than check "manually" if the user is asking for data of its own or not. Like this:

class UserObject(GenericAPIView):

    permission_classes = (IsAuthenticated,)
    def get(self, request, user_id):

        if (str(reques.user.id) != user_id):
            return Response(status=status.HTTP_403_FORBIDDEN)

        try:
            object = Object.objects.filter(user=user_id)
        except Object.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        serializer = ObjectSerializer(object, many=True)
        return Response(serializer.data)

If you really want to use a custom permission your can leave you view untouched and make you permission classe like this:

class UserPermission(permissions.BasePermission):

    def has_permission(self, request, view):
        if (not request.user.is_authenticated()):
            return False

        user_id = request.path.split('/')[1]

        if (str(request.user.id) == user_id):
            return True

        return False

Note: I'd recomend the first option.

Note: this code is an example, if it doen't work right away, try to
understand the idea and adapt it. I didn't tested it and it may need some ajusts, specially the part that gets the user_id frorm response.path.


问:
RestAssure: How to make the abstract layer for the type of endpoint call
This is my restAssure call for GET endpoints :

```<code>public static Response getCall(int expectedStatusCode){
    return given()
            .port(PORT)
            .contentType(ContentType.JSON)
            .when()
            .log().all()
            .get(getEndpoint)
            .then()
            .log().all()
            .assertThat()
            .statusCode(expectedStatusCode).extract().response();
}
</code>```

Below is the call for the POST endpoints:

```<code>public static Response postEndpoint(Request request, int expectedStatusCode) {
    return given()
            .port(PORT)
            .contentType(ContentType.JSON)
            .body(request)
            .when()
            .log().all()
            .post(postEndpointURI)
            .then()
            .log().all()
            .assertThat()
            .statusCode(expectedStatusCode).extract().response();
}
</code>```

AS its visible the code is redundant only difference is the type of call , POST and GET.

How can I make the code abstract and just have the calls different?

答:
Hopefully it helps a bit with your redundancy issue. You will probably get more ideas from here to improve refactor. </p>

```<code>private static final int PORT = 1922;
private static String getEndpoint;
private static String postEndpointURI;

/**
 * First part of the building up the request
 */
private static RequestSpecification buildRequest() {
    return given()
            .port(PORT)
            .contentType(ContentType.JSON)
            .when()
            .log().all();
}

/**
 * Relevant part of the GET request
 */
private static Response buildGetRequest() {
    return buildRequest().get(getEndpoint);
}

/**
 * Relevant part of the POST request
 */
private static Response buildPostRequest(Request request) {
    return buildRequest().body(request).post(postEndpointURI);
}

/**
 * Last bit redundant that was called by both calls
 */
private static Response extractResponse(Response response, int expectedStatusCode) {
    return response.then()
            .log().all()
            .assertThat()
            .statusCode(expectedStatusCode).extract().response();
}

/**
 * Your main GET method
 */
public static Response assertThatGetResponseStatusIs(int expectedStatusCode) {
    return extractResponse(buildGetRequest(), expectedStatusCode);
}

/**
 * Your main POST method
 */
public static Response assertThatPostResponseStatusIs(Request request, int expectedStatusCode) {
    return extractResponse(buildPostRequest(request), expectedStatusCode);
}

public static void main(String[] args) {
    System.out.println(assertThatGetResponseStatusIs(500));
    System.out.println(assertThatPostResponseStatusIs(request, 400));
}
</code>```

Body:
This is my restAssure call for GET endpoints :

public static Response getCall(int expectedStatusCode){
    return given()
            .port(PORT)
            .contentType(ContentType.JSON)
            .when()
            .log().all()
            .get(getEndpoint)
            .then()
            .log().all()
            .assertThat()
            .statusCode(expectedStatusCode).extract().response();
}

Below is the call for the POST endpoints:

public static Response postEndpoint(Request request, int expectedStatusCode) {
    return given()
            .port(PORT)
            .contentType(ContentType.JSON)
            .body(request)
            .when()
            .log().all()
            .post(postEndpointURI)
            .then()
            .log().all()
            .assertThat()
            .statusCode(expectedStatusCode).extract().response();
}

AS its visible the code is redundant only difference is the type of call , POST and GET.

How can I make the code abstract and just have the calls different?

Body:
Hopefully it helps a bit with your redundancy issue. You will probably get more ideas from here to improve refactor.

private static final int PORT = 1922;
private static String getEndpoint;
private static String postEndpointURI;

/**
 * First part of the building up the request
 */
private static RequestSpecification buildRequest() {
    return given()
            .port(PORT)
            .contentType(ContentType.JSON)
            .when()
            .log().all();
}

/**
 * Relevant part of the GET request
 */
private static Response buildGetRequest() {
    return buildRequest().get(getEndpoint);
}

/**
 * Relevant part of the POST request
 */
private static Response buildPostRequest(Request request) {
    return buildRequest().body(request).post(postEndpointURI);
}

/**
 * Last bit redundant that was called by both calls
 */
private static Response extractResponse(Response response, int expectedStatusCode) {
    return response.then()
            .log().all()
            .assertThat()
            .statusCode(expectedStatusCode).extract().response();
}

/**
 * Your main GET method
 */
public static Response assertThatGetResponseStatusIs(int expectedStatusCode) {
    return extractResponse(buildGetRequest(), expectedStatusCode);
}

/**
 * Your main POST method
 */
public static Response assertThatPostResponseStatusIs(Request request, int expectedStatusCode) {
    return extractResponse(buildPostRequest(request), expectedStatusCode);
}

public static void main(String[] args) {
    System.out.println(assertThatGetResponseStatusIs(500));
    System.out.println(assertThatPostResponseStatusIs(request, 400));
}


问:
C++ : How to ensure that a class member variable is modifiable only within a certain method
I am using C++ 14 with clang on MacOS Sierra. I want to enforce a rule by design. Following is the rule.

I have a member variable in my class say:

```<code>unsigned int m_important_num;
</code>```

There are 4 methods in my class.

```<code>fun1();
fun2();
fun3();
fun4();
</code>```

Objective:

I want only fun2() to be able to change the value of m_important_num.

Question:

Is it possible to make it compiler error if any method other than fun2() changes the variable?
One possible way is to declare it const somehow empower fun2() to change const variables? Is this a good solution? Or are their any better solutions?

Secondary question:

Is it a wrong design to try do such a thing?

答:
Sort of, with additional layer:

```<code>class S1 {
public:
    void fun2() { /*Modify m_important_num */ }
    unsigned int getImportantNum() const { return m_important_num;}
private:
    unsigned int m_important_num;
};
class S2 : private S1
{
public:
    void fun1();
    using S1::fun2; // or void fun2() {S1::fun2();}
    void fun3();
    void fun4();
};
</code>```

As Yakk commented, if func2 need access to S2 members, CRTP can solve that:

```<code>template <typename Derived>
class S1 {
public:
    void fun2() { asDerived().foo3(); /*Modify m_important_num */ }
    unsigned int getImportantNum() const { return m_important_num;}
private:
    Derived& asDerived() { return stataic_cast<Derived&>(*this); }
private:
    unsigned int m_important_num;
};
class S2 : private S1<S2>
{
    // friend class S1<S2>; // If required.
public:
    void fun1();
    using S1::fun2; // or void fun2() {S1::fun2();}
    void fun3();
    void fun4();
};
</code>```

Body:
I am using C++ 14 with clang on MacOS Sierra. I want to enforce a rule by design. Following is the rule.

I have a member variable in my class say:

unsigned int m_important_num;

There are 4 methods in my class.

fun1();
fun2();
fun3();
fun4();

Objective:

I want only fun2() to be able to change the value of m_important_num.

Question:

Is it possible to make it compiler error if any method other than fun2() changes the variable?
One possible way is to declare it const somehow empower fun2() to change const variables? Is this a good solution? Or are their any better solutions?

Secondary question:

Is it a wrong design to try do such a thing?

Body:
Sort of, with additional layer:

class S1 {
public:
    void fun2() { /*Modify m_important_num */ }
    unsigned int getImportantNum() const { return m_important_num;}
private:
    unsigned int m_important_num;
};
class S2 : private S1
{
public:
    void fun1();
    using S1::fun2; // or void fun2() {S1::fun2();}
    void fun3();
    void fun4();
};

As Yakk commented, if func2 need access to S2 members, CRTP can solve that:

template <typename Derived>
class S1 {
public:
    void fun2() { asDerived().foo3(); /*Modify m_important_num */ }
    unsigned int getImportantNum() const { return m_important_num;}
private:
    Derived& asDerived() { return stataic_cast<Derived&>(*this); }
private:
    unsigned int m_important_num;
};
class S2 : private S1<S2>
{
    // friend class S1<S2>; // If required.
public:
    void fun1();
    using S1::fun2; // or void fun2() {S1::fun2();}
    void fun3();
    void fun4();
};


问:
How to add data into join table from form in Rails?
I have three models in my rails application. When I create a new notification how do I rewrite the notifications_controller.rb and the form in notifications/new.html.erb so that the entry gets saved to the notifications_users table? Thanks

schema.rb

```<code>create_table "notifications", force: :cascade do |t|
 t.string "title"
 t.string "first_name"
 t.string "last_name"
 t.datetime "date"
 t.text "content"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false

 end

create_table "notifications_users", id: false, force: :cascade do |t|
 t.bigint "user_id", null: false
 t.bigint "notification_id", null: false
 end

create_table "users", force: :cascade do |t|
 t.string "first_name"
 t.string "last_name"
 t.string "user_type"
 t.string "username"
 t.string "password"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.string "password_digest"
 t.index ["username"], name: "index_users_on_username", unique: true

end
</code>```

new.html.erb

```<code><h1>New Message</h1>

 <div class="row">
 <div class="col-md-6 col-md-offset-3">

 <%= form_for(@notification, url: notifications_new_path) do |f| %>

  <%= f.label :title %>
  <%= f.text_field :title, class: 'form-control' %>

  <%= f.label :first_name %>
  <%= f.text_field :first_name, class: 'form-control' %>

  <%= f.label :date %>
  <%= f.datetime_field :date %>

  <%= f.label :content %>
  <%= f.text_area :content, class: 'form-control' %>

  <%= f.submit "Create my message", class: "btn btn-primary" %>
<% end %>
</code>```

notifications_controller.rb

```<code>def create
  @notification = Notification.new(notification_params)

  if @notification.save
    flash[:success] = "Notification created!"
    redirect_to @notification
 else
   render 'new'
 end
end
</code>```

答:
So you want to create two records here, a Notification record and a NotificationUser record. There are a number of ways to do this such as:

```<code>...
@notification = Notification.new(notification_params)

if @notification.save
  NotificationUser.create(user_id: USER_ID_HERE, notification_id: @notification.id) # OR NotificationUser.create(user: USER_RECORD_HERE, notification: @notification) OR @notification.users << USER_RECORD_HERE
...
</code>```

Body:
I have three models in my rails application. When I create a new notification how do I rewrite the notifications_controller.rb and the form in notifications/new.html.erb so that the entry gets saved to the notifications_users table? Thanks

schema.rb

create_table "notifications", force: :cascade do |t|
 t.string "title"
 t.string "first_name"
 t.string "last_name"
 t.datetime "date"
 t.text "content"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false

 end

create_table "notifications_users", id: false, force: :cascade do |t|
 t.bigint "user_id", null: false
 t.bigint "notification_id", null: false
 end

create_table "users", force: :cascade do |t|
 t.string "first_name"
 t.string "last_name"
 t.string "user_type"
 t.string "username"
 t.string "password"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.string "password_digest"
 t.index ["username"], name: "index_users_on_username", unique: true

end

new.html.erb

New Message

 <%= form_for(@notification, url: notifications_new_path) do |f| %>

  <%= f.label :title %>
  <%= f.text_field :title, class: 'form-control' %>

  <%= f.label :first_name %>
  <%= f.text_field :first_name, class: 'form-control' %>

  <%= f.label :date %>
  <%= f.datetime_field :date %>

  <%= f.label :content %>
  <%= f.text_area :content, class: 'form-control' %>

  <%= f.submit "Create my message", class: "btn btn-primary" %>
<% end %>

notifications_controller.rb

def create
  @notification = Notification.new(notification_params)

  if @notification.save
    flash[:success] = "Notification created!"
    redirect_to @notification
 else
   render 'new'
 end
end

Body:
So you want to create two records here, a Notification record and a NotificationUser record. There are a number of ways to do this such as:

...
@notification = Notification.new(notification_params)

if @notification.save
  NotificationUser.create(user_id: USER_ID_HERE, notification_id: @notification.id) # OR NotificationUser.create(user: USER_RECORD_HERE, notification: @notification) OR @notification.users << USER_RECORD_HERE
...


问:
RenderPartial and popup modal MVC C#
I have some code in Index view

```<code>@foreach (var item in Model){
<tr><td>......</td>
    <td><button class="success" data-toggle="modal" data-target="#detailsModal" >details</button>
        <div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="detailsModalLabel" aria-hidden="true">
             @{Html.RenderPartial("_Details", item);}
        </div></td></tr>}
</code>```

but after click my button on different rows, popup show always first item of database. How can I change it?

Controller

```<code>        public ActionResult Details(int? id)
    {
        DBase dbase = new DBase();
        dbase = db.DBase.Find(id);
        return PartialView("_Details", dbase);
    }
</code>```

答:
You have multiple modals declared in your HTML with same ID due to your foreach loop.

So it only uses the first modal element it found. To fix this give each of your modal a unique ID.

So you would change data-target="#detailsModal" and id="detailsModal" by adding index to it so it would be like id="detailsModal-1" etc

Title: RenderPartial and popup modal MVC C#

Body:
I have some code in Index view

@foreach (var item in Model){

......
    <button class="success" data-toggle="modal" data-target="#detailsModal" >details</button>

             @{Html.RenderPartial("_Details", item);}

}

but after click my button on different rows, popup show always first item of database. How can I change it?

Controller

        public ActionResult Details(int? id)
    {
        DBase dbase = new DBase();
        dbase = db.DBase.Find(id);
        return PartialView("_Details", dbase);
    }


问:
GWT Special Features compared to other Frameworks
I am on searching special features of GWT which are present only in GWT and not in other web framework. I am a student and I am not well acquainted to the many web frameworks on the market, so if u can help me increasing my list of special GWT features, it would be a great help. Some which i know are:

```<code> 1. GWT allows using java to program
web. (only, it also allows merging
javascript through JSNI of course)

2. The developer does not have to be a guru in browser incompatibilities
to develop web sites which works on
a variety of browsers because
incompatibilities are handled by GWT
through differed bindind

3. GWT allows easy integration of popular Java Tools such as ,
hibernate through gilead

4. GWT enables server implementation not only in java but also other
languages such as php

5. GWT enables code splitting which improves application interactivity
by allowing javaScript file to
download only when required

6. In essence GWT is toolkit, it does not force a way to program,
other layers can be placed on top of
it to program such as placing MVP or
MVC framework on top of GWT and then
develop app

7. GWT MVP is great because first it allows collaborative working, faster
testing with JUnit and the event bus
allows many updates in client side
application by placing event on the
event bus

8. GWT compiled java files to obfuscated mode which is first small
and make the application safer
because bots fails on the javascript
generated during the obfuscated mode
</code>```

In case in the 8 points, i've mention something which not special to GWT, then let me know.

答:
There's also 'perfect caching', which is the term used to describe the way that GWT optimises JavaScript for each browser.

Instead of building a large JavaScript file, with code that can handle all of the various browsers, GWT builds multiple JavaScript files at compile time, and downloads only the one that is relevant to the browser type that is being used.

EDIT: Every time you make a change to your Java code, GWT changes the name of the corresponding JavaScript file. Web servers can turn on caching for the JavaScript files (so that browsers won't re-download the same file), assured that the name will change when the Java code changes, and the browser will then download the latest version.

EDIT: I also really like the CssResource feature. By creating obfuscated CSS style names, GWT effectively gives each widget its own namespace for CSS styles; for example, I could define a 'pretty' style name on two different widgets, and have those styles using different CSS rules. Of course, it is possible to share CSS styles between widgets too.

Image resources are cool too. They optimise the way that images are downloaded and accessed.

Don't forget internationalization.

Body:
I am on searching special features of GWT which are present only in GWT and not in other web framework. I am a student and I am not well acquainted to the many web frameworks on the market, so if u can help me increasing my list of special GWT features, it would be a great help. Some which i know are:

 1. GWT allows using java to program
web. (only, it also allows merging
javascript through JSNI of course)

2. The developer does not have to be a guru in browser incompatibilities
to develop web sites which works on
a variety of browsers because
incompatibilities are handled by GWT
through differed bindind

3. GWT allows easy integration of popular Java Tools such as ,
hibernate through gilead

4. GWT enables server implementation not only in java but also other
languages such as php

5. GWT enables code splitting which improves application interactivity
by allowing javaScript file to
download only when required

6. In essence GWT is toolkit, it does not force a way to program,
other layers can be placed on top of
it to program such as placing MVP or
MVC framework on top of GWT and then
develop app

7. GWT MVP is great because first it allows collaborative working, faster
testing with JUnit and the event bus
allows many updates in client side
application by placing event on the
event bus

8. GWT compiled java files to obfuscated mode which is first small
and make the application safer
because bots fails on the javascript
generated during the obfuscated mode

In case in the 8 points, i've mention something which not special to GWT, then let me know.


问:
Calculating the sum of values from a text file?
im trying to find the sum of the cost of all my books in my libary system from a file, could someone say where im going wrong atm. It would be great help

```<code>int sum = 0;
    File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");

    try {
        Scanner fileReader  = new Scanner (Fileobject);

        // Read and display each line of the file

        while(fileReader.hasNext())
        {
            sum+= fileReader.nextInt ( );
            line = fileReader.nextLine();
            System.out.println(line);
            System.out.println(sum);
        }
            fileReader.close();
</code>```

This is my data im reading:

```<code>The_Hunger_Games - Suzanne_Collins - 5 - Scholastic_Press - 9781921988752

OOP_programming - Graham_Winter - 32.50 – Oreilly - 0471974555

Harry_potter - Jk_Rowling - 10 - Bloomsbury- 9788700631625
</code>```

This is the errors im getting:

```<code>Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at c3500948JavaProjectAssignement1.c3500948.main(c3500948.java:80)
</code>```

答:
The first line of your file is:

The_Hunger_Games - Suzanne_Collins - 5 - Scholastic_Press - 9781921988752

The code

```<code>sum+= fileReader.nextInt ( );
</code>```

expects a number thought.
Before calculating the sum you need to parse out the part of the line which is the number to be added to the sum.

Body:
im trying to find the sum of the cost of all my books in my libary system from a file, could someone say where im going wrong atm. It would be great help

int sum = 0;
    File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");

    try {
        Scanner fileReader  = new Scanner (Fileobject);

        // Read and display each line of the file

        while(fileReader.hasNext())
        {
            sum+= fileReader.nextInt ( );
            line = fileReader.nextLine();
            System.out.println(line);
            System.out.println(sum);
        }
            fileReader.close();

This is my data im reading:

The_Hunger_Games - Suzanne_Collins - 5 - Scholastic_Press - 9781921988752

OOP_programming - Graham_Winter - 32.50 – Oreilly - 0471974555

Harry_potter - Jk_Rowling - 10 - Bloomsbury- 9788700631625

This is the errors im getting:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at c3500948JavaProjectAssignement1.c3500948.main(c3500948.java:80)

Body:
The first line of your file is:

The_Hunger_Games - Suzanne_Collins - 5 - Scholastic_Press - 9781921988752

The code

sum+= fileReader.nextInt ( );

expects a number thought.
Before calculating the sum you need to parse out the part of the line which is the number to be added to the sum.


问:
Joining two tables where id does not equal
I'm struggling getting this query to produce the results I want.

I have:

table1, columns=empid, alt_id

table2, columns=empid, alt_id

I want to get the empid, and alt_id from table 1 where the alt_id does not match the alt_id in table2. They will both have alt_id numbers I just want to get the ones that do not match.

Any ideas?

答:
A left join will find all records in Table A that do not match those in Table B.  Then use a Where filter to find the Nulls from Table B.  That will give you all those in Table A that do not have a matching ID in Table B.

```<code>    Select A.*
    from Table A
    Left Join
    Table B
    on a.altid = b.altid
    where b.altid is null;
</code>```

Body:
A left join will find all records in Table A that do not match those in Table B.  Then use a Where filter to find the Nulls from Table B.  That will give you all those in Table A that do not have a matching ID in Table B.

    Select A.*
    from Table A
    Left Join
    Table B
    on a.altid = b.altid
    where b.altid is null;


问:
How to write the contents of one CSV file to another
I have a csv file and I want to transfer the raw data without the headers to a new csv file and have the rows and columns the same as the original.

```<code>IRIS_data = "IRIS_data.csv"

with open(IRIS_data, 'wb') as data:
    wr = csv.writer(data, quoting=csv.QUOTE_ALL)
    with open(IRIS) as f:
        next(f)
        for line in f:
            wr.writerow(line)
</code>```

The code above is my most recent attempt, when I try run it I get the following error:

```<code>a bytes-like object is required, not 'str'
</code>```

答:
You have to encode the line you are writing like this:

```<code>wr.writerow( line.encode(”utf8”))
</code>```

Also open your file using open(..., ‘wb’). This will open the file in binary mode. So you are certain the file is actually open in binary mode. Indeed it is better to now explicitly the encoding than assuming it. Enforcing encoding for both reading and writing will save you lots of trouble.

Body:
I have a csv file and I want to transfer the raw data without the headers to a new csv file and have the rows and columns the same as the original.

IRIS_data = "IRIS_data.csv"

with open(IRIS_data, 'wb') as data:
    wr = csv.writer(data, quoting=csv.QUOTE_ALL)
    with open(IRIS) as f:
        next(f)
        for line in f:
            wr.writerow(line)

The code above is my most recent attempt, when I try run it I get the following error:

a bytes-like object is required, not 'str'

Body:
You have to encode the line you are writing like this:

wr.writerow( line.encode(”utf8”))

Also open your file using open(..., ‘wb’). This will open the file in binary mode. So you are certain the file is actually open in binary mode. Indeed it is better to now explicitly the encoding than assuming it. Enforcing encoding for both reading and writing will save you lots of trouble.


问:
Google spreadsheet custom function returns nothing
I have a problem debugging the code. It's working if I define values by myself instead of taking it from properties and spreadsheet. I am new to JavaScript so it can be really basic error.

What I am trying to do with this function:

Taking name of person, date and name of school from the spreadsheet

Getting arrays data from the properties that was saved with other function. The saving line in that function looks like this:

```<code>PropertiesService.getScriptProperties().setProperty('Mokyklos', JSON.stringify(Mokyklos));
</code>```

It's 6 arrays of full names, array of date, array of school names and array of numbers. The numbers array is used to return the answer.

```<code>      function ApmokMokMokykloje(mokytojas, data, mokykla) {
      Utilities.sleep(Math.random() * 1000);
      var MokytojaiL = PropertiesService.getScriptProperties().getProperty('MokytojaiL');
      var Mokytojai1 = PropertiesService.getScriptProperties().getProperty('Mokytojai1');
      var Mokytojai2 = PropertiesService.getScriptProperties().getProperty('Mokytojai2');
      Utilities.sleep(Math.random() * 1000);
      var Mokytojai3 = PropertiesService.getScriptProperties().getProperty('Mokytojai3');
      var Mokytojai4 = PropertiesService.getScriptProperties().getProperty('Mokytojai4');
      var Mokytojai5 = PropertiesService.getScriptProperties().getProperty('Mokytojai5');
      Utilities.sleep(Math.random() * 1000);
      var Datos = PropertiesService.getScriptProperties().getProperty('Datos');
      var Mokyklos = PropertiesService.getScriptProperties().getProperty('Mokyklos');
      var ApmokMokSkaiciai = PropertiesService.getScriptProperties().getProperty('ApmokMokSkaiciai');

      var mokytojaiL = MokytojaiL;
      mokytojaiL = JSON.parse(mokytojaiL);

      var mokytojai1 = Mokytojai1;
      mokytojai1 = JSON.parse(mokytojai1);

      var mokytojai2 = Mokytojai2;
      mokytojai2 = JSON.parse(mokytojai2);

      var mokytojai3 = Mokytojai3;
      mokytojai3 = JSON.parse(mokytojai3);

      var mokytojai4 = Mokytojai4;
      mokytojai4 = JSON.parse(mokytojai4);

      var mokytojai5 = Mokytojai5;
      mokytojai5 = JSON.parse(mokytojai5);

      var datos = Datos;
      datos = JSON.parse(datos);

      var mokyklos = Mokyklos;
      mokyklos = JSON.parse(mokyklos);

      var skaicius = ApmokMokSkaiciai;
      skaicius = JSON.parse(skaicius);

      for(var i = 0; i < mokyklos.length; i++) {
        if(data==datos[i] && mokykla==mokyklos[i]) {
        if ((mokytojas==mokytojaiL[i]) || (mokytojas==mokytojai1[i]) || (mokytojas==mokytojai2[i]) || (mokytojas==mokytojai3[i]) || (mokytojas==mokytojai4[i]) || (mokytojas==mokytojai5[i]))  {
        return skaicius[i]; // returns blank
            }
          }
        }

    }
</code>```

The code below works fine.

```<code>function testas3(mokytojas, data, mokykla) {

  // the same values from spreadsheet
  var datapvz="2017-11-04T22:00:00.000Z";
  var mokyklapvz="Zalioji mokykla";
  var mokytojaspvz="Penivilas Gremlinavičius";

  // the same values from properties
  var datos = [];
datos[0]="2017-11-08T22:00:00.000Z";
datos[1] = "2017-11-15T22:00:00.000Z";
datos[2] = "2017-11-11T22:00:00.000Z";
datos[3] = "2017-11-03T22:00:00.000Z";
datos[4] = "2017-11-04T22:00:00.000Z";
  var mokyklos = [];
mokyklos[0] = "Mokykla nuostabioji";
mokyklos[1] = "Mylimiausioji mokyklele";
mokyklos[2] = "Dar viena mokyykla";
mokyklos[3] = "Raudonoji";
mokyklos[4] = "Zalioji mokykla";
  var mokytojaiL = [];
mokytojaiL[0] = "Cristopher Rangel";
mokytojaiL[1] = "Alessandra Knox";
mokytojaiL[2] = "Germtautas Falalavičius";
mokytojaiL[3] = "Lenkgaudė Trikojytė";
mokytojaiL[4] = "Penivilas Gremlinavičius";
var mokytojai1 = [];
mokytojai1[0] = "Mantvydas Špukys";
mokytojai1[1] = "Išeikbaida Visursėkmytė";
mokytojai1[2] = "Svaidgaudė Praperduvienė";
mokytojai1[3] = "Mantvinas Žirgmyla";
mokytojai1[4] = "Mantvinas Žirgmyla";
var mokytojai2 = [];
mokytojai2[0] = "Griovbaida Nepriteklytė";
mokytojai2[1] = "Išeikbaida Visursėkmytė";
mokytojai2[2] = "Griovbaida Nepriteklytė";
mokytojai2[3] = "Arjautauta Fragmentavičiutė";
mokytojai2[4] = "Kastuvaldas Parašiutauskas";
var mokytojai3 = [];
mokytojai3[0] = "Rustautas Celiulionis";
mokytojai3[1] = "Androbauda Parankpapaitė";
mokytojai3[2] = "Arjauvilė Katrakojytė";
mokytojai3[3] = null;
mokytojai3[4] = "Rustautas Celiulionis";
var mokytojai4 = [];
mokytojai4[0] = null;
mokytojai4[1] = null;
mokytojai4[2] = null;
mokytojai4[3] = "Arjauvilė Katrakojytė";
 var mokytojai5  = [];
  var skaicius = [];
skaicius[0]="99";
skaicius[1]="98";
skaicius[2]="87";
skaicius[3]="89";
skaicius[4]="89";

      for(var i = 0; i < mokyklos.length; i++) {
       if(datapvz==datos[i] && mokyklapvz==mokyklos[i]) {
        if ((mokytojaspvz==mokytojaiL[i]) || (mokytojaspvz==mokytojai1[i]) || (mokytojaspvz==mokytojai2[i]) || (mokytojaspvz==mokytojai3[i]) || (mokytojaspvz==mokytojai4[i]) || (mokytojaspvz==mokytojai5[i]))
        {
         return skaicius[i]; // returns 89
        }
      }
    }

}
</code>```

答:
I think the problem is that you're comparing a Date object (from the spreadsheet...e.g., from cell F$1) with a string literal (from your saved JSON object). To make them match, you should call toJSON() on the date object before comparing, like this:

```<code>var date = data.toJSON();
for(var i = 0; i < mokyklos.length; i++) {
    if(date==datos[i] && mokykla==mokyklos[i]) {
        if ((mokytojas==mokytojaiL[i]) || (mokytojas==mokytojai1[i]) || (mokytojas==mokytojai2[i]) || (mokytojas==mokytojai3[i]) || (mokytojas==mokytojai4[i]) || (mokytojas==mokytojai5[i]))  {
            return skaicius[i];
        }
    }
}
</code>```

Body:
I have a problem debugging the code. It's working if I define values by myself instead of taking it from properties and spreadsheet. I am new to JavaScript so it can be really basic error.

What I am trying to do with this function:

Taking name of person, date and name of school from the spreadsheet

Getting arrays data from the properties that was saved with other function. The saving line in that function looks like this:

PropertiesService.getScriptProperties().setProperty('Mokyklos', JSON.stringify(Mokyklos));

It's 6 arrays of full names, array of date, array of school names and array of numbers. The numbers array is used to return the answer.

      function ApmokMokMokykloje(mokytojas, data, mokykla) {
      Utilities.sleep(Math.random() * 1000);
      var MokytojaiL = PropertiesService.getScriptProperties().getProperty('MokytojaiL');
      var Mokytojai1 = PropertiesService.getScriptProperties().getProperty('Mokytojai1');
      var Mokytojai2 = PropertiesService.getScriptProperties().getProperty('Mokytojai2');
      Utilities.sleep(Math.random() * 1000);
      var Mokytojai3 = PropertiesService.getScriptProperties().getProperty('Mokytojai3');
      var Mokytojai4 = PropertiesService.getScriptProperties().getProperty('Mokytojai4');
      var Mokytojai5 = PropertiesService.getScriptProperties().getProperty('Mokytojai5');
      Utilities.sleep(Math.random() * 1000);
      var Datos = PropertiesService.getScriptProperties().getProperty('Datos');
      var Mokyklos = PropertiesService.getScriptProperties().getProperty('Mokyklos');
      var ApmokMokSkaiciai = PropertiesService.getScriptProperties().getProperty('ApmokMokSkaiciai');

      var mokytojaiL = MokytojaiL;
      mokytojaiL = JSON.parse(mokytojaiL);

      var mokytojai1 = Mokytojai1;
      mokytojai1 = JSON.parse(mokytojai1);

      var mokytojai2 = Mokytojai2;
      mokytojai2 = JSON.parse(mokytojai2);

      var mokytojai3 = Mokytojai3;
      mokytojai3 = JSON.parse(mokytojai3);

      var mokytojai4 = Mokytojai4;
      mokytojai4 = JSON.parse(mokytojai4);

      var mokytojai5 = Mokytojai5;
      mokytojai5 = JSON.parse(mokytojai5);

      var datos = Datos;
      datos = JSON.parse(datos);

      var mokyklos = Mokyklos;
      mokyklos = JSON.parse(mokyklos);

      var skaicius = ApmokMokSkaiciai;
      skaicius = JSON.parse(skaicius);

      for(var i = 0; i < mokyklos.length; i++) {
        if(data==datos[i] && mokykla==mokyklos[i]) {
        if ((mokytojas==mokytojaiL[i]) || (mokytojas==mokytojai1[i]) || (mokytojas==mokytojai2[i]) || (mokytojas==mokytojai3[i]) || (mokytojas==mokytojai4[i]) || (mokytojas==mokytojai5[i]))  {
        return skaicius[i]; // returns blank
            }
          }
        }

    }

The code below works fine.

function testas3(mokytojas, data, mokykla) {

  // the same values from spreadsheet
  var datapvz="2017-11-04T22:00:00.000Z";
  var mokyklapvz="Zalioji mokykla";
  var mokytojaspvz="Penivilas Gremlinavičius";

  // the same values from properties
  var datos = [];
datos[0]="2017-11-08T22:00:00.000Z";
datos[1] = "2017-11-15T22:00:00.000Z";
datos[2] = "2017-11-11T22:00:00.000Z";
datos[3] = "2017-11-03T22:00:00.000Z";
datos[4] = "2017-11-04T22:00:00.000Z";
  var mokyklos = [];
mokyklos[0] = "Mokykla nuostabioji";
mokyklos[1] = "Mylimiausioji mokyklele";
mokyklos[2] = "Dar viena mokyykla";
mokyklos[3] = "Raudonoji";
mokyklos[4] = "Zalioji mokykla";
  var mokytojaiL = [];
mokytojaiL[0] = "Cristopher Rangel";
mokytojaiL[1] = "Alessandra Knox";
mokytojaiL[2] = "Germtautas Falalavičius";
mokytojaiL[3] = "Lenkgaudė Trikojytė";
mokytojaiL[4] = "Penivilas Gremlinavičius";
var mokytojai1 = [];
mokytojai1[0] = "Mantvydas Špukys";
mokytojai1[1] = "Išeikbaida Visursėkmytė";
mokytojai1[2] = "Svaidgaudė Praperduvienė";
mokytojai1[3] = "Mantvinas Žirgmyla";
mokytojai1[4] = "Mantvinas Žirgmyla";
var mokytojai2 = [];
mokytojai2[0] = "Griovbaida Nepriteklytė";
mokytojai2[1] = "Išeikbaida Visursėkmytė";
mokytojai2[2] = "Griovbaida Nepriteklytė";
mokytojai2[3] = "Arjautauta Fragmentavičiutė";
mokytojai2[4] = "Kastuvaldas Parašiutauskas";
var mokytojai3 = [];
mokytojai3[0] = "Rustautas Celiulionis";
mokytojai3[1] = "Androbauda Parankpapaitė";
mokytojai3[2] = "Arjauvilė Katrakojytė";
mokytojai3[3] = null;
mokytojai3[4] = "Rustautas Celiulionis";
var mokytojai4 = [];
mokytojai4[0] = null;
mokytojai4[1] = null;
mokytojai4[2] = null;
mokytojai4[3] = "Arjauvilė Katrakojytė";
 var mokytojai5  = [];
  var skaicius = [];
skaicius[0]="99";
skaicius[1]="98";
skaicius[2]="87";
skaicius[3]="89";
skaicius[4]="89";

      for(var i = 0; i < mokyklos.length; i++) {
       if(datapvz==datos[i] && mokyklapvz==mokyklos[i]) {
        if ((mokytojaspvz==mokytojaiL[i]) || (mokytojaspvz==mokytojai1[i]) || (mokytojaspvz==mokytojai2[i]) || (mokytojaspvz==mokytojai3[i]) || (mokytojaspvz==mokytojai4[i]) || (mokytojaspvz==mokytojai5[i]))
        {
         return skaicius[i]; // returns 89
        }
      }
    }

}

Body:
I think the problem is that you're comparing a Date object (from the spreadsheet...e.g., from cell F$1) with a string literal (from your saved JSON object). To make them match, you should call toJSON() on the date object before comparing, like this:

var date = data.toJSON();
for(var i = 0; i < mokyklos.length; i++) {
    if(date==datos[i] && mokykla==mokyklos[i]) {
        if ((mokytojas==mokytojaiL[i]) || (mokytojas==mokytojai1[i]) || (mokytojas==mokytojai2[i]) || (mokytojas==mokytojai3[i]) || (mokytojas==mokytojai4[i]) || (mokytojas==mokytojai5[i]))  {
            return skaicius[i];
        }
    }
}


问:
Validation on BigDecimals taken as input from Scanner
I'm taking in user input from the console, which needs to be a BigDecimal. How can I validate this to ensure that it is this type before trying to use it in the program?

Here's how I'm reading it in: scanner.nextBigDecimal().

答:
You can use the hasNextBigDecimal to validate before reading the value:

Returns true if the next token in this scanner's input can be
  interpreted as a BigDecimal using the nextBigDecimal() method.


答:
If you want to prevent a method from modifying any member in the class you can use the trailing const identifier:

```<code>class something{
private:
  unsigned int var;

public:
  void fun1() const;
  void fun2();
  void fun3() const;
  void fun4() const;
}
</code>```

Here, only fun2() will be able to modify the variable.

Title: C++ : How to ensure that a class member variable is modifiable only within a certain method

Body:
If you want to prevent a method from modifying any member in the class you can use the trailing const identifier:

class something{
private:
  unsigned int var;

public:
  void fun1() const;
  void fun2();
  void fun3() const;
  void fun4() const;
}

Here, only fun2() will be able to modify the variable.


问:
Python shell automatically load changes
I really love python because I love interactive development. There's one area where python appears to fall short, however, and that's in the area of automatically reloading changed files. Basically, what I want to have happen is to be able to modify a python file on-disk and then have my running python instance automatically reload the changed module to allow me to immediately access my changes in the REPL so I can test them out. Basically, I want some sort of watch command.

I happen to use the bpython shell because I think it's the best one available, but this feature is so important to me that I'd be willing to switch to any other python shell that does it right. Is it possible?

答:
Something like tail -f in python + reload().

I really think they should make the tags OS and Python version mandatory though.

Title: Python shell automatically load changes


问:
Kafka retention policyoverride
I have created my topic when the retention policy in server.properties was set to 168 hours (7 days)
then changed the retention policy to 10 days since the topic has created at the time does it inherit server.properties of 7 days has been set as a part of topic creation as topic properties,

I did not alter the topic to customize the topic.

答:
If you did not specify an override when you created the topic, it uses the current value from server.properties and every time you update the value in server.properties, the new value will be taken into account when applying the retention policies.

A quick way to double check if you have any override is to run:

./bin/kafka-topics.sh --zookeeper ZK --describe --topic TOPICNAME

Title: Kafka retention policyoverride


问:
.htaccess Redirecting Too Many Times Using Get Variables
I'm trying to redirect users from my main index page back to the index page but with a variable in the url to swap the loaded files. What I'm getting is too many redirects since I've added variables.

Here is what I've done:

```<code> RewriteCond %{TIME} <20171201000000
 RewriteCond %{REMOTE_ADDR} !^00\.000\.000\.000
 RewriteCond %{REQUEST_FILENAME} !(styles|images|javascript).+$
 RewriteCond %{REQUEST_URI} !construction.php$ [NC]
 RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif|css|ttf|woff|js) [NC]
 RewriteRule .* /construction [R=302,L]
</code>```

This part works fine and redirects. However I've added a case switch function to my index page to eliminate the construction.php page altogether. So now I've made my redirect into this and it's redirecting too much.

```<code> RewriteCond %{TIME} <20171201000000
 RewriteCond %{REMOTE_ADDR} !^00\.000\.000\.000
 RewriteCond %{REQUEST_FILENAME} !(styles|images|javascript).+$
 RewriteCond %{REQUEST_URI} !index.php?redirect=construction$ [NC]
 RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif|css|ttf|woff|js) [NC]
 RewriteRule .* /index.php?redirect=construction [R=302,L]
</code>```

The reason I am doing this is because I am going to have several redirects from construction to maintenance, 404, etc.

What would cause this to keep redirecting too much when all I did was change the urls?

Just for reference here is the entire index.php file:

```<code><?php include $_SERVER['DOCUMENT_ROOT'] . "/settings/config.php"; ?>
<body>
<?php include $_SERVER['DOCUMENT_ROOT'] . "/php/header.php"; ?>
<?php
    if (! isset($_GET['redirect']))
    {
        include($_SERVER['DOCUMENT_ROOT'].'/php/index.main.php');

    } else {
        $redirect = $_GET['redirect'];
        switch($redirect)
        {
            case 'construction':
                include($_SERVER['DOCUMENT_ROOT'].'/php/index.construction.php');
                break;
            case 'maintenance':
                include($_SERVER['DOCUMENT_ROOT'].'/php/index.maintenance.php');
                break;
        }
    }
?>
<div class="container-fluid">
<?php include $_SERVER['DOCUMENT_ROOT'] . "/php/footer.php"; ?>
</div>
</body>
</html>
</code>```

答:
You can't do that:

```<code>RewriteCond %{REQUEST_URI} !index.php?redirect=construction$ [NC]
</code>```

Because query string is not part of the test uri. Use instead:

```<code>RewriteCond %{REQUEST_URI} !index\.php$ [NC,OR]
RewriteCond %{QUERY_STRING} !redirect=(?:construction|404)$ [NC]
</code>```

You can omit the first line, If you use redirect=construction only for this page.

Body:
I'm trying to redirect users from my main index page back to the index page but with a variable in the url to swap the loaded files. What I'm getting is too many redirects since I've added variables.

Here is what I've done:

 RewriteCond %{TIME} <20171201000000
 RewriteCond %{REMOTE_ADDR} !^00\.000\.000\.000
 RewriteCond %{REQUEST_FILENAME} !(styles|images|javascript).+$
 RewriteCond %{REQUEST_URI} !construction.php$ [NC]
 RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif|css|ttf|woff|js) [NC]
 RewriteRule .* /construction [R=302,L]

This part works fine and redirects. However I've added a case switch function to my index page to eliminate the construction.php page altogether. So now I've made my redirect into this and it's redirecting too much.

 RewriteCond %{TIME} <20171201000000
 RewriteCond %{REMOTE_ADDR} !^00\.000\.000\.000
 RewriteCond %{REQUEST_FILENAME} !(styles|images|javascript).+$
 RewriteCond %{REQUEST_URI} !index.php?redirect=construction$ [NC]
 RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif|css|ttf|woff|js) [NC]
 RewriteRule .* /index.php?redirect=construction [R=302,L]

The reason I am doing this is because I am going to have several redirects from construction to maintenance, 404, etc.

What would cause this to keep redirecting too much when all I did was change the urls?

Just for reference here is the entire index.php file:

<?php include $_SERVER['DOCUMENT_ROOT'] . "/settings/config.php"; ?>

<?php include $_SERVER['DOCUMENT_ROOT'] . "/php/header.php"; ?>
<?php
    if (! isset($_GET['redirect']))
    {
        include($_SERVER['DOCUMENT_ROOT'].'/php/index.main.php');

    } else {
        $redirect = $_GET['redirect'];
        switch($redirect)
        {
            case 'construction':
                include($_SERVER['DOCUMENT_ROOT'].'/php/index.construction.php');
                break;
            case 'maintenance':
                include($_SERVER['DOCUMENT_ROOT'].'/php/index.maintenance.php');
                break;
        }
    }
?>

<?php include $_SERVER['DOCUMENT_ROOT'] . "/php/footer.php"; ?>

Body:
You can't do that:

RewriteCond %{REQUEST_URI} !index.php?redirect=construction$ [NC]

Because query string is not part of the test uri. Use instead:

RewriteCond %{REQUEST_URI} !index\.php$ [NC,OR]
RewriteCond %{QUERY_STRING} !redirect=(?:construction|404)$ [NC]

You can omit the first line, If you use redirect=construction only for this page.