问:
Kafka - consuming messages based on timestamp
I'm kind of new to Kafka but need to implement the logic for the consumer to consume from a particular topic based on timestamp. Another use case is also for me to be able to consume for a particular time range (for example from 10:00 to 10:20). The range will always be dividable by 5 minutes - meaning I won't need to consume from for example 10:00 to 10:04). The logic I was thinking would be as follows:

create a table where I store timestamp and Kafka messageId (timestamp | id)

create a console\service which does the following every 5 minutes:

Get all partitions for a topic

Query all partitions for min offset value (a starting point)

Store the offset and timestamp in the table

Get all partitions for a topic

Now if everything is alright I should have something like this in the table:

```<code>10:00     | 0
10:05     | 100
10:10     | 200
HH: mm     | (some number)
</code>```

Now having this I could start the consumer at any time and knowing the offsets I should be able to consume just what I need.
Does it look right or have I made a flaw somewhere? Or maybe there is a better way of achieving the required result? Any thoughts or suggestions would be highly appreciated.

P.S.: one of my colleagues suggested to use partition and work out with each partition separately... Meaning if I got a topic and replica count is for example 5 - then I'd need to save offsets 5 times for my topic for every interval (once per partition). And then the consumer would also need to account for the partitions and consume based on what offsets I got for each partition. But this would kind of incorporate additional complexity which I am trying to avoid...

Thanks in advance!

BR,
Mike

答:
No need for tables.

You can use the seek method of a Consumer instance to move all partitions to an offset defined by that partition.

Partitioning might work... 12 partitions of 5 minute message intervals

I don't think replication addresses your problem.

Body:
I'm kind of new to Kafka but need to implement the logic for the consumer to consume from a particular topic based on timestamp. Another use case is also for me to be able to consume for a particular time range (for example from 10:00 to 10:20). The range will always be dividable by 5 minutes - meaning I won't need to consume from for example 10:00 to 10:04). The logic I was thinking would be as follows:

create a table where I store timestamp and Kafka messageId (timestamp | id)

create a console\service which does the following every 5 minutes:

Get all partitions for a topic

Query all partitions for min offset value (a starting point)

Store the offset and timestamp in the table

Get all partitions for a topic

Now if everything is alright I should have something like this in the table:

10:00     | 0
10:05     | 100
10:10     | 200
HH: mm     | (some number)

Now having this I could start the consumer at any time and knowing the offsets I should be able to consume just what I need.
Does it look right or have I made a flaw somewhere? Or maybe there is a better way of achieving the required result? Any thoughts or suggestions would be highly appreciated.

P.S.: one of my colleagues suggested to use partition and work out with each partition separately... Meaning if I got a topic and replica count is for example 5 - then I'd need to save offsets 5 times for my topic for every interval (once per partition). And then the consumer would also need to account for the partitions and consume based on what offsets I got for each partition. But this would kind of incorporate additional complexity which I am trying to avoid...

Thanks in advance!

BR,
Mike


来源: stackexchange

问:
Printing Javascript Template Strings with Line Breaks
Is there a way to print (using console.log) javascript template strings, applying the substitutions when it's the case, but considering the linebreaks '\n' when printing?

For instance, when I have the following:

let someVar = 'a';

let tsString = `here goes ${someVar}
some other line
some other line`;

console.log(tsString);```

I'd like it to print WITH the linebreaks, not printing the \n's instead.

I think there could be some transformation between template strings and regular strings, but I could not find it.

*** EDIT: It happens on Terminal, not browser. Running a NodeJS app. Sorry for not specifying that, I assumed that what I wanted would be JS-specific, not node's (at least the solution).

答:
Another solution besides adding to the string \n, which is the standard solution is as follows:

You've got there a character for new line:

(I cannot paste that character in here as the markdown kills it)

You could capture it in a variable and insert it in a template string:

```<code>const newline = tsString[12];
const myString = `Hello ${newline} World!`;
</code>```

Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to print (using console.log) javascript template strings, applying the substitutions when it's the case, but considering the linebreaks '\n' when printing?

For instance, when I have the following:

let someVar = 'a';

let tsString = `here goes ${someVar}
some other line
some other line`;

console.log(tsString);

I'd like it to print WITH the linebreaks, not printing the \n's instead.

I think there could be some transformation between template strings and regular strings, but I could not find it.

*** EDIT: It happens on Terminal, not browser. Running a NodeJS app. Sorry for not specifying that, I assumed that what I wanted would be JS-specific, not node's (at least the solution).

Body:
Another solution besides adding to the string \n, which is the standard solution is as follows:

You've got there a character for new line:

(I cannot paste that character in here as the markdown kills it)

You could capture it in a variable and insert it in a template string:

const newline = tsString[12];
const myString = `Hello ${newline} World!`;

Hope it helps.

ContentLicense: CC BY-SA 4.0


问:
windows service exception in .NET
I will be tested the application as windows application then it will be stored the datetime in MySQL data base.When I will be start this application using windows service it will be thrown this exception.

 ```
error [HY000][MySQL][ODBC 3.51 Driver] [MySqlid -6.0.11-alpha-community]incorrect datetime value " 5/6/2011 9:00:00 AM" for column column-name at row1
 ```

Windows application take the system format & my system format is yyyy-MM-dd hh:mm:ss
in windows service which format is used.

```
query18 += "select '" + obj8 + "' as DTvalue ,'" + date8 + "' as DTdatelogged1 ,'" + OpcGroup.QualityToString(e8.sts[counter8].Quality) + "' as DTquality ,'" + DateTime.FromFileTime(e8.sts[counter8].TimeStamp) + "' as DTtimestamp ,'" + e8.sts[counter8].HandleClient + "' as DTparamID Union " + Environment.NewLine;

UpdateQuery = Update parameter t Left join + Environment.NewLine;
                    UpdateQuery8 +=  (  + query18 +  ) Temp on" + Environment.NewLine;
                    UpdateQuery8 += t.itemID=Temp.DTparamID+ Environment.NewLine;
                    UpdateQuery8 += set paramvalue=DTvalue, date_logged1=DTdatelogged1,Quality=                         DTquality,date_logged=DTtimestamp   + Environment.NewLine;
                    UpdateQuery8 += where t.groupID=9 and t.itemID=Temp.DTparamID;

```

my query likethis timestamp value is 129500892576718750 it will be convert DateTime.FromFileTime() function converted value like '2011-05-17 12:30:57' in windows application it will be write into mysql database
but in windows service converted value like 2011/05/17 12:30:57 PM it will be not accepted by the MYSQL database same thing i will be used in the windows service

now

```
UpdateQuery8 = "Update parameter " + Environment.NewLine;
                        UpdateQuery8 += "set paramvalue=@paramvalue,date_logged1=@date_logged1,Quality=@Quality,date_logged=@date_logged" + Environment.NewLine;
UpdateQuery8 += "where groupID=9 and itemID=@itemID";
                        cmd8 = new OdbcCommand(UpdateQuery8, con136);
  cmd8.Parameters.Add("@paramvalue",  obj8.ToString());
  cmd8.Parameters.Add("@date_logged1", date8);
 cmd8.Parameters.Add("@Quality", OpcGroup.QualityToString(e8.sts[counter8].Quality));
  cmd8.Parameters.Add("@date_logged", dt);
  cmd8.Parameters.Add("@itemID",e8.sts[counter8].HandleClient);
  cmd8.ExecuteNonQuery();
