问:
Dowload Media in Download directory in android app
Am trying to download media file from server to android default Downloads directory,but on storing the media in downloads i got exception java.io.FileNotFoundException: Download/01-21-2022 04:15.jpeg (No such file or directory)

here is my code

```<code>val fileName = message.attributes.jsonObject!!.get("fileName")
val contentLength = response.body()!!.contentLength()
val file = File(Environment.DIRECTORY_DOWNLOADS, fileName as String)
responseBody.byteStream().apply {
    file.outputStream().use { fileOut ->
    var bytesCopied = 0
    val buffer = ByteArray(8*1024)
    var bytes = read(buffer)
    while (bytes >= 0) {
     fileOut.write(buffer, 0, bytes)
     bytesCopied += bytes
     bytes = read(buffer)
     reportStatus(((bytesCopied * 100) / contentLength).toInt())
    }
   }
  }
</code>```

答:
You have all to fix this. "No such file or directory".
Create file before usage. Try without apply, with verification that file was created. Be sure, that you have access to this directory.</p>

Body:
Am trying to download media file from server to android default Downloads directory,but on storing the media in downloads i got exception java.io.FileNotFoundException: Download/01-21-2022 04:15.jpeg (No such file or directory)

here is my code

val fileName = message.attributes.jsonObject!!.get("fileName")
val contentLength = response.body()!!.contentLength()
val file = File(Environment.DIRECTORY_DOWNLOADS, fileName as String)
responseBody.byteStream().apply {
    file.outputStream().use { fileOut ->
    var bytesCopied = 0
    val buffer = ByteArray(8*1024)
    var bytes = read(buffer)
    while (bytes >= 0) {
     fileOut.write(buffer, 0, bytes)
     bytesCopied += bytes
     bytes = read(buffer)
     reportStatus(((bytesCopied * 100) / contentLength).toInt())
    }
   }
  }


来源: stackexchange

问:
Trigger Lambda function by S3 PUT in subfolder of undefined folder
I have an AWS Lambda function, that I want to trigger when a user uploads a file to a subfolder in their S3 directory.

Every user has its own folder inside the 'private/' prefix, but when the user is uploading a file, it's put in a subfolder. This means that the trigger prefix should be 'private/userID/subFolder/', but I can't find how to define that the userID could be anything.

I have tried making the prefix 'private/*/subFolder/', but that doesn't trigger anything. If I make the prefix 'private/', the function will be triggered unnecessarily.

What is the best way to do this?

答:
You can't add a dynamic value for your trigger. So a solution is to get the event at a generic level like /prefix and then get the path of object. Extract the data you want and call your actual lambda. You can do this in 1 lambda as well and don't have to create 2.

```<code>S3 -> Lambda (extract path here) -> (actual) Lambda
</code>```

Alternate solution is to add the message in SQS after parsing the path. And then call Any number of lambda's accordingly.

```<code>S3 -> Lambda (extract path here) -> Path1 -> SQS1 -> Lambda
</code>```

OR

```<code>S3 -> Lambda (extract path here) -> SQS -> Lambda
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can't add a dynamic value for your trigger. So a solution is to get the event at a generic level like /prefix and then get the path of object. Extract the data you want and call your actual lambda. You can do this in 1 lambda as well and don't have to create 2.

S3 -> Lambda (extract path here) -> (actual) Lambda

Alternate solution is to add the message in SQS after parsing the path. And then call Any number of lambda's accordingly.

S3 -> Lambda (extract path here) -> Path1 -> SQS1 -> Lambda

OR

S3 -> Lambda (extract path here) -> SQS -> Lambda


问:
ORACLE, ignore null to sum
I want to add two columns(number type) of a row, together but when one of those columns is null then the result is null. I handlled it by NVL function(NVL(col1,0) + NVL(col2,0)). But i want to return null when both are null(instead of 0).
how can i handle it?
Is there function in ORACLE that ignore null to sum two columns of a row?</p>
```<code>| col1 | col2  |                                     |
|:---- |:-----:|:-----------------------------------:|
|  1   |   2   |      --> result have to be : 3      |
|  1   |  null |     --> result have to be : 1       |
| null |  null |     --> result have to be : null    |
</code>```

答:
coalesce(col1+col2,col1,col2) would be easier:

```<code>with t(col1,col2) as (
  select 0,1 from dual union all
  select 2,null from dual union all
  select null,3 from dual union all
  select null,null from dual
  )
select
  col1,col2,
  coalesce(col1+col2,col1,col2) sum_cols
from t;
</code>```

Results:

```<code>      COL1       COL2   SUM_COLS
---------- ---------- ----------
         0          1          1
         2       null          2
      null          3          3
      null       null       null

4 rows selected.
</code>```

or subquery with sum if you have more columns to sum:

```<code>(select sum(column_value) from table(sys.odcinumberlist(col1,col2,...,colN)))
</code>```

Example:

with t(col1,col2) as (
  select 0,1 from dual union all
  select 2,null from dual union all
  select null,3 from dual union all
  select null,null from dual
  )
select
  col1,col2,
  coalesce(col1+col2,col1,col2) sum_cols,
  (select sum(column_value) from table(sys.odcinumberlist(col1,col2))) sum_cols2
from t;
```

DBFiddle:
https://dbfiddle.uk/?rdbms=oracle_18&fiddle=eda8de9746f1d0def3c290420adbb705

Title: ORACLE, ignore null to sum

Body:
I want to add two columns(number type) of a row, together but when one of those columns is null then the result is null. I handlled it by NVL function(NVL(col1,0) + NVL(col2,0)). But i want to return null when both are null(instead of 0).
how can i handle it?
Is there function in ORACLE that ignore null to sum two columns of a row?

| col1 | col2  |                                     |
|:---- |:-----:|:-----------------------------------:|
|  1   |   2   |      --> result have to be : 3      |
|  1   |  null |     --> result have to be : 1       |
| null |  null |     --> result have to be : null    |

Body:
coalesce(col1+col2,col1,col2) would be easier:

with t(col1,col2) as (
  select 0,1 from dual union all
  select 2,null from dual union all
  select null,3 from dual union all
  select null,null from dual
  )
select
  col1,col2,
  coalesce(col1+col2,col1,col2) sum_cols
from t;

Results:

      COL1       COL2   SUM_COLS
---------- ---------- ----------
         0          1          1
         2       null          2
      null          3          3
      null       null       null

4 rows selected.

or subquery with sum if you have more columns to sum:

(select sum(column_value) from table(sys.odcinumberlist(col1,col2,...,colN)))

Example:

with t(col1,col2) as (
  select 0,1 from dual union all
  select 2,null from dual union all
  select null,3 from dual union all
  select null,null from dual
  )
select
  col1,col2,
  coalesce(col1+col2,col1,col2) sum_cols,
  (select sum(column_value) from table(sys.odcinumberlist(col1,col2))) sum_cols2
from t;

DBFiddle:
https://dbfiddle.uk/?rdbms=oracle_18&fiddle=eda8de9746f1d0def3c290420adbb705


问:
How to write a python function to return True when there's even number of 0 in a integer and return False otherwise using recursion?
I am asked to write a function that returns True if there's even number of 0 digits in a positive integer and return False otherwise (using recursion). As an attempt, I have written a function that counts the number of 0 in an integer. May I know how can I modify the program so that it will return True and False?</p>
```<code>def valid(n):
    number = str(n)
    position = number.find("0")

    if "0" not in number:
        return 0

    return 1 + valid(number[(position+1):])

print(valid(12340006))

</code>```

答:
If you are converting the number to a string using str, then you don't have to implement your own loop using recursion. You can count the number of '0' in the string using str.count, then test whether that number is odd or even using %.

def is_valid(n):
    s = str(n)
    nb_of_zeroes = s.count('0')
    return (nb_of_zeroes % 2 == 0)
```
<p>If you want to implement the logic yourself, rather than using <code>str</code> and <code>count</code>, then you can loop on the digits of <code>n</code> with <code>divmod(n, 10)</code> to extract <code>n%10</code> (the unit digit) and <code>n//10</code> (the number without its unit digit). For instance, <code>divmod(9836, 10)</code> is <code>(983, 6)</code>.</p>
<pre class="lang-py prettyprint-override"><code>def is_valid(n):
    if n == 0:
        return False  # special case for 0 which is a bit different from other numbers
    else:
        nb_of_zeroes = 0
        while n >= 10:
            n,u = divmod(n, 10)
            if u == 0:
                nb_of_zeroes += 1
        return (nb_of_zeroes % 2 == 0)

</code>```

Body:
I am asked to write a function that returns True if there's even number of 0 digits in a positive integer and return False otherwise (using recursion). As an attempt, I have written a function that counts the number of 0 in an integer. May I know how can I modify the program so that it will return True and False?

def valid(n):
    number = str(n)
    position = number.find("0")

    if "0" not in number:
        return 0

    return 1 + valid(number[(position+1):])

print(valid(12340006))

Body:
If you are converting the number to a string using str, then you don't have to implement your own loop using recursion. You can count the number of '0' in the string using str.count, then test whether that number is odd or even using %.

def is_valid(n):
    s = str(n)
    nb_of_zeroes = s.count('0')
    return (nb_of_zeroes % 2 == 0)

If you want to implement the logic yourself, rather than using str and count, then you can loop on the digits of n with divmod(n, 10) to extract n%10 (the unit digit) and n//10 (the number without its unit digit). For instance, divmod(9836, 10) is (983, 6).

def is_valid(n):
    if n == 0:
        return False  # special case for 0 which is a bit different from other numbers
    else:
        nb_of_zeroes = 0
        while n >= 10:
            n,u = divmod(n, 10)
            if u == 0:
                nb_of_zeroes += 1
        return (nb_of_zeroes % 2 == 0)


问:
How do you correctly use React.lazy() in Typescript to import a react component with a generic type parameter?
(repro at https://github.com/codingismy11to7/lazy-component-typing)

I'm guessing this is an issue with @types/react and the LazyExoticComponent definition...

When using React.lazy() on a component with a type parameter, Typescript can no longer compile
the project.

Given the component:

```<code>import React from "react";

export interface Props<T> {
  value: T;
  valueCallback: (t: T) => void;
}

export default function TypedComponent<T>(props: Props<T>) {
  return (
    <>
      <div>{`${props.value}`}</div>
      <button onClick={() => props.valueCallback(props.value)}>click</button>
    </>
  )
}
</code>```

This compiles:

```<code>import React, {useState} from "react";
import TypedComponent from "./TypedComponent";

export default function StrictComponent() {
  const [state, setState] = useState("blah");

  return (
    <TypedComponent value={state} valueCallback={setState}/>
  );
}
</code>```

while this does not:

```<code>import React, {lazy, useState} from "react";
const TypedComponent = lazy(() => import("./TypedComponent"));

export default function LazyComponent() {
  const [state, setState] = useState("blah");

  return (
    <TypedComponent value={state} valueCallback={setState}/>
  );
}
</code>```

```<code>TypeScript error in D:/dev/lazy-component-typing/src/LazyComponent.tsx(9,35):
Type 'Dispatch<SetStateAction<string>>' is not assignable to type '(t: unknown) => void'.
  Types of parameters 'value' and 't' are incompatible.
    Type 'unknown' is not assignable to type 'SetStateAction<string>'.
      Type 'unknown' is not assignable to type '(prevState: string) => string'.  TS2322

     7 |
     8 |   return (
  >  9 |     <TypedComponent value={state} valueCallback={setState}/>
       |                                   ^
    10 |   );
    11 | }
    12 |
</code>```

答:
TL;DR:
You can override React.lazy type definition to support generics.

react.d.ts:

```<code>declare namespace React {
  function lazy<T extends ComponentType<any>>(
    factory: () => Promise<{ default: T }>,
  ): T;
}
</code>```

Explanation: Original React.lazy declaration looks like this:

```<code>function lazy<T extends ComponentType<any>>(
  factory: () => Promise<{ default: T }>
): LazyExoticComponent<T>;
</code>```

It returns LazyExoticComponent type, which is superset of ExoticComponent. Unfortunately, this interface is written in way which don't support generics. However, according to comment above the interface, it is meant only for internal distinction between "regular" and other components, like results of lazy and memo calls; in JSX syntax there's no difference between this ExoticComponent and Component. That's why we can safely omit LaxyExoticComponent type in our custom override and make use of generics.

Body:
(repro at https://github.com/codingismy11to7/lazy-component-typing)

I'm guessing this is an issue with @types/react and the LazyExoticComponent definition...

When using React.lazy() on a component with a type parameter, Typescript can no longer compile
the project.

Given the component:

import React from "react";

export interface Props<T> {
  value: T;
  valueCallback: (t: T) => void;
}

export default function TypedComponent<T>(props: Props<T>) {
  return (
    <>

{`${props.value}`}

      <button onClick={() => props.valueCallback(props.value)}>click</button>
    </>
  )
}

This compiles:

import React, {useState} from "react";
import TypedComponent from "./TypedComponent";

export default function StrictComponent() {
  const [state, setState] = useState("blah");

  return (
    <TypedComponent value={state} valueCallback={setState}/>
  );
}

while this does not:

import React, {lazy, useState} from "react";
const TypedComponent = lazy(() => import("./TypedComponent"));

export default function LazyComponent() {
  const [state, setState] = useState("blah");

  return (
    <TypedComponent value={state} valueCallback={setState}/>
  );
}

TypeScript error in D:/dev/lazy-component-typing/src/LazyComponent.tsx(9,35):
Type 'Dispatch<SetStateAction<string>>' is not assignable to type '(t: unknown) => void'.
  Types of parameters 'value' and 't' are incompatible.
    Type 'unknown' is not assignable to type 'SetStateAction<string>'.
      Type 'unknown' is not assignable to type '(prevState: string) => string'.  TS2322

     7 |
     8 |   return (
  >  9 |     <TypedComponent value={state} valueCallback={setState}/>
       |                                   ^
    10 |   );
    11 | }
    12 |

Body:
TL;DR:
You can override React.lazy type definition to support generics.

react.d.ts:

declare namespace React {
  function lazy<T extends ComponentType<any>>(
    factory: () => Promise<{ default: T }>,
  ): T;
}

Explanation: Original React.lazy declaration looks like this:

function lazy<T extends ComponentType<any>>(
  factory: () => Promise<{ default: T }>
): LazyExoticComponent<T>;

It returns LazyExoticComponent type, which is superset of ExoticComponent. Unfortunately, this interface is written in way which don't support generics. However, according to comment above the interface, it is meant only for internal distinction between "regular" and other components, like results of lazy and memo calls; in JSX syntax there's no difference between this ExoticComponent and Component. That's why we can safely omit LaxyExoticComponent type in our custom override and make use of generics.


问:
Artemis-2.6.3 console: Service Unavailable
I started artemis-service successfully. But web console not working.

cmnd: sudo "/usr/lib/myBroker/bin/artemis-service" start

url: http://ip:8161/console/

response:

HTTP ERROR 503 Problem accessing /console/. Reason:

```<code>Service Unavailable
</code>```

I change the bootstrap.xml to access 8161 port from outside.

From: bind="http://localhost:8161"

To: bind="http://0.0.0.0:8161"

N.B: when I start it in my local-machine working fine without change bootstrap.xml.

答:
I had same problem when i tried to setup the broker as Windows service.
After some tries i just start the broker by executing:

artemis run

(from broker bin directory)
Now i got access to the console.

Body:
I started artemis-service successfully. But web console not working.

cmnd: sudo "/usr/lib/myBroker/bin/artemis-service" start

url: http://ip:8161/console/

response:

HTTP ERROR 503 Problem accessing /console/. Reason:

Service Unavailable

I change the bootstrap.xml to access 8161 port from outside.

From: bind="http://localhost:8161"

To: bind="http://0.0.0.0:8161"

N.B: when I start it in my local-machine working fine without change bootstrap.xml.


问:
How to save a keras StringLookup object with pickle?
I have a computer vision model to break CAPTCHAS. Before running the model I have to map the image labels using the following code:

# Mapping characters to integers
  char_to_num = layers.StringLookup(
  vocabulary=list(characters), mask_token=None)

# Mapping integers back to original characters
  num_to_char = layers.StringLookup(
  vocabulary=char_to_num.get_vocabulary(), mask_token=None, invert=True)
```

Also, the object type of the char_to_num object is: <keras.layers.preprocessing.string_lookup.StringLookup object at 0x00000269799D2C40>

My problem is that I want to save this mapping so I can use it later when I load the model. Does anyone know how to do that? Maybe using pickle?

答: char_to_num.get_vocabulary() is a list, which you can save in a text file. During inference read the file and create num_to_char. You can refer to app.py in the demo I have created on HuggingFace spaces OCR for CAPTCHA

Body:
I have a computer vision model to break CAPTCHAS. Before running the model I have to map the image labels using the following code:

# Mapping characters to integers
  char_to_num = layers.StringLookup(
  vocabulary=list(characters), mask_token=None)

# Mapping integers back to original characters
  num_to_char = layers.StringLookup(
  vocabulary=char_to_num.get_vocabulary(), mask_token=None, invert=True)

Also, the object type of the char_to_num object is: <keras.layers.preprocessing.string_lookup.StringLookup object at 0x00000269799D2C40>

My problem is that I want to save this mapping so I can use it later when I load the model. Does anyone know how to do that? Maybe using pickle?


问:
Convert object to array of prorperties
I need to convert object:

```<code>{
        middleName: null,
        name: "Test Name",
        university: {
            country: {
                code: "PL"
            },
            isGraduated: true,
            speciality: "Computer Science"
        }
    }
</code>```

to array:

```<code>[{
        key: "name",
        propertyValue: "Test Name",
    },
    {
        key: "middleName",
        propertyValue: null,
    },
    {
        key: "university.isGraduated",
        propertyValue: true,
    },
    {
        key: "university.speciality",
        propertyValue: "Computer Science",
    },
    {
        key: "university.country.code",
        propertyValue: "PL"
    }];
</code>```

I wrote algorithm, but it's pretty dummy, how can I improve it? Important, if object has nested object than I need to write nested object via dot (e.g university.contry: "value")

```<code>let arr = [];
    Object.keys(parsedObj).map((key) => {
        if (parsedObj[key] instanceof Object) {
            Object.keys(parsedObj[key]).map((keyNested) => {
                if (parsedObj[key][keyNested] instanceof Object) {
                    Object.keys(parsedObj[key][keyNested]).map((keyNestedNested) => {
                        arr.push({ 'key': key + '.' + keyNested + '.' + keyNestedNested, 'propertyValue': parsedObj[key][keyNested][keyNestedNested] })
                    })
                } else {
                    arr.push({ 'key': key + '.' + keyNested, 'propertyValue': parsedObj[key][keyNested] })
                }
            })
        } else {
            arr.push({ 'key': key, 'propertyValue': parsedObj[key] })
        }
    });
</code>```

Thanks

答:
A recursive function implementation.

I have considered that your object consist of only string and object as the values. If you have more kind of data types as your values, you may have to develop on top of this function.

const myObj = {
  middleName: null,
  name: "Test Name",
  university: {
    country: {
      code: "PL"
    },
    isGraduated: true,
    speciality: "Computer Science"
  }
}
const myArr = [];

function convertObjectToArray(obj, keyPrepender) {
  Object.entries(obj).forEach(([key, propertyValue]) => {
    if (typeof propertyValue === "object" && propertyValue) {
      const updatedKey = keyPrepender ? `${keyPrepender}.${key}` : key;
      convertObjectToArray(propertyValue, updatedKey)
    } else {
      myArr.push({
        key: keyPrepender ? `${keyPrepender}.${key}` : key,
        propertyValue
      })
    }
  })
}

convertObjectToArray(myObj);
console.log(myArr);```

Title: Convert object to array of prorperties

Body:
I need to convert object:

{
        middleName: null,
        name: "Test Name",
        university: {
            country: {
                code: "PL"
            },
            isGraduated: true,
            speciality: "Computer Science"
        }
    }

to array:

[{
        key: "name",
        propertyValue: "Test Name",
    },
    {
        key: "middleName",
        propertyValue: null,
    },
    {
        key: "university.isGraduated",
        propertyValue: true,
    },
    {
        key: "university.speciality",
        propertyValue: "Computer Science",
    },
    {
        key: "university.country.code",
        propertyValue: "PL"
    }];

I wrote algorithm, but it's pretty dummy, how can I improve it? Important, if object has nested object than I need to write nested object via dot (e.g university.contry: "value")

let arr = [];
    Object.keys(parsedObj).map((key) => {
        if (parsedObj[key] instanceof Object) {
            Object.keys(parsedObj[key]).map((keyNested) => {
                if (parsedObj[key][keyNested] instanceof Object) {
                    Object.keys(parsedObj[key][keyNested]).map((keyNestedNested) => {
                        arr.push({ 'key': key + '.' + keyNested + '.' + keyNestedNested, 'propertyValue': parsedObj[key][keyNested][keyNestedNested] })
                    })
                } else {
                    arr.push({ 'key': key + '.' + keyNested, 'propertyValue': parsedObj[key][keyNested] })
                }
            })
        } else {
            arr.push({ 'key': key, 'propertyValue': parsedObj[key] })
        }
    });

Thanks


问:
How is XOR helping find the unique value?
I have a problem to writhe a function that finds the unique value from an array, i could not solve the problem but i asked someone to help, he provided the solution by using XOR(^), but could not explain for me to understand it. I know that XOR has the following table:

```<code>1 ^ 0 = 1
1 ^ 1 = 0
0 ^ 0 = 0
0 ^ 1 = 1
</code>```

So, if the values are different XOR returns 1 or a non negative value in case of other numbers but I still don't get how this is helping me to solve this.
Can someone please explain how the code below is working and how is it finding the unique value?

int xor = 0;
int index = 0;

while(index < arr.length) {
    xor = arr[index] ^ xor;
    index++;
}

return xor;
```

答:
This work only when you have one unique value and even number of duplicate values.

Consider the following test case:
7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4
This can be rearranged as 7 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5)

xor is commutative: A ^ B = B ^ A

xor is associative: (A ^ B) ^ C = A ^ (B ^ C)

xoring with zero does nothing: A ^ 0 = A

xoring something twice removes it: A ^ A = 0

Applying this rules on above test case gives
7 ^ 0 ^ 0 ^ 0 then 7 ^ 0 i.e 7

Refer this for more info about XOR

Body:
I have a problem to writhe a function that finds the unique value from an array, i could not solve the problem but i asked someone to help, he provided the solution by using XOR(^), but could not explain for me to understand it. I know that XOR has the following table:

1 ^ 0 = 1
1 ^ 1 = 0
0 ^ 0 = 0
0 ^ 1 = 1

So, if the values are different XOR returns 1 or a non negative value in case of other numbers but I still don't get how this is helping me to solve this.
Can someone please explain how the code below is working and how is it finding the unique value?

int xor = 0;
int index = 0;

while(index < arr.length) {
    xor = arr[index] ^ xor;
    index++;
}

return xor;


问:
How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?
A C# desktop application (on the Visual Studio Express edition) worked, but then it didn't work 5 seconds later.

I tried the following:

Ensure debug configuration, debug flag, and full debug information are set on all assemblies.

Delete all bin and obj folders and all DLL files related to the project from my entire machine.

Recreate projects causing the problem from scratch.

Reboot.

I have two Windows Forms projects in the solution. One of them loads the debug information, one doesn't. They both refer to the assembly I'm trying to get debug information on in exactly the same way in the project file. Any ideas?

I want to add here, mostly for myself when I come back to review this question, that symbols are not loaded until the assembly is loaded, and the assembly is not loaded until it is needed. If the breakpoint is in a library that is only used in one function in your main assembly, the symbols will not be loaded (and it will show the breakpoint as not being hit) until that function is called.

答:
Make sure you're in Debug and not is release by choosing debug in the dropdown menu like you can see in the picture below.

Then, try cleaning your project by clicking the right button in your mouse on the solution in the solution explorer window and choosing Clean solution.

Then rebuild your solution by clicking the right button in your mouse on the solution in the solution explorer window and choose Rebuild solution


问:
removing text added to a plot with mtext
Having added text to an R plot with mtext

e.g.

```<code>mtext("my added text",side=1)
</code>```

How can I remove it?

答: Make another plot. (They are dirt cheap after all). mtext like most base graphic functions operates via a one-way side-effect model of plotting. There is no underlying storage facility that can be modified after the fact. ( I in the past have tried writing over with identical col="white" letters but it looks terrible.)  Failing that, if one is on an OS that has a default "Save as.." that creates a pdf file, then one can use a pdf-editing program.

ContentLicense: CC BY-SA 3.0

Body:
Having added text to an R plot with mtext

e.g.

mtext("my added text",side=1)

How can I remove it?


问:
Drop first row when index doesn't start at 0
I want to drop the first row of a dataframe subset which is a subset of the main dataframe main. The first row of the dataframe has index = 31, so when I try dropping the first row I get the following error:

```<code>>>> subset.drop(0, axis=1)
KeyError: '[0] not found in axis'
</code>```

I want to perform this drop on multiple dataframes, so I cannot drop index 31 on every dataframe. Is it possible to drop the first row when the index isn't equal to 0?

答:
```<code>df = df if df.index[0] == 0 else df.iloc[1:]
</code>```

Body:
I want to drop the first row of a dataframe subset which is a subset of the main dataframe main. The first row of the dataframe has index = 31, so when I try dropping the first row I get the following error:

>>> subset.drop(0, axis=1)
KeyError: '[0] not found in axis'

I want to perform this drop on multiple dataframes, so I cannot drop index 31 on every dataframe. Is it possible to drop the first row when the index isn't equal to 0?


问:
Is there a way to configure the filename for a Neo4j Desktop database dump file to exclude timestamp?
I'm a first time user of Neo4j and following a training course to install and learn the basics.

I've installed Neo4j Desktop on a Windows machine and can see that it comes with a demo DB called "Movie DBMS". I'm trying to follow steps to dump the database, by stopping the database, clicking on "..." and then "Dump".

The dump errors with the following error in the log file:

[2022-01-31 12:54:36.022] [error] Selecting JVM - Version:11.0.8+10-LTS, Name:OpenJDK 64-Bit Server VM, Vendor:Azul Systems, Inc.
java.nio.file.InvalidPathException: Illegal char <:> at index 128: C:\Users<me>.Neo4jDesktop\relate-data\projects<my project name>\movie-dbms-neo4j-31-Jan-2022-12:54:31.dump

It would appear that the automatic configuration for the dump file is adding a timestamp with includes colons (hh:mm:ss). How can I configure the file name to either exclude the timestamp or avoid using ":"?

Thanks.

答:
I had no responses. But I've figured it out myself.

The answer was to use the command line to dump the database manually. At that point I can specify my own "--to=" filename which doesn't include a ":".

Details in this section of the manual: https://neo4j.com/docs/operations-manual/current/backup-restore/offline-backup/#offline-backup


问:
How to change the default click event behavior of inputs in AngularJS?
Using AngularJS and i have a radio box which retrieves the list from Database on selected.

```<code><input type="radio" id="activeMeetingRadio" class="form-check-input mt-0 p-3"  ng-model="my.model" value="Active" ng-change="call to backend">
</code>```

Once i select this radio my list is fetched and radio seems clicked, now after submit the forms,i sets the form as pristine and reset the checked value of radio to blank like below which makes the radio as unchecked.

```<code>my.model='';
</code>```

but the issue is, even if i click the radio again, no event gets fired until i click another radio and then click back to this radio. Seems like a default bahaviour of AngularJS form controls. Is there any way i can make this radio fire event?

答: I was able to resolve this by setting the value in controller scope and then reset it using my.model='' will reset the value.</p>

Body:
Using AngularJS and i have a radio box which retrieves the list from Database on selected.

<input type="radio" id="activeMeetingRadio" class="form-check-input mt-0 p-3"  ng-model="my.model" value="Active" ng-change="call to backend">

Once i select this radio my list is fetched and radio seems clicked, now after submit the forms,i sets the form as pristine and reset the checked value of radio to blank like below which makes the radio as unchecked.

my.model='';

but the issue is, even if i click the radio again, no event gets fired until i click another radio and then click back to this radio. Seems like a default bahaviour of AngularJS form controls. Is there any way i can make this radio fire event?


问:
keep original array order when appling a active record "where" on it
Just a question, i have an array with some ids array = [19, 5, 1, 4]  when i call a where on it Delivery.where(id: array.map(&:id)) to have an active record relation instead an array, the “where” statement is sorting the ids and give me all objects sorting by ids  :
#<ActiveRecord::Relation [#<Delivery id: 1, ... >, #<Delivery id: 4, ... >, #<Delivery id: 5, ... >, #<Delivery id: 19, ... >
Is anyone know how to keep the original order ?

Thanks !

答:
ActiveRecord.find – when called with an array – will return the records in exactly the same order automatically.

Just change your query to:

```<code>Delivery.find(array.map(&:id))
</code>```

Quote from the docs:

NOTE: The returned records are in the same order as the ids you provide. [...]

Body:
ActiveRecord.find – when called with an array – will return the records in exactly the same order automatically.

Just change your query to:

Delivery.find(array.map(&:id))

Quote from the docs:

NOTE: The returned records are in the same order as the ids you provide. [...]


问:
Add a custom query parameter in Feathers request
I'm hoping to add a custom query parameter that can be used in a hook to process some results.

I'd like to add $foo=bar to the request. I can whitelist $foo and it appears in the request, but the service is using an ORM so it tries to query the database for $foo=bar.

In a before hook, I can strip $foo from the params.query, but is there somewhere else in the context of the hook that I could stash the value of $foo so that I can act on it in an after hook?

答:
I used to delete the params once the functionality is over here we added customer variable $paginate in before find hook.</p>
```<code>find: [
      (hook) => {
        if (hook.params.query && hook.params.query.$paginate) {
          hook.params.paginate =
            hook.params.query.$paginate === 'false' ||
            hook.params.query.$paginate === false;
          delete hook.params.query.$paginate;
        }
        return hook;
      }
    ],
</code>```

Body:
I used to delete the params once the functionality is over here we added customer variable $paginate in before find hook.

find: [
      (hook) => {
        if (hook.params.query && hook.params.query.$paginate) {
          hook.params.paginate =
            hook.params.query.$paginate === 'false' ||
            hook.params.query.$paginate === false;
          delete hook.params.query.$paginate;
        }
        return hook;
      }
    ],


问:
Javascript - Show a div with a given class after clicking on a given class
Several spans that have certain classes.

```<code><span class="1 click-1">1</span>
<span class="2 click-2">2</span>
<span class="3 click-3">4</span>
<span class="4 click-4">4</span>
</code>```

Clicking on a given  displays a DIV that contains the same class. How to do it?

```<code><div class="click-1">Hello!</div>
<div class="click-2">Hello 2!</div>
<div class="click-3">Hello 3!</div>
<div class="click-4">Hello 4!</div>
</code>```

I need such a solution because it is development on the CMS side. User can add much more span and div. So the script has to be universal.

答:
Looking for something like this?

document.querySelectorAll("span").forEach(e => {
  e.onclick = () => {                          // on click on span
    const div = document.createElement("div"); // create new div
    div.classList = e.classList;               // copy and reuse class list
    div.innerText = `Hello ${e.innerText}!`;   // set inner text to 'Hello ${}!'
    document.body.append(div);                 // append div to dom
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
  display: block;
}</code>```

1
2
4
4
Clicking on a given  displays a DIV that contains the same class. How to do it?```

Body:
Several spans that have certain classes.

1
2
4
4

Clicking on a given  displays a DIV that contains the same class. How to do it?

Hello!

Hello 2!

Hello 3!

Hello 4!

I need such a solution because it is development on the CMS side. User can add much more span and div. So the script has to be universal.

Body:
Looking for something like this?

document.querySelectorAll("span").forEach(e => {
  e.onclick = () => {                          // on click on span
    const div = document.createElement("div"); // create new div
    div.classList = e.classList;               // copy and reuse class list
    div.innerText = `Hello ${e.innerText}!`;   // set inner text to 'Hello ${}!'
    document.body.append(div);                 // append div to dom
  }
})

span {
  display: block;
}

<span class="1 click-1">1</span>
<span class="2 click-2">2</span>
<span class="3 click-3">4</span>
<span class="4 click-4">4</span>
Clicking on a given <span> displays a DIV that contains the same class. How to do it?


问:
How to pass data from nodejs to inside html script tags
I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?

static-pages-server.js:

```<code> app.get('/index', function(req, res) {
        var name = "hello";
        res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
    });
</code>```

index.html:

```<code> <script type="text/javascript">
        console.log(name);
 </script>
</code>```

Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.

```<code><script type="text/javascript">
        console.log(<%=name%>);
 </script>
</code>```

答:
You cant directly inject variables into a html file in nodejs . That is why you have templating engines in express. Check out ejs.

It would allow you to pass data directly from your routes into the page you are rendering.

Body:
I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?

static-pages-server.js:

 app.get('/index', function(req, res) {
        var name = "hello";
        res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
    });

index.html:

Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.


问:
Connecting Mongodb databse to node.js server
I have been trying to make a web app using node.js and express and decided to work with mongodb.
I am using mongodb node.js driver version: 4.3.1
I have tried all the possible ways to connect the node.js server with my mongodb atlas database.

My database also got connected using the following code in my db.js file:

```<code>const app = require('./app');

const MongoClient = require('mongodb').MongoClient

const Url = 'mongodb+srv://todoAppUser:<myOriginalPasswordHere>@cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority';

MongoClient.connect(Url, function (err, client) {
  if (err) throw err;

  var db = client.db('myDatabase');

  db.collection('products').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
    client.close();
  });
});
</code>```

The above code works fine and gives the output as well.
But I want to use MVC (Model-view-Controller) framework for which I need to export the connection.

I made the following change in the above code:

```<code>MongoClient.connect(Url, function (err, client) {
  if (err) throw err;

  var db = client.db('myDatabase');

  db.collection('products').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
  module.exports = db
    client.close();
  });
});
</code>```

After the change when I try to access my connection (const productCollection = require('./db').collection("product");) from any other file of mine, it gives me the following error:

```<code>const productCollection = require('./db').collection("product");
                                          ^