```

it will be execute but there no updation in database

Please help me in this regard.

Thanks in Advance.

答: Always use parametrized queries to pass data to the DB driver. Then it is up to the driver to format your dates correctly, and you avoid being susceptible to SQL-Injection attacks.</p>

Title: windows service exception in .NET

Body:
I will be tested the application as windows application then it will be stored the datetime in MySQL data base.When I will be start this application using windows service it will be thrown this exception.

error [HY000][MySQL][ODBC 3.51 Driver] [MySqlid -6.0.11-alpha-community]incorrect datetime value " 5/6/2011 9:00:00 AM" for column column-name at row1

Windows application take the system format & my system format is yyyy-MM-dd hh:mm:ss
in windows service which format is used.

query18 += "select '" + obj8 + "' as DTvalue ,'" + date8 + "' as DTdatelogged1 ,'" + OpcGroup.QualityToString(e8.sts[counter8].Quality) + "' as DTquality ,'" + DateTime.FromFileTime(e8.sts[counter8].TimeStamp) + "' as DTtimestamp ,'" + e8.sts[counter8].HandleClient + "' as DTparamID Union " + Environment.NewLine;

UpdateQuery = Update parameter t Left join + Environment.NewLine;
                    UpdateQuery8 +=  (  + query18 +  ) Temp on" + Environment.NewLine;
                    UpdateQuery8 += t.itemID=Temp.DTparamID+ Environment.NewLine;
                    UpdateQuery8 += set paramvalue=DTvalue, date_logged1=DTdatelogged1,Quality=                         DTquality,date_logged=DTtimestamp   + Environment.NewLine;
                    UpdateQuery8 += where t.groupID=9 and t.itemID=Temp.DTparamID;

my query likethis timestamp value is 129500892576718750 it will be convert DateTime.FromFileTime() function converted value like '2011-05-17 12:30:57' in windows application it will be write into mysql database
but in windows service converted value like 2011/05/17 12:30:57 PM it will be not accepted by the MYSQL database same thing i will be used in the windows service

now

UpdateQuery8 = "Update parameter " + Environment.NewLine;
                        UpdateQuery8 += "set paramvalue=@paramvalue,date_logged1=@date_logged1,Quality=@Quality,date_logged=@date_logged" + Environment.NewLine;
UpdateQuery8 += "where groupID=9 and itemID=@itemID";
                        cmd8 = new OdbcCommand(UpdateQuery8, con136);
  cmd8.Parameters.Add("@paramvalue",  obj8.ToString());
  cmd8.Parameters.Add("@date_logged1", date8);
 cmd8.Parameters.Add("@Quality", OpcGroup.QualityToString(e8.sts[counter8].Quality));
  cmd8.Parameters.Add("@date_logged", dt);
  cmd8.Parameters.Add("@itemID",e8.sts[counter8].HandleClient);
  cmd8.ExecuteNonQuery();

it will be execute but there no updation in database

Please help me in this regard.

Thanks in Advance.


问:
Spring boot ExceptionHandler when an exception is thrown within a service
I am using ControllerAdvice to handle exceptions in my spring boot application.

```<code>@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ErrorApiHandler extends ResponseEntityExceptionHandler {

    final
    ResponsesHelper rh;

    public ErrorApiHandler(ResponsesHelper rh) {
        this.rh = rh;
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseEntity<Object> handleUsernameNotFoundException(UsernameNotFoundException ex) {
    log.error(ExceptionUtils.getStackTrace(ex));

    var error = buildError(ex);
    return rh.buildResponse(error, HttpStatus.NOT_FOUND);
    }
...
}
</code>```

It works fine for exceptions thrown within my controllers.
However, with exceptions thrown, for example within a service the ControllerAdvice is not executed.

```<code>@Service
public class CustomUserDetailsService implements UserDetailsService {

    final
    UserRepository userRepository;

    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    @Transactional
    public User loadUserByUsername(String email)
            throws UsernameNotFoundException {

        log.debug(String.format("Loading user %s", email));

        User user = userRepository.findByEmail(email)
                .orElseThrow(() -> {

                    log.debug(String.format("User %s not found", email));
                    return new UsernameNotFoundException("User not found : " + email); // <- This exception is not handled.
                });

        log.debug(String.format("User %s loaded", user));
        return user;
    }
</code>```

How can I handle all exceptions thrown within my application?

Thanks in advance.

答:
I found this in ResponseEntityExceptionHandler docs:

A convenient base class for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods.

It seems that a custom exception handler that extends that class will only handle exceptions in the controller layer.

I found this tutorial - a solution that uses HandlerExceptionResolver sounds like the one you are looking for.

Body:
I am using ControllerAdvice to handle exceptions in my spring boot application.

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ErrorApiHandler extends ResponseEntityExceptionHandler {

    final
    ResponsesHelper rh;

    public ErrorApiHandler(ResponsesHelper rh) {
        this.rh = rh;
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseEntity<Object> handleUsernameNotFoundException(UsernameNotFoundException ex) {
    log.error(ExceptionUtils.getStackTrace(ex));

    var error = buildError(ex);
    return rh.buildResponse(error, HttpStatus.NOT_FOUND);
    }
...
}

It works fine for exceptions thrown within my controllers.
However, with exceptions thrown, for example within a service the ControllerAdvice is not executed.

@Service
public class CustomUserDetailsService implements UserDetailsService {

    final
    UserRepository userRepository;

    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    @Transactional
    public User loadUserByUsername(String email)
            throws UsernameNotFoundException {

        log.debug(String.format("Loading user %s", email));

        User user = userRepository.findByEmail(email)
                .orElseThrow(() -> {

                    log.debug(String.format("User %s not found", email));
                    return new UsernameNotFoundException("User not found : " + email); // <- This exception is not handled.
                });

        log.debug(String.format("User %s loaded", user));
        return user;
    }

How can I handle all exceptions thrown within my application?

Thanks in advance.


问:
App is not maintaining the state after installation - Xamarin android
Recently I noticed one thing in my app.
I created apk for my app say ABC.apk and copied to my device and installed it by clicking on it. After the installation got successfully completed, I got 2 options 'Done' and 'Open', the usual options we get after installation.
I clicked on 'Open' and run the app. I moved to some screen and I minimized the app and moved to someother app, when I click my ABC, it started from my first screen.
It was just fraction of seconds I moved back to it, hence it should not be killed though launched it like it is first time.

Few things I noticed I if I explicitly killed this first instance from background running apps and start the app again it is not giving me this problem, same if I click 'Done' instead of 'Open' it works fine.

Is there anyone who are facing same issue, or have some solution for it?

Thanks in advance.
Prajakta

答:
The problem is the way that the app gets launched from the installer doesn't exactly match the way Android launches apps from the HOME screen. Because this, if you initially launch your app from the installer, when you then later launch the app again from the HOME screen, Android doesn't recognize that the app is already running and just creates a new instance of the root Activity and adds it to the existing task on top of whatever activities are already there.

This is why, if you kill the app and start it again from the HOME screen, you won't ever see this strange behaviour.

This is a nasty Android bug which has been around since the dawn of time and is still broken, even though countless issues have been opened about it and the behaviour is reproducible and well-documented.

See the following issues and questions:

https://issuetracker.google.com/issues/36941942

https://issuetracker.google.com/issues/36907463

https://issuetracker.google.com/issues/64108432

App restarts rather than resumes

Re-launch of Activity on Home button, but...only the first time

There is a workaround documented in my answer to
Re-launch of Activity on Home button, but...only the first time


问:
URL to S3 file in private bucket
I've uploaded a file using the SDK to my private S3 bucket.

I can access this file through the S3 UI.

However, I cannot access this file through a direct link.  It gives me some XML that includes "AccessDenied" as a code and message.

It seems reasonable that since I'm authenticated in the browser and am clicking on a direct link to the file from the same browser, that I should be allowed through.  At the very least, I should be directed to a login page.

Does anyone have any experience with this?

答:
You can use the direct link if you are inside a VPC. You have to :

1- Create a VPC endpoint for Amazon S3.

2- Add a bucket policy that allows access from the VPC endpoint.

All steps are described in the following link :

https://aws.amazon.com/premiumsupport/knowledge-center/s3-private-connection-no-authentication/?nc1=h_ls

Title: URL to S3 file in private bucket


问:
Is there a way to convert a string (ASCII) to Hex in CMake
Is there a way to convert a string (ASCII "a-z, A-Z, 0-9") to Hex in CMake?

For example (ASCII to hex):

```<code>"HELLO" --> 0x48 0x45 0x4C 0x4C 0x4F
</code>```

Should be the opposite operation of the following command (see here):

```<code>string(ASCII <number> \[<number> ...\] <output variable>)
</code>```

I tried some CMake math operations, but it didn't seem to work on strings.

I can implement a function with a big "if" that compares the char input of "a-z, A-Z, 0-9" and returns its hex according to the AsciiTable, but I am looking for a smarter/shorter solution.

答:
I ended up creating this function, based on @squareskittles response:

```<code>function(STRING_HEX_KEY_TO_C_BYTE_ARRAY STRING_HEX VARIABLE_NAME)
    # Separate into individual bytes.
    string(REGEX MATCHALL "([A-Fa-f0-9][A-Fa-f0-9])" SEPARATED_HEX ${STRING_HEX})

    # Append the "0x" to each byte.
    list(JOIN SEPARATED_HEX ", 0x" FORMATTED_HEX)

    # Prepend "{ 0x"
    string(PREPEND FORMATTED_HEX "{ 0x")

    # Append " }"
    string(APPEND FORMATTED_HEX " }")

    set(${VARIABLE_NAME} ${FORMATTED_HEX} PARENT_SCOPE)
    message(${VARIABLE_NAME}=${FORMATTED_HEX})
endfunction()
</code>```

Use this function to convert string hex to C byte array, like this:

```<code>STRING_HEX_KEY_TO_C_BYTE_ARRAY("FFFF020200000030" "DEVICE_EUI")
</code>```

Output message:

```<code>DEVICE_EUI={ 0xFF, 0xFF, 0x02, 0x02, 0x00, 0x00, 0x00, 0x30 }
</code>```

Body:
Is there a way to convert a string (ASCII "a-z, A-Z, 0-9") to Hex in CMake?

For example (ASCII to hex):

"HELLO" --> 0x48 0x45 0x4C 0x4C 0x4F

Should be the opposite operation of the following command (see here):

string(ASCII <number> \[<number> ...\] <output variable>)

I tried some CMake math operations, but it didn't seem to work on strings.

I can implement a function with a big "if" that compares the char input of "a-z, A-Z, 0-9" and returns its hex according to the AsciiTable, but I am looking for a smarter/shorter solution.

Body:
I ended up creating this function, based on @squareskittles response:

function(STRING_HEX_KEY_TO_C_BYTE_ARRAY STRING_HEX VARIABLE_NAME)
    # Separate into individual bytes.
    string(REGEX MATCHALL "([A-Fa-f0-9][A-Fa-f0-9])" SEPARATED_HEX ${STRING_HEX})

    # Append the "0x" to each byte.
    list(JOIN SEPARATED_HEX ", 0x" FORMATTED_HEX)

    # Prepend "{ 0x"
    string(PREPEND FORMATTED_HEX "{ 0x")

    # Append " }"
    string(APPEND FORMATTED_HEX " }")

    set(${VARIABLE_NAME} ${FORMATTED_HEX} PARENT_SCOPE)
    message(${VARIABLE_NAME}=${FORMATTED_HEX})
endfunction()

Use this function to convert string hex to C byte array, like this:

STRING_HEX_KEY_TO_C_BYTE_ARRAY("FFFF020200000030" "DEVICE_EUI")

Output message:

DEVICE_EUI={ 0xFF, 0xFF, 0x02, 0x02, 0x00, 0x00, 0x00, 0x30 }


问:
Merge Pandas Dataframe based on boolean function
I am looking for an efficient way to merge two pandas data frames based on a function that takes as input columns from both data frames and returns True or False. E.g. Assume I have the following "tables":

```<code>import pandas as pd

df_1 = pd.DataFrame(data=[1, 2, 3])
df_2 = pd.DataFrame(data=[4, 5, 6])

def validation(a, b):
    return ((a + b) % 2) == 0
</code>```

I would like to join df1 and df2 on each row where the sum of the first column is an even number. The resulting table would be

```<code>       1 5
df_3 = 2 4
       2 6
       3 5
</code>```

Please think of it as a general problem not as a task to return just df_3. The solution should accept any function that validates a combination of columns and return True or False.

THX Lazloo

答:
You can use broadcasting, or the outer functions, to compare all rows. You'll run into issues as the length becomes large.

```<code>import pandas as pd
import numpy as np

def validation(a, b):
    """a,b : np.array"""
    arr = np.add.outer(a, b)     # How to combine rows
    i,j = np.where(arr % 2 == 0) # Condition

    return pd.DataFrame(np.stack([a[i], b[j]], axis=1))

validation(df_1[0].to_numpy(), df_2[0].to_numpy())

   0  1
0  1  5
1  2  4
2  2  6
3  3  5
</code>```

In this particular case you might leverage the fact that even numbers maintain parity when added to even numbers, and odd numbers change parity when added to odd numbers, so define that column and merge on that.

```<code>df_1['parity'] = df_1[0]%2
df_2['parity'] = df_2[0]%2

df_3 = df_1.merge(df_2, on='parity')

   0_x  parity  0_y
0    1       1    5
1    3       1    5
2    2       0    4
3    2       0    6
</code>```

Body:
I am looking for an efficient way to merge two pandas data frames based on a function that takes as input columns from both data frames and returns True or False. E.g. Assume I have the following "tables":

import pandas as pd

df_1 = pd.DataFrame(data=[1, 2, 3])
df_2 = pd.DataFrame(data=[4, 5, 6])

def validation(a, b):
    return ((a + b) % 2) == 0

I would like to join df1 and df2 on each row where the sum of the first column is an even number. The resulting table would be

       1 5
df_3 = 2 4
       2 6
       3 5

Please think of it as a general problem not as a task to return just df_3. The solution should accept any function that validates a combination of columns and return True or False.

THX Lazloo

Body:
You can use broadcasting, or the outer functions, to compare all rows. You'll run into issues as the length becomes large.

import pandas as pd
import numpy as np

def validation(a, b):
    """a,b : np.array"""
    arr = np.add.outer(a, b)     # How to combine rows
    i,j = np.where(arr % 2 == 0) # Condition

    return pd.DataFrame(np.stack([a[i], b[j]], axis=1))

validation(df_1[0].to_numpy(), df_2[0].to_numpy())

   0  1
0  1  5
1  2  4
2  2  6
3  3  5

In this particular case you might leverage the fact that even numbers maintain parity when added to even numbers, and odd numbers change parity when added to odd numbers, so define that column and merge on that.

df_1['parity'] = df_1[0]%2
df_2['parity'] = df_2[0]%2

df_3 = df_1.merge(df_2, on='parity')

   0_x  parity  0_y
0    1       1    5
1    3       1    5
2    2       0    4
3    2       0    6


问:
Vuetify Fullscreen property not creating an element with height:100%
I am still very new to the Vue.js and Vuetify frameworks. I am currently trying to create a front page element with a css property of height:100% in Vuetify, but for some reason I am unable to fill the page with the first row element.

As seen below, I am using the "fullscreen" Vuetify property in the v-row element.

Thanks!

<template>

        <v-row class="grey fullscreen" align="center" justify="space-around">
          <v-col xs=12 md=5>

Clever and
 Practical Designs.

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quo exercitationem repellat, officia consequuntur obcaecati voluptate cum voluptas placeat dolores temporibus vel ex saepe reprehenderit porro asperiores cumque distinctio accusantium optio.

              <v-row>
                <v-btn href="" class="button white--text pa-4">
                View our Products
                </v-btn>
              </v-row>
          </v-col>
          <v-col xs=12 md=5>
            <v-img contain class="homeimg" max-width="500px" src="../assets/Large_product.png"></v-img>
          </v-col>
        </v-row>

</template>```

答:
I found a solution:

Adding a style element in the App.vue file to get the fullscreen class to function properly :

<template>
  <v-app>
    <Navbar />
    <v-content>
      <router-view></router-view>
    </v-content>
  </v-app>
</template>

```

Body:
I found a solution:

Adding a style element in the App.vue file to get the fullscreen class to function properly :

<template>
  <v-app>
    <Navbar />
    <v-content>
      <router-view></router-view>
    </v-content>
  </v-app>
</template>

<script>
import Navbar from '@/components/Navbar'

export default {
  name: 'App',
  components: { Navbar },
  data: () => ({
    //
  }),
};
</script>
<style lang="scss">
.fullscreen {
  width: 100%;
  height: 100vh;
}
</style>


问:
Citrus Framework - echo action does not "echo"
I am attempting to debug/trace an integration test written with the Citrus Framework. Among the various test "actions" that can be taken, there is an echo action which is supposed to do what you might expect: echo something to the console log. The problem is: it does not echo.

When I run the integration test (via Maven failsafe plugin), errors from the test failing appear on the console, but nothing else.

What am I missing?

UPDATE:

This appears to only be a problem when running the integration tests as part of a maven build. When the test is run from eclipse, the complete console log appears.

答: I was able to figure out how to get logging to capture the Citrus integration test console output. See related issue Citrus Framework logging - how to enable/use.</p>


问:
Slow SELECT with LEFT JOIN over 4 tables
My database has 4 tables: org_addresses, org_main, zipcodes and cities.

The table org_addresses contains address data for organizations, the table org_main contains the main data for these organizations, the table zipcodes contains city zipcodes, and the table cities contains city names.

org_addresses:

```<code>| id | org_id | address_line | zipcode |
</code>```

org_main:

```<code>| id | name |
</code>```

zipcodes

```<code>| id | city_id | zipcode |
</code>```

cities

```<code>| id | name |
</code>```

In my query, I join all 4 tables using LEFT JOIN together to output complete data as a list with 1600 organizations.

As soon as I join the table zipcodes via LEFT JOIN and then join to the table cities, the request slows down to 4 seconds. Without the table zipcodes, the query takes 0.009 seconds.

```<code>SELECT a.org_id
     , a.address_line2
     , a.zipcode
     , m.name
  FROM org_addresses a
  LEFT
  JOIN org_main m
    ON a.org_id = m.id
  LEFT
  JOIN zipcodes z
    ON a.zipcode = z.zipcode
  LEFT
  JOIN cities c
    ON z.city_id = c.id
</code>```

What am I doing wrong?

答:
be sure you have proper index

on table  org_addresses composite index on columns  (org_id, zipcode)

on table  zipcodes column composite index on columns ( city_id, zipcode)

on table  cities on column (id)

Body:
My database has 4 tables: org_addresses, org_main, zipcodes and cities.

The table org_addresses contains address data for organizations, the table org_main contains the main data for these organizations, the table zipcodes contains city zipcodes, and the table cities contains city names.

org_addresses:

| id | org_id | address_line | zipcode |

org_main:

| id | name |

zipcodes

| id | city_id | zipcode |

cities

| id | name |

In my query, I join all 4 tables using LEFT JOIN together to output complete data as a list with 1600 organizations.

As soon as I join the table zipcodes via LEFT JOIN and then join to the table cities, the request slows down to 4 seconds. Without the table zipcodes, the query takes 0.009 seconds.

SELECT a.org_id
     , a.address_line2
     , a.zipcode
     , m.name
  FROM org_addresses a
  LEFT
  JOIN org_main m
    ON a.org_id = m.id
  LEFT
  JOIN zipcodes z
    ON a.zipcode = z.zipcode
  LEFT
  JOIN cities c
    ON z.city_id = c.id

What am I doing wrong?


答:
This oneliner works by splitting by 9 and mapping to integers again.

for i in range(0, len(str(aux)), 9) This will iterate over chunks of size 9.

list(map(int, aux[i,i+9])) This will map each character from string to int and create list of it. You can see map function in python for more info.

Above two steps combined in list comprehension will give you list of lists.

aux=900000001051200030000980000680740000730000908010058670008100000002007090190004060 # assumption 81 digit number or string ?
m = [list(map(int, str(aux)[i:i+9])) for i in range(0, len(str(aux)), 9)]
print(m)
```

<ul>
<li>Output</li>
</ul>

```[[9, 0, 0, 0, 0, 0, 0, 0, 1],
 [0, 5, 1, 2, 0, 0, 0, 3, 0],
 [0, 0, 0, 9, 8, 0, 0, 0, 0],
 [6, 8, 0, 7, 4, 0, 0, 0, 0],
 [7, 3, 0, 0, 0, 0, 9, 0, 8],
 [0, 1, 0, 0, 5, 8, 6, 7, 0],
 [0, 0, 8, 1, 0, 0, 0, 0, 0],
 [0, 0, 2, 0, 0, 7, 0, 9, 0],
 [1, 9, 0, 0, 0, 4, 0, 6, 0]]
```

Title: How to insert a series of numbers into a matrix?

Body:
As an example, I have a 9x9 matrix:

x=[
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
]

and I want to insert a series of numbers like the example:

aux=900000001051200030000980000680740000730000908010058670008100000002007090190004060

I want to be able to put each digit into an individual position of the matrix, but I am a little stuck on attacking this problem.

Body:
This oneliner works by splitting by 9 and mapping to integers again.

for i in range(0, len(str(aux)), 9) This will iterate over chunks of size 9.

list(map(int, aux[i,i+9])) This will map each character from string to int and create list of it. You can see map function in python for more info.

Above two steps combined in list comprehension will give you list of lists.

aux=900000001051200030000980000680740000730000908010058670008100000002007090190004060 # assumption 81 digit number or string ?
m = [list(map(int, str(aux)[i:i+9])) for i in range(0, len(str(aux)), 9)]
print(m)

Output

[[9, 0, 0, 0, 0, 0, 0, 0, 1],
 [0, 5, 1, 2, 0, 0, 0, 3, 0],
 [0, 0, 0, 9, 8, 0, 0, 0, 0],
 [6, 8, 0, 7, 4, 0, 0, 0, 0],
 [7, 3, 0, 0, 0, 0, 9, 0, 8],
 [0, 1, 0, 0, 5, 8, 6, 7, 0],
 [0, 0, 8, 1, 0, 0, 0, 0, 0],
 [0, 0, 2, 0, 0, 7, 0, 9, 0],
 [1, 9, 0, 0, 0, 4, 0, 6, 0]]


问:
What are the best options for source control integrated with visual studio (2017), small team, multiple projects?
What are your thoughts, suggestions, and recommendations for source control for the following environment?

MUST have Visual Studio integration!
Major Languages used: Visual Basic, SQL, C#
Possible other languages: Python, ASP MVC, others
Team size: small (currently 2 and probably won't change in the near future)
Organization: Not for profit, 500 employees, small IT department

答:
As of Visual Studio 2013 Update 1, Git is included in the IDE by default. https://git-scm.com/book/en/v2/Appendix-A%3A-Git-in-Other-Environments-Git-in-Visual-Studio

I've used Git on teams as small as 1 and up to 10 people and never had any real issue with it.

In my experience, version control systems come down to preference. Here is a comparison of multiple version control systems. https://en.wikipedia.org/wiki/Comparison_of_version-control_software#General_information


问:
creating orderer genesis block without cryptogen
I am currently trying to build a production hyperledger-fabric setup. Therefore I am using a CA instead of cryptogen.
My structure looks like this:

orderer

org1

peer0.org1

peer1.org1

org2

peer0.org2

peer1.org2

and I have 2 CAs (1 for every org).
I have registered and enrolled orderer, peer0.org1, peer1.org1 and Org1Admin @CA1
and peer0.org2, peer1.org2 and Org2Admin @CA2.
The orderer has ROOT_CERTS of both CAs.

But how can I create the orderer genesis block based of those MSPs?
The configtx.yaml asks for an 'MSPDir' when describing the organizations, but I don't have an MSP directory for the organization itself, I only got the MSPs of the identites. Do I have to set up a specific folder structure for this?

答:
You need to manually setup the MSP folder structure for an organization. Typically for any organization without TLS enabled and no Intermediate CA, it should have cacerts folder, admincerts folder. cacerts folder root CA certificates, admin certs hold the admin certificates for that organization.

You need to point MSPDir in configtx.yaml to this organization msp folder.


问:
Is there a way to make a multiset?
Is there a way to create a multiset in python? I have my set here:
{'a', 'u', 'i', 'o', 'e'} but I would like to have repeated characters, but still unorganised. Thanks

答:
Sure, you can use:

```<code>from multiset import *
vowels_set = Multiset('auioe')
</code>```

"A multiset is similar to the builtin set, but it allows an element to occur multiple times. It is an unordered collection of elements which have to be hashable just like in a set. It supports the same methods and operations as set does, e.g. membership test, union, intersection, and (symmetric) difference. Multisets can be used in combination with regular sets for those operations." - https://multiset.readthedocs.io/en/stable/

Title: Is there a way to make a multiset?

Body:
Sure, you can use:

from multiset import *
vowels_set = Multiset('auioe')

"A multiset is similar to the builtin set, but it allows an element to occur multiple times. It is an unordered collection of elements which have to be hashable just like in a set. It supports the same methods and operations as set does, e.g. membership test, union, intersection, and (symmetric) difference. Multisets can be used in combination with regular sets for those operations." - https://multiset.readthedocs.io/en/stable/


问:
Express passing arrays into sql (express/mssql/react)
I am trying to upload two arrays into my sql database.
This is what I have come up with.(this is my server.js using a endpoint from my client side)

My express

```<code>app.post("/post-question-answers", async (req, res) => {
  console.log("!called");
  try {
    await sql.connect(config);

    // create Request object
    var request = new sql.Request();

    let results = req.body.results;

    let questions = [];
    let answers = [];

    results.forEach(element => questions.push(element.question));
    results.forEach(element => answers.push(element.answer));

    for (var i = -1; i < results.length; i++) {
      request.input("Question", sql.VarChar, questions[i]);
      request.input("Answer", sql.VarChar, answers[i]);
      request.execute("dbo.AddQuestionResponses", function(err, recordset) {
        if (err) console.log(err);
        // send records as a response
        res.json(recordset);
      });
    }
  } catch (e) {
    console.log(e);
  }
});
</code>```

My sql stored procedrue

```<code>alter procedure AddQuestionResponses
@Question nvarchar (50),
@Answer nvarchar (50)

as

insert into QuestionResponses(QuestionWhenAnswered, QuestionResponse)
values (@Question ,@Answer )

</code>```

However this throws

```<code>RequestError: The parameter name Question has already been declared. Parameter names must be unique
</code>```

I believe this is because

```<code>  request.input("Question", sql.VarChar, questions[i]);
      request.input("Answer", sql.VarChar, answers[i]);
</code>```

need to be unique and as they are in a for loop they are repeated within the statement. Is there a way in which I can make this a valid transaction with the database and so that these are unique.

Thankyou for your time :)

答:
I solved this issue by putting

```<code>var request = new sql.Request();
</code>```

within the for loop.

Body:
I am trying to upload two arrays into my sql database.
This is what I have come up with.(this is my server.js using a endpoint from my client side)

My express

app.post("/post-question-answers", async (req, res) => {
  console.log("!called");
  try {
    await sql.connect(config);

    // create Request object
    var request = new sql.Request();

    let results = req.body.results;

    let questions = [];
    let answers = [];

    results.forEach(element => questions.push(element.question));
    results.forEach(element => answers.push(element.answer));

    for (var i = -1; i < results.length; i++) {
      request.input("Question", sql.VarChar, questions[i]);
      request.input("Answer", sql.VarChar, answers[i]);
      request.execute("dbo.AddQuestionResponses", function(err, recordset) {
        if (err) console.log(err);
        // send records as a response
        res.json(recordset);
      });
    }
  } catch (e) {
    console.log(e);
  }
});

My sql stored procedrue

alter procedure AddQuestionResponses
@Question nvarchar (50),
@Answer nvarchar (50)

as

insert into QuestionResponses(QuestionWhenAnswered, QuestionResponse)
values (@Question ,@Answer )

However this throws

RequestError: The parameter name Question has already been declared. Parameter names must be unique

I believe this is because

  request.input("Question", sql.VarChar, questions[i]);
      request.input("Answer", sql.VarChar, answers[i]);

need to be unique and as they are in a for loop they are repeated within the statement. Is there a way in which I can make this a valid transaction with the database and so that these are unique.

Thankyou for your time :)

Body:
I solved this issue by putting

var request = new sql.Request();

within the for loop.


问:
Is there a way to take text from a file and turn it into an argument for my c program?
I have a C project where the user can type in an 8 bit binary number or open up a text file with an 8 bit binary number. What I'm having trouble with is getting the 8 bit binary number from a file and making that an argument char* argv[] for my program.
This is how I'm reading the 8 bit binary number from the file

```<code>    fd = open(argv[1], O_RDONLY);
    read(fd,jString, 100);
    close(fd);
    printf("jString: %s\n", jString);

</code>```

Right now I only know how to put the 8 bit binary number into a string but what I want is to turn each 8 bit binary number input separated by spaces from the file into an argument char* argv[] for my program is this possible if so how do I do it?

Something that I already tried is this.

```<code>    fd = open(argv[1], O_RDONLY);
    read(fd,argv[1], 100);
</code>```

the problem with this is that it just reads the whole file into argv[1] and doesn't seperate them by spaces and into different arguments for my program.

答:
here your program with dynamic memory allocation:

Argument separtor = ' '

Argument from commande = your_program_name "10001010" "01010101"

Argument from file : command-line = your_program_name "...\yourfile.xyz" Example :

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

#define DELIMITER ' '

// Tokenize function
int Tokenize(char* pcLine, char ** pcListeArgs, const char* pcDelim)
{
    int iNumElet = 0;
    size_t len = 0;

    // Get line size
    int init_size = strlen(pcLine);

    char *ptr = strtok(pcLine, pcDelim);

    while(ptr != NULL)
    {
        len = strlen(ptr);
        pcListeArgs [iNumElet] = (char*) calloc (len+1, sizeof (char));
        memset(pcListeArgs [iNumElet], 0, len+1); // reset content
        memcpy (pcListeArgs [iNumElet], ptr, len); // copy data

        ptr = strtok(NULL, pcDelim);

        iNumElet ++;
    }

    return iNumElet;
}

int main(int argc, char** argv)
{
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    char ch;
    char *pcFileContent;
    char cDelim = DELIMITER;

    // Case : argument are a file
    if (argc == 2)
    {
        const char* pcFilePath = argv[1];
        fp = fopen(pcFilePath, "r");

        if (fp == NULL)
        {
            perror("Error while opening the file.\n");
            return (-1);
        }

        // Put the curso at the end of file
        fseek (fp,0, SEEK_END);

        // Get number of charactes
        len = ftell(fp);

        // Allocat memory
        pcFileContent = (char*) calloc (len+1, sizeof (char));

        //Erase content to zero
        memset(pcFileContent,'\0',len+1);

        // Put the curso at the begining of file
        fseek (fp,0, SEEK_SET);

        // Read file char by char
        unsigned int i=0;
        unsigned int iNbArgs = 1;

        while((ch = fgetc(fp)) != EOF)
        {
            if (ch == DELIMITER)
                iNbArgs ++; // We have a new arguments

            pcFileContent[i++] = ch;
        }

        char **pcListeArgs =  (char**) calloc (iNbArgs, sizeof (char*));

        iNbArgs = Tokenize (pcFileContent, pcListeArgs, &cDelim);

        // here you have all you arguments ....
        for ( i=0; i< iNbArgs; i++)
        {
            printf ("Argument %d = %s\n", i, pcListeArgs[i]);
        }

        // Free memory
        for(int i = 0; i < iNbArgs; i++)
            free(pcListeArgs[i]);

        free(pcListeArgs);
        free(pcFileContent);

    }else if ( argc > 2) // Case : argument is binary number
    {
        for ( int i=1; i< argc; i++)
        {
            printf ("Argument %d = %s\n", i, argv[i]);
        }
    }

    return 0;
}
</code>```

Result:

Argument from commande = ArgParsor.exe "10001010" "01010101" "01010111"

Argument from file : command-line = ArgParsor.exe "G:\temp.txt"

Body:
I have a C project where the user can type in an 8 bit binary number or open up a text file with an 8 bit binary number. What I'm having trouble with is getting the 8 bit binary number from a file and making that an argument char* argv[] for my program.
This is how I'm reading the 8 bit binary number from the file

    fd = open(argv[1], O_RDONLY);
    read(fd,jString, 100);
    close(fd);
    printf("jString: %s\n", jString);

Right now I only know how to put the 8 bit binary number into a string but what I want is to turn each 8 bit binary number input separated by spaces from the file into an argument char* argv[] for my program is this possible if so how do I do it?

Something that I already tried is this.

    fd = open(argv[1], O_RDONLY);
    read(fd,argv[1], 100);

the problem with this is that it just reads the whole file into argv[1] and doesn't seperate them by spaces and into different arguments for my program.

Body:
here your program with dynamic memory allocation:

Argument separtor = ' '

Argument from commande = your_program_name "10001010" "01010101"

Argument from file : command-line = your_program_name "...\yourfile.xyz" Example :

#include <malloc.h>
#include <string.h>
#include <stdio.h>

#define DELIMITER ' '

// Tokenize function
int Tokenize(char* pcLine, char ** pcListeArgs, const char* pcDelim)
{
    int iNumElet = 0;
    size_t len = 0;

    // Get line size
    int init_size = strlen(pcLine);

    char *ptr = strtok(pcLine, pcDelim);

    while(ptr != NULL)
    {
        len = strlen(ptr);
        pcListeArgs [iNumElet] = (char*) calloc (len+1, sizeof (char));
        memset(pcListeArgs [iNumElet], 0, len+1); // reset content
        memcpy (pcListeArgs [iNumElet], ptr, len); // copy data

        ptr = strtok(NULL, pcDelim);

        iNumElet ++;
    }

    return iNumElet;
}

int main(int argc, char** argv)
{
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    char ch;
    char *pcFileContent;
    char cDelim = DELIMITER;

    // Case : argument are a file
    if (argc == 2)
    {
        const char* pcFilePath = argv[1];
        fp = fopen(pcFilePath, "r");

        if (fp == NULL)
        {
            perror("Error while opening the file.\n");
            return (-1);
        }

        // Put the curso at the end of file
        fseek (fp,0, SEEK_END);

        // Get number of charactes
        len = ftell(fp);

        // Allocat memory
        pcFileContent = (char*) calloc (len+1, sizeof (char));

        //Erase content to zero
        memset(pcFileContent,'\0',len+1);

        // Put the curso at the begining of file
        fseek (fp,0, SEEK_SET);

        // Read file char by char
        unsigned int i=0;
        unsigned int iNbArgs = 1;

        while((ch = fgetc(fp)) != EOF)
        {
            if (ch == DELIMITER)
                iNbArgs ++; // We have a new arguments

            pcFileContent[i++] = ch;
        }

        char **pcListeArgs =  (char**) calloc (iNbArgs, sizeof (char*));

        iNbArgs = Tokenize (pcFileContent, pcListeArgs, &cDelim);

        // here you have all you arguments ....
        for ( i=0; i< iNbArgs; i++)
        {
            printf ("Argument %d = %s\n", i, pcListeArgs[i]);
        }

        // Free memory
        for(int i = 0; i < iNbArgs; i++)
            free(pcListeArgs[i]);

        free(pcListeArgs);
        free(pcFileContent);

    }else if ( argc > 2) // Case : argument is binary number
    {
        for ( int i=1; i< argc; i++)
        {
            printf ("Argument %d = %s\n", i, argv[i]);
        }
    }

    return 0;
}

Result:

Argument from commande = ArgParsor.exe "10001010" "01010101" "01010111"

Argument from file : command-line = ArgParsor.exe "G:\temp.txt"


问:
How to remove an line from a numpy array/table if it is empty
I have numpy arrays which are around 2000 long each, but not every element has a value. Some are blank. As you can see at the end of the code ive stacked them into one called 'match'. How would I remove a row in match if it is missing an element. So for example if a particular ID is missing the magnitude it removes the entire row. I'm only interested in keeping the rows that have data for all of the elements.</p>

```<code>from astropy.table import Table
import numpy as np

data = '/home/myname/datable.fits'
data = Table.read(data, format="fits")

ID = np.array(data['ID'])
ID.astype(str)

redshift = np.array(data['z'])
redshift.astype(float)

radius = np.array(data['r'])
radius.astype(float)

mag = np.array(data['MAG'])
mag.astype(float)

match = (ID, redshift, radius, mag)
np.stack(match, axis=1)
</code>```

答:
Here you can use the numpy.isnan method which gives true for missing values and false for existing values. But numpy.isnan can be applied to NumPy arrays of native dtype (such as np.float64).

Your requirement can be achieved as follows:

Note: considering data is your numpy array.

```<code>import numpy as np

data = np.array(some_array) # set data as your numpy array
key_col = np.array(data[:,0], dtype=np.float64) # If you want to filter based on column 0
filtered_data = data[~np.isnan(key_col)] # ~ is the logical not here
</code>```

For better flexibility, consider using pandas!!
Hope this helps!!

Body:
I have numpy arrays which are around 2000 long each, but not every element has a value. Some are blank. As you can see at the end of the code ive stacked them into one called 'match'. How would I remove a row in match if it is missing an element. So for example if a particular ID is missing the magnitude it removes the entire row. I'm only interested in keeping the rows that have data for all of the elements.

from astropy.table import Table
import numpy as np

data = '/home/myname/datable.fits'
data = Table.read(data, format="fits")

ID = np.array(data['ID'])
ID.astype(str)

redshift = np.array(data['z'])
redshift.astype(float)

radius = np.array(data['r'])
radius.astype(float)

mag = np.array(data['MAG'])
mag.astype(float)

match = (ID, redshift, radius, mag)
np.stack(match, axis=1)

Body:
Here you can use the numpy.isnan method which gives true for missing values and false for existing values. But numpy.isnan can be applied to NumPy arrays of native dtype (such as np.float64).

Your requirement can be achieved as follows:

Note: considering data is your numpy array.

import numpy as np

data = np.array(some_array) # set data as your numpy array
key_col = np.array(data[:,0], dtype=np.float64) # If you want to filter based on column 0
filtered_data = data[~np.isnan(key_col)] # ~ is the logical not here

For better flexibility, consider using pandas!!
Hope this helps!!


问:
Quality Gate Failure in SonarQube does not fail the build in Teamcity
I set up a Build project in TeamCity and integrated Sonarqube with it. The project is getting build and even publish the report successfully in SonarQube console. But when the quality gate fails, it's not breaking the build. I searched and read about the build breaker, but its already supported with Sonarqube plugin of TeamCity as this document https://confluence.jetbrains.com/display/TW/SonarQube+Integration

Am I missing something to configure/or any gotcha? I tried to search a lot but didn't find any sort of proper documentation or lead on that.

答:
I managed to fail the build based on Quality Gate settings using the sonar.qualitygate.wait=true parameter.

There's an example on their GitLab pipeline sample page: https://docs.sonarqube.org/latest/analysis/gitlab-cicd/


问:
How would you programmatically test a file for viruses?
I want to programmatically test a file for viruses.

I'm aware of this thread, which didn't get a satisfactory answer in my opinion, but I'm not looking for an API here. Any kind of workaround to make it possible to test a file would be fine.

Of course, an API would probably be the best solution (I'm using .net on a Windows platform), but maybe it's possible to drop the file in the folder, and to then check whether I can still open it or if it's been quarantined by the antivirus software.

Has someone run into the same sort of situation?

答:
Assuming you wish to integrate with whatever antivirus is already present on the system rather than bundling your own, you should check out the way Firefox 3 does this.

Bugs 103487
  and 408153
  - Inform anti-virus software when Firefox downloads an executable (using
  the Windows "IOfficeAntiVirus" and
  "IAttachmentExecute" APIs).

(of course if you wish to bundle your own, check out ClamAV/ClamWin, but then you must deal with updates, etc, and you should probably first check there is not a fully updated solution on the target system for politeness)

OwnerDisplayName: Brann

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

OwnerDisplayName: Colin Pickard


问:
load a php image using src
Is it possible to load a image using:

```<code><img src="image.php?image_id=1">
</code>```

?

for image.php:

```<code>$image_id = $_GET['image_id'];
echo "image".$image_id.".png";
</code>```

答:
You have to change the header content-type and print the contents of the image file. Here is an example for your image.php file:</p>

```<code>$image_id = $_GET['image_id'];
$filename = "image".$image_id.".png";
header('Content-Type: image/png');
print file_get_contents($filename);
</code>```

Title: load a php image using src

Body:
Is it possible to load a image using:

?

for image.php:

$image_id = $_GET['image_id'];
echo "image".$image_id.".png";

Body:
You have to change the header content-type and print the contents of the image file. Here is an example for your image.php file:

$image_id = $_GET['image_id'];
$filename = "image".$image_id.".png";
header('Content-Type: image/png');
print file_get_contents($filename);


问:
Debug Print Macro in C?
in C, what is the proper way to define a printf like macro that will print only when DEBUG symbol is defined?

```<code>#ifdef DEBUG
#define DEBUG_PRINT(???) ???
#else
#define DEBUG_PRINT(???) ???
#endif
</code>```

where ??? is where I am not sure what to fill in

答:
I like this way the best because it wont add any asm instructions to your release build. </p>

```<code>#define DEBUG
#ifdef DEBUG
#define  debug_printf(fmt, ...)  printf(fmt, __VA_ARGS__);
#else
#define debug_printf(fmt, ...)    /* Do nothing */
#endif
</code>```

Title: Debug Print Macro in C?

Body:
in C, what is the proper way to define a printf like macro that will print only when DEBUG symbol is defined?

#ifdef DEBUG
#define DEBUG_PRINT(???) ???
#else
#define DEBUG_PRINT(???) ???
#endif

where ??? is where I am not sure what to fill in

Body:
I like this way the best because it wont add any asm instructions to your release build.

#define DEBUG
#ifdef DEBUG
#define  debug_printf(fmt, ...)  printf(fmt, __VA_ARGS__);
#else
#define debug_printf(fmt, ...)    /* Do nothing */
#endif


问:
LINQ, Join, Group By and SUM
In this VB.NET query, how can I get access to the fields in the new statement?

Dim query =
    From t1 In tbl1
    Join t2 In tbl2 On t1.CAMPAIGNID Equals t2.CAMPAIGNID
    Group By t1.CAMPAIGNID Into Group
    Select New With {
     .id = CAMPAIGNID,
     .CALLS = Group.Sum(Function(a) t2.CALLS),
     .count = Group.Count(Function(a) t1.TERMCD = "Refused")
    }
```

答:
You can access the fields via the passed in parameter a. The parameter a is of the anonymous type you created via New With {...}

Dim query =
    From t1 In tbl1
    Join t2 In tbl2 On t1.CAMPAIGNID Equals t2.CAMPAIGNID
    Group By t1.CAMPAIGNID Into Group
    Select New With {
        .id = CAMPAIGNID,
        .CALLS = Group.Sum(Function(a) a.t2.CALLS),
        .count = Group.Count(Function(a) a.t1.TERMCD = "Refused")
    }
```

Title: LINQ, Join, Group By and SUM


问:
How to count the number of cells which contain specific text using Google Sheet Scripts?
How to count the number of cells which contain specific text using Google sheet scripts?

Currently I'am using the following script to count the number of cells which contain specific text, for example cells which contain: 'Complete' or 'Not Complete'.

```<code>function COUNT_TEXT_ACROSS_SHEETS(sheetNames, range, text) {
  sheetNames = sheetNames.split(',');
  var count = 0;
  sheetNames.forEach(function(sheetName) {
    var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
    var values = sheet.getRange(range).getValues();
    values.forEach(function(row) {
      row.forEach(function(cell) {
        if (cell.indexOf(text) !== -1 ) count++;
      });
    });
  });
  return count;
};
</code>```

Currently the script counts both cells which contain the text 'Complete' and 'Not Complete' is there a way to modify the script to only count cells which contain the full word 'Complete' instead of also counting cells which contain 'Not Complete' because the cell also contains the keyword: 'Complete'?

Example usage of the current script:

```<code>=COUNT_TEXT_ACROSS_SHEETS("Sheet1", "C1:C1000", "NOT COMPLETE")
</code>```

Body:
How to count the number of cells which contain specific text using Google sheet scripts?

Currently I'am using the following script to count the number of cells which contain specific text, for example cells which contain: 'Complete' or 'Not Complete'.

function COUNT_TEXT_ACROSS_SHEETS(sheetNames, range, text) {
  sheetNames = sheetNames.split(',');
  var count = 0;
  sheetNames.forEach(function(sheetName) {
    var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
    var values = sheet.getRange(range).getValues();
    values.forEach(function(row) {
      row.forEach(function(cell) {
        if (cell.indexOf(text) !== -1 ) count++;
      });
    });
  });
  return count;
};

Currently the script counts both cells which contain the text 'Complete' and 'Not Complete' is there a way to modify the script to only count cells which contain the full word 'Complete' instead of also counting cells which contain 'Not Complete' because the cell also contains the keyword: 'Complete'?

Example usage of the current script:

=COUNT_TEXT_ACROSS_SHEETS("Sheet1", "C1:C1000", "NOT COMPLETE")

Body: =COUNTIF(Sheet1!C1:C1000;"=NOT COMPLETE")


问:
Woocommerce: Order items not showing in order email
All my orders are created with the on-hold state by default until payment is confirmed and then the state turns to processing. I created a hook to send the on-hold email every time a new order is created to ensure every user will receive an email once the order is created.

```<code>//Force on-hold email notification bug workaround
add_action('woocommerce_new_order', 'new_order_on_hold_notification', 30, 1 );
function new_order_on_hold_notification( $order_id ) {
    //global $woocommerce;
    //$mailer = $woocommerce->mailer();
    $order = wc_get_order( $order_id );

    // Send Customer On-Hold Order notification
    WC()->mailer()->get_emails()['WC_Email_Customer_On_Hold_Order']->trigger( $order_id );
}
</code>```

The email is being sent, but for some reason, the order items are not being included in the email, this is weird since the rest of the emails woocommerce sends (upon order completion, shipped and delivered states) are correctly sent with order items.

UPDATE
As requested I attach the customer-on-hold-order.php template Im using in my theme, it's basically the same as the default woocommerce template just added an image at the top of the email.

```<code><?php
/**
 * Customer on-hold order email
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/emails/customer-on-hold-order.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce/Templates/Emails
 * @version 3.7.0
 */

defined( 'ABSPATH' ) || exit;

/*
 * @hooked WC_Emails::email_header() Output the email header
 */
do_action( 'woocommerce_email_header', $email_heading, $email ); ?>

<!--[if gte MSO 9]>
  <table width="640">
     <tr>
        <td>
<![endif]-->
  <table width="100%" style="max-width:640px;">
    <tr>
      <td>
        <img src="https://ebani.com.co/wp-content/themes/martfury-child/woocommerce/emails/images/pedido-en-espera.jpg" width="100%" />
      </td>
    </tr>
  </table>
<!--[if gte MSO 9]>
      </td>
    </tr>
  </table>
<![endif]-->

<?php /* translators: %s: Customer first name */ ?>
<p><?php printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $order->get_billing_first_name() ) ); ?></p>
<p><?php esc_html_e( 'Thanks for your order. It’s on-hold until we confirm that payment has been received. In the meantime, here’s a reminder of what you ordered:', 'woocommerce' ); ?></p>