TypeError: require(...).collection is not a function
    at Object.<anonymous> (D:\Kush- Complete Data\exp-projects\nodeApp\productController.js:1:43)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (D:\Kush- Complete Data\exp-projects\nodeApp\router.js:3:27)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
[nodemon] app crashed - waiting for file changes before starting...
</code>```

May anyone please guide me and show a possible way out.

Thanks,
Kush

答:
This can't work, because modules are evaluated synchronously. Your callback is called asynchronously but your module has been alread evaluated at this time. Means module.exports has no effect and require('./db').collection() is not defined. Please see Node.js Modules for details.

To solve your problem, handle the connection stored in a module internal variable and export a getter instead of the connection variable itself.

```<code>// db.js
let client;
let db;

function connectDB(url, dbName) {
    client = new MongoClient(url);

    return new Promise(function(resolve, reject) {
        client.connect(function(err) {
            if(err) return reject(err);

            db = client.db(dbName);
            return resolve(db);
        });
    });
}

function getCurrentDB() {
    return db;
}

module.exports.connectDB = connectDB;
module.exports.getCurrentDB = getCurrentDB;
</code>```

Then reuse your opened connection in other files like the following:

```<code>// other.js
const db = require("./db.js");

db.getCurrentDB().collection("product");
</code>```

Of course, getCurrentDB() can only return a database connection if a connection has been established via connectDB() beforehand. So you have to wait for the resolution of the Promise.

Body:
I have been trying to make a web app using node.js and express and decided to work with mongodb.
I am using mongodb node.js driver version: 4.3.1
I have tried all the possible ways to connect the node.js server with my mongodb atlas database.

My database also got connected using the following code in my db.js file:

const app = require('./app');

const MongoClient = require('mongodb').MongoClient

const Url = 'mongodb+srv://todoAppUser:<myOriginalPasswordHere>@cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority';

MongoClient.connect(Url, function (err, client) {
  if (err) throw err;

  var db = client.db('myDatabase');

  db.collection('products').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
    client.close();
  });
});

The above code works fine and gives the output as well.
But I want to use MVC (Model-view-Controller) framework for which I need to export the connection.

I made the following change in the above code:

MongoClient.connect(Url, function (err, client) {
  if (err) throw err;

  var db = client.db('myDatabase');

  db.collection('products').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
  module.exports = db
    client.close();
  });
});

After the change when I try to access my connection (const productCollection = require('./db').collection("product");) from any other file of mine, it gives me the following error:

const productCollection = require('./db').collection("product");
                                          ^

TypeError: require(...).collection is not a function
    at Object.<anonymous> (D:\Kush- Complete Data\exp-projects\nodeApp\productController.js:1:43)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (D:\Kush- Complete Data\exp-projects\nodeApp\router.js:3:27)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
[nodemon] app crashed - waiting for file changes before starting...

May anyone please guide me and show a possible way out.

Thanks,
Kush

Body:
This can't work, because modules are evaluated synchronously. Your callback is called asynchronously but your module has been alread evaluated at this time. Means module.exports has no effect and require('./db').collection() is not defined. Please see Node.js Modules for details.

To solve your problem, handle the connection stored in a module internal variable and export a getter instead of the connection variable itself.

// db.js
let client;
let db;

function connectDB(url, dbName) {
    client = new MongoClient(url);

    return new Promise(function(resolve, reject) {
        client.connect(function(err) {
            if(err) return reject(err);

            db = client.db(dbName);
            return resolve(db);
        });
    });
}

function getCurrentDB() {
    return db;
}

module.exports.connectDB = connectDB;
module.exports.getCurrentDB = getCurrentDB;

Then reuse your opened connection in other files like the following:

// other.js
const db = require("./db.js");

db.getCurrentDB().collection("product");

Of course, getCurrentDB() can only return a database connection if a connection has been established via connectDB() beforehand. So you have to wait for the resolution of the Promise.


问:
How to not change the length of preexisting character variables when creating a new dataset in proc-iml?
I have a dataset which I manipulate in proc-iml and then create a new dataset reading some of the manipulated values in. When I read character values in, their length is changed from 7 to 9.

This doesn't really create a problem, except for the minor annoyance that when I later merge this new dataset, I receive the warning that the variables' length is different in two datasets.

Is there a way to keep the length of the original variable?

Sample code

```<code>data data1;
infile datalines delimiter=',';

input classif :$9. time :$7.;
datalines;
05, 2021_11
051, 2021_11
;
run;

proc iml;
    use work.data1;
    read all var {classif time } into _temp_1;
    classif = _temp_1[,1];
    time   = _temp_1[,2];
close;
create work.data2 var{classif time};
append;
quit;

</code>```

Observe how the length of time is 7 in data1, but 9 in data2.

答:
From Understanding the SAS/IML Language

Defining a Matrix

A matrix is the fundamental structure in the SAS/IML language. A matrix is a two-dimensional array of numeric or character values. Matrices are useful for working with data and have the following properties:

Matrices can be either numeric or character. Elements of a numeric matrix are double-precision values. Elements of a character matrix are character strings of equal length.

The INTO places the character values into a matrix _temp_1 that must hold all the original values, so the elements width are the attribute length of the widest data set variable.

The attributes of the _temp_1 matrix elements are propagated through the assignment statements.

Body:
I have a dataset which I manipulate in proc-iml and then create a new dataset reading some of the manipulated values in. When I read character values in, their length is changed from 7 to 9.

This doesn't really create a problem, except for the minor annoyance that when I later merge this new dataset, I receive the warning that the variables' length is different in two datasets.

Is there a way to keep the length of the original variable?

Sample code

data data1;
infile datalines delimiter=',';

input classif :$9. time :$7.;
datalines;
05, 2021_11
051, 2021_11
;
run;

proc iml;
    use work.data1;
    read all var {classif time } into _temp_1;
    classif = _temp_1[,1];
    time   = _temp_1[,2];
close;
create work.data2 var{classif time};
append;
quit;

Observe how the length of time is 7 in data1, but 9 in data2.


问:
What is a regular expression for a MAC Address?
In this format:

```<code>3D:F2:C9:A6:B3:4F
</code>```

or:

```<code>3D-F2-C9-A6-B3-4F
</code>```

答:
This could be used tested in sublime with my MAC address
This solution will only work with ideal MAC address That will look like this.. XX:XX:XX:XX:XX:XX

```<code>(([a-fA-F0-9]{2}[:]){5}[a-fA-F0-9]{2})
</code>```

Body:
In this format:

3D:F2:C9:A6:B3:4F

or:

3D-F2-C9-A6-B3-4F

Body:
This could be used tested in sublime with my MAC address
This solution will only work with ideal MAC address That will look like this.. XX:XX:XX:XX:XX:XX

(([a-fA-F0-9]{2}[:]){5}[a-fA-F0-9]{2})


问:
Any reason not to keep ViewModels in a separate, xaml-not-allowed assembly?
Just wondering if I am shooting myself in the foot if I put all my ViewModels into a separate assembly from the xaml of my silverlight application?  Do I lose any blendability?

It just seems more natural to me to have the ViewModels, which are (or should be) completely UI independent, in a separate assembly from the Xaml/views.

Do I lose anything in the area of blendability?

Im thinking it pretty much forces ease of unit testing, or am I missing something?

I found one post on this that agrees with my sentiment, but MVVMLights default project creation seems to put them together, so Im wondering if I am missing the point...

答:
We do this often for larger applications. For small ones, it is typically not really needed. Separating the assemblies like this does not have a real technical advantage (you rarely reuse a VM library) so it's really about organization of work and structure. In terms of Blendability, you don't lose anything. Also, if you work with services, you'll need to have the interface definition in the VM library (or in a 3rd project).

Note that sometimes you get confusing build error messages. If the VM library doesn't compile, you may see errors about non-existing objects in the XAML, which are simply caused by the fact that the library is not built yet. Don't get confused.

Cheers
Laurent


问:
How to Disable "Chrome --disable-web-security" in Jmeter Webdriver Sampler?
We are trying to Performance Test one of our web Applications which has Security feature enabled using JMeter and we are unable to pass Chrome --disable-web-security in webdriver Sampler and was wondering do we have any option to pass Chrome --disable-web-security when the webdriver sampler launches the chrome Browser ?

Below is the sample command line which we are using to disable web security manually to test the application.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --disable-web-security --user-data-dir="chrome"

答:
Enabling the Chrome Driver Config Option, "Allow Insecure Certs" worked well for my requirement.Could be worth a try.

Chrome Driver Config Screenshot


问:
How to use only one Connection to execute multiple commands and queries?
Here is Complete code link

I wanted to use only npgsql connection to execute multiple queries, instead of using multiple connections as shown below:

```<code>class TransactionAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        public static void GetExpense(DateTime startDate, DateTime endDate)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            var Expense = connection.Query<TransactionView>(@"SELECT SUM(t.amount) as Expense
                                                        FROM transaction AS t
                                                        INNER JOIN account AS a ON t.account_id = a.account_id
                                                        WHERE t.date BETWEEN @startDate AND @endDate AND a.type = 'expense'", new { startDate, endDate });
            Expense.Dump();
        }
    }

    public static void GetFilteredTransactionsList(DateTime startDate, DateTime endDate)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            var filteredTransactions = connection.Query<TransactionView>(@"SELECT a.account_name, a.account_id, a.type, DATE(t.date), t.transaction_id, t.amount, t.note
                                                                       FROM transaction AS t
                                                                       INNER JOIN account AS a ON t.account_id = a.account_id
                                                                       WHERE t.date BETWEEN @startDate AND @endDate
                                                                       ORDER BY t.date", new { startDate, endDate });
            filteredTransactions.Dump();
        }
    }
}
</code>```

Instead, I want to do something like this:

```<code>    class TransactionAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
    using (var connection = new NpgsqlConnection(connString))
{
public static void GetExpense(DateTime startDate, DateTime endDate)
    {
            var Expense = connection.Query<TransactionView>(@"SELECT SUM(t.amount) as Expense
                                                        FROM transaction AS t
                                                        INNER JOIN account AS a ON t.account_id = a.account_id
                                                        WHERE t.date BETWEEN @startDate AND @endDate AND a.type = 'expense'", new { startDate, endDate });
            Expense.Dump();

    }

    public static void GetFilteredTransactionsList(DateTime startDate, DateTime endDate)
    {
            var filteredTransactions = connection.Query<TransactionView>(@"SELECT a.account_name, a.account_id, a.type, DATE(t.date), t.transaction_id, t.amount, t.note
                                                                       FROM transaction AS t
                                                                       INNER JOIN account AS a ON t.account_id = a.account_id
                                                                       WHERE t.date BETWEEN @startDate AND @endDate
                                                                       ORDER BY t.date", new { startDate, endDate });
            filteredTransactions.Dump();

    }
}
</code>```

like this, using a single connection to execute multiple queries and methods/ How can I do that?

If anyone can help a bit more please edit the code accordingly in here

答:
Create a member variable for your TransactionAccess class, named as conn of type NpgsqlConnection. And also make your class implement the IDisposable interface.

You should open the connection only in the constructor of this class and initialize it like below,

```<code>  conn = new NpgsqlConnection(connString);
</code>```

The other member functions like GetExpense() etc, can use the conn member to execute the queries as per your business logic.

And in your class' Dispose method, remember to close the connection, like so,

```<code> public void Dispose()
 {
    conn.Close();
 }
</code>```

Body:
Here is Complete code link

I wanted to use only npgsql connection to execute multiple queries, instead of using multiple connections as shown below:

class TransactionAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        public static void GetExpense(DateTime startDate, DateTime endDate)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            var Expense = connection.Query<TransactionView>(@"SELECT SUM(t.amount) as Expense
                                                        FROM transaction AS t
                                                        INNER JOIN account AS a ON t.account_id = a.account_id
                                                        WHERE t.date BETWEEN @startDate AND @endDate AND a.type = 'expense'", new { startDate, endDate });
            Expense.Dump();
        }
    }

    public static void GetFilteredTransactionsList(DateTime startDate, DateTime endDate)
    {
        using (var connection = new NpgsqlConnection(connString))
        {
            var filteredTransactions = connection.Query<TransactionView>(@"SELECT a.account_name, a.account_id, a.type, DATE(t.date), t.transaction_id, t.amount, t.note
                                                                       FROM transaction AS t
                                                                       INNER JOIN account AS a ON t.account_id = a.account_id
                                                                       WHERE t.date BETWEEN @startDate AND @endDate
                                                                       ORDER BY t.date", new { startDate, endDate });
            filteredTransactions.Dump();
        }
    }
}

Instead, I want to do something like this:

    class TransactionAccess
{
    private const string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
    using (var connection = new NpgsqlConnection(connString))
{
public static void GetExpense(DateTime startDate, DateTime endDate)
    {
            var Expense = connection.Query<TransactionView>(@"SELECT SUM(t.amount) as Expense
                                                        FROM transaction AS t
                                                        INNER JOIN account AS a ON t.account_id = a.account_id
                                                        WHERE t.date BETWEEN @startDate AND @endDate AND a.type = 'expense'", new { startDate, endDate });
            Expense.Dump();

    }

    public static void GetFilteredTransactionsList(DateTime startDate, DateTime endDate)
    {
            var filteredTransactions = connection.Query<TransactionView>(@"SELECT a.account_name, a.account_id, a.type, DATE(t.date), t.transaction_id, t.amount, t.note
                                                                       FROM transaction AS t
                                                                       INNER JOIN account AS a ON t.account_id = a.account_id
                                                                       WHERE t.date BETWEEN @startDate AND @endDate
                                                                       ORDER BY t.date", new { startDate, endDate });
            filteredTransactions.Dump();

    }
}

like this, using a single connection to execute multiple queries and methods/ How can I do that?

If anyone can help a bit more please edit the code accordingly in here

Body:
Create a member variable for your TransactionAccess class, named as conn of type NpgsqlConnection. And also make your class implement the IDisposable interface.

You should open the connection only in the constructor of this class and initialize it like below,

  conn = new NpgsqlConnection(connString);

The other member functions like GetExpense() etc, can use the conn member to execute the queries as per your business logic.

And in your class' Dispose method, remember to close the connection, like so,

 public void Dispose()
 {
    conn.Close();
 }


问:
Scala Assert Testing Expectations
I am creating some tests in Scala and am trying to better understand some behavior I am seeing.

When I write my method as so, with a return Type, my test passes.

```<code>def cube(x: Int): Int ={
        x * x * x
    }
</code>```
```<code>test("CubeTest") {
    assert(CubeCalculator.cube(3) === 27)
  }
</code>```

However, when I do not specify the return type the test fails:

```<code>def cube(x: Int){
        x * x * x
    }
</code>```

I was under the impression that The Scala compiler can infer return types for methods so why do I need to state it for the test to pass?

答:
Omitting the return type isn't the problem with your code, it's omitting the = sign.

def cube(x: Int){
  x * x * x
}
```
<p>Is equivalent to:</p>
<pre class="lang-scala prettyprint-override"><code>def cube(x: Int): Unit = {
  x * x * x
}
</code>```

Since a Unit cannot possibly be an Int, the comparison in your test cannot pass; presumably the === is a "typesafe equality operator" which prevents impossible comparisons like this from compiling.

This syntax for defining Unit-resulting methods is dropped in Scala 3.

It's worth noting what exactly this procedure does:

It  calculates x * x * x

It throws away that result and returns the singleton value of Unit: ()

This throwing away of the result is at the very least wasteful; there's a compiler option which makes such discarding of a value a warning: -Ywarn-discard.  With this option in force, you would have to write

def cube(x: Int) {
  x * x * x
  ()
}
```
<p>Which at least makes it clear that you want <code>x * x * x</code> computed and thrown away.</p>
<pre class="lang-scala prettyprint-override"><code>def cube(x: Int) = x * x * x
</code>```

Should have an inferred result type of Int.  That said, using an explicit return type on (at least) externally visible non-constant methods may serve a useful documentation function, improve compiler speed, and prevent situations where you think you're returning one type but are actually returning another.

Title: Scala Assert Testing Expectations

Body:
I am creating some tests in Scala and am trying to better understand some behavior I am seeing.

When I write my method as so, with a return Type, my test passes.

def cube(x: Int): Int ={
        x * x * x
    }

test("CubeTest") {
    assert(CubeCalculator.cube(3) === 27)
  }

However, when I do not specify the return type the test fails:

def cube(x: Int){
        x * x * x
    }

I was under the impression that The Scala compiler can infer return types for methods so why do I need to state it for the test to pass?

Body:
Omitting the return type isn't the problem with your code, it's omitting the = sign.

def cube(x: Int){
  x * x * x
}

Is equivalent to:

def cube(x: Int): Unit = {
  x * x * x
}

Since a Unit cannot possibly be an Int, the comparison in your test cannot pass; presumably the === is a "typesafe equality operator" which prevents impossible comparisons like this from compiling.

This syntax for defining Unit-resulting methods is dropped in Scala 3.

It's worth noting what exactly this procedure does:

It  calculates x * x * x

It throws away that result and returns the singleton value of Unit: ()

This throwing away of the result is at the very least wasteful; there's a compiler option which makes such discarding of a value a warning: -Ywarn-discard.  With this option in force, you would have to write

def cube(x: Int) {
  x * x * x
  ()
}

Which at least makes it clear that you want x * x * x computed and thrown away.

def cube(x: Int) = x * x * x

Should have an inferred result type of Int.  That said, using an explicit return type on (at least) externally visible non-constant methods may serve a useful documentation function, improve compiler speed, and prevent situations where you think you're returning one type but are actually returning another.


问:
How to use @Viewbuilder and return view in swiftUi?
I have overlay with below code

```<code>.overlay(abcViewModel.isError ? AnyView(DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
    action()
    abcViewModel.isError = false
}, isDialogboxFirstButtonClicked: .constant(true))) :  AnyView(EmptyView()))
</code>```

I am trying to avoid use of Anyview and did below code but getting error as "Unknown attribute 'Viewbuilder'" and not sure how to return view in if case

```<code>private func getOverlayView() -> some View {
     if abcViewModel.isError {
          DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
              action()
              abcViewModel.isError = false
          }, isDialogboxFirstButtonClicked: .constant(true))
    } else {
       return EmptyView()
    }
}
</code>```

Kindly help me the best way for this

答:
You can add @ViewBuilder above your function signature like:

```<code>@ViewBuilder private func createOverlay() -> some View { ... }
</code>```

And get rid of all return keywords.

 Cleaner method

You can extend the View and define a simple function and hide any view conditionally like:

```<code>extension View {

    @ViewBuilder
    func hidden(if condition: Bool) -> some View {
        if condition { self.hidden() }
        else { self }
    }
}
</code>```

and use it like:

```<code>DialogBoxOneButton(...)
    .hidden(if: !abcViewModel.isError)