<?php

/*
 * @hooked WC_Emails::order_details() Shows the order details table.
 * @hooked WC_Structured_Data::generate_order_data() Generates structured data.
 * @hooked WC_Structured_Data::output_structured_data() Outputs structured data.
 * @since 2.5.0
 */
do_action( 'woocommerce_email_order_details', $order, $sent_to_admin, $plain_text, $email );

/*
 * @hooked WC_Emails::order_meta() Shows order meta data.
 */
do_action( 'woocommerce_email_order_meta', $order, $sent_to_admin, $plain_text, $email );

/*
 * @hooked WC_Emails::customer_details() Shows customer details
 * @hooked WC_Emails::email_address() Shows email address
 */
do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email );

/**
 * Show user-defined additional content - this is set in each email's settings.
 */
if ( $additional_content ) {
    echo wp_kses_post( wpautop( wptexturize( $additional_content ) ) );
}

/*
 * @hooked WC_Emails::email_footer() Output the email footer
 */
do_action( 'woocommerce_email_footer', $email );
</code>```

Update #2
After debugging the email-order-items.php template I found that the $items array is empty however this is weird as I told you all other emails are correct with the order items.

答:
Finally, I found the root of the issue thanks to this question, it seems when woocommerce_new_order
 is called the order is not yet fully populated, that's why in the notification email the order items array is empty. using woocommerce_checkout_order_processed instead made the trick!

```<code>add_action('woocommerce_checkout_order_processed', 'new_order_on_hold_notification');
    function new_order_on_hold_notification( $order_id ) {
                    $order = wc_get_order( $order_id );

                    // Only for on hold new orders
                    if( ! $order->has_status('on-hold') )
                        return; // Exit

                    // Send Customer On-Hold Order notification
                    WC()->mailer()->get_emails()['WC_Email_Customer_On_Hold_Order']->trigger( $order_id );
     }
</code>```

Body:
All my orders are created with the on-hold state by default until payment is confirmed and then the state turns to processing. I created a hook to send the on-hold email every time a new order is created to ensure every user will receive an email once the order is created.

//Force on-hold email notification bug workaround
add_action('woocommerce_new_order', 'new_order_on_hold_notification', 30, 1 );
function new_order_on_hold_notification( $order_id ) {
    //global $woocommerce;
    //$mailer = $woocommerce->mailer();
    $order = wc_get_order( $order_id );

    // Send Customer On-Hold Order notification
    WC()->mailer()->get_emails()['WC_Email_Customer_On_Hold_Order']->trigger( $order_id );
}

The email is being sent, but for some reason, the order items are not being included in the email, this is weird since the rest of the emails woocommerce sends (upon order completion, shipped and delivered states) are correctly sent with order items.

UPDATE
As requested I attach the customer-on-hold-order.php template Im using in my theme, it's basically the same as the default woocommerce template just added an image at the top of the email.

<?php
/**
 * Customer on-hold order email
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/emails/customer-on-hold-order.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce/Templates/Emails
 * @version 3.7.0
 */

defined( 'ABSPATH' ) || exit;

/*
 * @hooked WC_Emails::email_header() Output the email header
 */
do_action( 'woocommerce_email_header', $email_heading, $email ); ?>

<?php /* translators: %s: Customer first name */ ?>

<?php printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $order->get_billing_first_name() ) ); ?>

<?php esc_html_e( 'Thanks for your order. It’s on-hold until we confirm that payment has been received. In the meantime, here’s a reminder of what you ordered:', 'woocommerce' ); ?>

<?php

/*
 * @hooked WC_Emails::order_details() Shows the order details table.
 * @hooked WC_Structured_Data::generate_order_data() Generates structured data.
 * @hooked WC_Structured_Data::output_structured_data() Outputs structured data.
 * @since 2.5.0
 */
do_action( 'woocommerce_email_order_details', $order, $sent_to_admin, $plain_text, $email );

/*
 * @hooked WC_Emails::order_meta() Shows order meta data.
 */
do_action( 'woocommerce_email_order_meta', $order, $sent_to_admin, $plain_text, $email );

/*
 * @hooked WC_Emails::customer_details() Shows customer details
 * @hooked WC_Emails::email_address() Shows email address
 */
do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email );

/**
 * Show user-defined additional content - this is set in each email's settings.
 */
if ( $additional_content ) {
    echo wp_kses_post( wpautop( wptexturize( $additional_content ) ) );
}

/*
 * @hooked WC_Emails::email_footer() Output the email footer
 */
do_action( 'woocommerce_email_footer', $email );

Update #2
After debugging the email-order-items.php template I found that the $items array is empty however this is weird as I told you all other emails are correct with the order items.

Body:
Finally, I found the root of the issue thanks to this question, it seems when woocommerce_new_order
 is called the order is not yet fully populated, that's why in the notification email the order items array is empty. using woocommerce_checkout_order_processed instead made the trick!

add_action('woocommerce_checkout_order_processed', 'new_order_on_hold_notification');
    function new_order_on_hold_notification( $order_id ) {
                    $order = wc_get_order( $order_id );

                    // Only for on hold new orders
                    if( ! $order->has_status('on-hold') )
                        return; // Exit

                    // Send Customer On-Hold Order notification
                    WC()->mailer()->get_emails()['WC_Email_Customer_On_Hold_Order']->trigger( $order_id );
     }


问:
Data Preparation End OF Every Month - Moving Over 12 Months
I have data prep procedure in SQL. I want to have data preparation at the end of every month
 Say I want the procedure run on last day of month e.g. on 31 January 2020 it should prep data from 1 January to 31 January.

So it's kind of moving window over all months of the year. Because I need data for evaluation at the end of each month.

I tried this, however, this does not give automation. Its sort of manual running end of every month

```<code>select '2020-10-01' as beginDate_AnalysisWindow
, '2020 -01-31' as endDate_AnalysisWindow
   into #AnalysisWindow --create temporary table #AnalysisWindow