</code>```

Body:
I have overlay with below code

.overlay(abcViewModel.isError ? AnyView(DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
    action()
    abcViewModel.isError = false
}, isDialogboxFirstButtonClicked: .constant(true))) :  AnyView(EmptyView()))

I am trying to avoid use of Anyview and did below code but getting error as "Unknown attribute 'Viewbuilder'" and not sure how to return view in if case

private func getOverlayView() -> some View {
     if abcViewModel.isError {
          DialogBoxOneButton(accessibilityID: "dialogboxes", dialogboxType: .error, dialogboxTitle: "title", dialogboxBody: "body", dialogboxFirstButtonTitle: "title", dialogboxFirstButtonCallback: {
              action()
              abcViewModel.isError = false
          }, isDialogboxFirstButtonClicked: .constant(true))
    } else {
       return EmptyView()
    }
}

Kindly help me the best way for this

Body:
You can add @ViewBuilder above your function signature like:

@ViewBuilder private func createOverlay() -> some View { ... }

And get rid of all return keywords.

 Cleaner method

You can extend the View and define a simple function and hide any view conditionally like:

extension View {

    @ViewBuilder
    func hidden(if condition: Bool) -> some View {
        if condition { self.hidden() }
        else { self }
    }
}

and use it like:

DialogBoxOneButton(...)
    .hidden(if: !abcViewModel.isError)


问:
strncpy making weird output
I'm trying to make an algorithm for strncpy

I read how it work in the manual and made my algorithm

then I made a test to see if there's any difference between my ft_strncpy and the real strncpy

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

char    *ft_strncpy(char *dest, char *src, unsigned int n)
{
    unsigned int    i;

    i = 0;
    while (i < n && src[i] != '\0')
    {
        dest[i] = src[i];
        i++;
    }
    while (i < n)
    {
        dest[i] = '\0';
        i++;
    }
    return (dest);
}

int main(void)
{
    char src1[] = "123456789q00000";
    char dest1[] = "zzz";
    printf("my output\n");
    printf("src1: %s\n", src1);
    ft_strncpy(dest1, src1, 8);
    printf("dest1: %s\n", dest1);

    printf("\nhow it should be\n");
    char src2[] = "123456789q00000";
    char dest2[] = "zzz";
    printf("src2: %s\n", src2);
    strncpy(dest2, src2, 8);
    printf("dest2: %s\n", dest2);
}
```
<p>the <code>how it should be</code> section supposed to be the right output of the real <code>strncpy</code>
but I'm having weird outputs just like in the code I provided<br>
I get this error</p>
<pre class="lang-c prettyprint-override"><code>*** buffer overflow detected ***: terminated
signal: aborted (core dumped)
</code>```

what I understood from the manual is

strncpy copies n first characters from *src to *dest

so a code like

    char src2[] = "123456789q00000";
    char dest2[] = "zzz";
    printf("src2: %s\n", src2);
    strncpy(dest2, src2, 10);
    printf("dest2: %s\n", dest2);
```