</code>```

I also tried the following, however, I’m not sure if it does for the whole month or just one day?

```<code>SELECT START_OF_MONTH_DATE AS beginDate_AnalysisWindow
,END_OF_MONTH_DATE AS endDate_AnalysisWindow
INTO #AnalysisWindow
FROM [dbo].[Date] WITH (NOLOCK)
WHERE DATE = DATEADD(dd, - 1,  CAST(GETDATE() AS DATE))
</code>```

Could someone pls help me/give me some suggestions.

Thanks in advance

答:
You can also try:

```<code>where getdate() <= EOMONTH(GETDATE()) AND
      getdate() > DATEADD(DAY, 1, EOMONTH(GETDATE(), -1))
</code>```

Instead of getdate(), you can use your date column.

Body:
I have data prep procedure in SQL. I want to have data preparation at the end of every month
 Say I want the procedure run on last day of month e.g. on 31 January 2020 it should prep data from 1 January to 31 January.

So it's kind of moving window over all months of the year. Because I need data for evaluation at the end of each month.

I tried this, however, this does not give automation. Its sort of manual running end of every month

select '2020-10-01' as beginDate_AnalysisWindow
, '2020 -01-31' as endDate_AnalysisWindow
   into #AnalysisWindow --create temporary table #AnalysisWindow

I also tried the following, however, I’m not sure if it does for the whole month or just one day?

SELECT START_OF_MONTH_DATE AS beginDate_AnalysisWindow
,END_OF_MONTH_DATE AS endDate_AnalysisWindow
INTO #AnalysisWindow
FROM [dbo].[Date] WITH (NOLOCK)
WHERE DATE = DATEADD(dd, - 1,  CAST(GETDATE() AS DATE))

Could someone pls help me/give me some suggestions.

Thanks in advance

Body:
You can also try:

where getdate() <= EOMONTH(GETDATE()) AND
      getdate() > DATEADD(DAY, 1, EOMONTH(GETDATE(), -1))

Instead of getdate(), you can use your date column.


问:
TypeScript method in parent class access Type in subclass
I have one class:

```<code>export class DataAccess {
  tableName: string;
  constructor({ tableName }: { tableName: string }) {
    this.tableName = tableName;
  }
  async getWhere(where: any, { single = false } = {}) {
    const options: { limit?: number } = {};
    if (single) {
      options.limit = 1;
    }
    const results = await someDBobj[this.tableName].find(where, options);
    if (!single) {
      return results;
    }
    return results.length ? results[0] : null;
  }
}
</code>```

And a subclass:

```<code>import { DataAccess } from "./data-access";

type UsersTable = {
  id: string;
  email: string;
  password: string;
  createdAt: Date;
};

export default class Users extends DataAccess {
  columns: { [P in keyof UsersTable]: string };
  constructor() {
    super({
      tableName: "users"
    });
    this.columns = {
      id: "id",
      email: "email",
      password: "password",
      createdAt: "createdAt"
    };
  }
}
</code>```

And using the Users class:

```<code>await users.getWhere(
  {
    email: user,
    password
  },
  {
    single: true
  }
);
</code>```

How can I set the Type of where: any in the parent DataAccess Class, so it knows that its the Users subclass that's called it?

答:
You can use generic class

export class DataAccess<T> {
  columns: { [P in keyof T]: string };
  tableName: string;
  constructor({ tableName }: { tableName: string }) {
    this.tableName = tableName;
  }
  async getWhere(where: Partial<T>, { single = false } = {}) {
    const options: { limit?: number } = {};
    if (single) {
      options.limit = 1;
    }
    const results = await someDBobj[this.tableName].find(where, options);
    if (!single) {
      return results;
    }
    return results.length ? results[0] : null;
  }
}

```

<pre class="lang-js prettyprint-override"><code>import { DataAccess } from "./data-access";

type UsersTable = {
  id: string;
  email: string;
  password: string;
  createdAt: Date;
};

export default class Users extends DataAccess<UsersTable > {
  constructor() {
    super({
      tableName: "users"
    });
    this.columns = {
      id: "id",
      email: "email",
      password: "password",
      createdAt: "createdAt"
    };
  }
}

</code>```

Body:
I have one class:

export class DataAccess {
  tableName: string;
  constructor({ tableName }: { tableName: string }) {
    this.tableName = tableName;
  }
  async getWhere(where: any, { single = false } = {}) {
    const options: { limit?: number } = {};
    if (single) {
      options.limit = 1;
    }
    const results = await someDBobj[this.tableName].find(where, options);
    if (!single) {
      return results;
    }
    return results.length ? results[0] : null;
  }
}

And a subclass:

import { DataAccess } from "./data-access";

type UsersTable = {
  id: string;
  email: string;
  password: string;
  createdAt: Date;
};

export default class Users extends DataAccess {
  columns: { [P in keyof UsersTable]: string };
  constructor() {
    super({
      tableName: "users"
    });
    this.columns = {
      id: "id",
      email: "email",
      password: "password",
      createdAt: "createdAt"
    };
  }
}

And using the Users class:

await users.getWhere(
  {
    email: user,
    password
  },
  {
    single: true
  }
);

How can I set the Type of where: any in the parent DataAccess Class, so it knows that its the Users subclass that's called it?

Body:
You can use generic class

export class DataAccess<T> {
  columns: { [P in keyof T]: string };
  tableName: string;
  constructor({ tableName }: { tableName: string }) {
    this.tableName = tableName;
  }
  async getWhere(where: Partial<T>, { single = false } = {}) {
    const options: { limit?: number } = {};
    if (single) {
      options.limit = 1;
    }
    const results = await someDBobj[this.tableName].find(where, options);
    if (!single) {
      return results;
    }
    return results.length ? results[0] : null;
  }
}

import { DataAccess } from "./data-access";

type UsersTable = {
  id: string;
  email: string;
  password: string;
  createdAt: Date;
};

export default class Users extends DataAccess<UsersTable > {
  constructor() {
    super({
      tableName: "users"
    });
    this.columns = {
      id: "id",
      email: "email",
      password: "password",
      createdAt: "createdAt"
    };
  }
}


问:
mailto with no default email client
A friend has developed a corporate website which has a mailto link as the 'contact us' link.  The problem is that if windows has no default email client it does not work, there isn't even an error message.  I was going to suggest changing it to a link through to a contact page with perhaps an email form but can anyone suggest anything quicker/simpler?

```<code>mailto:email@company.com?subject= enquiry
</code>```

Cheers,
Cap

答: There isn't anything quicker. You can, however, make sure the link text is the email address to facilitiate copy/paste into a webmail client.</p>

Title: mailto with no default email client

Body:
A friend has developed a corporate website which has a mailto link as the 'contact us' link.  The problem is that if windows has no default email client it does not work, there isn't even an error message.  I was going to suggest changing it to a link through to a contact page with perhaps an email form but can anyone suggest anything quicker/simpler?

mailto:email@company.com?subject= enquiry

Cheers,
Cap


问:
C++ Lua userdata messing with Mathfu float values
I'm trying to use Mathfu::Vector from Lua to create vectors but I've got an issue when I try to retrieve the user data back from the stack.

here is the function I use to define the user data

static int vec4(lua_State *L)
{
  const float x = luaL_checknumber(L, 1);
  const float y = luaL_checknumber(L, 2);
  const float z = luaL_checknumber(L, 3);
  const float w = luaL_checknumber(L, 4);

  mathfu::Vector<float, 4> vec(x, y, z, w);
  *static_cast<mathfu::Vector<float, 4> **>(
      lua_newuserdata(L, sizeof(mathfu::Vector<float, 4> *))) = &vec;
  luaL_setmetatable(L, VECTOR_LIB_NAME);

  return 1;
}
```