should output : 123456789q as the value of dest
I'm I missing smth here?

答:
strncpy(dest2, src2, 10); has undefined behavior because it will modify 10 bytes starting with dest2[0], yet dest2 is only 4 bytes long.

You have the same problem in ft_strncpy(dest1, src1, 8); for the same reason.

Nothing can be concluded from tests with code that has undefined behavior. The code must be corrected first.

You code for ft_strncpy() seems correct, except for the type unsigned int for the length argument which should be size_t. Using unsigned int is probably a requirement for your school project, but a debatable one, among other counter-productive requirements such as banning for loops and mandating parentheses around the return value.

Here is a modified version:

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

char    *ft_strncpy(char *dest, char *src, unsigned int n)
{
    unsigned int    i;

    i = 0;
    while (i < n && src[i] != '\0')
    {
        dest[i] = src[i];
        i++;
    }
    while (i < n)
    {
        dest[i] = '\0';
        i++;
    }
    return (dest);
}

void dump(const char *prefix, const char *p, size_t size)
{
    size_t i;

    printf("%s: %s  [", prefix, p);
    i = 0;
    while (i < size) {
        printf(" %.2X", (unsigned char)p[i]);
        i++;
    }
    printf(" ]\n");
}

int main(void)
{
    char src1[] = "zzz";
    char dest1[] = "123456789q00000";

    printf("my output\n");
    printf("src1: %s\n", src1);
    ft_strncpy(dest1, src1, 8);
    dump("dest1: ", dest1, sizeof dest1);

    printf("\nhow it should be\n");
    char src2[] = "zzz";
    char dest2[] = "123456789q00000";
    printf("src2: %s\n", src2);
    strncpy(dest2, src2, 8);
    dump("dest1: ", dest1, sizeof dest1);

    return 0;
}
</code>```

Output:

my output
src1: zzz
dest1: : zzz  [ 7A 7A 7A 00 00 00 00 00 39 71 30 30 30 30 30 00 ]

how it should be
src2: zzz
dest1: : zzz  [ 7A 7A 7A 00 00 00 00 00 39 71 30 30 30 30 30 00 ]
```

Title: strncpy making weird output

Body:
I'm trying to make an algorithm for strncpy

I read how it work in the manual and made my algorithm

then I made a test to see if there's any difference between my ft_strncpy and the real strncpy

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

char    *ft_strncpy(char *dest, char *src, unsigned int n)
{
    unsigned int    i;

    i = 0;
    while (i < n && src[i] != '\0')
    {
        dest[i] = src[i];
        i++;
    }
    while (i < n)
    {
        dest[i] = '\0';
        i++;
    }
    return (dest);
}

int main(void)
{
    char src1[] = "123456789q00000";
    char dest1[] = "zzz";
    printf("my output\n");
    printf("src1: %s\n", src1);
    ft_strncpy(dest1, src1, 8);
    printf("dest1: %s\n", dest1);

    printf("\nhow it should be\n");
    char src2[] = "123456789q00000";
    char dest2[] = "zzz";
    printf("src2: %s\n", src2);
    strncpy(dest2, src2, 8);
    printf("dest2: %s\n", dest2);
}

the how it should be section supposed to be the right output of the real strncpy
but I'm having weird outputs just like in the code I provided

I get this error

*** buffer overflow detected ***: terminated
signal: aborted (core dumped)

what I understood from the manual is

strncpy copies n first characters from *src to *dest

so a code like

    char src2[] = "123456789q00000";
    char dest2[] = "zzz";
    printf("src2: %s\n", src2);
    strncpy(dest2, src2, 10);
    printf("dest2: %s\n", dest2);

should output : 123456789q as the value of dest
I'm I missing smth here?

Body:
strncpy(dest2, src2, 10); has undefined behavior because it will modify 10 bytes starting with dest2[0], yet dest2 is only 4 bytes long.

You have the same problem in ft_strncpy(dest1, src1, 8); for the same reason.

Nothing can be concluded from tests with code that has undefined behavior. The code must be corrected first.

You code for ft_strncpy() seems correct, except for the type unsigned int for the length argument which should be size_t. Using unsigned int is probably a requirement for your school project, but a debatable one, among other counter-productive requirements such as banning for loops and mandating parentheses around the return value.

Here is a modified version:

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

char    *ft_strncpy(char *dest, char *src, unsigned int n)
{
    unsigned int    i;

    i = 0;
    while (i < n && src[i] != '\0')
    {
        dest[i] = src[i];
        i++;
    }
    while (i < n)
    {
        dest[i] = '\0';
        i++;
    }
    return (dest);
}

void dump(const char *prefix, const char *p, size_t size)
{
    size_t i;

    printf("%s: %s  [", prefix, p);
    i = 0;
    while (i < size) {
        printf(" %.2X", (unsigned char)p[i]);
        i++;
    }
    printf(" ]\n");
}

int main(void)
{
    char src1[] = "zzz";
    char dest1[] = "123456789q00000";

    printf("my output\n");
    printf("src1: %s\n", src1);
    ft_strncpy(dest1, src1, 8);
    dump("dest1: ", dest1, sizeof dest1);

    printf("\nhow it should be\n");
    char src2[] = "zzz";
    char dest2[] = "123456789q00000";
    printf("src2: %s\n", src2);
    strncpy(dest2, src2, 8);
    dump("dest1: ", dest1, sizeof dest1);

    return 0;
}

Output:

my output
src1: zzz
dest1: : zzz  [ 7A 7A 7A 00 00 00 00 00 39 71 30 30 30 30 30 00 ]

how it should be
src2: zzz
dest1: : zzz  [ 7A 7A 7A 00 00 00 00 00 39 71 30 30 30 30 30 00 ]


问:
Send CGI request from C++ program?
I am currently working on integrating a prototype product I made into a larger program. What I did in the prototype was create a HTTP server on a microcontroller, and then wrote some HTML to call .cgi functions on the web-server. This was so I could control I/O on the micro controller via an ethernet.

My html seems very straight forward, to call a cgi function on the microcontroller I have made buttons with the following syntax:

```<code><script type="text/javascript">
function my_confirm(a){
  var r=confirm("Are you sure you'd like to run "+a+"?");
  if (r==true)
    location.href = a;
}
</script>
<button type = "button" onclick=" my_confirm('started.cgi')" >Started</button>
</code>```

additionally, if i were to type in "169.254.129.12/started.cgi" into a web browser, the microcontroller would respond appropriately. Now that the prototype is completed ahead of schedule, my new task is to integrate my controls into a C++/CLI program. GREAT. I have never written in C++...

Rather than re-doing all of the backend stuff, I would like to add a menu to send similiar requests. Over the last 4-5 days I have gotten a menu in VS2005 and have had limited success, with the code below:

```<code>int sendHttpRequestAndRespond(System::Uri^ url){
    if(url->Scheme == System::Uri::UriSchemeHttp){
        HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(WebRequest::Create(url));
        request->Method = System::Net::WebRequestMethods::Http::Get;
        return 0;
    }
    //HttpWebResponse^ response = dynamic_cast<HttpWebResponse^> (request->GetResponse());
    //RequestState^ state = gcnew RequestState();
    //state->request = request;
    //try{
    //  IAsyncResult^ response = dynamic_cast<IAsyncResult^> (request->BeginGetResponse(gcnew AsyncCallback( responseReceived),state));
    //}
    //catch(WebException^ e){}
    else
        return -1;
}
</code>```

With the code written as shown above(with comments present) the I/O control of the microcontroller does not operate properly. Oddly, if I put in the HttpWebResponse line, things (sometimes) go properly, and other times, nothing seems to happen. Lastly, if I use the AsyncResponse, things are similiar to if I use the HttpWebResponse portion.

Now my thought/understanding was that merely putting in the request via the GET method I am using in the code shown above would initiate the I/O control on the microcontroller, but it seems the response plays a role in it as well.

Do any of you have a better route to go with this? At this point I am highly confused/frustrated and open to any advice! Thank you,

EDIT 1: UPDATED CODE:

```<code>int sendHttpRequestAndRespond(System::Uri^ url){
    if(url->Scheme == System::Uri::UriSchemeHttp){
        HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(WebRequest::Create(url));
        request->Method = System::Net::WebRequestMethods::Http::Get;
        RequestState^ state = gcnew RequestState();
        state->request = request;
        try{
                IAsyncResult^ response = dynamic_cast<IAsyncResult^> (request->BeginGetResponse(gcnew AsyncCallback( responseReceived),state));
            }
        catch(WebException^ e){}
        return 0;
    }
</code>```

With this code I get into my callback function (responseReceived) the first two times I call the function, but never on the 3rd or further time. I am testing this with http://www.facebook.com, as this seems to work for my CGI calling, but only the first two times as well.
Thanks,

EDIT 2: Resolution and new problems!
Okay, I figured out my problem was due mostly to not ending the requests. In the callBack function I wasn't ending the request, and HTTP protocol has a 2 connections/ip restriction, making the first two calls work, but future ones wouldn't.

Now my new issue is that on the asyc call I a using, it first does synchronous DNS resolution. Since I am sending these commands to an embedded computer with an IP, there's no DNS inbetween, and the function blocks for a long time. Once my computer realizes there's been a DNS resolution error, it fires off the request any ways, and it works! Subsequent requests work instantly, as there's a cache that remembers the failure.

So im about 99% of the way there, but I need to fix this first time lockup some how. My current ideas are:

Somehow disable dns resolution before the request

Shorten the dns resolution timeout from 60+ seconds to 1ish seconds

trick my comptuer/the computer the program runs on into thinking that http://169.254.129.12  has an ip address of 169.254.129.12 (local host file??)

I am not sure how to accomplish those, or if there are better ideas??

Thank you,

Any better ideas?

答:
I'm not very familiar with the HttpWebRequest class and related classes, but as I understand it the request doesn't get sent to the server until you either (a) send it explictly by writing to the request stream, or (b) retrieve the response by calling GetResponse. So for starters I think you need to uncomment all that stuff.

I wonder why you return on line 5 before doing anything with the request. I know this code is a work in progress. But surely you don't want to return before doing anything?

And finally, you're using async comms, which is probably extra complexity that you can do without right now. I suggest you do everything synchronously first to get it working, and then switch to async if you really need to.

Title: Send CGI request from C++ program?

Body:
I am currently working on integrating a prototype product I made into a larger program. What I did in the prototype was create a HTTP server on a microcontroller, and then wrote some HTML to call .cgi functions on the web-server. This was so I could control I/O on the micro controller via an ethernet.

My html seems very straight forward, to call a cgi function on the microcontroller I have made buttons with the following syntax:

<button type = "button" onclick=" my_confirm('started.cgi')" >Started</button>

additionally, if i were to type in "169.254.129.12/started.cgi" into a web browser, the microcontroller would respond appropriately. Now that the prototype is completed ahead of schedule, my new task is to integrate my controls into a C++/CLI program. GREAT. I have never written in C++...

Rather than re-doing all of the backend stuff, I would like to add a menu to send similiar requests. Over the last 4-5 days I have gotten a menu in VS2005 and have had limited success, with the code below:

int sendHttpRequestAndRespond(System::Uri^ url){
    if(url->Scheme == System::Uri::UriSchemeHttp){
        HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(WebRequest::Create(url));
        request->Method = System::Net::WebRequestMethods::Http::Get;
        return 0;
    }
    //HttpWebResponse^ response = dynamic_cast<HttpWebResponse^> (request->GetResponse());
    //RequestState^ state = gcnew RequestState();
    //state->request = request;
    //try{
    //  IAsyncResult^ response = dynamic_cast<IAsyncResult^> (request->BeginGetResponse(gcnew AsyncCallback( responseReceived),state));
    //}
    //catch(WebException^ e){}
    else
        return -1;
}

With the code written as shown above(with comments present) the I/O control of the microcontroller does not operate properly. Oddly, if I put in the HttpWebResponse line, things (sometimes) go properly, and other times, nothing seems to happen. Lastly, if I use the AsyncResponse, things are similiar to if I use the HttpWebResponse portion.

Now my thought/understanding was that merely putting in the request via the GET method I am using in the code shown above would initiate the I/O control on the microcontroller, but it seems the response plays a role in it as well.

Do any of you have a better route to go with this? At this point I am highly confused/frustrated and open to any advice! Thank you,

EDIT 1: UPDATED CODE:

int sendHttpRequestAndRespond(System::Uri^ url){
    if(url->Scheme == System::Uri::UriSchemeHttp){
        HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(WebRequest::Create(url));
        request->Method = System::Net::WebRequestMethods::Http::Get;
        RequestState^ state = gcnew RequestState();
        state->request = request;
        try{
                IAsyncResult^ response = dynamic_cast<IAsyncResult^> (request->BeginGetResponse(gcnew AsyncCallback( responseReceived),state));
            }
        catch(WebException^ e){}
        return 0;
    }

With this code I get into my callback function (responseReceived) the first two times I call the function, but never on the 3rd or further time. I am testing this with http://www.facebook.com, as this seems to work for my CGI calling, but only the first two times as well.
Thanks,

EDIT 2: Resolution and new problems!
Okay, I figured out my problem was due mostly to not ending the requests. In the callBack function I wasn't ending the request, and HTTP protocol has a 2 connections/ip restriction, making the first two calls work, but future ones wouldn't.

Now my new issue is that on the asyc call I a using, it first does synchronous DNS resolution. Since I am sending these commands to an embedded computer with an IP, there's no DNS inbetween, and the function blocks for a long time. Once my computer realizes there's been a DNS resolution error, it fires off the request any ways, and it works! Subsequent requests work instantly, as there's a cache that remembers the failure.

So im about 99% of the way there, but I need to fix this first time lockup some how. My current ideas are:

Somehow disable dns resolution before the request

Shorten the dns resolution timeout from 60+ seconds to 1ish seconds

trick my comptuer/the computer the program runs on into thinking that http://169.254.129.12  has an ip address of 169.254.129.12 (local host file??)

I am not sure how to accomplish those, or if there are better ideas??

Thank you,

Any better ideas?


问:
Cannot understand warnings in Gradient

Background

I am now trying Gradual type checking, as a consequence I am giving a shot to Gradient. As I see it, this is an alternative to Dialyzer.

Problems

So, on my first ever code snippet, I started with a pure function:

```<code>defmodule TipCalculator do

  @spec getTipPercentage(List[String.t()]) :: non_neg_integer
  def getTipPercentage(names) do
    names_size = length(names)

    cond do
      names_size > 5 -> 20
      names_size > 0 -> 10
      true -> 0
    end
  end
end

</code>```

From my point of view, my type checks are rather solid.
However, Gradient seems to have a different opinion:

```<code>===> Analyzing applications...
===> Compiling gradualizer
src/gradualizer.erl:45:2: Warning: opaque type top() is underspecified and therefore meaningless

src/typechecker.erl:3234:1: Warning: function type_check_cons_in/4 is unused
src/typechecker.erl:3247:1: Warning: function type_check_cons_union/4 is unused
src/typechecker.erl:4612:1: Warning: function verbose/3 is unused
src/typechecker.erl:4870:1: Warning: function gen_partition/3 is unused
src/typechecker.erl:4872:1: Warning: function paux/3 is unused

==> gradient
Compiling 14 files (.ex)
Generated gradient app
==> grokking_fp
Compiling 1 file (.ex)
warning: code block contains unused literal "\n" (remove the literal or assign it to _ to avoid warnings)
  lib/tip_calculator.ex: TipCalculator

Generated grokking_fp app
Typechecking files...
lib/tip_calculator.ex: Undefined remote type Access:get/2 on line 0

</code>```

From what I can understand, this one piece of code (from a fresh project) has several issues:

warning: code block contains unused literal "\n" (remove the literal or assign it to _ to avoid warnings)

lib/tip_calculator.ex: Undefined remote type Access:get/2 on line 0

The fist one sounds like a warning credo (or a linter) would give me. So I am not really sure what do do with it. I am expecting a tool that does type checks only (maybe I am wrong?).

The second one, I have no idea.

Questions

What am I doing wrong?

答:
Answer

I got confused a little bit, the correct typing was [String.t] and not List[String.t].

I will say however that:

lib/tip_calculator.ex: Undefined remote type Access:get/2 on line 0

Is not (to me) a very descriptive error message.
However, given the alternative (dialzyer) message is not much better:

```<code>lib/tip_calculator.ex:8:unknown_type
Unknown type: Access.get/2.
</code>```

I will say however, the line number was an incredible help to find the issue.
With Gradient line 0 really threw me off.

Title: Cannot understand warnings in Gradient

Body:
Background

I am now trying Gradual type checking, as a consequence I am giving a shot to Gradient. As I see it, this is an alternative to Dialyzer.

Problems

So, on my first ever code snippet, I started with a pure function:

defmodule TipCalculator do

  @spec getTipPercentage(List[String.t()]) :: non_neg_integer
  def getTipPercentage(names) do
    names_size = length(names)

    cond do
      names_size > 5 -> 20
      names_size > 0 -> 10
      true -> 0
    end
  end
end

From my point of view, my type checks are rather solid.
However, Gradient seems to have a different opinion:

===> Analyzing applications...
===> Compiling gradualizer
src/gradualizer.erl:45:2: Warning: opaque type top() is underspecified and therefore meaningless

src/typechecker.erl:3234:1: Warning: function type_check_cons_in/4 is unused
src/typechecker.erl:3247:1: Warning: function type_check_cons_union/4 is unused
src/typechecker.erl:4612:1: Warning: function verbose/3 is unused
src/typechecker.erl:4870:1: Warning: function gen_partition/3 is unused
src/typechecker.erl:4872:1: Warning: function paux/3 is unused

==> gradient
Compiling 14 files (.ex)
Generated gradient app
==> grokking_fp
Compiling 1 file (.ex)
warning: code block contains unused literal "\n" (remove the literal or assign it to _ to avoid warnings)
  lib/tip_calculator.ex: TipCalculator

Generated grokking_fp app
Typechecking files...
lib/tip_calculator.ex: Undefined remote type Access:get/2 on line 0

From what I can understand, this one piece of code (from a fresh project) has several issues:

warning: code block contains unused literal "\n" (remove the literal or assign it to _ to avoid warnings)

lib/tip_calculator.ex: Undefined remote type Access:get/2 on line 0

The fist one sounds like a warning credo (or a linter) would give me. So I am not really sure what do do with it. I am expecting a tool that does type checks only (maybe I am wrong?).

The second one, I have no idea.

Questions

What am I doing wrong?

Body:
Answer

I got confused a little bit, the correct typing was [String.t] and not List[String.t].

I will say however that:

lib/tip_calculator.ex: Undefined remote type Access:get/2 on line 0

Is not (to me) a very descriptive error message.
However, given the alternative (dialzyer) message is not much better:

lib/tip_calculator.ex:8:unknown_type
Unknown type: Access.get/2.

I will say however, the line number was an incredible help to find the issue.
With Gradient line 0 really threw me off.


问:
Copy/Paste visible row whith hidden/filtered rows
I try to add a function which can copy/paste a visible row, inserting a new one in the same table.
It works pretty well but not anymore with hidden rows.
Error message :

"This operation does not work with ranges where one line is filtered."

Would it be possible to solve it ?

```<code>function addRow() {
  var sh = ss.getActiveSheet(), lRow = sh.getLastRow();
  var lCol = sh.getLastColumn(), range = sh.getRange(lRow,1,1,lCol);
  sh.insertRowsAfter(lRow, 1);
  range.copyTo(sh.getRange(lRow+1, 1, 1, lCol), {contentsOnly:false});
}
</code>```

答:
I found a formula that works well:</p>
```<code>function copypasteRow() {
  var active_range = sheet.getActiveRange();
  var sh = ss.getActiveSheet(), lRow = sh.getLastRow();
  var lCol = sh.getLastColumn();
  sh.insertRowsAfter(lRow, 1);
  active_range.copyTo(sh.getRange(lRow+1, 1, 1, lCol), {contentsOnly:false});
}
</code>```

Body:
I try to add a function which can copy/paste a visible row, inserting a new one in the same table.
It works pretty well but not anymore with hidden rows.
Error message :

"This operation does not work with ranges where one line is filtered."

Would it be possible to solve it ?

function addRow() {
  var sh = ss.getActiveSheet(), lRow = sh.getLastRow();
  var lCol = sh.getLastColumn(), range = sh.getRange(lRow,1,1,lCol);
  sh.insertRowsAfter(lRow, 1);
  range.copyTo(sh.getRange(lRow+1, 1, 1, lCol), {contentsOnly:false});
}

Body:
I found a formula that works well:

function copypasteRow() {
  var active_range = sheet.getActiveRange();
  var sh = ss.getActiveSheet(), lRow = sh.getLastRow();
  var lCol = sh.getLastColumn();
  sh.insertRowsAfter(lRow, 1);
  active_range.copyTo(sh.getRange(lRow+1, 1, 1, lCol), {contentsOnly:false});
}


问:
helm chart template: if value does not exist, defaults to true
I am trying to declare that a block of code in a helm template should be present if a variable is true OR does not exist (ie, the default of the var is true). The following works:

```<code>    {{- if or .Values.livenessProbe (not (hasKey .Values "livenessProbe")) }}
    ...
    {{- end }}
</code>```

This seems rather complex, is there something simpler? I tried with default function in a few ways but they all result in ignoring the value (present or not, true or false, the block always gets rendered):

```<code>    {{- if (default true .Values.livenessProbe) }}
    ...
    {{- end }}
</code>```

答:
simpler solution I got was to do it like this</p>
```<code>list nil true | has .Values.value
</code>```

Body:
I am trying to declare that a block of code in a helm template should be present if a variable is true OR does not exist (ie, the default of the var is true). The following works:

    {{- if or .Values.livenessProbe (not (hasKey .Values "livenessProbe")) }}
    ...
    {{- end }}

This seems rather complex, is there something simpler? I tried with default function in a few ways but they all result in ignoring the value (present or not, true or false, the block always gets rendered):

    {{- if (default true .Values.livenessProbe) }}
    ...
    {{- end }}

Body:
simpler solution I got was to do it like this

list nil true | has .Values.value


问:
How can I access Data Class Properties created from JSON in Kotlin/Android
I am just getting started with Android/Kotlin and I am having issues with something very basic. I use retrofit to return JSON:

```<code>[
  {
    "id": "45837",
    "date_time": "2022-02-02 12:50:06",
    "pool_filter_status": "0",
    "pool_temperature": "97.59",
    "target_temperature": "97.3",
    "status_changed": "1"
  }
]
</code>```

In my viewmodel class, I have the following function that does retrieve the code from the server:

```<code>...

   private val _pooldata = MutableLiveData<List<PoolData>>()
   val pooldata: LiveData<List<PoolData>> = _pooldata

...

private fun getPoolData() {

        viewModelScope.launch {
            _status.value = PoolApiStatus.LOADING
            try {
                _pooldata.value = PoolDataApi.retrofitService.getPoolData()
                _status.value = PoolApiStatus.DONE
            } catch (e: Exception) {
                _status.value = PoolApiStatus.ERROR

            }

        }

    }
</code>```

For what its worth, its always just a single JSON object (though its in a single element array)

My really dumb question is how to access the properties of the data object / returned JSON.

If I log _pooldata.value.toString(), I just get:

```<code>[PoolData(id=45833, date_time=2022-02-02 12:30:02, pool_filter_status=1, pool_temperature=96.91, target_temperature=97.3, status_changed=0)]
</code>```

I am just trying to understand Kotlin "by doing" at this point, but I don't understand how to access those values (id, date_time, etc). its not _pooldata.id.value, _pooldata[0].id.value etc.

The data class is setup as:

```<code>data class PoolData(
    val id: String,
    val date_time: String,
    val pool_filter_status: String,
    val pool_temperature: String,
    val target_temperature: String,
    val status_changed: String
)

</code>```

Thanks.

答:
You are giving your data class as the data format in which retrofit will save your data and your data class refers only one object.
What you need is an array of data classes representing the PoolData.

For example:

```<code>data class JsonFromApi(val headers: String , listOfPoolData: List<PoolData>..etc)
</code>```

From here you will reference this class to access the PoolData like JsonFromApi.listOfPoolData which will be a list and you can then use index numbers to access any element.

For example:

```<code>JsonFromApi.listOfPoolData[index] // which will be of PoolData type with all defined properties
</code>```

Body:
I am just getting started with Android/Kotlin and I am having issues with something very basic. I use retrofit to return JSON:

[
  {
    "id": "45837",
    "date_time": "2022-02-02 12:50:06",
    "pool_filter_status": "0",
    "pool_temperature": "97.59",
    "target_temperature": "97.3",
    "status_changed": "1"
  }
]

In my viewmodel class, I have the following function that does retrieve the code from the server:

...

   private val _pooldata = MutableLiveData<List<PoolData>>()
   val pooldata: LiveData<List<PoolData>> = _pooldata

...

private fun getPoolData() {

        viewModelScope.launch {
            _status.value = PoolApiStatus.LOADING
            try {
                _pooldata.value = PoolDataApi.retrofitService.getPoolData()
                _status.value = PoolApiStatus.DONE
            } catch (e: Exception) {
                _status.value = PoolApiStatus.ERROR

            }

        }

    }

For what its worth, its always just a single JSON object (though its in a single element array)

My really dumb question is how to access the properties of the data object / returned JSON.

If I log _pooldata.value.toString(), I just get:

[PoolData(id=45833, date_time=2022-02-02 12:30:02, pool_filter_status=1, pool_temperature=96.91, target_temperature=97.3, status_changed=0)]

I am just trying to understand Kotlin "by doing" at this point, but I don't understand how to access those values (id, date_time, etc). its not _pooldata.id.value, _pooldata[0].id.value etc.

The data class is setup as:

data class PoolData(
    val id: String,
    val date_time: String,
    val pool_filter_status: String,
    val pool_temperature: String,
    val target_temperature: String,
    val status_changed: String
)

Thanks.

Body:
You are giving your data class as the data format in which retrofit will save your data and your data class refers only one object.
What you need is an array of data classes representing the PoolData.

For example:

data class JsonFromApi(val headers: String , listOfPoolData: List<PoolData>..etc)

From here you will reference this class to access the PoolData like JsonFromApi.listOfPoolData which will be a list and you can then use index numbers to access any element.

For example:

JsonFromApi.listOfPoolData[index] // which will be of PoolData type with all defined properties


问:
Intellij ignores java Compiler additional compiler options
I have a java 11 project which has some native functions.
I am trying to generate the corresponding Header-files by adding '-h myDir' to the additional compiler options in Intellij but it seems like IntelliJ does not even look for those.

I am going to: Files > Setting > Build,Execution,Deployment > Compiler > Java Compiler > Additional Command line parameter

Can someone tell me what i am doing wrong.

答:
Fixed my own problem.

Since Intellij ignored the compiler options for my jdk11 project via Files > Setting > Build,Execution,Deployment > Compiler > Java Compiler > Additional Command line parameter I simply set them in gradle.build and it now runs perfectly.

In your gradle.build include following:

```<code>compileJava {
    options.compilerArgs += ['-h', 'absolute dir where you want to put the header files']
}
</code>```

Body:
Fixed my own problem.

Since Intellij ignored the compiler options for my jdk11 project via Files > Setting > Build,Execution,Deployment > Compiler > Java Compiler > Additional Command line parameter I simply set them in gradle.build and it now runs perfectly.

In your gradle.build include following:

compileJava {
    options.compilerArgs += ['-h', 'absolute dir where you want to put the header files']
}