<p>And I have a function that gets the dot product of two vectors based on a <code>self</code> value and an argument (both userdata)</p>

<pre class="lang-cpp prettyprint-override"><code>static int dotVector(lua_State *L)
{
  mathfu::Vector<float, 4> *vecA = *static_cast<mathfu::Vector<float, 4> **>(luaL_checkudata(L, 1, VECTOR_LIB_NAME));
  mathfu::Vector<float, 4> *vecB = *static_cast<mathfu::Vector<float, 4> **>(luaL_checkudata(L, 2, VECTOR_LIB_NAME));

  LOGI("A: %f, %f, %f", vecA->x, vecA->y, vecA->z);
  LOGI("B: %f, %f, %f", vecB->x, vecB->y, vecB->z);
  float dot = mathfu::Vector<float, 4>::DotProduct(*vecA, *vecB);
  lua_pushnumber(L, dot);

  return 1;
};
</code>```

called from lua like

local vecA = vec4(1, 2, 3, 4)
local vecB = vec4(5, 6, 7, 8)
vecA:dot(vecB)
```

<p>But the values that get printed are crazy like it's converting bad data to a float</p>

```A: -8055257885499399810754615288266752.000000, 0.000000, 0.000000
B: 0.000000, 3746318080.000000, 3573.204346
```

I've examined the stack and the first two elements are definitely UserData but I don't seem to be able to dig any deeper into the user data. The vars in C++ contain those values but I'm at a loss as to what might be causing this. Pretty sure the userdata isn't what I expect it to be where I expect it to be.

答:
This turned out to be something silly in the end, taking the reference with & appears to be the incorrect way to get a pointer to an object. I changed my vector init code to

static int vec4(lua_State *L)
{
  const float x = luaL_checknumber(L, 1);
  const float y = luaL_checknumber(L, 2);
  const float z = luaL_checknumber(L, 3);
  const float w = luaL_checknumber(L, 4);

  *static_cast<mathfu::Vector<float, 4> **>(
      lua_newuserdata(L, sizeof(mathfu::Vector<float, 4> *))) = new mathfu::Vector<float, 4>(x, y, z, w);;
  luaL_setmetatable(L, VECTOR_LIB_NAME);

  return 1;
}
```

And it all works, I assume that because when I use new it gives me an "actual" pointer address instead of a reference? Live and learn.

Body:
I'm trying to use Mathfu::Vector from Lua to create vectors but I've got an issue when I try to retrieve the user data back from the stack.

here is the function I use to define the user data

static int vec4(lua_State *L)
{
  const float x = luaL_checknumber(L, 1);
  const float y = luaL_checknumber(L, 2);
  const float z = luaL_checknumber(L, 3);
  const float w = luaL_checknumber(L, 4);

  mathfu::Vector<float, 4> vec(x, y, z, w);
  *static_cast<mathfu::Vector<float, 4> **>(
      lua_newuserdata(L, sizeof(mathfu::Vector<float, 4> *))) = &vec;
  luaL_setmetatable(L, VECTOR_LIB_NAME);

  return 1;
}

And I have a function that gets the dot product of two vectors based on a self value and an argument (both userdata)

static int dotVector(lua_State *L)
{
  mathfu::Vector<float, 4> *vecA = *static_cast<mathfu::Vector<float, 4> **>(luaL_checkudata(L, 1, VECTOR_LIB_NAME));
  mathfu::Vector<float, 4> *vecB = *static_cast<mathfu::Vector<float, 4> **>(luaL_checkudata(L, 2, VECTOR_LIB_NAME));

  LOGI("A: %f, %f, %f", vecA->x, vecA->y, vecA->z);
  LOGI("B: %f, %f, %f", vecB->x, vecB->y, vecB->z);
  float dot = mathfu::Vector<float, 4>::DotProduct(*vecA, *vecB);
  lua_pushnumber(L, dot);

  return 1;
};

called from lua like

local vecA = vec4(1, 2, 3, 4)
local vecB = vec4(5, 6, 7, 8)
vecA:dot(vecB)

But the values that get printed are crazy like it's converting bad data to a float

A: -8055257885499399810754615288266752.000000, 0.000000, 0.000000
B: 0.000000, 3746318080.000000, 3573.204346

I've examined the stack and the first two elements are definitely UserData but I don't seem to be able to dig any deeper into the user data. The vars in C++ contain those values but I'm at a loss as to what might be causing this. Pretty sure the userdata isn't what I expect it to be where I expect it to be.

Body:
This turned out to be something silly in the end, taking the reference with & appears to be the incorrect way to get a pointer to an object. I changed my vector init code to

static int vec4(lua_State *L)
{
  const float x = luaL_checknumber(L, 1);
  const float y = luaL_checknumber(L, 2);
  const float z = luaL_checknumber(L, 3);
  const float w = luaL_checknumber(L, 4);

  *static_cast<mathfu::Vector<float, 4> **>(
      lua_newuserdata(L, sizeof(mathfu::Vector<float, 4> *))) = new mathfu::Vector<float, 4>(x, y, z, w);;
  luaL_setmetatable(L, VECTOR_LIB_NAME);

  return 1;
}

And it all works, I assume that because when I use new it gives me an "actual" pointer address instead of a reference? Live and learn.


问:
Get the all GET requests for a time range by the grep from the logs
How can I get all GET requests for the some time range from the log file?
As an example here is the record from log:

```<code>41.201.181.27 - [2019-04-06 18:20:13] "GET /popup.php?choix=2 HTTP/1.1" 200 1692 "http://example.com/popup.php?choix=1" "Mozilla/4.0" "-"
</code>```

I need extract all GET records for the 17th February from the 14:00 to 23:00

答:
With grep you can filter for the timestamp part of the date field. Something like this

grep -E '2019-02-17 (1[4-9]|2[0-2]|23:00)'
```

This will match the first and the last line as well so you have all the lines from the last second as well

Body:
How can I get all GET requests for the some time range from the log file?
As an example here is the record from log:

41.201.181.27 - [2019-04-06 18:20:13] "GET /popup.php?choix=2 HTTP/1.1" 200 1692 "http://example.com/popup.php?choix=1" "Mozilla/4.0" "-"

I need extract all GET records for the 17th February from the 14:00 to 23:00

Body:
With grep you can filter for the timestamp part of the date field. Something like this

grep -E '2019-02-17 (1[4-9]|2[0-2]|23:00)'

This will match the first and the last line as well so you have all the lines from the last second as well


问:
Elasticsearch limit result like Google
I'm having an issue finding the best approach to the following elastic search. I have data as below:

```<code>{product: "A", sellerID: "1"},
{product: "B", sellerID: "2"},
{product: "C", sellerID: "2"},
{product: "D", sellerID: “2”},
{product: "E", sellerID: “1"},
{product: "F", sellerID: "3"}
</code>```

I'd like to be able to return the results:

```<code>{product: "A", sellerID: "1"},
{product: "B", sellerID: "2"},
{product: "C", sellerID: “2"},
{product: "E", sellerID: "1"},
{product: "F", sellerID: "3"}
</code>```

Like google search, each domain is only displayed a maximum of 2 times in each results page. Each page will have 10 products and each sellerID will only be shown up to 2 of their products. Go to pages 2,3, ... the rules are still the same, that means an sellerID has 2 products displayed on page 1, then on page 2 they can still have 2 products displayed.

答: You may be looking for top_hits agg. Please see my answer to this question: ElasticSearch: query for N items of each category</p>

Title: Elasticsearch limit result like Google

Body:
I'm having an issue finding the best approach to the following elastic search. I have data as below:

{product: "A", sellerID: "1"},
{product: "B", sellerID: "2"},
{product: "C", sellerID: "2"},
{product: "D", sellerID: “2”},
{product: "E", sellerID: “1"},
{product: "F", sellerID: "3"}

I'd like to be able to return the results:

{product: "A", sellerID: "1"},
{product: "B", sellerID: "2"},
{product: "C", sellerID: “2"},
{product: "E", sellerID: "1"},
{product: "F", sellerID: "3"}

Like google search, each domain is only displayed a maximum of 2 times in each results page. Each page will have 10 products and each sellerID will only be shown up to 2 of their products. Go to pages 2,3, ... the rules are still the same, that means an sellerID has 2 products displayed on page 1, then on page 2 they can still have 2 products displayed.


问:
How to ignore NULL values Sorting in Angular Material Table
I am adding a row into table, in order to add a new record and i want to keep that row at top regardless the sort header (asc, desc or none).

When no order or asc is defined the row is at top but when desc order is clicked the row goes to bottom.

Any ideas on how to keep null values (new row object in data source has null values for column sort) always at top?

Order None is OK:
https://i.stack.imgur.com/J3Ou1.png

Order Asc is OK too:
https://i.stack.imgur.com/xFolC.png

But Order Desc IS NOT ok:
https://i.stack.imgur.com/bsksj.png

答:
When the value is null, you can 'replace' it by a character that sorts after Z, for example omega (Ω), by overwriting the sorting mechanism.

```<code>this.dataSource.sortingDataAccessor = (item, key) => item[key] || 'Ω';
</code>```

The sorting mechanism will return the key/value pair, but when no value is found, it will return the omega character, but for sorting only, so it won't show up in your table.

Body:
When the value is null, you can 'replace' it by a character that sorts after Z, for example omega (Ω), by overwriting the sorting mechanism.

this.dataSource.sortingDataAccessor = (item, key) => item[key] || 'Ω';

The sorting mechanism will return the key/value pair, but when no value is found, it will return the omega character, but for sorting only, so it won't show up in your table.


问:
How can I fetch data from an HTTPS Url via Proxy?
I am getting Connection timed out: connect.

My code:

```<code>    System.setProperty("http.proxyHost", "proxy.mycompany.com");
    System.setProperty("http.proxyPort", "8080");

    String url = URL_BASE + "&limit=5";
    URL u = new URL(url);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
            u.openStream()));

    String inputLine;

    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

    in.close();
</code>```

答:
If you're fetching a URL on HTTPS, then you must set https.proxyHost and https.proxyPort. See documentation on Java Networking and Proxies, section 2.2.

```<code>System.setProperty("https.proxyHost", "proxy.mycompany.com");
System.setProperty("https.proxyPort", "8080");
</code>```

assuming that proxy.mycompany.com on port 8080 is also an HTTPS proxy

Body:
I am getting Connection timed out: connect.

My code:

    System.setProperty("http.proxyHost", "proxy.mycompany.com");
    System.setProperty("http.proxyPort", "8080");

    String url = URL_BASE + "&limit=5";
    URL u = new URL(url);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
            u.openStream()));

    String inputLine;

    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

    in.close();

Body:
If you're fetching a URL on HTTPS, then you must set https.proxyHost and https.proxyPort. See documentation on Java Networking and Proxies, section 2.2.

System.setProperty("https.proxyHost", "proxy.mycompany.com");
System.setProperty("https.proxyPort", "8080");

assuming that proxy.mycompany.com on port 8080 is also an HTTPS proxy


问:
Tab panes losing width in Bootstrap 4
I've created tabbed content in my project with three tabs. For each tab pane, the pane loses width. For example the first tab pane is the full 100% width, however each pane onwards loses 100-200px consecutively.

For example:

The first pane is 1140px (full width of the container)

The second pane is: 1004px width

The third pane is: 794px width

I've checked for missing divs and I don't believe the use of rows and columns within the tab panes is the cause of the issue. I've also tried setting width: 100% to the tab panes with no luck.

I can't understand why this is happening.

```<code><section class="home-office-types">
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <ul class="nav nav-tabs home-office-types__tabs" id="myTab" role="tablist">
          <li class="nav-item home-office-types__tab">
            <a class="nav-link home-office-types__tab-link active" id="managed-offices-tab" data-toggle="tab" href="#managed-offices" role="tab"
              aria-controls="managed-offices" aria-selected="true">Serviced & managed offices</a>
          </li>
          <li class="nav-item home-office-types__tab">
            <a class="nav-link home-office-types__tab-link" id="meeting-rooms-tab" data-toggle="tab" href="#meeting-rooms" role="tab"
              aria-controls="meeting-rooms" aria-selected="true">Meeting Rooms</a>
          </li>
          <li class="nav-item home-office-types__tab">
            <a class="nav-link home-office-types__tab-link" id="virtual-offices-tab" data-toggle="tab" href="#virtual-offices" role="tab"
              aria-controls="virtual-offices" aria-selected="true">Virtual Offices</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="row">
      <div class="tab-content home-office-types__content" id="myTabContent">
        <div class="tab-pane fade show active" id="managed-offices" role="tabpanel"
          aria-labelledby="managed-offices-tab">
          <div class="row">
            <div class="col-lg-7 d-flex justify-content-start">
              <ul>
                <li>State of the art internet & phone packages</li>
                <li>Fully furnished and ready for you to move in and make your home</li>
                <li>No hidden costs - your monthly fee covers everything from all your utilities to cleaning</li>
                <li>Great value and truly affordable prices</li>
                <li>No long contracts - choose from a few days to as long as you want giving you total control of your business’ finances</li>
              </ul>
            </div>
            <div class="col-lg-5 d-flex justify-content-end">
              <img class="home-office-types__image img-fluid" src="https://placehold.co/304x304" alt="">
            </div>
          </div>
        </div>
        <div class="tab-pane fade" id="meeting-rooms" role="tabpanel" aria-labelledby="meeting-rooms-tab">
          <div class="row">
            <div class="col-lg-7 d-flex justify-content-start">
              <ul>
                <li>State of the art internet & phone packages</li>
                <li>Fully furnished and ready for you to move in and make your home</li>
              </ul>
            </div>
            <div class="col-lg-5 d-flex justify-content-end">
              <img class="home-office-types__image img-fluid" src="https://placehold.co/304x304" alt="">
            </div>
          </div>
        </div>
        <div class="tab-pane fade" id="virtual-offices" role="tabpanel" aria-labelledby="virtual-offices-tab">
          <div class="row">
            <div class="col-lg-7 d-flex justify-content-start">
              <ul>
                <li>State of the art internet & phone packages</li>
              </ul>
            </div>
            <div class="col-lg-5 d-flex justify-content-end">
              <img class="home-office-types__image img-fluid" src="https://placehold.co/304x304" alt="">
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
</code>```

Below is the JS Fiddle:

https://jsfiddle.net/graeme95/qo6tj819/2/

答:
```<code>.tab-content {
  width: 100%;
}
</code>```

Also noticed that your grid only starts at lg. Mobile first!

Title: Tab panes losing width in Bootstrap 4

Body:
I've created tabbed content in my project with three tabs. For each tab pane, the pane loses width. For example the first tab pane is the full 100% width, however each pane onwards loses 100-200px consecutively.

For example:

The first pane is 1140px (full width of the container)

The second pane is: 1004px width

The third pane is: 794px width

I've checked for missing divs and I don't believe the use of rows and columns within the tab panes is the cause of the issue. I've also tried setting width: 100% to the tab panes with no luck.

I can't understand why this is happening.

            Serviced & managed offices

            Meeting Rooms

            Virtual Offices

State of the art internet & phone packages

Fully furnished and ready for you to move in and make your home

No hidden costs - your monthly fee covers everything from all your utilities to cleaning

Great value and truly affordable prices

No long contracts - choose from a few days to as long as you want giving you total control of your business’ finances

State of the art internet & phone packages

Fully furnished and ready for you to move in and make your home

State of the art internet & phone packages

Below is the JS Fiddle:

https://jsfiddle.net/graeme95/qo6tj819/2/

Body:
.tab-content {
  width: 100%;
}

Also noticed that your grid only starts at lg. Mobile first!


问:
Creating an Alert in Sentinel by REST API (Graph) for Azure Sentinel
I was looking at Alerts APIs for Microsoft Security Graph and it seems like you can't create a new alert by an API? I was wondering if there is anyway I can programmatically create a new alert into Azure Sentinel? </p>

答: Security alerts are supplied by Microsoft security providers, so creating alerts is not currently an allowed method under Microsoft Graph Security. However, you can create incidents from alerts in Azure Sentinel. Please refer to this documentation.</p>


问:
Circular buffer in JavaScript
Has anyone already implemented a circular buffer in JavaScript? How would you do that without having pointers?</p>

答:
Here's my take. Specifically this is a very simple object implementation of a circular/ring sliding buffer.

A little side note. Despite the fact that people call it similar names, "circular", "ring", "queue", it should be worth clarifying, because they can mean different things.

A ring/circular queue. You can add elements to the head, and crop them from the end. Min size is 0, max size is the size of underlying array. The queue wraps around the underlying array.

The same thing, a queue, FIFO, first-in-first-out, but with variable (indefinite) max size, and implemented using standard push() and unshift() array methods. To add element, you simply push() it onto an array, and to consume element you unshift() it, that's it, pretty standard functions, no need to invent anything.

A sliding buffer of constant size, where new elements are added to the head (right), the buffer slides back (left), and left-most excessive elements are automatically lost. Conceptually it is a sliding buffer, it just happens to get implemented most efficiently as a circular/ring one.

This is the implementation of a (3) kind. This can be used, and is primarily intended, as a back-end of a data visualization widget, e.g. a sliding line graph for real-time monitoring.

The object:

```<code>function make_CRS_Buffer(size) {
    return {
        A:  [],
        Ai: 0,
        Asz:    size,
        add:    function(value) {
            this.A[ this.Ai ] = value;
            this.Ai = (this.Ai + 1) % this.Asz;
        },
        forall: function(callback) {
            var mAi = this.A.length < this.Asz ? 0 : this.Ai;
            for (var i = 0; i < this.A.length; i++) {
                callback(this.A[ (mAi + i) % this.Asz ]);
            }

        }
    };
}
</code>```

Usage:

```<code>var buff1 = make_CRS_Buffer(5);

buff1.add(cnt);

buff1.forall(value => {
    b1.innerHTML += value + " ";
});
</code>```

And, a complete functional example, with two buffers running in parallel:

var b1 = document.getElementById("b1");
var b2 = document.getElementById("b2");

var cnt = 0;

var buff1 = make_CRS_Buffer(5);
var buff2 = make_CRS_Buffer(12);

function add() {
 buff1.add(cnt);
 buff2.add(cnt);
 cnt ++;

 b1.innerHTML = "";
 buff1.forall(value => {
  b1.innerHTML += value + " ";
 });

 b2.innerHTML = "";
 buff2.forall(value => {
  b2.innerHTML += value + " ";
 });
}

function make_CRS_Buffer(size) {
 return {
  A: [],
  Ai: 0,
  Asz: size,
  add: function(value) {
   this.A[ this.Ai ] = value;
   this.Ai = (this.Ai + 1) % this.Asz;
  },
  forall: function(callback) {
   var mAi = this.A.length < this.Asz ? 0 : this.Ai;
   for (var i = 0; i < this.A.length; i++) {
    callback(this.A[ (mAi + i) % this.Asz ]);
   }

  }
 };
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>

<h1>Circular/Ring Sliding Buffer</h1>

<p><i>(c) 2020, Leonid Titov</i>

<div id="b1" style="
 background-color: hsl(0,0%,80%);
 padding: 5px;
">empty</div>

<div id="b2" style="
 background-color: hsl(0,0%,80%);
 padding: 5px;
">empty</div>

<br>
<button onclick="add()">Add one more</button>

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

Hope it'll be useful.

Title: Circular buffer in JavaScript

Body:
Here's my take. Specifically this is a very simple object implementation of a circular/ring sliding buffer.

A little side note. Despite the fact that people call it similar names, "circular", "ring", "queue", it should be worth clarifying, because they can mean different things.

A ring/circular queue. You can add elements to the head, and crop them from the end. Min size is 0, max size is the size of underlying array. The queue wraps around the underlying array.

The same thing, a queue, FIFO, first-in-first-out, but with variable (indefinite) max size, and implemented using standard push() and unshift() array methods. To add element, you simply push() it onto an array, and to consume element you unshift() it, that's it, pretty standard functions, no need to invent anything.

A sliding buffer of constant size, where new elements are added to the head (right), the buffer slides back (left), and left-most excessive elements are automatically lost. Conceptually it is a sliding buffer, it just happens to get implemented most efficiently as a circular/ring one.

This is the implementation of a (3) kind. This can be used, and is primarily intended, as a back-end of a data visualization widget, e.g. a sliding line graph for real-time monitoring.

The object:

function make_CRS_Buffer(size) {
    return {
        A:  [],
        Ai: 0,
        Asz:    size,
        add:    function(value) {
            this.A[ this.Ai ] = value;
            this.Ai = (this.Ai + 1) % this.Asz;
        },
        forall: function(callback) {
            var mAi = this.A.length < this.Asz ? 0 : this.Ai;
            for (var i = 0; i < this.A.length; i++) {
                callback(this.A[ (mAi + i) % this.Asz ]);
            }

        }
    };
}

Usage:

var buff1 = make_CRS_Buffer(5);

buff1.add(cnt);

buff1.forall(value => {
    b1.innerHTML += value + " ";
});

And, a complete functional example, with two buffers running in parallel:

var b1 = document.getElementById("b1");
var b2 = document.getElementById("b2");

var cnt = 0;

var buff1 = make_CRS_Buffer(5);
var buff2 = make_CRS_Buffer(12);

function add() {
 buff1.add(cnt);
 buff2.add(cnt);
 cnt ++;

 b1.innerHTML = "";
 buff1.forall(value => {
  b1.innerHTML += value + " ";
 });

 b2.innerHTML = "";
 buff2.forall(value => {
  b2.innerHTML += value + " ";
 });
}

function make_CRS_Buffer(size) {
 return {
  A: [],
  Ai: 0,
  Asz: size,
  add: function(value) {
   this.A[ this.Ai ] = value;
   this.Ai = (this.Ai + 1) % this.Asz;
  },
  forall: function(callback) {
   var mAi = this.A.length < this.Asz ? 0 : this.Ai;
   for (var i = 0; i < this.A.length; i++) {
    callback(this.A[ (mAi + i) % this.Asz ]);
   }

  }
 };
}

<!DOCTYPE html>
<html>
<body>

<h1>Circular/Ring Sliding Buffer</h1>

<p><i>(c) 2020, Leonid Titov</i>

<div id="b1" style="
 background-color: hsl(0,0%,80%);
 padding: 5px;
">empty</div>

<div id="b2" style="
 background-color: hsl(0,0%,80%);
 padding: 5px;
">empty</div>

<br>
<button onclick="add()">Add one more</button>

</body>
</html>

Hope it'll be useful.